init.c revision 7a36210cdb39bde3a7d73095d5891678685e431f
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 <time.h>
29#include <errno.h>
30#include <stdarg.h>
31#include <mtd/mtd-user.h>
32#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/un.h>
35#include <sys/reboot.h>
36
37#include <cutils/sockets.h>
38#include <termios.h>
39#include <linux/kd.h>
40#include <linux/keychord.h>
41
42#include <sys/system_properties.h>
43
44#include "devices.h"
45#include "init.h"
46#include "property_service.h"
47#include "bootchart.h"
48
49static int property_triggers_enabled = 0;
50
51#if BOOTCHART
52static int   bootchart_count;
53#endif
54
55static char console[32];
56static char serialno[32];
57static char bootmode[32];
58static char baseband[32];
59static char carrier[32];
60static char bootloader[32];
61static char hardware[32];
62static unsigned revision = 0;
63static char qemu[32];
64static struct input_keychord *keychords = 0;
65static int keychords_count = 0;
66static int keychords_length = 0;
67
68static void notify_service_state(const char *name, const char *state)
69{
70    char pname[PROP_NAME_MAX];
71    int len = strlen(name);
72    if ((len + 10) > PROP_NAME_MAX)
73        return;
74    snprintf(pname, sizeof(pname), "init.svc.%s", name);
75    property_set(pname, state);
76}
77
78static int have_console;
79static char *console_name = "/dev/console";
80static time_t process_needs_restart;
81
82static const char *ENV[32];
83
84/* add_environment - add "key=value" to the current environment */
85int add_environment(const char *key, const char *val)
86{
87    int n;
88
89    for (n = 0; n < 31; n++) {
90        if (!ENV[n]) {
91            size_t len = strlen(key) + strlen(val) + 2;
92            char *entry = malloc(len);
93            snprintf(entry, len, "%s=%s", key, val);
94            ENV[n] = entry;
95            return 0;
96        }
97    }
98
99    return 1;
100}
101
102static void zap_stdio(void)
103{
104    int fd;
105    fd = open("/dev/null", O_RDWR);
106    dup2(fd, 0);
107    dup2(fd, 1);
108    dup2(fd, 2);
109    close(fd);
110}
111
112static void open_console()
113{
114    int fd;
115    if ((fd = open(console_name, O_RDWR)) < 0) {
116        fd = open("/dev/null", O_RDWR);
117    }
118    dup2(fd, 0);
119    dup2(fd, 1);
120    dup2(fd, 2);
121    close(fd);
122}
123
124/*
125 * gettime() - returns the time in seconds of the system's monotonic clock or
126 * zero on error.
127 */
128static time_t gettime(void)
129{
130    struct timespec ts;
131    int ret;
132
133    ret = clock_gettime(CLOCK_MONOTONIC, &ts);
134    if (ret < 0) {
135        ERROR("clock_gettime(CLOCK_MONOTONIC) failed: %s\n", strerror(errno));
136        return 0;
137    }
138
139    return ts.tv_sec;
140}
141
142static void publish_socket(const char *name, int fd)
143{
144    char key[64] = ANDROID_SOCKET_ENV_PREFIX;
145    char val[64];
146
147    strlcpy(key + sizeof(ANDROID_SOCKET_ENV_PREFIX) - 1,
148            name,
149            sizeof(key) - sizeof(ANDROID_SOCKET_ENV_PREFIX));
150    snprintf(val, sizeof(val), "%d", fd);
151    add_environment(key, val);
152
153    /* make sure we don't close-on-exec */
154    fcntl(fd, F_SETFD, 0);
155}
156
157void service_start(struct service *svc, const char *dynamic_args)
158{
159    struct stat s;
160    pid_t pid;
161    int needs_console;
162    int n;
163
164        /* starting a service removes it from the disabled
165         * state and immediately takes it out of the restarting
166         * state if it was in there
167         */
168    svc->flags &= (~(SVC_DISABLED|SVC_RESTARTING));
169    svc->time_started = 0;
170
171        /* running processes require no additional work -- if
172         * they're in the process of exiting, we've ensured
173         * that they will immediately restart on exit, unless
174         * they are ONESHOT
175         */
176    if (svc->flags & SVC_RUNNING) {
177        return;
178    }
179
180    needs_console = (svc->flags & SVC_CONSOLE) ? 1 : 0;
181    if (needs_console && (!have_console)) {
182        ERROR("service '%s' requires console\n", svc->name);
183        svc->flags |= SVC_DISABLED;
184        return;
185    }
186
187    if (stat(svc->args[0], &s) != 0) {
188        ERROR("cannot find '%s', disabling '%s'\n", svc->args[0], svc->name);
189        svc->flags |= SVC_DISABLED;
190        return;
191    }
192
193    if ((!(svc->flags & SVC_ONESHOT)) && dynamic_args) {
194        ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
195               svc->args[0]);
196        svc->flags |= SVC_DISABLED;
197        return;
198    }
199
200    NOTICE("starting '%s'\n", svc->name);
201
202    pid = fork();
203
204    if (pid == 0) {
205        struct socketinfo *si;
206        struct svcenvinfo *ei;
207        char tmp[32];
208        int fd, sz;
209
210        get_property_workspace(&fd, &sz);
211        sprintf(tmp, "%d,%d", dup(fd), sz);
212        add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);
213
214        for (ei = svc->envvars; ei; ei = ei->next)
215            add_environment(ei->name, ei->value);
216
217        for (si = svc->sockets; si; si = si->next) {
218            int s = create_socket(si->name,
219                                  !strcmp(si->type, "dgram") ?
220                                  SOCK_DGRAM : SOCK_STREAM,
221                                  si->perm, si->uid, si->gid);
222            if (s >= 0) {
223                publish_socket(si->name, s);
224            }
225        }
226
227        if (needs_console) {
228            setsid();
229            open_console();
230        } else {
231            zap_stdio();
232        }
233
234#if 0
235        for (n = 0; svc->args[n]; n++) {
236            INFO("args[%d] = '%s'\n", n, svc->args[n]);
237        }
238        for (n = 0; ENV[n]; n++) {
239            INFO("env[%d] = '%s'\n", n, ENV[n]);
240        }
241#endif
242
243        setpgid(0, getpid());
244
245    /* as requested, set our gid, supplemental gids, and uid */
246        if (svc->gid) {
247            setgid(svc->gid);
248        }
249        if (svc->nr_supp_gids) {
250            setgroups(svc->nr_supp_gids, svc->supp_gids);
251        }
252        if (svc->uid) {
253            setuid(svc->uid);
254        }
255
256        if (!dynamic_args) {
257            if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
258                ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
259            }
260        } else {
261            char *arg_ptrs[SVC_MAXARGS+1];
262            int arg_idx = svc->nargs;
263            char *tmp = strdup(dynamic_args);
264            char *next = tmp;
265            char *bword;
266
267            /* Copy the static arguments */
268            memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));
269
270            while((bword = strsep(&next, " "))) {
271                arg_ptrs[arg_idx++] = bword;
272                if (arg_idx == SVC_MAXARGS)
273                    break;
274            }
275            arg_ptrs[arg_idx] = '\0';
276            execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
277        }
278        _exit(127);
279    }
280
281    if (pid < 0) {
282        ERROR("failed to start '%s'\n", svc->name);
283        svc->pid = 0;
284        return;
285    }
286
287    svc->time_started = gettime();
288    svc->pid = pid;
289    svc->flags |= SVC_RUNNING;
290
291    notify_service_state(svc->name, "running");
292}
293
294void service_stop(struct service *svc)
295{
296        /* we are no longer running, nor should we
297         * attempt to restart
298         */
299    svc->flags &= (~(SVC_RUNNING|SVC_RESTARTING));
300
301        /* if the service has not yet started, prevent
302         * it from auto-starting with its class
303         */
304    svc->flags |= SVC_DISABLED;
305
306    if (svc->pid) {
307        NOTICE("service '%s' is being killed\n", svc->name);
308        kill(-svc->pid, SIGTERM);
309        notify_service_state(svc->name, "stopping");
310    } else {
311        notify_service_state(svc->name, "stopped");
312    }
313}
314
315void property_changed(const char *name, const char *value)
316{
317    if (property_triggers_enabled) {
318        queue_property_triggers(name, value);
319        drain_action_queue();
320    }
321}
322
323#define CRITICAL_CRASH_THRESHOLD    4       /* if we crash >4 times ... */
324#define CRITICAL_CRASH_WINDOW       (4*60)  /* ... in 4 minutes, goto recovery*/
325
326static int wait_for_one_process(int block)
327{
328    pid_t pid;
329    int status;
330    struct service *svc;
331    struct socketinfo *si;
332    time_t now;
333    struct listnode *node;
334    struct command *cmd;
335
336    while ( (pid = waitpid(-1, &status, block ? 0 : WNOHANG)) == -1 && errno == EINTR );
337    if (pid <= 0) return -1;
338    INFO("waitpid returned pid %d, status = %08x\n", pid, status);
339
340    svc = service_find_by_pid(pid);
341    if (!svc) {
342        ERROR("untracked pid %d exited\n", pid);
343        return 0;
344    }
345
346    NOTICE("process '%s', pid %d exited\n", svc->name, pid);
347
348    if (!(svc->flags & SVC_ONESHOT)) {
349        kill(-pid, SIGKILL);
350        NOTICE("process '%s' killing any children in process group\n", svc->name);
351    }
352
353    /* remove any sockets we may have created */
354    for (si = svc->sockets; si; si = si->next) {
355        char tmp[128];
356        snprintf(tmp, sizeof(tmp), ANDROID_SOCKET_DIR"/%s", si->name);
357        unlink(tmp);
358    }
359
360    svc->pid = 0;
361    svc->flags &= (~SVC_RUNNING);
362
363        /* oneshot processes go into the disabled state on exit */
364    if (svc->flags & SVC_ONESHOT) {
365        svc->flags |= SVC_DISABLED;
366    }
367
368        /* disabled processes do not get restarted automatically */
369    if (svc->flags & SVC_DISABLED) {
370        notify_service_state(svc->name, "stopped");
371        return 0;
372    }
373
374    now = gettime();
375    if (svc->flags & SVC_CRITICAL) {
376        if (svc->time_crashed + CRITICAL_CRASH_WINDOW >= now) {
377            if (++svc->nr_crashed > CRITICAL_CRASH_THRESHOLD) {
378                ERROR("critical process '%s' exited %d times in %d minutes; "
379                      "rebooting into recovery mode\n", svc->name,
380                      CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
381                sync();
382                __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
383                         LINUX_REBOOT_CMD_RESTART2, "recovery");
384                return 0;
385            }
386        } else {
387            svc->time_crashed = now;
388            svc->nr_crashed = 1;
389        }
390    }
391
392    svc->flags |= SVC_RESTARTING;
393
394    /* Execute all onrestart commands for this service. */
395    list_for_each(node, &svc->onrestart.commands) {
396        cmd = node_to_item(node, struct command, clist);
397        cmd->func(cmd->nargs, cmd->args);
398    }
399    notify_service_state(svc->name, "restarting");
400    return 0;
401}
402
403static void restart_service_if_needed(struct service *svc)
404{
405    time_t next_start_time = svc->time_started + 5;
406
407    if (next_start_time <= gettime()) {
408        svc->flags &= (~SVC_RESTARTING);
409        service_start(svc, NULL);
410        return;
411    }
412
413    if ((next_start_time < process_needs_restart) ||
414        (process_needs_restart == 0)) {
415        process_needs_restart = next_start_time;
416    }
417}
418
419static void restart_processes()
420{
421    process_needs_restart = 0;
422    service_for_each_flags(SVC_RESTARTING,
423                           restart_service_if_needed);
424}
425
426static int signal_fd = -1;
427
428static void sigchld_handler(int s)
429{
430    write(signal_fd, &s, 1);
431}
432
433static void msg_start(const char *name)
434{
435    struct service *svc;
436    char *tmp = NULL;
437    char *args = NULL;
438
439    if (!strchr(name, ':'))
440        svc = service_find_by_name(name);
441    else {
442        tmp = strdup(name);
443        args = strchr(tmp, ':');
444        *args = '\0';
445        args++;
446
447        svc = service_find_by_name(tmp);
448    }
449
450    if (svc) {
451        service_start(svc, args);
452    } else {
453        ERROR("no such service '%s'\n", name);
454    }
455    if (tmp)
456        free(tmp);
457}
458
459static void msg_stop(const char *name)
460{
461    struct service *svc = service_find_by_name(name);
462
463    if (svc) {
464        service_stop(svc);
465    } else {
466        ERROR("no such service '%s'\n", name);
467    }
468}
469
470void handle_control_message(const char *msg, const char *arg)
471{
472    if (!strcmp(msg,"start")) {
473        msg_start(arg);
474    } else if (!strcmp(msg,"stop")) {
475        msg_stop(arg);
476    } else {
477        ERROR("unknown control msg '%s'\n", msg);
478    }
479}
480
481#define MAX_MTD_PARTITIONS 16
482
483static struct {
484    char name[16];
485    int number;
486} mtd_part_map[MAX_MTD_PARTITIONS];
487
488static int mtd_part_count = -1;
489
490static void find_mtd_partitions(void)
491{
492    int fd;
493    char buf[1024];
494    char *pmtdbufp;
495    ssize_t pmtdsize;
496    int r;
497
498    fd = open("/proc/mtd", O_RDONLY);
499    if (fd < 0)
500        return;
501
502    buf[sizeof(buf) - 1] = '\0';
503    pmtdsize = read(fd, buf, sizeof(buf) - 1);
504    pmtdbufp = buf;
505    while (pmtdsize > 0) {
506        int mtdnum, mtdsize, mtderasesize;
507        char mtdname[16];
508        mtdname[0] = '\0';
509        mtdnum = -1;
510        r = sscanf(pmtdbufp, "mtd%d: %x %x %15s",
511                   &mtdnum, &mtdsize, &mtderasesize, mtdname);
512        if ((r == 4) && (mtdname[0] == '"')) {
513            char *x = strchr(mtdname + 1, '"');
514            if (x) {
515                *x = 0;
516            }
517            INFO("mtd partition %d, %s\n", mtdnum, mtdname + 1);
518            if (mtd_part_count < MAX_MTD_PARTITIONS) {
519                strcpy(mtd_part_map[mtd_part_count].name, mtdname + 1);
520                mtd_part_map[mtd_part_count].number = mtdnum;
521                mtd_part_count++;
522            } else {
523                ERROR("too many mtd partitions\n");
524            }
525        }
526        while (pmtdsize > 0 && *pmtdbufp != '\n') {
527            pmtdbufp++;
528            pmtdsize--;
529        }
530        if (pmtdsize > 0) {
531            pmtdbufp++;
532            pmtdsize--;
533        }
534    }
535    close(fd);
536}
537
538int mtd_name_to_number(const char *name)
539{
540    int n;
541    if (mtd_part_count < 0) {
542        mtd_part_count = 0;
543        find_mtd_partitions();
544    }
545    for (n = 0; n < mtd_part_count; n++) {
546        if (!strcmp(name, mtd_part_map[n].name)) {
547            return mtd_part_map[n].number;
548        }
549    }
550    return -1;
551}
552
553static void import_kernel_nv(char *name, int in_qemu)
554{
555    char *value = strchr(name, '=');
556
557    if (value == 0) return;
558    *value++ = 0;
559    if (*name == 0) return;
560
561    if (!in_qemu)
562    {
563        /* on a real device, white-list the kernel options */
564        if (!strcmp(name,"qemu")) {
565            strlcpy(qemu, value, sizeof(qemu));
566        } else if (!strcmp(name,"androidboot.console")) {
567            strlcpy(console, value, sizeof(console));
568        } else if (!strcmp(name,"androidboot.mode")) {
569            strlcpy(bootmode, value, sizeof(bootmode));
570        } else if (!strcmp(name,"androidboot.serialno")) {
571            strlcpy(serialno, value, sizeof(serialno));
572        } else if (!strcmp(name,"androidboot.baseband")) {
573            strlcpy(baseband, value, sizeof(baseband));
574        } else if (!strcmp(name,"androidboot.carrier")) {
575            strlcpy(carrier, value, sizeof(carrier));
576        } else if (!strcmp(name,"androidboot.bootloader")) {
577            strlcpy(bootloader, value, sizeof(bootloader));
578        } else if (!strcmp(name,"androidboot.hardware")) {
579            strlcpy(hardware, value, sizeof(hardware));
580        } else {
581            qemu_cmdline(name, value);
582        }
583    } else {
584        /* in the emulator, export any kernel option with the
585         * ro.kernel. prefix */
586        char  buff[32];
587        int   len = snprintf( buff, sizeof(buff), "ro.kernel.%s", name );
588        if (len < (int)sizeof(buff)) {
589            property_set( buff, value );
590        }
591    }
592}
593
594static void import_kernel_cmdline(int in_qemu)
595{
596    char cmdline[1024];
597    char *ptr;
598    int fd;
599
600    fd = open("/proc/cmdline", O_RDONLY);
601    if (fd >= 0) {
602        int n = read(fd, cmdline, 1023);
603        if (n < 0) n = 0;
604
605        /* get rid of trailing newline, it happens */
606        if (n > 0 && cmdline[n-1] == '\n') n--;
607
608        cmdline[n] = 0;
609        close(fd);
610    } else {
611        cmdline[0] = 0;
612    }
613
614    ptr = cmdline;
615    while (ptr && *ptr) {
616        char *x = strchr(ptr, ' ');
617        if (x != 0) *x++ = 0;
618        import_kernel_nv(ptr, in_qemu);
619        ptr = x;
620    }
621
622        /* don't expose the raw commandline to nonpriv processes */
623    chmod("/proc/cmdline", 0440);
624}
625
626static void get_hardware_name(void)
627{
628    char data[1024];
629    int fd, n;
630    char *x, *hw, *rev;
631
632    /* Hardware string was provided on kernel command line */
633    if (hardware[0])
634        return;
635
636    fd = open("/proc/cpuinfo", O_RDONLY);
637    if (fd < 0) return;
638
639    n = read(fd, data, 1023);
640    close(fd);
641    if (n < 0) return;
642
643    data[n] = 0;
644    hw = strstr(data, "\nHardware");
645    rev = strstr(data, "\nRevision");
646
647    if (hw) {
648        x = strstr(hw, ": ");
649        if (x) {
650            x += 2;
651            n = 0;
652            while (*x && !isspace(*x)) {
653                hardware[n++] = tolower(*x);
654                x++;
655                if (n == 31) break;
656            }
657            hardware[n] = 0;
658        }
659    }
660
661    if (rev) {
662        x = strstr(rev, ": ");
663        if (x) {
664            revision = strtoul(x + 2, 0, 16);
665        }
666    }
667}
668
669void drain_action_queue(void)
670{
671    struct listnode *node;
672    struct command *cmd;
673    struct action *act;
674    int ret;
675
676    while ((act = action_remove_queue_head())) {
677        INFO("processing action %p (%s)\n", act, act->name);
678        list_for_each(node, &act->commands) {
679            cmd = node_to_item(node, struct command, clist);
680            ret = cmd->func(cmd->nargs, cmd->args);
681            INFO("command '%s' r=%d\n", cmd->args[0], ret);
682        }
683    }
684}
685
686void open_devnull_stdio(void)
687{
688    int fd;
689    static const char *name = "/dev/__null__";
690    if (mknod(name, S_IFCHR | 0600, (1 << 8) | 3) == 0) {
691        fd = open(name, O_RDWR);
692        unlink(name);
693        if (fd >= 0) {
694            dup2(fd, 0);
695            dup2(fd, 1);
696            dup2(fd, 2);
697            if (fd > 2) {
698                close(fd);
699            }
700            return;
701        }
702    }
703
704    exit(1);
705}
706
707void add_service_keycodes(struct service *svc)
708{
709    struct input_keychord *keychord;
710    int i, size;
711
712    if (svc->keycodes) {
713        /* add a new keychord to the list */
714        size = sizeof(*keychord) + svc->nkeycodes * sizeof(keychord->keycodes[0]);
715        keychords = realloc(keychords, keychords_length + size);
716        if (!keychords) {
717            ERROR("could not allocate keychords\n");
718            keychords_length = 0;
719            keychords_count = 0;
720            return;
721        }
722
723        keychord = (struct input_keychord *)((char *)keychords + keychords_length);
724        keychord->version = KEYCHORD_VERSION;
725        keychord->id = keychords_count + 1;
726        keychord->count = svc->nkeycodes;
727        svc->keychord_id = keychord->id;
728
729        for (i = 0; i < svc->nkeycodes; i++) {
730            keychord->keycodes[i] = svc->keycodes[i];
731        }
732        keychords_count++;
733        keychords_length += size;
734    }
735}
736
737int open_keychord()
738{
739    int fd, ret;
740
741    service_for_each(add_service_keycodes);
742
743    /* nothing to do if no services require keychords */
744    if (!keychords)
745        return -1;
746
747    fd = open("/dev/keychord", O_RDWR);
748    if (fd < 0) {
749        ERROR("could not open /dev/keychord\n");
750        return fd;
751    }
752    fcntl(fd, F_SETFD, FD_CLOEXEC);
753
754    ret = write(fd, keychords, keychords_length);
755    if (ret != keychords_length) {
756        ERROR("could not configure /dev/keychord %d (%d)\n", ret, errno);
757        close(fd);
758        fd = -1;
759    }
760
761    free(keychords);
762    keychords = 0;
763
764    return fd;
765}
766
767void handle_keychord(int fd)
768{
769    struct service *svc;
770    char* debuggable;
771    char* adb_enabled;
772    int ret;
773    __u16 id;
774
775    // only handle keychords if ro.debuggable is set or adb is enabled.
776    // the logic here is that bugreports should be enabled in userdebug or eng builds
777    // and on user builds for users that are developers.
778    debuggable = property_get("ro.debuggable");
779    adb_enabled = property_get("init.svc.adbd");
780    if ((debuggable && !strcmp(debuggable, "1")) ||
781        (adb_enabled && !strcmp(adb_enabled, "running"))) {
782        ret = read(fd, &id, sizeof(id));
783        if (ret != sizeof(id)) {
784            ERROR("could not read keychord id\n");
785            return;
786        }
787
788        svc = service_find_by_keychord(id);
789        if (svc) {
790            INFO("starting service %s from keychord\n", svc->name);
791            service_start(svc, NULL);
792        } else {
793            ERROR("service for keychord %d not found\n", id);
794        }
795    }
796}
797
798int main(int argc, char **argv)
799{
800    int device_fd = -1;
801    int property_set_fd = -1;
802    int signal_recv_fd = -1;
803    int keychord_fd = -1;
804    int fd_count;
805    int s[2];
806    int fd;
807    struct sigaction act;
808    char tmp[PROP_VALUE_MAX];
809    struct pollfd ufds[4];
810    char *tmpdev;
811    char* debuggable;
812
813    act.sa_handler = sigchld_handler;
814    act.sa_flags = SA_NOCLDSTOP;
815    act.sa_mask = 0;
816    act.sa_restorer = NULL;
817    sigaction(SIGCHLD, &act, 0);
818
819    /* clear the umask */
820    umask(0);
821
822        /* Get the basic filesystem setup we need put
823         * together in the initramdisk on / and then we'll
824         * let the rc file figure out the rest.
825         */
826    mkdir("/dev", 0755);
827    mkdir("/proc", 0755);
828    mkdir("/sys", 0755);
829
830    mount("tmpfs", "/dev", "tmpfs", 0, "mode=0755");
831    mkdir("/dev/pts", 0755);
832    mkdir("/dev/socket", 0755);
833    mount("devpts", "/dev/pts", "devpts", 0, NULL);
834    mount("proc", "/proc", "proc", 0, NULL);
835    mount("sysfs", "/sys", "sysfs", 0, NULL);
836
837        /* We must have some place other than / to create the
838         * device nodes for kmsg and null, otherwise we won't
839         * be able to remount / read-only later on.
840         * Now that tmpfs is mounted on /dev, we can actually
841         * talk to the outside world.
842         */
843    open_devnull_stdio();
844    log_init();
845
846    INFO("reading config file\n");
847    parse_config_file("/init.rc");
848
849    /* pull the kernel commandline and ramdisk properties file in */
850    qemu_init();
851    import_kernel_cmdline(0);
852
853    get_hardware_name();
854    snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);
855    parse_config_file(tmp);
856
857    action_for_each_trigger("early-init", action_add_queue_tail);
858    drain_action_queue();
859
860    INFO("device init\n");
861    device_fd = device_init();
862
863    property_init();
864
865    // only listen for keychords if ro.debuggable is true
866    keychord_fd = open_keychord();
867
868    if (console[0]) {
869        snprintf(tmp, sizeof(tmp), "/dev/%s", console);
870        console_name = strdup(tmp);
871    }
872
873    fd = open(console_name, O_RDWR);
874    if (fd >= 0)
875        have_console = 1;
876    close(fd);
877
878    if( load_565rle_image(INIT_IMAGE_FILE) ) {
879    fd = open("/dev/tty0", O_WRONLY);
880    if (fd >= 0) {
881        const char *msg;
882            msg = "\n"
883        "\n"
884        "\n"
885        "\n"
886        "\n"
887        "\n"
888        "\n"  // console is 40 cols x 30 lines
889        "\n"
890        "\n"
891        "\n"
892        "\n"
893        "\n"
894        "\n"
895        "\n"
896        "             A N D R O I D ";
897        write(fd, msg, strlen(msg));
898        close(fd);
899    }
900    }
901
902    if (qemu[0])
903        import_kernel_cmdline(1);
904
905    if (!strcmp(bootmode,"factory"))
906        property_set("ro.factorytest", "1");
907    else if (!strcmp(bootmode,"factory2"))
908        property_set("ro.factorytest", "2");
909    else
910        property_set("ro.factorytest", "0");
911
912    property_set("ro.serialno", serialno[0] ? serialno : "");
913    property_set("ro.bootmode", bootmode[0] ? bootmode : "unknown");
914    property_set("ro.baseband", baseband[0] ? baseband : "unknown");
915    property_set("ro.carrier", carrier[0] ? carrier : "unknown");
916    property_set("ro.bootloader", bootloader[0] ? bootloader : "unknown");
917
918    property_set("ro.hardware", hardware);
919    snprintf(tmp, PROP_VALUE_MAX, "%d", revision);
920    property_set("ro.revision", tmp);
921
922        /* execute all the boot actions to get us started */
923    action_for_each_trigger("init", action_add_queue_tail);
924    drain_action_queue();
925
926        /* read any property files on system or data and
927         * fire up the property service.  This must happen
928         * after the ro.foo properties are set above so
929         * that /data/local.prop cannot interfere with them.
930         */
931    property_set_fd = start_property_service();
932
933    /* create a signalling mechanism for the sigchld handler */
934    if (socketpair(AF_UNIX, SOCK_STREAM, 0, s) == 0) {
935        signal_fd = s[0];
936        signal_recv_fd = s[1];
937        fcntl(s[0], F_SETFD, FD_CLOEXEC);
938        fcntl(s[0], F_SETFL, O_NONBLOCK);
939        fcntl(s[1], F_SETFD, FD_CLOEXEC);
940        fcntl(s[1], F_SETFL, O_NONBLOCK);
941    }
942
943    /* make sure we actually have all the pieces we need */
944    if ((device_fd < 0) ||
945        (property_set_fd < 0) ||
946        (signal_recv_fd < 0)) {
947        ERROR("init startup failure\n");
948        return 1;
949    }
950
951    /* execute all the boot actions to get us started */
952    action_for_each_trigger("early-boot", action_add_queue_tail);
953    action_for_each_trigger("boot", action_add_queue_tail);
954    drain_action_queue();
955
956        /* run all property triggers based on current state of the properties */
957    queue_all_property_triggers();
958    drain_action_queue();
959
960        /* enable property triggers */
961    property_triggers_enabled = 1;
962
963    ufds[0].fd = device_fd;
964    ufds[0].events = POLLIN;
965    ufds[1].fd = property_set_fd;
966    ufds[1].events = POLLIN;
967    ufds[2].fd = signal_recv_fd;
968    ufds[2].events = POLLIN;
969    fd_count = 3;
970
971    if (keychord_fd > 0) {
972        ufds[3].fd = keychord_fd;
973        ufds[3].events = POLLIN;
974        fd_count++;
975    } else {
976        ufds[3].events = 0;
977        ufds[3].revents = 0;
978    }
979
980#if BOOTCHART
981    bootchart_count = bootchart_init();
982    if (bootchart_count < 0) {
983        ERROR("bootcharting init failure\n");
984    } else if (bootchart_count > 0) {
985        NOTICE("bootcharting started (period=%d ms)\n", bootchart_count*BOOTCHART_POLLING_MS);
986    } else {
987        NOTICE("bootcharting ignored\n");
988    }
989#endif
990
991    for(;;) {
992        int nr, i, timeout = -1;
993
994        for (i = 0; i < fd_count; i++)
995            ufds[i].revents = 0;
996
997        drain_action_queue();
998        restart_processes();
999
1000        if (process_needs_restart) {
1001            timeout = (process_needs_restart - gettime()) * 1000;
1002            if (timeout < 0)
1003                timeout = 0;
1004        }
1005
1006#if BOOTCHART
1007        if (bootchart_count > 0) {
1008            if (timeout < 0 || timeout > BOOTCHART_POLLING_MS)
1009                timeout = BOOTCHART_POLLING_MS;
1010            if (bootchart_step() < 0 || --bootchart_count == 0) {
1011                bootchart_finish();
1012                bootchart_count = 0;
1013            }
1014        }
1015#endif
1016        nr = poll(ufds, fd_count, timeout);
1017        if (nr <= 0)
1018            continue;
1019
1020        if (ufds[2].revents == POLLIN) {
1021            /* we got a SIGCHLD - reap and restart as needed */
1022            read(signal_recv_fd, tmp, sizeof(tmp));
1023            while (!wait_for_one_process(0))
1024                ;
1025            continue;
1026        }
1027
1028        if (ufds[0].revents == POLLIN)
1029            handle_device_fd(device_fd);
1030
1031        if (ufds[1].revents == POLLIN)
1032            handle_property_set_fd(property_set_fd);
1033        if (ufds[3].revents == POLLIN)
1034            handle_keychord(keychord_fd);
1035    }
1036
1037    return 0;
1038}
1039