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