]> git.ipfire.org Git - thirdparty/systemd.git/blame - test/test-functions
sd-device: use qsort_safe() (#10099)
[thirdparty/systemd.git] / test / test-functions
CommitLineData
898720b7
HH
1#!/bin/bash
2# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
3# ex: ts=8 sw=4 sts=4 et filetype=sh
4PATH=/sbin:/bin:/usr/sbin:/usr/bin
5export PATH
6
c2f32f61
SLM
7LOOKS_LIKE_DEBIAN=$(source /etc/os-release && [[ "$ID" = "debian" || " $ID_LIKE " = *" debian "* ]] && echo yes || true)
8LOOKS_LIKE_ARCH=$(source /etc/os-release && [[ "$ID" = "arch" || " $ID_LIKE " = *" arch "* ]] && echo yes || true)
9LOOKS_LIKE_SUSE=$(source /etc/os-release && [[ " $ID_LIKE " = *" suse "* ]] && echo yes || true)
0d6e798a
HH
10KERNEL_VER=${KERNEL_VER-$(uname -r)}
11KERNEL_MODS="/lib/modules/$KERNEL_VER/"
91f9f8f1 12QEMU_TIMEOUT="${QEMU_TIMEOUT:-infinity}"
43bbb8f0 13NSPAWN_TIMEOUT="${NSPAWN_TIMEOUT:-infinity}"
b2ecd099 14TIMED_OUT= # will be 1 after run_* if *_TIMEOUT is set and test timed out
4b742c8a 15[[ "$LOOKS_LIKE_SUSE" ]] && FSTYPE="${FSTYPE:-btrfs}" || FSTYPE="${FSTYPE:-ext4}"
22f1f8f2 16UNIFIED_CGROUP_HIERARCHY="${UNIFIED_CGROUP_HIERARCHY:-default}"
7624e721 17EFI_MOUNT="$(bootctl -p 2>/dev/null || echo /boot)"
898720b7 18
3486cb6c
MP
19if ! ROOTLIBDIR=$(pkg-config --variable=systemdutildir systemd); then
20 echo "WARNING! Cannot determine rootlibdir from pkg-config, assuming /usr/lib/systemd" >&2
21 ROOTLIBDIR=/usr/lib/systemd
22fi
23
016fa3b9
EV
24PATH_TO_INIT=$ROOTLIBDIR/systemd
25
1786fae3 26BASICTOOLS="test sh bash setsid loadkeys setfont login sulogin gzip sleep echo mount umount cryptsetup date dmsetup modprobe sed cmp tee rm true false chmod chown ln xargs"
09f6f45a 27DEBUGTOOLS="df free ls stty cat ps ln ip route dmesg dhclient mkdir cp ping dhclient strace less grep id tty touch du sort hostname find"
889a9042 28
22077c9c
MP
29STATEDIR="${BUILD_DIR:-.}/test/$(basename $(dirname $(realpath $0)))"
30STATEFILE="$STATEDIR/.testdir"
31TESTLOG="$STATEDIR/test.log"
32
ec9181d2
EV
33is_built_with_asan() {
34 if ! type -P objdump >/dev/null; then
35 ddebug "Failed to find objdump. Assuming systemd hasn't been built with ASAN."
36 return 1
37 fi
38
39 # Borrowed from https://github.com/google/oss-fuzz/blob/cd9acd02f9d3f6e80011cc1e9549be526ce5f270/infra/base-images/base-runner/bad_build_check#L182
40 local _asan_calls=$(objdump -dC $BUILD_DIR/systemd | egrep "callq\s+[0-9a-f]+\s+<__asan" -c)
41 if (( $_asan_calls < 1000 )); then
42 return 1
43 else
44 return 0
45 fi
46}
47
48IS_BUILT_WITH_ASAN=$(is_built_with_asan && echo yes || echo no)
49
50if [[ "$IS_BUILT_WITH_ASAN" = "yes" ]]; then
51 STRIP_BINARIES=no
016fa3b9
EV
52 SKIP_INITRD=yes
53 PATH_TO_INIT=$ROOTLIBDIR/systemd-under-asan
ec9181d2
EV
54fi
55
c6a77179 56function find_qemu_bin() {
3e7aa2ed
LP
57 # SUSE and Red Hat call the binary qemu-kvm. Debian and Gentoo call it kvm.
58 # Either way, only use this version if we aren't running in KVM, because
59 # nested KVM is flaky still.
60 if [ `systemd-detect-virt -v` != kvm ] ; then
61 [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a kvm qemu-kvm 2>/dev/null | grep '^/' -m1)
62 fi
c6a77179
RC
63
64 [ "$ARCH" ] || ARCH=$(uname -m)
65 case $ARCH in
66 x86_64)
67 # QEMU's own build system calls it qemu-system-x86_64
68 [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu-system-x86_64 2>/dev/null | grep '^/' -m1)
69 ;;
70 i*86)
71 # new i386 version of QEMU
72 [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu-system-i386 2>/dev/null | grep '^/' -m1)
73
74 # i386 version of QEMU
75 [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu 2>/dev/null | grep '^/' -m1)
76 ;;
cf5f9bb8
ZJS
77 ppc64*)
78 [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu-system-$ARCH 2>/dev/null | grep '^/' -m1)
79 ;;
c6a77179
RC
80 esac
81
82 if [ ! -e "$QEMU_BIN" ]; then
83 echo "Could not find a suitable QEMU binary" >&2
84 return 1
85 fi
86}
87
b2ecd099
MP
88# Return 0 if QEMU did run (then you must check the result state/logs for actual
89# success), or 1 if QEMU is not available.
889a9042 90run_qemu() {
b6f0c419
HH
91 if [ -f /etc/machine-id ]; then
92 read MACHINE_ID < /etc/machine-id
906bbac4
ZJS
93 [ -z "$INITRD" ] && [ -e "$EFI_MOUNT/$MACHINE_ID/$KERNEL_VER/initrd" ] \
94 && INITRD="$EFI_MOUNT/$MACHINE_ID/$KERNEL_VER/initrd"
95 [ -z "$KERNEL_BIN" ] && [ -e "$EFI_MOUNT/$MACHINE_ID/$KERNEL_VER/linux" ] \
96 && KERNEL_BIN="$EFI_MOUNT/$MACHINE_ID/$KERNEL_VER/linux"
b6f0c419
HH
97 fi
98
e1a27318
EV
99 if [[ ! "$KERNEL_BIN" ]]; then
100 if [[ "$LOOKS_LIKE_ARCH" ]]; then
101 KERNEL_BIN=/boot/vmlinuz-linux
102 else
103 KERNEL_BIN=/boot/vmlinuz-$KERNEL_VER
104 fi
105 fi
106
61fea35e
EV
107 default_fedora_initrd=/boot/initramfs-${KERNEL_VER}.img
108 default_debian_initrd=/boot/initrd.img-${KERNEL_VER}
e1a27318 109 default_arch_initrd=/boot/initramfs-linux.img
85393d8f 110 default_suse_initrd=/boot/initrd-${KERNEL_VER}
e1a27318
EV
111 if [[ ! "$INITRD" ]]; then
112 if [[ -e "$default_fedora_initrd" ]]; then
113 INITRD="$default_fedora_initrd"
114 elif [[ "$LOOKS_LIKE_DEBIAN" && -e "$default_debian_initrd" ]]; then
115 INITRD="$default_debian_initrd"
116 elif [[ "$LOOKS_LIKE_ARCH" && -e "$default_arch_initrd" ]]; then
117 INITRD="$default_arch_initrd"
85393d8f
TB
118 elif [[ "$LOOKS_LIKE_SUSE" && -e "$default_suse_initrd" ]]; then
119 INITRD="$default_suse_initrd"
e1a27318
EV
120 fi
121 fi
122
c6a77179
RC
123 [ "$QEMU_SMP" ] || QEMU_SMP=1
124
125 find_qemu_bin || return 1
126
22f1f8f2
EV
127 local _cgroup_args
128 if [[ "$UNIFIED_CGROUP_HIERARCHY" = "yes" ]]; then
129 _cgroup_args="systemd.unified_cgroup_hierarchy=yes"
130 elif [[ "$UNIFIED_CGROUP_HIERARCHY" = "no" ]]; then
131 _cgroup_args="systemd.unified_cgroup_hierarchy=no systemd.legacy_systemd_cgroup_controller=yes"
132 elif [[ "$UNIFIED_CGROUP_HIERARCHY" = "hybrid" ]]; then
133 _cgroup_args="systemd.unified_cgroup_hierarchy=no systemd.legacy_systemd_cgroup_controller=no"
134 elif [[ "$UNIFIED_CGROUP_HIERARCHY" != "default" ]]; then
135 dfatal "Unknown UNIFIED_CGROUP_HIERARCHY. Got $UNIFIED_CGROUP_HIERARCHY, expected [yes|no|hybrid|default]"
136 exit 1
137 fi
138
85393d8f
TB
139if [[ "$LOOKS_LIKE_SUSE" ]]; then
140 PARAMS+="rd.hostonly=0"
141else
142 PARAMS+="ro"
143fi
144
145KERNEL_APPEND="$PARAMS \
146root=/dev/sda1 \
c6a77179
RC
147raid=noautodetect \
148loglevel=2 \
016fa3b9 149init=$PATH_TO_INIT \
c6a77179
RC
150console=ttyS0 \
151selinux=0 \
b2ad25d3 152printk.devkmsg=on \
22f1f8f2 153$_cgroup_args \
c6a77179
RC
154$KERNEL_APPEND \
155"
156
dbf43a42 157 QEMU_OPTIONS="-smp $QEMU_SMP \
c6a77179
RC
158-net none \
159-m 512M \
160-nographic \
161-kernel $KERNEL_BIN \
5b23cef0 162-drive format=raw,cache=unsafe,file=${TESTDIR}/rootdisk.img \
c6a77179
RC
163"
164
91f9f8f1 165 if [[ "$INITRD" && "$SKIP_INITRD" != "yes" ]]; then
c6a77179
RC
166 QEMU_OPTIONS="$QEMU_OPTIONS -initrd $INITRD"
167 fi
168
3e7aa2ed
LP
169 # Let's use KVM if it is available, but let's avoid using nested KVM as that is still flaky
170 if [ -c /dev/kvm -a `systemd-detect-virt -v` != kvm ]; then
dbf43a42
DM
171 QEMU_OPTIONS="$QEMU_OPTIONS -machine accel=kvm -enable-kvm -cpu host"
172 fi
173
91f9f8f1
EV
174 if [[ "$QEMU_TIMEOUT" != "infinity" ]]; then
175 QEMU_BIN="timeout --foreground $QEMU_TIMEOUT $QEMU_BIN"
176 fi
b2ecd099
MP
177 (set -x; $QEMU_BIN $QEMU_OPTIONS -append "$KERNEL_APPEND")
178 rc=$?
179 if [ "$rc" = 124 ] && [ "$QEMU_TIMEOUT" != "infinity" ]; then
180 derror "test timed out after $QEMU_TIMEOUT s"
181 TIMED_OUT=1
182 else
183 [ "$rc" != 0 ] && derror "QEMU failed with exit code $rc"
184 fi
185 return 0
889a9042
RC
186}
187
7cad32bb
MP
188# Return 0 if nspawn did run (then you must check the result state/logs for actual
189# success), or 1 if nspawn is not available.
889a9042 190run_nspawn() {
7cad32bb
MP
191 [[ -d /run/systemd/system ]] || return 1
192
746fbd9c 193 local _nspawn_cmd="$BUILD_DIR/systemd-nspawn $NSPAWN_ARGUMENTS --register=no --kill-signal=SIGKILL --directory=$TESTDIR/$1 $PATH_TO_INIT $KERNEL_APPEND"
43bbb8f0
EV
194 if [[ "$NSPAWN_TIMEOUT" != "infinity" ]]; then
195 _nspawn_cmd="timeout --foreground $NSPAWN_TIMEOUT $_nspawn_cmd"
196 fi
856ca72b 197
22f1f8f2
EV
198 if [[ "$UNIFIED_CGROUP_HIERARCHY" = "hybrid" ]]; then
199 dwarn "nspawn doesn't support UNIFIED_CGROUP_HIERARCHY=hybrid, skipping"
200 exit
201 elif [[ "$UNIFIED_CGROUP_HIERARCHY" = "yes" || "$UNIFIED_CGROUP_HIERARCHY" = "no" ]]; then
202 _nspawn_cmd="env UNIFIED_CGROUP_HIERARCHY=$UNIFIED_CGROUP_HIERARCHY $_nspawn_cmd"
203 elif [[ "$UNIFIED_CGROUP_HIERARCHY" = "default" ]]; then
204 _nspawn_cmd="env --unset=UNIFIED_CGROUP_HIERARCHY $_nspawn_cmd"
205 else
206 dfatal "Unknown UNIFIED_CGROUP_HIERARCHY. Got $UNIFIED_CGROUP_HIERARCHY, expected [yes|no|hybrid|default]"
207 exit 1
208 fi
856ca72b 209
b2ecd099
MP
210 (set -x; $_nspawn_cmd)
211 rc=$?
212 if [ "$rc" = 124 ] && [ "$NSPAWN_TIMEOUT" != "infinity" ]; then
213 derror "test timed out after $NSPAWN_TIMEOUT s"
214 TIMED_OUT=1
215 else
216 [ "$rc" != 0 ] && derror "nspawn failed with exit code $rc"
217 fi
218 return 0
889a9042
RC
219}
220
221setup_basic_environment() {
222 # create the basic filesystem layout
223 setup_basic_dirs
224
225 install_systemd
226 install_missing_libraries
227 install_config_files
228 create_rc_local
229 install_basic_tools
230 install_libnss
231 install_pam
232 install_dbus
233 install_fonts
234 install_keymaps
235 install_terminfo
236 install_execs
9974ff63 237 install_fsck
889a9042
RC
238 install_plymouth
239 install_debug_tools
240 install_ld_so_conf
e3ce42e7 241 setup_selinux
889a9042
RC
242 strip_binaries
243 install_depmod_files
244 generate_module_dependencies
ec9181d2
EV
245 if [[ "$IS_BUILT_WITH_ASAN" = "yes" ]]; then
246 create_asan_wrapper
247 fi
889a9042
RC
248}
249
e3ce42e7
EV
250setup_selinux() {
251 # don't forget KERNEL_APPEND='... selinux=1 ...'
252 if [[ "$SETUP_SELINUX" != "yes" ]]; then
253 ddebug "Don't setup SELinux"
254 return 0
255 fi
256 ddebug "Setup SELinux"
257 local _conf_dir=/etc/selinux
258 local _fixfiles_tools="bash uname cat sort uniq awk grep egrep head expr find rm secon setfiles"
259
260 rm -rf $initdir/$_conf_dir
261 if ! cp -ar $_conf_dir $initdir/$_conf_dir; then
262 dfatal "Failed to copy $_conf_dir"
263 exit 1
264 fi
265
266 cat <<EOF >$initdir/etc/systemd/system/autorelabel.service
267[Unit]
268Description=Relabel all filesystems
269DefaultDependencies=no
270Requires=local-fs.target
271Conflicts=shutdown.target
272After=local-fs.target
273Before=sysinit.target shutdown.target
274ConditionSecurity=selinux
275ConditionPathExists=|/.autorelabel
276
277[Service]
278ExecStart=/bin/sh -x -c 'echo 0 >/sys/fs/selinux/enforce && fixfiles -f -F relabel && rm /.autorelabel && systemctl --force reboot'
279Type=oneshot
280TimeoutSec=0
281RemainAfterExit=yes
282EOF
283
284 touch $initdir/.autorelabel
285 mkdir -p $initdir/etc/systemd/system/basic.target.wants
286 ln -fs autorelabel.service $initdir/etc/systemd/system/basic.target.wants/autorelabel.service
287
288 dracut_install $_fixfiles_tools
289 dracut_install fixfiles
290 dracut_install sestatus
291}
292
a2fbff31
EV
293install_valgrind() {
294 if ! type -p valgrind; then
295 dfatal "Failed to install valgrind"
296 exit 1
297 fi
298
299 local _valgrind_bins=$(strace -e execve valgrind /bin/true 2>&1 >/dev/null | perl -lne 'print $1 if /^execve\("([^"]+)"/')
300 dracut_install $_valgrind_bins
301
302 local _valgrind_libs=$(LD_DEBUG=files valgrind /bin/true 2>&1 >/dev/null | perl -lne 'print $1 if m{calling init: (/.*vgpreload_.*)}')
303 dracut_install $_valgrind_libs
304
305 local _valgrind_dbg_and_supp=$(
306 strace -e open valgrind /bin/true 2>&1 >/dev/null |
307 perl -lne 'if (my ($fname) = /^open\("([^"]+).*= (?!-)\d+/) { print $fname if $fname =~ /debug|\.supp$/ }'
308 )
309 dracut_install $_valgrind_dbg_and_supp
310}
311
cb2f9d3f
EV
312create_valgrind_wrapper() {
313 local _valgrind_wrapper=$initdir/$ROOTLIBDIR/systemd-under-valgrind
314 ddebug "Create $_valgrind_wrapper"
315 cat >$_valgrind_wrapper <<EOF
316#!/bin/bash
317
23cabb68 318mount -t proc proc /proc
cb2f9d3f
EV
319exec valgrind --leak-check=full --log-file=/valgrind.out $ROOTLIBDIR/systemd "\$@"
320EOF
321 chmod 0755 $_valgrind_wrapper
322}
323
1786fae3
EV
324create_asan_wrapper() {
325 local _asan_wrapper=$initdir/$ROOTLIBDIR/systemd-under-asan
326 ddebug "Create $_asan_wrapper"
327 cat >$_asan_wrapper <<EOF
328#!/bin/bash
329
330set -x
331
332DEFAULT_ASAN_OPTIONS=strict_string_checks=1:detect_stack_use_after_return=1:check_initialization_order=1:strict_init_order=1
333DEFAULT_ENVIRONMENT=ASAN_OPTIONS=\$DEFAULT_ASAN_OPTIONS
334
335mount -t proc proc /proc
336mount -t sysfs sysfs /sys
337mount -o remount,rw /
338
339PATH_TO_ASAN=\$(find / -name '*libasan*' | sed 1q)
340if [[ "\$PATH_TO_ASAN" ]]; then
341 # A lot of services (most notably dbus) won't start without preloading libasan
342 # See https://github.com/systemd/systemd/issues/5004
343 DEFAULT_ENVIRONMENT="\$DEFAULT_ENVIRONMENT LD_PRELOAD=\$PATH_TO_ASAN"
344fi
345echo DefaultEnvironment=\$DEFAULT_ENVIRONMENT >>/etc/systemd/system.conf
346
347# ASAN and syscall filters aren't compatible with each other.
348find / -name '*.service' -type f | xargs sed -i 's/^\\(MemoryDeny\\|SystemCall\\)/#\\1/'
349
88ed0f26
EV
350# The redirection of ASAN reports to a file prevents them from ending up in /dev/null.
351# But, apparently, sometimes it doesn't work: https://github.com/google/sanitizers/issues/886.
352JOURNALD_CONF_DIR=/etc/systemd/system/systemd-journald.service.d
353mkdir -p "\$JOURNALD_CONF_DIR"
354printf "[Service]\nEnvironment=ASAN_OPTIONS=\$DEFAULT_ASAN_OPTIONS:log_path=/systemd-journald.asan.log\n" >"\$JOURNALD_CONF_DIR/env.conf"
355
1786fae3
EV
356export ASAN_OPTIONS=\$DEFAULT_ASAN_OPTIONS:log_path=/systemd.asan.log
357exec $ROOTLIBDIR/systemd "\$@"
358EOF
359
360 chmod 0755 $_asan_wrapper
361}
362
45dbd7b6
EV
363create_strace_wrapper() {
364 local _strace_wrapper=$initdir/$ROOTLIBDIR/systemd-under-strace
365 ddebug "Create $_strace_wrapper"
366 cat >$_strace_wrapper <<EOF
367#!/bin/bash
368
369exec strace -D -o /strace.out $ROOTLIBDIR/systemd "\$@"
370EOF
371 chmod 0755 $_strace_wrapper
372}
373
9974ff63
EV
374install_fsck() {
375 dracut_install /sbin/fsck*
376 dracut_install -o /bin/fsck*
331fb4ca
EV
377
378 # fskc.reiserfs calls reiserfsck. so, install it
379 dracut_install -o reiserfsck
9974ff63
EV
380}
381
889a9042
RC
382install_dmevent() {
383 instmods dm_crypt =crypto
384 type -P dmeventd >/dev/null && dracut_install dmeventd
385 inst_libdir_file "libdevmapper-event.so*"
ac289ce3
EV
386 if [[ "$LOOKS_LIKE_DEBIAN" ]]; then
387 # dmsetup installs 55-dm and 60-persistent-storage-dm on Debian/Ubuntu
9c869ff6
DJL
388 # and since buster/bionic 95-dm-notify.rules
389 # see https://gitlab.com/debian-lvm/lvm2/blob/master/debian/patches/udev.patch
390 inst_rules 55-dm.rules 60-persistent-storage-dm.rules 95-dm-notify.rules
ac289ce3
EV
391 else
392 inst_rules 10-dm.rules 13-dm-disk.rules 95-dm-notify.rules
393 fi
889a9042
RC
394}
395
396install_systemd() {
397 # install compiled files
ca992ecf
EV
398 local _ninja_bin=$(type -P ninja || type -P ninja-build)
399 if [[ -z "$_ninja_bin" ]]; then
400 dfatal "ninja was not found"
401 exit 1
402 fi
403 (set -x; DESTDIR=$initdir "$_ninja_bin" -C $BUILD_DIR install)
889a9042 404 # remove unneeded documentation
23756070 405 rm -fr $initdir/usr/share/{man,doc}
889a9042
RC
406 # we strip binaries since debug symbols increase binaries size a lot
407 # and it could fill the available space
408 strip_binaries
61b480b6 409
85393d8f
TB
410 [[ "$LOOKS_LIKE_SUSE" ]] && setup_suse
411
61b480b6
ZJS
412 # enable debug logging in PID1
413 echo LogLevel=debug >> $initdir/etc/systemd/system.conf
889a9042
RC
414}
415
d7a4278d
FS
416get_ldpath() {
417 local _bin="$1"
418 objdump -p "$_bin" 2>/dev/null | awk "/R(UN)?PATH/ { print \"$initdir\" \$2 }" | paste -sd :
419}
420
889a9042
RC
421install_missing_libraries() {
422 # install possible missing libraries
11ea3431 423 for i in $initdir{,/usr}/{sbin,bin}/* $initdir{,/usr}/lib/systemd/*; do
d7a4278d 424 LD_LIBRARY_PATH=$(get_ldpath $i) inst_libs $i
889a9042
RC
425 done
426}
427
428create_empty_image() {
28c7474e
EV
429 local _size=500
430 if [[ "$STRIP_BINARIES" = "no" ]]; then
431 _size=$((2*_size))
432 fi
739d81dd 433 rm -f "$TESTDIR/rootdisk.img"
889a9042 434 # Create the blank file to use as a root filesystem
28c7474e 435 dd if=/dev/null of="$TESTDIR/rootdisk.img" bs=1M seek="$_size"
889a9042 436 LOOPDEV=$(losetup --show -P -f $TESTDIR/rootdisk.img)
739d81dd 437 [ -b "$LOOPDEV" ] || return 1
889a9042 438 echo "LOOPDEV=$LOOPDEV" >> $STATEFILE
edbced8a 439 sfdisk "$LOOPDEV" <<EOF
28c7474e 440,$((_size-10))M
889a9042
RC
441,
442EOF
443
053edc5b
EV
444 udevadm settle
445
331fb4ca
EV
446 local _label="-L systemd"
447 # mkfs.reiserfs doesn't know -L. so, use --label instead
448 [[ "$FSTYPE" == "reiserfs" ]] && _label="--label systemd"
449 if ! mkfs -t "${FSTYPE}" ${_label} "${LOOPDEV}p1" -q; then
450 dfatal "Failed to mkfs -t ${FSTYPE}"
451 exit 1
452 fi
889a9042
RC
453}
454
455check_result_nspawn() {
456 ret=1
746fbd9c
EV
457 [[ -e $TESTDIR/$1/testok ]] && ret=0
458 [[ -f $TESTDIR/$1/failed ]] && cp -a $TESTDIR/$1/failed $TESTDIR
459 cp -a $TESTDIR/$1/var/log/journal $TESTDIR
889a9042
RC
460 [[ -f $TESTDIR/failed ]] && cat $TESTDIR/failed
461 ls -l $TESTDIR/journal/*/*.journal
462 test -s $TESTDIR/failed && ret=$(($ret+1))
b2ecd099 463 [ -n "$TIMED_OUT" ] && ret=$(($ret+1))
889a9042
RC
464 return $ret
465}
466
054ee249
MP
467# can be overridden in specific test
468check_result_qemu() {
469 ret=1
470 mkdir -p $TESTDIR/root
471 mount ${LOOPDEV}p1 $TESTDIR/root
472 [[ -e $TESTDIR/root/testok ]] && ret=0
473 [[ -f $TESTDIR/root/failed ]] && cp -a $TESTDIR/root/failed $TESTDIR
474 cp -a $TESTDIR/root/var/log/journal $TESTDIR
475 umount $TESTDIR/root
476 [[ -f $TESTDIR/failed ]] && cat $TESTDIR/failed
477 ls -l $TESTDIR/journal/*/*.journal
478 test -s $TESTDIR/failed && ret=$(($ret+1))
479 [ -n "$TIMED_OUT" ] && ret=$(($ret+1))
480 return $ret
481}
482
889a9042 483strip_binaries() {
5a613464
EV
484 if [[ "$STRIP_BINARIES" = "no" ]]; then
485 ddebug "Don't strip binaries"
486 return 0
487 fi
889a9042
RC
488 ddebug "Strip binaries"
489 find "$initdir" -executable -not -path '*/lib/modules/*.ko' -type f | xargs strip --strip-unneeded | ddebug
490}
491
492create_rc_local() {
493 mkdir -p $initdir/etc/rc.d
494 cat >$initdir/etc/rc.d/rc.local <<EOF
495#!/bin/bash
496exit 0
497EOF
498 chmod 0755 $initdir/etc/rc.d/rc.local
499}
500
501install_execs() {
c7eda013
EV
502 ddebug "install any Execs from the service files"
503 (
209f4b9e 504 export PKG_CONFIG_PATH=$BUILD_DIR/src/core/
c7eda013
EV
505 systemdsystemunitdir=$(pkg-config --variable=systemdsystemunitdir systemd)
506 systemduserunitdir=$(pkg-config --variable=systemduserunitdir systemd)
507 egrep -ho '^Exec[^ ]*=[^ ]+' $initdir/{$systemdsystemunitdir,$systemduserunitdir}/*.service \
508 | while read i; do
5ed0dcf4 509 i=${i##Exec*=}; i=${i##[@+\!-]}; i=${i##\!}
818567fc
MP
510 # some {rc,halt}.local scripts and programs are okay to not exist, the rest should
511 inst $i || [ "${i%.local}" != "$i" ] || [ "${i%systemd-update-done}" != "$i" ]
c7eda013
EV
512 done
513 )
889a9042
RC
514}
515
516generate_module_dependencies() {
517 if [[ -d $initdir/lib/modules/$KERNEL_VER ]] && \
518 ! depmod -a -b "$initdir" $KERNEL_VER; then
519 dfatal "\"depmod -a $KERNEL_VER\" failed."
520 exit 1
521 fi
522}
523
524install_depmod_files() {
525 inst /lib/modules/$KERNEL_VER/modules.order
526 inst /lib/modules/$KERNEL_VER/modules.builtin
527}
528
529install_plymouth() {
530 # install plymouth, if found... else remove plymouth service files
531 # if [ -x /usr/libexec/plymouth/plymouth-populate-initrd ]; then
532 # PLYMOUTH_POPULATE_SOURCE_FUNCTIONS="$TEST_BASE_DIR/test-functions" \
533 # /usr/libexec/plymouth/plymouth-populate-initrd -t $initdir
534 # dracut_install plymouth plymouthd
535 # else
536 rm -f $initdir/{usr/lib,etc}/systemd/system/plymouth* $initdir/{usr/lib,etc}/systemd/system/*/plymouth*
537 # fi
538}
539
540install_ld_so_conf() {
541 cp -a /etc/ld.so.conf* $initdir/etc
542 ldconfig -r "$initdir"
543}
544
545install_config_files() {
818567fc 546 inst /etc/sysconfig/init || true
889a9042
RC
547 inst /etc/passwd
548 inst /etc/shadow
bf3a947c 549 inst /etc/login.defs
889a9042
RC
550 inst /etc/group
551 inst /etc/shells
552 inst /etc/nsswitch.conf
818567fc
MP
553 inst /etc/pam.conf || true
554 inst /etc/securetty || true
889a9042
RC
555 inst /etc/os-release
556 inst /etc/localtime
557 # we want an empty environment
558 > $initdir/etc/environment
559 > $initdir/etc/machine-id
560 # set the hostname
561 echo systemd-testsuite > $initdir/etc/hostname
562 # fstab
85393d8f
TB
563 if [[ "$LOOKS_LIKE_SUSE" ]]; then
564 ROOTMOUNT="/dev/sda1 / ${FSTYPE} rw 0 1"
565 else
566 ROOTMOUNT="LABEL=systemd / ${FSTYPE} rw 0 1"
567 fi
568
889a9042 569 cat >$initdir/etc/fstab <<EOF
85393d8f 570$ROOTMOUNT
889a9042
RC
571EOF
572}
573
574install_basic_tools() {
575 [[ $BASICTOOLS ]] && dracut_install $BASICTOOLS
4be4833e 576 dracut_install -o sushell
7d023341
MP
577 # in Debian ldconfig is just a shell script wrapper around ldconfig.real
578 dracut_install -o ldconfig.real
889a9042
RC
579}
580
581install_debug_tools() {
582 [[ $DEBUGTOOLS ]] && dracut_install $DEBUGTOOLS
583}
584
585install_libnss() {
586 # install libnss_files for login
cffae62b 587 NSS_LIBS=$(LD_DEBUG=files getent passwd 2>&1 >/dev/null |sed -n '/calling init: .*libnss_/ {s!^.* /!/!; p}')
99877b7e 588 dracut_install $NSS_LIBS
889a9042
RC
589}
590
591install_dbus() {
3486cb6c
MP
592 inst $ROOTLIBDIR/system/dbus.socket
593 inst $ROOTLIBDIR/system/dbus.service
889a9042
RC
594
595 find \
e63b61be 596 /etc/dbus-1 /usr/share/dbus-1 -xtype f \
889a9042
RC
597 | while read file; do
598 inst $file
599 done
600}
601
602install_pam() {
0fe15dc8 603 (
818567fc
MP
604 if [[ "$LOOKS_LIKE_DEBIAN" ]] && type -p dpkg-architecture &>/dev/null; then
605 find "/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/security" -xtype f
606 else
607 find /lib*/security -xtype f
608 fi
609 find /etc/pam.d /etc/security -xtype f
0fe15dc8 610 ) | while read file; do
889a9042
RC
611 inst $file
612 done
417491f1 613
d5172c79
EV
614 # pam_unix depends on unix_chkpwd.
615 # see http://www.linux-pam.org/Linux-PAM-html/sag-pam_unix.html
616 dracut_install -o unix_chkpwd
617
417491f1
EV
618 [[ "$LOOKS_LIKE_DEBIAN" ]] &&
619 cp /etc/pam.d/systemd-user $initdir/etc/pam.d/
e14b866b
ZJS
620
621 # set empty root password for easy debugging
622 sed -i 's/^root:x:/root::/' $initdir/etc/passwd
889a9042
RC
623}
624
625install_keymaps() {
626 for i in \
627 /usr/lib/kbd/keymaps/include/* \
628 /usr/lib/kbd/keymaps/i386/include/* \
629 /usr/lib/kbd/keymaps/i386/qwerty/us.*; do
630 [[ -f $i ]] || continue
631 inst $i
632 done
633}
634
635install_fonts() {
636 for i in \
25b47f96 637 /usr/lib/kbd/consolefonts/eurlatgr* \
889a9042
RC
638 /usr/lib/kbd/consolefonts/latarcyrheb-sun16*; do
639 [[ -f $i ]] || continue
640 inst $i
641 done
642}
643
644install_terminfo() {
645 for _terminfodir in /lib/terminfo /etc/terminfo /usr/share/terminfo; do
646 [ -f ${_terminfodir}/l/linux ] && break
647 done
648 dracut_install -o ${_terminfodir}/l/linux
649}
650
651setup_testsuite() {
53d90f95 652 cp $TEST_BASE_DIR/testsuite.target $initdir/etc/systemd/system/
5c404f1a 653 cp $TEST_BASE_DIR/end.service $initdir/etc/systemd/system/
889a9042
RC
654
655 mkdir -p $initdir/etc/systemd/system/testsuite.target.wants
656 ln -fs $TEST_BASE_DIR/testsuite.service $initdir/etc/systemd/system/testsuite.target.wants/testsuite.service
657 ln -fs $TEST_BASE_DIR/end.service $initdir/etc/systemd/system/testsuite.target.wants/end.service
658
659 # make the testsuite the default target
660 ln -fs testsuite.target $initdir/etc/systemd/system/default.target
661}
662
663setup_nspawn_root() {
664 rm -fr $TESTDIR/nspawn-root
665 ddebug "cp -ar $initdir $TESTDIR/nspawn-root"
666 cp -ar $initdir $TESTDIR/nspawn-root
667 # we don't mount in the nspawn root
668 rm -f $TESTDIR/nspawn-root/etc/fstab
746fbd9c
EV
669 if [[ "$RUN_IN_UNPRIVILEGED_CONTAINER" = "yes" ]]; then
670 cp -ar $TESTDIR/nspawn-root $TESTDIR/unprivileged-nspawn-root
671 fi
889a9042
RC
672}
673
0d6e798a 674setup_basic_dirs() {
889a9042
RC
675 mkdir -p $initdir/run
676 mkdir -p $initdir/etc/systemd/system
677 mkdir -p $initdir/var/log/journal
678
0d6e798a 679 for d in usr/bin usr/sbin bin etc lib "$libdir" sbin tmp usr var var/log dev proc sys sysroot root run run/lock run/initramfs; do
898720b7
HH
680 if [ -L "/$d" ]; then
681 inst_symlink "/$d"
682 else
0d6e798a 683 inst_dir "/$d"
898720b7
HH
684 fi
685 done
686
687 ln -sfn /run "$initdir/var/run"
688 ln -sfn /run/lock "$initdir/var/lock"
689}
690
691inst_libs() {
692 local _bin=$1
693 local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
694 local _file _line
695
696 LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
697 [[ $_line = 'not a dynamic executable' ]] && break
698
699 if [[ $_line =~ $_so_regex ]]; then
700 _file=${BASH_REMATCH[1]}
701 [[ -e ${initdir}/$_file ]] && continue
702 inst_library "$_file"
703 continue
704 fi
705
706 if [[ $_line =~ not\ found ]]; then
707 dfatal "Missing a shared library required by $_bin."
708 dfatal "Run \"ldd $_bin\" to find out what it is."
709 dfatal "$_line"
710 dfatal "dracut cannot create an initrd."
711 exit 1
712 fi
713 done
714}
715
716import_testdir() {
898720b7
HH
717 [[ -e $STATEFILE ]] && . $STATEFILE
718 if [[ -z "$TESTDIR" ]] || [[ ! -d "$TESTDIR" ]]; then
719 TESTDIR=$(mktemp --tmpdir=/var/tmp -d -t systemd-test.XXXXXX)
720 echo "TESTDIR=\"$TESTDIR\"" > $STATEFILE
721 export TESTDIR
722 fi
723}
724
889a9042
RC
725import_initdir() {
726 initdir=$TESTDIR/root
727 export initdir
728}
729
898720b7
HH
730## @brief Converts numeric logging level to the first letter of level name.
731#
732# @param lvl Numeric logging level in range from 1 to 6.
733# @retval 1 if @a lvl is out of range.
734# @retval 0 if @a lvl is correct.
735# @result Echoes first letter of level name.
736_lvl2char() {
737 case "$1" in
738 1) echo F;;
739 2) echo E;;
740 3) echo W;;
741 4) echo I;;
742 5) echo D;;
743 6) echo T;;
744 *) return 1;;
745 esac
746}
747
748## @brief Internal helper function for _do_dlog()
749#
750# @param lvl Numeric logging level.
751# @param msg Message.
752# @retval 0 It's always returned, even if logging failed.
753#
754# @note This function is not supposed to be called manually. Please use
755# dtrace(), ddebug(), or others instead which wrap this one.
756#
757# This function calls _do_dlog() either with parameter msg, or if
758# none is given, it will read standard input and will use every line as
759# a message.
760#
761# This enables:
762# dwarn "This is a warning"
763# echo "This is a warning" | dwarn
764LOG_LEVEL=4
765
766dlog() {
767 [ -z "$LOG_LEVEL" ] && return 0
768 [ $1 -le $LOG_LEVEL ] || return 0
769 local lvl="$1"; shift
770 local lvlc=$(_lvl2char "$lvl") || return 0
771
772 if [ $# -ge 1 ]; then
773 echo "$lvlc: $*"
774 else
775 while read line; do
776 echo "$lvlc: " "$line"
777 done
778 fi
779}
780
781## @brief Logs message at TRACE level (6)
782#
783# @param msg Message.
784# @retval 0 It's always returned, even if logging failed.
785dtrace() {
786 set +x
787 dlog 6 "$@"
788 [ -n "$debug" ] && set -x || :
789}
790
791## @brief Logs message at DEBUG level (5)
792#
793# @param msg Message.
794# @retval 0 It's always returned, even if logging failed.
795ddebug() {
0d6e798a 796# set +x
898720b7 797 dlog 5 "$@"
0d6e798a 798# [ -n "$debug" ] && set -x || :
898720b7
HH
799}
800
801## @brief Logs message at INFO level (4)
802#
803# @param msg Message.
804# @retval 0 It's always returned, even if logging failed.
805dinfo() {
806 set +x
807 dlog 4 "$@"
808 [ -n "$debug" ] && set -x || :
809}
810
811## @brief Logs message at WARN level (3)
812#
813# @param msg Message.
814# @retval 0 It's always returned, even if logging failed.
815dwarn() {
816 set +x
817 dlog 3 "$@"
818 [ -n "$debug" ] && set -x || :
819}
820
821## @brief Logs message at ERROR level (2)
822#
823# @param msg Message.
824# @retval 0 It's always returned, even if logging failed.
825derror() {
0d6e798a 826# set +x
898720b7 827 dlog 2 "$@"
0d6e798a 828# [ -n "$debug" ] && set -x || :
898720b7
HH
829}
830
831## @brief Logs message at FATAL level (1)
832#
833# @param msg Message.
834# @retval 0 It's always returned, even if logging failed.
835dfatal() {
836 set +x
837 dlog 1 "$@"
838 [ -n "$debug" ] && set -x || :
839}
840
841
842# Generic substring function. If $2 is in $1, return 0.
843strstr() { [ "${1#*$2*}" != "$1" ]; }
844
845# normalize_path <path>
846# Prints the normalized path, where it removes any duplicated
847# and trailing slashes.
848# Example:
849# $ normalize_path ///test/test//
850# /test/test
851normalize_path() {
852 shopt -q -s extglob
853 set -- "${1//+(\/)//}"
854 shopt -q -u extglob
855 echo "${1%/}"
856}
857
858# convert_abs_rel <from> <to>
859# Prints the relative path, when creating a symlink to <to> from <from>.
860# Example:
861# $ convert_abs_rel /usr/bin/test /bin/test-2
862# ../../bin/test-2
863# $ ln -s $(convert_abs_rel /usr/bin/test /bin/test-2) /usr/bin/test
864convert_abs_rel() {
865 local __current __absolute __abssize __cursize __newpath
866 local -i __i __level
867
868 set -- "$(normalize_path "$1")" "$(normalize_path "$2")"
869
870 # corner case #1 - self looping link
871 [[ "$1" == "$2" ]] && { echo "${1##*/}"; return; }
872
873 # corner case #2 - own dir link
874 [[ "${1%/*}" == "$2" ]] && { echo "."; return; }
875
876 IFS="/" __current=($1)
877 IFS="/" __absolute=($2)
878
879 __abssize=${#__absolute[@]}
880 __cursize=${#__current[@]}
881
882 while [[ ${__absolute[__level]} == ${__current[__level]} ]]
883 do
884 (( __level++ ))
885 if (( __level > __abssize || __level > __cursize ))
886 then
887 break
888 fi
889 done
890
891 for ((__i = __level; __i < __cursize-1; __i++))
892 do
893 if ((__i > __level))
894 then
895 __newpath=$__newpath"/"
896 fi
897 __newpath=$__newpath".."
898 done
899
900 for ((__i = __level; __i < __abssize; __i++))
901 do
902 if [[ -n $__newpath ]]
903 then
904 __newpath=$__newpath"/"
905 fi
906 __newpath=$__newpath${__absolute[__i]}
907 done
908
909 echo "$__newpath"
910}
911
912
913# Install a directory, keeping symlinks as on the original system.
914# Example: if /lib points to /lib64 on the host, "inst_dir /lib/file"
915# will create ${initdir}/lib64, ${initdir}/lib64/file,
916# and a symlink ${initdir}/lib -> lib64.
917inst_dir() {
918 [[ -e ${initdir}/"$1" ]] && return 0 # already there
919
920 local _dir="$1" _part="${1%/*}" _file
921 while [[ "$_part" != "${_part%/*}" ]] && ! [[ -e "${initdir}/${_part}" ]]; do
922 _dir="$_part $_dir"
923 _part=${_part%/*}
924 done
925
926 # iterate over parent directories
927 for _file in $_dir; do
928 [[ -e "${initdir}/$_file" ]] && continue
929 if [[ -L $_file ]]; then
930 inst_symlink "$_file"
931 else
932 # create directory
933 mkdir -m 0755 -p "${initdir}/$_file" || return 1
934 [[ -e "$_file" ]] && chmod --reference="$_file" "${initdir}/$_file"
935 chmod u+w "${initdir}/$_file"
936 fi
937 done
938}
939
940# $1 = file to copy to ramdisk
941# $2 (optional) Name for the file on the ramdisk
942# Location of the image dir is assumed to be $initdir
943# We never overwrite the target if it exists.
944inst_simple() {
945 [[ -f "$1" ]] || return 1
946 strstr "$1" "/" || return 1
947
948 local _src=$1 target="${2:-$1}"
949 if ! [[ -d ${initdir}/$target ]]; then
950 [[ -e ${initdir}/$target ]] && return 0
951 [[ -L ${initdir}/$target ]] && return 0
952 [[ -d "${initdir}/${target%/*}" ]] || inst_dir "${target%/*}"
953 fi
954 # install checksum files also
955 if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
956 inst "${_src%/*}/.${_src##*/}.hmac" "${target%/*}/.${target##*/}.hmac"
957 fi
958 ddebug "Installing $_src"
959 cp --sparse=always -pfL "$_src" "${initdir}/$target"
960}
961
962# find symlinks linked to given library file
963# $1 = library file
964# Function searches for symlinks by stripping version numbers appended to
965# library filename, checks if it points to the same target and finally
966# prints the list of symlinks to stdout.
967#
968# Example:
969# rev_lib_symlinks libfoo.so.8.1
970# output: libfoo.so.8 libfoo.so
971# (Only if libfoo.so.8 and libfoo.so exists on host system.)
972rev_lib_symlinks() {
973 [[ ! $1 ]] && return 0
974
975 local fn="$1" orig="$(readlink -f "$1")" links=''
976
977 [[ ${fn} =~ .*\.so\..* ]] || return 1
978
979 until [[ ${fn##*.} == so ]]; do
980 fn="${fn%.*}"
981 [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
982 done
983
984 echo "${links}"
985}
986
987# Same as above, but specialized to handle dynamic libraries.
988# It handles making symlinks according to how the original library
989# is referenced.
990inst_library() {
991 local _src="$1" _dest=${2:-$1} _lib _reallib _symlink
992 strstr "$1" "/" || return 1
993 [[ -e $initdir/$_dest ]] && return 0
994 if [[ -L $_src ]]; then
995 # install checksum files also
996 if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
997 inst "${_src%/*}/.${_src##*/}.hmac" "${_dest%/*}/.${_dest##*/}.hmac"
998 fi
999 _reallib=$(readlink -f "$_src")
1000 inst_simple "$_reallib" "$_reallib"
1001 inst_dir "${_dest%/*}"
1002 [[ -d "${_dest%/*}" ]] && _dest=$(readlink -f "${_dest%/*}")/${_dest##*/}
1003 ln -sfn $(convert_abs_rel "${_dest}" "${_reallib}") "${initdir}/${_dest}"
1004 else
1005 inst_simple "$_src" "$_dest"
1006 fi
1007
1008 # Create additional symlinks. See rev_symlinks description.
1009 for _symlink in $(rev_lib_symlinks $_src) $(rev_lib_symlinks $_reallib); do
818567fc 1010 [[ -e $initdir/$_symlink ]] || {
898720b7
HH
1011 ddebug "Creating extra symlink: $_symlink"
1012 inst_symlink $_symlink
1013 }
1014 done
1015}
1016
1017# find a binary. If we were not passed the full path directly,
1018# search in the usual places to find the binary.
1019find_binary() {
1020 if [[ -z ${1##/*} ]]; then
1021 if [[ -x $1 ]] || { strstr "$1" ".so" && ldd $1 &>/dev/null; }; then
1022 echo $1
1023 return 0
1024 fi
1025 fi
1026
1027 type -P $1
1028}
1029
1030# Same as above, but specialized to install binary executables.
1031# Install binary executable, and all shared library dependencies, if any.
1032inst_binary() {
1033 local _bin _target
1034 _bin=$(find_binary "$1") || return 1
1035 _target=${2:-$_bin}
1036 [[ -e $initdir/$_target ]] && return 0
1037 [[ -L $_bin ]] && inst_symlink $_bin $_target && return 0
1038 local _file _line
1039 local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
1040 # I love bash!
1041 LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
1042 [[ $_line = 'not a dynamic executable' ]] && break
1043
1044 if [[ $_line =~ $_so_regex ]]; then
1045 _file=${BASH_REMATCH[1]}
1046 [[ -e ${initdir}/$_file ]] && continue
1047 inst_library "$_file"
1048 continue
1049 fi
1050
1051 if [[ $_line =~ not\ found ]]; then
1052 dfatal "Missing a shared library required by $_bin."
1053 dfatal "Run \"ldd $_bin\" to find out what it is."
1054 dfatal "$_line"
1055 dfatal "dracut cannot create an initrd."
1056 exit 1
1057 fi
1058 done
1059 inst_simple "$_bin" "$_target"
1060}
1061
1062# same as above, except for shell scripts.
1063# If your shell script does not start with shebang, it is not a shell script.
1064inst_script() {
1065 local _bin
1066 _bin=$(find_binary "$1") || return 1
1067 shift
1068 local _line _shebang_regex
1069 read -r -n 80 _line <"$_bin"
1070 # If debug is set, clean unprintable chars to prevent messing up the term
1071 [[ $debug ]] && _line=$(echo -n "$_line" | tr -c -d '[:print:][:space:]')
1072 _shebang_regex='(#! *)(/[^ ]+).*'
1073 [[ $_line =~ $_shebang_regex ]] || return 1
1074 inst "${BASH_REMATCH[2]}" && inst_simple "$_bin" "$@"
1075}
1076
1077# same as above, but specialized for symlinks
1078inst_symlink() {
1079 local _src=$1 _target=${2:-$1} _realsrc
1080 strstr "$1" "/" || return 1
1081 [[ -L $1 ]] || return 1
1082 [[ -L $initdir/$_target ]] && return 0
1083 _realsrc=$(readlink -f "$_src")
1084 if ! [[ -e $initdir/$_realsrc ]]; then
1085 if [[ -d $_realsrc ]]; then
1086 inst_dir "$_realsrc"
1087 else
1088 inst "$_realsrc"
1089 fi
1090 fi
1091 [[ ! -e $initdir/${_target%/*} ]] && inst_dir "${_target%/*}"
1092 [[ -d ${_target%/*} ]] && _target=$(readlink -f ${_target%/*})/${_target##*/}
1093 ln -sfn $(convert_abs_rel "${_target}" "${_realsrc}") "$initdir/$_target"
1094}
1095
1096# attempt to install any programs specified in a udev rule
1097inst_rule_programs() {
1098 local _prog _bin
1099
1100 if grep -qE 'PROGRAM==?"[^ "]+' "$1"; then
1101 for _prog in $(grep -E 'PROGRAM==?"[^ "]+' "$1" | sed -r 's/.*PROGRAM==?"([^ "]+).*/\1/'); do
1102 if [ -x /lib/udev/$_prog ]; then
1103 _bin=/lib/udev/$_prog
1104 else
1105 _bin=$(find_binary "$_prog") || {
1106 dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
1107 continue;
1108 }
1109 fi
1110
1111 #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
1112 dracut_install "$_bin"
1113 done
1114 fi
1115}
1116
1117# udev rules always get installed in the same place, so
1118# create a function to install them to make life simpler.
1119inst_rules() {
1120 local _target=/etc/udev/rules.d _rule _found
1121
1122 inst_dir "/lib/udev/rules.d"
1123 inst_dir "$_target"
1124 for _rule in "$@"; do
1125 if [ "${rule#/}" = "$rule" ]; then
1126 for r in /lib/udev/rules.d /etc/udev/rules.d; do
1127 if [[ -f $r/$_rule ]]; then
1128 _found="$r/$_rule"
1129 inst_simple "$_found"
1130 inst_rule_programs "$_found"
1131 fi
1132 done
1133 fi
1134 for r in '' ./ $dracutbasedir/rules.d/; do
1135 if [[ -f ${r}$_rule ]]; then
1136 _found="${r}$_rule"
1137 inst_simple "$_found" "$_target/${_found##*/}"
1138 inst_rule_programs "$_found"
1139 fi
1140 done
1141 [[ $_found ]] || dinfo "Skipping udev rule: $_rule"
31ce89e7 1142 _found=
898720b7
HH
1143 done
1144}
1145
1146# general purpose installation function
1147# Same args as above.
1148inst() {
1149 local _x
1150
1151 case $# in
1152 1) ;;
1153 2) [[ ! $initdir && -d $2 ]] && export initdir=$2
1154 [[ $initdir = $2 ]] && set $1;;
1155 3) [[ -z $initdir ]] && export initdir=$2
1156 set $1 $3;;
1157 *) dfatal "inst only takes 1 or 2 or 3 arguments"
1158 exit 1;;
1159 esac
1160 for _x in inst_symlink inst_script inst_binary inst_simple; do
1161 $_x "$@" && return 0
1162 done
1163 return 1
1164}
1165
1166# install any of listed files
1167#
1168# If first argument is '-d' and second some destination path, first accessible
1169# source is installed into this path, otherwise it will installed in the same
1170# path as source. If none of listed files was installed, function return 1.
1171# On first successful installation it returns with 0 status.
1172#
1173# Example:
1174#
1175# inst_any -d /bin/foo /bin/bar /bin/baz
1176#
1177# Lets assume that /bin/baz exists, so it will be installed as /bin/foo in
1178# initramfs.
1179inst_any() {
1180 local to f
1181
1182 [[ $1 = '-d' ]] && to="$2" && shift 2
1183
1184 for f in "$@"; do
1185 if [[ -e $f ]]; then
1186 [[ $to ]] && inst "$f" "$to" && return 0
1187 inst "$f" && return 0
1188 fi
1189 done
1190
1191 return 1
1192}
1193
1194# dracut_install [-o ] <file> [<file> ... ]
1195# Install <file> to the initramfs image
1196# -o optionally install the <file> and don't fail, if it is not there
1197dracut_install() {
1198 local _optional=no
1199 if [[ $1 = '-o' ]]; then
1200 _optional=yes
1201 shift
1202 fi
1203 while (($# > 0)); do
1204 if ! inst "$1" ; then
1205 if [[ $_optional = yes ]]; then
1206 dinfo "Skipping program $1 as it cannot be found and is" \
1207 "flagged to be optional"
1208 else
1209 dfatal "Failed to install $1"
1210 exit 1
1211 fi
1212 fi
1213 shift
1214 done
1215}
1216
0d6e798a
HH
1217# Install a single kernel module along with any firmware it may require.
1218# $1 = full path to kernel module to install
1219install_kmod_with_fw() {
1220 # no need to go further if the module is already installed
1221
1222 [[ -e "${initdir}/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" ]] \
1223 && return 0
1224
1225 [[ -e "$initdir/.kernelmodseen/${1##*/}" ]] && return 0
1226
1227 if [[ $omit_drivers ]]; then
1228 local _kmod=${1##*/}
1229 _kmod=${_kmod%.ko}
1230 _kmod=${_kmod/-/_}
1231 if [[ "$_kmod" =~ $omit_drivers ]]; then
1232 dinfo "Omitting driver $_kmod"
1233 return 1
1234 fi
1235 if [[ "${1##*/lib/modules/$KERNEL_VER/}" =~ $omit_drivers ]]; then
1236 dinfo "Omitting driver $_kmod"
1237 return 1
1238 fi
1239 fi
1240
1241 [ -d "$initdir/.kernelmodseen" ] && \
1242 > "$initdir/.kernelmodseen/${1##*/}"
1243
1244 inst_simple "$1" "/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" \
1245 || return $?
1246
1247 local _modname=${1##*/} _fwdir _found _fw
1248 _modname=${_modname%.ko*}
1249 for _fw in $(modinfo -k $KERNEL_VER -F firmware $1 2>/dev/null); do
1250 _found=''
1251 for _fwdir in $fw_dir; do
1252 if [[ -d $_fwdir && -f $_fwdir/$_fw ]]; then
1253 inst_simple "$_fwdir/$_fw" "/lib/firmware/$_fw"
1254 _found=yes
1255 fi
1256 done
1257 if [[ $_found != yes ]]; then
1258 if ! grep -qe "\<${_modname//-/_}\>" /proc/modules; then
1259 dinfo "Possible missing firmware \"${_fw}\" for kernel module" \
1260 "\"${_modname}.ko\""
1261 else
1262 dwarn "Possible missing firmware \"${_fw}\" for kernel module" \
1263 "\"${_modname}.ko\""
1264 fi
1265 fi
1266 done
1267 return 0
1268}
1269
1270# Do something with all the dependencies of a kernel module.
1271# Note that kernel modules depend on themselves using the technique we use
1272# $1 = function to call for each dependency we find
1273# It will be passed the full path to the found kernel module
1274# $2 = module to get dependencies for
1275# rest of args = arguments to modprobe
1276# _fderr specifies FD passed from surrounding scope
1277for_each_kmod_dep() {
1278 local _func=$1 _kmod=$2 _cmd _modpath _options _found=0
1279 shift 2
1280 modprobe "$@" --ignore-install --show-depends $_kmod 2>&${_fderr} | (
1281 while read _cmd _modpath _options; do
1282 [[ $_cmd = insmod ]] || continue
1283 $_func ${_modpath} || exit $?
1284 _found=1
1285 done
1286 [[ $_found -eq 0 ]] && exit 1
1287 exit 0
1288 )
1289}
1290
1291# filter kernel modules to install certain modules that meet specific
1292# requirements.
1293# $1 = search only in subdirectory of /kernel/$1
1294# $2 = function to call with module name to filter.
1295# This function will be passed the full path to the module to test.
c5315881 1296# The behavior of this function can vary depending on whether $hostonly is set.
0d6e798a
HH
1297# If it is, we will only look at modules that are already in memory.
1298# If it is not, we will look at all kernel modules
1299# This function returns the full filenames of modules that match $1
1300filter_kernel_modules_by_path () (
1301 local _modname _filtercmd
1302 if ! [[ $hostonly ]]; then
1303 _filtercmd='find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra"'
1304 _filtercmd+=' "$KERNEL_MODS/weak-updates" -name "*.ko" -o -name "*.ko.gz"'
1305 _filtercmd+=' -o -name "*.ko.xz"'
1306 _filtercmd+=' 2>/dev/null'
1307 else
1308 _filtercmd='cut -d " " -f 1 </proc/modules|xargs modinfo -F filename '
1309 _filtercmd+='-k $KERNEL_VER 2>/dev/null'
1310 fi
1311 for _modname in $(eval $_filtercmd); do
1312 case $_modname in
1313 *.ko) "$2" "$_modname" && echo "$_modname";;
1314 *.ko.gz) gzip -dc "$_modname" > $initdir/$$.ko
1315 $2 $initdir/$$.ko && echo "$_modname"
1316 rm -f $initdir/$$.ko
1317 ;;
1318 *.ko.xz) xz -dc "$_modname" > $initdir/$$.ko
1319 $2 $initdir/$$.ko && echo "$_modname"
1320 rm -f $initdir/$$.ko
1321 ;;
1322 esac
1323 done
1324)
1325find_kernel_modules_by_path () (
1326 if ! [[ $hostonly ]]; then
1327 find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra" "$KERNEL_MODS/weak-updates" \
1328 -name "*.ko" -o -name "*.ko.gz" -o -name "*.ko.xz" 2>/dev/null
1329 else
1330 cut -d " " -f 1 </proc/modules \
1331 | xargs modinfo -F filename -k $KERNEL_VER 2>/dev/null
1332 fi
1333)
1334
1335filter_kernel_modules () {
1336 filter_kernel_modules_by_path drivers "$1"
1337}
1338
1339find_kernel_modules () {
1340 find_kernel_modules_by_path drivers
1341}
1342
1343# instmods [-c] <kernel module> [<kernel module> ... ]
1344# instmods [-c] <kernel subsystem>
1345# install kernel modules along with all their dependencies.
1346# <kernel subsystem> can be e.g. "=block" or "=drivers/usb/storage"
1347instmods() {
1348 [[ $no_kernel = yes ]] && return
1349 # called [sub]functions inherit _fderr
1350 local _fderr=9
1351 local _check=no
1352 if [[ $1 = '-c' ]]; then
1353 _check=yes
1354 shift
1355 fi
1356
1357 function inst1mod() {
1358 local _ret=0 _mod="$1"
1359 case $_mod in
1360 =*)
1361 if [ -f $KERNEL_MODS/modules.${_mod#=} ]; then
1362 ( [[ "$_mpargs" ]] && echo $_mpargs
1363 cat "${KERNEL_MODS}/modules.${_mod#=}" ) \
1364 | instmods
1365 else
1366 ( [[ "$_mpargs" ]] && echo $_mpargs
1367 find "$KERNEL_MODS" -path "*/${_mod#=}/*" -printf '%f\n' ) \
1368 | instmods
1369 fi
1370 ;;
1371 --*) _mpargs+=" $_mod" ;;
1372 i2o_scsi) return ;; # Do not load this diagnostic-only module
1373 *)
1374 _mod=${_mod##*/}
1375 # if we are already installed, skip this module and go on
1376 # to the next one.
1377 [[ -f "$initdir/.kernelmodseen/${_mod%.ko}.ko" ]] && return
1378
1379 if [[ $omit_drivers ]] && [[ "$1" =~ $omit_drivers ]]; then
1380 dinfo "Omitting driver ${_mod##$KERNEL_MODS}"
1381 return
1382 fi
1383 # If we are building a host-specific initramfs and this
1384 # module is not already loaded, move on to the next one.
1385 [[ $hostonly ]] && ! grep -qe "\<${_mod//-/_}\>" /proc/modules \
1386 && ! echo $add_drivers | grep -qe "\<${_mod}\>" \
1387 && return
1388
1389 # We use '-d' option in modprobe only if modules prefix path
1390 # differs from default '/'. This allows us to use Dracut with
1391 # old version of modprobe which doesn't have '-d' option.
1392 local _moddirname=${KERNEL_MODS%%/lib/modules/*}
1393 [[ -n ${_moddirname} ]] && _moddirname="-d ${_moddirname}/"
1394
1395 # ok, load the module, all its dependencies, and any firmware
1396 # it may require
1397 for_each_kmod_dep install_kmod_with_fw $_mod \
1398 --set-version $KERNEL_VER ${_moddirname} $_mpargs
1399 ((_ret+=$?))
1400 ;;
1401 esac
1402 return $_ret
1403 }
1404
1405 function instmods_1() {
1406 local _mod _mpargs
1407 if (($# == 0)); then # filenames from stdin
1408 while read _mod; do
1409 inst1mod "${_mod%.ko*}" || {
1410 if [ "$_check" = "yes" ]; then
1411 dfatal "Failed to install $_mod"
1412 return 1
1413 fi
1414 }
1415 done
1416 fi
1417 while (($# > 0)); do # filenames as arguments
1418 inst1mod ${1%.ko*} || {
1419 if [ "$_check" = "yes" ]; then
1420 dfatal "Failed to install $1"
1421 return 1
1422 fi
1423 }
1424 shift
1425 done
1426 return 0
1427 }
1428
1429 local _ret _filter_not_found='FATAL: Module .* not found.'
1430 set -o pipefail
1431 # Capture all stderr from modprobe to _fderr. We could use {var}>...
1432 # redirections, but that would make dracut require bash4 at least.
1433 eval "( instmods_1 \"\$@\" ) ${_fderr}>&1" \
1434 | while read line; do [[ "$line" =~ $_filter_not_found ]] && echo $line || echo $line >&2 ;done | derror
1435 _ret=$?
1436 set +o pipefail
1437 return $_ret
1438}
898720b7
HH
1439
1440# inst_libdir_file [-n <pattern>] <file> [<file>...]
1441# Install a <file> located on a lib directory to the initramfs image
1442# -n <pattern> install non-matching files
1443inst_libdir_file() {
1444 if [[ "$1" == "-n" ]]; then
1445 local _pattern=$1
1446 shift 2
1447 for _dir in $libdirs; do
1448 for _i in "$@"; do
1449 for _f in "$_dir"/$_i; do
1450 [[ "$_i" =~ $_pattern ]] || continue
1451 [[ -e "$_i" ]] && dracut_install "$_i"
1452 done
1453 done
1454 done
1455 else
1456 for _dir in $libdirs; do
1457 for _i in "$@"; do
1458 for _f in "$_dir"/$_i; do
1459 [[ -e "$_f" ]] && dracut_install "$_f"
1460 done
1461 done
1462 done
1463 fi
1464}
1465
85393d8f 1466setup_suse() {
caced732
FB
1467 ln -fs ../usr/bin/systemctl $initdir/bin/
1468 ln -fs ../usr/lib/systemd $initdir/lib/
85393d8f
TB
1469 inst_simple "/usr/lib/systemd/system/haveged.service"
1470}
1471
054ee249
MP
1472# can be overridden in specific test
1473test_cleanup() {
1474 umount $TESTDIR/root 2>/dev/null || true
818567fc 1475 [[ $LOOPDEV ]] && losetup -d $LOOPDEV || true
054ee249
MP
1476 return 0
1477}
1478
1479test_run() {
1480 if [ -z "$TEST_NO_QEMU" ]; then
1481 if run_qemu; then
1482 check_result_qemu || return 1
1483 else
1484 dwarn "can't run QEMU, skipping"
1485 fi
1486 fi
1487 if [ -z "$TEST_NO_NSPAWN" ]; then
746fbd9c
EV
1488 if run_nspawn "nspawn-root"; then
1489 check_result_nspawn "nspawn-root" || return 1
054ee249
MP
1490 else
1491 dwarn "can't run systemd-nspawn, skipping"
1492 fi
746fbd9c
EV
1493
1494 if [[ "$RUN_IN_UNPRIVILEGED_CONTAINER" = "yes" ]]; then
1495 if NSPAWN_ARGUMENTS="-U --private-network $NSPAWN_ARGUMENTS" run_nspawn "unprivileged-nspawn-root"; then
1496 check_result_nspawn "unprivileged-nspawn-root" || return 1
1497 else
1498 dwarn "can't run systemd-nspawn, skipping"
1499 fi
1500 fi
054ee249
MP
1501 fi
1502 return 0
1503}
1504
898720b7 1505do_test() {
33a5e20f
HH
1506 if [[ $UID != "0" ]]; then
1507 echo "TEST: $TEST_DESCRIPTION [SKIPPED]: not root" >&2
1508 exit 0
1509 fi
1510
898720b7
HH
1511# Detect lib paths
1512 [[ $libdir ]] || for libdir in /lib64 /lib; do
1513 [[ -d $libdir ]] && libdirs+=" $libdir" && break
1514 done
1515
1516 [[ $usrlibdir ]] || for usrlibdir in /usr/lib64 /usr/lib; do
1517 [[ -d $usrlibdir ]] && libdirs+=" $usrlibdir" && break
1518 done
1519
22077c9c
MP
1520 mkdir -p "$STATEDIR"
1521
898720b7 1522 import_testdir
889a9042 1523 import_initdir
898720b7
HH
1524
1525 while (($# > 0)); do
1526 case $1 in
1527 --run)
1528 echo "TEST RUN: $TEST_DESCRIPTION"
818567fc 1529 if test_run; then
898720b7
HH
1530 echo "TEST RUN: $TEST_DESCRIPTION [OK]"
1531 else
1532 echo "TEST RUN: $TEST_DESCRIPTION [FAILED]"
1533 fi
1534 exit $ret;;
1535 --setup)
1536 echo "TEST SETUP: $TEST_DESCRIPTION"
1537 test_setup
818567fc 1538 ;;
898720b7
HH
1539 --clean)
1540 echo "TEST CLEANUP: $TEST_DESCRIPTION"
1541 test_cleanup
1542 rm -fr "$TESTDIR"
22077c9c 1543 rm -f "$STATEFILE"
818567fc 1544 ;;
898720b7 1545 --all)
818567fc 1546 ret=0
898720b7
HH
1547 echo -n "TEST: $TEST_DESCRIPTION ";
1548 (
1549 test_setup && test_run
1550 ret=$?
1551 test_cleanup
1552 rm -fr "$TESTDIR"
22077c9c 1553 rm -f "$STATEFILE"
898720b7 1554 exit $ret
818567fc 1555 ) </dev/null >"$TESTLOG" 2>&1 || ret=$?
898720b7 1556 if [ $ret -eq 0 ]; then
22077c9c 1557 rm "$TESTLOG"
898720b7
HH
1558 echo "[OK]"
1559 else
1560 echo "[FAILED]"
22077c9c 1561 echo "see $TESTLOG"
898720b7
HH
1562 fi
1563 exit $ret;;
1564 *) break ;;
1565 esac
1566 shift
1567 done
1568}