chiark / gitweb /
tests: install ldconfig.real for Debian based distros
[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 hostname"
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     # in Debian ldconfig is just a shell script wrapper around ldconfig.real
237     dracut_install -o ldconfig.real
238 }
239
240 install_debug_tools() {
241     [[ $DEBUGTOOLS ]] && dracut_install $DEBUGTOOLS
242 }
243
244 install_libnss() {
245     # install libnss_files for login
246     NSS_LIBS=$(LD_DEBUG=files getent passwd 2>&1 >/dev/null |sed -n '/calling init: .*libnss_/ {s!^.* /!/!; p}')
247     for l in $NSS_LIBS; do
248         dracut_install $l
249     done
250 }
251
252 install_dbus() {
253     inst $ROOTLIBDIR/system/dbus.socket
254     inst $ROOTLIBDIR/system/dbus.service
255
256     find \
257         /etc/dbus-1 -xtype f \
258         | while read file; do
259         inst $file
260     done
261 }
262
263 install_pam() {
264     find \
265         /etc/pam.d \
266         /etc/security \
267         /lib64/security \
268         /lib/security -xtype f \
269         | while read file; do
270         inst $file
271     done
272 }
273
274 install_keymaps() {
275     for i in \
276         /usr/lib/kbd/keymaps/include/* \
277         /usr/lib/kbd/keymaps/i386/include/* \
278         /usr/lib/kbd/keymaps/i386/qwerty/us.*; do
279             [[ -f $i ]] || continue
280             inst $i
281     done
282 }
283
284 install_fonts() {
285     for i in \
286         /usr/lib/kbd/consolefonts/eurlatgr* \
287         /usr/lib/kbd/consolefonts/latarcyrheb-sun16*; do
288             [[ -f $i ]] || continue
289             inst $i
290     done
291 }
292
293 install_terminfo() {
294     for _terminfodir in /lib/terminfo /etc/terminfo /usr/share/terminfo; do
295         [ -f ${_terminfodir}/l/linux ] && break
296     done
297     dracut_install -o ${_terminfodir}/l/linux
298 }
299
300 setup_testsuite() {
301     cp $TEST_BASE_DIR/testsuite.target $initdir/etc/systemd/system/
302     sed "s#@SYSTEMCTL@#$(type -P systemctl)#g" $TEST_BASE_DIR/end.service.in > $initdir/etc/systemd/system/end.service
303
304     mkdir -p $initdir/etc/systemd/system/testsuite.target.wants
305     ln -fs $TEST_BASE_DIR/testsuite.service $initdir/etc/systemd/system/testsuite.target.wants/testsuite.service
306     ln -fs $TEST_BASE_DIR/end.service $initdir/etc/systemd/system/testsuite.target.wants/end.service
307
308     # make the testsuite the default target
309     ln -fs testsuite.target $initdir/etc/systemd/system/default.target
310 }
311
312 setup_nspawn_root() {
313     rm -fr $TESTDIR/nspawn-root
314     ddebug "cp -ar $initdir $TESTDIR/nspawn-root"
315     cp -ar $initdir $TESTDIR/nspawn-root
316     # we don't mount in the nspawn root
317     rm -f $TESTDIR/nspawn-root/etc/fstab
318 }
319
320 setup_basic_dirs() {
321     mkdir -p $initdir/run
322     mkdir -p $initdir/etc/systemd/system
323     mkdir -p $initdir/var/log/journal
324
325     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
326         if [ -L "/$d" ]; then
327             inst_symlink "/$d"
328         else
329             inst_dir "/$d"
330         fi
331     done
332
333     ln -sfn /run "$initdir/var/run"
334     ln -sfn /run/lock "$initdir/var/lock"
335 }
336
337 inst_libs() {
338     local _bin=$1
339     local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
340     local _file _line
341
342     LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
343         [[ $_line = 'not a dynamic executable' ]] && break
344
345         if [[ $_line =~ $_so_regex ]]; then
346             _file=${BASH_REMATCH[1]}
347             [[ -e ${initdir}/$_file ]] && continue
348             inst_library "$_file"
349             continue
350         fi
351
352         if [[ $_line =~ not\ found ]]; then
353             dfatal "Missing a shared library required by $_bin."
354             dfatal "Run \"ldd $_bin\" to find out what it is."
355             dfatal "$_line"
356             dfatal "dracut cannot create an initrd."
357             exit 1
358         fi
359     done
360 }
361
362 import_testdir() {
363     STATEFILE=".testdir"
364     [[ -e $STATEFILE ]] && . $STATEFILE
365     if [[ -z "$TESTDIR" ]] || [[ ! -d "$TESTDIR" ]]; then
366         TESTDIR=$(mktemp --tmpdir=/var/tmp -d -t systemd-test.XXXXXX)
367         echo "TESTDIR=\"$TESTDIR\"" > $STATEFILE
368         export TESTDIR
369     fi
370 }
371
372 import_initdir() {
373     initdir=$TESTDIR/root
374     export initdir
375 }
376
377 ## @brief Converts numeric logging level to the first letter of level name.
378 #
379 # @param lvl Numeric logging level in range from 1 to 6.
380 # @retval 1 if @a lvl is out of range.
381 # @retval 0 if @a lvl is correct.
382 # @result Echoes first letter of level name.
383 _lvl2char() {
384     case "$1" in
385         1) echo F;;
386         2) echo E;;
387         3) echo W;;
388         4) echo I;;
389         5) echo D;;
390         6) echo T;;
391         *) return 1;;
392     esac
393 }
394
395 ## @brief Internal helper function for _do_dlog()
396 #
397 # @param lvl Numeric logging level.
398 # @param msg Message.
399 # @retval 0 It's always returned, even if logging failed.
400 #
401 # @note This function is not supposed to be called manually. Please use
402 # dtrace(), ddebug(), or others instead which wrap this one.
403 #
404 # This function calls _do_dlog() either with parameter msg, or if
405 # none is given, it will read standard input and will use every line as
406 # a message.
407 #
408 # This enables:
409 # dwarn "This is a warning"
410 # echo "This is a warning" | dwarn
411 LOG_LEVEL=4
412
413 dlog() {
414     [ -z "$LOG_LEVEL" ] && return 0
415     [ $1 -le $LOG_LEVEL ] || return 0
416     local lvl="$1"; shift
417     local lvlc=$(_lvl2char "$lvl") || return 0
418
419     if [ $# -ge 1 ]; then
420         echo "$lvlc: $*"
421     else
422         while read line; do
423             echo "$lvlc: " "$line"
424         done
425     fi
426 }
427
428 ## @brief Logs message at TRACE level (6)
429 #
430 # @param msg Message.
431 # @retval 0 It's always returned, even if logging failed.
432 dtrace() {
433     set +x
434     dlog 6 "$@"
435     [ -n "$debug" ] && set -x || :
436 }
437
438 ## @brief Logs message at DEBUG level (5)
439 #
440 # @param msg Message.
441 # @retval 0 It's always returned, even if logging failed.
442 ddebug() {
443 #    set +x
444     dlog 5 "$@"
445 #    [ -n "$debug" ] && set -x || :
446 }
447
448 ## @brief Logs message at INFO level (4)
449 #
450 # @param msg Message.
451 # @retval 0 It's always returned, even if logging failed.
452 dinfo() {
453     set +x
454     dlog 4 "$@"
455     [ -n "$debug" ] && set -x || :
456 }
457
458 ## @brief Logs message at WARN level (3)
459 #
460 # @param msg Message.
461 # @retval 0 It's always returned, even if logging failed.
462 dwarn() {
463     set +x
464     dlog 3 "$@"
465     [ -n "$debug" ] && set -x || :
466 }
467
468 ## @brief Logs message at ERROR level (2)
469 #
470 # @param msg Message.
471 # @retval 0 It's always returned, even if logging failed.
472 derror() {
473 #    set +x
474     dlog 2 "$@"
475 #    [ -n "$debug" ] && set -x || :
476 }
477
478 ## @brief Logs message at FATAL level (1)
479 #
480 # @param msg Message.
481 # @retval 0 It's always returned, even if logging failed.
482 dfatal() {
483     set +x
484     dlog 1 "$@"
485     [ -n "$debug" ] && set -x || :
486 }
487
488
489 # Generic substring function.  If $2 is in $1, return 0.
490 strstr() { [ "${1#*$2*}" != "$1" ]; }
491
492 # normalize_path <path>
493 # Prints the normalized path, where it removes any duplicated
494 # and trailing slashes.
495 # Example:
496 # $ normalize_path ///test/test//
497 # /test/test
498 normalize_path() {
499     shopt -q -s extglob
500     set -- "${1//+(\/)//}"
501     shopt -q -u extglob
502     echo "${1%/}"
503 }
504
505 # convert_abs_rel <from> <to>
506 # Prints the relative path, when creating a symlink to <to> from <from>.
507 # Example:
508 # $ convert_abs_rel /usr/bin/test /bin/test-2
509 # ../../bin/test-2
510 # $ ln -s $(convert_abs_rel /usr/bin/test /bin/test-2) /usr/bin/test
511 convert_abs_rel() {
512     local __current __absolute __abssize __cursize __newpath
513     local -i __i __level
514
515     set -- "$(normalize_path "$1")" "$(normalize_path "$2")"
516
517     # corner case #1 - self looping link
518     [[ "$1" == "$2" ]] && { echo "${1##*/}"; return; }
519
520     # corner case #2 - own dir link
521     [[ "${1%/*}" == "$2" ]] && { echo "."; return; }
522
523     IFS="/" __current=($1)
524     IFS="/" __absolute=($2)
525
526     __abssize=${#__absolute[@]}
527     __cursize=${#__current[@]}
528
529     while [[ ${__absolute[__level]} == ${__current[__level]} ]]
530     do
531         (( __level++ ))
532         if (( __level > __abssize || __level > __cursize ))
533         then
534             break
535         fi
536     done
537
538     for ((__i = __level; __i < __cursize-1; __i++))
539     do
540         if ((__i > __level))
541         then
542             __newpath=$__newpath"/"
543         fi
544         __newpath=$__newpath".."
545     done
546
547     for ((__i = __level; __i < __abssize; __i++))
548     do
549         if [[ -n $__newpath ]]
550         then
551             __newpath=$__newpath"/"
552         fi
553         __newpath=$__newpath${__absolute[__i]}
554     done
555
556     echo "$__newpath"
557 }
558
559
560 # Install a directory, keeping symlinks as on the original system.
561 # Example: if /lib points to /lib64 on the host, "inst_dir /lib/file"
562 # will create ${initdir}/lib64, ${initdir}/lib64/file,
563 # and a symlink ${initdir}/lib -> lib64.
564 inst_dir() {
565     [[ -e ${initdir}/"$1" ]] && return 0  # already there
566
567     local _dir="$1" _part="${1%/*}" _file
568     while [[ "$_part" != "${_part%/*}" ]] && ! [[ -e "${initdir}/${_part}" ]]; do
569         _dir="$_part $_dir"
570         _part=${_part%/*}
571     done
572
573     # iterate over parent directories
574     for _file in $_dir; do
575         [[ -e "${initdir}/$_file" ]] && continue
576         if [[ -L $_file ]]; then
577             inst_symlink "$_file"
578         else
579             # create directory
580             mkdir -m 0755 -p "${initdir}/$_file" || return 1
581             [[ -e "$_file" ]] && chmod --reference="$_file" "${initdir}/$_file"
582             chmod u+w "${initdir}/$_file"
583         fi
584     done
585 }
586
587 # $1 = file to copy to ramdisk
588 # $2 (optional) Name for the file on the ramdisk
589 # Location of the image dir is assumed to be $initdir
590 # We never overwrite the target if it exists.
591 inst_simple() {
592     [[ -f "$1" ]] || return 1
593     strstr "$1" "/" || return 1
594
595     local _src=$1 target="${2:-$1}"
596     if ! [[ -d ${initdir}/$target ]]; then
597         [[ -e ${initdir}/$target ]] && return 0
598         [[ -L ${initdir}/$target ]] && return 0
599         [[ -d "${initdir}/${target%/*}" ]] || inst_dir "${target%/*}"
600     fi
601     # install checksum files also
602     if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
603         inst "${_src%/*}/.${_src##*/}.hmac" "${target%/*}/.${target##*/}.hmac"
604     fi
605     ddebug "Installing $_src"
606     cp --sparse=always -pfL "$_src" "${initdir}/$target"
607 }
608
609 # find symlinks linked to given library file
610 # $1 = library file
611 # Function searches for symlinks by stripping version numbers appended to
612 # library filename, checks if it points to the same target and finally
613 # prints the list of symlinks to stdout.
614 #
615 # Example:
616 # rev_lib_symlinks libfoo.so.8.1
617 # output: libfoo.so.8 libfoo.so
618 # (Only if libfoo.so.8 and libfoo.so exists on host system.)
619 rev_lib_symlinks() {
620     [[ ! $1 ]] && return 0
621
622     local fn="$1" orig="$(readlink -f "$1")" links=''
623
624     [[ ${fn} =~ .*\.so\..* ]] || return 1
625
626     until [[ ${fn##*.} == so ]]; do
627         fn="${fn%.*}"
628         [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
629     done
630
631     echo "${links}"
632 }
633
634 # Same as above, but specialized to handle dynamic libraries.
635 # It handles making symlinks according to how the original library
636 # is referenced.
637 inst_library() {
638     local _src="$1" _dest=${2:-$1} _lib _reallib _symlink
639     strstr "$1" "/" || return 1
640     [[ -e $initdir/$_dest ]] && return 0
641     if [[ -L $_src ]]; then
642         # install checksum files also
643         if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
644             inst "${_src%/*}/.${_src##*/}.hmac" "${_dest%/*}/.${_dest##*/}.hmac"
645         fi
646         _reallib=$(readlink -f "$_src")
647         inst_simple "$_reallib" "$_reallib"
648         inst_dir "${_dest%/*}"
649         [[ -d "${_dest%/*}" ]] && _dest=$(readlink -f "${_dest%/*}")/${_dest##*/}
650         ln -sfn $(convert_abs_rel "${_dest}" "${_reallib}") "${initdir}/${_dest}"
651     else
652         inst_simple "$_src" "$_dest"
653     fi
654
655     # Create additional symlinks.  See rev_symlinks description.
656     for _symlink in $(rev_lib_symlinks $_src) $(rev_lib_symlinks $_reallib); do
657         [[ ! -e $initdir/$_symlink ]] && {
658             ddebug "Creating extra symlink: $_symlink"
659             inst_symlink $_symlink
660         }
661     done
662 }
663
664 # find a binary.  If we were not passed the full path directly,
665 # search in the usual places to find the binary.
666 find_binary() {
667     if [[ -z ${1##/*} ]]; then
668         if [[ -x $1 ]] || { strstr "$1" ".so" && ldd $1 &>/dev/null; };  then
669             echo $1
670             return 0
671         fi
672     fi
673
674     type -P $1
675 }
676
677 # Same as above, but specialized to install binary executables.
678 # Install binary executable, and all shared library dependencies, if any.
679 inst_binary() {
680     local _bin _target
681     _bin=$(find_binary "$1") || return 1
682     _target=${2:-$_bin}
683     [[ -e $initdir/$_target ]] && return 0
684     [[ -L $_bin ]] && inst_symlink $_bin $_target && return 0
685     local _file _line
686     local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
687     # I love bash!
688     LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
689         [[ $_line = 'not a dynamic executable' ]] && break
690
691         if [[ $_line =~ $_so_regex ]]; then
692             _file=${BASH_REMATCH[1]}
693             [[ -e ${initdir}/$_file ]] && continue
694             inst_library "$_file"
695             continue
696         fi
697
698         if [[ $_line =~ not\ found ]]; then
699             dfatal "Missing a shared library required by $_bin."
700             dfatal "Run \"ldd $_bin\" to find out what it is."
701             dfatal "$_line"
702             dfatal "dracut cannot create an initrd."
703             exit 1
704         fi
705     done
706     inst_simple "$_bin" "$_target"
707 }
708
709 # same as above, except for shell scripts.
710 # If your shell script does not start with shebang, it is not a shell script.
711 inst_script() {
712     local _bin
713     _bin=$(find_binary "$1") || return 1
714     shift
715     local _line _shebang_regex
716     read -r -n 80 _line <"$_bin"
717     # If debug is set, clean unprintable chars to prevent messing up the term
718     [[ $debug ]] && _line=$(echo -n "$_line" | tr -c -d '[:print:][:space:]')
719     _shebang_regex='(#! *)(/[^ ]+).*'
720     [[ $_line =~ $_shebang_regex ]] || return 1
721     inst "${BASH_REMATCH[2]}" && inst_simple "$_bin" "$@"
722 }
723
724 # same as above, but specialized for symlinks
725 inst_symlink() {
726     local _src=$1 _target=${2:-$1} _realsrc
727     strstr "$1" "/" || return 1
728     [[ -L $1 ]] || return 1
729     [[ -L $initdir/$_target ]] && return 0
730     _realsrc=$(readlink -f "$_src")
731     if ! [[ -e $initdir/$_realsrc ]]; then
732         if [[ -d $_realsrc ]]; then
733             inst_dir "$_realsrc"
734         else
735             inst "$_realsrc"
736         fi
737     fi
738     [[ ! -e $initdir/${_target%/*} ]] && inst_dir "${_target%/*}"
739     [[ -d ${_target%/*} ]] && _target=$(readlink -f ${_target%/*})/${_target##*/}
740     ln -sfn $(convert_abs_rel "${_target}" "${_realsrc}") "$initdir/$_target"
741 }
742
743 # attempt to install any programs specified in a udev rule
744 inst_rule_programs() {
745     local _prog _bin
746
747     if grep -qE 'PROGRAM==?"[^ "]+' "$1"; then
748         for _prog in $(grep -E 'PROGRAM==?"[^ "]+' "$1" | sed -r 's/.*PROGRAM==?"([^ "]+).*/\1/'); do
749             if [ -x /lib/udev/$_prog ]; then
750                 _bin=/lib/udev/$_prog
751             else
752                 _bin=$(find_binary "$_prog") || {
753                     dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
754                     continue;
755                 }
756             fi
757
758             #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
759             dracut_install "$_bin"
760         done
761     fi
762 }
763
764 # udev rules always get installed in the same place, so
765 # create a function to install them to make life simpler.
766 inst_rules() {
767     local _target=/etc/udev/rules.d _rule _found
768
769     inst_dir "/lib/udev/rules.d"
770     inst_dir "$_target"
771     for _rule in "$@"; do
772         if [ "${rule#/}" = "$rule" ]; then
773             for r in /lib/udev/rules.d /etc/udev/rules.d; do
774                 if [[ -f $r/$_rule ]]; then
775                     _found="$r/$_rule"
776                     inst_simple "$_found"
777                     inst_rule_programs "$_found"
778                 fi
779             done
780         fi
781         for r in '' ./ $dracutbasedir/rules.d/; do
782             if [[ -f ${r}$_rule ]]; then
783                 _found="${r}$_rule"
784                 inst_simple "$_found" "$_target/${_found##*/}"
785                 inst_rule_programs "$_found"
786             fi
787         done
788         [[ $_found ]] || dinfo "Skipping udev rule: $_rule"
789     done
790 }
791
792 # general purpose installation function
793 # Same args as above.
794 inst() {
795     local _x
796
797     case $# in
798         1) ;;
799         2) [[ ! $initdir && -d $2 ]] && export initdir=$2
800             [[ $initdir = $2 ]] && set $1;;
801         3) [[ -z $initdir ]] && export initdir=$2
802             set $1 $3;;
803         *) dfatal "inst only takes 1 or 2 or 3 arguments"
804             exit 1;;
805     esac
806     for _x in inst_symlink inst_script inst_binary inst_simple; do
807         $_x "$@" && return 0
808     done
809     return 1
810 }
811
812 # install any of listed files
813 #
814 # If first argument is '-d' and second some destination path, first accessible
815 # source is installed into this path, otherwise it will installed in the same
816 # path as source.  If none of listed files was installed, function return 1.
817 # On first successful installation it returns with 0 status.
818 #
819 # Example:
820 #
821 # inst_any -d /bin/foo /bin/bar /bin/baz
822 #
823 # Lets assume that /bin/baz exists, so it will be installed as /bin/foo in
824 # initramfs.
825 inst_any() {
826     local to f
827
828     [[ $1 = '-d' ]] && to="$2" && shift 2
829
830     for f in "$@"; do
831         if [[ -e $f ]]; then
832             [[ $to ]] && inst "$f" "$to" && return 0
833             inst "$f" && return 0
834         fi
835     done
836
837     return 1
838 }
839
840 # dracut_install [-o ] <file> [<file> ... ]
841 # Install <file> to the initramfs image
842 # -o optionally install the <file> and don't fail, if it is not there
843 dracut_install() {
844     local _optional=no
845     if [[ $1 = '-o' ]]; then
846         _optional=yes
847         shift
848     fi
849     while (($# > 0)); do
850         if ! inst "$1" ; then
851             if [[ $_optional = yes ]]; then
852                 dinfo "Skipping program $1 as it cannot be found and is" \
853                     "flagged to be optional"
854             else
855                 dfatal "Failed to install $1"
856                 exit 1
857             fi
858         fi
859         shift
860     done
861 }
862
863 # Install a single kernel module along with any firmware it may require.
864 # $1 = full path to kernel module to install
865 install_kmod_with_fw() {
866     # no need to go further if the module is already installed
867
868     [[ -e "${initdir}/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" ]] \
869         && return 0
870
871     [[ -e "$initdir/.kernelmodseen/${1##*/}" ]] && return 0
872
873     if [[ $omit_drivers ]]; then
874         local _kmod=${1##*/}
875         _kmod=${_kmod%.ko}
876         _kmod=${_kmod/-/_}
877         if [[ "$_kmod" =~ $omit_drivers ]]; then
878             dinfo "Omitting driver $_kmod"
879             return 1
880         fi
881         if [[ "${1##*/lib/modules/$KERNEL_VER/}" =~ $omit_drivers ]]; then
882             dinfo "Omitting driver $_kmod"
883             return 1
884         fi
885     fi
886
887     [ -d "$initdir/.kernelmodseen" ] && \
888         > "$initdir/.kernelmodseen/${1##*/}"
889
890     inst_simple "$1" "/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" \
891         || return $?
892
893     local _modname=${1##*/} _fwdir _found _fw
894     _modname=${_modname%.ko*}
895     for _fw in $(modinfo -k $KERNEL_VER -F firmware $1 2>/dev/null); do
896         _found=''
897         for _fwdir in $fw_dir; do
898             if [[ -d $_fwdir && -f $_fwdir/$_fw ]]; then
899                 inst_simple "$_fwdir/$_fw" "/lib/firmware/$_fw"
900                 _found=yes
901             fi
902         done
903         if [[ $_found != yes ]]; then
904             if ! grep -qe "\<${_modname//-/_}\>" /proc/modules; then
905                 dinfo "Possible missing firmware \"${_fw}\" for kernel module" \
906                     "\"${_modname}.ko\""
907             else
908                 dwarn "Possible missing firmware \"${_fw}\" for kernel module" \
909                     "\"${_modname}.ko\""
910             fi
911         fi
912     done
913     return 0
914 }
915
916 # Do something with all the dependencies of a kernel module.
917 # Note that kernel modules depend on themselves using the technique we use
918 # $1 = function to call for each dependency we find
919 #      It will be passed the full path to the found kernel module
920 # $2 = module to get dependencies for
921 # rest of args = arguments to modprobe
922 # _fderr specifies FD passed from surrounding scope
923 for_each_kmod_dep() {
924     local _func=$1 _kmod=$2 _cmd _modpath _options _found=0
925     shift 2
926     modprobe "$@" --ignore-install --show-depends $_kmod 2>&${_fderr} | (
927         while read _cmd _modpath _options; do
928             [[ $_cmd = insmod ]] || continue
929             $_func ${_modpath} || exit $?
930             _found=1
931         done
932         [[ $_found -eq 0 ]] && exit 1
933         exit 0
934     )
935 }
936
937 # filter kernel modules to install certain modules that meet specific
938 # requirements.
939 # $1 = search only in subdirectory of /kernel/$1
940 # $2 = function to call with module name to filter.
941 #      This function will be passed the full path to the module to test.
942 # The behavior of this function can vary depending on whether $hostonly is set.
943 # If it is, we will only look at modules that are already in memory.
944 # If it is not, we will look at all kernel modules
945 # This function returns the full filenames of modules that match $1
946 filter_kernel_modules_by_path () (
947     local _modname _filtercmd
948     if ! [[ $hostonly ]]; then
949         _filtercmd='find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra"'
950         _filtercmd+=' "$KERNEL_MODS/weak-updates" -name "*.ko" -o -name "*.ko.gz"'
951         _filtercmd+=' -o -name "*.ko.xz"'
952         _filtercmd+=' 2>/dev/null'
953     else
954         _filtercmd='cut -d " " -f 1 </proc/modules|xargs modinfo -F filename '
955         _filtercmd+='-k $KERNEL_VER 2>/dev/null'
956     fi
957     for _modname in $(eval $_filtercmd); do
958         case $_modname in
959             *.ko) "$2" "$_modname" && echo "$_modname";;
960             *.ko.gz) gzip -dc "$_modname" > $initdir/$$.ko
961                 $2 $initdir/$$.ko && echo "$_modname"
962                 rm -f $initdir/$$.ko
963                 ;;
964             *.ko.xz) xz -dc "$_modname" > $initdir/$$.ko
965                 $2 $initdir/$$.ko && echo "$_modname"
966                 rm -f $initdir/$$.ko
967                 ;;
968         esac
969     done
970 )
971 find_kernel_modules_by_path () (
972     if ! [[ $hostonly ]]; then
973         find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra" "$KERNEL_MODS/weak-updates" \
974           -name "*.ko" -o -name "*.ko.gz" -o -name "*.ko.xz" 2>/dev/null
975     else
976         cut -d " " -f 1 </proc/modules \
977         | xargs modinfo -F filename -k $KERNEL_VER 2>/dev/null
978     fi
979 )
980
981 filter_kernel_modules () {
982     filter_kernel_modules_by_path  drivers  "$1"
983 }
984
985 find_kernel_modules () {
986     find_kernel_modules_by_path  drivers
987 }
988
989 # instmods [-c] <kernel module> [<kernel module> ... ]
990 # instmods [-c] <kernel subsystem>
991 # install kernel modules along with all their dependencies.
992 # <kernel subsystem> can be e.g. "=block" or "=drivers/usb/storage"
993 instmods() {
994     [[ $no_kernel = yes ]] && return
995     # called [sub]functions inherit _fderr
996     local _fderr=9
997     local _check=no
998     if [[ $1 = '-c' ]]; then
999         _check=yes
1000         shift
1001     fi
1002
1003     function inst1mod() {
1004         local _ret=0 _mod="$1"
1005         case $_mod in
1006             =*)
1007                 if [ -f $KERNEL_MODS/modules.${_mod#=} ]; then
1008                     ( [[ "$_mpargs" ]] && echo $_mpargs
1009                       cat "${KERNEL_MODS}/modules.${_mod#=}" ) \
1010                     | instmods
1011                 else
1012                     ( [[ "$_mpargs" ]] && echo $_mpargs
1013                       find "$KERNEL_MODS" -path "*/${_mod#=}/*" -printf '%f\n' ) \
1014                     | instmods
1015                 fi
1016                 ;;
1017             --*) _mpargs+=" $_mod" ;;
1018             i2o_scsi) return ;; # Do not load this diagnostic-only module
1019             *)
1020                 _mod=${_mod##*/}
1021                 # if we are already installed, skip this module and go on
1022                 # to the next one.
1023                 [[ -f "$initdir/.kernelmodseen/${_mod%.ko}.ko" ]] && return
1024
1025                 if [[ $omit_drivers ]] && [[ "$1" =~ $omit_drivers ]]; then
1026                     dinfo "Omitting driver ${_mod##$KERNEL_MODS}"
1027                     return
1028                 fi
1029                 # If we are building a host-specific initramfs and this
1030                 # module is not already loaded, move on to the next one.
1031                 [[ $hostonly ]] && ! grep -qe "\<${_mod//-/_}\>" /proc/modules \
1032                     && ! echo $add_drivers | grep -qe "\<${_mod}\>" \
1033                     && return
1034
1035                 # We use '-d' option in modprobe only if modules prefix path
1036                 # differs from default '/'.  This allows us to use Dracut with
1037                 # old version of modprobe which doesn't have '-d' option.
1038                 local _moddirname=${KERNEL_MODS%%/lib/modules/*}
1039                 [[ -n ${_moddirname} ]] && _moddirname="-d ${_moddirname}/"
1040
1041                 # ok, load the module, all its dependencies, and any firmware
1042                 # it may require
1043                 for_each_kmod_dep install_kmod_with_fw $_mod \
1044                     --set-version $KERNEL_VER ${_moddirname} $_mpargs
1045                 ((_ret+=$?))
1046                 ;;
1047         esac
1048         return $_ret
1049     }
1050
1051     function instmods_1() {
1052         local _mod _mpargs
1053         if (($# == 0)); then  # filenames from stdin
1054             while read _mod; do
1055                 inst1mod "${_mod%.ko*}" || {
1056                     if [ "$_check" = "yes" ]; then
1057                         dfatal "Failed to install $_mod"
1058                         return 1
1059                     fi
1060                 }
1061             done
1062         fi
1063         while (($# > 0)); do  # filenames as arguments
1064             inst1mod ${1%.ko*} || {
1065                 if [ "$_check" = "yes" ]; then
1066                     dfatal "Failed to install $1"
1067                     return 1
1068                 fi
1069             }
1070             shift
1071         done
1072         return 0
1073     }
1074
1075     local _ret _filter_not_found='FATAL: Module .* not found.'
1076     set -o pipefail
1077     # Capture all stderr from modprobe to _fderr. We could use {var}>...
1078     # redirections, but that would make dracut require bash4 at least.
1079     eval "( instmods_1 \"\$@\" ) ${_fderr}>&1" \
1080     | while read line; do [[ "$line" =~ $_filter_not_found ]] && echo $line || echo $line >&2 ;done | derror
1081     _ret=$?
1082     set +o pipefail
1083     return $_ret
1084 }
1085
1086 # inst_libdir_file [-n <pattern>] <file> [<file>...]
1087 # Install a <file> located on a lib directory to the initramfs image
1088 # -n <pattern> install non-matching files
1089 inst_libdir_file() {
1090     if [[ "$1" == "-n" ]]; then
1091         local _pattern=$1
1092         shift 2
1093         for _dir in $libdirs; do
1094             for _i in "$@"; do
1095                 for _f in "$_dir"/$_i; do
1096                     [[ "$_i" =~ $_pattern ]] || continue
1097                     [[ -e "$_i" ]] && dracut_install "$_i"
1098                 done
1099             done
1100         done
1101     else
1102         for _dir in $libdirs; do
1103             for _i in "$@"; do
1104                 for _f in "$_dir"/$_i; do
1105                     [[ -e "$_f" ]] && dracut_install "$_f"
1106                 done
1107             done
1108         done
1109     fi
1110 }
1111
1112 check_nspawn() {
1113     [[ -d /sys/fs/cgroup/systemd ]]
1114 }
1115
1116
1117 do_test() {
1118     if [[ $UID != "0" ]]; then
1119         echo "TEST: $TEST_DESCRIPTION [SKIPPED]: not root" >&2
1120         exit 0
1121     fi
1122
1123 # Detect lib paths
1124     [[ $libdir ]] || for libdir in /lib64 /lib; do
1125         [[ -d $libdir ]] && libdirs+=" $libdir" && break
1126     done
1127
1128     [[ $usrlibdir ]] || for usrlibdir in /usr/lib64 /usr/lib; do
1129         [[ -d $usrlibdir ]] && libdirs+=" $usrlibdir" && break
1130     done
1131
1132     import_testdir
1133     import_initdir
1134
1135     while (($# > 0)); do
1136         case $1 in
1137             --run)
1138                 echo "TEST RUN: $TEST_DESCRIPTION"
1139                 test_run
1140                 ret=$?
1141                 if [ $ret -eq 0 ]; then
1142                     echo "TEST RUN: $TEST_DESCRIPTION [OK]"
1143                 else
1144                     echo "TEST RUN: $TEST_DESCRIPTION [FAILED]"
1145                 fi
1146                 exit $ret;;
1147             --setup)
1148                 echo "TEST SETUP: $TEST_DESCRIPTION"
1149                 test_setup
1150                 exit $?;;
1151             --clean)
1152                 echo "TEST CLEANUP: $TEST_DESCRIPTION"
1153                 test_cleanup
1154                 rm -fr "$TESTDIR"
1155                 rm -f .testdir
1156                 exit $?;;
1157             --all)
1158                 echo -n "TEST: $TEST_DESCRIPTION ";
1159                 (
1160                     test_setup && test_run
1161                     ret=$?
1162                     test_cleanup
1163                     rm -fr "$TESTDIR"
1164                     rm -f .testdir
1165                     exit $ret
1166                 ) </dev/null >test.log 2>&1
1167                 ret=$?
1168                 if [ $ret -eq 0 ]; then
1169                     rm test.log
1170                     echo "[OK]"
1171                 else
1172                     echo "[FAILED]"
1173                     echo "see $(pwd)/test.log"
1174                 fi
1175                 exit $ret;;
1176             *) break ;;
1177         esac
1178         shift
1179     done
1180 }