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