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