]> git.ipfire.org Git - thirdparty/dracut.git/blob - dracut-functions.sh
dracut-functions.sh: replace strstr()
[thirdparty/dracut.git] / dracut-functions.sh
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 #
5 # functions used by dracut and other tools.
6 #
7 # Copyright 2005-2009 Red Hat, Inc. All rights reserved.
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 # Generic substring function. If $2 is in $1, return 0.
24 strstr() { [[ $1 = *$2* ]]; }
25
26 if ! [[ $dracutbasedir ]]; then
27 dracutbasedir=${BASH_SOURCE[0]%/*}
28 [[ $dracutbasedir = "dracut-functions" ]] && dracutbasedir="."
29 [[ $dracutbasedir ]] || dracutbasedir="."
30 dracutbasedir="$(readlink -f $dracutbasedir)"
31 fi
32
33 # Detect lib paths
34 if ! [[ $libdirs ]] ; then
35 if strstr "$(ldd /bin/sh)" "/lib64/" &>/dev/null \
36 && [[ -d /lib64 ]]; then
37 libdirs+=" /lib64"
38 [[ -d /usr/lib64 ]] && libdirs+=" /usr/lib64"
39 else
40 libdirs+=" /lib"
41 [[ -d /usr/lib ]] && libdirs+=" /usr/lib"
42 fi
43 export libdirs
44 fi
45
46 if ! [[ $kernel ]]; then
47 kernel=$(uname -r)
48 export kernel
49 fi
50
51 srcmods="/lib/modules/$kernel/"
52 [[ $drivers_dir ]] && {
53 if vercmp $(modprobe --version | cut -d' ' -f3) lt 3.7; then
54 dfatal 'To use --kmoddir option module-init-tools >= 3.7 is required.'
55 exit 1
56 fi
57 srcmods="$drivers_dir"
58 }
59 export srcmods
60
61 if ! type dinfo >/dev/null 2>&1; then
62 . "$dracutbasedir/dracut-logger.sh"
63 dlog_init
64 fi
65
66 # export standard hookdirs
67 [[ $hookdirs ]] || {
68 hookdirs="cmdline pre-udev pre-trigger netroot "
69 hookdirs+="initqueue initqueue/settled initqueue/online initqueue/finished initqueue/timeout "
70 hookdirs+="pre-mount pre-pivot cleanup mount "
71 hookdirs+="emergency shutdown-emergency shutdown "
72 export hookdirs
73 }
74
75 # Create all subdirectories for given path without creating the last element.
76 # $1 = path
77 mksubdirs() { mkdir -m 0755 -p ${1%/*}; }
78
79 # Version comparision function. Assumes Linux style version scheme.
80 # $1 = version a
81 # $2 = comparision op (gt, ge, eq, le, lt, ne)
82 # $3 = version b
83 vercmp() {
84 local _n1=(${1//./ }) _op=$2 _n2=(${3//./ }) _i _res
85
86 for ((_i=0; ; _i++))
87 do
88 if [[ ! ${_n1[_i]}${_n2[_i]} ]]; then _res=0
89 elif ((${_n1[_i]:-0} > ${_n2[_i]:-0})); then _res=1
90 elif ((${_n1[_i]:-0} < ${_n2[_i]:-0})); then _res=2
91 else continue
92 fi
93 break
94 done
95
96 case $_op in
97 gt) ((_res == 1));;
98 ge) ((_res != 2));;
99 eq) ((_res == 0));;
100 le) ((_res != 1));;
101 lt) ((_res == 2));;
102 ne) ((_res != 0));;
103 esac
104 }
105
106 # is_func <command>
107 # Check whether $1 is a function.
108 is_func() {
109 [[ $(type -t $1) = "function" ]]
110 }
111
112 # Function prints global variables in format name=value line by line.
113 # $@ = list of global variables' name
114 print_vars() {
115 local _var _value
116
117 for _var in $@
118 do
119 _value=$(eval echo \$$_var)
120 [[ ${_value} ]] && echo "${_var}=\"${_value}\""
121 done
122 }
123
124 # normalize_path <path>
125 # Prints the normalized path, where it removes any duplicated
126 # and trailing slashes.
127 # Example:
128 # $ normalize_path ///test/test//
129 # /test/test
130 normalize_path() {
131 shopt -q -s extglob
132 set -- "${1//+(\/)//}"
133 shopt -q -u extglob
134 echo "${1%/}"
135 }
136
137 # convert_abs_rel <from> <to>
138 # Prints the relative path, when creating a symlink to <to> from <from>.
139 # Example:
140 # $ convert_abs_rel /usr/bin/test /bin/test-2
141 # ../../bin/test-2
142 # $ ln -s $(convert_abs_rel /usr/bin/test /bin/test-2) /usr/bin/test
143 convert_abs_rel() {
144 local __current __absolute __abssize __cursize __newpath
145 local -i __i __level
146
147 set -- "$(normalize_path "$1")" "$(normalize_path "$2")"
148
149 # corner case #1 - self looping link
150 [[ "$1" == "$2" ]] && { echo "${1##*/}"; return; }
151
152 # corner case #2 - own dir link
153 [[ "${1%/*}" == "$2" ]] && { echo "."; return; }
154
155 IFS="/" __current=($1)
156 IFS="/" __absolute=($2)
157
158 __abssize=${#__absolute[@]}
159 __cursize=${#__current[@]}
160
161 while [[ ${__absolute[__level]} == ${__current[__level]} ]]
162 do
163 (( __level++ ))
164 if (( __level > __abssize || __level > __cursize ))
165 then
166 break
167 fi
168 done
169
170 for ((__i = __level; __i < __cursize-1; __i++))
171 do
172 if ((__i > __level))
173 then
174 __newpath=$__newpath"/"
175 fi
176 __newpath=$__newpath".."
177 done
178
179 for ((__i = __level; __i < __abssize; __i++))
180 do
181 if [[ -n $__newpath ]]
182 then
183 __newpath=$__newpath"/"
184 fi
185 __newpath=$__newpath${__absolute[__i]}
186 done
187
188 echo "$__newpath"
189 }
190
191 if strstr "$(ln --help)" "relative"; then
192 ln_r() {
193 ln -sfnr "${initdir}/$1" "${initdir}/$2"
194 }
195 else
196 ln_r() {
197 local _source=$1
198 local _dest=$2
199 [[ -d "${_dest%/*}" ]] && _dest=$(readlink -f "${_dest%/*}")/${_dest##*/}
200 ln -sfn $(convert_abs_rel "${_dest}" "${_source}") "${initdir}/${_dest}"
201 }
202 fi
203
204 # get_fs_env <device>
205 # Get and set the ID_FS_TYPE and ID_FS_UUID variable from udev for a device.
206 # Example:
207 # $ get_fs_env /dev/sda2; echo $ID_FS_TYPE; echo $ID_FS_UUID
208 # ext4
209 # 551a39aa-4ae9-4e70-a262-ef665cadb574
210 get_fs_env() {
211 local evalstr
212 local found
213
214 [[ $1 ]] || return
215 unset ID_FS_TYPE
216 unset ID_FS_UUID
217 if evalstr=$(udevadm info --query=env --name=$1 \
218 | { while read line; do
219 strstr "$line" "DEVPATH" && found=1;
220 strstr "$line" "ID_FS_TYPE=" && { echo $line; exit 0;}
221 done; [[ $found ]] && exit 0; exit 1; }) ; then
222 eval $evalstr
223 [[ $ID_FS_TYPE ]] && return 0
224 return 1
225 fi
226
227 # Fallback, if we don't have udev information
228 if find_binary blkid >/dev/null; then
229 eval $(blkid -o udev $1 \
230 | while read line; do
231 strstr "$line" "ID_FS_TYPE=" && echo $line;
232 done)
233 [[ $ID_FS_TYPE ]] && return 0
234 fi
235 return 1
236 }
237
238 # get_maj_min <device>
239 # Prints the major and minor of a device node.
240 # Example:
241 # $ get_maj_min /dev/sda2
242 # 8:2
243 get_maj_min() {
244 local _dev
245 _dev=$(stat -L -c '$((0x%t)):$((0x%T))' "$1" 2>/dev/null)
246 _dev=$(eval "echo $_dev")
247 echo $_dev
248 }
249
250 # find_block_device <mountpoint>
251 # Prints the major and minor number of the block device
252 # for a given mountpoint.
253 # Unless $use_fstab is set to "yes" the functions
254 # uses /proc/self/mountinfo as the primary source of the
255 # information and only falls back to /etc/fstab, if the mountpoint
256 # is not found there.
257 # Example:
258 # $ find_block_device /usr
259 # 8:4
260 find_block_device() {
261 local _x _mpt _majmin _dev _fs _maj _min
262 if [[ $use_fstab != yes ]]; then
263 while read _x _x _majmin _x _mpt _x _x _fs _dev _x; do
264 [[ $_mpt = $1 ]] || continue
265 [[ $_fs = nfs ]] && { echo $_dev; return 0;}
266 [[ $_fs = nfs3 ]] && { echo $_dev; return 0;}
267 [[ $_fs = nfs4 ]] && { echo $_dev; return 0;}
268 [[ $_fs = btrfs ]] && {
269 get_maj_min $_dev
270 return 0;
271 }
272 if [[ ${_majmin#0:} = $_majmin ]]; then
273 echo $_majmin
274 return 0 # we have a winner!
275 fi
276 done < /proc/self/mountinfo
277 fi
278 # fall back to /etc/fstab
279 while read _dev _mpt _fs _x; do
280 [ "${_dev%%#*}" != "$_dev" ] && continue
281
282 if [[ $_mpt = $1 ]]; then
283 [[ $_fs = nfs ]] && { echo $_dev; return 0;}
284 [[ $_fs = nfs3 ]] && { echo $_dev; return 0;}
285 [[ $_fs = nfs4 ]] && { echo $_dev; return 0;}
286 [[ $_dev != ${_dev#UUID=} ]] && _dev=/dev/disk/by-uuid/${_dev#UUID=}
287 [[ $_dev != ${_dev#LABEL=} ]] && _dev=/dev/disk/by-label/${_dev#LABEL=}
288 [[ -b $_dev ]] || return 1 # oops, not a block device.
289 get_maj_min "$_dev" && return 0
290 fi
291 done < /etc/fstab
292
293 return 1
294 }
295
296 # find_dev_fstype <device>
297 # Echo the filesystem type for a given device.
298 # /proc/self/mountinfo is taken as the primary source of information
299 # and /etc/fstab is used as a fallback.
300 # No newline is appended!
301 # Example:
302 # $ find_dev_fstype /dev/sda2;echo
303 # ext4
304 find_dev_fstype() {
305 local _x _mpt _majmin _dev _fs _maj _min
306 while read _x _x _majmin _x _mpt _x _x _fs _dev _x; do
307 [[ $_dev = $1 ]] || continue
308 echo -n $_fs;
309 return 0;
310 done < /proc/self/mountinfo
311
312 # fall back to /etc/fstab
313 while read _dev _mpt _fs _x; do
314 [[ $_dev = $1 ]] || continue
315 echo -n $_fs;
316 return 0;
317 done < /etc/fstab
318
319 return 1
320 }
321
322 # finds the major:minor of the block device backing the root filesystem.
323 find_root_block_device() { find_block_device /; }
324
325 # for_each_host_dev_fs <func>
326 # Execute "<func> <dev> <filesystem>" for every "<dev>|<fs>" pair found
327 # in ${host_fs_types[@]}
328 for_each_host_dev_fs()
329 {
330 local _func="$1"
331 local _dev
332 local _fs
333 local _ret=1
334 for f in ${host_fs_types[@]}; do
335 OLDIFS="$IFS"
336 IFS="|"
337 set -- $f
338 IFS="$OLDIFS"
339 _dev="$1"
340 [[ -b "$_dev" ]] || continue
341 _fs="$2"
342 $_func $_dev $_fs && _ret=0
343 done
344 return $_ret
345 }
346
347 # Walk all the slave relationships for a given block device.
348 # Stop when our helper function returns success
349 # $1 = function to call on every found block device
350 # $2 = block device in major:minor format
351 check_block_and_slaves() {
352 local _x
353 [[ -b /dev/block/$2 ]] || return 1 # Not a block device? So sorry.
354 "$1" $2 && return
355 check_vol_slaves "$@" && return 0
356 if [[ -f /sys/dev/block/$2/../dev ]]; then
357 check_block_and_slaves $1 $(cat "/sys/dev/block/$2/../dev") && return 0
358 fi
359 [[ -d /sys/dev/block/$2/slaves ]] || return 1
360 for _x in /sys/dev/block/$2/slaves/*/dev; do
361 [[ -f $_x ]] || continue
362 check_block_and_slaves $1 $(cat "$_x") && return 0
363 done
364 return 1
365 }
366
367 # ugly workaround for the lvm design
368 # There is no volume group device,
369 # so, there are no slave devices for volume groups.
370 # Logical volumes only have the slave devices they really live on,
371 # but you cannot create the logical volume without the volume group.
372 # And the volume group might be bigger than the devices the LV needs.
373 check_vol_slaves() {
374 local _lv _vg _pv
375 for i in /dev/mapper/*; do
376 _lv=$(get_maj_min $i)
377 if [[ $_lv = $2 ]]; then
378 _vg=$(lvm lvs --noheadings -o vg_name $i 2>/dev/null)
379 # strip space
380 _vg=$(echo $_vg)
381 if [[ $_vg ]]; then
382 for _pv in $(lvm vgs --noheadings -o pv_name "$_vg" 2>/dev/null)
383 do
384 check_block_and_slaves $1 $(get_maj_min $_pv) && return 0
385 done
386 fi
387 fi
388 done
389 return 1
390 }
391
392 # Install a directory, keeping symlinks as on the original system.
393 # Example: if /lib points to /lib64 on the host, "inst_dir /lib/file"
394 # will create ${initdir}/lib64, ${initdir}/lib64/file,
395 # and a symlink ${initdir}/lib -> lib64.
396 inst_dir() {
397 [[ -e ${initdir}/"$1" ]] && return 0 # already there
398
399 local _dir="$1" _part="${1%/*}" _file
400 while [[ "$_part" != "${_part%/*}" ]] && ! [[ -e "${initdir}/${_part}" ]]; do
401 _dir="$_part $_dir"
402 _part=${_part%/*}
403 done
404
405 # iterate over parent directories
406 for _file in $_dir; do
407 [[ -e "${initdir}/$_file" ]] && continue
408 if [[ -L $_file ]]; then
409 inst_symlink "$_file"
410 else
411 # create directory
412 mkdir -m 0755 -p "${initdir}/$_file" || return 1
413 [[ -e "$_file" ]] && chmod --reference="$_file" "${initdir}/$_file"
414 chmod u+w "${initdir}/$_file"
415 fi
416 done
417 }
418
419 # $1 = file to copy to ramdisk
420 # $2 (optional) Name for the file on the ramdisk
421 # Location of the image dir is assumed to be $initdir
422 # We never overwrite the target if it exists.
423 inst_simple() {
424 [[ -f "$1" ]] || return 1
425 strstr "$1" "/" || return 1
426
427 local _src=$1 target="${2:-$1}"
428 if ! [[ -d ${initdir}/$target ]]; then
429 [[ -e ${initdir}/$target ]] && return 0
430 [[ -L ${initdir}/$target ]] && return 0
431 [[ -d "${initdir}/${target%/*}" ]] || inst_dir "${target%/*}"
432 fi
433 # install checksum files also
434 if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
435 inst "${_src%/*}/.${_src##*/}.hmac" "${target%/*}/.${target##*/}.hmac"
436 fi
437 ddebug "Installing $_src"
438 cp --sparse=always -pfL "$_src" "${initdir}/$target"
439 }
440
441 # find symlinks linked to given library file
442 # $1 = library file
443 # Function searches for symlinks by stripping version numbers appended to
444 # library filename, checks if it points to the same target and finally
445 # prints the list of symlinks to stdout.
446 #
447 # Example:
448 # rev_lib_symlinks libfoo.so.8.1
449 # output: libfoo.so.8 libfoo.so
450 # (Only if libfoo.so.8 and libfoo.so exists on host system.)
451 rev_lib_symlinks() {
452 [[ ! $1 ]] && return 0
453
454 local fn="$1" orig="$(readlink -f "$1")" links=''
455
456 [[ ${fn} =~ .*\.so\..* ]] || return 1
457
458 until [[ ${fn##*.} == so ]]; do
459 fn="${fn%.*}"
460 [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
461 done
462
463 echo "${links}"
464 }
465
466 # Same as above, but specialized to handle dynamic libraries.
467 # It handles making symlinks according to how the original library
468 # is referenced.
469 inst_library() {
470 local _src="$1" _dest=${2:-$1} _lib _reallib _symlink
471 strstr "$1" "/" || return 1
472 [[ -e $initdir/$_dest ]] && return 0
473 if [[ -L $_src ]]; then
474 # install checksum files also
475 if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
476 inst "${_src%/*}/.${_src##*/}.hmac" "${_dest%/*}/.${_dest##*/}.hmac"
477 fi
478 _reallib=$(readlink -f "$_src")
479 inst_simple "$_reallib" "$_reallib"
480 inst_dir "${_dest%/*}"
481 ln_r "${_reallib}" "${_dest}"
482 else
483 inst_simple "$_src" "$_dest"
484 fi
485
486 # Create additional symlinks. See rev_symlinks description.
487 for _symlink in $(rev_lib_symlinks $_src) $(rev_lib_symlinks $_reallib); do
488 [[ ! -e $initdir/$_symlink ]] && {
489 ddebug "Creating extra symlink: $_symlink"
490 inst_symlink $_symlink
491 }
492 done
493 }
494
495 # find a binary. If we were not passed the full path directly,
496 # search in the usual places to find the binary.
497 find_binary() {
498 if [[ -z ${1##/*} ]]; then
499 if [[ -x $1 ]] || { strstr "$1" ".so" && ldd $1 &>/dev/null; }; then
500 echo $1
501 return 0
502 fi
503 fi
504
505 type -P $1
506 }
507
508 # Same as above, but specialized to install binary executables.
509 # Install binary executable, and all shared library dependencies, if any.
510 inst_binary() {
511 local _bin _target
512 _bin=$(find_binary "$1") || return 1
513 _target=${2:-$_bin}
514 [[ -e $initdir/$_target ]] && return 0
515 [[ -L $_bin ]] && inst_symlink $_bin $_target && return 0
516 local _file _line
517 local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
518 # I love bash!
519 LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
520 [[ $_line = 'not a dynamic executable' ]] && break
521
522 if [[ $_line =~ $_so_regex ]]; then
523 _file=${BASH_REMATCH[1]}
524 [[ -e ${initdir}/$_file ]] && continue
525 inst_library "$_file"
526 continue
527 fi
528
529 if [[ $_line =~ not\ found ]]; then
530 dfatal "Missing a shared library required by $_bin."
531 dfatal "Run \"ldd $_bin\" to find out what it is."
532 dfatal "$_line"
533 dfatal "dracut cannot create an initrd."
534 exit 1
535 fi
536 done
537 inst_simple "$_bin" "$_target"
538 }
539
540 # same as above, except for shell scripts.
541 # If your shell script does not start with shebang, it is not a shell script.
542 inst_script() {
543 local _bin
544 _bin=$(find_binary "$1") || return 1
545 shift
546 local _line _shebang_regex
547 read -r -n 80 _line <"$_bin"
548 # If debug is set, clean unprintable chars to prevent messing up the term
549 [[ $debug ]] && _line=$(echo -n "$_line" | tr -c -d '[:print:][:space:]')
550 _shebang_regex='(#! *)(/[^ ]+).*'
551 [[ $_line =~ $_shebang_regex ]] || return 1
552 inst "${BASH_REMATCH[2]}" && inst_simple "$_bin" "$@"
553 }
554
555 # same as above, but specialized for symlinks
556 inst_symlink() {
557 local _src=$1 _target=${2:-$1} _realsrc
558 strstr "$1" "/" || return 1
559 [[ -L $1 ]] || return 1
560 [[ -L $initdir/$_target ]] && return 0
561 _realsrc=$(readlink -f "$_src")
562 if ! [[ -e $initdir/$_realsrc ]]; then
563 if [[ -d $_realsrc ]]; then
564 inst_dir "$_realsrc"
565 else
566 inst "$_realsrc"
567 fi
568 fi
569 [[ ! -e $initdir/${_target%/*} ]] && inst_dir "${_target%/*}"
570
571 ln_r "${_realsrc}" "${_target}"
572 }
573
574 # attempt to install any programs specified in a udev rule
575 inst_rule_programs() {
576 local _prog _bin
577
578 if grep -qE 'PROGRAM==?"[^ "]+' "$1"; then
579 for _prog in $(grep -E 'PROGRAM==?"[^ "]+' "$1" | sed -r 's/.*PROGRAM==?"([^ "]+).*/\1/'); do
580 if [ -x ${udevdir}/$_prog ]; then
581 _bin=${udevdir}/$_prog
582 else
583 _bin=$(find_binary "$_prog") || {
584 dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
585 continue;
586 }
587 fi
588
589 #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
590 dracut_install "$_bin"
591 done
592 fi
593 if grep -qE 'RUN==?"[^ "]+' "$1"; then
594 for _prog in $(grep -E 'RUN==?"[^ "]+' "$1" | sed -r 's/.*RUN==?"([^ "]+).*/\1/'); do
595 if [ -x ${udevdir}/$_prog ]; then
596 _bin=${udevdir}/$_prog
597 else
598 _bin=$(find_binary "$_prog") || {
599 dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
600 continue;
601 }
602 fi
603
604 #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
605 dracut_install "$_bin"
606 done
607 fi
608 if grep -qE 'PROGRAM==?"[^ "]+' "$1"; then
609 for _prog in $(grep -E 'IMPORT==?"[^ "]+' "$1" | sed -r 's/.*IMPORT==?"([^ "]+).*/\1/'); do
610 if [ -x ${udevdir}/$_prog ]; then
611 _bin=${udevdir}/$_prog
612 else
613 _bin=$(find_binary "$_prog") || {
614 dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
615 continue;
616 }
617 fi
618
619 #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
620 dracut_install "$_bin"
621 done
622 fi
623 }
624
625 # udev rules always get installed in the same place, so
626 # create a function to install them to make life simpler.
627 inst_rules() {
628 local _target=/etc/udev/rules.d _rule _found
629
630 inst_dir "${udevdir}/rules.d"
631 inst_dir "$_target"
632 for _rule in "$@"; do
633 if [ "${rule#/}" = "$rule" ]; then
634 for r in ${udevdir}/rules.d /etc/udev/rules.d; do
635 if [[ -f $r/$_rule ]]; then
636 _found="$r/$_rule"
637 inst_rule_programs "$_found"
638 inst_simple "$_found"
639 fi
640 done
641 fi
642 for r in '' ./ $dracutbasedir/rules.d/; do
643 if [[ -f ${r}$_rule ]]; then
644 _found="${r}$_rule"
645 inst_rule_programs "$_found"
646 inst_simple "$_found" "$_target/${_found##*/}"
647 fi
648 done
649 [[ $_found ]] || dinfo "Skipping udev rule: $_rule"
650 done
651 }
652
653 # general purpose installation function
654 # Same args as above.
655 inst() {
656 local _x
657
658 case $# in
659 1) ;;
660 2) [[ ! $initdir && -d $2 ]] && export initdir=$2
661 [[ $initdir = $2 ]] && set $1;;
662 3) [[ -z $initdir ]] && export initdir=$2
663 set $1 $3;;
664 *) dfatal "inst only takes 1 or 2 or 3 arguments"
665 exit 1;;
666 esac
667 for _x in inst_symlink inst_script inst_binary inst_simple; do
668 $_x "$@" && return 0
669 done
670 return 1
671 }
672
673 # install function specialized for hooks
674 # $1 = type of hook, $2 = hook priority (lower runs first), $3 = hook
675 # All hooks should be POSIX/SuS compliant, they will be sourced by init.
676 inst_hook() {
677 if ! [[ -f $3 ]]; then
678 dfatal "Cannot install a hook ($3) that does not exist."
679 dfatal "Aborting initrd creation."
680 exit 1
681 elif ! strstr "$hookdirs" "$1"; then
682 dfatal "No such hook type $1. Aborting initrd creation."
683 exit 1
684 fi
685 inst_simple "$3" "/lib/dracut/hooks/${1}/${2}${3##*/}"
686 }
687
688 # install any of listed files
689 #
690 # If first argument is '-d' and second some destination path, first accessible
691 # source is installed into this path, otherwise it will installed in the same
692 # path as source. If none of listed files was installed, function return 1.
693 # On first successful installation it returns with 0 status.
694 #
695 # Example:
696 #
697 # inst_any -d /bin/foo /bin/bar /bin/baz
698 #
699 # Lets assume that /bin/baz exists, so it will be installed as /bin/foo in
700 # initramfs.
701 inst_any() {
702 local to f
703
704 [[ $1 = '-d' ]] && to="$2" && shift 2
705
706 for f in "$@"; do
707 if [[ -e $f ]]; then
708 [[ $to ]] && inst "$f" "$to" && return 0
709 inst "$f" && return 0
710 fi
711 done
712
713 return 1
714 }
715
716 # dracut_install [-o ] <file> [<file> ... ]
717 # Install <file> to the initramfs image
718 # -o optionally install the <file> and don't fail, if it is not there
719 dracut_install() {
720 local _optional=no
721 if [[ $1 = '-o' ]]; then
722 _optional=yes
723 shift
724 fi
725 while (($# > 0)); do
726 if ! inst "$1" ; then
727 if [[ $_optional = yes ]]; then
728 dinfo "Skipping program $1 as it cannot be found and is" \
729 "flagged to be optional"
730 else
731 dfatal "Failed to install $1"
732 exit 1
733 fi
734 fi
735 shift
736 done
737 }
738
739
740 # inst_libdir_file [-n <pattern>] <file> [<file>...]
741 # Install a <file> located on a lib directory to the initramfs image
742 # -n <pattern> install matching files
743 inst_libdir_file() {
744 if [[ "$1" == "-n" ]]; then
745 local _pattern=$2
746 shift 2
747 for _dir in $libdirs; do
748 for _i in "$@"; do
749 for _f in "$_dir"/$_i; do
750 [[ "$_f" =~ $_pattern ]] || continue
751 [[ -e "$_f" ]] && dracut_install "$_f"
752 done
753 done
754 done
755 else
756 for _dir in $libdirs; do
757 for _i in "$@"; do
758 for _f in "$_dir"/$_i; do
759 [[ -e "$_f" ]] && dracut_install "$_f"
760 done
761 done
762 done
763 fi
764 }
765
766
767 # install function decompressing the target and handling symlinks
768 # $@ = list of compressed (gz or bz2) files or symlinks pointing to such files
769 #
770 # Function install targets in the same paths inside overlay but decompressed
771 # and without extensions (.gz, .bz2).
772 inst_decompress() {
773 local _src _dst _realsrc _realdst _cmd
774
775 for _src in $@
776 do
777 case ${_src} in
778 *.gz) _cmd='gzip -d' ;;
779 *.bz2) _cmd='bzip2 -d' ;;
780 *) return 1 ;;
781 esac
782
783 if [[ -L ${_src} ]]
784 then
785 _realsrc="$(readlink -f ${_src})" # symlink target with extension
786 _dst="${_src%.*}" # symlink without extension
787 _realdst="${_realsrc%.*}" # symlink target without extension
788 mksubdirs "${initdir}/${_src}"
789 # Create symlink without extension to target without extension.
790 ln -sfn "${_realdst}" "${initdir}/${_dst}"
791 fi
792
793 # If the source is symlink we operate on its target.
794 [[ ${_realsrc} ]] && _src=${_realsrc}
795 inst ${_src}
796 # Decompress with chosen tool. We assume that tool changes name e.g.
797 # from 'name.gz' to 'name'.
798 ${_cmd} "${initdir}${_src}"
799 done
800 }
801
802 # It's similar to above, but if file is not compressed, performs standard
803 # install.
804 # $@ = list of files
805 inst_opt_decompress() {
806 local _src
807
808 for _src in $@
809 do
810 inst_decompress "${_src}" || inst "${_src}"
811 done
812 }
813
814 # module_check <dracut module>
815 # execute the check() function of module-setup.sh of <dracut module>
816 # or the "check" script, if module-setup.sh is not found
817 # "check $hostonly" is called
818 module_check() {
819 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
820 local _ret
821 local _forced=0
822 local _hostonly=$hostonly
823 [ $# -eq 2 ] && _forced=$2
824 [[ -d $_moddir ]] || return 1
825 if [[ ! -f $_moddir/module-setup.sh ]]; then
826 # if we do not have a check script, we are unconditionally included
827 [[ -x $_moddir/check ]] || return 0
828 [ $_forced -ne 0 ] && unset hostonly
829 $_moddir/check $hostonly
830 _ret=$?
831 else
832 unset check depends install installkernel
833 . $_moddir/module-setup.sh
834 is_func check || return 0
835 [ $_forced -ne 0 ] && unset hostonly
836 check $hostonly
837 _ret=$?
838 unset check depends install installkernel
839 fi
840 hostonly=$_hostonly
841 return $_ret
842 }
843
844 # module_check_mount <dracut module>
845 # execute the check() function of module-setup.sh of <dracut module>
846 # or the "check" script, if module-setup.sh is not found
847 # "mount_needs=1 check 0" is called
848 module_check_mount() {
849 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
850 local _ret
851 mount_needs=1
852 [[ -d $_moddir ]] || return 1
853 if [[ ! -f $_moddir/module-setup.sh ]]; then
854 # if we do not have a check script, we are unconditionally included
855 [[ -x $_moddir/check ]] || return 0
856 mount_needs=1 $_moddir/check 0
857 _ret=$?
858 else
859 unset check depends install installkernel
860 . $_moddir/module-setup.sh
861 is_func check || return 1
862 check 0
863 _ret=$?
864 unset check depends install installkernel
865 fi
866 unset mount_needs
867 return $_ret
868 }
869
870 # module_depends <dracut module>
871 # execute the depends() function of module-setup.sh of <dracut module>
872 # or the "depends" script, if module-setup.sh is not found
873 module_depends() {
874 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
875 local _ret
876 [[ -d $_moddir ]] || return 1
877 if [[ ! -f $_moddir/module-setup.sh ]]; then
878 # if we do not have a check script, we have no deps
879 [[ -x $_moddir/check ]] || return 0
880 $_moddir/check -d
881 return $?
882 else
883 unset check depends install installkernel
884 . $_moddir/module-setup.sh
885 is_func depends || return 0
886 depends
887 _ret=$?
888 unset check depends install installkernel
889 return $_ret
890 fi
891 }
892
893 # module_install <dracut module>
894 # execute the install() function of module-setup.sh of <dracut module>
895 # or the "install" script, if module-setup.sh is not found
896 module_install() {
897 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
898 local _ret
899 [[ -d $_moddir ]] || return 1
900 if [[ ! -f $_moddir/module-setup.sh ]]; then
901 [[ -x $_moddir/install ]] && . "$_moddir/install"
902 return $?
903 else
904 unset check depends install installkernel
905 . $_moddir/module-setup.sh
906 is_func install || return 0
907 install
908 _ret=$?
909 unset check depends install installkernel
910 return $_ret
911 fi
912 }
913
914 # module_installkernel <dracut module>
915 # execute the installkernel() function of module-setup.sh of <dracut module>
916 # or the "installkernel" script, if module-setup.sh is not found
917 module_installkernel() {
918 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
919 local _ret
920 [[ -d $_moddir ]] || return 1
921 if [[ ! -f $_moddir/module-setup.sh ]]; then
922 [[ -x $_moddir/installkernel ]] && . "$_moddir/installkernel"
923 return $?
924 else
925 unset check depends install installkernel
926 . $_moddir/module-setup.sh
927 is_func installkernel || return 0
928 installkernel
929 _ret=$?
930 unset check depends install installkernel
931 return $_ret
932 fi
933 }
934
935 # check_mount <dracut module>
936 # check_mount checks, if a dracut module is needed for the given
937 # device and filesystem types in "${host_fs_types[@]}"
938 check_mount() {
939 local _mod=$1
940 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
941 local _ret
942 local _moddep
943 # If we are already scheduled to be loaded, no need to check again.
944 strstr " $mods_to_load " " $_mod " && return 0
945 strstr " $mods_checked_as_dep " " $_mod " && return 1
946
947 # This should never happen, but...
948 [[ -d $_moddir ]] || return 1
949
950 [[ $2 ]] || mods_checked_as_dep+=" $_mod "
951
952 strstr " $omit_dracutmodules " " $_mod " && return 1
953
954 if [ "${#host_fs_types[*]}" -gt 0 ]; then
955 module_check_mount $_mod || return 1
956 else
957 # skip this module
958 return 1
959 fi
960
961 for _moddep in $(module_depends $_mod); do
962 # handle deps as if they were manually added
963 strstr " $add_dracutmodules " " $_moddep " || \
964 add_dracutmodules+=" $_moddep "
965 strstr " $force_add_dracutmodules " " $_moddep " || \
966 force_add_dracutmodules+=" $_moddep "
967 # if a module we depend on fail, fail also
968 check_module $_moddep || return 1
969 done
970
971 strstr " $mods_to_load " " $_mod " || \
972 mods_to_load+=" $_mod "
973
974 return 0
975 }
976
977 # check_module <dracut module> [<use_as_dep>]
978 # check if a dracut module is to be used in the initramfs process
979 # if <use_as_dep> is set, then the process also keeps track
980 # that the modules were checked for the dependency tracking process
981 check_module() {
982 local _mod=$1
983 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
984 local _ret
985 local _moddep
986 # If we are already scheduled to be loaded, no need to check again.
987 strstr " $mods_to_load " " $_mod " && return 0
988 strstr " $mods_checked_as_dep " " $_mod " && return 1
989
990 # This should never happen, but...
991 [[ -d $_moddir ]] || return 1
992
993 [[ $2 ]] || mods_checked_as_dep+=" $_mod "
994
995 strstr " $omit_dracutmodules " " $_mod " && return 1
996
997 if strstr " $dracutmodules $add_dracutmodules $force_add_dracutmodules" " $_mod "; then
998 if strstr " $force_add_dracutmodules" " $_mod"; then
999 module_check $_mod 1; ret=$?
1000 else
1001 module_check $_mod 0; ret=$?
1002 fi
1003 # explicit module, so also accept ret=255
1004 [[ $ret = 0 || $ret = 255 ]] || return 1
1005 else
1006 # module not in our list
1007 if [[ $dracutmodules = all ]]; then
1008 # check, if we can and should install this module
1009 module_check $_mod || return 1
1010 else
1011 # skip this module
1012 return 1
1013 fi
1014 fi
1015
1016 for _moddep in $(module_depends $_mod); do
1017 # handle deps as if they were manually added
1018 strstr " $add_dracutmodules " " $_moddep " || \
1019 add_dracutmodules+=" $_moddep "
1020 strstr " $force_add_dracutmodules " " $_moddep " || \
1021 force_add_dracutmodules+=" $_moddep "
1022 # if a module we depend on fail, fail also
1023 check_module $_moddep || return 1
1024 done
1025
1026 strstr " $mods_to_load " " $_mod " || \
1027 mods_to_load+=" $_mod "
1028
1029 return 0
1030 }
1031
1032 # for_each_module_dir <func>
1033 # execute "<func> <dracut module> 1"
1034 for_each_module_dir() {
1035 local _modcheck
1036 local _mod
1037 local _moddir
1038 local _func
1039 _func=$1
1040 for _moddir in "$dracutbasedir/modules.d"/[0-9][0-9]*; do
1041 _mod=${_moddir##*/}; _mod=${_mod#[0-9][0-9]}
1042 $_func $_mod 1
1043 done
1044
1045 # Report any missing dracut modules, the user has specified
1046 _modcheck="$add_dracutmodules $force_add_dracutmodules"
1047 [[ $dracutmodules != all ]] && _modcheck="$m $dracutmodules"
1048 for _mod in $_modcheck; do
1049 strstr "$mods_to_load" "$_mod" && continue
1050 strstr "$omit_dracutmodules" "$_mod" && continue
1051 derror "Dracut module \"$_mod\" cannot be found."
1052 done
1053 }
1054
1055 # Install a single kernel module along with any firmware it may require.
1056 # $1 = full path to kernel module to install
1057 install_kmod_with_fw() {
1058 # no need to go further if the module is already installed
1059
1060 [[ -e "${initdir}/lib/modules/$kernel/${1##*/lib/modules/$kernel/}" ]] \
1061 && return 0
1062
1063 [[ -e "$initdir/.kernelmodseen/${1##*/}" ]] && return 0
1064
1065 if [[ $omit_drivers ]]; then
1066 local _kmod=${1##*/}
1067 _kmod=${_kmod%.ko}
1068 _kmod=${_kmod/-/_}
1069 if [[ "$_kmod" =~ $omit_drivers ]]; then
1070 dinfo "Omitting driver $_kmod"
1071 return 0
1072 fi
1073 if [[ "${1##*/lib/modules/$kernel/}" =~ $omit_drivers ]]; then
1074 dinfo "Omitting driver $_kmod"
1075 return 0
1076 fi
1077 fi
1078
1079 [ -d "$initdir/.kernelmodseen" ] && \
1080 > "$initdir/.kernelmodseen/${1##*/}"
1081
1082 inst_simple "$1" "/lib/modules/$kernel/${1##*/lib/modules/$kernel/}" \
1083 || return $?
1084
1085 local _modname=${1##*/} _fwdir _found _fw
1086 _modname=${_modname%.ko*}
1087 for _fw in $(modinfo -k $kernel -F firmware $1 2>/dev/null); do
1088 _found=''
1089 for _fwdir in $fw_dir; do
1090 if [[ -d $_fwdir && -f $_fwdir/$_fw ]]; then
1091 inst_simple "$_fwdir/$_fw" "/lib/firmware/$_fw"
1092 _found=yes
1093 fi
1094 done
1095 if [[ $_found != yes ]]; then
1096 if ! [[ -d $(echo /sys/module/${_modname//-/_}|{ read a b; echo $a; }) ]]; then
1097 dinfo "Possible missing firmware \"${_fw}\" for kernel module" \
1098 "\"${_modname}.ko\""
1099 else
1100 dwarn "Possible missing firmware \"${_fw}\" for kernel module" \
1101 "\"${_modname}.ko\""
1102 fi
1103 fi
1104 done
1105 return 0
1106 }
1107
1108 # Do something with all the dependencies of a kernel module.
1109 # Note that kernel modules depend on themselves using the technique we use
1110 # $1 = function to call for each dependency we find
1111 # It will be passed the full path to the found kernel module
1112 # $2 = module to get dependencies for
1113 # rest of args = arguments to modprobe
1114 # _fderr specifies FD passed from surrounding scope
1115 for_each_kmod_dep() {
1116 local _func=$1 _kmod=$2 _cmd _modpath _options
1117 shift 2
1118 modprobe "$@" --ignore-install --show-depends $_kmod 2>&${_fderr} | (
1119 while read _cmd _modpath _options; do
1120 [[ $_cmd = insmod ]] || continue
1121 $_func ${_modpath} || exit $?
1122 done
1123 )
1124 }
1125
1126
1127 find_kernel_modules_by_path () (
1128 if ! [[ $hostonly ]]; then
1129 while read a rest; do
1130 if [[ "${a##kernel}" != "$a" ]]; then
1131 [[ "${a##kernel/$1}" != "$a" ]] || continue
1132 fi
1133 echo $srcmods/${a%:}
1134 done < $srcmods/modules.dep
1135 else
1136 ( cd /sys/module; echo *; ) \
1137 | xargs modinfo -F filename -k $kernel 2>/dev/null
1138 fi
1139 )
1140
1141 find_kernel_modules () {
1142 find_kernel_modules_by_path drivers
1143 }
1144
1145 # instmods [-c] <kernel module> [<kernel module> ... ]
1146 # instmods [-c] <kernel subsystem>
1147 # install kernel modules along with all their dependencies.
1148 # <kernel subsystem> can be e.g. "=block" or "=drivers/usb/storage"
1149 instmods() {
1150 [[ $no_kernel = yes ]] && return
1151 # called [sub]functions inherit _fderr
1152 local _fderr=9
1153 local _check=no
1154 if [[ $1 = '-c' ]]; then
1155 _check=yes
1156 shift
1157 fi
1158
1159 function inst1mod() {
1160 local _ret=0 _mod="$1"
1161 case $_mod in
1162 =*)
1163 if [ -f $srcmods/modules.${_mod#=} ]; then
1164 ( [[ "$_mpargs" ]] && echo $_mpargs
1165 cat "${srcmods}/modules.${_mod#=}" ) \
1166 | instmods
1167 ((_ret+=$?))
1168 else
1169 ( [[ "$_mpargs" ]] && echo $_mpargs
1170 find "$srcmods" -type f -path "*/${_mod#=}/*" -printf '%f\n' ) \
1171 | instmods
1172 ((_ret+=$?))
1173 fi
1174 ;;
1175 --*) _mpargs+=" $_mod" ;;
1176 i2o_scsi) return 0;; # Do not load this diagnostic-only module
1177 *)
1178 _mod=${_mod##*/}
1179 # if we are already installed, skip this module and go on
1180 # to the next one.
1181 [[ -f "$initdir/.kernelmodseen/${_mod%.ko}.ko" ]] && return
1182
1183 if [[ $omit_drivers ]] && [[ "$1" =~ $omit_drivers ]]; then
1184 dinfo "Omitting driver ${_mod##$srcmods}"
1185 return 0
1186 fi
1187 # If we are building a host-specific initramfs and this
1188 # module is not already loaded, move on to the next one.
1189 [[ $hostonly ]] \
1190 && ! [[ -d $(echo /sys/module/${_mod//-/_}|{ read a b; echo $a; }) ]] \
1191 && ! [[ "$add_drivers" =~ " ${_mod} " ]] \
1192 && return 0
1193
1194 # We use '-d' option in modprobe only if modules prefix path
1195 # differs from default '/'. This allows us to use Dracut with
1196 # old version of modprobe which doesn't have '-d' option.
1197 local _moddirname=${srcmods%%/lib/modules/*}
1198 [[ -n ${_moddirname} ]] && _moddirname="-d ${_moddirname}/"
1199
1200 # ok, load the module, all its dependencies, and any firmware
1201 # it may require
1202 for_each_kmod_dep install_kmod_with_fw $_mod \
1203 --set-version $kernel ${_moddirname} $_mpargs
1204 ((_ret+=$?))
1205 ;;
1206 esac
1207 return $_ret
1208 }
1209
1210 function instmods_1() {
1211 local _mod _mpargs
1212 if (($# == 0)); then # filenames from stdin
1213 while read _mod; do
1214 inst1mod "${_mod%.ko*}" || {
1215 if [ "$_check" = "yes" ]; then
1216 dfatal "Failed to install $_mod"
1217 return 1
1218 fi
1219 }
1220 done
1221 fi
1222 while (($# > 0)); do # filenames as arguments
1223 inst1mod ${1%.ko*} || {
1224 if [ "$_check" = "yes" ]; then
1225 dfatal "Failed to install $1"
1226 return 1
1227 fi
1228 }
1229 shift
1230 done
1231 return 0
1232 }
1233
1234 local _ret _filter_not_found='FATAL: Module .* not found.'
1235 # Capture all stderr from modprobe to _fderr. We could use {var}>...
1236 # redirections, but that would make dracut require bash4 at least.
1237 eval "( instmods_1 \"\$@\" ) ${_fderr}>&1" \
1238 | while read line; do [[ "$line" =~ $_filter_not_found ]] || echo $line;done | derror
1239 _ret=$?
1240 return $_ret
1241 }