1 /* SPDX-License-Identifier: LGPL-2.1 OR MIT */
2 /*
3  * C Run Time support for NOLIBC
4  * Copyright (C) 2023 Zhangjin Wu <falcon@tinylab.org>
5  */
6 
7 #ifndef _NOLIBC_CRT_H
8 #define _NOLIBC_CRT_H
9 
10 char **environ __attribute__((weak));
11 const unsigned long *_auxv __attribute__((weak));
12 
13 static void __stack_chk_init(void);
14 static void exit(int);
15 
16 extern void (*const __preinit_array_start[])(int, char **, char**) __attribute__((weak));
17 extern void (*const __preinit_array_end[])(int, char **, char**) __attribute__((weak));
18 
19 extern void (*const __init_array_start[])(int, char **, char**) __attribute__((weak));
20 extern void (*const __init_array_end[])(int, char **, char**) __attribute__((weak));
21 
22 extern void (*const __fini_array_start[])(void) __attribute__((weak));
23 extern void (*const __fini_array_end[])(void) __attribute__((weak));
24 
25 __attribute__((weak,used))
_start_c(long * sp)26 void _start_c(long *sp)
27 {
28 	long argc;
29 	char **argv;
30 	char **envp;
31 	int exitcode;
32 	void (* const *ctor_func)(int, char **, char **);
33 	void (* const *dtor_func)(void);
34 	const unsigned long *auxv;
35 	/* silence potential warning: conflicting types for 'main' */
36 	int _nolibc_main(int, char **, char **) __asm__ ("main");
37 
38 	/* initialize stack protector */
39 	__stack_chk_init();
40 
41 	/*
42 	 * sp  :    argc          <-- argument count, required by main()
43 	 * argv:    argv[0]       <-- argument vector, required by main()
44 	 *          argv[1]
45 	 *          ...
46 	 *          argv[argc-1]
47 	 *          null
48 	 * environ: environ[0]    <-- environment variables, required by main() and getenv()
49 	 *          environ[1]
50 	 *          ...
51 	 *          null
52 	 * _auxv:   _auxv[0]      <-- auxiliary vector, required by getauxval()
53 	 *          _auxv[1]
54 	 *          ...
55 	 *          null
56 	 */
57 
58 	/* assign argc and argv */
59 	argc = *sp;
60 	argv = (void *)(sp + 1);
61 
62 	/* find environ */
63 	environ = envp = argv + argc + 1;
64 
65 	/* find _auxv */
66 	for (auxv = (void *)envp; *auxv++;)
67 		;
68 	_auxv = auxv;
69 
70 	for (ctor_func = __preinit_array_start; ctor_func < __preinit_array_end; ctor_func++)
71 		(*ctor_func)(argc, argv, envp);
72 	for (ctor_func = __init_array_start; ctor_func < __init_array_end; ctor_func++)
73 		(*ctor_func)(argc, argv, envp);
74 
75 	/* go to application */
76 	exitcode = _nolibc_main(argc, argv, envp);
77 
78 	for (dtor_func = __fini_array_end; dtor_func > __fini_array_start;)
79 		(*--dtor_func)();
80 
81 	exit(exitcode);
82 }
83 
84 #endif /* _NOLIBC_CRT_H */
85