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