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