summaryrefslogtreecommitdiff
path: root/mkinitcpio
blob: b758f85aa5dcac42f597a964d1bb20c9d7866a6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-2.0-only
#
# mkinitcpio - modular tool for building an initramfs images
#

declare -r version=%VERSION%

shopt -s extglob
### globals within mkinitcpio, but not intended to be used by hooks

# needed files/directories
_f_functions=functions
_f_config=mkinitcpio.conf
_d_config=mkinitcpio.conf.d
_d_hooks="$PWD/hooks:/usr/lib/initcpio/hooks:/lib/initcpio/hooks"
_d_install="$PWD/install:/usr/lib/initcpio/install:/lib/initcpio/install"
_d_post="$PWD/post:/usr/lib/initcpio/post:/lib/initcpio/post"
_d_flag_hooks=
_d_flag_install=
_d_flag_post=
_d_firmware=({/usr,}/lib/firmware/updates {/usr,}/lib/firmware)
_d_presets=mkinitcpio.d

# options and runtime data
_optmoduleroot='' _optgenimg=''
_optcompress='' _opttargetdir=''
_optosrelease=''
_optuki='' _optmicrocode=() _optcmdline='' _optsplash='' _optkernelimage='' _optuefistub=''
_optshowautomods=0 _optsavetree=0 _optshowmods=0 _optremove=0 _optnocmdline=0
_optquiet=1 _optcolor=1 _optconfd=1
_optskiphooks=() _optaddhooks=() _hooks=() _optpreset=() _tmpfiles=() _generated=()
declare -A _runhooks _addedmodules _modpaths _autodetect_cache

# export a sane PATH
export PATH='/usr/bin'

# Sanitize environment further
# GREP_OPTIONS="--color=always" will break everything
# CDPATH can affect cd and pushd
# LIBMOUNT_* options can affect findmnt and other tools
unset GREP_OPTIONS CDPATH "${!LIBMOUNT_@}"

usage() {
    cat <<EOF
mkinitcpio $version
usage: ${0##*/} [options]

  Options:
   -A, --addhooks <hooks>       Add specified hooks, comma separated, to image
   -c, --config <config>        Use alternate config file. (default: /etc/mkinitcpio.conf)
   -g, --generate <path>        Generate cpio image and write to specified path
   -H, --hookhelp <hookname>    Display help for given hook and exit
   -h, --help                   Display this message and exit
   -k, --kernel <kernelver>     Use specified kernel version (default: $(uname -r))
   -L, --listhooks              List all available hooks
   -M, --automods               Display modules found via autodetection
   -n, --nocolor                Disable colorized output messages
   -p, --preset <file>          Build specified preset from /etc/mkinitcpio.d
   -P, --allpresets             Process all preset files in /etc/mkinitcpio.d
   -R, --remove                 Remove specified preset images
                                This option can only be used with either '-p|--presets' or '-P|--allpresets'
   -r, --moduleroot <dir>       Root directory for modules (default: /)
   -S, --skiphooks <hooks>      Skip specified hooks, comma-separated, during build
   -s, --save                   Save build directory. (default: no)
   -d, --generatedir <dir>      Write generated image into <dir>
   -t, --builddir <dir>         Use DIR as the temporary build directory
   -D, --hookdir <dir>          Specify where to look for hooks
   -U, --uki <path>             Build a unified kernel image
   -V, --version                Display version information and exit
   -v, --verbose                Verbose output (default: no)
   -z, --compress <program>     Use an alternate compressor on the image (cat, xz, lz4, zstd)

  Options for unified kernel image (-U, --uki):
   --cmdline <path>             Set kernel command line from file
                                (default: /etc/kernel/cmdline or /proc/cmdline)
   --microcode <path>           Location of microcode
   --osrelease <path>           Include os-release (default: /etc/os-release)
   --splash <path>              Include bitmap splash
   --kernelimage <path>         Kernel image
   --uefistub <path>            Location of UEFI stub loader

EOF
}

version() {
    cat <<EOF
mkinitcpio "$version"
EOF
}

# The function is called from the EXIT trap
# shellcheck disable=SC2317
cleanup() {
    local err="${1:-$?}"

    if (( ${#_tmpfiles[@]} )); then
        rm -f -- "${_tmpfiles[@]}"
    fi
    if [[ -n "$_d_workdir" ]]; then
        # when _optpreset is set, we're in the main loop, not a worker process
        if (( _optsavetree )) && [[ -z ${_optpreset[*]} ]]; then
            printf '%s\n' "${!_autodetect_cache[@]}" >"$_d_workdir/autodetect_modules"
            msg "build directory saved in '%s'" "$_d_workdir"
        else
            rm -rf -- "$_d_workdir"
        fi
    fi

    exit "$err"
}

resolve_kernver() {
    local kernel="$1" arch=''

    if [[ -z "$kernel" ]]; then
        uname -r
        return 0
    fi

    if [[ "${kernel:0:1}" != / ]]; then
        echo "$kernel"
        return 0
    fi

    if [[ ! -e "$kernel" ]]; then
        error "specified kernel image does not exist: '%s'" "$kernel"
        return 1
    fi

    kver "$kernel" && return

    error "invalid kernel specified: '%s'" "$1"

    arch="$(uname -m)"
    if [[ "$arch" != @(i?86|x86_64) ]]; then
        error "kernel version extraction from image not supported for '%s' architecture" "$arch"
        error "there's a chance the generic version extractor may work with a valid uncompressed kernel image"
    fi

    return 1
}

hook_help() {
    local resolved script
    script="$(PATH="$_d_install" type -p "$1")"

    # this will be true for broken symlinks as well
    if [[ -z "$script" ]]; then
        error "Hook '%s' not found" "$1"
        return 1
    fi

    if resolved="$(readlink "$script")" && [[ "${script##*/}" != "${resolved##*/}" ]]; then
        msg "This hook is deprecated. See the '%s' hook" "${resolved##*/}"
        return 0
    fi

    # shellcheck disable=SC1090
    . "$script"
    if ! declare -f help >/dev/null; then
        error "No help for hook $1"
        return 1
    fi

    msg "Help for hook '$1':"
    help

    list_hookpoints "$1"
}

hook_list() {
    local p hook resolved
    local -a paths hooklist depr
    local ss_ordinals=(¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹)

    IFS=: read -ra paths <<<"$_d_install"

    for path in "${paths[@]}"; do
        for hook in "$path"/*; do
            [[ -e "$hook" || -L "$hook" ]] || continue

            # handle deprecated hooks and point to replacement
            if resolved="$(readlink "$hook")" && [[ "${hook##*/}" != "${resolved##*/}" ]]; then
                resolved="${resolved##*/}"

                if ! index_of "$resolved" "${depr[@]}"; then
                    # deprecated hook
                    depr+=("$resolved")
                    _idx=$(( ${#depr[*]} - 1 ))
                fi

                hook+=${ss_ordinals[_idx]}
            fi

            hooklist+=("${hook##*/}")
        done
    done

    msg "Available hooks"
    printf '%s\n' "${hooklist[@]}" | sort -u | column -c"$(tput cols)"

    if (( ${#depr[*]} )); then
        echo
        for p in "${!depr[@]}"; do
            printf $'\'%s\' This hook is deprecated in favor of \'%s\'\n' \
                "${ss_ordinals[p]}" "${depr[p]}"
        done
    fi
}

compute_hookset() {
    local h

    for h in "${HOOKS[@]}" "${_optaddhooks[@]}"; do
        in_array "$h" "${_optskiphooks[@]}" && continue
        _hooks+=("$h")
    done
}

build_image() {
    local out="$1" compressout="$1" compress="$2" errmsg pipestatus

    case "$compress" in
        cat)
            msg "Creating uncompressed initcpio image: '%s'" "$out"
            unset COMPRESSION_OPTIONS
            ;;
        *)
            msg "Creating %s-compressed initcpio image: '%s'" "$compress" "$out"
            ;;&
        xz)
            COMPRESSION_OPTIONS=('-T0' '--check=crc32' "${COMPRESSION_OPTIONS[@]}")
            ;;
        lz4)
            COMPRESSION_OPTIONS=('-l' "${COMPRESSION_OPTIONS[@]}")
            ;;
        zstd)
            COMPRESSION_OPTIONS=('-T0' "${COMPRESSION_OPTIONS[@]}")
            ;;
    esac

    if [[ -f "$out" ]]; then
        local curr_size space_left_on_device

        curr_size="$(stat --format="%s" "$out")"
        space_left_on_device="$(($(stat -f --format="%a*%S" "$out")))"

        # check if there is enough space on the device to write the image to a tempfile, fallback otherwise
        # this assumes that the new image is not more than 1¼ times the size of the old one
        (( $((curr_size + (curr_size/4))) < space_left_on_device )) && compressout="$out".tmp
    fi

    pushd "$BUILDROOT" >/dev/null || return

    # Reproducibility: set all timestamps to 0
    find . -mindepth 1 -execdir touch -hcd "@0" "{}" +

    # If this pipeline changes, |pipeprogs| below needs to be updated as well.
    find . -mindepth 1 -printf '%P\0' \
        | sort -z \
        | LANG=C bsdtar --uid 0 --gid 0 --null -cnf - -T - \
        | LANG=C bsdtar --null -cf - --format=newc @- \
        | $compress "${COMPRESSION_OPTIONS[@]}" >"$compressout"

    pipestatus=("${PIPESTATUS[@]}")
    pipeprogs=('find' 'sort' 'bsdtar (step 1)' 'bsdtar (step 2)' "$compress")

    popd >/dev/null || return

    for (( i = 0; i < ${#pipestatus[*]}; ++i )); do
        if (( pipestatus[i] )); then
            errmsg="${pipeprogs[i]} reported an error"
            break
        fi
    done

    if (( _builderrors )); then
        warning "errors were encountered during the build. The image may not be complete."
    fi

    if [[ -n "$errmsg" ]]; then
        error "Image generation FAILED: '%s'" "$errmsg"
        return 1
    elif (( _builderrors == 0 )); then
        msg "Image generation successful"
    fi

    # sync and rename as we only wrote to a tempfile so far to ensure consistency
    if [[ "$compressout" != "$out" ]]; then
        sync -d -- "$compressout"
        mv -f -- "$compressout" "$out"
    fi
}

# do not invoke directly, this is called by uki_init and uki_add_section
_uki_increase_offset() {
    local step="$1"
    _uki_offset+="$(((step + _uki_alignment - 1) / _uki_alignment * _uki_alignment))"
}

uki_init() {
    local uefistub="$1"

    # global variables shared between uki functions
    declare -gi _uki_offset=0 _uki_alignment=0
    declare -ga _uki_objcopy_args=("$uefistub")

    # reproducibility, preserve dates of used files
    _uki_objcopy_args+=(-p)

    _uki_alignment="$(LC_ALL=C objdump -p "${uefistub}" \
        | awk '/SectionAlignment/ {print strtonum("0x"$2)}')"
    _uki_increase_offset "$(LC_ALL=C objdump -h "${uefistub}" \
        | awk 'NF==7 {size=strtonum("0x"$3); offset=strtonum("0x"$4)} END {print size + offset}')"
}

uki_add_section() {
    local secname="$1" filename="${2:-/dev/stdin}"
    if [[ ! -f "$filename" ]]; then
        local tmpfile
        tmpfile="$(mktemp -t 'mkinitcpio.XXXXXX')"
        _tmpfiles+=("$tmpfile")
        cat -- "$filename" > "$tmpfile"
        filename="$tmpfile"
    fi
    _uki_objcopy_args+=(--add-section "$secname=$filename" --change-section-vma "$secname=$(printf 0x%x "$_uki_offset")")
    _uki_increase_offset "$(stat -Lc%s "$filename")"
}

uki_assemble() {
    local out="$1"
    objcopy "${_uki_objcopy_args[@]}" "$out"
}

build_uki() {
    local out="$1" initramfs="$2" cmdline="$3" osrelease="$4" splash="$5" kernelimg="$6" uefistub="$7" microcode=("${@:8}") errmsg='' stub cpuarch uefiarch

    msg "Creating unified kernel image: '%s'" "$out"

    if [[ -z "$uefistub" ]]; then
        cpuarch="$(uname -m)"
        case "$cpuarch" in
            x86_64)
                uefiarch='x64'
                # Detect 64-bit x86_64 systems with 32-bit IA32 UEFI
                if [[ -e /sys/firmware/efi/fw_platform_size ]]; then
                    if (( $(< /sys/firmware/efi/fw_platform_size) == 32 )); then
                        uefiarch='ia32'
                    fi
                else
                    warning 'Cannot determine UEFI bitness. Assuming x64 UEFI.'
                fi
                ;;
            i386|i686)
                uefiarch='ia32'
                ;;
            aarch64*|arm64|armv8*)
                uefiarch='aa64'
                ;;
            arm*)
                uefiarch='arm'
                ;;
            *)
                uefiarch="$cpuarch"
                ;;
        esac
        for stub in /usr/lib/{systemd/boot/efi,gummiboot}/"linux${uefiarch}.efi.stub"; do
            if [[ -f "$stub" ]]; then
                uefistub="$stub"
                msg2 "Using UEFI stub: '%s'" "$uefistub"
                break
            fi
        done
        if [[ -z "$uefistub" ]]; then
            error "UEFI stub for architecture '%s' not found" "$uefiarch"
            return 1
        fi
    fi
    if [[ ! -f "$uefistub" ]]; then
        error "UEFI stub '%s' not found" "$uefistub"
        return 1
    fi

    uki_init "$uefistub"

    if [[ -z "$osrelease" ]]; then
        if [[ -f "/etc/os-release" ]]; then
            osrelease="/etc/os-release"
        elif [[ -f "/usr/lib/os-release" ]]; then
            osrelease="/usr/lib/os-release"
        fi
        msg2 "Using os-release file: '%s'" "$osrelease"
    fi
    if [[ ! -f "$osrelease" ]]; then
        error "os-release file '%s' not found" "$osrelease"
        return 1
    fi

    uki_add_section '.osrel' <(
        suffix="${MKINITCPIO_PROCESS_PRESET##*-}"
        [[ "$suffix" == 'default' ]] && suffix=""
        printf 'VERSION_ID=%s%s\n' "$KERNELVERSION" "${suffix:+"~$suffix"}"
        grep -v '^VERSION_ID=' "$osrelease"
    )
    uki_add_section '.uname' <(printf %s "$KERNELVERSION")

    local cmdline_files=()
    if [[ -n "$cmdline" ]]; then
        if [[ -f "$cmdline" ]]; then
            cmdline_files+=("$cmdline")
        else
            error "Kernel cmdline file '%s' not found" "$cmdline"
            return 1
        fi
    fi

    if (( ! _optnocmdline )); then
        if [[ -z "$cmdline" ]]; then
            if [[ -f "/etc/kernel/cmdline" ]]; then
                cmdline_files+=("/etc/kernel/cmdline")
            elif [[ -f "/usr/lib/kernel/cmdline" ]]; then
                cmdline_files+=("/usr/lib/kernel/cmdline")
            fi
            if [[ -d '/etc/cmdline.d' ]]; then
                mapfile -d '' -O "${#cmdline_files[@]}" cmdline_files < <(find "/etc/cmdline.d" -xtype f -name '*.conf' -print0 | sort -zVu)
            fi
        fi

        if (( ! ${#cmdline_files[@]} )); then
            warning "Note: no cmdline files where found and --cmdline is not set!"
            cmdline_files=("/proc/cmdline")
            warning "Reusing current kernel cmdline from ${cmdline_files[*]}"
        else
            msg2 "Using cmdline file: '%s'" "${cmdline_files[@]}"
        fi

        uki_add_section '.cmdline' <(printf '%s\n\0' "$(grep -ha -- '^[^#]' "${cmdline_files[@]}" | tr -s '\n' ' ')")
    else
        quiet 'Kernel cmdline will not be embedded.'
    fi

    if [[ -n "$splash" ]]; then
        uki_add_section '.splash' "$splash"
        msg2 "Using splash image: '%s'" "$splash"
    fi

    if [[ -z "$kernelimg" ]]; then
        # FIXME: fallback to /boot/vmlinuz-linux can probably be removed as
        #   $KERNELIMAGE should point to an image with the correct version
        for img in "$KERNELIMAGE" "/boot/vmlinuz-linux"; do
            if [[ -f "$img" ]]; then
                kernelimg="$img"
                msg2 "Using kernel image: '%s'" "$kernelimg"
                break
            fi
        done
    fi
    if [[ ! -f "$kernelimg" ]]; then
        error "Kernel image '%s' not found" "$kernelimg"
        return 1
    fi

    uki_add_section '.linux' "$kernelimg"

    if [[ -z "$initramfs" ]]; then
        error "Initramfs '%s' not found" "$initramfs"
        return 1
    fi

    for image in "${microcode[@]}"; do
        msg2 "Using microcode image: '%s'" "$image"
    done

    uki_add_section '.initrd' <(cat -- "${microcode[@]}" "$initramfs")

    uki_assemble "$out"

    status="$?"
    if (( status )) ; then
        error 'Unified kernel image generation FAILED'
    else
        msg 'Unified kernel image generation successful'
    fi
}

# The function is invoked via `map process_preset`
# shellcheck disable=SC2317
process_preset() (
    local preset="$1" preset_image='' preset_options=''
    local -a preset_mkopts preset_cmd preset_remove_cmd
    if [[ -n "$MKINITCPIO_PROCESS_PRESET" ]]; then
        error "You appear to be calling a preset from a preset. This is a configuration error."
        exit 1
    fi

    # allow path to preset file, else resolve it in $_d_presets
    if [[ $preset != */* ]]; then
        printf -v preset '%s/%s.preset' "$_d_presets" "$preset"
    fi

    # shellcheck disable=SC1090
    . "$preset" || die "Failed to load preset: '%s'" "$preset"

    (( ! ${#PRESETS[@]} )) && warning "Preset file '%s' is empty or does not contain any presets." "$preset"

    # Use -m and -v options specified earlier
    (( _optquiet )) || preset_mkopts+=(-v)
    (( _optcolor )) || preset_mkopts+=(-n)

    (( _optsavetree )) && preset_mkopts+=(-s)

    ret=0
    for p in "${PRESETS[@]}"; do
        if (( _optremove )); then
            msg "Removing image for preset: $preset: '$p'"
        else
            msg "Building image from preset: $preset: '$p'"
        fi
        preset_cmd=("${preset_mkopts[@]}")
        preset_remove_cmd=()

        preset_kver="${p}_kver"
        if [[ -n "${!preset_kver:-$ALL_kver}" ]]; then
            preset_cmd+=(-k "${!preset_kver:-$ALL_kver}")
        else
            warning "No kernel version specified. Skipping image '%s'" "$p"
            continue
        fi

        preset_config="${p}_config"
        if [[ -n "${!preset_config:-$ALL_config}" ]]; then
            preset_cmd+=(-c "${!preset_config:-$ALL_config}")
            msg "Using configuration file: '%s'" "${!preset_config:-$ALL_config}"
        else
            msg "Using default configuration file: '%s'" "$_f_config"
        fi

        preset_uki="${p}_uki"
        if [[ ! -v "${p}_uki" && -v "${p}_efi_image" ]]; then
            preset_uki="${p}_efi_image"
            warning "Deprecated option '%s' found. Update '%s' to use '%s' instead." "${p}_efi_image" "$preset" "${p}_uki"
        fi

        if [[ -n "${!preset_uki}" ]]; then
            preset_cmd+=(-U "${!preset_uki}")
            preset_remove_cmd+=("${!preset_uki}")
        fi

        preset_image="${p}_image"
        if [[ -n "${!preset_image}" ]]; then
            preset_cmd+=(-g "${!preset_image}")
            preset_remove_cmd+=("${!preset_image}")
        elif [[ -z "${!preset_uki}" ]]; then
            warning "No image or UKI specified. Skipping image '%s'" "$p"
            continue
        fi

        local -n preset_options="${p}_options"
        if [[ "${preset_options@a}" == *a* ]]; then
            preset_cmd+=("${preset_options[@]}")
        elif [[ -n "$preset_options" ]]; then
            mapfile -d ' ' -O "${#preset_cmd[@]}" -t preset_cmd < <(
                printf '%s' "$preset_options"
            )
        fi

        local -n preset_microcode="${p}_microcode"
        if [[ -n "${preset_microcode[*]}" || -n "${ALL_microcode[*]}" ]]; then
            mapfile -d '' -O "${#preset_cmd[@]}" -t preset_cmd < <(
                printf -- '--microcode\0%s\0' "${preset_microcode[@]:-${ALL_microcode[@]}}"
            )
        fi

        if (( _optremove )); then
            if (( ${#preset_remove_cmd[*]} )); then
                for pr in "${preset_remove_cmd[@]}"; do
                    if [[ ! -f "${pr}" ]]; then
                        warning "Image not found: '%s'" "$pr"
                    elif [[ ! -w "${pr}" ]]; then
                        error "Image not writable: '%s'" "$pr"
                    else
                        rm -f -- "${pr}"
                        msg2 "Removed: '%s'" "$pr"
                        warning "Image not found: '%s'" "$pr"
                    fi
                done
            fi
        else
            local preset_name="${preset##*/}"; preset_name="${preset_name%.preset}-$p"
            preset_cmd+=("${OPTREST[@]}")
            msg2 "${preset_cmd[*]}"
            # we won't be calling mkinitcpio recursively, so no need to set MKINITCPIO_PROCESS_PRESET
            MKINITCPIO_PROCESS_PRESET="$preset_name" "$0" "${preset_cmd[@]}"
        fi
        # shellcheck disable=SC2181
        (( $? )) && ret=1
    done

    exit "$ret"
)

preload_builtin_modules() {
    local modname field value
    local -a path

    # Prime the _addedmodules list with the builtins for this kernel. We prefer
    # the modinfo file if it exists, but this requires a recent enough kernel
    # and kmod>=27.

    if [[ -r $_d_kmoduledir/modules.builtin.modinfo ]]; then
        while IFS=.= read -rd '' modname field value; do
            _addedmodules[${modname//-/_}]=2
            case "$field" in
                alias)
                    _addedmodules["${value//-/_}"]=2
                    ;;
            esac
        done <"$_d_kmoduledir/modules.builtin.modinfo"

    elif [[ -r "$_d_kmoduledir/modules.builtin" ]]; then
        while IFS=/ read -ra path; do
            modname="${path[-1]%.ko}"
            _addedmodules["${modname//-/_}"]=2
        done <"$_d_kmoduledir/modules.builtin"
    fi
}

run_post_hooks() {
    local args=("$@")
    local hook status
    local -i count=0
    local -a paths seen

    IFS=: read -ra paths <<<"$_d_post"

    for path in "${paths[@]}"; do
        for hook in "$path"/*; do
            if [[ ! -e "$hook" ]] || in_array "${hook##*/}" "${seen[@]}"; then
                continue
            fi
            seen+=("${hook##*/}")

            [[ -x "$hook" ]] || continue

            (( count++ )) || msg 'Running post hooks'
            msg2 'Running post hook: [%s]' "${hook##*/}"

            KERNELVERSION="$KERNELVERSION" KERNELDESTINATION="$KERNELDESTINATION" command "$hook" "$KERNELIMAGE" "${args[@]}"
            status="$?"

            if (( status )); then
                error "'%s' failed with exit code %d" "$hook" "$status"
                return 1
            fi
        done
    done

    (( count )) && msg 'Post processing done'
    return 0
}

# shellcheck source=functions
. "$_f_functions"

trap 'cleanup' EXIT

_opt_short='A:c:D:g:H:hk:nLMPp:Rr:S:sd:t:U:Vvz:'
_opt_long=('add:' 'addhooks:' 'config:' 'generate:' 'hookdir': 'hookhelp:' 'help'
           'kernel:' 'listhooks' 'automods' 'moduleroot:' 'nocolor' 'allpresets'
           'preset:' 'remove' 'skiphooks:' 'save' 'generatedir:' 'builddir:' 'version' 'verbose' 'compress:'
           'uki:' 'uefi:' 'microcode:' 'splash:' 'kernelimage:' 'uefistub:' 'cmdline:' 'osrelease:' 'no-cmdline')

parseopts "$_opt_short" "${_opt_long[@]}" -- "$@" || exit 1
set -- "${OPTRET[@]}"
unset _opt_short _opt_long OPTRET

while :; do
    case "$1" in
        # --add remains for backwards compat
        -A | --add | --addhooks)
            shift
            IFS=, read -r -a add <<<"$1"
            _optaddhooks+=("${add[@]}")
            unset add
            ;;
        -c | --config)
            shift
            _f_config="$1"
            _optconfd=0
            ;;
        --cmdline)
            shift
            _optcmdline="$1"
            ;;
        --no-cmdline)
            _optnocmdline=1
            ;;
        -k | --kernel)
            shift
            KERNELVERSION="$1"
            ;;
        -s | --save)
            _optsavetree=1
            ;;
        -d | --generatedir)
            shift
            _opttargetdir="$1"
            ;;
        -g | --generate)
            shift
            [[ -d "$1" ]] && die 'Invalid image path -- must not be a directory'
            if ! _optgenimg="$(readlink -f "$1")" || [[ ! -e "${_optgenimg%/*}" ]]; then
                die "Unable to write to path: '%s'" "$1"
            fi
            ;;
        -h | --help)
            usage
            exit 0
            ;;
        -V | --version)
            version
            exit 0
            ;;
        -p | --preset)
            shift
            _optpreset+=("$1")
            ;;
        -R | --remove)
            _optremove=1
            ;;
        -n | --nocolor)
            _optcolor=0
            ;;
        --uefi)
            warning 'The --uefi option is deprecated. Use --uki instead.'
            ;&
        -U | --uki)
            shift
            [[ -d "$1" ]] && die "Invalid image path -- must not be a directory"
            if ! _optuki="$(readlink -f "$1")" || [[ ! -e "${_optuki%/*}" ]]; then
                die "Unable to write to path: '%s'" "$1"
            fi
            ;;
        -v | --verbose)
            _optquiet=0
            ;;
        -S | --skiphooks)
            shift
            IFS=, read -r -a skip <<<"$1"
            _optskiphooks+=("${skip[@]}")
            unset skip
            ;;
        -H | --hookhelp)
            shift
            hook_help "$1"
            exit
            ;;
        -L | --listhooks)
            hook_list
            exit 0
            ;;
        --splash)
            shift
            [[ -f "$1" ]] || die 'Invalid file -- must be a file'
            _optsplash="$1"
            ;;
        --kernelimage)
            shift
            _optkernelimage="$1"
            ;;
        --uefistub)
            shift
            _optuefistub="$1"
            ;;
        -M | --automods)
            _optshowautomods=1
            ;;
        --microcode)
            shift
            _optmicrocode+=("$1")
            ;;
        -P | --allpresets)
            _optpreset=("$_d_presets"/*.preset)
            [[ -e "${_optpreset[0]}" ]] || die 'No presets found in %s' "$_d_presets"
            ;;
        --osrelease)
            shift
            [[ ! -f "$1" ]] && die 'Invalid file -- must be a file'
            _optosrelease="$1"
            ;;
        -t | --builddir)
            shift
            export TMPDIR="$1"
            ;;
        -z | --compress)
            shift
            _optcompress="$1"
            ;;
        -r | --moduleroot)
            shift
            _optmoduleroot="$1"
            ;;
        -D | --hookdir)
            shift
            _d_flag_hooks+="$1/hooks:"
            _d_flag_install+="$1/install:"
            _d_flag_post+="$1/post:"
            ;;
        --)
            shift
            break 2
            ;;
    esac
    shift
done

OPTREST=("$@")

if [[ -t 1 ]] && (( _optcolor )); then
    try_enable_color
fi

# if we get presets and remove flag, skip to preset processing
if (( _optremove && ${#_optpreset[*]} )); then
    map process_preset "${_optpreset[@]}"
    exit
fi

if [[ -n "$_d_flag_hooks" && -n "$_d_flag_install" && -n "$_d_flag_post" ]]; then
    _d_hooks="${_d_flag_hooks%:}"
    _d_install="${_d_flag_install%:}"
    _d_post="${_d_flag_post%:}"
fi

# If we specified --uki but no -g we want to create a temporary initramfs which will be used with the efi executable.
if [[ -n "$_optuki" && -z "$_optgenimg" ]]; then
    tmpfile="$(mktemp -t mkinitcpio.XXXXXX)"
    _tmpfiles+=("$tmpfile")
    _optgenimg="$tmpfile"
fi

# insist that /proc and /dev be mounted (important for chroots)
# NOTE: avoid using mountpoint for this -- look for the paths that we actually
# use in mkinitcpio. Avoids issues like FS#26344.
[[ -e /proc/self/mountinfo ]] || die "/proc must be mounted!"
[[ -e /dev/fd ]] || die "/dev must be mounted!"

# use preset $_optpreset (exits after processing)
if (( ${#_optpreset[*]} )); then
    map process_preset "${_optpreset[@]}"
    exit
fi

KERNELIMAGE='' KERNELDESTINATION=''
if [[ "$KERNELVERSION" != 'none' ]]; then
    # if the "version" is given as a file name, use it without modification,
    # if doesn't exist, resolve_kernver will fail anyway
    if [[ "${KERNELVERSION:0:1}" == '/' ]]; then
        KERNELIMAGE="$KERNELVERSION"
    fi

    KERNELVERSION="$(resolve_kernver "$KERNELVERSION")" || exit 1
    _d_kmoduledir="$_optmoduleroot/lib/modules/$KERNELVERSION"
    [[ -d "$_d_kmoduledir" ]] || die "'$_d_kmoduledir' is not a valid kernel module directory"

    if [[ -z "$KERNELIMAGE" ]]; then
        # search well-known locations for the kernel image
        for img in "$_d_kmoduledir/vmlinuz" "/lib/modules/$KERNELVERSION/vmlinuz"; do
            if [[ -f "$img" ]]; then
                KERNELIMAGE="$img"
                if read -r pkgbase &>/dev/null <"${img%/*}/pkgbase"; then
                    KERNELDESTINATION="/boot/vmlinuz-$pkgbase"
                else
                    KERNELDESTINATION="/boot/vmlinuz-$KERNELVERSION"
                fi
                quiet "located kernel image: '%s'" "$KERNELIMAGE"
                break
            fi
        done
    fi

    if [[ -z "$KERNELIMAGE" ]]; then
        # check version of all kernels in /boot
        for img in /boot/vmlinuz-*; do
            if [[ "$(kver "$img")" == "$KERNELVERSION" ]]; then
                KERNELIMAGE="$img"
                quiet "located kernel image: '%s'" "$KERNELIMAGE"
                break
            fi
        done
    fi

    if [[ -f "$KERNELIMAGE" ]]; then
        [[ -z "$KERNELDESTINATION" ]] && KERNELDESTINATION="$KERNELIMAGE"
    else
        # this is not fatal, initramfs will still be generated but post
        # hooks will not know what kernel image is used
        warning 'Could not find kernel image for version %s' "$KERNELVERSION"
    fi
fi

MODULES_DECOMPRESS="${MODULES_DECOMPRESS:-"yes"}"

_d_workdir="$(initialize_buildroot "$KERNELVERSION" "$_opttargetdir")" || exit 1
BUILDROOT="${_opttargetdir:-$_d_workdir/root}"

# Source additional configuration files, if no configuration file has been defined either with "-c" or via preset file
if [[ -d "$_d_config" ]] && (( _optconfd )); then
    mapfile -d '' conf_files < <(find "$_d_config" -maxdepth 1 -xtype f -name '*.conf' -print0 | sed -z 's/.*\///' | sort -zVu)
    if (( ${#conf_files[@]} )); then
        tmpfile="$(mktemp -t mkinitcpio.XXXXXX)"
        _tmpfiles+=("$tmpfile")
        cat -- "$_f_config" > "$tmpfile" || die "Failed to read configuration '%s'" "$_f_config"
        for conf in "${conf_files[@]}"; do
            if [[ -r "$_d_config/$conf" ]]; then
                cat -- "$_d_config/$conf" >> "$tmpfile"
                msg "Using drop-in configuration file: '%s'" "$conf"
            fi
        done
        _f_config="$tmpfile"
    fi
fi

# shellcheck disable=SC1091 source=mkinitcpio.conf
. "$_f_config" || die "Failed to read configuration '%s'" "$_f_config"

arrayize_config

# after returning, hooks are populated into the array '_hooks'
# HOOKS should not be referenced from here on
compute_hookset

if (( ${#_hooks[*]} == 0 )); then
    die "Invalid config: No hooks found"
fi

if (( _optshowautomods )); then
    msg "Modules autodetected"
    # shellcheck source=install/autodetect
    PATH="$_d_install" . 'autodetect'
    build
    printf '%s\n' "${!_autodetect_cache[@]}" | sort
    exit 0
fi

if [[ -n "$_optgenimg" ]]; then
    # check for permissions. if the image doesn't already exist,
    # then check the directory
    if [[ ( -e $_optgenimg && ! -w $_optgenimg ) ||
            ( ! -d ${_optgenimg%/*} || ! -w ${_optgenimg%/*} ) ]]; then
        die "Unable to write to '%s'" "$_optgenimg"
    fi

    _optcompress="${_optcompress:-"${COMPRESSION:-zstd}"}"
    if ! type -P "$_optcompress" >/dev/null; then
        warning "Unable to locate compression method: '%s'" "$_optcompress"
        _optcompress='cat'
    fi

    msg "Starting build: '%s'" "$KERNELVERSION"
elif [[ -n "$_opttargetdir" ]]; then
    msg "Starting build: '%s'" "$KERNELVERSION"
else
    msg "Starting dry run: '%s'" "$KERNELVERSION"
fi

# set functrace and trap to catch errors in add_* functions
declare -i _builderrors=0
set -o functrace
trap '(( $? )) && [[ "$FUNCNAME" == add_* ]] && (( ++_builderrors ))' RETURN

preload_builtin_modules

map run_build_hook "${_hooks[@]}" || (( ++_builderrors ))

# process config file
parse_config "$_f_config"

# switch out the error handler to catch all errors
trap -- RETURN
trap '(( ++_builderrors ))' ERR
set -o errtrace

install_modules "${!_modpaths[@]}"

# unset errtrace and trap
set +o functrace
set +o errtrace
trap -- ERR

# this is simply a nice-to-have -- it doesn't matter if it fails.
ldconfig -r "$BUILDROOT" &>/dev/null
# remove /var/cache/ldconfig/aux-cache for reproducibility
rm -f -- "$BUILDROOT/var/cache/ldconfig/aux-cache"

# Set umask to create initramfs images and unified kernel images as 600
umask 077

if [[ -n "$_optgenimg" ]]; then
    build_image "$_optgenimg" "$_optcompress" || exit 1
    _generated+=("$_optgenimg")
elif [[ -n "$_opttargetdir" ]]; then
    msg "Build complete."
else
    msg "Dry run complete, use -g IMAGE to generate a real image"
fi

if [[ -n "$_optuki" && -n "$_optgenimg" ]]; then
    build_uki "$_optuki" "$_optgenimg" "$_optcmdline" "$_optosrelease" "$_optsplash" "$_optkernelimage" "$_optuefistub" "${_optmicrocode[@]}" \
        && (( ${#_generated[*]} )) && _generated+=("$_optuki")
fi

if (( ${#_generated[*]} )); then
    run_post_hooks "${_generated[@]}" || (( ++_builderrors ))
fi

exit $(( !!_builderrors ))

# vim: set ft=sh ts=4 sw=4 et: