Jiyong Park | d352412 | 2022-07-07 15:00:51 +0900 | [diff] [blame] | 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/syscall.h> |
| 27 | #include <sys/types.h> |
| 28 | #include <unistd.h> |
| 29 | |
| 30 | static int open_checked(const char* path) { |
| 31 | int fd = open(path, O_RDONLY); |
| 32 | if (fd == -1) { |
| 33 | fprintf(stderr, "Failed to open %s: %s\n", path, strerror(errno)); |
| 34 | exit(1); |
| 35 | } |
| 36 | return fd; |
| 37 | } |
| 38 | |
| 39 | int main(int argc, const char* argv[]) { |
| 40 | if (argc != 4) { |
| 41 | fprintf(stderr, "Usage: %s <kernel> <initrd> <commandline>\n", argv[0]); |
| 42 | return 1; |
| 43 | } |
| 44 | |
| 45 | // TODO(b/238272206): consider harding these |
| 46 | const char* kernel = argv[1]; |
| 47 | const char* initrd = argv[2]; |
| 48 | const char* cmdline = argv[3]; |
| 49 | unsigned long cmdline_len = strlen(cmdline) + 1; // include null terminator, otherwise EINVAL |
| 50 | |
| 51 | if (syscall(SYS_kexec_file_load, open_checked(kernel), open_checked(initrd), cmdline_len, |
| 52 | cmdline, KEXEC_FILE_ON_CRASH) == -1) { |
| 53 | fprintf(stderr, "Failed to load panic kernel: %s\n", strerror(errno)); |
| 54 | return 1; |
| 55 | } |
| 56 | return 0; |
| 57 | } |