]> git.ipfire.org Git - thirdparty/systemd.git/blame - test/test-functions
travis: also run TEST-01-BASIC with QEMU to cover udevd and so on
[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
b4a450d8 40 local _asan_calls=$(objdump -dC $BUILD_DIR/systemd-journald | egrep "callq\s+[0-9a-f]+\s+<__asan" -c)
ec9181d2
EV
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
c1342d55 333DEFAULT_UBSAN_OPTIONS=print_stacktrace=1:print_summary=1
2614d83a 334DEFAULT_ENVIRONMENT="ASAN_OPTIONS=\$DEFAULT_ASAN_OPTIONS UBSAN_OPTIONS=\$DEFAULT_UBSAN_OPTIONS:halt_on_error=1"
1786fae3
EV
335
336mount -t proc proc /proc
337mount -t sysfs sysfs /sys
338mount -o remount,rw /
339
340PATH_TO_ASAN=\$(find / -name '*libasan*' | sed 1q)
341if [[ "\$PATH_TO_ASAN" ]]; then
342 # A lot of services (most notably dbus) won't start without preloading libasan
343 # See https://github.com/systemd/systemd/issues/5004
344 DEFAULT_ENVIRONMENT="\$DEFAULT_ENVIRONMENT LD_PRELOAD=\$PATH_TO_ASAN"
345fi
346echo DefaultEnvironment=\$DEFAULT_ENVIRONMENT >>/etc/systemd/system.conf
347
348# ASAN and syscall filters aren't compatible with each other.
349find / -name '*.service' -type f | xargs sed -i 's/^\\(MemoryDeny\\|SystemCall\\)/#\\1/'
350
88ed0f26
EV
351# The redirection of ASAN reports to a file prevents them from ending up in /dev/null.
352# But, apparently, sometimes it doesn't work: https://github.com/google/sanitizers/issues/886.
353JOURNALD_CONF_DIR=/etc/systemd/system/systemd-journald.service.d
354mkdir -p "\$JOURNALD_CONF_DIR"
355printf "[Service]\nEnvironment=ASAN_OPTIONS=\$DEFAULT_ASAN_OPTIONS:log_path=/systemd-journald.asan.log\n" >"\$JOURNALD_CONF_DIR/env.conf"
356
082bcdca
EV
357# 90s isn't enough for some services to finish when literally everything is run
358# under ASan+UBSan in containers, which, in turn, are run in VMs.
359mkdir -p /etc/systemd/system/systemd-hwdb-update.service.d
360printf "[Service]\nTimeoutSec=180s\n" >/etc/systemd/system/systemd-hwdb-update.service.d/timeout.conf
361
c1342d55 362export ASAN_OPTIONS=\$DEFAULT_ASAN_OPTIONS:log_path=/systemd.asan.log UBSAN_OPTIONS=\$DEFAULT_UBSAN_OPTIONS
1786fae3
EV
363exec $ROOTLIBDIR/systemd "\$@"
364EOF
365
366 chmod 0755 $_asan_wrapper
367}
368
45dbd7b6
EV
369create_strace_wrapper() {
370 local _strace_wrapper=$initdir/$ROOTLIBDIR/systemd-under-strace
371 ddebug "Create $_strace_wrapper"
372 cat >$_strace_wrapper <<EOF
373#!/bin/bash
374
375exec strace -D -o /strace.out $ROOTLIBDIR/systemd "\$@"
376EOF
377 chmod 0755 $_strace_wrapper
378}
379
9974ff63
EV
380install_fsck() {
381 dracut_install /sbin/fsck*
382 dracut_install -o /bin/fsck*
331fb4ca
EV
383
384 # fskc.reiserfs calls reiserfsck. so, install it
385 dracut_install -o reiserfsck
9974ff63
EV
386}
387
889a9042
RC
388install_dmevent() {
389 instmods dm_crypt =crypto
390 type -P dmeventd >/dev/null && dracut_install dmeventd
391 inst_libdir_file "libdevmapper-event.so*"
ac289ce3
EV
392 if [[ "$LOOKS_LIKE_DEBIAN" ]]; then
393 # dmsetup installs 55-dm and 60-persistent-storage-dm on Debian/Ubuntu
9c869ff6
DJL
394 # and since buster/bionic 95-dm-notify.rules
395 # see https://gitlab.com/debian-lvm/lvm2/blob/master/debian/patches/udev.patch
396 inst_rules 55-dm.rules 60-persistent-storage-dm.rules 95-dm-notify.rules
ac289ce3
EV
397 else
398 inst_rules 10-dm.rules 13-dm-disk.rules 95-dm-notify.rules
399 fi
889a9042
RC
400}
401
402install_systemd() {
403 # install compiled files
ca992ecf
EV
404 local _ninja_bin=$(type -P ninja || type -P ninja-build)
405 if [[ -z "$_ninja_bin" ]]; then
406 dfatal "ninja was not found"
407 exit 1
408 fi
409 (set -x; DESTDIR=$initdir "$_ninja_bin" -C $BUILD_DIR install)
889a9042 410 # remove unneeded documentation
23756070 411 rm -fr $initdir/usr/share/{man,doc}
889a9042
RC
412 # we strip binaries since debug symbols increase binaries size a lot
413 # and it could fill the available space
414 strip_binaries
61b480b6 415
85393d8f
TB
416 [[ "$LOOKS_LIKE_SUSE" ]] && setup_suse
417
61b480b6
ZJS
418 # enable debug logging in PID1
419 echo LogLevel=debug >> $initdir/etc/systemd/system.conf
889a9042
RC
420}
421
d7a4278d
FS
422get_ldpath() {
423 local _bin="$1"
424 objdump -p "$_bin" 2>/dev/null | awk "/R(UN)?PATH/ { print \"$initdir\" \$2 }" | paste -sd :
425}
426
889a9042
RC
427install_missing_libraries() {
428 # install possible missing libraries
e3d3dada 429 for i in $initdir{,/usr}/{sbin,bin}/* $initdir{,/usr}/lib/systemd/{,tests/{,manual/,unsafe/}}*; do
d7a4278d 430 LD_LIBRARY_PATH=$(get_ldpath $i) inst_libs $i
889a9042
RC
431 done
432}
433
434create_empty_image() {
28c7474e
EV
435 local _size=500
436 if [[ "$STRIP_BINARIES" = "no" ]]; then
437 _size=$((2*_size))
438 fi
739d81dd 439 rm -f "$TESTDIR/rootdisk.img"
889a9042 440 # Create the blank file to use as a root filesystem
28c7474e 441 dd if=/dev/null of="$TESTDIR/rootdisk.img" bs=1M seek="$_size"
889a9042 442 LOOPDEV=$(losetup --show -P -f $TESTDIR/rootdisk.img)
739d81dd 443 [ -b "$LOOPDEV" ] || return 1
889a9042 444 echo "LOOPDEV=$LOOPDEV" >> $STATEFILE
edbced8a 445 sfdisk "$LOOPDEV" <<EOF
28c7474e 446,$((_size-10))M
889a9042
RC
447,
448EOF
449
053edc5b
EV
450 udevadm settle
451
331fb4ca
EV
452 local _label="-L systemd"
453 # mkfs.reiserfs doesn't know -L. so, use --label instead
454 [[ "$FSTYPE" == "reiserfs" ]] && _label="--label systemd"
455 if ! mkfs -t "${FSTYPE}" ${_label} "${LOOPDEV}p1" -q; then
456 dfatal "Failed to mkfs -t ${FSTYPE}"
457 exit 1
458 fi
889a9042
RC
459}
460
461check_result_nspawn() {
0013fac2 462 local ret=1
998445fd 463 local journald_report=""
746fbd9c
EV
464 [[ -e $TESTDIR/$1/testok ]] && ret=0
465 [[ -f $TESTDIR/$1/failed ]] && cp -a $TESTDIR/$1/failed $TESTDIR
466 cp -a $TESTDIR/$1/var/log/journal $TESTDIR
889a9042
RC
467 [[ -f $TESTDIR/failed ]] && cat $TESTDIR/failed
468 ls -l $TESTDIR/journal/*/*.journal
469 test -s $TESTDIR/failed && ret=$(($ret+1))
b2ecd099 470 [ -n "$TIMED_OUT" ] && ret=$(($ret+1))
7e11a95e
EV
471 if [[ "$IS_BUILT_WITH_ASAN" = "yes" ]]; then
472 ls -l "$TESTDIR/$1"
473 if [[ -e "$TESTDIR/$1/systemd.asan.log.1" ]]; then
474 cat "$TESTDIR/$1/systemd.asan.log.1"
475 ret=$(($ret+1))
476 fi
998445fd
EV
477
478 journald_report=$(find "$TESTDIR/$1" -name "systemd-journald.asan.log*" -exec cat {} \;)
479 if [[ ! -z "$journald_report" ]]; then
480 printf "%s" "$journald_report"
481 ret=$(($ret+1))
482 fi
7e11a95e
EV
483 fi
484
889a9042
RC
485 return $ret
486}
487
054ee249
MP
488# can be overridden in specific test
489check_result_qemu() {
0013fac2 490 local ret=1
054ee249
MP
491 mkdir -p $TESTDIR/root
492 mount ${LOOPDEV}p1 $TESTDIR/root
493 [[ -e $TESTDIR/root/testok ]] && ret=0
494 [[ -f $TESTDIR/root/failed ]] && cp -a $TESTDIR/root/failed $TESTDIR
495 cp -a $TESTDIR/root/var/log/journal $TESTDIR
496 umount $TESTDIR/root
497 [[ -f $TESTDIR/failed ]] && cat $TESTDIR/failed
498 ls -l $TESTDIR/journal/*/*.journal
499 test -s $TESTDIR/failed && ret=$(($ret+1))
500 [ -n "$TIMED_OUT" ] && ret=$(($ret+1))
501 return $ret
502}
503
889a9042 504strip_binaries() {
5a613464
EV
505 if [[ "$STRIP_BINARIES" = "no" ]]; then
506 ddebug "Don't strip binaries"
507 return 0
508 fi
889a9042
RC
509 ddebug "Strip binaries"
510 find "$initdir" -executable -not -path '*/lib/modules/*.ko' -type f | xargs strip --strip-unneeded | ddebug
511}
512
513create_rc_local() {
514 mkdir -p $initdir/etc/rc.d
515 cat >$initdir/etc/rc.d/rc.local <<EOF
516#!/bin/bash
517exit 0
518EOF
519 chmod 0755 $initdir/etc/rc.d/rc.local
520}
521
522install_execs() {
c7eda013
EV
523 ddebug "install any Execs from the service files"
524 (
209f4b9e 525 export PKG_CONFIG_PATH=$BUILD_DIR/src/core/
c7eda013
EV
526 systemdsystemunitdir=$(pkg-config --variable=systemdsystemunitdir systemd)
527 systemduserunitdir=$(pkg-config --variable=systemduserunitdir systemd)
fe4bd4e5 528 sed -r -n 's|^Exec[a-zA-Z]*=[@+!-]*([^ ]+).*|\1|gp' $initdir/{$systemdsystemunitdir,$systemduserunitdir}/*.service \
e180bdb5 529 | sort -u | while read i; do
818567fc
MP
530 # some {rc,halt}.local scripts and programs are okay to not exist, the rest should
531 inst $i || [ "${i%.local}" != "$i" ] || [ "${i%systemd-update-done}" != "$i" ]
c7eda013
EV
532 done
533 )
889a9042
RC
534}
535
536generate_module_dependencies() {
537 if [[ -d $initdir/lib/modules/$KERNEL_VER ]] && \
538 ! depmod -a -b "$initdir" $KERNEL_VER; then
539 dfatal "\"depmod -a $KERNEL_VER\" failed."
540 exit 1
541 fi
542}
543
544install_depmod_files() {
545 inst /lib/modules/$KERNEL_VER/modules.order
546 inst /lib/modules/$KERNEL_VER/modules.builtin
547}
548
549install_plymouth() {
550 # install plymouth, if found... else remove plymouth service files
551 # if [ -x /usr/libexec/plymouth/plymouth-populate-initrd ]; then
552 # PLYMOUTH_POPULATE_SOURCE_FUNCTIONS="$TEST_BASE_DIR/test-functions" \
553 # /usr/libexec/plymouth/plymouth-populate-initrd -t $initdir
554 # dracut_install plymouth plymouthd
555 # else
556 rm -f $initdir/{usr/lib,etc}/systemd/system/plymouth* $initdir/{usr/lib,etc}/systemd/system/*/plymouth*
557 # fi
558}
559
560install_ld_so_conf() {
561 cp -a /etc/ld.so.conf* $initdir/etc
562 ldconfig -r "$initdir"
563}
564
565install_config_files() {
818567fc 566 inst /etc/sysconfig/init || true
889a9042
RC
567 inst /etc/passwd
568 inst /etc/shadow
bf3a947c 569 inst /etc/login.defs
889a9042
RC
570 inst /etc/group
571 inst /etc/shells
572 inst /etc/nsswitch.conf
818567fc
MP
573 inst /etc/pam.conf || true
574 inst /etc/securetty || true
889a9042
RC
575 inst /etc/os-release
576 inst /etc/localtime
577 # we want an empty environment
578 > $initdir/etc/environment
579 > $initdir/etc/machine-id
580 # set the hostname
581 echo systemd-testsuite > $initdir/etc/hostname
582 # fstab
85393d8f
TB
583 if [[ "$LOOKS_LIKE_SUSE" ]]; then
584 ROOTMOUNT="/dev/sda1 / ${FSTYPE} rw 0 1"
585 else
586 ROOTMOUNT="LABEL=systemd / ${FSTYPE} rw 0 1"
587 fi
588
889a9042 589 cat >$initdir/etc/fstab <<EOF
85393d8f 590$ROOTMOUNT
889a9042
RC
591EOF
592}
593
594install_basic_tools() {
595 [[ $BASICTOOLS ]] && dracut_install $BASICTOOLS
4be4833e 596 dracut_install -o sushell
7d023341
MP
597 # in Debian ldconfig is just a shell script wrapper around ldconfig.real
598 dracut_install -o ldconfig.real
889a9042
RC
599}
600
601install_debug_tools() {
602 [[ $DEBUGTOOLS ]] && dracut_install $DEBUGTOOLS
603}
604
605install_libnss() {
606 # install libnss_files for login
cffae62b 607 NSS_LIBS=$(LD_DEBUG=files getent passwd 2>&1 >/dev/null |sed -n '/calling init: .*libnss_/ {s!^.* /!/!; p}')
99877b7e 608 dracut_install $NSS_LIBS
889a9042
RC
609}
610
611install_dbus() {
3486cb6c 612 inst $ROOTLIBDIR/system/dbus.socket
a978c9f2
FS
613
614 # Fedora rawhide replaced dbus.service with dbus-daemon.service
615 if [ -f $ROOTLIBDIR/system/dbus-daemon.service ]; then
616 inst $ROOTLIBDIR/system/dbus-daemon.service
617 # Alias symlink
618 inst_symlink /etc/systemd/system/dbus.service
619 else
620 inst $ROOTLIBDIR/system/dbus.service
621 fi
889a9042
RC
622
623 find \
e63b61be 624 /etc/dbus-1 /usr/share/dbus-1 -xtype f \
889a9042
RC
625 | while read file; do
626 inst $file
627 done
628}
629
630install_pam() {
0fe15dc8 631 (
818567fc
MP
632 if [[ "$LOOKS_LIKE_DEBIAN" ]] && type -p dpkg-architecture &>/dev/null; then
633 find "/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/security" -xtype f
634 else
635 find /lib*/security -xtype f
636 fi
637 find /etc/pam.d /etc/security -xtype f
0fe15dc8 638 ) | while read file; do
889a9042
RC
639 inst $file
640 done
417491f1 641
d5172c79
EV
642 # pam_unix depends on unix_chkpwd.
643 # see http://www.linux-pam.org/Linux-PAM-html/sag-pam_unix.html
644 dracut_install -o unix_chkpwd
645
417491f1
EV
646 [[ "$LOOKS_LIKE_DEBIAN" ]] &&
647 cp /etc/pam.d/systemd-user $initdir/etc/pam.d/
e14b866b
ZJS
648
649 # set empty root password for easy debugging
650 sed -i 's/^root:x:/root::/' $initdir/etc/passwd
889a9042
RC
651}
652
653install_keymaps() {
83a7051e
YW
654 # The first three paths may be deprecated.
655 # It seems now the last two paths are used by many distributions.
889a9042
RC
656 for i in \
657 /usr/lib/kbd/keymaps/include/* \
658 /usr/lib/kbd/keymaps/i386/include/* \
83a7051e
YW
659 /usr/lib/kbd/keymaps/i386/qwerty/us.* \
660 /usr/lib/kbd/keymaps/legacy/include/* \
661 /usr/lib/kbd/keymaps/legacy/i386/qwerty/us.*; do
889a9042
RC
662 [[ -f $i ]] || continue
663 inst $i
664 done
ad931fee
YW
665
666 # When it takes any argument, then install more keymaps.
667 if [[ -n $1 ]]; then
668 for i in \
669 /usr/lib/kbd/keymaps/i386/*/* \
670 /usr/lib/kbd/keymaps/legacy/i386/*/*; do
671 [[ -f $i ]] || continue
672 inst $i
673 done
674 fi
889a9042
RC
675}
676
7d10ec1c
YW
677install_zoneinfo() {
678 for i in /usr/share/zoneinfo/{,*/,*/*/}*; do
679 [[ -f $i ]] || continue
680 inst $i
681 done
682}
683
889a9042
RC
684install_fonts() {
685 for i in \
25b47f96 686 /usr/lib/kbd/consolefonts/eurlatgr* \
889a9042
RC
687 /usr/lib/kbd/consolefonts/latarcyrheb-sun16*; do
688 [[ -f $i ]] || continue
689 inst $i
690 done
691}
692
693install_terminfo() {
694 for _terminfodir in /lib/terminfo /etc/terminfo /usr/share/terminfo; do
695 [ -f ${_terminfodir}/l/linux ] && break
696 done
697 dracut_install -o ${_terminfodir}/l/linux
698}
699
700setup_testsuite() {
53d90f95 701 cp $TEST_BASE_DIR/testsuite.target $initdir/etc/systemd/system/
5c404f1a 702 cp $TEST_BASE_DIR/end.service $initdir/etc/systemd/system/
889a9042
RC
703
704 mkdir -p $initdir/etc/systemd/system/testsuite.target.wants
705 ln -fs $TEST_BASE_DIR/testsuite.service $initdir/etc/systemd/system/testsuite.target.wants/testsuite.service
706 ln -fs $TEST_BASE_DIR/end.service $initdir/etc/systemd/system/testsuite.target.wants/end.service
707
708 # make the testsuite the default target
709 ln -fs testsuite.target $initdir/etc/systemd/system/default.target
710}
711
712setup_nspawn_root() {
713 rm -fr $TESTDIR/nspawn-root
714 ddebug "cp -ar $initdir $TESTDIR/nspawn-root"
715 cp -ar $initdir $TESTDIR/nspawn-root
716 # we don't mount in the nspawn root
717 rm -f $TESTDIR/nspawn-root/etc/fstab
746fbd9c
EV
718 if [[ "$RUN_IN_UNPRIVILEGED_CONTAINER" = "yes" ]]; then
719 cp -ar $TESTDIR/nspawn-root $TESTDIR/unprivileged-nspawn-root
720 fi
889a9042
RC
721}
722
0d6e798a 723setup_basic_dirs() {
889a9042
RC
724 mkdir -p $initdir/run
725 mkdir -p $initdir/etc/systemd/system
726 mkdir -p $initdir/var/log/journal
727
0d6e798a 728 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
729 if [ -L "/$d" ]; then
730 inst_symlink "/$d"
731 else
0d6e798a 732 inst_dir "/$d"
898720b7
HH
733 fi
734 done
735
736 ln -sfn /run "$initdir/var/run"
737 ln -sfn /run/lock "$initdir/var/lock"
738}
739
740inst_libs() {
741 local _bin=$1
742 local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
743 local _file _line
744
745 LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
746 [[ $_line = 'not a dynamic executable' ]] && break
747
748 if [[ $_line =~ $_so_regex ]]; then
749 _file=${BASH_REMATCH[1]}
750 [[ -e ${initdir}/$_file ]] && continue
751 inst_library "$_file"
752 continue
753 fi
754
755 if [[ $_line =~ not\ found ]]; then
756 dfatal "Missing a shared library required by $_bin."
757 dfatal "Run \"ldd $_bin\" to find out what it is."
758 dfatal "$_line"
759 dfatal "dracut cannot create an initrd."
760 exit 1
761 fi
762 done
763}
764
765import_testdir() {
898720b7
HH
766 [[ -e $STATEFILE ]] && . $STATEFILE
767 if [[ -z "$TESTDIR" ]] || [[ ! -d "$TESTDIR" ]]; then
768 TESTDIR=$(mktemp --tmpdir=/var/tmp -d -t systemd-test.XXXXXX)
769 echo "TESTDIR=\"$TESTDIR\"" > $STATEFILE
770 export TESTDIR
771 fi
772}
773
889a9042
RC
774import_initdir() {
775 initdir=$TESTDIR/root
776 export initdir
777}
778
898720b7
HH
779## @brief Converts numeric logging level to the first letter of level name.
780#
781# @param lvl Numeric logging level in range from 1 to 6.
782# @retval 1 if @a lvl is out of range.
783# @retval 0 if @a lvl is correct.
784# @result Echoes first letter of level name.
785_lvl2char() {
786 case "$1" in
787 1) echo F;;
788 2) echo E;;
789 3) echo W;;
790 4) echo I;;
791 5) echo D;;
792 6) echo T;;
793 *) return 1;;
794 esac
795}
796
797## @brief Internal helper function for _do_dlog()
798#
799# @param lvl Numeric logging level.
800# @param msg Message.
801# @retval 0 It's always returned, even if logging failed.
802#
803# @note This function is not supposed to be called manually. Please use
804# dtrace(), ddebug(), or others instead which wrap this one.
805#
806# This function calls _do_dlog() either with parameter msg, or if
807# none is given, it will read standard input and will use every line as
808# a message.
809#
810# This enables:
811# dwarn "This is a warning"
812# echo "This is a warning" | dwarn
20fc56c0 813LOG_LEVEL=${LOG_LEVEL:-4}
898720b7
HH
814
815dlog() {
816 [ -z "$LOG_LEVEL" ] && return 0
817 [ $1 -le $LOG_LEVEL ] || return 0
818 local lvl="$1"; shift
819 local lvlc=$(_lvl2char "$lvl") || return 0
820
821 if [ $# -ge 1 ]; then
822 echo "$lvlc: $*"
823 else
824 while read line; do
825 echo "$lvlc: " "$line"
826 done
827 fi
828}
829
830## @brief Logs message at TRACE level (6)
831#
832# @param msg Message.
833# @retval 0 It's always returned, even if logging failed.
834dtrace() {
835 set +x
836 dlog 6 "$@"
837 [ -n "$debug" ] && set -x || :
838}
839
840## @brief Logs message at DEBUG level (5)
841#
842# @param msg Message.
843# @retval 0 It's always returned, even if logging failed.
844ddebug() {
0d6e798a 845# set +x
898720b7 846 dlog 5 "$@"
0d6e798a 847# [ -n "$debug" ] && set -x || :
898720b7
HH
848}
849
850## @brief Logs message at INFO level (4)
851#
852# @param msg Message.
853# @retval 0 It's always returned, even if logging failed.
854dinfo() {
855 set +x
856 dlog 4 "$@"
857 [ -n "$debug" ] && set -x || :
858}
859
860## @brief Logs message at WARN level (3)
861#
862# @param msg Message.
863# @retval 0 It's always returned, even if logging failed.
864dwarn() {
865 set +x
866 dlog 3 "$@"
867 [ -n "$debug" ] && set -x || :
868}
869
870## @brief Logs message at ERROR level (2)
871#
872# @param msg Message.
873# @retval 0 It's always returned, even if logging failed.
874derror() {
0d6e798a 875# set +x
898720b7 876 dlog 2 "$@"
0d6e798a 877# [ -n "$debug" ] && set -x || :
898720b7
HH
878}
879
880## @brief Logs message at FATAL level (1)
881#
882# @param msg Message.
883# @retval 0 It's always returned, even if logging failed.
884dfatal() {
885 set +x
886 dlog 1 "$@"
887 [ -n "$debug" ] && set -x || :
888}
889
890
891# Generic substring function. If $2 is in $1, return 0.
892strstr() { [ "${1#*$2*}" != "$1" ]; }
893
894# normalize_path <path>
895# Prints the normalized path, where it removes any duplicated
896# and trailing slashes.
897# Example:
898# $ normalize_path ///test/test//
899# /test/test
900normalize_path() {
901 shopt -q -s extglob
902 set -- "${1//+(\/)//}"
903 shopt -q -u extglob
904 echo "${1%/}"
905}
906
907# convert_abs_rel <from> <to>
908# Prints the relative path, when creating a symlink to <to> from <from>.
909# Example:
910# $ convert_abs_rel /usr/bin/test /bin/test-2
911# ../../bin/test-2
912# $ ln -s $(convert_abs_rel /usr/bin/test /bin/test-2) /usr/bin/test
913convert_abs_rel() {
914 local __current __absolute __abssize __cursize __newpath
915 local -i __i __level
916
917 set -- "$(normalize_path "$1")" "$(normalize_path "$2")"
918
919 # corner case #1 - self looping link
920 [[ "$1" == "$2" ]] && { echo "${1##*/}"; return; }
921
922 # corner case #2 - own dir link
923 [[ "${1%/*}" == "$2" ]] && { echo "."; return; }
924
925 IFS="/" __current=($1)
926 IFS="/" __absolute=($2)
927
928 __abssize=${#__absolute[@]}
929 __cursize=${#__current[@]}
930
931 while [[ ${__absolute[__level]} == ${__current[__level]} ]]
932 do
933 (( __level++ ))
934 if (( __level > __abssize || __level > __cursize ))
935 then
936 break
937 fi
938 done
939
940 for ((__i = __level; __i < __cursize-1; __i++))
941 do
942 if ((__i > __level))
943 then
944 __newpath=$__newpath"/"
945 fi
946 __newpath=$__newpath".."
947 done
948
949 for ((__i = __level; __i < __abssize; __i++))
950 do
951 if [[ -n $__newpath ]]
952 then
953 __newpath=$__newpath"/"
954 fi
955 __newpath=$__newpath${__absolute[__i]}
956 done
957
958 echo "$__newpath"
959}
960
961
962# Install a directory, keeping symlinks as on the original system.
963# Example: if /lib points to /lib64 on the host, "inst_dir /lib/file"
964# will create ${initdir}/lib64, ${initdir}/lib64/file,
965# and a symlink ${initdir}/lib -> lib64.
966inst_dir() {
967 [[ -e ${initdir}/"$1" ]] && return 0 # already there
968
969 local _dir="$1" _part="${1%/*}" _file
970 while [[ "$_part" != "${_part%/*}" ]] && ! [[ -e "${initdir}/${_part}" ]]; do
971 _dir="$_part $_dir"
972 _part=${_part%/*}
973 done
974
975 # iterate over parent directories
976 for _file in $_dir; do
977 [[ -e "${initdir}/$_file" ]] && continue
978 if [[ -L $_file ]]; then
979 inst_symlink "$_file"
980 else
981 # create directory
982 mkdir -m 0755 -p "${initdir}/$_file" || return 1
983 [[ -e "$_file" ]] && chmod --reference="$_file" "${initdir}/$_file"
984 chmod u+w "${initdir}/$_file"
985 fi
986 done
987}
988
989# $1 = file to copy to ramdisk
990# $2 (optional) Name for the file on the ramdisk
991# Location of the image dir is assumed to be $initdir
992# We never overwrite the target if it exists.
993inst_simple() {
994 [[ -f "$1" ]] || return 1
995 strstr "$1" "/" || return 1
996
997 local _src=$1 target="${2:-$1}"
998 if ! [[ -d ${initdir}/$target ]]; then
999 [[ -e ${initdir}/$target ]] && return 0
1000 [[ -L ${initdir}/$target ]] && return 0
1001 [[ -d "${initdir}/${target%/*}" ]] || inst_dir "${target%/*}"
1002 fi
1003 # install checksum files also
1004 if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
1005 inst "${_src%/*}/.${_src##*/}.hmac" "${target%/*}/.${target##*/}.hmac"
1006 fi
1007 ddebug "Installing $_src"
1008 cp --sparse=always -pfL "$_src" "${initdir}/$target"
1009}
1010
1011# find symlinks linked to given library file
1012# $1 = library file
1013# Function searches for symlinks by stripping version numbers appended to
1014# library filename, checks if it points to the same target and finally
1015# prints the list of symlinks to stdout.
1016#
1017# Example:
1018# rev_lib_symlinks libfoo.so.8.1
1019# output: libfoo.so.8 libfoo.so
1020# (Only if libfoo.so.8 and libfoo.so exists on host system.)
1021rev_lib_symlinks() {
1022 [[ ! $1 ]] && return 0
1023
1024 local fn="$1" orig="$(readlink -f "$1")" links=''
1025
1026 [[ ${fn} =~ .*\.so\..* ]] || return 1
1027
1028 until [[ ${fn##*.} == so ]]; do
1029 fn="${fn%.*}"
1030 [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
1031 done
1032
1033 echo "${links}"
1034}
1035
1036# Same as above, but specialized to handle dynamic libraries.
1037# It handles making symlinks according to how the original library
1038# is referenced.
1039inst_library() {
1040 local _src="$1" _dest=${2:-$1} _lib _reallib _symlink
1041 strstr "$1" "/" || return 1
1042 [[ -e $initdir/$_dest ]] && return 0
1043 if [[ -L $_src ]]; then
1044 # install checksum files also
1045 if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
1046 inst "${_src%/*}/.${_src##*/}.hmac" "${_dest%/*}/.${_dest##*/}.hmac"
1047 fi
1048 _reallib=$(readlink -f "$_src")
1049 inst_simple "$_reallib" "$_reallib"
1050 inst_dir "${_dest%/*}"
1051 [[ -d "${_dest%/*}" ]] && _dest=$(readlink -f "${_dest%/*}")/${_dest##*/}
1052 ln -sfn $(convert_abs_rel "${_dest}" "${_reallib}") "${initdir}/${_dest}"
1053 else
1054 inst_simple "$_src" "$_dest"
1055 fi
1056
1057 # Create additional symlinks. See rev_symlinks description.
1058 for _symlink in $(rev_lib_symlinks $_src) $(rev_lib_symlinks $_reallib); do
818567fc 1059 [[ -e $initdir/$_symlink ]] || {
898720b7
HH
1060 ddebug "Creating extra symlink: $_symlink"
1061 inst_symlink $_symlink
1062 }
1063 done
1064}
1065
1066# find a binary. If we were not passed the full path directly,
1067# search in the usual places to find the binary.
1068find_binary() {
1069 if [[ -z ${1##/*} ]]; then
1070 if [[ -x $1 ]] || { strstr "$1" ".so" && ldd $1 &>/dev/null; }; then
1071 echo $1
1072 return 0
1073 fi
1074 fi
1075
1076 type -P $1
1077}
1078
1079# Same as above, but specialized to install binary executables.
1080# Install binary executable, and all shared library dependencies, if any.
1081inst_binary() {
1082 local _bin _target
1083 _bin=$(find_binary "$1") || return 1
1084 _target=${2:-$_bin}
1085 [[ -e $initdir/$_target ]] && return 0
1086 [[ -L $_bin ]] && inst_symlink $_bin $_target && return 0
1087 local _file _line
1088 local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
1089 # I love bash!
1090 LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
1091 [[ $_line = 'not a dynamic executable' ]] && break
1092
1093 if [[ $_line =~ $_so_regex ]]; then
1094 _file=${BASH_REMATCH[1]}
1095 [[ -e ${initdir}/$_file ]] && continue
1096 inst_library "$_file"
1097 continue
1098 fi
1099
1100 if [[ $_line =~ not\ found ]]; then
1101 dfatal "Missing a shared library required by $_bin."
1102 dfatal "Run \"ldd $_bin\" to find out what it is."
1103 dfatal "$_line"
1104 dfatal "dracut cannot create an initrd."
1105 exit 1
1106 fi
1107 done
1108 inst_simple "$_bin" "$_target"
1109}
1110
1111# same as above, except for shell scripts.
1112# If your shell script does not start with shebang, it is not a shell script.
1113inst_script() {
1114 local _bin
1115 _bin=$(find_binary "$1") || return 1
1116 shift
1117 local _line _shebang_regex
1118 read -r -n 80 _line <"$_bin"
1119 # If debug is set, clean unprintable chars to prevent messing up the term
1120 [[ $debug ]] && _line=$(echo -n "$_line" | tr -c -d '[:print:][:space:]')
1121 _shebang_regex='(#! *)(/[^ ]+).*'
1122 [[ $_line =~ $_shebang_regex ]] || return 1
1123 inst "${BASH_REMATCH[2]}" && inst_simple "$_bin" "$@"
1124}
1125
1126# same as above, but specialized for symlinks
1127inst_symlink() {
1128 local _src=$1 _target=${2:-$1} _realsrc
1129 strstr "$1" "/" || return 1
1130 [[ -L $1 ]] || return 1
1131 [[ -L $initdir/$_target ]] && return 0
1132 _realsrc=$(readlink -f "$_src")
1133 if ! [[ -e $initdir/$_realsrc ]]; then
1134 if [[ -d $_realsrc ]]; then
1135 inst_dir "$_realsrc"
1136 else
1137 inst "$_realsrc"
1138 fi
1139 fi
1140 [[ ! -e $initdir/${_target%/*} ]] && inst_dir "${_target%/*}"
1141 [[ -d ${_target%/*} ]] && _target=$(readlink -f ${_target%/*})/${_target##*/}
1142 ln -sfn $(convert_abs_rel "${_target}" "${_realsrc}") "$initdir/$_target"
1143}
1144
1145# attempt to install any programs specified in a udev rule
1146inst_rule_programs() {
1147 local _prog _bin
1148
1149 if grep -qE 'PROGRAM==?"[^ "]+' "$1"; then
1150 for _prog in $(grep -E 'PROGRAM==?"[^ "]+' "$1" | sed -r 's/.*PROGRAM==?"([^ "]+).*/\1/'); do
1151 if [ -x /lib/udev/$_prog ]; then
1152 _bin=/lib/udev/$_prog
1153 else
1154 _bin=$(find_binary "$_prog") || {
1155 dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
1156 continue;
1157 }
1158 fi
1159
1160 #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
1161 dracut_install "$_bin"
1162 done
1163 fi
1164}
1165
1166# udev rules always get installed in the same place, so
1167# create a function to install them to make life simpler.
1168inst_rules() {
1169 local _target=/etc/udev/rules.d _rule _found
1170
1171 inst_dir "/lib/udev/rules.d"
1172 inst_dir "$_target"
1173 for _rule in "$@"; do
1174 if [ "${rule#/}" = "$rule" ]; then
1175 for r in /lib/udev/rules.d /etc/udev/rules.d; do
1176 if [[ -f $r/$_rule ]]; then
1177 _found="$r/$_rule"
1178 inst_simple "$_found"
1179 inst_rule_programs "$_found"
1180 fi
1181 done
1182 fi
1183 for r in '' ./ $dracutbasedir/rules.d/; do
1184 if [[ -f ${r}$_rule ]]; then
1185 _found="${r}$_rule"
1186 inst_simple "$_found" "$_target/${_found##*/}"
1187 inst_rule_programs "$_found"
1188 fi
1189 done
1190 [[ $_found ]] || dinfo "Skipping udev rule: $_rule"
31ce89e7 1191 _found=
898720b7
HH
1192 done
1193}
1194
1195# general purpose installation function
1196# Same args as above.
1197inst() {
1198 local _x
1199
1200 case $# in
1201 1) ;;
1202 2) [[ ! $initdir && -d $2 ]] && export initdir=$2
1203 [[ $initdir = $2 ]] && set $1;;
1204 3) [[ -z $initdir ]] && export initdir=$2
1205 set $1 $3;;
1206 *) dfatal "inst only takes 1 or 2 or 3 arguments"
1207 exit 1;;
1208 esac
1209 for _x in inst_symlink inst_script inst_binary inst_simple; do
1210 $_x "$@" && return 0
1211 done
1212 return 1
1213}
1214
1215# install any of listed files
1216#
1217# If first argument is '-d' and second some destination path, first accessible
1218# source is installed into this path, otherwise it will installed in the same
1219# path as source. If none of listed files was installed, function return 1.
1220# On first successful installation it returns with 0 status.
1221#
1222# Example:
1223#
1224# inst_any -d /bin/foo /bin/bar /bin/baz
1225#
1226# Lets assume that /bin/baz exists, so it will be installed as /bin/foo in
1227# initramfs.
1228inst_any() {
1229 local to f
1230
1231 [[ $1 = '-d' ]] && to="$2" && shift 2
1232
1233 for f in "$@"; do
1234 if [[ -e $f ]]; then
1235 [[ $to ]] && inst "$f" "$to" && return 0
1236 inst "$f" && return 0
1237 fi
1238 done
1239
1240 return 1
1241}
1242
1243# dracut_install [-o ] <file> [<file> ... ]
1244# Install <file> to the initramfs image
1245# -o optionally install the <file> and don't fail, if it is not there
1246dracut_install() {
1247 local _optional=no
1248 if [[ $1 = '-o' ]]; then
1249 _optional=yes
1250 shift
1251 fi
1252 while (($# > 0)); do
1253 if ! inst "$1" ; then
1254 if [[ $_optional = yes ]]; then
1255 dinfo "Skipping program $1 as it cannot be found and is" \
1256 "flagged to be optional"
1257 else
1258 dfatal "Failed to install $1"
1259 exit 1
1260 fi
1261 fi
1262 shift
1263 done
1264}
1265
0d6e798a
HH
1266# Install a single kernel module along with any firmware it may require.
1267# $1 = full path to kernel module to install
1268install_kmod_with_fw() {
1269 # no need to go further if the module is already installed
1270
1271 [[ -e "${initdir}/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" ]] \
1272 && return 0
1273
1274 [[ -e "$initdir/.kernelmodseen/${1##*/}" ]] && return 0
1275
1276 if [[ $omit_drivers ]]; then
1277 local _kmod=${1##*/}
1278 _kmod=${_kmod%.ko}
1279 _kmod=${_kmod/-/_}
1280 if [[ "$_kmod" =~ $omit_drivers ]]; then
1281 dinfo "Omitting driver $_kmod"
1282 return 1
1283 fi
1284 if [[ "${1##*/lib/modules/$KERNEL_VER/}" =~ $omit_drivers ]]; then
1285 dinfo "Omitting driver $_kmod"
1286 return 1
1287 fi
1288 fi
1289
1290 [ -d "$initdir/.kernelmodseen" ] && \
1291 > "$initdir/.kernelmodseen/${1##*/}"
1292
1293 inst_simple "$1" "/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" \
1294 || return $?
1295
1296 local _modname=${1##*/} _fwdir _found _fw
1297 _modname=${_modname%.ko*}
1298 for _fw in $(modinfo -k $KERNEL_VER -F firmware $1 2>/dev/null); do
1299 _found=''
1300 for _fwdir in $fw_dir; do
1301 if [[ -d $_fwdir && -f $_fwdir/$_fw ]]; then
1302 inst_simple "$_fwdir/$_fw" "/lib/firmware/$_fw"
1303 _found=yes
1304 fi
1305 done
1306 if [[ $_found != yes ]]; then
1307 if ! grep -qe "\<${_modname//-/_}\>" /proc/modules; then
1308 dinfo "Possible missing firmware \"${_fw}\" for kernel module" \
1309 "\"${_modname}.ko\""
1310 else
1311 dwarn "Possible missing firmware \"${_fw}\" for kernel module" \
1312 "\"${_modname}.ko\""
1313 fi
1314 fi
1315 done
1316 return 0
1317}
1318
1319# Do something with all the dependencies of a kernel module.
1320# Note that kernel modules depend on themselves using the technique we use
1321# $1 = function to call for each dependency we find
1322# It will be passed the full path to the found kernel module
1323# $2 = module to get dependencies for
1324# rest of args = arguments to modprobe
1325# _fderr specifies FD passed from surrounding scope
1326for_each_kmod_dep() {
1327 local _func=$1 _kmod=$2 _cmd _modpath _options _found=0
1328 shift 2
1329 modprobe "$@" --ignore-install --show-depends $_kmod 2>&${_fderr} | (
1330 while read _cmd _modpath _options; do
1331 [[ $_cmd = insmod ]] || continue
1332 $_func ${_modpath} || exit $?
1333 _found=1
1334 done
1335 [[ $_found -eq 0 ]] && exit 1
1336 exit 0
1337 )
1338}
1339
1340# filter kernel modules to install certain modules that meet specific
1341# requirements.
1342# $1 = search only in subdirectory of /kernel/$1
1343# $2 = function to call with module name to filter.
1344# This function will be passed the full path to the module to test.
c5315881 1345# The behavior of this function can vary depending on whether $hostonly is set.
0d6e798a
HH
1346# If it is, we will only look at modules that are already in memory.
1347# If it is not, we will look at all kernel modules
1348# This function returns the full filenames of modules that match $1
1349filter_kernel_modules_by_path () (
1350 local _modname _filtercmd
1351 if ! [[ $hostonly ]]; then
1352 _filtercmd='find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra"'
1353 _filtercmd+=' "$KERNEL_MODS/weak-updates" -name "*.ko" -o -name "*.ko.gz"'
1354 _filtercmd+=' -o -name "*.ko.xz"'
1355 _filtercmd+=' 2>/dev/null'
1356 else
1357 _filtercmd='cut -d " " -f 1 </proc/modules|xargs modinfo -F filename '
1358 _filtercmd+='-k $KERNEL_VER 2>/dev/null'
1359 fi
1360 for _modname in $(eval $_filtercmd); do
1361 case $_modname in
1362 *.ko) "$2" "$_modname" && echo "$_modname";;
1363 *.ko.gz) gzip -dc "$_modname" > $initdir/$$.ko
1364 $2 $initdir/$$.ko && echo "$_modname"
1365 rm -f $initdir/$$.ko
1366 ;;
1367 *.ko.xz) xz -dc "$_modname" > $initdir/$$.ko
1368 $2 $initdir/$$.ko && echo "$_modname"
1369 rm -f $initdir/$$.ko
1370 ;;
1371 esac
1372 done
1373)
1374find_kernel_modules_by_path () (
1375 if ! [[ $hostonly ]]; then
1376 find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra" "$KERNEL_MODS/weak-updates" \
1377 -name "*.ko" -o -name "*.ko.gz" -o -name "*.ko.xz" 2>/dev/null
1378 else
1379 cut -d " " -f 1 </proc/modules \
1380 | xargs modinfo -F filename -k $KERNEL_VER 2>/dev/null
1381 fi
1382)
1383
1384filter_kernel_modules () {
1385 filter_kernel_modules_by_path drivers "$1"
1386}
1387
1388find_kernel_modules () {
1389 find_kernel_modules_by_path drivers
1390}
1391
1392# instmods [-c] <kernel module> [<kernel module> ... ]
1393# instmods [-c] <kernel subsystem>
1394# install kernel modules along with all their dependencies.
1395# <kernel subsystem> can be e.g. "=block" or "=drivers/usb/storage"
1396instmods() {
1397 [[ $no_kernel = yes ]] && return
1398 # called [sub]functions inherit _fderr
1399 local _fderr=9
1400 local _check=no
1401 if [[ $1 = '-c' ]]; then
1402 _check=yes
1403 shift
1404 fi
1405
1406 function inst1mod() {
1407 local _ret=0 _mod="$1"
1408 case $_mod in
1409 =*)
1410 if [ -f $KERNEL_MODS/modules.${_mod#=} ]; then
1411 ( [[ "$_mpargs" ]] && echo $_mpargs
1412 cat "${KERNEL_MODS}/modules.${_mod#=}" ) \
1413 | instmods
1414 else
1415 ( [[ "$_mpargs" ]] && echo $_mpargs
1416 find "$KERNEL_MODS" -path "*/${_mod#=}/*" -printf '%f\n' ) \
1417 | instmods
1418 fi
1419 ;;
1420 --*) _mpargs+=" $_mod" ;;
1421 i2o_scsi) return ;; # Do not load this diagnostic-only module
1422 *)
1423 _mod=${_mod##*/}
1424 # if we are already installed, skip this module and go on
1425 # to the next one.
1426 [[ -f "$initdir/.kernelmodseen/${_mod%.ko}.ko" ]] && return
1427
1428 if [[ $omit_drivers ]] && [[ "$1" =~ $omit_drivers ]]; then
1429 dinfo "Omitting driver ${_mod##$KERNEL_MODS}"
1430 return
1431 fi
1432 # If we are building a host-specific initramfs and this
1433 # module is not already loaded, move on to the next one.
1434 [[ $hostonly ]] && ! grep -qe "\<${_mod//-/_}\>" /proc/modules \
1435 && ! echo $add_drivers | grep -qe "\<${_mod}\>" \
1436 && return
1437
1438 # We use '-d' option in modprobe only if modules prefix path
1439 # differs from default '/'. This allows us to use Dracut with
1440 # old version of modprobe which doesn't have '-d' option.
1441 local _moddirname=${KERNEL_MODS%%/lib/modules/*}
1442 [[ -n ${_moddirname} ]] && _moddirname="-d ${_moddirname}/"
1443
1444 # ok, load the module, all its dependencies, and any firmware
1445 # it may require
1446 for_each_kmod_dep install_kmod_with_fw $_mod \
1447 --set-version $KERNEL_VER ${_moddirname} $_mpargs
1448 ((_ret+=$?))
1449 ;;
1450 esac
1451 return $_ret
1452 }
1453
1454 function instmods_1() {
1455 local _mod _mpargs
1456 if (($# == 0)); then # filenames from stdin
1457 while read _mod; do
1458 inst1mod "${_mod%.ko*}" || {
1459 if [ "$_check" = "yes" ]; then
1460 dfatal "Failed to install $_mod"
1461 return 1
1462 fi
1463 }
1464 done
1465 fi
1466 while (($# > 0)); do # filenames as arguments
1467 inst1mod ${1%.ko*} || {
1468 if [ "$_check" = "yes" ]; then
1469 dfatal "Failed to install $1"
1470 return 1
1471 fi
1472 }
1473 shift
1474 done
1475 return 0
1476 }
1477
1478 local _ret _filter_not_found='FATAL: Module .* not found.'
1479 set -o pipefail
1480 # Capture all stderr from modprobe to _fderr. We could use {var}>...
1481 # redirections, but that would make dracut require bash4 at least.
1482 eval "( instmods_1 \"\$@\" ) ${_fderr}>&1" \
1483 | while read line; do [[ "$line" =~ $_filter_not_found ]] && echo $line || echo $line >&2 ;done | derror
1484 _ret=$?
1485 set +o pipefail
1486 return $_ret
1487}
898720b7
HH
1488
1489# inst_libdir_file [-n <pattern>] <file> [<file>...]
1490# Install a <file> located on a lib directory to the initramfs image
1491# -n <pattern> install non-matching files
1492inst_libdir_file() {
1493 if [[ "$1" == "-n" ]]; then
1494 local _pattern=$1
1495 shift 2
1496 for _dir in $libdirs; do
1497 for _i in "$@"; do
1498 for _f in "$_dir"/$_i; do
1499 [[ "$_i" =~ $_pattern ]] || continue
1500 [[ -e "$_i" ]] && dracut_install "$_i"
1501 done
1502 done
1503 done
1504 else
1505 for _dir in $libdirs; do
1506 for _i in "$@"; do
1507 for _f in "$_dir"/$_i; do
1508 [[ -e "$_f" ]] && dracut_install "$_f"
1509 done
1510 done
1511 done
1512 fi
1513}
1514
85393d8f 1515setup_suse() {
caced732
FB
1516 ln -fs ../usr/bin/systemctl $initdir/bin/
1517 ln -fs ../usr/lib/systemd $initdir/lib/
85393d8f
TB
1518 inst_simple "/usr/lib/systemd/system/haveged.service"
1519}
1520
054ee249
MP
1521# can be overridden in specific test
1522test_cleanup() {
1523 umount $TESTDIR/root 2>/dev/null || true
818567fc 1524 [[ $LOOPDEV ]] && losetup -d $LOOPDEV || true
054ee249
MP
1525 return 0
1526}
1527
1528test_run() {
1529 if [ -z "$TEST_NO_QEMU" ]; then
1530 if run_qemu; then
1531 check_result_qemu || return 1
1532 else
1533 dwarn "can't run QEMU, skipping"
1534 fi
1535 fi
1536 if [ -z "$TEST_NO_NSPAWN" ]; then
746fbd9c
EV
1537 if run_nspawn "nspawn-root"; then
1538 check_result_nspawn "nspawn-root" || return 1
054ee249
MP
1539 else
1540 dwarn "can't run systemd-nspawn, skipping"
1541 fi
746fbd9c
EV
1542
1543 if [[ "$RUN_IN_UNPRIVILEGED_CONTAINER" = "yes" ]]; then
1544 if NSPAWN_ARGUMENTS="-U --private-network $NSPAWN_ARGUMENTS" run_nspawn "unprivileged-nspawn-root"; then
1545 check_result_nspawn "unprivileged-nspawn-root" || return 1
1546 else
1547 dwarn "can't run systemd-nspawn, skipping"
1548 fi
1549 fi
054ee249
MP
1550 fi
1551 return 0
1552}
1553
898720b7 1554do_test() {
33a5e20f
HH
1555 if [[ $UID != "0" ]]; then
1556 echo "TEST: $TEST_DESCRIPTION [SKIPPED]: not root" >&2
1557 exit 0
1558 fi
1559
898720b7
HH
1560# Detect lib paths
1561 [[ $libdir ]] || for libdir in /lib64 /lib; do
1562 [[ -d $libdir ]] && libdirs+=" $libdir" && break
1563 done
1564
1565 [[ $usrlibdir ]] || for usrlibdir in /usr/lib64 /usr/lib; do
1566 [[ -d $usrlibdir ]] && libdirs+=" $usrlibdir" && break
1567 done
1568
22077c9c
MP
1569 mkdir -p "$STATEDIR"
1570
898720b7 1571 import_testdir
889a9042 1572 import_initdir
898720b7
HH
1573
1574 while (($# > 0)); do
1575 case $1 in
1576 --run)
1577 echo "TEST RUN: $TEST_DESCRIPTION"
0013fac2
YW
1578 test_run
1579 ret=$?
1580 if (( $ret == 0 )); then
898720b7
HH
1581 echo "TEST RUN: $TEST_DESCRIPTION [OK]"
1582 else
1583 echo "TEST RUN: $TEST_DESCRIPTION [FAILED]"
1584 fi
1585 exit $ret;;
1586 --setup)
1587 echo "TEST SETUP: $TEST_DESCRIPTION"
1588 test_setup
818567fc 1589 ;;
898720b7
HH
1590 --clean)
1591 echo "TEST CLEANUP: $TEST_DESCRIPTION"
1592 test_cleanup
1593 rm -fr "$TESTDIR"
22077c9c 1594 rm -f "$STATEFILE"
818567fc 1595 ;;
898720b7 1596 --all)
818567fc 1597 ret=0
898720b7
HH
1598 echo -n "TEST: $TEST_DESCRIPTION ";
1599 (
1600 test_setup && test_run
1601 ret=$?
1602 test_cleanup
1603 rm -fr "$TESTDIR"
22077c9c 1604 rm -f "$STATEFILE"
898720b7 1605 exit $ret
818567fc 1606 ) </dev/null >"$TESTLOG" 2>&1 || ret=$?
898720b7 1607 if [ $ret -eq 0 ]; then
22077c9c 1608 rm "$TESTLOG"
898720b7
HH
1609 echo "[OK]"
1610 else
1611 echo "[FAILED]"
22077c9c 1612 echo "see $TESTLOG"
898720b7
HH
1613 fi
1614 exit $ret;;
1615 *) break ;;
1616 esac
1617 shift
1618 done
1619}