chiark / gitweb /
a0f1bf4eb2a3ca27bedc591cd68c58b4e9aeb68a
[elogind.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 KERNEL_VER=${KERNEL_VER-$(uname -r)}
8 KERNEL_MODS="/lib/modules/$KERNEL_VER/"
9
10 if ! ROOTLIBDIR=$(pkg-config --variable=systemdutildir systemd); then
11     echo "WARNING! Cannot determine rootlibdir from pkg-config, assuming /usr/lib/systemd" >&2
12     ROOTLIBDIR=/usr/lib/systemd
13 fi
14
15 BASICTOOLS="sh bash setsid loadkeys setfont login sulogin gzip sleep echo mount umount cryptsetup date dmsetup modprobe"
16 DEBUGTOOLS="df free ls stty cat ps ln ip route dmesg dhclient mkdir cp ping dhclient strace less grep id tty touch du sort"
17
18 function find_qemu_bin() {
19     # SUSE and Red Hat call the binary qemu-kvm
20     # Debian and Gentoo call it kvm
21     [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a kvm qemu-kvm 2>/dev/null | grep '^/' -m1)
22
23     [ "$ARCH" ] || ARCH=$(uname -m)
24     case $ARCH in
25     x86_64)
26         # QEMU's own build system calls it qemu-system-x86_64
27         [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu-system-x86_64 2>/dev/null | grep '^/' -m1)
28         ;;
29     i*86)
30         # new i386 version of QEMU
31         [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu-system-i386 2>/dev/null | grep '^/' -m1)
32
33         # i386 version of QEMU
34         [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu 2>/dev/null | grep '^/' -m1)
35         ;;
36     esac
37
38     if [ ! -e "$QEMU_BIN" ]; then
39         echo "Could not find a suitable QEMU binary" >&2
40         return 1
41     fi
42 }
43
44 run_qemu() {
45     [ "$KERNEL_BIN" ] || KERNEL_BIN=/boot/vmlinuz-$KERNEL_VER
46     [ "$INITRD" ]     || INITRD=/boot/initramfs-${KERNEL_VER}.img
47     [ "$QEMU_SMP" ]   || QEMU_SMP=1
48
49     find_qemu_bin || return 1
50
51     KERNEL_APPEND="root=/dev/sda1 \
52 systemd.log_level=debug \
53 raid=noautodetect \
54 loglevel=2 \
55 init=$ROOTLIBDIR/systemd \
56 ro \
57 console=ttyS0 \
58 selinux=0 \
59 $KERNEL_APPEND \
60 "
61
62     QEMU_OPTIONS="-machine accel=kvm:tcg \
63 -smp $QEMU_SMP \
64 -net none \
65 -m 512M \
66 -nographic \
67 -kernel $KERNEL_BIN \
68 "
69
70     if [ "$INITRD" ]; then
71         QEMU_OPTIONS="$QEMU_OPTIONS -initrd $INITRD"
72     fi
73
74     ( set -x
75       $QEMU_BIN $QEMU_OPTIONS -append "$KERNEL_APPEND" $TESTDIR/rootdisk.img ) || return 1
76 }
77
78 run_nspawn() {
79     set -x
80     ../../systemd-nspawn --boot --directory=$TESTDIR/nspawn-root $ROOTLIBDIR/systemd $KERNEL_APPEND
81 }
82
83 setup_basic_environment() {
84     # create the basic filesystem layout
85     setup_basic_dirs
86
87     install_systemd
88     install_missing_libraries
89     install_config_files
90     create_rc_local
91     install_basic_tools
92     install_libnss
93     install_pam
94     install_dbus
95     install_fonts
96     install_keymaps
97     install_terminfo
98     install_execs
99     install_plymouth
100     install_debug_tools
101     install_ld_so_conf
102     strip_binaries
103     install_depmod_files
104     generate_module_dependencies
105     # softlink mtab
106     ln -fs /proc/self/mounts $initdir/etc/mtab
107 }
108
109 install_dmevent() {
110     instmods dm_crypt =crypto
111     type -P dmeventd >/dev/null && dracut_install dmeventd
112     inst_libdir_file "libdevmapper-event.so*"
113     inst_rules 10-dm.rules 13-dm-disk.rules 95-dm-notify.rules
114 }
115
116 install_systemd() {
117     # install compiled files
118     (cd $TEST_BASE_DIR/..; set -x; make DESTDIR=$initdir install)
119     # remove unneeded documentation
120     rm -fr $initdir/usr/share/{man,doc,gtk-doc}
121     # we strip binaries since debug symbols increase binaries size a lot
122     # and it could fill the available space
123     strip_binaries
124 }
125
126 install_missing_libraries() {
127     # install possible missing libraries
128     for i in $initdir/{sbin,bin}/* $initdir/lib/systemd/*; do
129         inst_libs $i
130     done
131 }
132
133 create_empty_image() {
134     rm -f "$TESTDIR/rootdisk.img"
135     # Create the blank file to use as a root filesystem
136     dd if=/dev/null of="$TESTDIR/rootdisk.img" bs=1M seek=300
137     LOOPDEV=$(losetup --show -P -f $TESTDIR/rootdisk.img)
138     [ -b "$LOOPDEV" ] || return 1
139     echo "LOOPDEV=$LOOPDEV" >> $STATEFILE
140     sfdisk -C 9600 -H 2 -S 32 -L "$LOOPDEV" <<EOF
141 ,4800
142 ,
143 EOF
144
145     mkfs.ext3 -L systemd "${LOOPDEV}p1"
146 }
147
148 check_result_nspawn() {
149     ret=1
150     [[ -e $TESTDIR/nspawn-root/testok ]] && ret=0
151     [[ -f $TESTDIR/nspawn-root/failed ]] && cp -a $TESTDIR/nspawn-root/failed $TESTDIR
152     cp -a $TESTDIR/nspawn-root/var/log/journal $TESTDIR
153     [[ -f $TESTDIR/failed ]] && cat $TESTDIR/failed
154     ls -l $TESTDIR/journal/*/*.journal
155     test -s $TESTDIR/failed && ret=$(($ret+1))
156     return $ret
157 }
158
159 strip_binaries() {
160     ddebug "Strip binaries"
161     find "$initdir" -executable -not -path '*/lib/modules/*.ko' -type f | xargs strip --strip-unneeded | ddebug
162 }
163
164 create_rc_local() {
165     mkdir -p $initdir/etc/rc.d
166     cat >$initdir/etc/rc.d/rc.local <<EOF
167 #!/bin/bash
168 exit 0
169 EOF
170     chmod 0755 $initdir/etc/rc.d/rc.local
171 }
172
173 install_execs() {
174     # install any Execs from the service files
175     egrep -ho '^Exec[^ ]*=[^ ]+' $initdir/lib/systemd/system/*.service \
176         | while read i; do
177         i=${i##Exec*=}; i=${i##-}
178         inst $i
179     done
180 }
181
182 generate_module_dependencies() {
183     if [[ -d $initdir/lib/modules/$KERNEL_VER ]] && \
184         ! depmod -a -b "$initdir" $KERNEL_VER; then
185             dfatal "\"depmod -a $KERNEL_VER\" failed."
186             exit 1
187     fi
188 }
189
190 install_depmod_files() {
191     inst /lib/modules/$KERNEL_VER/modules.order
192     inst /lib/modules/$KERNEL_VER/modules.builtin
193 }
194
195 install_plymouth() {
196     # install plymouth, if found... else remove plymouth service files
197     # if [ -x /usr/libexec/plymouth/plymouth-populate-initrd ]; then
198     #     PLYMOUTH_POPULATE_SOURCE_FUNCTIONS="$TEST_BASE_DIR/test-functions" \
199     #         /usr/libexec/plymouth/plymouth-populate-initrd -t $initdir
200     #         dracut_install plymouth plymouthd
201     # else
202         rm -f $initdir/{usr/lib,etc}/systemd/system/plymouth* $initdir/{usr/lib,etc}/systemd/system/*/plymouth*
203     # fi
204 }
205
206 install_ld_so_conf() {
207     cp -a /etc/ld.so.conf* $initdir/etc
208     ldconfig -r "$initdir"
209 }
210
211 install_config_files() {
212     inst /etc/sysconfig/init
213     inst /etc/passwd
214     inst /etc/shadow
215     inst /etc/group
216     inst /etc/shells
217     inst /etc/nsswitch.conf
218     inst /etc/pam.conf
219     inst /etc/securetty
220     inst /etc/os-release
221     inst /etc/localtime
222     # we want an empty environment
223     > $initdir/etc/environment
224     > $initdir/etc/machine-id
225     # set the hostname
226     echo systemd-testsuite > $initdir/etc/hostname
227     # fstab
228     cat >$initdir/etc/fstab <<EOF
229 LABEL=systemd           /       ext3    rw 0 1
230 EOF
231 }
232
233 install_basic_tools() {
234     [[ $BASICTOOLS ]] && dracut_install $BASICTOOLS
235     dracut_install -o sushell
236 }
237
238 install_debug_tools() {
239     [[ $DEBUGTOOLS ]] && dracut_install $DEBUGTOOLS
240 }
241
242 install_libnss() {
243     # install libnss_files for login
244     inst_libdir_file "libnss_files*"
245 }
246
247 install_dbus() {
248     inst $ROOTLIBDIR/system/dbus.socket
249     inst $ROOTLIBDIR/system/dbus.service
250
251     find \
252         /etc/dbus-1 -xtype f \
253         | while read file; do
254         inst $file
255     done
256 }
257
258 install_pam() {
259     find \
260         /etc/pam.d \
261         /etc/security \
262         /lib64/security \
263         /lib/security -xtype f \
264         | while read file; do
265         inst $file
266     done
267 }
268
269 install_keymaps() {
270     for i in \
271         /usr/lib/kbd/keymaps/include/* \
272         /usr/lib/kbd/keymaps/i386/include/* \
273         /usr/lib/kbd/keymaps/i386/qwerty/us.*; do
274             [[ -f $i ]] || continue
275             inst $i
276     done
277 }
278
279 install_fonts() {
280     for i in \
281         /usr/lib/kbd/consolefonts/eurlatgr* \
282         /usr/lib/kbd/consolefonts/latarcyrheb-sun16*; do
283             [[ -f $i ]] || continue
284             inst $i
285     done
286 }
287
288 install_terminfo() {
289     for _terminfodir in /lib/terminfo /etc/terminfo /usr/share/terminfo; do
290         [ -f ${_terminfodir}/l/linux ] && break
291     done
292     dracut_install -o ${_terminfodir}/l/linux
293 }
294
295 setup_testsuite() {
296     cp $TEST_BASE_DIR/{testsuite.target,end.service} $initdir/etc/systemd/system/
297
298     mkdir -p $initdir/etc/systemd/system/testsuite.target.wants
299     ln -fs $TEST_BASE_DIR/testsuite.service $initdir/etc/systemd/system/testsuite.target.wants/testsuite.service
300     ln -fs $TEST_BASE_DIR/end.service $initdir/etc/systemd/system/testsuite.target.wants/end.service
301
302     # make the testsuite the default target
303     ln -fs testsuite.target $initdir/etc/systemd/system/default.target
304 }
305
306 setup_nspawn_root() {
307     rm -fr $TESTDIR/nspawn-root
308     ddebug "cp -ar $initdir $TESTDIR/nspawn-root"
309     cp -ar $initdir $TESTDIR/nspawn-root
310     # we don't mount in the nspawn root
311     rm -f $TESTDIR/nspawn-root/etc/fstab
312 }
313
314 setup_basic_dirs() {
315     mkdir -p $initdir/run
316     mkdir -p $initdir/etc/systemd/system
317     mkdir -p $initdir/var/log/journal
318
319     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
320         if [ -L "/$d" ]; then
321             inst_symlink "/$d"
322         else
323             inst_dir "/$d"
324         fi
325     done
326
327     ln -sfn /run "$initdir/var/run"
328     ln -sfn /run/lock "$initdir/var/lock"
329 }
330
331 inst_libs() {
332     local _bin=$1
333     local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
334     local _file _line
335
336     LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
337         [[ $_line = 'not a dynamic executable' ]] && break
338
339         if [[ $_line =~ $_so_regex ]]; then
340             _file=${BASH_REMATCH[1]}
341             [[ -e ${initdir}/$_file ]] && continue
342             inst_library "$_file"
343             continue
344         fi
345
346         if [[ $_line =~ not\ found ]]; then
347             dfatal "Missing a shared library required by $_bin."
348             dfatal "Run \"ldd $_bin\" to find out what it is."
349             dfatal "$_line"
350             dfatal "dracut cannot create an initrd."
351             exit 1
352         fi
353     done
354 }
355
356 import_testdir() {
357     STATEFILE=".testdir"
358     [[ -e $STATEFILE ]] && . $STATEFILE
359     if [[ -z "$TESTDIR" ]] || [[ ! -d "$TESTDIR" ]]; then
360         TESTDIR=$(mktemp --tmpdir=/var/tmp -d -t systemd-test.XXXXXX)
361         echo "TESTDIR=\"$TESTDIR\"" > $STATEFILE
362         export TESTDIR
363     fi
364 }
365
366 import_initdir() {
367     initdir=$TESTDIR/root
368     export initdir
369 }
370
371 ## @brief Converts numeric logging level to the first letter of level name.
372 #
373 # @param lvl Numeric logging level in range from 1 to 6.
374 # @retval 1 if @a lvl is out of range.
375 # @retval 0 if @a lvl is correct.
376 # @result Echoes first letter of level name.
377 _lvl2char() {
378     case "$1" in
379         1) echo F;;
380         2) echo E;;
381         3) echo W;;
382         4) echo I;;
383         5) echo D;;
384         6) echo T;;
385         *) return 1;;
386     esac
387 }
388
389 ## @brief Internal helper function for _do_dlog()
390 #
391 # @param lvl Numeric logging level.
392 # @param msg Message.
393 # @retval 0 It's always returned, even if logging failed.
394 #
395 # @note This function is not supposed to be called manually. Please use
396 # dtrace(), ddebug(), or others instead which wrap this one.
397 #
398 # This function calls _do_dlog() either with parameter msg, or if
399 # none is given, it will read standard input and will use every line as
400 # a message.
401 #
402 # This enables:
403 # dwarn "This is a warning"
404 # echo "This is a warning" | dwarn
405 LOG_LEVEL=4
406
407 dlog() {
408     [ -z "$LOG_LEVEL" ] && return 0
409     [ $1 -le $LOG_LEVEL ] || return 0
410     local lvl="$1"; shift
411     local lvlc=$(_lvl2char "$lvl") || return 0
412
413     if [ $# -ge 1 ]; then
414         echo "$lvlc: $*"
415     else
416         while read line; do
417             echo "$lvlc: " "$line"
418         done
419     fi
420 }
421
422 ## @brief Logs message at TRACE level (6)
423 #
424 # @param msg Message.
425 # @retval 0 It's always returned, even if logging failed.
426 dtrace() {
427     set +x
428     dlog 6 "$@"
429     [ -n "$debug" ] && set -x || :
430 }
431
432 ## @brief Logs message at DEBUG level (5)
433 #
434 # @param msg Message.
435 # @retval 0 It's always returned, even if logging failed.
436 ddebug() {
437 #    set +x
438     dlog 5 "$@"
439 #    [ -n "$debug" ] && set -x || :
440 }
441
442 ## @brief Logs message at INFO level (4)
443 #
444 # @param msg Message.
445 # @retval 0 It's always returned, even if logging failed.
446 dinfo() {
447     set +x
448     dlog 4 "$@"
449     [ -n "$debug" ] && set -x || :
450 }
451
452 ## @brief Logs message at WARN level (3)
453 #
454 # @param msg Message.
455 # @retval 0 It's always returned, even if logging failed.
456 dwarn() {
457     set +x
458     dlog 3 "$@"
459     [ -n "$debug" ] && set -x || :
460 }
461
462 ## @brief Logs message at ERROR level (2)
463 #
464 # @param msg Message.
465 # @retval 0 It's always returned, even if logging failed.
466 derror() {
467 #    set +x
468     dlog 2 "$@"
469 #    [ -n "$debug" ] && set -x || :
470 }
471
472 ## @brief Logs message at FATAL level (1)
473 #
474 # @param msg Message.
475 # @retval 0 It's always returned, even if logging failed.
476 dfatal() {
477     set +x
478     dlog 1 "$@"
479     [ -n "$debug" ] && set -x || :
480 }
481
482
483 # Generic substring function.  If $2 is in $1, return 0.
484 strstr() { [ "${1#*$2*}" != "$1" ]; }
485
486 # normalize_path <path>
487 # Prints the normalized path, where it removes any duplicated
488 # and trailing slashes.
489 # Example:
490 # $ normalize_path ///test/test//
491 # /test/test
492 normalize_path() {
493     shopt -q -s extglob
494     set -- "${1//+(\/)//}"
495     shopt -q -u extglob
496     echo "${1%/}"
497 }
498
499 # convert_abs_rel <from> <to>
500 # Prints the relative path, when creating a symlink to <to> from <from>.
501 # Example:
502 # $ convert_abs_rel /usr/bin/test /bin/test-2
503 # ../../bin/test-2
504 # $ ln -s $(convert_abs_rel /usr/bin/test /bin/test-2) /usr/bin/test
505 convert_abs_rel() {
506     local __current __absolute __abssize __cursize __newpath
507     local -i __i __level
508
509     set -- "$(normalize_path "$1")" "$(normalize_path "$2")"
510
511     # corner case #1 - self looping link
512     [[ "$1" == "$2" ]] && { echo "${1##*/}"; return; }
513
514     # corner case #2 - own dir link
515     [[ "${1%/*}" == "$2" ]] && { echo "."; return; }
516
517     IFS="/" __current=($1)
518     IFS="/" __absolute=($2)
519
520     __abssize=${#__absolute[@]}
521     __cursize=${#__current[@]}
522
523     while [[ ${__absolute[__level]} == ${__current[__level]} ]]
524     do
525         (( __level++ ))
526         if (( __level > __abssize || __level > __cursize ))
527         then
528             break
529         fi
530     done
531
532     for ((__i = __level; __i < __cursize-1; __i++))
533     do
534         if ((__i > __level))
535         then
536             __newpath=$__newpath"/"
537         fi
538         __newpath=$__newpath".."
539     done
540
541     for ((__i = __level; __i < __abssize; __i++))
542     do
543         if [[ -n $__newpath ]]
544         then
545             __newpath=$__newpath"/"
546         fi
547         __newpath=$__newpath${__absolute[__i]}
548     done
549
550     echo "$__newpath"
551 }
552
553
554 # Install a directory, keeping symlinks as on the original system.
555 # Example: if /lib points to /lib64 on the host, "inst_dir /lib/file"
556 # will create ${initdir}/lib64, ${initdir}/lib64/file,
557 # and a symlink ${initdir}/lib -> lib64.
558 inst_dir() {
559     [[ -e ${initdir}/"$1" ]] && return 0  # already there
560
561     local _dir="$1" _part="${1%/*}" _file
562     while [[ "$_part" != "${_part%/*}" ]] && ! [[ -e "${initdir}/${_part}" ]]; do
563         _dir="$_part $_dir"
564         _part=${_part%/*}
565     done
566
567     # iterate over parent directories
568     for _file in $_dir; do
569         [[ -e "${initdir}/$_file" ]] && continue
570         if [[ -L $_file ]]; then
571             inst_symlink "$_file"
572         else
573             # create directory
574             mkdir -m 0755 -p "${initdir}/$_file" || return 1
575             [[ -e "$_file" ]] && chmod --reference="$_file" "${initdir}/$_file"
576             chmod u+w "${initdir}/$_file"
577         fi
578     done
579 }
580
581 # $1 = file to copy to ramdisk
582 # $2 (optional) Name for the file on the ramdisk
583 # Location of the image dir is assumed to be $initdir
584 # We never overwrite the target if it exists.
585 inst_simple() {
586     [[ -f "$1" ]] || return 1
587     strstr "$1" "/" || return 1
588
589     local _src=$1 target="${2:-$1}"
590     if ! [[ -d ${initdir}/$target ]]; then
591         [[ -e ${initdir}/$target ]] && return 0
592         [[ -L ${initdir}/$target ]] && return 0
593         [[ -d "${initdir}/${target%/*}" ]] || inst_dir "${target%/*}"
594     fi
595     # install checksum files also
596     if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
597         inst "${_src%/*}/.${_src##*/}.hmac" "${target%/*}/.${target##*/}.hmac"
598     fi
599     ddebug "Installing $_src"
600     cp --sparse=always -pfL "$_src" "${initdir}/$target"
601 }
602
603 # find symlinks linked to given library file
604 # $1 = library file
605 # Function searches for symlinks by stripping version numbers appended to
606 # library filename, checks if it points to the same target and finally
607 # prints the list of symlinks to stdout.
608 #
609 # Example:
610 # rev_lib_symlinks libfoo.so.8.1
611 # output: libfoo.so.8 libfoo.so
612 # (Only if libfoo.so.8 and libfoo.so exists on host system.)
613 rev_lib_symlinks() {
614     [[ ! $1 ]] && return 0
615
616     local fn="$1" orig="$(readlink -f "$1")" links=''
617
618     [[ ${fn} =~ .*\.so\..* ]] || return 1
619
620     until [[ ${fn##*.} == so ]]; do
621         fn="${fn%.*}"
622         [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
623     done
624
625     echo "${links}"
626 }
627
628 # Same as above, but specialized to handle dynamic libraries.
629 # It handles making symlinks according to how the original library
630 # is referenced.
631 inst_library() {
632     local _src="$1" _dest=${2:-$1} _lib _reallib _symlink
633     strstr "$1" "/" || return 1
634     [[ -e $initdir/$_dest ]] && return 0
635     if [[ -L $_src ]]; then
636         # install checksum files also
637         if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
638             inst "${_src%/*}/.${_src##*/}.hmac" "${_dest%/*}/.${_dest##*/}.hmac"
639         fi
640         _reallib=$(readlink -f "$_src")
641         inst_simple "$_reallib" "$_reallib"
642         inst_dir "${_dest%/*}"
643         [[ -d "${_dest%/*}" ]] && _dest=$(readlink -f "${_dest%/*}")/${_dest##*/}
644         ln -sfn $(convert_abs_rel "${_dest}" "${_reallib}") "${initdir}/${_dest}"
645     else
646         inst_simple "$_src" "$_dest"
647     fi
648
649     # Create additional symlinks.  See rev_symlinks description.
650     for _symlink in $(rev_lib_symlinks $_src) $(rev_lib_symlinks $_reallib); do
651         [[ ! -e $initdir/$_symlink ]] && {
652             ddebug "Creating extra symlink: $_symlink"
653             inst_symlink $_symlink
654         }
655     done
656 }
657
658 # find a binary.  If we were not passed the full path directly,
659 # search in the usual places to find the binary.
660 find_binary() {
661     if [[ -z ${1##/*} ]]; then
662         if [[ -x $1 ]] || { strstr "$1" ".so" && ldd $1 &>/dev/null; };  then
663             echo $1
664             return 0
665         fi
666     fi
667
668     type -P $1
669 }
670
671 # Same as above, but specialized to install binary executables.
672 # Install binary executable, and all shared library dependencies, if any.
673 inst_binary() {
674     local _bin _target
675     _bin=$(find_binary "$1") || return 1
676     _target=${2:-$_bin}
677     [[ -e $initdir/$_target ]] && return 0
678     [[ -L $_bin ]] && inst_symlink $_bin $_target && return 0
679     local _file _line
680     local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
681     # I love bash!
682     LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
683         [[ $_line = 'not a dynamic executable' ]] && break
684
685         if [[ $_line =~ $_so_regex ]]; then
686             _file=${BASH_REMATCH[1]}
687             [[ -e ${initdir}/$_file ]] && continue
688             inst_library "$_file"
689             continue
690         fi
691
692         if [[ $_line =~ not\ found ]]; then
693             dfatal "Missing a shared library required by $_bin."
694             dfatal "Run \"ldd $_bin\" to find out what it is."
695             dfatal "$_line"
696             dfatal "dracut cannot create an initrd."
697             exit 1
698         fi
699     done
700     inst_simple "$_bin" "$_target"
701 }
702
703 # same as above, except for shell scripts.
704 # If your shell script does not start with shebang, it is not a shell script.
705 inst_script() {
706     local _bin
707     _bin=$(find_binary "$1") || return 1
708     shift
709     local _line _shebang_regex
710     read -r -n 80 _line <"$_bin"
711     # If debug is set, clean unprintable chars to prevent messing up the term
712     [[ $debug ]] && _line=$(echo -n "$_line" | tr -c -d '[:print:][:space:]')
713     _shebang_regex='(#! *)(/[^ ]+).*'
714     [[ $_line =~ $_shebang_regex ]] || return 1
715     inst "${BASH_REMATCH[2]}" && inst_simple "$_bin" "$@"
716 }
717
718 # same as above, but specialized for symlinks
719 inst_symlink() {
720     local _src=$1 _target=${2:-$1} _realsrc
721     strstr "$1" "/" || return 1
722     [[ -L $1 ]] || return 1
723     [[ -L $initdir/$_target ]] && return 0
724     _realsrc=$(readlink -f "$_src")
725     if ! [[ -e $initdir/$_realsrc ]]; then
726         if [[ -d $_realsrc ]]; then
727             inst_dir "$_realsrc"
728         else
729             inst "$_realsrc"
730         fi
731     fi
732     [[ ! -e $initdir/${_target%/*} ]] && inst_dir "${_target%/*}"
733     [[ -d ${_target%/*} ]] && _target=$(readlink -f ${_target%/*})/${_target##*/}
734     ln -sfn $(convert_abs_rel "${_target}" "${_realsrc}") "$initdir/$_target"
735 }
736
737 # attempt to install any programs specified in a udev rule
738 inst_rule_programs() {
739     local _prog _bin
740
741     if grep -qE 'PROGRAM==?"[^ "]+' "$1"; then
742         for _prog in $(grep -E 'PROGRAM==?"[^ "]+' "$1" | sed -r 's/.*PROGRAM==?"([^ "]+).*/\1/'); do
743             if [ -x /lib/udev/$_prog ]; then
744                 _bin=/lib/udev/$_prog
745             else
746                 _bin=$(find_binary "$_prog") || {
747                     dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
748                     continue;
749                 }
750             fi
751
752             #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
753             dracut_install "$_bin"
754         done
755     fi
756 }
757
758 # udev rules always get installed in the same place, so
759 # create a function to install them to make life simpler.
760 inst_rules() {
761     local _target=/etc/udev/rules.d _rule _found
762
763     inst_dir "/lib/udev/rules.d"
764     inst_dir "$_target"
765     for _rule in "$@"; do
766         if [ "${rule#/}" = "$rule" ]; then
767             for r in /lib/udev/rules.d /etc/udev/rules.d; do
768                 if [[ -f $r/$_rule ]]; then
769                     _found="$r/$_rule"
770                     inst_simple "$_found"
771                     inst_rule_programs "$_found"
772                 fi
773             done
774         fi
775         for r in '' ./ $dracutbasedir/rules.d/; do
776             if [[ -f ${r}$_rule ]]; then
777                 _found="${r}$_rule"
778                 inst_simple "$_found" "$_target/${_found##*/}"
779                 inst_rule_programs "$_found"
780             fi
781         done
782         [[ $_found ]] || dinfo "Skipping udev rule: $_rule"
783     done
784 }
785
786 # general purpose installation function
787 # Same args as above.
788 inst() {
789     local _x
790
791     case $# in
792         1) ;;
793         2) [[ ! $initdir && -d $2 ]] && export initdir=$2
794             [[ $initdir = $2 ]] && set $1;;
795         3) [[ -z $initdir ]] && export initdir=$2
796             set $1 $3;;
797         *) dfatal "inst only takes 1 or 2 or 3 arguments"
798             exit 1;;
799     esac
800     for _x in inst_symlink inst_script inst_binary inst_simple; do
801         $_x "$@" && return 0
802     done
803     return 1
804 }
805
806 # install any of listed files
807 #
808 # If first argument is '-d' and second some destination path, first accessible
809 # source is installed into this path, otherwise it will installed in the same
810 # path as source.  If none of listed files was installed, function return 1.
811 # On first successful installation it returns with 0 status.
812 #
813 # Example:
814 #
815 # inst_any -d /bin/foo /bin/bar /bin/baz
816 #
817 # Lets assume that /bin/baz exists, so it will be installed as /bin/foo in
818 # initramfs.
819 inst_any() {
820     local to f
821
822     [[ $1 = '-d' ]] && to="$2" && shift 2
823
824     for f in "$@"; do
825         if [[ -e $f ]]; then
826             [[ $to ]] && inst "$f" "$to" && return 0
827             inst "$f" && return 0
828         fi
829     done
830
831     return 1
832 }
833
834 # dracut_install [-o ] <file> [<file> ... ]
835 # Install <file> to the initramfs image
836 # -o optionally install the <file> and don't fail, if it is not there
837 dracut_install() {
838     local _optional=no
839     if [[ $1 = '-o' ]]; then
840         _optional=yes
841         shift
842     fi
843     while (($# > 0)); do
844         if ! inst "$1" ; then
845             if [[ $_optional = yes ]]; then
846                 dinfo "Skipping program $1 as it cannot be found and is" \
847                     "flagged to be optional"
848             else
849                 dfatal "Failed to install $1"
850                 exit 1
851             fi
852         fi
853         shift
854     done
855 }
856
857 # Install a single kernel module along with any firmware it may require.
858 # $1 = full path to kernel module to install
859 install_kmod_with_fw() {
860     # no need to go further if the module is already installed
861
862     [[ -e "${initdir}/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" ]] \
863         && return 0
864
865     [[ -e "$initdir/.kernelmodseen/${1##*/}" ]] && return 0
866
867     if [[ $omit_drivers ]]; then
868         local _kmod=${1##*/}
869         _kmod=${_kmod%.ko}
870         _kmod=${_kmod/-/_}
871         if [[ "$_kmod" =~ $omit_drivers ]]; then
872             dinfo "Omitting driver $_kmod"
873             return 1
874         fi
875         if [[ "${1##*/lib/modules/$KERNEL_VER/}" =~ $omit_drivers ]]; then
876             dinfo "Omitting driver $_kmod"
877             return 1
878         fi
879     fi
880
881     [ -d "$initdir/.kernelmodseen" ] && \
882         > "$initdir/.kernelmodseen/${1##*/}"
883
884     inst_simple "$1" "/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" \
885         || return $?
886
887     local _modname=${1##*/} _fwdir _found _fw
888     _modname=${_modname%.ko*}
889     for _fw in $(modinfo -k $KERNEL_VER -F firmware $1 2>/dev/null); do
890         _found=''
891         for _fwdir in $fw_dir; do
892             if [[ -d $_fwdir && -f $_fwdir/$_fw ]]; then
893                 inst_simple "$_fwdir/$_fw" "/lib/firmware/$_fw"
894                 _found=yes
895             fi
896         done
897         if [[ $_found != yes ]]; then
898             if ! grep -qe "\<${_modname//-/_}\>" /proc/modules; then
899                 dinfo "Possible missing firmware \"${_fw}\" for kernel module" \
900                     "\"${_modname}.ko\""
901             else
902                 dwarn "Possible missing firmware \"${_fw}\" for kernel module" \
903                     "\"${_modname}.ko\""
904             fi
905         fi
906     done
907     return 0
908 }
909
910 # Do something with all the dependencies of a kernel module.
911 # Note that kernel modules depend on themselves using the technique we use
912 # $1 = function to call for each dependency we find
913 #      It will be passed the full path to the found kernel module
914 # $2 = module to get dependencies for
915 # rest of args = arguments to modprobe
916 # _fderr specifies FD passed from surrounding scope
917 for_each_kmod_dep() {
918     local _func=$1 _kmod=$2 _cmd _modpath _options _found=0
919     shift 2
920     modprobe "$@" --ignore-install --show-depends $_kmod 2>&${_fderr} | (
921         while read _cmd _modpath _options; do
922             [[ $_cmd = insmod ]] || continue
923             $_func ${_modpath} || exit $?
924             _found=1
925         done
926         [[ $_found -eq 0 ]] && exit 1
927         exit 0
928     )
929 }
930
931 # filter kernel modules to install certain modules that meet specific
932 # requirements.
933 # $1 = search only in subdirectory of /kernel/$1
934 # $2 = function to call with module name to filter.
935 #      This function will be passed the full path to the module to test.
936 # The behavior of this function can vary depending on whether $hostonly is set.
937 # If it is, we will only look at modules that are already in memory.
938 # If it is not, we will look at all kernel modules
939 # This function returns the full filenames of modules that match $1
940 filter_kernel_modules_by_path () (
941     local _modname _filtercmd
942     if ! [[ $hostonly ]]; then
943         _filtercmd='find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra"'
944         _filtercmd+=' "$KERNEL_MODS/weak-updates" -name "*.ko" -o -name "*.ko.gz"'
945         _filtercmd+=' -o -name "*.ko.xz"'
946         _filtercmd+=' 2>/dev/null'
947     else
948         _filtercmd='cut -d " " -f 1 </proc/modules|xargs modinfo -F filename '
949         _filtercmd+='-k $KERNEL_VER 2>/dev/null'
950     fi
951     for _modname in $(eval $_filtercmd); do
952         case $_modname in
953             *.ko) "$2" "$_modname" && echo "$_modname";;
954             *.ko.gz) gzip -dc "$_modname" > $initdir/$$.ko
955                 $2 $initdir/$$.ko && echo "$_modname"
956                 rm -f $initdir/$$.ko
957                 ;;
958             *.ko.xz) xz -dc "$_modname" > $initdir/$$.ko
959                 $2 $initdir/$$.ko && echo "$_modname"
960                 rm -f $initdir/$$.ko
961                 ;;
962         esac
963     done
964 )
965 find_kernel_modules_by_path () (
966     if ! [[ $hostonly ]]; then
967         find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra" "$KERNEL_MODS/weak-updates" \
968           -name "*.ko" -o -name "*.ko.gz" -o -name "*.ko.xz" 2>/dev/null
969     else
970         cut -d " " -f 1 </proc/modules \
971         | xargs modinfo -F filename -k $KERNEL_VER 2>/dev/null
972     fi
973 )
974
975 filter_kernel_modules () {
976     filter_kernel_modules_by_path  drivers  "$1"
977 }
978
979 find_kernel_modules () {
980     find_kernel_modules_by_path  drivers
981 }
982
983 # instmods [-c] <kernel module> [<kernel module> ... ]
984 # instmods [-c] <kernel subsystem>
985 # install kernel modules along with all their dependencies.
986 # <kernel subsystem> can be e.g. "=block" or "=drivers/usb/storage"
987 instmods() {
988     [[ $no_kernel = yes ]] && return
989     # called [sub]functions inherit _fderr
990     local _fderr=9
991     local _check=no
992     if [[ $1 = '-c' ]]; then
993         _check=yes
994         shift
995     fi
996
997     function inst1mod() {
998         local _ret=0 _mod="$1"
999         case $_mod in
1000             =*)
1001                 if [ -f $KERNEL_MODS/modules.${_mod#=} ]; then
1002                     ( [[ "$_mpargs" ]] && echo $_mpargs
1003                       cat "${KERNEL_MODS}/modules.${_mod#=}" ) \
1004                     | instmods
1005                 else
1006                     ( [[ "$_mpargs" ]] && echo $_mpargs
1007                       find "$KERNEL_MODS" -path "*/${_mod#=}/*" -printf '%f\n' ) \
1008                     | instmods
1009                 fi
1010                 ;;
1011             --*) _mpargs+=" $_mod" ;;
1012             i2o_scsi) return ;; # Do not load this diagnostic-only module
1013             *)
1014                 _mod=${_mod##*/}
1015                 # if we are already installed, skip this module and go on
1016                 # to the next one.
1017                 [[ -f "$initdir/.kernelmodseen/${_mod%.ko}.ko" ]] && return
1018
1019                 if [[ $omit_drivers ]] && [[ "$1" =~ $omit_drivers ]]; then
1020                     dinfo "Omitting driver ${_mod##$KERNEL_MODS}"
1021                     return
1022                 fi
1023                 # If we are building a host-specific initramfs and this
1024                 # module is not already loaded, move on to the next one.
1025                 [[ $hostonly ]] && ! grep -qe "\<${_mod//-/_}\>" /proc/modules \
1026                     && ! echo $add_drivers | grep -qe "\<${_mod}\>" \
1027                     && return
1028
1029                 # We use '-d' option in modprobe only if modules prefix path
1030                 # differs from default '/'.  This allows us to use Dracut with
1031                 # old version of modprobe which doesn't have '-d' option.
1032                 local _moddirname=${KERNEL_MODS%%/lib/modules/*}
1033                 [[ -n ${_moddirname} ]] && _moddirname="-d ${_moddirname}/"
1034
1035                 # ok, load the module, all its dependencies, and any firmware
1036                 # it may require
1037                 for_each_kmod_dep install_kmod_with_fw $_mod \
1038                     --set-version $KERNEL_VER ${_moddirname} $_mpargs
1039                 ((_ret+=$?))
1040                 ;;
1041         esac
1042         return $_ret
1043     }
1044
1045     function instmods_1() {
1046         local _mod _mpargs
1047         if (($# == 0)); then  # filenames from stdin
1048             while read _mod; do
1049                 inst1mod "${_mod%.ko*}" || {
1050                     if [ "$_check" = "yes" ]; then
1051                         dfatal "Failed to install $_mod"
1052                         return 1
1053                     fi
1054                 }
1055             done
1056         fi
1057         while (($# > 0)); do  # filenames as arguments
1058             inst1mod ${1%.ko*} || {
1059                 if [ "$_check" = "yes" ]; then
1060                     dfatal "Failed to install $1"
1061                     return 1
1062                 fi
1063             }
1064             shift
1065         done
1066         return 0
1067     }
1068
1069     local _ret _filter_not_found='FATAL: Module .* not found.'
1070     set -o pipefail
1071     # Capture all stderr from modprobe to _fderr. We could use {var}>...
1072     # redirections, but that would make dracut require bash4 at least.
1073     eval "( instmods_1 \"\$@\" ) ${_fderr}>&1" \
1074     | while read line; do [[ "$line" =~ $_filter_not_found ]] && echo $line || echo $line >&2 ;done | derror
1075     _ret=$?
1076     set +o pipefail
1077     return $_ret
1078 }
1079
1080 # inst_libdir_file [-n <pattern>] <file> [<file>...]
1081 # Install a <file> located on a lib directory to the initramfs image
1082 # -n <pattern> install non-matching files
1083 inst_libdir_file() {
1084     if [[ "$1" == "-n" ]]; then
1085         local _pattern=$1
1086         shift 2
1087         for _dir in $libdirs; do
1088             for _i in "$@"; do
1089                 for _f in "$_dir"/$_i; do
1090                     [[ "$_i" =~ $_pattern ]] || continue
1091                     [[ -e "$_i" ]] && dracut_install "$_i"
1092                 done
1093             done
1094         done
1095     else
1096         for _dir in $libdirs; do
1097             for _i in "$@"; do
1098                 for _f in "$_dir"/$_i; do
1099                     [[ -e "$_f" ]] && dracut_install "$_f"
1100                 done
1101             done
1102         done
1103     fi
1104 }
1105
1106 check_nspawn() {
1107     [[ -d /sys/fs/cgroup/systemd ]]
1108 }
1109
1110
1111 do_test() {
1112     if [[ $UID != "0" ]]; then
1113         echo "TEST: $TEST_DESCRIPTION [SKIPPED]: not root" >&2
1114         exit 0
1115     fi
1116
1117 # Detect lib paths
1118     [[ $libdir ]] || for libdir in /lib64 /lib; do
1119         [[ -d $libdir ]] && libdirs+=" $libdir" && break
1120     done
1121
1122     [[ $usrlibdir ]] || for usrlibdir in /usr/lib64 /usr/lib; do
1123         [[ -d $usrlibdir ]] && libdirs+=" $usrlibdir" && break
1124     done
1125
1126     import_testdir
1127     import_initdir
1128
1129     while (($# > 0)); do
1130         case $1 in
1131             --run)
1132                 echo "TEST RUN: $TEST_DESCRIPTION"
1133                 test_run
1134                 ret=$?
1135                 if [ $ret -eq 0 ]; then
1136                     echo "TEST RUN: $TEST_DESCRIPTION [OK]"
1137                 else
1138                     echo "TEST RUN: $TEST_DESCRIPTION [FAILED]"
1139                 fi
1140                 exit $ret;;
1141             --setup)
1142                 echo "TEST SETUP: $TEST_DESCRIPTION"
1143                 test_setup
1144                 exit $?;;
1145             --clean)
1146                 echo "TEST CLEANUP: $TEST_DESCRIPTION"
1147                 test_cleanup
1148                 rm -fr "$TESTDIR"
1149                 rm -f .testdir
1150                 exit $?;;
1151             --all)
1152                 echo -n "TEST: $TEST_DESCRIPTION ";
1153                 (
1154                     test_setup && test_run
1155                     ret=$?
1156                     test_cleanup
1157                     rm -fr "$TESTDIR"
1158                     rm -f .testdir
1159                     exit $ret
1160                 ) </dev/null >test.log 2>&1
1161                 ret=$?
1162                 if [ $ret -eq 0 ]; then
1163                     rm test.log
1164                     echo "[OK]"
1165                 else
1166                     echo "[FAILED]"
1167                     echo "see $(pwd)/test.log"
1168                 fi
1169                 exit $ret;;
1170             *) break ;;
1171         esac
1172         shift
1173     done
1174 }