1 /*
2  * Copyright (c) 2024 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stddef.h>
8 #include <ctype.h>
9 #include <zephyr/toolchain.h>
10 #include <posix_native_task.h>
11 #include <nsi_cmdline_main_if.h>
12 #include <nsi_host_trampolines.h>
13 #include <nsi_tracing.h>
14 
remove_one_char(char * str)15 static void remove_one_char(char *str)
16 {
17 	int i;
18 
19 	for (i = 0; str[i] != 0; i++) {
20 		str[i] = str[i+1];
21 	}
22 }
23 
register_kconfig_args(void)24 static void register_kconfig_args(void)
25 {
26 	static char kconfig_args[] = CONFIG_NATIVE_EXTRA_CMDLINE_ARGS;
27 	int argc = 0;
28 	char **argv = NULL;
29 #define REALLOC_INC 100
30 	int alloced = 0;
31 	bool new_arg = true, literal = false, escape = false;
32 
33 	if (kconfig_args[0] == 0) {
34 		return;
35 	}
36 
37 	for (int i = 0; kconfig_args[i] != 0; i++) {
38 		if ((literal == false) && (escape == false) && isspace(kconfig_args[i])) {
39 			new_arg = true;
40 			kconfig_args[i] = 0;
41 			continue;
42 		}
43 		if ((escape == false) && (kconfig_args[i] == '\\')) {
44 			escape = true;
45 			remove_one_char(&kconfig_args[i]);
46 			i--;
47 			continue;
48 		}
49 		if ((escape == false) && (kconfig_args[i] == '"')) {
50 			literal = !literal;
51 			remove_one_char(&kconfig_args[i]);
52 			i--;
53 			continue;
54 		}
55 		escape = false;
56 
57 		if (new_arg) {
58 			new_arg = false;
59 			if (argc >= alloced) {
60 				alloced += REALLOC_INC;
61 				argv = nsi_host_realloc(argv, alloced*sizeof(char *));
62 				if (argv == NULL) {
63 					nsi_print_error_and_exit("Out of memory\n");
64 				}
65 			}
66 			argv[argc++] = &kconfig_args[i];
67 		}
68 	}
69 
70 	nsi_register_extra_args(argc, argv);
71 
72 	nsi_host_free(argv);
73 }
74 
75 NATIVE_TASK(register_kconfig_args, PRE_BOOT_1, 100);
76