init.c revision b710ed21dec88c0dde8209264df054c842561589
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <unistd.h>
21#include <fcntl.h>
22#include <ctype.h>
23#include <signal.h>
24#include <sys/wait.h>
25#include <sys/mount.h>
26#include <sys/stat.h>
27#include <sys/poll.h>
28#include <errno.h>
29#include <stdarg.h>
30#include <mtd/mtd-user.h>
31#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/un.h>
34
35#include <selinux/selinux.h>
36#include <selinux/label.h>
37#include <selinux/android.h>
38
39#include <libgen.h>
40
41#include <cutils/list.h>
42#include <cutils/android_reboot.h>
43#include <cutils/sockets.h>
44#include <cutils/iosched_policy.h>
45#include <private/android_filesystem_config.h>
46#include <termios.h>
47
48#include <sys/system_properties.h>
49
50#include "devices.h"
51#include "init.h"
52#include "log.h"
53#include "property_service.h"
54#include "bootchart.h"
55#include "signal_handler.h"
56#include "keychords.h"
57#include "init_parser.h"
58#include "util.h"
59#include "ueventd.h"
60#include "watchdogd.h"
61
62struct selabel_handle *sehandle;
63struct selabel_handle *sehandle_prop;
64
65static int property_triggers_enabled = 0;
66
67#if BOOTCHART
68static int   bootchart_count;
69#endif
70
71static char console[32];
72static char bootmode[32];
73static char hardware[32];
74static unsigned revision = 0;
75static char qemu[32];
76
77static struct action *cur_action = NULL;
78static struct command *cur_command = NULL;
79static struct listnode *command_queue = NULL;
80
81void notify_service_state(const char *name, const char *state)
82{
83    char pname[PROP_NAME_MAX];
84    int len = strlen(name);
85    if ((len + 10) > PROP_NAME_MAX)
86        return;
87    snprintf(pname, sizeof(pname), "init.svc.%s", name);
88    property_set(pname, state);
89}
90
91static int have_console;
92static char console_name[PROP_VALUE_MAX] = "/dev/console";
93static time_t process_needs_restart;
94
95static const char *ENV[32];
96
97/* add_environment - add "key=value" to the current environment */
98int add_environment(const char *key, const char *val)
99{
100    int n;
101
102    for (n = 0; n < 31; n++) {
103        if (!ENV[n]) {
104            size_t len = strlen(key) + strlen(val) + 2;
105            char *entry = malloc(len);
106            snprintf(entry, len, "%s=%s", key, val);
107            ENV[n] = entry;
108            return 0;
109        }
110    }
111
112    return 1;
113}
114
115static void zap_stdio(void)
116{
117    int fd;
118    fd = open("/dev/null", O_RDWR);
119    dup2(fd, 0);
120    dup2(fd, 1);
121    dup2(fd, 2);
122    close(fd);
123}
124
125static void open_console()
126{
127    int fd;
128    if ((fd = open(console_name, O_RDWR)) < 0) {
129        fd = open("/dev/null", O_RDWR);
130    }
131    ioctl(fd, TIOCSCTTY, 0);
132    dup2(fd, 0);
133    dup2(fd, 1);
134    dup2(fd, 2);
135    close(fd);
136}
137
138static void publish_socket(const char *name, int fd)
139{
140    char key[64] = ANDROID_SOCKET_ENV_PREFIX;
141    char val[64];
142
143    strlcpy(key + sizeof(ANDROID_SOCKET_ENV_PREFIX) - 1,
144            name,
145            sizeof(key) - sizeof(ANDROID_SOCKET_ENV_PREFIX));
146    snprintf(val, sizeof(val), "%d", fd);
147    add_environment(key, val);
148
149    /* make sure we don't close-on-exec */
150    fcntl(fd, F_SETFD, 0);
151}
152
153void service_start(struct service *svc, const char *dynamic_args)
154{
155    struct stat s;
156    pid_t pid;
157    int needs_console;
158    int n;
159    char *scon = NULL;
160    int rc;
161
162        /* starting a service removes it from the disabled or reset
163         * state and immediately takes it out of the restarting
164         * state if it was in there
165         */
166    svc->flags &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET));
167    svc->time_started = 0;
168
169        /* running processes require no additional work -- if
170         * they're in the process of exiting, we've ensured
171         * that they will immediately restart on exit, unless
172         * they are ONESHOT
173         */
174    if (svc->flags & SVC_RUNNING) {
175        return;
176    }
177
178    needs_console = (svc->flags & SVC_CONSOLE) ? 1 : 0;
179    if (needs_console && (!have_console)) {
180        ERROR("service '%s' requires console\n", svc->name);
181        svc->flags |= SVC_DISABLED;
182        return;
183    }
184
185    if (stat(svc->args[0], &s) != 0) {
186        ERROR("cannot find '%s', disabling '%s'\n", svc->args[0], svc->name);
187        svc->flags |= SVC_DISABLED;
188        return;
189    }
190
191    if ((!(svc->flags & SVC_ONESHOT)) && dynamic_args) {
192        ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
193               svc->args[0]);
194        svc->flags |= SVC_DISABLED;
195        return;
196    }
197
198    if (is_selinux_enabled() > 0) {
199        if (svc->seclabel) {
200            scon = strdup(svc->seclabel);
201            if (!scon) {
202                ERROR("Out of memory while starting '%s'\n", svc->name);
203                return;
204            }
205        } else {
206            char *mycon = NULL, *fcon = NULL;
207
208            INFO("computing context for service '%s'\n", svc->args[0]);
209            rc = getcon(&mycon);
210            if (rc < 0) {
211                ERROR("could not get context while starting '%s'\n", svc->name);
212                return;
213            }
214
215            rc = getfilecon(svc->args[0], &fcon);
216            if (rc < 0) {
217                ERROR("could not get context while starting '%s'\n", svc->name);
218                freecon(mycon);
219                return;
220            }
221
222            rc = security_compute_create(mycon, fcon, string_to_security_class("process"), &scon);
223            freecon(mycon);
224            freecon(fcon);
225            if (rc < 0) {
226                ERROR("could not get context while starting '%s'\n", svc->name);
227                return;
228            }
229        }
230    }
231
232    NOTICE("starting '%s'\n", svc->name);
233
234    pid = fork();
235
236    if (pid == 0) {
237        struct socketinfo *si;
238        struct svcenvinfo *ei;
239        char tmp[32];
240        int fd, sz;
241
242        umask(077);
243        if (properties_inited()) {
244            get_property_workspace(&fd, &sz);
245            sprintf(tmp, "%d,%d", dup(fd), sz);
246            add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);
247        }
248
249        for (ei = svc->envvars; ei; ei = ei->next)
250            add_environment(ei->name, ei->value);
251
252        setsockcreatecon(scon);
253
254        for (si = svc->sockets; si; si = si->next) {
255            int socket_type = (
256                    !strcmp(si->type, "stream") ? SOCK_STREAM :
257                        (!strcmp(si->type, "dgram") ? SOCK_DGRAM : SOCK_SEQPACKET));
258            int s = create_socket(si->name, socket_type,
259                                  si->perm, si->uid, si->gid);
260            if (s >= 0) {
261                publish_socket(si->name, s);
262            }
263        }
264
265        freecon(scon);
266        scon = NULL;
267        setsockcreatecon(NULL);
268
269        if (svc->ioprio_class != IoSchedClass_NONE) {
270            if (android_set_ioprio(getpid(), svc->ioprio_class, svc->ioprio_pri)) {
271                ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
272                      getpid(), svc->ioprio_class, svc->ioprio_pri, strerror(errno));
273            }
274        }
275
276        if (needs_console) {
277            setsid();
278            open_console();
279        } else {
280            zap_stdio();
281        }
282
283#if 0
284        for (n = 0; svc->args[n]; n++) {
285            INFO("args[%d] = '%s'\n", n, svc->args[n]);
286        }
287        for (n = 0; ENV[n]; n++) {
288            INFO("env[%d] = '%s'\n", n, ENV[n]);
289        }
290#endif
291
292        setpgid(0, getpid());
293
294    /* as requested, set our gid, supplemental gids, and uid */
295        if (svc->gid) {
296            if (setgid(svc->gid) != 0) {
297                ERROR("setgid failed: %s\n", strerror(errno));
298                _exit(127);
299            }
300        }
301        if (svc->nr_supp_gids) {
302            if (setgroups(svc->nr_supp_gids, svc->supp_gids) != 0) {
303                ERROR("setgroups failed: %s\n", strerror(errno));
304                _exit(127);
305            }
306        }
307        if (svc->uid) {
308            if (setuid(svc->uid) != 0) {
309                ERROR("setuid failed: %s\n", strerror(errno));
310                _exit(127);
311            }
312        }
313        if (svc->seclabel) {
314            if (is_selinux_enabled() > 0 && setexeccon(svc->seclabel) < 0) {
315                ERROR("cannot setexeccon('%s'): %s\n", svc->seclabel, strerror(errno));
316                _exit(127);
317            }
318        }
319
320        if (!dynamic_args) {
321            if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
322                ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
323            }
324        } else {
325            char *arg_ptrs[INIT_PARSER_MAXARGS+1];
326            int arg_idx = svc->nargs;
327            char *tmp = strdup(dynamic_args);
328            char *next = tmp;
329            char *bword;
330
331            /* Copy the static arguments */
332            memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));
333
334            while((bword = strsep(&next, " "))) {
335                arg_ptrs[arg_idx++] = bword;
336                if (arg_idx == INIT_PARSER_MAXARGS)
337                    break;
338            }
339            arg_ptrs[arg_idx] = '\0';
340            execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
341        }
342        _exit(127);
343    }
344
345    freecon(scon);
346
347    if (pid < 0) {
348        ERROR("failed to start '%s'\n", svc->name);
349        svc->pid = 0;
350        return;
351    }
352
353    svc->time_started = gettime();
354    svc->pid = pid;
355    svc->flags |= SVC_RUNNING;
356
357    if (properties_inited())
358        notify_service_state(svc->name, "running");
359}
360
361/* The how field should be either SVC_DISABLED or SVC_RESET */
362static void service_stop_or_reset(struct service *svc, int how)
363{
364        /* we are no longer running, nor should we
365         * attempt to restart
366         */
367    svc->flags &= (~(SVC_RUNNING|SVC_RESTARTING));
368
369    if ((how != SVC_DISABLED) && (how != SVC_RESET)) {
370        /* Hrm, an illegal flag.  Default to SVC_DISABLED */
371        how = SVC_DISABLED;
372    }
373        /* if the service has not yet started, prevent
374         * it from auto-starting with its class
375         */
376    if (how == SVC_RESET) {
377        svc->flags |= (svc->flags & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
378    } else {
379        svc->flags |= how;
380    }
381
382    if (svc->pid) {
383        NOTICE("service '%s' is being killed\n", svc->name);
384        kill(-svc->pid, SIGKILL);
385        notify_service_state(svc->name, "stopping");
386    } else {
387        notify_service_state(svc->name, "stopped");
388    }
389}
390
391void service_reset(struct service *svc)
392{
393    service_stop_or_reset(svc, SVC_RESET);
394}
395
396void service_stop(struct service *svc)
397{
398    service_stop_or_reset(svc, SVC_DISABLED);
399}
400
401void property_changed(const char *name, const char *value)
402{
403    if (property_triggers_enabled)
404        queue_property_triggers(name, value);
405}
406
407static void restart_service_if_needed(struct service *svc)
408{
409    time_t next_start_time = svc->time_started + 5;
410
411    if (next_start_time <= gettime()) {
412        svc->flags &= (~SVC_RESTARTING);
413        service_start(svc, NULL);
414        return;
415    }
416
417    if ((next_start_time < process_needs_restart) ||
418        (process_needs_restart == 0)) {
419        process_needs_restart = next_start_time;
420    }
421}
422
423static void restart_processes()
424{
425    process_needs_restart = 0;
426    service_for_each_flags(SVC_RESTARTING,
427                           restart_service_if_needed);
428}
429
430static void msg_start(const char *name)
431{
432    struct service *svc = NULL;
433    char *tmp = NULL;
434    char *args = NULL;
435
436    if (!strchr(name, ':'))
437        svc = service_find_by_name(name);
438    else {
439        tmp = strdup(name);
440        if (tmp) {
441            args = strchr(tmp, ':');
442            *args = '\0';
443            args++;
444
445            svc = service_find_by_name(tmp);
446        }
447    }
448
449    if (svc) {
450        service_start(svc, args);
451    } else {
452        ERROR("no such service '%s'\n", name);
453    }
454    if (tmp)
455        free(tmp);
456}
457
458static void msg_stop(const char *name)
459{
460    struct service *svc = service_find_by_name(name);
461
462    if (svc) {
463        service_stop(svc);
464    } else {
465        ERROR("no such service '%s'\n", name);
466    }
467}
468
469void handle_control_message(const char *msg, const char *arg)
470{
471    if (!strcmp(msg,"start")) {
472        msg_start(arg);
473    } else if (!strcmp(msg,"stop")) {
474        msg_stop(arg);
475    } else if (!strcmp(msg,"restart")) {
476        msg_stop(arg);
477        msg_start(arg);
478    } else {
479        ERROR("unknown control msg '%s'\n", msg);
480    }
481}
482
483static struct command *get_first_command(struct action *act)
484{
485    struct listnode *node;
486    node = list_head(&act->commands);
487    if (!node || list_empty(&act->commands))
488        return NULL;
489
490    return node_to_item(node, struct command, clist);
491}
492
493static struct command *get_next_command(struct action *act, struct command *cmd)
494{
495    struct listnode *node;
496    node = cmd->clist.next;
497    if (!node)
498        return NULL;
499    if (node == &act->commands)
500        return NULL;
501
502    return node_to_item(node, struct command, clist);
503}
504
505static int is_last_command(struct action *act, struct command *cmd)
506{
507    return (list_tail(&act->commands) == &cmd->clist);
508}
509
510void execute_one_command(void)
511{
512    int ret;
513
514    if (!cur_action || !cur_command || is_last_command(cur_action, cur_command)) {
515        cur_action = action_remove_queue_head();
516        cur_command = NULL;
517        if (!cur_action)
518            return;
519        INFO("processing action %p (%s)\n", cur_action, cur_action->name);
520        cur_command = get_first_command(cur_action);
521    } else {
522        cur_command = get_next_command(cur_action, cur_command);
523    }
524
525    if (!cur_command)
526        return;
527
528    ret = cur_command->func(cur_command->nargs, cur_command->args);
529    INFO("command '%s' r=%d\n", cur_command->args[0], ret);
530}
531
532static int wait_for_coldboot_done_action(int nargs, char **args)
533{
534    int ret;
535    INFO("wait for %s\n", coldboot_done);
536    ret = wait_for_file(coldboot_done, COMMAND_RETRY_TIMEOUT);
537    if (ret)
538        ERROR("Timed out waiting for %s\n", coldboot_done);
539    return ret;
540}
541
542static int keychord_init_action(int nargs, char **args)
543{
544    keychord_init();
545    return 0;
546}
547
548static int console_init_action(int nargs, char **args)
549{
550    int fd;
551
552    if (console[0]) {
553        snprintf(console_name, sizeof(console_name), "/dev/%s", console);
554    }
555
556    fd = open(console_name, O_RDWR);
557    if (fd >= 0)
558        have_console = 1;
559    close(fd);
560
561    if( load_565rle_image(INIT_IMAGE_FILE) ) {
562        fd = open("/dev/tty0", O_WRONLY);
563        if (fd >= 0) {
564            const char *msg;
565                msg = "\n"
566            "\n"
567            "\n"
568            "\n"
569            "\n"
570            "\n"
571            "\n"  // console is 40 cols x 30 lines
572            "\n"
573            "\n"
574            "\n"
575            "\n"
576            "\n"
577            "\n"
578            "\n"
579            "             A N D R O I D ";
580            write(fd, msg, strlen(msg));
581            close(fd);
582        }
583    }
584    return 0;
585}
586
587static void import_kernel_nv(char *name, int for_emulator)
588{
589    char *value = strchr(name, '=');
590    int name_len = strlen(name);
591
592    if (value == 0) return;
593    *value++ = 0;
594    if (name_len == 0) return;
595
596    if (for_emulator) {
597        /* in the emulator, export any kernel option with the
598         * ro.kernel. prefix */
599        char buff[PROP_NAME_MAX];
600        int len = snprintf( buff, sizeof(buff), "ro.kernel.%s", name );
601
602        if (len < (int)sizeof(buff))
603            property_set( buff, value );
604        return;
605    }
606
607    if (!strcmp(name,"qemu")) {
608        strlcpy(qemu, value, sizeof(qemu));
609    } else if (!strncmp(name, "androidboot.", 12) && name_len > 12) {
610        const char *boot_prop_name = name + 12;
611        char prop[PROP_NAME_MAX];
612        int cnt;
613
614        cnt = snprintf(prop, sizeof(prop), "ro.boot.%s", boot_prop_name);
615        if (cnt < PROP_NAME_MAX)
616            property_set(prop, value);
617    }
618}
619
620static void export_kernel_boot_props(void)
621{
622    char tmp[PROP_VALUE_MAX];
623    int ret;
624    unsigned i;
625    struct {
626        const char *src_prop;
627        const char *dest_prop;
628        const char *def_val;
629    } prop_map[] = {
630        { "ro.boot.serialno", "ro.serialno", "", },
631        { "ro.boot.mode", "ro.bootmode", "unknown", },
632        { "ro.boot.baseband", "ro.baseband", "unknown", },
633        { "ro.boot.bootloader", "ro.bootloader", "unknown", },
634    };
635
636    for (i = 0; i < ARRAY_SIZE(prop_map); i++) {
637        ret = property_get(prop_map[i].src_prop, tmp);
638        if (ret > 0)
639            property_set(prop_map[i].dest_prop, tmp);
640        else
641            property_set(prop_map[i].dest_prop, prop_map[i].def_val);
642    }
643
644    ret = property_get("ro.boot.console", tmp);
645    if (ret)
646        strlcpy(console, tmp, sizeof(console));
647
648    /* save a copy for init's usage during boot */
649    property_get("ro.bootmode", tmp);
650    strlcpy(bootmode, tmp, sizeof(bootmode));
651
652    /* if this was given on kernel command line, override what we read
653     * before (e.g. from /proc/cpuinfo), if anything */
654    ret = property_get("ro.boot.hardware", tmp);
655    if (ret)
656        strlcpy(hardware, tmp, sizeof(hardware));
657    property_set("ro.hardware", hardware);
658
659    snprintf(tmp, PROP_VALUE_MAX, "%d", revision);
660    property_set("ro.revision", tmp);
661
662    /* TODO: these are obsolete. We should delete them */
663    if (!strcmp(bootmode,"factory"))
664        property_set("ro.factorytest", "1");
665    else if (!strcmp(bootmode,"factory2"))
666        property_set("ro.factorytest", "2");
667    else
668        property_set("ro.factorytest", "0");
669}
670
671static void process_kernel_cmdline(void)
672{
673    /* don't expose the raw commandline to nonpriv processes */
674    chmod("/proc/cmdline", 0440);
675
676    /* first pass does the common stuff, and finds if we are in qemu.
677     * second pass is only necessary for qemu to export all kernel params
678     * as props.
679     */
680    import_kernel_cmdline(0, import_kernel_nv);
681    if (qemu[0])
682        import_kernel_cmdline(1, import_kernel_nv);
683
684    /* now propogate the info given on command line to internal variables
685     * used by init as well as the current required properties
686     */
687    export_kernel_boot_props();
688}
689
690static int property_service_init_action(int nargs, char **args)
691{
692    /* read any property files on system or data and
693     * fire up the property service.  This must happen
694     * after the ro.foo properties are set above so
695     * that /data/local.prop cannot interfere with them.
696     */
697    start_property_service();
698    return 0;
699}
700
701static int signal_init_action(int nargs, char **args)
702{
703    signal_init();
704    return 0;
705}
706
707static int check_startup_action(int nargs, char **args)
708{
709    /* make sure we actually have all the pieces we need */
710    if ((get_property_set_fd() < 0) ||
711        (get_signal_fd() < 0)) {
712        ERROR("init startup failure\n");
713        exit(1);
714    }
715
716        /* signal that we hit this point */
717    unlink("/dev/.booting");
718
719    return 0;
720}
721
722static int queue_property_triggers_action(int nargs, char **args)
723{
724    queue_all_property_triggers();
725    /* enable property triggers */
726    property_triggers_enabled = 1;
727    return 0;
728}
729
730#if BOOTCHART
731static int bootchart_init_action(int nargs, char **args)
732{
733    bootchart_count = bootchart_init();
734    if (bootchart_count < 0) {
735        ERROR("bootcharting init failure\n");
736    } else if (bootchart_count > 0) {
737        NOTICE("bootcharting started (period=%d ms)\n", bootchart_count*BOOTCHART_POLLING_MS);
738    } else {
739        NOTICE("bootcharting ignored\n");
740    }
741
742    return 0;
743}
744#endif
745
746static const struct selinux_opt seopts_prop[] = {
747        { SELABEL_OPT_PATH, "/data/security/property_contexts" },
748        { SELABEL_OPT_PATH, "/property_contexts" },
749        { 0, NULL }
750};
751
752struct selabel_handle* selinux_android_prop_context_handle(void)
753{
754    int i = 0;
755    struct selabel_handle* sehandle = NULL;
756    while ((sehandle == NULL) && seopts_prop[i].value) {
757        sehandle = selabel_open(SELABEL_CTX_ANDROID_PROP, &seopts_prop[i], 1);
758        i++;
759    }
760
761    if (!sehandle) {
762        ERROR("SELinux:  Could not load property_contexts:  %s\n",
763              strerror(errno));
764        return NULL;
765    }
766    INFO("SELinux: Loaded property contexts from %s\n", seopts_prop[i - 1].value);
767    return sehandle;
768}
769
770void selinux_init_all_handles(void)
771{
772    sehandle = selinux_android_file_context_handle();
773    sehandle_prop = selinux_android_prop_context_handle();
774}
775
776int selinux_reload_policy(void)
777{
778    INFO("SELinux: Attempting to reload policy files\n");
779
780    if (selinux_android_reload_policy() == -1) {
781        return -1;
782    }
783
784    if (sehandle)
785        selabel_close(sehandle);
786
787    if (sehandle_prop)
788        selabel_close(sehandle_prop);
789
790    selinux_init_all_handles();
791    return 0;
792}
793
794int audit_callback(void *data, security_class_t cls, char *buf, size_t len)
795{
796    snprintf(buf, len, "property=%s", !data ? "NULL" : (char *)data);
797    return 0;
798}
799
800static void selinux_initialize(void)
801{
802    if (access("/sys/fs/selinux", F_OK) != 0) {
803        // SELinux is not compiled into this kernel. Fail gracefully.
804        return;
805    }
806
807    INFO("loading selinux policy\n");
808    if (selinux_android_load_policy() < 0) {
809        ERROR("SELinux: Failed to load policy; rebooting into recovery mode\n");
810        android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
811        while (1) { pause(); }  // never reached
812    }
813
814    selinux_init_all_handles();
815    security_setenforce(1);
816}
817
818int main(int argc, char **argv)
819{
820    int fd_count = 0;
821    struct pollfd ufds[4];
822    char *tmpdev;
823    char* debuggable;
824    char tmp[32];
825    int property_set_fd_init = 0;
826    int signal_fd_init = 0;
827    int keychord_fd_init = 0;
828    bool is_charger = false;
829
830    if (!strcmp(basename(argv[0]), "ueventd"))
831        return ueventd_main(argc, argv);
832
833    if (!strcmp(basename(argv[0]), "watchdogd"))
834        return watchdogd_main(argc, argv);
835
836    /* clear the umask */
837    umask(0);
838
839        /* Get the basic filesystem setup we need put
840         * together in the initramdisk on / and then we'll
841         * let the rc file figure out the rest.
842         */
843    mkdir("/dev", 0755);
844    mkdir("/proc", 0755);
845    mkdir("/sys", 0755);
846
847    mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
848    mkdir("/dev/pts", 0755);
849    mkdir("/dev/socket", 0755);
850    mount("devpts", "/dev/pts", "devpts", 0, NULL);
851    mount("proc", "/proc", "proc", 0, NULL);
852    mount("sysfs", "/sys", "sysfs", 0, NULL);
853
854        /* indicate that booting is in progress to background fw loaders, etc */
855    close(open("/dev/.booting", O_WRONLY | O_CREAT, 0000));
856
857        /* We must have some place other than / to create the
858         * device nodes for kmsg and null, otherwise we won't
859         * be able to remount / read-only later on.
860         * Now that tmpfs is mounted on /dev, we can actually
861         * talk to the outside world.
862         */
863    open_devnull_stdio();
864    klog_init();
865    property_init();
866
867    get_hardware_name(hardware, &revision);
868
869    process_kernel_cmdline();
870
871    union selinux_callback cb;
872    cb.func_log = klog_write;
873    selinux_set_callback(SELINUX_CB_LOG, cb);
874
875    cb.func_audit = audit_callback;
876    selinux_set_callback(SELINUX_CB_AUDIT, cb);
877
878    selinux_initialize();
879    /* These directories were necessarily created before initial policy load
880     * and therefore need their security context restored to the proper value.
881     * This must happen before /dev is populated by ueventd.
882     */
883    restorecon("/dev");
884    restorecon("/dev/socket");
885    restorecon("/dev/__properties__");
886
887    is_charger = !strcmp(bootmode, "charger");
888
889    INFO("property init\n");
890    if (!is_charger)
891        property_load_boot_defaults();
892
893    INFO("reading config file\n");
894    init_parse_config_file("/init.rc");
895
896    action_for_each_trigger("early-init", action_add_queue_tail);
897
898    queue_builtin_action(wait_for_coldboot_done_action, "wait_for_coldboot_done");
899    queue_builtin_action(keychord_init_action, "keychord_init");
900    queue_builtin_action(console_init_action, "console_init");
901
902    /* execute all the boot actions to get us started */
903    action_for_each_trigger("init", action_add_queue_tail);
904
905    /* skip mounting filesystems in charger mode */
906    if (!is_charger) {
907        action_for_each_trigger("early-fs", action_add_queue_tail);
908        action_for_each_trigger("fs", action_add_queue_tail);
909        action_for_each_trigger("post-fs", action_add_queue_tail);
910        action_for_each_trigger("post-fs-data", action_add_queue_tail);
911    }
912
913    queue_builtin_action(property_service_init_action, "property_service_init");
914    queue_builtin_action(signal_init_action, "signal_init");
915    queue_builtin_action(check_startup_action, "check_startup");
916
917    if (is_charger) {
918        action_for_each_trigger("charger", action_add_queue_tail);
919    } else {
920        action_for_each_trigger("early-boot", action_add_queue_tail);
921        action_for_each_trigger("boot", action_add_queue_tail);
922    }
923
924        /* run all property triggers based on current state of the properties */
925    queue_builtin_action(queue_property_triggers_action, "queue_property_triggers");
926
927
928#if BOOTCHART
929    queue_builtin_action(bootchart_init_action, "bootchart_init");
930#endif
931
932    for(;;) {
933        int nr, i, timeout = -1;
934
935        execute_one_command();
936        restart_processes();
937
938        if (!property_set_fd_init && get_property_set_fd() > 0) {
939            ufds[fd_count].fd = get_property_set_fd();
940            ufds[fd_count].events = POLLIN;
941            ufds[fd_count].revents = 0;
942            fd_count++;
943            property_set_fd_init = 1;
944        }
945        if (!signal_fd_init && get_signal_fd() > 0) {
946            ufds[fd_count].fd = get_signal_fd();
947            ufds[fd_count].events = POLLIN;
948            ufds[fd_count].revents = 0;
949            fd_count++;
950            signal_fd_init = 1;
951        }
952        if (!keychord_fd_init && get_keychord_fd() > 0) {
953            ufds[fd_count].fd = get_keychord_fd();
954            ufds[fd_count].events = POLLIN;
955            ufds[fd_count].revents = 0;
956            fd_count++;
957            keychord_fd_init = 1;
958        }
959
960        if (process_needs_restart) {
961            timeout = (process_needs_restart - gettime()) * 1000;
962            if (timeout < 0)
963                timeout = 0;
964        }
965
966        if (!action_queue_empty() || cur_action)
967            timeout = 0;
968
969#if BOOTCHART
970        if (bootchart_count > 0) {
971            if (timeout < 0 || timeout > BOOTCHART_POLLING_MS)
972                timeout = BOOTCHART_POLLING_MS;
973            if (bootchart_step() < 0 || --bootchart_count == 0) {
974                bootchart_finish();
975                bootchart_count = 0;
976            }
977        }
978#endif
979
980        nr = poll(ufds, fd_count, timeout);
981        if (nr <= 0)
982            continue;
983
984        for (i = 0; i < fd_count; i++) {
985            if (ufds[i].revents == POLLIN) {
986                if (ufds[i].fd == get_property_set_fd())
987                    handle_property_set_fd();
988                else if (ufds[i].fd == get_keychord_fd())
989                    handle_keychord();
990                else if (ufds[i].fd == get_signal_fd())
991                    handle_signal();
992            }
993        }
994    }
995
996    return 0;
997}
998