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