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[])(void) __attribute__((weak)); 17 extern void (*const __preinit_array_end[])(void) __attribute__((weak)); 18 19 extern void (*const __init_array_start[])(void) __attribute__((weak)); 20 extern void (*const __init_array_end[])(void) __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)) 26 void _start_c(long *sp) 27 { 28 long argc; 29 char **argv; 30 char **envp; 31 int exitcode; 32 void (* const *func)(void); 33 const unsigned long *auxv; 34 /* silence potential warning: conflicting types for 'main' */ 35 int _nolibc_main(int, char **, char **) __asm__ ("main"); 36 37 /* initialize stack protector */ 38 __stack_chk_init(); 39 40 /* 41 * sp : argc <-- argument count, required by main() 42 * argv: argv[0] <-- argument vector, required by main() 43 * argv[1] 44 * ... 45 * argv[argc-1] 46 * null 47 * environ: environ[0] <-- environment variables, required by main() and getenv() 48 * environ[1] 49 * ... 50 * null 51 * _auxv: _auxv[0] <-- auxiliary vector, required by getauxval() 52 * _auxv[1] 53 * ... 54 * null 55 */ 56 57 /* assign argc and argv */ 58 argc = *sp; 59 argv = (void *)(sp + 1); 60 61 /* find environ */ 62 environ = envp = argv + argc + 1; 63 64 /* find _auxv */ 65 for (auxv = (void *)envp; *auxv++;) 66 ; 67 _auxv = auxv; 68 69 for (func = __preinit_array_start; func < __preinit_array_end; func++) 70 (*func)(); 71 for (func = __init_array_start; func < __init_array_end; func++) 72 (*func)(); 73 74 /* go to application */ 75 exitcode = _nolibc_main(argc, argv, envp); 76 77 for (func = __fini_array_end; func > __fini_array_start;) 78 (*--func)(); 79 80 exit(exitcode); 81 } 82 83 #endif /* _NOLIBC_CRT_H */ 84