1 /*
2  * Copyright (c) 2025 GARDENA GmbH
3  * Copyright (c) 2025 Nordic Semiconductor ASA
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <stdbool.h>
9 #include <errno.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <nsi_main.h>
13 #include <nsi_tasks.h>
14 #include <nsi_tracing.h>
15 #include <nsi_cmdline.h>
16 #include <nsi_host_trampolines.h>
17 
18 static const char module[] = "native_sim_reboot";
19 
20 static bool reboot_on_exit;
21 
native_set_reboot_on_exit(void)22 void native_set_reboot_on_exit(void)
23 {
24 	reboot_on_exit = true;
25 }
26 
maybe_reboot(void)27 void maybe_reboot(void)
28 {
29 	char **argv;
30 	int argc;
31 
32 	if (!reboot_on_exit) {
33 		return;
34 	}
35 
36 	reboot_on_exit = false; /* If we reenter it means we failed to reboot */
37 
38 	nsi_get_cmd_line_args(&argc, &argv);
39 
40 	/* Let's set an environment variable which the native_sim hw_info driver may check */
41 	(void)nsi_host_setenv("NATIVE_SIM_RESET_CAUSE", "SOFTWARE", 1);
42 
43 	nsi_print_warning("%s: Restarting process.\n", module);
44 
45 	(void)execv("/proc/self/exe", argv);
46 
47 	nsi_print_error_and_exit("%s: Failed to restart process, exiting (%s)\n", module,
48 				 strerror(errno));
49 }
50 
51 NSI_TASK(maybe_reboot, ON_EXIT_POST, 999);
52