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