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