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