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