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