1 /* vi: set sw=4 ts=4: */
3 * Mini init implementation for busybox
5 * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Adjusted by so many folks, it's impossible to keep track.
9 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
15 #include <sys/reboot.h>
16 #include <sys/resource.h>
20 /* Was a CONFIG_xxx option. A lot of people were building
21 * not fully functional init by switching it on! */
24 #define COMMAND_SIZE 256
25 #define CONSOLE_NAME_SIZE 32
27 /* Default sysinit script. */
29 #define INIT_SCRIPT "/etc/init.d/rcS"
32 /* Each type of actions can appear many times. They will be
33 * handled in order. RESTART is an exception, only 1st is used.
35 /* Start these actions first and wait for completion */
37 /* Start these after SYSINIT and wait for completion */
39 /* Start these after WAIT and *dont* wait for completion */
42 * NB: while SYSINIT/WAIT/ONCE are being processed,
43 * SIGHUP ("reread /etc/inittab") will be processed only after
44 * each group of actions. If new inittab adds, say, a SYSINIT action,
45 * it will not be run, since init is already "past SYSINIT stage".
47 /* Start these after ONCE are started, restart on exit */
49 /* Like RESPAWN, but wait for <Enter> to be pressed on tty */
52 * Start these on SIGINT, and wait for completion.
53 * Then go back to respawning RESPAWN and ASKFIRST actions.
54 * NB: kernel sends SIGINT to us if Ctrl-Alt-Del was pressed.
56 #define CTRLALTDEL 0x20
58 * Start these before killing all processes in preparation for
59 * running RESTART actions or doing low-level halt/reboot/poweroff
60 * (initiated by SIGUSR1/SIGTERM/SIGUSR2).
61 * Wait for completion before proceeding.
65 * exec() on SIGQUIT. SHUTDOWN actions are started and waited for,
66 * then all processes are killed, then init exec's 1st RESTART action,
67 * replacing itself by it. If no RESTART action specified,
68 * SIGQUIT has no effect.
73 /* A linked list of init_actions, to be read from inittab */
75 struct init_action *next;
78 char terminal[CONSOLE_NAME_SIZE];
79 char command[COMMAND_SIZE];
82 static struct init_action *init_action_list = NULL;
84 static const char *log_console = VC_5;
89 #ifndef RB_HALT_SYSTEM
90 RB_HALT_SYSTEM = 0xcdef0123, /* FIXME: this overflows enum */
91 RB_ENABLE_CAD = 0x89abcdef,
93 RB_POWER_OFF = 0x4321fedc,
94 RB_AUTOBOOT = 0x01234567,
98 /* Print a message to the specified device.
99 * "where" may be bitwise-or'd from L_LOG | L_CONSOLE
100 * NB: careful, we can be called after vfork!
102 #define dbg_message(...) do { if (DEBUG_INIT) message(__VA_ARGS__); } while (0)
103 static void message(int where, const char *fmt, ...)
104 __attribute__ ((format(printf, 2, 3)));
105 static void message(int where, const char *fmt, ...)
112 va_start(arguments, fmt);
113 l = 1 + vsnprintf(msg + 1, sizeof(msg) - 2, fmt, arguments);
114 if (l > sizeof(msg) - 1)
118 #if ENABLE_FEATURE_INIT_SYSLOG
121 /* Log the message to syslogd */
122 openlog(applet_name, 0, LOG_DAEMON);
123 /* don't print "\r" */
124 syslog(LOG_INFO, "%s", msg + 1);
131 static int log_fd = -1;
135 /* Take full control of the log tty, and never close it.
136 * It's mine, all mine! Muhahahaha! */
139 log_fd = STDERR_FILENO;
141 log_fd = device_open(log_console, O_WRONLY | O_NONBLOCK | O_NOCTTY);
143 bb_error_msg("can't log to %s", log_console);
146 close_on_exec_on(log_fd);
151 full_write(log_fd, msg, l);
152 if (log_fd == STDERR_FILENO)
153 return; /* don't print dup messages */
158 if (where & L_CONSOLE) {
159 /* Send console messages to console so people will see them. */
160 full_write(STDERR_FILENO, msg, l);
164 static void console_init(void)
169 s = getenv("CONSOLE");
171 s = getenv("console");
173 int fd = open(s, O_RDWR | O_NONBLOCK | O_NOCTTY);
175 dup2(fd, STDIN_FILENO);
176 dup2(fd, STDOUT_FILENO);
177 xmove_fd(fd, STDERR_FILENO);
179 dbg_message(L_LOG, "console='%s'", s);
181 /* Make sure fd 0,1,2 are not closed
182 * (so that they won't be used by future opens) */
184 // Users report problems
185 // /* Make sure init can't be blocked by writing to stderr */
186 // fcntl(STDERR_FILENO, F_SETFL, fcntl(STDERR_FILENO, F_GETFL) | O_NONBLOCK);
190 if (ioctl(STDIN_FILENO, VT_OPENQRY, &vtno) != 0) {
191 /* Not a linux terminal, probably serial console.
192 * Force the TERM setting to vt102
193 * if TERM is set to linux (the default) */
194 if (!s || strcmp(s, "linux") == 0)
195 putenv((char*)"TERM=vt102");
196 if (!ENABLE_FEATURE_INIT_SYSLOG)
199 putenv((char*)"TERM=linux");
202 /* Set terminal settings to reasonable defaults.
203 * NB: careful, we can be called after vfork! */
204 static void set_sane_term(void)
208 tcgetattr(STDIN_FILENO, &tty);
210 /* set control chars */
211 tty.c_cc[VINTR] = 3; /* C-c */
212 tty.c_cc[VQUIT] = 28; /* C-\ */
213 tty.c_cc[VERASE] = 127; /* C-? */
214 tty.c_cc[VKILL] = 21; /* C-u */
215 tty.c_cc[VEOF] = 4; /* C-d */
216 tty.c_cc[VSTART] = 17; /* C-q */
217 tty.c_cc[VSTOP] = 19; /* C-s */
218 tty.c_cc[VSUSP] = 26; /* C-z */
220 /* use line discipline 0 */
223 /* Make it be sane */
224 tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
225 tty.c_cflag |= CREAD | HUPCL | CLOCAL;
228 tty.c_iflag = ICRNL | IXON | IXOFF;
231 tty.c_oflag = OPOST | ONLCR;
235 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
237 tcsetattr_stdin_TCSANOW(&tty);
240 /* Open the new terminal device.
241 * NB: careful, we can be called after vfork! */
242 static int open_stdio_to_tty(const char* tty_name)
244 /* empty tty_name means "use init's tty", else... */
249 /* fd can be only < 0 or 0: */
250 fd = device_open(tty_name, O_RDWR);
252 message(L_LOG | L_CONSOLE, "can't open %s: %s",
253 tty_name, strerror(errno));
254 return 0; /* failure */
256 dup2(STDIN_FILENO, STDOUT_FILENO);
257 dup2(STDIN_FILENO, STDERR_FILENO);
260 return 1; /* success */
263 static void reset_sighandlers_and_unblock_sigs(void)
275 sigprocmask_allsigs(SIG_UNBLOCK);
278 /* Wrapper around exec:
279 * Takes string (max COMMAND_SIZE chars).
280 * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
281 * Otherwise splits words on whitespace, deals with leading dash,
282 * and uses plain exec().
283 * NB: careful, we can be called after vfork!
285 static void init_exec(const char *command)
287 char *cmd[COMMAND_SIZE / 2];
288 char buf[COMMAND_SIZE + 6]; /* COMMAND_SIZE+strlen("exec ")+1 */
289 int dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
291 /* See if any special /bin/sh requiring characters are present */
292 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
293 strcpy(buf, "exec ");
294 strcpy(buf + 5, command + dash); /* excluding "-" */
295 /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
296 cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
297 cmd[1] = (char*)"-c";
301 /* Convert command (char*) into cmd (char**, one word per string) */
304 next = strcpy(buf, command); /* including "-" */
305 while ((word = strsep(&next, " \t")) != NULL) {
306 if (*word != '\0') { /* not two spaces/tabs together? */
313 /* If we saw leading "-", it is interactive shell.
314 * Try harder to give it a controlling tty.
315 * And skip "-" in actual exec call. */
317 /* _Attempt_ to make stdin a controlling tty. */
318 if (ENABLE_FEATURE_INIT_SCTTY)
319 ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
321 BB_EXECVP(cmd[0] + dash, cmd);
322 message(L_LOG | L_CONSOLE, "can't run '%s': %s", cmd[0], strerror(errno));
323 /* returns if execvp fails */
326 /* Used only by run_actions */
327 static pid_t run(const struct init_action *a)
331 /* Careful: don't be affected by a signal in vforked child */
332 sigprocmask_allsigs(SIG_BLOCK);
333 if (BB_MMU && (a->action_type & ASKFIRST))
338 message(L_LOG | L_CONSOLE, "can't fork");
340 sigprocmask_allsigs(SIG_UNBLOCK);
341 return pid; /* Parent or error */
346 /* Reset signal handlers that were set by the parent process */
347 reset_sighandlers_and_unblock_sigs();
349 /* Create a new session and make ourself the process group leader */
352 /* Open the new terminal device */
353 if (!open_stdio_to_tty(a->terminal))
356 /* NB: on NOMMU we can't wait for input in child, so
357 * "askfirst" will work the same as "respawn". */
358 if (BB_MMU && (a->action_type & ASKFIRST)) {
359 static const char press_enter[] ALIGN1 =
360 #ifdef CUSTOMIZED_BANNER
361 #include CUSTOMIZED_BANNER
363 "\nPlease press Enter to activate this console. ";
366 * Save memory by not exec-ing anything large (like a shell)
367 * before the user wants it. This is critical if swap is not
368 * enabled and the system has low memory. Generally this will
369 * be run on the second virtual console, and the first will
370 * be allowed to start a shell or whatever an init script
373 dbg_message(L_LOG, "waiting for enter to start '%s'"
374 "(pid %d, tty '%s')\n",
375 a->command, getpid(), a->terminal);
376 full_write(STDOUT_FILENO, press_enter, sizeof(press_enter) - 1);
377 while (safe_read(STDIN_FILENO, &c, 1) == 1 && c != '\n')
382 * When a file named /.init_enable_core exists, setrlimit is called
383 * before processes are spawned to set core file size as unlimited.
384 * This is for debugging only. Don't use this is production, unless
385 * you want core dumps lying about....
387 if (ENABLE_FEATURE_INIT_COREDUMPS) {
388 if (access("/.init_enable_core", F_OK) == 0) {
390 limit.rlim_cur = RLIM_INFINITY;
391 limit.rlim_max = RLIM_INFINITY;
392 setrlimit(RLIMIT_CORE, &limit);
396 /* Log the process name and args */
397 message(L_LOG, "starting pid %d, tty '%s': '%s'",
398 getpid(), a->terminal, a->command);
400 /* Now run it. The new program will take over this PID,
401 * so nothing further in init.c should be run. */
402 init_exec(a->command);
403 /* We're still here? Some error happened. */
407 static struct init_action *mark_terminated(pid_t pid)
409 struct init_action *a;
412 for (a = init_action_list; a; a = a->next) {
422 static void waitfor(pid_t pid)
424 /* waitfor(run(x)): protect against failed fork inside run() */
428 /* Wait for any child (prevent zombies from exiting orphaned processes)
429 * but exit the loop only when specified one has exited. */
431 pid_t wpid = wait(NULL);
432 mark_terminated(wpid);
433 /* Unsafe. SIGTSTP handler might have wait'ed it already */
434 /*if (wpid == pid) break;*/
441 /* Run all commands of a particular type */
442 static void run_actions(int action_type)
444 struct init_action *a;
446 for (a = init_action_list; a; a = a->next) {
447 if (!(a->action_type & action_type))
450 if (a->action_type & (SYSINIT | WAIT | ONCE | CTRLALTDEL | SHUTDOWN)) {
452 if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN))
455 if (a->action_type & (RESPAWN | ASKFIRST)) {
456 /* Only run stuff with pid == 0. If pid != 0,
457 * it is already running
465 static void new_init_action(uint8_t action_type, const char *command, const char *cons)
467 struct init_action *a, **nextp;
471 * ::shutdown:umount -a -r
472 * ::shutdown:swapoff -a
474 * ::shutdown:swapoff -a
475 * ::shutdown:umount -a -r
476 * On reload, we must ensure entries end up in correct order.
477 * To achieve that, if we find a matching entry, we move it
480 nextp = &init_action_list;
481 while ((a = *nextp) != NULL) {
482 /* Don't enter action if it's already in the list,
483 * This prevents losing running RESPAWNs.
485 if (strcmp(a->command, command) == 0
486 && strcmp(a->terminal, cons) == 0
488 /* Remove from list */
490 /* Find the end of the list */
491 while (*nextp != NULL)
492 nextp = &(*nextp)->next;
500 a = xzalloc(sizeof(*a));
501 /* Append to the end of the list */
503 a->action_type = action_type;
504 safe_strncpy(a->command, command, sizeof(a->command));
505 safe_strncpy(a->terminal, cons, sizeof(a->terminal));
506 dbg_message(L_LOG | L_CONSOLE, "command='%s' action=%d tty='%s'\n",
507 a->command, a->action_type, a->terminal);
510 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
511 * then parse_inittab() simply adds in some default
512 * actions(i.e., runs INIT_SCRIPT and then starts a pair
513 * of "askfirst" shells). If CONFIG_FEATURE_USE_INITTAB
514 * _is_ defined, but /etc/inittab is missing, this
515 * results in the same set of default behaviors.
517 static void parse_inittab(void)
519 #if ENABLE_FEATURE_USE_INITTAB
521 parser_t *parser = config_open2("/etc/inittab", fopen_for_read);
526 /* No inittab file - set up some default behavior */
527 /* Reboot on Ctrl-Alt-Del */
528 new_init_action(CTRLALTDEL, "reboot", "");
529 /* Umount all filesystems on halt/reboot */
530 new_init_action(SHUTDOWN, "umount -a -r", "");
531 /* Swapoff on halt/reboot */
532 if (ENABLE_SWAPONOFF)
533 new_init_action(SHUTDOWN, "swapoff -a", "");
534 /* Prepare to restart init when a QUIT is received */
535 new_init_action(RESTART, "init", "");
536 /* Askfirst shell on tty1-4 */
537 new_init_action(ASKFIRST, bb_default_login_shell, "");
538 //TODO: VC_1 instead of ""? "" is console -> ctty problems -> angry users
539 new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
540 new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
541 new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
543 new_init_action(SYSINIT, INIT_SCRIPT, "");
547 #if ENABLE_FEATURE_USE_INITTAB
548 /* optional_tty:ignored_runlevel:action:command
549 * Delims are not to be collapsed and need exactly 4 tokens
551 while (config_read(parser, token, 4, 0, "#:",
552 PARSE_NORMAL & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
553 /* order must correspond to SYSINIT..RESTART constants */
554 static const char actions[] ALIGN1 =
555 "sysinit\0""wait\0""once\0""respawn\0""askfirst\0"
556 "ctrlaltdel\0""shutdown\0""restart\0";
558 char *tty = token[0];
560 if (!token[3]) /* less than 4 tokens */
562 action = index_in_strings(actions, token[2]);
563 if (action < 0 || !token[3][0]) /* token[3]: command */
565 /* turn .*TTY -> /dev/TTY */
567 if (strncmp(tty, "/dev/", 5) == 0)
569 tty = concat_path_file("/dev/", tty);
571 new_init_action(1 << action, token[3], tty);
576 message(L_LOG | L_CONSOLE, "Bad inittab entry at line %d",
579 config_close(parser);
583 static void pause_and_low_level_reboot(unsigned magic) NORETURN;
584 static void pause_and_low_level_reboot(unsigned magic)
588 /* Allow time for last message to reach serial console, etc */
591 /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)
592 * in linux/kernel/sys.c, which can cause the machine to panic when
593 * the init process exits... */
595 if (pid == 0) { /* child */
603 static void run_shutdown_and_kill_processes(void)
605 /* Run everything to be run at "shutdown". This is done _prior_
606 * to killing everything, in case people wish to use scripts to
607 * shut things down gracefully... */
608 run_actions(SHUTDOWN);
610 message(L_CONSOLE | L_LOG, "The system is going down NOW!");
612 /* Send signals to every process _except_ pid 1 */
614 message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");
619 message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
621 /*sleep(1); - callers take care about making a pause */
624 /* Signal handling by init:
626 * For process with PID==1, on entry kernel sets all signals to SIG_DFL
627 * and unmasks all signals. However, for process with PID==1,
628 * default action (SIG_DFL) on any signal is to ignore it,
629 * even for special signals SIGKILL and SIGCONT.
630 * Also, any signal can be caught or blocked.
631 * (but SIGSTOP is still handled specially, at least in 2.6.20)
633 * We install two kinds of handlers, "immediate" and "delayed".
635 * Immediate handlers execute at any time, even while, say, sysinit
638 * Delayed handlers just set a flag variable. The variable is checked
639 * in the main loop and acted upon.
641 * halt/poweroff/reboot and restart have immediate handlers.
642 * They only traverse linked list of struct action's, never modify it,
643 * this should be safe to do even in signal handler. Also they
646 * SIGSTOP and SIGTSTP have immediate handlers. They just wait
647 * for SIGCONT to happen.
649 * SIGHUP has a delayed handler, because modifying linked list
650 * of struct action's from a signal handler while it is manipulated
651 * by the program may be disastrous.
653 * Ctrl-Alt-Del has a delayed handler. Not a must, but allowing
654 * it to happen even somewhere inside "sysinit" would be a bit awkward.
656 * There is a tiny probability that SIGHUP and Ctrl-Alt-Del will collide
657 * and only one will be remembered and acted upon.
660 /* The SIGUSR[12]/SIGTERM handler */
661 static void halt_reboot_pwoff(int sig) NORETURN;
662 static void halt_reboot_pwoff(int sig)
667 /* We may call run() and it unmasks signals,
668 * including the one masked inside this signal handler.
669 * Testcase which would start multiple reboot scripts:
670 * while true; do reboot; done
673 reset_sighandlers_and_unblock_sigs();
675 run_shutdown_and_kill_processes();
679 if (sig == SIGTERM) {
682 } else if (sig == SIGUSR2) {
686 message(L_CONSOLE, "Requesting system %s", m);
687 pause_and_low_level_reboot(rb);
691 /* Handler for QUIT - exec "restart" action,
692 * else (no such action defined) do nothing */
693 static void restart_handler(int sig UNUSED_PARAM)
695 struct init_action *a;
697 for (a = init_action_list; a; a = a->next) {
698 if (!(a->action_type & RESTART))
701 /* Starting from here, we won't return.
702 * Thus don't need to worry about preserving errno
706 reset_sighandlers_and_unblock_sigs();
708 run_shutdown_and_kill_processes();
710 /* Allow Ctrl-Alt-Del to reboot the system.
711 * This is how kernel sets it up for init, we follow suit.
713 reboot(RB_ENABLE_CAD); /* misnomer */
715 if (open_stdio_to_tty(a->terminal)) {
716 dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);
717 /* Theoretically should be safe.
718 * But in practice, kernel bugs may leave
719 * unkillable processes, and wait() may block forever.
720 * Oh well. Hoping "new" init won't be too surprised
721 * by having children it didn't create.
723 //while (wait(NULL) > 0)
725 init_exec(a->command);
727 /* Open or exec failed */
728 pause_and_low_level_reboot(RB_HALT_SYSTEM);
733 /* The SIGSTOP/SIGTSTP handler
734 * NB: inside it, all signals except SIGCONT are masked
735 * via appropriate setup in sigaction().
737 static void stop_handler(int sig UNUSED_PARAM)
739 smallint saved_bb_got_signal;
742 saved_bb_got_signal = bb_got_signal;
744 signal(SIGCONT, record_signo);
749 if (bb_got_signal == SIGCONT)
751 /* NB: this can accidentally wait() for a process
752 * which we waitfor() elsewhere! waitfor() must have
753 * code which is resilient against this.
755 wpid = wait_any_nohang(NULL);
756 mark_terminated(wpid);
760 signal(SIGCONT, SIG_DFL);
762 bb_got_signal = saved_bb_got_signal;
765 #if ENABLE_FEATURE_USE_INITTAB
766 static void reload_inittab(void)
768 struct init_action *a, **nextp;
770 message(L_LOG, "reloading /etc/inittab");
772 /* Disable old entries */
773 for (a = init_action_list; a; a = a->next)
776 /* Append new entries, or modify existing entries
777 * (incl. setting a->action_type) if cmd and device name
778 * match new ones. End result: only entries with
779 * a->action_type == 0 are stale.
783 #if ENABLE_FEATURE_KILL_REMOVED
784 /* Kill stale entries */
785 /* Be nice and send SIGTERM first */
786 for (a = init_action_list; a; a = a->next)
787 if (a->action_type == 0 && a->pid != 0)
788 kill(a->pid, SIGTERM);
789 if (CONFIG_FEATURE_KILL_DELAY) {
790 /* NB: parent will wait in NOMMU case */
791 if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
792 sleep(CONFIG_FEATURE_KILL_DELAY);
793 for (a = init_action_list; a; a = a->next)
794 if (a->action_type == 0 && a->pid != 0)
795 kill(a->pid, SIGKILL);
801 /* Remove stale entries and SYSINIT entries.
802 * We never rerun SYSINIT entries anyway,
803 * removing them too saves a few bytes */
804 nextp = &init_action_list;
805 while ((a = *nextp) != NULL) {
806 if ((a->action_type & ~SYSINIT) == 0) {
815 /* run_actions(RESPAWN | ASKFIRST); */
816 /* - we return to main loop, which does this automagically */
820 static int check_delayed_sigs(void)
825 smallint sig = bb_got_signal;
831 #if ENABLE_FEATURE_USE_INITTAB
836 run_actions(CTRLALTDEL);
840 int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
841 int init_main(int argc UNUSED_PARAM, char **argv)
843 die_sleep = 30 * 24*60*60; /* if xmalloc would ever die... */
845 if (argv[1] && strcmp(argv[1], "-q") == 0) {
846 return kill(1, SIGHUP);
850 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
852 && (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc"))
856 /* Turn off rebooting via CTL-ALT-DEL - we get a
857 * SIGINT on CAD so we can shut things down gracefully... */
858 reboot(RB_DISABLE_CAD); /* misnomer */
861 /* Figure out where the default console should be */
867 /* Make sure environs is set to something sane */
868 putenv((char *) "HOME=/");
869 putenv((char *) bb_PATH_root_path);
870 putenv((char *) "SHELL=/bin/sh");
871 putenv((char *) "USER=root"); /* needed? why? */
874 xsetenv("RUNLEVEL", argv[1]);
876 #if !ENABLE_FEATURE_EXTRA_QUIET
878 message(L_CONSOLE | L_LOG, "init started: %s", bb_banner);
881 /* Make sure there is enough memory to do something useful. */
882 if (ENABLE_SWAPONOFF) {
885 if (sysinfo(&info) == 0
886 && (info.mem_unit ? info.mem_unit : 1) * (long long)info.totalram < 1024*1024
888 message(L_CONSOLE, "Low memory, forcing swapon");
889 /* swapon -a requires /proc typically */
890 new_init_action(SYSINIT, "mount -t proc proc /proc", "");
891 /* Try to turn on swap */
892 new_init_action(SYSINIT, "swapon -a", "");
893 run_actions(SYSINIT); /* wait and removing */
897 /* Check if we are supposed to be in single user mode */
899 && (strcmp(argv[1], "single") == 0 || strcmp(argv[1], "-s") == 0 || LONE_CHAR(argv[1], '1'))
901 /* ??? shouldn't we set RUNLEVEL="b" here? */
902 /* Start a shell on console */
903 new_init_action(RESPAWN, bb_default_login_shell, "");
905 /* Not in single user mode - see what inittab says */
907 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
908 * then parse_inittab() simply adds in some default
909 * actions(i.e., INIT_SCRIPT and a pair
910 * of "askfirst" shells */
915 if (getenv("SELINUX_INIT") == NULL) {
918 putenv((char*)"SELINUX_INIT=YES");
919 if (selinux_init_load_policy(&enforce) == 0) {
920 BB_EXECVP(argv[0], argv);
921 } else if (enforce > 0) {
922 /* SELinux in enforcing mode but load_policy failed */
923 message(L_CONSOLE, "can't load SELinux Policy. "
924 "Machine is in enforcing mode. Halting now.");
930 /* Make the command line just say "init" - thats all, nothing else */
931 strncpy(argv[0], "init", strlen(argv[0]));
932 /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
934 memset(*argv, 0, strlen(*argv));
936 /* Set up signal handlers */
941 + (1 << SIGUSR1) /* halt */
942 + (1 << SIGTERM) /* reboot */
943 + (1 << SIGUSR2) /* poweroff */
944 , halt_reboot_pwoff);
945 signal(SIGQUIT, restart_handler); /* re-exec another init */
947 /* Stop handler must allow only SIGCONT inside itself */
948 memset(&sa, 0, sizeof(sa));
949 sigfillset(&sa.sa_mask);
950 sigdelset(&sa.sa_mask, SIGCONT);
951 sa.sa_handler = stop_handler;
952 /* NB: sa_flags doesn't have SA_RESTART.
953 * It must be able to interrupt wait().
955 sigaction_set(SIGTSTP, &sa); /* pause */
956 /* Does not work as intended, at least in 2.6.20.
957 * SIGSTOP is simply ignored by init:
959 sigaction_set(SIGSTOP, &sa); /* pause */
961 /* SIGINT (Ctrl-Alt-Del) must interrupt wait(),
962 * setting handler without SA_RESTART flag.
964 bb_signals_recursive_norestart((1 << SIGINT), record_signo);
967 /* Set up "reread /etc/inittab" handler.
968 * Handler is set up without SA_RESTART, it will interrupt syscalls.
970 if (!DEBUG_INIT && ENABLE_FEATURE_USE_INITTAB)
971 bb_signals_recursive_norestart((1 << SIGHUP), record_signo);
973 /* Now run everything that needs to be run */
974 /* First run the sysinit command */
975 run_actions(SYSINIT);
976 check_delayed_sigs();
977 /* Next run anything that wants to block */
979 check_delayed_sigs();
980 /* Next run anything to be run only once */
983 /* Now run the looping stuff for the rest of forever.
988 maybe_WNOHANG = check_delayed_sigs();
990 /* (Re)run the respawn/askfirst stuff */
991 run_actions(RESPAWN | ASKFIRST);
992 maybe_WNOHANG |= check_delayed_sigs();
994 /* Don't consume all CPU time - sleep a bit */
996 maybe_WNOHANG |= check_delayed_sigs();
998 /* Wait for any child process(es) to exit.
1000 * If check_delayed_sigs above reported that a signal
1001 * was caught, wait will be nonblocking. This ensures
1002 * that if SIGHUP has reloaded inittab, respawn and askfirst
1003 * actions will not be delayed until next child death.
1006 maybe_WNOHANG = WNOHANG;
1009 struct init_action *a;
1011 /* If signals happen _in_ the wait, they interrupt it,
1012 * bb_signals_recursive_norestart set them up that way
1014 wpid = waitpid(-1, NULL, maybe_WNOHANG);
1018 a = mark_terminated(wpid);
1020 message(L_LOG, "process '%s' (pid %d) exited. "
1021 "Scheduling for restart.",
1024 /* See if anyone else is waiting to be reaped */
1025 maybe_WNOHANG = WNOHANG;