1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 // This program loads kernel and initrd which the system will boot into when
18 // panic occurs.
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <linux/kexec.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/syscall.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30
31 #if defined(__aarch64__)
32 #define EARLYCON "earlycon=uart8250,mmio,0x3f8"
33 #elif defined(__x86_64__)
34 #define EARLYCON "earlycon=uart8250,io,0x3f8"
35 #endif
36
37 static const char *KERNEL = "/system/etc/microdroid_crashdump_kernel";
38 static const char *INITRD = "/system/etc/microdroid_crashdump_initrd.img";
39 static const char *CMDLINE = "1 panic=-1 rdinit=/bin/crashdump nr_cpus=1 reset_devices "
40 "console=hvc0 " EARLYCON;
41
open_checked(const char * path)42 static int open_checked(const char *path) {
43 int fd = open(path, O_RDONLY);
44 if (fd == -1) {
45 fprintf(stderr, "Failed to open %s: %s\n", path, strerror(errno));
46 exit(1);
47 }
48 return fd;
49 }
50
main()51 int main() {
52 unsigned long cmdline_len = strlen(CMDLINE) + 1; // include null terminator, otherwise EINVAL
53
54 if (syscall(SYS_kexec_file_load, open_checked(KERNEL), open_checked(INITRD), cmdline_len,
55 CMDLINE, KEXEC_FILE_ON_CRASH) == -1) {
56 fprintf(stderr, "Failed to load panic kernel: %s\n", strerror(errno));
57 if (errno == EADDRNOTAVAIL) {
58 struct stat st;
59 off_t kernel_size = 0;
60 off_t initrd_size = 0;
61
62 if (stat(KERNEL, &st) == 0) {
63 kernel_size = st.st_size;
64 }
65 if (stat(INITRD, &st) == 0) {
66 initrd_size = st.st_size;
67 }
68 fprintf(stderr, "Image size too big? %s:%ld bytes, %s:%ld bytes", KERNEL, kernel_size,
69 INITRD, initrd_size);
70 }
71 return 1;
72 }
73 return 0;
74 }
75