Create Service and ServiceManager classes

Change-Id: I363a5e4751ad83d2f4096882a6fbbeddca03acfe
diff --git a/init/Android.mk b/init/Android.mk
index 045e213..6737be4 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -48,6 +48,7 @@
     init_parser.cpp \
     log.cpp \
     parser.cpp \
+    service.cpp \
     util.cpp \
 
 LOCAL_STATIC_LIBRARIES := libbase
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 7848e10..470437c 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -44,20 +44,19 @@
 #include <private/android_filesystem_config.h>
 
 #include "action.h"
-#include "init.h"
-#include "keywords.h"
-#include "property_service.h"
 #include "devices.h"
+#include "init.h"
 #include "init_parser.h"
-#include "util.h"
+#include "keywords.h"
 #include "log.h"
+#include "property_service.h"
+#include "service.h"
+#include "util.h"
 
 #define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
 #define UNMOUNT_CHECK_MS 5000
 #define UNMOUNT_CHECK_TIMES 10
 
-int add_environment(const char *name, const char *value);
-
 // System call provided by bionic but not in any header file.
 extern "C" int init_module(void *, unsigned long, const char *);
 
@@ -100,15 +99,6 @@
     return ret;
 }
 
-static void service_start_if_not_disabled(struct service *svc)
-{
-    if (!(svc->flags & SVC_DISABLED)) {
-        service_start(svc, NULL);
-    } else {
-        svc->flags |= SVC_DISABLED_START;
-    }
-}
-
 static void unmount_and_fsck(const struct mntent *entry)
 {
     if (strcmp(entry->mnt_type, "f2fs") && strcmp(entry->mnt_type, "ext4"))
@@ -131,7 +121,7 @@
      * automatically restart after kill(), but that is not really a problem
      * because |entry->mnt_dir| is no longer visible to such new processes.
      */
-    service_for_each(service_stop);
+    ServiceManager::GetInstance().ForEachService([] (Service* s) { s->Stop(); });
     TEMP_FAILURE_RETRY(kill(-1, SIGKILL));
 
     int count = 0;
@@ -176,19 +166,22 @@
          * which are explicitly disabled.  They must
          * be started individually.
          */
-    service_for_each_class(args[1].c_str(), service_start_if_not_disabled);
+    ServiceManager::GetInstance().
+        ForEachServiceInClass(args[1], [] (Service* s) { s->StartIfNotDisabled(); });
     return 0;
 }
 
 int do_class_stop(const std::vector<std::string>& args)
 {
-    service_for_each_class(args[1].c_str(), service_stop);
+    ServiceManager::GetInstance().
+        ForEachServiceInClass(args[1], [] (Service* s) { s->Stop(); });
     return 0;
 }
 
 int do_class_reset(const std::vector<std::string>& args)
 {
-    service_for_each_class(args[1].c_str(), service_reset);
+    ServiceManager::GetInstance().
+        ForEachServiceInClass(args[1], [] (Service* s) { s->Reset(); });
     return 0;
 }
 
@@ -199,30 +192,22 @@
 
 int do_enable(const std::vector<std::string>& args)
 {
-    struct service *svc;
-    svc = service_find_by_name(args[1].c_str());
-    if (svc) {
-        svc->flags &= ~(SVC_DISABLED | SVC_RC_DISABLED);
-        if (svc->flags & SVC_DISABLED_START) {
-            service_start(svc, NULL);
-        }
-    } else {
+    Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
+    if (!svc) {
         return -1;
     }
-    return 0;
+    return svc->Enable();
 }
 
 int do_exec(const std::vector<std::string>& args) {
-    std::vector<char*> strs;
-    strs.reserve(args.size());
-    for (const auto& s : args) {
-        strs.push_back(const_cast<char*>(s.c_str()));
-    }
-    service* svc = make_exec_oneshot_service(strs.size(), &strs[0]);
-    if (svc == NULL) {
+    Service* svc = ServiceManager::GetInstance().MakeExecOneshotService(args);
+    if (!svc) {
         return -1;
     }
-    service_start(svc, NULL);
+    if (!svc->Start()) {
+        return -1;
+    }
+    waiting_for_exec = true;
     return 0;
 }
 
@@ -567,31 +552,35 @@
 
 int do_start(const std::vector<std::string>& args)
 {
-    struct service *svc;
-    svc = service_find_by_name(args[1].c_str());
-    if (svc) {
-        service_start(svc, NULL);
+    Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
+    if (!svc) {
+        ERROR("do_start: Service %s not found\n", args[1].c_str());
+        return -1;
     }
+    if (!svc->Start())
+        return -1;
     return 0;
 }
 
 int do_stop(const std::vector<std::string>& args)
 {
-    struct service *svc;
-    svc = service_find_by_name(args[1].c_str());
-    if (svc) {
-        service_stop(svc);
+    Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
+    if (!svc) {
+        ERROR("do_stop: Service %s not found\n", args[1].c_str());
+        return -1;
     }
+    svc->Stop();
     return 0;
 }
 
 int do_restart(const std::vector<std::string>& args)
 {
-    struct service *svc;
-    svc = service_find_by_name(args[1].c_str());
-    if (svc) {
-        service_restart(svc);
+    Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
+    if (!svc) {
+        ERROR("do_restart: Service %s not found\n", args[1].c_str());
+        return -1;
     }
+    svc->Restart();
     return 0;
 }
 
diff --git a/init/init.cpp b/init/init.cpp
index ac4db7c..c94a6fe 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -32,7 +32,6 @@
 #include <sys/types.h>
 #include <sys/un.h>
 #include <sys/wait.h>
-#include <termios.h>
 #include <unistd.h>
 
 #include <mtd/mtd-user.h>
@@ -54,16 +53,17 @@
 #include <memory>
 
 #include "action.h"
+#include "bootchart.h"
 #include "devices.h"
 #include "init.h"
+#include "init_parser.h"
+#include "keychords.h"
 #include "log.h"
 #include "property_service.h"
-#include "bootchart.h"
+#include "service.h"
 #include "signal_handler.h"
-#include "keychords.h"
-#include "init_parser.h"
-#include "util.h"
 #include "ueventd.h"
+#include "util.h"
 #include "watchdogd.h"
 
 struct selabel_handle *sehandle;
@@ -73,11 +73,11 @@
 
 static char qemu[32];
 
-static int have_console;
-static std::string console_name = "/dev/console";
+int have_console;
+std::string console_name = "/dev/console";
 static time_t process_needs_restart;
 
-static const char *ENV[32];
+const char *ENV[32];
 
 bool waiting_for_exec = false;
 
@@ -92,27 +92,6 @@
     }
 }
 
-void service::NotifyStateChange(const char* new_state) {
-    if (!properties_initialized()) {
-        // If properties aren't available yet, we can't set them.
-        return;
-    }
-
-    if ((flags & SVC_EXEC) != 0) {
-        // 'exec' commands don't have properties tracking their state.
-        return;
-    }
-
-    char prop_name[PROP_NAME_MAX];
-    if (snprintf(prop_name, sizeof(prop_name), "init.svc.%s", name) >= PROP_NAME_MAX) {
-        // If the property name would be too long, we can't set it.
-        ERROR("Property name \"init.svc.%s\" too long; not setting to %s\n", name, new_state);
-        return;
-    }
-
-    property_set(prop_name, new_state);
-}
-
 /* add_environment - add "key=value" to the current environment */
 int add_environment(const char *key, const char *val)
 {
@@ -145,398 +124,76 @@
     return -1;
 }
 
-void zap_stdio(void)
-{
-    int fd;
-    fd = open("/dev/null", O_RDWR);
-    dup2(fd, 0);
-    dup2(fd, 1);
-    dup2(fd, 2);
-    close(fd);
-}
-
-static void open_console()
-{
-    int fd;
-    if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
-        fd = open("/dev/null", O_RDWR);
-    }
-    ioctl(fd, TIOCSCTTY, 0);
-    dup2(fd, 0);
-    dup2(fd, 1);
-    dup2(fd, 2);
-    close(fd);
-}
-
-static void publish_socket(const char *name, int fd)
-{
-    char key[64] = ANDROID_SOCKET_ENV_PREFIX;
-    char val[64];
-
-    strlcpy(key + sizeof(ANDROID_SOCKET_ENV_PREFIX) - 1,
-            name,
-            sizeof(key) - sizeof(ANDROID_SOCKET_ENV_PREFIX));
-    snprintf(val, sizeof(val), "%d", fd);
-    add_environment(key, val);
-
-    /* make sure we don't close-on-exec */
-    fcntl(fd, F_SETFD, 0);
-}
-
-void service_start(struct service *svc, const char *dynamic_args)
-{
-    // Starting a service removes it from the disabled or reset state and
-    // immediately takes it out of the restarting state if it was in there.
-    svc->flags &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
-    svc->time_started = 0;
-
-    // Running processes require no additional work --- if they're in the
-    // process of exiting, we've ensured that they will immediately restart
-    // on exit, unless they are ONESHOT.
-    if (svc->flags & SVC_RUNNING) {
-        return;
-    }
-
-    bool needs_console = (svc->flags & SVC_CONSOLE);
-    if (needs_console && !have_console) {
-        ERROR("service '%s' requires console\n", svc->name);
-        svc->flags |= SVC_DISABLED;
-        return;
-    }
-
-    struct stat sb;
-    if (stat(svc->args[0], &sb) == -1) {
-        ERROR("cannot find '%s' (%s), disabling '%s'\n", svc->args[0], strerror(errno), svc->name);
-        svc->flags |= SVC_DISABLED;
-        return;
-    }
-
-    if ((!(svc->flags & SVC_ONESHOT)) && dynamic_args) {
-        ERROR("service '%s' must be one-shot to use dynamic args, disabling\n", svc->args[0]);
-        svc->flags |= SVC_DISABLED;
-        return;
-    }
-
-    char* scon = NULL;
-    if (svc->seclabel) {
-        scon = strdup(svc->seclabel);
-        if (!scon) {
-            ERROR("Out of memory while starting '%s'\n", svc->name);
-            return;
-        }
-    } else {
-        char *mycon = NULL, *fcon = NULL;
-
-        INFO("computing context for service '%s'\n", svc->args[0]);
-        int rc = getcon(&mycon);
-        if (rc < 0) {
-            ERROR("could not get context while starting '%s'\n", svc->name);
-            return;
-        }
-
-        rc = getfilecon(svc->args[0], &fcon);
-        if (rc < 0) {
-            ERROR("could not get context while starting '%s'\n", svc->name);
-            free(mycon);
-            return;
-        }
-
-        rc = security_compute_create(mycon, fcon, string_to_security_class("process"), &scon);
-        if (rc == 0 && !strcmp(scon, mycon)) {
-            ERROR("Service %s does not have a SELinux domain defined.\n", svc->name);
-            free(mycon);
-            free(fcon);
-            free(scon);
-            return;
-        }
-        free(mycon);
-        free(fcon);
-        if (rc < 0) {
-            ERROR("could not get context while starting '%s'\n", svc->name);
-            return;
-        }
-    }
-
-    NOTICE("Starting service '%s'...\n", svc->name);
-
-    pid_t pid = fork();
-    if (pid == 0) {
-        struct socketinfo *si;
-        struct svcenvinfo *ei;
-        char tmp[32];
-        int fd, sz;
-
-        umask(077);
-        if (properties_initialized()) {
-            get_property_workspace(&fd, &sz);
-            snprintf(tmp, sizeof(tmp), "%d,%d", dup(fd), sz);
-            add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);
-        }
-
-        for (ei = svc->envvars; ei; ei = ei->next)
-            add_environment(ei->name, ei->value);
-
-        for (si = svc->sockets; si; si = si->next) {
-            int socket_type = (
-                    !strcmp(si->type, "stream") ? SOCK_STREAM :
-                        (!strcmp(si->type, "dgram") ? SOCK_DGRAM : SOCK_SEQPACKET));
-            int s = create_socket(si->name, socket_type,
-                                  si->perm, si->uid, si->gid, si->socketcon ?: scon);
-            if (s >= 0) {
-                publish_socket(si->name, s);
-            }
-        }
-
-        free(scon);
-        scon = NULL;
-
-        if (svc->writepid_files_) {
-            std::string pid_str = android::base::StringPrintf("%d", pid);
-            for (auto& file : *svc->writepid_files_) {
-                if (!android::base::WriteStringToFile(pid_str, file)) {
-                    ERROR("couldn't write %s to %s: %s\n",
-                          pid_str.c_str(), file.c_str(), strerror(errno));
-                }
-            }
-        }
-
-        if (svc->ioprio_class != IoSchedClass_NONE) {
-            if (android_set_ioprio(getpid(), svc->ioprio_class, svc->ioprio_pri)) {
-                ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
-                      getpid(), svc->ioprio_class, svc->ioprio_pri, strerror(errno));
-            }
-        }
-
-        if (needs_console) {
-            setsid();
-            open_console();
-        } else {
-            zap_stdio();
-        }
-
-        if (false) {
-            for (size_t n = 0; svc->args[n]; n++) {
-                INFO("args[%zu] = '%s'\n", n, svc->args[n]);
-            }
-            for (size_t n = 0; ENV[n]; n++) {
-                INFO("env[%zu] = '%s'\n", n, ENV[n]);
-            }
-        }
-
-        setpgid(0, getpid());
-
-        // As requested, set our gid, supplemental gids, and uid.
-        if (svc->gid) {
-            if (setgid(svc->gid) != 0) {
-                ERROR("setgid failed: %s\n", strerror(errno));
-                _exit(127);
-            }
-        }
-        if (svc->nr_supp_gids) {
-            if (setgroups(svc->nr_supp_gids, svc->supp_gids) != 0) {
-                ERROR("setgroups failed: %s\n", strerror(errno));
-                _exit(127);
-            }
-        }
-        if (svc->uid) {
-            if (setuid(svc->uid) != 0) {
-                ERROR("setuid failed: %s\n", strerror(errno));
-                _exit(127);
-            }
-        }
-        if (svc->seclabel) {
-            if (setexeccon(svc->seclabel) < 0) {
-                ERROR("cannot setexeccon('%s'): %s\n", svc->seclabel, strerror(errno));
-                _exit(127);
-            }
-        }
-
-        if (!dynamic_args) {
-            if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
-                ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
-            }
-        } else {
-            char *arg_ptrs[INIT_PARSER_MAXARGS+1];
-            int arg_idx = svc->nargs;
-            char *tmp = strdup(dynamic_args);
-            char *next = tmp;
-            char *bword;
-
-            /* Copy the static arguments */
-            memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));
-
-            while((bword = strsep(&next, " "))) {
-                arg_ptrs[arg_idx++] = bword;
-                if (arg_idx == INIT_PARSER_MAXARGS)
-                    break;
-            }
-            arg_ptrs[arg_idx] = NULL;
-            execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
-        }
-        _exit(127);
-    }
-
-    free(scon);
-
-    if (pid < 0) {
-        ERROR("failed to start '%s'\n", svc->name);
-        svc->pid = 0;
-        return;
-    }
-
-    svc->time_started = gettime();
-    svc->pid = pid;
-    svc->flags |= SVC_RUNNING;
-
-    if ((svc->flags & SVC_EXEC) != 0) {
-        INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
-             svc->pid, svc->uid, svc->gid, svc->nr_supp_gids,
-             svc->seclabel ? : "default");
-        waiting_for_exec = true;
-    }
-
-    svc->NotifyStateChange("running");
-}
-
-/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
-static void service_stop_or_reset(struct service *svc, int how)
-{
-    /* The service is still SVC_RUNNING until its process exits, but if it has
-     * already exited it shoudn't attempt a restart yet. */
-    svc->flags &= ~(SVC_RESTARTING | SVC_DISABLED_START);
-
-    if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
-        /* Hrm, an illegal flag.  Default to SVC_DISABLED */
-        how = SVC_DISABLED;
-    }
-        /* if the service has not yet started, prevent
-         * it from auto-starting with its class
-         */
-    if (how == SVC_RESET) {
-        svc->flags |= (svc->flags & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
-    } else {
-        svc->flags |= how;
-    }
-
-    if (svc->pid) {
-        NOTICE("Service '%s' is being killed...\n", svc->name);
-        kill(-svc->pid, SIGKILL);
-        svc->NotifyStateChange("stopping");
-    } else {
-        svc->NotifyStateChange("stopped");
-    }
-}
-
-void service_reset(struct service *svc)
-{
-    service_stop_or_reset(svc, SVC_RESET);
-}
-
-void service_stop(struct service *svc)
-{
-    service_stop_or_reset(svc, SVC_DISABLED);
-}
-
-void service_restart(struct service *svc)
-{
-    if (svc->flags & SVC_RUNNING) {
-        /* Stop, wait, then start the service. */
-        service_stop_or_reset(svc, SVC_RESTART);
-    } else if (!(svc->flags & SVC_RESTARTING)) {
-        /* Just start the service since it's not running. */
-        service_start(svc, NULL);
-    } /* else: Service is restarting anyways. */
-}
-
 void property_changed(const char *name, const char *value)
 {
     if (property_triggers_enabled)
         ActionManager::GetInstance().QueuePropertyTrigger(name, value);
 }
 
-static void restart_service_if_needed(struct service *svc)
-{
-    time_t next_start_time = svc->time_started + 5;
-
-    if (next_start_time <= gettime()) {
-        svc->flags &= (~SVC_RESTARTING);
-        service_start(svc, NULL);
-        return;
-    }
-
-    if ((next_start_time < process_needs_restart) ||
-        (process_needs_restart == 0)) {
-        process_needs_restart = next_start_time;
-    }
-}
-
 static void restart_processes()
 {
     process_needs_restart = 0;
-    service_for_each_flags(SVC_RESTARTING,
-                           restart_service_if_needed);
+    ServiceManager::GetInstance().
+        ForEachServiceWithFlags(SVC_RESTARTING, [] (Service* s) {
+                s->RestartIfNeeded(process_needs_restart);
+            });
 }
 
-static void msg_start(const char *name)
+static void msg_start(const std::string& name)
 {
-    struct service *svc = NULL;
-    char *tmp = NULL;
-    char *args = NULL;
+    Service* svc = nullptr;
+    std::vector<std::string> vargs;
 
-    if (!strchr(name, ':'))
-        svc = service_find_by_name(name);
-    else {
-        tmp = strdup(name);
-        if (tmp) {
-            args = strchr(tmp, ':');
-            *args = '\0';
-            args++;
+    size_t colon_pos = name.find(':');
+    if (colon_pos == std::string::npos) {
+        svc = ServiceManager::GetInstance().FindServiceByName(name);
+    } else {
+        std::string service_name(name.substr(0, colon_pos));
+        std::string args(name.substr(colon_pos + 1));
+        vargs = android::base::Split(args, " ");
 
-            svc = service_find_by_name(tmp);
-        }
+        svc = ServiceManager::GetInstance().FindServiceByName(service_name);
     }
 
     if (svc) {
-        service_start(svc, args);
+        svc->Start(vargs);
     } else {
-        ERROR("no such service '%s'\n", name);
+        ERROR("no such service '%s'\n", name.c_str());
     }
-    if (tmp)
-        free(tmp);
 }
 
-static void msg_stop(const char *name)
+static void msg_stop(const std::string& name)
 {
-    struct service *svc = service_find_by_name(name);
+    Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
 
     if (svc) {
-        service_stop(svc);
+        svc->Stop();
     } else {
-        ERROR("no such service '%s'\n", name);
+        ERROR("no such service '%s'\n", name.c_str());
     }
 }
 
-static void msg_restart(const char *name)
+static void msg_restart(const std::string& name)
 {
-    struct service *svc = service_find_by_name(name);
+    Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
 
     if (svc) {
-        service_restart(svc);
+        svc->Restart();
     } else {
-        ERROR("no such service '%s'\n", name);
+        ERROR("no such service '%s'\n", name.c_str());
     }
 }
 
-void handle_control_message(const char *msg, const char *arg)
+void handle_control_message(const std::string& msg, const std::string& arg)
 {
-    if (!strcmp(msg,"start")) {
+    if (msg == "start") {
         msg_start(arg);
-    } else if (!strcmp(msg,"stop")) {
+    } else if (msg == "stop") {
         msg_stop(arg);
-    } else if (!strcmp(msg,"restart")) {
+    } else if (msg == "restart") {
         msg_restart(arg);
     } else {
-        ERROR("unknown control msg '%s'\n", msg);
+        ERROR("unknown control msg '%s'\n", msg.c_str());
     }
 }
 
diff --git a/init/init.h b/init/init.h
index 4d23103..345d442 100644
--- a/init/init.h
+++ b/init/init.h
@@ -17,117 +17,28 @@
 #ifndef _INIT_INIT_H
 #define _INIT_INIT_H
 
-#include <sys/types.h>
-#include <stdlib.h>
-
-#include <list>
-#include <map>
 #include <string>
-#include <vector>
-
-#include <cutils/list.h>
-#include <cutils/iosched_policy.h>
 
 class Action;
-
-struct socketinfo {
-    struct socketinfo *next;
-    const char *name;
-    const char *type;
-    uid_t uid;
-    gid_t gid;
-    int perm;
-    const char *socketcon;
-};
-
-struct svcenvinfo {
-    struct svcenvinfo *next;
-    const char *name;
-    const char *value;
-};
-
-#define SVC_DISABLED       0x001  // do not autostart with class
-#define SVC_ONESHOT        0x002  // do not restart on exit
-#define SVC_RUNNING        0x004  // currently active
-#define SVC_RESTARTING     0x008  // waiting to restart
-#define SVC_CONSOLE        0x010  // requires console
-#define SVC_CRITICAL       0x020  // will reboot into recovery if keeps crashing
-#define SVC_RESET          0x040  // Use when stopping a process, but not disabling so it can be restarted with its class.
-#define SVC_RC_DISABLED    0x080  // Remember if the disabled flag was set in the rc script.
-#define SVC_RESTART        0x100  // Use to safely restart (stop, wait, start) a service.
-#define SVC_DISABLED_START 0x200  // A start was requested but it was disabled at the time.
-#define SVC_EXEC           0x400  // This synthetic service corresponds to an 'exec'.
-
-#define NR_SVC_SUPP_GIDS 12    /* twelve supplementary groups */
+class Service;
 
 #define COMMAND_RETRY_TIMEOUT 5
 
-struct service {
-    void NotifyStateChange(const char* new_state);
-
-        /* list of all services */
-    struct listnode slist;
-
-    char *name;
-    const char *classname;
-
-    unsigned flags;
-    pid_t pid;
-    time_t time_started;    /* time of last start */
-    time_t time_crashed;    /* first crash within inspection window */
-    int nr_crashed;         /* number of times crashed within window */
-
-    uid_t uid;
-    gid_t gid;
-    gid_t supp_gids[NR_SVC_SUPP_GIDS];
-    size_t nr_supp_gids;
-
-    const char* seclabel;
-
-    struct socketinfo *sockets;
-    struct svcenvinfo *envvars;
-
-    Action* onrestart;  /* Commands to execute on restart. */
-
-    std::vector<std::string>* writepid_files_;
-
-    /* keycodes for triggering this service via /dev/keychord */
-    int *keycodes;
-    int nkeycodes;
-    int keychord_id;
-
-    IoSchedClass ioprio_class;
-    int ioprio_pri;
-
-    int nargs;
-    /* "MUST BE AT THE END OF THE STRUCT" */
-    char *args[1];
-}; /*     ^-------'args' MUST be at the end of this struct! */
-
+extern const char *ENV[32];
 extern bool waiting_for_exec;
+extern int have_console;
+extern std::string console_name;
 extern struct selabel_handle *sehandle;
 extern struct selabel_handle *sehandle_prop;
 
-void handle_control_message(const char *msg, const char *arg);
+void handle_control_message(const std::string& msg, const std::string& arg);
 
-struct service *service_find_by_name(const char *name);
-struct service *service_find_by_pid(pid_t pid);
-struct service *service_find_by_keychord(int keychord_id);
-void service_for_each(void (*func)(struct service *svc));
-void service_for_each_class(const char *classname,
-                            void (*func)(struct service *svc));
-void service_for_each_flags(unsigned matchflags,
-                            void (*func)(struct service *svc));
-void service_stop(struct service *svc);
-void service_reset(struct service *svc);
-void service_restart(struct service *svc);
-void service_start(struct service *svc, const char *dynamic_args);
 void property_changed(const char *name, const char *value);
 
 int selinux_reload_policy(void);
 
-void zap_stdio(void);
-
 void register_epoll_handler(int fd, void (*fn)());
 
+int add_environment(const char* key, const char* val);
+
 #endif  /* _INIT_INIT_H */
diff --git a/init/init_parser.cpp b/init/init_parser.cpp
index d420351..3ed1d58 100644
--- a/init/init_parser.cpp
+++ b/init/init_parser.cpp
@@ -28,10 +28,11 @@
 
 #include "action.h"
 #include "init.h"
-#include "parser.h"
 #include "init_parser.h"
 #include "log.h"
+#include "parser.h"
 #include "property_service.h"
+#include "service.h"
 #include "util.h"
 
 #include <base/stringprintf.h>
@@ -63,7 +64,7 @@
 static struct {
     const char *name;
     int (*func)(const std::vector<std::string>& args);
-    unsigned char nargs;
+    size_t nargs;
     unsigned char flags;
 } keyword_info[KEYWORD_COUNT] = {
     [ K_UNKNOWN ] = { "unknown", 0, 0, 0 },
@@ -77,23 +78,8 @@
 #define kw_nargs(kw) (keyword_info[kw].nargs)
 
 void dump_parser_state() {
-    if (false) {
-        struct listnode* node;
-        list_for_each(node, &service_list) {
-            service* svc = node_to_item(node, struct service, slist);
-            INFO("service %s\n", svc->name);
-            INFO("  class '%s'\n", svc->classname);
-            INFO("  exec");
-            for (int n = 0; n < svc->nargs; n++) {
-                INFO(" '%s'", svc->args[n]);
-            }
-            INFO("\n");
-            for (socketinfo* si = svc->sockets; si; si = si->next) {
-                INFO("  socket %s %s 0%o\n", si->name, si->type, si->perm);
-            }
-        }
-        ActionManager::GetInstance().DumpState();
-    }
+    ServiceManager::GetInstance().DumpState();
+    ActionManager::GetInstance().DumpState();
 }
 
 static int lookup_keyword(const char *s)
@@ -419,363 +405,38 @@
     return init_parse_config_file(path);
 }
 
-static int valid_name(const char *name)
-{
-    if (strlen(name) > 16) {
-        return 0;
-    }
-    while (*name) {
-        if (!isalnum(*name) && (*name != '_') && (*name != '-')) {
-            return 0;
-        }
-        name++;
-    }
-    return 1;
-}
-
-struct service *service_find_by_name(const char *name)
-{
-    struct listnode *node;
-    struct service *svc;
-    list_for_each(node, &service_list) {
-        svc = node_to_item(node, struct service, slist);
-        if (!strcmp(svc->name, name)) {
-            return svc;
-        }
-    }
-    return 0;
-}
-
-struct service *service_find_by_pid(pid_t pid)
-{
-    struct listnode *node;
-    struct service *svc;
-    list_for_each(node, &service_list) {
-        svc = node_to_item(node, struct service, slist);
-        if (svc->pid == pid) {
-            return svc;
-        }
-    }
-    return 0;
-}
-
-struct service *service_find_by_keychord(int keychord_id)
-{
-    struct listnode *node;
-    struct service *svc;
-    list_for_each(node, &service_list) {
-        svc = node_to_item(node, struct service, slist);
-        if (svc->keychord_id == keychord_id) {
-            return svc;
-        }
-    }
-    return 0;
-}
-
-void service_for_each(void (*func)(struct service *svc))
-{
-    struct listnode *node;
-    struct service *svc;
-    list_for_each(node, &service_list) {
-        svc = node_to_item(node, struct service, slist);
-        func(svc);
-    }
-}
-
-void service_for_each_class(const char *classname,
-                            void (*func)(struct service *svc))
-{
-    struct listnode *node;
-    struct service *svc;
-    list_for_each(node, &service_list) {
-        svc = node_to_item(node, struct service, slist);
-        if (!strcmp(svc->classname, classname)) {
-            func(svc);
-        }
-    }
-}
-
-void service_for_each_flags(unsigned matchflags,
-                            void (*func)(struct service *svc))
-{
-    struct listnode *node;
-    struct service *svc;
-    list_for_each(node, &service_list) {
-        svc = node_to_item(node, struct service, slist);
-        if (svc->flags & matchflags) {
-            func(svc);
-        }
-    }
-}
-
-service* make_exec_oneshot_service(int nargs, char** args) {
-    // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
-    // SECLABEL can be a - to denote default
-    int command_arg = 1;
-    for (int i = 1; i < nargs; ++i) {
-        if (strcmp(args[i], "--") == 0) {
-            command_arg = i + 1;
-            break;
-        }
-    }
-    if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
-        ERROR("exec called with too many supplementary group ids\n");
-        return NULL;
-    }
-
-    int argc = nargs - command_arg;
-    char** argv = (args + command_arg);
-    if (argc < 1) {
-        ERROR("exec called without command\n");
-        return NULL;
-    }
-
-    service* svc = (service*) calloc(1, sizeof(*svc) + sizeof(char*) * argc);
-    if (svc == NULL) {
-        ERROR("Couldn't allocate service for exec of '%s': %s", argv[0], strerror(errno));
-        return NULL;
-    }
-
-    if ((command_arg > 2) && strcmp(args[1], "-")) {
-        svc->seclabel = args[1];
-    }
-    if (command_arg > 3) {
-        svc->uid = decode_uid(args[2]);
-    }
-    if (command_arg > 4) {
-        svc->gid = decode_uid(args[3]);
-        svc->nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
-        for (size_t i = 0; i < svc->nr_supp_gids; ++i) {
-            svc->supp_gids[i] = decode_uid(args[4 + i]);
-        }
-    }
-
-    static int exec_count; // Every service needs a unique name.
-    char* name = NULL;
-    asprintf(&name, "exec %d (%s)", exec_count++, argv[0]);
-    if (name == NULL) {
-        ERROR("Couldn't allocate name for exec service '%s'\n", argv[0]);
-        free(svc);
-        return NULL;
-    }
-    svc->name = name;
-    svc->classname = "default";
-    svc->flags = SVC_EXEC | SVC_ONESHOT;
-    svc->nargs = argc;
-    memcpy(svc->args, argv, sizeof(char*) * svc->nargs);
-    svc->args[argc] = NULL;
-    list_add_tail(&service_list, &svc->slist);
-    return svc;
-}
-
 static void *parse_service(struct parse_state *state, int nargs, char **args)
 {
     if (nargs < 3) {
         parse_error(state, "services must have a name and a program\n");
-        return 0;
+        return nullptr;
     }
-    if (!valid_name(args[1])) {
-        parse_error(state, "invalid service name '%s'\n", args[1]);
-        return 0;
-    }
+    std::vector<std::string> str_args(args + 2, args + nargs);
+    std::string ret_err;
+    Service* svc = ServiceManager::GetInstance().AddNewService(args[1], "default",
+                                                               str_args, &ret_err);
 
-    service* svc = (service*) service_find_by_name(args[1]);
-    if (svc) {
-        parse_error(state, "ignored duplicate definition of service '%s'\n", args[1]);
-        return 0;
-    }
-
-    nargs -= 2;
-    svc = (service*) calloc(1, sizeof(*svc) + sizeof(char*) * nargs);
     if (!svc) {
-        parse_error(state, "out of memory\n");
-        return 0;
+        parse_error(state, "%s\n", ret_err.c_str());
     }
-    svc->name = strdup(args[1]);
-    svc->classname = "default";
-    memcpy(svc->args, args + 2, sizeof(char*) * nargs);
-    svc->args[nargs] = 0;
-    svc->nargs = nargs;
-    svc->onrestart = new Action();
-    svc->onrestart->InitSingleTrigger("onrestart");
-    list_add_tail(&service_list, &svc->slist);
+
     return svc;
 }
 
 static void parse_line_service(struct parse_state *state, int nargs, char **args)
 {
-    struct service *svc = (service*) state->context;
-    int i, kw, kw_nargs;
-    std::vector<std::string> str_args;
-
     if (nargs == 0) {
         return;
     }
 
-    svc->ioprio_class = IoSchedClass_NONE;
+    Service* svc = static_cast<Service*>(state->context);
+    int kw = lookup_keyword(args[0]);
+    std::vector<std::string> str_args(args, args + nargs);
+    std::string ret_err;
+    bool ret = svc->HandleLine(kw, str_args, &ret_err);
 
-    kw = lookup_keyword(args[0]);
-    switch (kw) {
-    case K_class:
-        if (nargs != 2) {
-            parse_error(state, "class option requires a classname\n");
-        } else {
-            svc->classname = args[1];
-        }
-        break;
-    case K_console:
-        svc->flags |= SVC_CONSOLE;
-        break;
-    case K_disabled:
-        svc->flags |= SVC_DISABLED;
-        svc->flags |= SVC_RC_DISABLED;
-        break;
-    case K_ioprio:
-        if (nargs != 3) {
-            parse_error(state, "ioprio optin usage: ioprio <rt|be|idle> <ioprio 0-7>\n");
-        } else {
-            svc->ioprio_pri = strtoul(args[2], 0, 8);
-
-            if (svc->ioprio_pri < 0 || svc->ioprio_pri > 7) {
-                parse_error(state, "priority value must be range 0 - 7\n");
-                break;
-            }
-
-            if (!strcmp(args[1], "rt")) {
-                svc->ioprio_class = IoSchedClass_RT;
-            } else if (!strcmp(args[1], "be")) {
-                svc->ioprio_class = IoSchedClass_BE;
-            } else if (!strcmp(args[1], "idle")) {
-                svc->ioprio_class = IoSchedClass_IDLE;
-            } else {
-                parse_error(state, "ioprio option usage: ioprio <rt|be|idle> <0-7>\n");
-            }
-        }
-        break;
-    case K_group:
-        if (nargs < 2) {
-            parse_error(state, "group option requires a group id\n");
-        } else if (nargs > NR_SVC_SUPP_GIDS + 2) {
-            parse_error(state, "group option accepts at most %d supp. groups\n",
-                        NR_SVC_SUPP_GIDS);
-        } else {
-            int n;
-            svc->gid = decode_uid(args[1]);
-            for (n = 2; n < nargs; n++) {
-                svc->supp_gids[n-2] = decode_uid(args[n]);
-            }
-            svc->nr_supp_gids = n - 2;
-        }
-        break;
-    case K_keycodes:
-        if (nargs < 2) {
-            parse_error(state, "keycodes option requires atleast one keycode\n");
-        } else {
-            svc->keycodes = (int*) malloc((nargs - 1) * sizeof(svc->keycodes[0]));
-            if (!svc->keycodes) {
-                parse_error(state, "could not allocate keycodes\n");
-            } else {
-                svc->nkeycodes = nargs - 1;
-                for (i = 1; i < nargs; i++) {
-                    svc->keycodes[i - 1] = atoi(args[i]);
-                }
-            }
-        }
-        break;
-    case K_oneshot:
-        svc->flags |= SVC_ONESHOT;
-        break;
-    case K_onrestart:
-        nargs--;
-        args++;
-        kw = lookup_keyword(args[0]);
-        if (!kw_is(kw, COMMAND)) {
-            parse_error(state, "invalid command '%s'\n", args[0]);
-            break;
-        }
-        kw_nargs = kw_nargs(kw);
-        if (nargs < kw_nargs) {
-            parse_error(state, "%s requires %d %s\n", args[0], kw_nargs - 1,
-                kw_nargs > 2 ? "arguments" : "argument");
-            break;
-        }
-        str_args.assign(args, args + nargs);
-        svc->onrestart->AddCommand(kw_func(kw), str_args);
-        break;
-    case K_critical:
-        svc->flags |= SVC_CRITICAL;
-        break;
-    case K_setenv: { /* name value */
-        if (nargs < 3) {
-            parse_error(state, "setenv option requires name and value arguments\n");
-            break;
-        }
-        svcenvinfo* ei = (svcenvinfo*) calloc(1, sizeof(*ei));
-        if (!ei) {
-            parse_error(state, "out of memory\n");
-            break;
-        }
-        ei->name = args[1];
-        ei->value = args[2];
-        ei->next = svc->envvars;
-        svc->envvars = ei;
-        break;
-    }
-    case K_socket: {/* name type perm [ uid gid context ] */
-        if (nargs < 4) {
-            parse_error(state, "socket option requires name, type, perm arguments\n");
-            break;
-        }
-        if (strcmp(args[2],"dgram") && strcmp(args[2],"stream")
-                && strcmp(args[2],"seqpacket")) {
-            parse_error(state, "socket type must be 'dgram', 'stream' or 'seqpacket'\n");
-            break;
-        }
-        socketinfo* si = (socketinfo*) calloc(1, sizeof(*si));
-        if (!si) {
-            parse_error(state, "out of memory\n");
-            break;
-        }
-        si->name = args[1];
-        si->type = args[2];
-        si->perm = strtoul(args[3], 0, 8);
-        if (nargs > 4)
-            si->uid = decode_uid(args[4]);
-        if (nargs > 5)
-            si->gid = decode_uid(args[5]);
-        if (nargs > 6)
-            si->socketcon = args[6];
-        si->next = svc->sockets;
-        svc->sockets = si;
-        break;
-    }
-    case K_user:
-        if (nargs != 2) {
-            parse_error(state, "user option requires a user id\n");
-        } else {
-            svc->uid = decode_uid(args[1]);
-        }
-        break;
-    case K_seclabel:
-        if (nargs != 2) {
-            parse_error(state, "seclabel option requires a label string\n");
-        } else {
-            svc->seclabel = args[1];
-        }
-        break;
-    case K_writepid:
-        if (nargs < 2) {
-            parse_error(state, "writepid option requires at least one filename\n");
-            break;
-        }
-        svc->writepid_files_ = new std::vector<std::string>;
-        for (int i = 1; i < nargs; ++i) {
-            svc->writepid_files_->push_back(args[i]);
-        }
-        break;
-
-    default:
-        parse_error(state, "invalid option '%s'\n", args[0]);
+    if (!ret) {
+        parse_error(state, "%s\n", ret_err.c_str());
     }
 }
 
@@ -792,28 +453,42 @@
     return ret;
 }
 
+bool add_command_to_action(Action* action, const std::vector<std::string>& args,
+                           const std::string& filename, int line, std::string* err)
+{
+    int kw;
+    size_t n;
+
+    kw = lookup_keyword(args[0].c_str());
+    if (!kw_is(kw, COMMAND)) {
+        *err = android::base::StringPrintf("invalid command '%s'\n", args[0].c_str());
+        return false;
+    }
+
+    n = kw_nargs(kw);
+    if (args.size() < n) {
+        *err = android::base::StringPrintf("%s requires %zu %s\n",
+                                           args[0].c_str(), n - 1,
+                                           n > 2 ? "arguments" : "argument");
+        return false;
+    }
+
+    action->AddCommand(kw_func(kw), args, filename, line);
+    return true;
+}
+
 static void parse_line_action(struct parse_state* state, int nargs, char **args)
 {
-    Action* act = (Action*) state->context;
-    int kw, n;
-
     if (nargs == 0) {
         return;
     }
 
-    kw = lookup_keyword(args[0]);
-    if (!kw_is(kw, COMMAND)) {
-        parse_error(state, "invalid command '%s'\n", args[0]);
-        return;
-    }
-
-    n = kw_nargs(kw);
-    if (nargs < n) {
-        parse_error(state, "%s requires %d %s\n", args[0], n - 1,
-            n > 2 ? "arguments" : "argument");
-        return;
-    }
-
+    Action* action = static_cast<Action*>(state->context);
     std::vector<std::string> str_args(args, args + nargs);
-    act->AddCommand(kw_func(kw), str_args, state->filename, state->line);
+    std::string ret_err;
+    bool ret = add_command_to_action(action, str_args, state->filename,
+                                     state->line, &ret_err);
+    if (!ret) {
+        parse_error(state, "%s\n", ret_err.c_str());
+    }
 }
diff --git a/init/init_parser.h b/init/init_parser.h
index fe96bdc..709dca8 100644
--- a/init/init_parser.h
+++ b/init/init_parser.h
@@ -18,14 +18,15 @@
 #define _INIT_INIT_PARSER_H_
 
 #include <string>
+#include <vector>
 
 #define INIT_PARSER_MAXARGS 64
 
-struct service;
+class Action;
 
 bool init_parse_config(const char* path);
 int expand_props(const std::string& src, std::string* dst);
-
-service* make_exec_oneshot_service(int argc, char** argv);
+bool add_command_to_action(Action* action, const std::vector<std::string>& args,
+                           const std::string& filename, int line, std::string* err);
 
 #endif
diff --git a/init/init_parser_test.cpp b/init/init_parser_test.cpp
index 170a73a..52aaa37 100644
--- a/init/init_parser_test.cpp
+++ b/init/init_parser_test.cpp
@@ -17,96 +17,97 @@
 #include "init_parser.h"
 
 #include "init.h"
+#include "service.h"
 #include "util.h"
 
 #include <errno.h>
 #include <gtest/gtest.h>
 
-TEST(init_parser, make_exec_oneshot_service_invalid_syntax) {
-    char* argv[10];
-    memset(argv, 0, sizeof(argv));
+#include <string>
+#include <vector>
 
+TEST(init_parser, make_exec_oneshot_service_invalid_syntax) {
+    ServiceManager& sm = ServiceManager::GetInstance();
+    std::vector<std::string> args;
     // Nothing.
-    ASSERT_EQ(nullptr, make_exec_oneshot_service(0, argv));
+    ASSERT_EQ(nullptr, sm.MakeExecOneshotService(args));
 
     // No arguments to 'exec'.
-    argv[0] = const_cast<char*>("exec");
-    ASSERT_EQ(nullptr, make_exec_oneshot_service(1, argv));
+    args.push_back("exec");
+    ASSERT_EQ(nullptr, sm.MakeExecOneshotService(args));
 
     // No command in "exec --".
-    argv[1] = const_cast<char*>("--");
-    ASSERT_EQ(nullptr, make_exec_oneshot_service(2, argv));
+    args.push_back("--");
+    ASSERT_EQ(nullptr, sm.MakeExecOneshotService(args));
 }
 
 TEST(init_parser, make_exec_oneshot_service_too_many_supplementary_gids) {
-    int argc = 0;
-    char* argv[4 + NR_SVC_SUPP_GIDS + 3];
-    argv[argc++] = const_cast<char*>("exec");
-    argv[argc++] = const_cast<char*>("seclabel");
-    argv[argc++] = const_cast<char*>("root"); // uid.
-    argv[argc++] = const_cast<char*>("root"); // gid.
+    ServiceManager& sm = ServiceManager::GetInstance();
+    std::vector<std::string> args;
+    args.push_back("exec");
+    args.push_back("seclabel");
+    args.push_back("root"); // uid.
+    args.push_back("root"); // gid.
     for (int i = 0; i < NR_SVC_SUPP_GIDS; ++i) {
-        argv[argc++] = const_cast<char*>("root"); // Supplementary gid.
+        args.push_back("root"); // Supplementary gid.
     }
-    argv[argc++] = const_cast<char*>("--");
-    argv[argc++] = const_cast<char*>("/system/bin/id");
-    argv[argc] = nullptr;
-    ASSERT_EQ(nullptr, make_exec_oneshot_service(argc, argv));
+    args.push_back("--");
+    args.push_back("/system/bin/id");
+    ASSERT_EQ(nullptr, sm.MakeExecOneshotService(args));
 }
 
-static void Test_make_exec_oneshot_service(bool dash_dash, bool seclabel, bool uid, bool gid, bool supplementary_gids) {
-    int argc = 0;
-    char* argv[10];
-    argv[argc++] = const_cast<char*>("exec");
+static void Test_make_exec_oneshot_service(bool dash_dash, bool seclabel, bool uid,
+                                           bool gid, bool supplementary_gids) {
+    ServiceManager& sm = ServiceManager::GetInstance();
+    std::vector<std::string> args;
+    args.push_back("exec");
     if (seclabel) {
-        argv[argc++] = const_cast<char*>("u:r:su:s0"); // seclabel
+        args.push_back("u:r:su:s0"); // seclabel
         if (uid) {
-            argv[argc++] = const_cast<char*>("log");      // uid
+            args.push_back("log");      // uid
             if (gid) {
-                argv[argc++] = const_cast<char*>("shell");     // gid
+                args.push_back("shell");     // gid
                 if (supplementary_gids) {
-                    argv[argc++] = const_cast<char*>("system");    // supplementary gid 0
-                    argv[argc++] = const_cast<char*>("adb");       // supplementary gid 1
+                    args.push_back("system");    // supplementary gid 0
+                    args.push_back("adb");       // supplementary gid 1
                 }
             }
         }
     }
     if (dash_dash) {
-        argv[argc++] = const_cast<char*>("--");
+        args.push_back("--");
     }
-    argv[argc++] = const_cast<char*>("/system/bin/toybox");
-    argv[argc++] = const_cast<char*>("id");
-    argv[argc] = nullptr;
-    service* svc = make_exec_oneshot_service(argc, argv);
+    args.push_back("/system/bin/toybox");
+    args.push_back("id");
+    Service* svc = sm.MakeExecOneshotService(args);
     ASSERT_NE(nullptr, svc);
 
     if (seclabel) {
-        ASSERT_STREQ("u:r:su:s0", svc->seclabel);
+        ASSERT_EQ("u:r:su:s0", svc->seclabel());
     } else {
-        ASSERT_EQ(nullptr, svc->seclabel);
+        ASSERT_EQ("", svc->seclabel());
     }
     if (uid) {
-        ASSERT_EQ(decode_uid("log"), svc->uid);
+        ASSERT_EQ(decode_uid("log"), svc->uid());
     } else {
-        ASSERT_EQ(0U, svc->uid);
+        ASSERT_EQ(0U, svc->uid());
     }
     if (gid) {
-        ASSERT_EQ(decode_uid("shell"), svc->gid);
+        ASSERT_EQ(decode_uid("shell"), svc->gid());
     } else {
-        ASSERT_EQ(0U, svc->gid);
+        ASSERT_EQ(0U, svc->gid());
     }
     if (supplementary_gids) {
-        ASSERT_EQ(2U, svc->nr_supp_gids);
-        ASSERT_EQ(decode_uid("system"), svc->supp_gids[0]);
-        ASSERT_EQ(decode_uid("adb"), svc->supp_gids[1]);
+        ASSERT_EQ(2U, svc->supp_gids().size());
+        ASSERT_EQ(decode_uid("system"), svc->supp_gids()[0]);
+        ASSERT_EQ(decode_uid("adb"), svc->supp_gids()[1]);
     } else {
-        ASSERT_EQ(0U, svc->nr_supp_gids);
+        ASSERT_EQ(0U, svc->supp_gids().size());
     }
 
-    ASSERT_EQ(2, svc->nargs);
-    ASSERT_EQ("/system/bin/toybox", svc->args[0]);
-    ASSERT_EQ("id", svc->args[1]);
-    ASSERT_EQ(nullptr, svc->args[2]);
+    ASSERT_EQ(static_cast<std::size_t>(2), svc->args().size());
+    ASSERT_EQ("/system/bin/toybox", svc->args()[0]);
+    ASSERT_EQ("id", svc->args()[1]);
 }
 
 TEST(init_parser, make_exec_oneshot_service_with_everything) {
diff --git a/init/keychords.cpp b/init/keychords.cpp
index c4ebdf9..7a7838d 100644
--- a/init/keychords.cpp
+++ b/init/keychords.cpp
@@ -26,20 +26,21 @@
 #include "init.h"
 #include "log.h"
 #include "property_service.h"
+#include "service.h"
 
 static struct input_keychord *keychords = 0;
 static int keychords_count = 0;
 static int keychords_length = 0;
 static int keychord_fd = -1;
 
-void add_service_keycodes(struct service *svc)
+void add_service_keycodes(Service* svc)
 {
     struct input_keychord *keychord;
-    int i, size;
+    size_t i, size;
 
-    if (svc->keycodes) {
+    if (!svc->keycodes().empty()) {
         /* add a new keychord to the list */
-        size = sizeof(*keychord) + svc->nkeycodes * sizeof(keychord->keycodes[0]);
+        size = sizeof(*keychord) + svc->keycodes().size() * sizeof(keychord->keycodes[0]);
         keychords = (input_keychord*) realloc(keychords, keychords_length + size);
         if (!keychords) {
             ERROR("could not allocate keychords\n");
@@ -51,11 +52,11 @@
         keychord = (struct input_keychord *)((char *)keychords + keychords_length);
         keychord->version = KEYCHORD_VERSION;
         keychord->id = keychords_count + 1;
-        keychord->count = svc->nkeycodes;
-        svc->keychord_id = keychord->id;
+        keychord->count = svc->keycodes().size();
+        svc->set_keychord_id(keychord->id);
 
-        for (i = 0; i < svc->nkeycodes; i++) {
-            keychord->keycodes[i] = svc->keycodes[i];
+        for (i = 0; i < svc->keycodes().size(); i++) {
+            keychord->keycodes[i] = svc->keycodes()[i];
         }
         keychords_count++;
         keychords_length += size;
@@ -63,7 +64,6 @@
 }
 
 static void handle_keychord() {
-    struct service *svc;
     int ret;
     __u16 id;
 
@@ -76,10 +76,10 @@
     // Only handle keychords if adb is enabled.
     std::string adb_enabled = property_get("init.svc.adbd");
     if (adb_enabled == "running") {
-        svc = service_find_by_keychord(id);
+        Service* svc = ServiceManager::GetInstance().FindServiceByKeychord(id);
         if (svc) {
-            INFO("Starting service %s from keychord\n", svc->name);
-            service_start(svc, NULL);
+            INFO("Starting service %s from keychord\n", svc->name().c_str());
+            svc->Start();
         } else {
             ERROR("service for keychord %d not found\n", id);
         }
@@ -87,7 +87,7 @@
 }
 
 void keychord_init() {
-    service_for_each(add_service_keycodes);
+    ServiceManager::GetInstance().ForEachService(add_service_keycodes);
 
     // Nothing to do if no services require keychords.
     if (!keychords) {
diff --git a/init/service.cpp b/init/service.cpp
new file mode 100644
index 0000000..5c2a0cb
--- /dev/null
+++ b/init/service.cpp
@@ -0,0 +1,804 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "service.h"
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <termios.h>
+
+#include <selinux/selinux.h>
+
+#include <base/file.h>
+#include <base/stringprintf.h>
+#include <cutils/android_reboot.h>
+#include <cutils/sockets.h>
+
+#include "action.h"
+#include "init.h"
+#include "init_parser.h"
+#include "keywords.h"
+#include "log.h"
+#include "property_service.h"
+#include "util.h"
+
+#define CRITICAL_CRASH_THRESHOLD    4       // if we crash >4 times ...
+#define CRITICAL_CRASH_WINDOW       (4*60)  // ... in 4 minutes, goto recovery
+
+SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
+}
+
+SocketInfo::SocketInfo(const std::string& name, const std::string& type, uid_t uid,
+                       gid_t gid, int perm, const std::string& socketcon)
+    : name(name), type(type), uid(uid), gid(gid), perm(perm), socketcon(socketcon) {
+}
+
+ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
+}
+
+ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
+                                               const std::string& value)
+    : name(name), value(value) {
+}
+
+Service::Service(const std::string& name, const std::string& classname,
+                 const std::vector<std::string>& args)
+    : name_(name), classname_(classname), flags_(0), pid_(0), time_started_(0),
+      time_crashed_(0), nr_crashed_(0), uid_(0), gid_(0), seclabel_(""),
+      ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
+    onrestart_.InitSingleTrigger("onrestart");
+}
+
+Service::Service(const std::string& name, const std::string& classname,
+                 unsigned flags, uid_t uid, gid_t gid, const std::vector<gid_t>& supp_gids,
+                 const std::string& seclabel,  const std::vector<std::string>& args)
+    : name_(name), classname_(classname), flags_(flags), pid_(0), time_started_(0),
+      time_crashed_(0), nr_crashed_(0), uid_(uid), gid_(gid), supp_gids_(supp_gids),
+      seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
+    onrestart_.InitSingleTrigger("onrestart");
+}
+
+void Service::NotifyStateChange(const std::string& new_state) const {
+    if (!properties_initialized()) {
+        // If properties aren't available yet, we can't set them.
+        return;
+    }
+
+    if ((flags_ & SVC_EXEC) != 0) {
+        // 'exec' commands don't have properties tracking their state.
+        return;
+    }
+
+    std::string prop_name = android::base::StringPrintf("init.svc.%s", name_.c_str());
+    if (prop_name.length() >= PROP_NAME_MAX) {
+        // If the property name would be too long, we can't set it.
+        ERROR("Property name \"init.svc.%s\" too long; not setting to %s\n",
+              name_.c_str(), new_state.c_str());
+        return;
+    }
+
+    property_set(prop_name.c_str(), new_state.c_str());
+}
+
+bool Service::Reap() {
+    if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
+        NOTICE("Service '%s' (pid %d) killing any children in process group\n",
+               name_.c_str(), pid_);
+        kill(-pid_, SIGKILL);
+    }
+
+    // Remove any sockets we may have created.
+    for (const auto& si : sockets_) {
+        std::string tmp = android::base::StringPrintf(ANDROID_SOCKET_DIR "/%s",
+                                                      si.name.c_str());
+        unlink(tmp.c_str());
+    }
+
+    if (flags_ & SVC_EXEC) {
+        INFO("SVC_EXEC pid %d finished...\n", pid_);
+        return true;
+    }
+
+    pid_ = 0;
+    flags_ &= (~SVC_RUNNING);
+
+    // Oneshot processes go into the disabled state on exit,
+    // except when manually restarted.
+    if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
+        flags_ |= SVC_DISABLED;
+    }
+
+    // Disabled and reset processes do not get restarted automatically.
+    if (flags_ & (SVC_DISABLED | SVC_RESET))  {
+        NotifyStateChange("stopped");
+        return false;
+    }
+
+    time_t now = gettime();
+    if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
+        if (time_crashed_ + CRITICAL_CRASH_WINDOW >= now) {
+            if (++nr_crashed_ > CRITICAL_CRASH_THRESHOLD) {
+                ERROR("critical process '%s' exited %d times in %d minutes; "
+                      "rebooting into recovery mode\n", name_.c_str(),
+                      CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
+                android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
+                return false;
+            }
+        } else {
+            time_crashed_ = now;
+            nr_crashed_ = 1;
+        }
+    }
+
+    flags_ &= (~SVC_RESTART);
+    flags_ |= SVC_RESTARTING;
+
+    // Execute all onrestart commands for this service.
+    onrestart_.ExecuteAllCommands();
+
+    NotifyStateChange("restarting");
+    return false;
+}
+
+void Service::DumpState() const {
+    INFO("service %s\n", name_.c_str());
+    INFO("  class '%s'\n", classname_.c_str());
+    INFO("  exec");
+    for (const auto& s : args_) {
+        INFO(" '%s'", s.c_str());
+    }
+    INFO("\n");
+    for (const auto& si : sockets_) {
+        INFO("  socket %s %s 0%o\n", si.name.c_str(), si.type.c_str(), si.perm);
+    }
+}
+
+bool Service::HandleLine(int kw, const std::vector<std::string>& args, std::string* err) {
+    std::vector<std::string> str_args;
+
+    ioprio_class_ = IoSchedClass_NONE;
+
+    switch (kw) {
+    case K_class:
+        if (args.size() != 2) {
+            *err = "class option requires a classname\n";
+            return false;
+        } else {
+            classname_ = args[1];
+        }
+        break;
+    case K_console:
+        flags_ |= SVC_CONSOLE;
+        break;
+    case K_disabled:
+        flags_ |= SVC_DISABLED;
+        flags_ |= SVC_RC_DISABLED;
+        break;
+    case K_ioprio:
+        if (args.size() != 3) {
+            *err = "ioprio optin usage: ioprio <rt|be|idle> <ioprio 0-7>\n";
+            return false;
+        } else {
+            ioprio_pri_ = std::stoul(args[2], 0, 8);
+
+            if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
+                *err = "priority value must be range 0 - 7\n";
+                return false;
+            }
+
+            if (args[1] == "rt") {
+                ioprio_class_ = IoSchedClass_RT;
+            } else if (args[1] == "be") {
+                ioprio_class_ = IoSchedClass_BE;
+            } else if (args[1] == "idle") {
+                ioprio_class_ = IoSchedClass_IDLE;
+            } else {
+                *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>\n";
+                return false;
+            }
+        }
+        break;
+    case K_group:
+        if (args.size() < 2) {
+            *err = "group option requires a group id\n";
+            return false;
+        } else if (args.size() > NR_SVC_SUPP_GIDS + 2) {
+            *err = android::base::StringPrintf("group option accepts at most %d supp. groups\n",
+                                               NR_SVC_SUPP_GIDS);
+            return false;
+        } else {
+            gid_ = decode_uid(args[1].c_str());
+            for (std::size_t n = 2; n < args.size(); n++) {
+                supp_gids_.push_back(decode_uid(args[n].c_str()));
+            }
+        }
+        break;
+    case K_keycodes:
+        if (args.size() < 2) {
+            *err = "keycodes option requires atleast one keycode\n";
+            return false;
+        } else {
+            for (std::size_t i = 1; i < args.size(); i++) {
+                keycodes_.push_back(std::stoi(args[i]));
+            }
+        }
+        break;
+    case K_oneshot:
+        flags_ |= SVC_ONESHOT;
+        break;
+    case K_onrestart:
+        if (args.size() < 2) {
+            return false;
+        }
+        str_args.assign(args.begin() + 1, args.end());
+        add_command_to_action(&onrestart_, str_args, "", 0, err);
+        break;
+    case K_critical:
+        flags_ |= SVC_CRITICAL;
+        break;
+    case K_setenv: { /* name value */
+        if (args.size() < 3) {
+            *err = "setenv option requires name and value arguments\n";
+            return false;
+        }
+
+        envvars_.push_back({args[1], args[2]});
+        break;
+    }
+    case K_socket: {/* name type perm [ uid gid context ] */
+        if (args.size() < 4) {
+            *err = "socket option requires name, type, perm arguments\n";
+            return false;
+        }
+        if (args[2] != "dgram" && args[2] != "stream" &&
+            args[2] != "seqpacket") {
+            *err = "socket type must be 'dgram', 'stream' or 'seqpacket'\n";
+            return false;
+        }
+
+        int perm = std::stoul(args[3], 0, 8);
+        uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
+        gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
+        std::string socketcon = args.size() > 6 ? args[6] : "";
+
+        sockets_.push_back({args[1], args[2], uid, gid, perm, socketcon});
+        break;
+    }
+    case K_user:
+        if (args.size() != 2) {
+            *err = "user option requires a user id\n";
+            return false;
+        } else {
+            uid_ = decode_uid(args[1].c_str());
+        }
+        break;
+    case K_seclabel:
+        if (args.size() != 2) {
+            *err = "seclabel option requires a label string\n";
+            return false;
+        } else {
+            seclabel_ = args[1];
+        }
+        break;
+    case K_writepid:
+        if (args.size() < 2) {
+            *err = "writepid option requires at least one filename\n";
+            return false;
+        }
+        writepid_files_.assign(args.begin() + 1, args.end());
+        break;
+
+    default:
+        *err = android::base::StringPrintf("invalid option '%s'\n", args[0].c_str());
+        return false;
+    }
+    return true;
+}
+
+bool Service::Start(const std::vector<std::string>& dynamic_args) {
+    // Starting a service removes it from the disabled or reset state and
+    // immediately takes it out of the restarting state if it was in there.
+    flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
+    time_started_ = 0;
+
+    // Running processes require no additional work --- if they're in the
+    // process of exiting, we've ensured that they will immediately restart
+    // on exit, unless they are ONESHOT.
+    if (flags_ & SVC_RUNNING) {
+        return false;
+    }
+
+    bool needs_console = (flags_ & SVC_CONSOLE);
+    if (needs_console && !have_console) {
+        ERROR("service '%s' requires console\n", name_.c_str());
+        flags_ |= SVC_DISABLED;
+        return false;
+    }
+
+    struct stat sb;
+    if (stat(args_[0].c_str(), &sb) == -1) {
+        ERROR("cannot find '%s' (%s), disabling '%s'\n",
+              args_[0].c_str(), strerror(errno), name_.c_str());
+        flags_ |= SVC_DISABLED;
+        return false;
+    }
+
+    if ((!(flags_ & SVC_ONESHOT)) && !dynamic_args.empty()) {
+        ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
+              args_[0].c_str());
+        flags_ |= SVC_DISABLED;
+        return false;
+    }
+
+    std::string scon;
+    if (!seclabel_.empty()) {
+        scon = seclabel_;
+    } else {
+        char* mycon = nullptr;
+        char* fcon = nullptr;
+
+        INFO("computing context for service '%s'\n", args_[0].c_str());
+        int rc = getcon(&mycon);
+        if (rc < 0) {
+            ERROR("could not get context while starting '%s'\n", name_.c_str());
+            return false;
+        }
+
+        rc = getfilecon(args_[0].c_str(), &fcon);
+        if (rc < 0) {
+            ERROR("could not get context while starting '%s'\n", name_.c_str());
+            free(mycon);
+            return false;
+        }
+
+        char* ret_scon = nullptr;
+        rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
+                                     &ret_scon);
+        if (rc == 0) {
+            scon = ret_scon;
+            free(ret_scon);
+        }
+        if (rc == 0 && scon == mycon) {
+            ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
+            free(mycon);
+            free(fcon);
+            return false;
+        }
+        free(mycon);
+        free(fcon);
+        if (rc < 0) {
+            ERROR("could not get context while starting '%s'\n", name_.c_str());
+            return false;
+        }
+    }
+
+    NOTICE("Starting service '%s'...\n", name_.c_str());
+
+    pid_t pid = fork();
+    if (pid == 0) {
+        int fd, sz;
+
+        umask(077);
+        if (properties_initialized()) {
+            get_property_workspace(&fd, &sz);
+            std::string tmp = android::base::StringPrintf("%d,%d", dup(fd), sz);
+            add_environment("ANDROID_PROPERTY_WORKSPACE", tmp.c_str());
+        }
+
+        for (const auto& ei : envvars_) {
+            add_environment(ei.name.c_str(), ei.value.c_str());
+        }
+
+        for (const auto& si : sockets_) {
+            int socket_type = ((si.type == "stream" ? SOCK_STREAM :
+                                (si.type == "dgram" ? SOCK_DGRAM :
+                                 SOCK_SEQPACKET)));
+            const char* socketcon =
+                !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
+
+            int s = create_socket(si.name.c_str(), socket_type, si.perm,
+                                  si.uid, si.gid, socketcon);
+            if (s >= 0) {
+                PublishSocket(si.name, s);
+            }
+        }
+
+        std::string pid_str = android::base::StringPrintf("%d", pid);
+        for (const auto& file : writepid_files_) {
+            if (!android::base::WriteStringToFile(pid_str, file)) {
+                ERROR("couldn't write %s to %s: %s\n",
+                      pid_str.c_str(), file.c_str(), strerror(errno));
+            }
+        }
+
+        if (ioprio_class_ != IoSchedClass_NONE) {
+            if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
+                ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
+                      getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
+            }
+        }
+
+        if (needs_console) {
+            setsid();
+            OpenConsole();
+        } else {
+            ZapStdio();
+        }
+
+        setpgid(0, getpid());
+
+        // As requested, set our gid, supplemental gids, and uid.
+        if (gid_) {
+            if (setgid(gid_) != 0) {
+                ERROR("setgid failed: %s\n", strerror(errno));
+                _exit(127);
+            }
+        }
+        if (!supp_gids_.empty()) {
+            if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
+                ERROR("setgroups failed: %s\n", strerror(errno));
+                _exit(127);
+            }
+        }
+        if (uid_) {
+            if (setuid(uid_) != 0) {
+                ERROR("setuid failed: %s\n", strerror(errno));
+                _exit(127);
+            }
+        }
+        if (!seclabel_.empty()) {
+            if (setexeccon(seclabel_.c_str()) < 0) {
+                ERROR("cannot setexeccon('%s'): %s\n",
+                      seclabel_.c_str(), strerror(errno));
+                _exit(127);
+            }
+        }
+
+        std::vector<char*> strs;
+        for (const auto& s : args_) {
+            strs.push_back(const_cast<char*>(s.c_str()));
+        }
+        for (const auto& s : dynamic_args) {
+            strs.push_back(const_cast<char*>(s.c_str()));
+        }
+        strs.push_back(nullptr);
+        if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
+            ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), strerror(errno));
+        }
+
+        _exit(127);
+    }
+
+    if (pid < 0) {
+        ERROR("failed to start '%s'\n", name_.c_str());
+        pid_ = 0;
+        return false;
+    }
+
+    time_started_ = gettime();
+    pid_ = pid;
+    flags_ |= SVC_RUNNING;
+
+    if ((flags_ & SVC_EXEC) != 0) {
+        INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
+             pid_, uid_, gid_, supp_gids_.size(),
+             !seclabel_.empty() ? seclabel_.c_str() : "default");
+    }
+
+    NotifyStateChange("running");
+    return true;
+}
+
+bool Service::Start() {
+    const std::vector<std::string> null_dynamic_args;
+    return Start(null_dynamic_args);
+}
+
+bool Service::StartIfNotDisabled() {
+    if (!(flags_ & SVC_DISABLED)) {
+        return Start();
+    } else {
+        flags_ |= SVC_DISABLED_START;
+    }
+    return true;
+}
+
+bool Service::Enable() {
+    flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
+    if (flags_ & SVC_DISABLED_START) {
+        return Start();
+    }
+    return true;
+}
+
+void Service::Reset() {
+    StopOrReset(SVC_RESET);
+}
+
+void Service::Stop() {
+    StopOrReset(SVC_DISABLED);
+}
+
+void Service::Restart() {
+    if (flags_ & SVC_RUNNING) {
+        /* Stop, wait, then start the service. */
+        StopOrReset(SVC_RESTART);
+    } else if (!(flags_ & SVC_RESTARTING)) {
+        /* Just start the service since it's not running. */
+        Start();
+    } /* else: Service is restarting anyways. */
+}
+
+void Service::RestartIfNeeded(time_t& process_needs_restart) {
+    time_t next_start_time = time_started_ + 5;
+
+    if (next_start_time <= gettime()) {
+        flags_ &= (~SVC_RESTARTING);
+        Start();
+        return;
+    }
+
+    if ((next_start_time < process_needs_restart) ||
+        (process_needs_restart == 0)) {
+        process_needs_restart = next_start_time;
+    }
+}
+
+/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
+void Service::StopOrReset(int how) {
+    /* The service is still SVC_RUNNING until its process exits, but if it has
+     * already exited it shoudn't attempt a restart yet. */
+    flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
+
+    if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
+        /* Hrm, an illegal flag.  Default to SVC_DISABLED */
+        how = SVC_DISABLED;
+    }
+        /* if the service has not yet started, prevent
+         * it from auto-starting with its class
+         */
+    if (how == SVC_RESET) {
+        flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
+    } else {
+        flags_ |= how;
+    }
+
+    if (pid_) {
+        NOTICE("Service '%s' is being killed...\n", name_.c_str());
+        kill(-pid_, SIGKILL);
+        NotifyStateChange("stopping");
+    } else {
+        NotifyStateChange("stopped");
+    }
+}
+
+void Service::ZapStdio() const {
+    int fd;
+    fd = open("/dev/null", O_RDWR);
+    dup2(fd, 0);
+    dup2(fd, 1);
+    dup2(fd, 2);
+    close(fd);
+}
+
+void Service::OpenConsole() const {
+    int fd;
+    if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
+        fd = open("/dev/null", O_RDWR);
+    }
+    ioctl(fd, TIOCSCTTY, 0);
+    dup2(fd, 0);
+    dup2(fd, 1);
+    dup2(fd, 2);
+    close(fd);
+}
+
+void Service::PublishSocket(const std::string& name, int fd) const {
+    std::string key = android::base::StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s",
+                                                  name.c_str());
+    std::string val = android::base::StringPrintf("%d", fd);
+    add_environment(key.c_str(), val.c_str());
+
+    /* make sure we don't close-on-exec */
+    fcntl(fd, F_SETFD, 0);
+}
+
+int ServiceManager::exec_count_ = 0;
+
+ServiceManager::ServiceManager() {
+}
+
+ServiceManager& ServiceManager::GetInstance() {
+    static ServiceManager instance;
+    return instance;
+}
+
+Service* ServiceManager::AddNewService(const std::string& name,
+                                       const std::string& classname,
+                                       const std::vector<std::string>& args,
+                                       std::string* err) {
+    if (!IsValidName(name)) {
+        *err = android::base::StringPrintf("invalid service name '%s'\n", name.c_str());
+        return nullptr;
+    }
+
+    Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
+    if (svc) {
+        *err = android::base::StringPrintf("ignored duplicate definition of service '%s'\n",
+                                           name.c_str());
+        return nullptr;
+    }
+
+    std::unique_ptr<Service> svc_p(new Service(name, classname, args));
+    if (!svc_p) {
+        ERROR("Couldn't allocate service for service '%s'", name.c_str());
+        return nullptr;
+    }
+    svc = svc_p.get();
+    services_.push_back(std::move(svc_p));
+
+    return svc;
+}
+
+Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
+    // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
+    // SECLABEL can be a - to denote default
+    std::size_t command_arg = 1;
+    for (std::size_t i = 1; i < args.size(); ++i) {
+        if (args[i] == "--") {
+            command_arg = i + 1;
+            break;
+        }
+    }
+    if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
+        ERROR("exec called with too many supplementary group ids\n");
+        return nullptr;
+    }
+
+    if (command_arg >= args.size()) {
+        ERROR("exec called without command\n");
+        return nullptr;
+    }
+    std::vector<std::string> str_args(args.begin() + command_arg, args.end());
+
+    exec_count_++;
+    std::string name = android::base::StringPrintf("exec %d (%s)", exec_count_,
+                                                   str_args[0].c_str());
+    unsigned flags = SVC_EXEC | SVC_ONESHOT;
+
+    std::string seclabel = "";
+    if (command_arg > 2 && args[1] != "-") {
+        seclabel = args[1];
+    }
+    uid_t uid = 0;
+    if (command_arg > 3) {
+        uid = decode_uid(args[2].c_str());
+    }
+    gid_t gid = 0;
+    std::vector<gid_t> supp_gids;
+    if (command_arg > 4) {
+        gid = decode_uid(args[3].c_str());
+        std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
+        for (size_t i = 0; i < nr_supp_gids; ++i) {
+            supp_gids.push_back(decode_uid(args[4 + i].c_str()));
+        }
+    }
+
+    std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
+                                               supp_gids, seclabel, str_args));
+    if (!svc_p) {
+        ERROR("Couldn't allocate service for exec of '%s'",
+              str_args[0].c_str());
+        return nullptr;
+    }
+    Service* svc = svc_p.get();
+    services_.push_back(std::move(svc_p));
+
+    return svc;
+}
+
+Service* ServiceManager::FindServiceByName(const std::string& name) const {
+    auto svc = std::find_if(services_.begin(), services_.end(),
+                            [&name] (const std::unique_ptr<Service>& s) {
+                                return name == s->name();
+                            });
+    if (svc != services_.end()) {
+        return svc->get();
+    }
+    return nullptr;
+}
+
+Service* ServiceManager::FindServiceByPid(pid_t pid) const {
+    auto svc = std::find_if(services_.begin(), services_.end(),
+                            [&pid] (const std::unique_ptr<Service>& s) {
+                                return s->pid() == pid;
+                            });
+    if (svc != services_.end()) {
+        return svc->get();
+    }
+    return nullptr;
+}
+
+Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
+    auto svc = std::find_if(services_.begin(), services_.end(),
+                            [&keychord_id] (const std::unique_ptr<Service>& s) {
+                                return s->keychord_id() == keychord_id;
+                            });
+
+    if (svc != services_.end()) {
+        return svc->get();
+    }
+    return nullptr;
+}
+
+void ServiceManager::ForEachService(void (*func)(Service* svc)) const {
+    for (const auto& s : services_) {
+        func(s.get());
+    }
+}
+
+void ServiceManager::ForEachServiceInClass(const std::string& classname,
+                                           void (*func)(Service* svc)) const {
+    for (const auto& s : services_) {
+        if (classname == s->classname()) {
+            func(s.get());
+        }
+    }
+}
+
+void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
+                                             void (*func)(Service* svc)) const {
+    for (const auto& s : services_) {
+        if (s->flags() & matchflags) {
+            func(s.get());
+        }
+    }
+}
+
+void ServiceManager::RemoveService(const Service& svc)
+{
+    auto svc_it = std::find_if(services_.begin(), services_.end(),
+                               [&svc] (const std::unique_ptr<Service>& s) {
+                                   return svc.name() == s->name();
+                               });
+    if (svc_it == services_.end()) {
+        return;
+    }
+
+    services_.erase(svc_it);
+}
+
+bool ServiceManager::IsValidName(const std::string& name) const
+{
+    if (name.size() > 16) {
+        return false;
+    }
+    for (const auto& c : name) {
+        if (!isalnum(c) && (c != '_') && (c != '-')) {
+            return false;
+        }
+    }
+    return true;
+}
+
+void ServiceManager::DumpState() const
+{
+    for (const auto& s : services_) {
+        s->DumpState();
+    }
+    INFO("\n");
+}
diff --git a/init/service.h b/init/service.h
new file mode 100644
index 0000000..1ecf78a
--- /dev/null
+++ b/init/service.h
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _INIT_SERVICE_H
+#define _INIT_SERVICE_H
+
+#include <sys/types.h>
+
+#include <cutils/iosched_policy.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "action.h"
+
+#define SVC_DISABLED       0x001  // do not autostart with class
+#define SVC_ONESHOT        0x002  // do not restart on exit
+#define SVC_RUNNING        0x004  // currently active
+#define SVC_RESTARTING     0x008  // waiting to restart
+#define SVC_CONSOLE        0x010  // requires console
+#define SVC_CRITICAL       0x020  // will reboot into recovery if keeps crashing
+#define SVC_RESET          0x040  // Use when stopping a process,
+                                  // but not disabling so it can be restarted with its class.
+#define SVC_RC_DISABLED    0x080  // Remember if the disabled flag was set in the rc script.
+#define SVC_RESTART        0x100  // Use to safely restart (stop, wait, start) a service.
+#define SVC_DISABLED_START 0x200  // A start was requested but it was disabled at the time.
+#define SVC_EXEC           0x400  // This synthetic service corresponds to an 'exec'.
+
+#define NR_SVC_SUPP_GIDS 12    // twelve supplementary groups
+
+class Action;
+class ServiceManager;
+
+struct SocketInfo {
+    SocketInfo();
+    SocketInfo(const std::string& name, const std::string& type, uid_t uid,
+                       gid_t gid, int perm, const std::string& socketcon);
+    std::string name;
+    std::string type;
+    uid_t uid;
+    gid_t gid;
+    int perm;
+    std::string socketcon;
+};
+
+struct ServiceEnvironmentInfo {
+    ServiceEnvironmentInfo();
+    ServiceEnvironmentInfo(const std::string& name, const std::string& value);
+    std::string name;
+    std::string value;
+};
+
+class Service {
+public:
+    Service(const std::string& name, const std::string& classname,
+            const std::vector<std::string>& args);
+
+    Service(const std::string& name, const std::string& classname,
+            unsigned flags, uid_t uid, gid_t gid, const std::vector<gid_t>& supp_gids,
+            const std::string& seclabel,  const std::vector<std::string>& args);
+
+    bool HandleLine(int kw, const std::vector<std::string>& args, std::string* err);
+    bool Start(const std::vector<std::string>& dynamic_args);
+    bool Start();
+    bool StartIfNotDisabled();
+    bool Enable();
+    void Reset();
+    void Stop();
+    void Restart();
+    void RestartIfNeeded(time_t& process_needs_restart);
+    bool Reap();
+    void DumpState() const;
+
+    const std::string& name() const { return name_; }
+    const std::string& classname() const { return classname_; }
+    unsigned flags() const { return flags_; }
+    pid_t pid() const { return pid_; }
+    uid_t uid() const { return uid_; }
+    gid_t gid() const { return gid_; }
+    const std::vector<gid_t>& supp_gids() const { return supp_gids_; }
+    const std::string& seclabel() const { return seclabel_; }
+    const std::vector<int>& keycodes() const { return keycodes_; }
+    int keychord_id() const { return keychord_id_; }
+    void set_keychord_id(int keychord_id) { keychord_id_ = keychord_id; }
+    const std::vector<std::string>& args() const { return args_; }
+
+private:
+    void NotifyStateChange(const std::string& new_state) const;
+    void StopOrReset(int how);
+    void ZapStdio() const;
+    void OpenConsole() const;
+    void PublishSocket(const std::string& name, int fd) const;
+
+    std::string name_;
+    std::string classname_;
+
+    unsigned flags_;
+    pid_t pid_;
+    time_t time_started_;    // time of last start
+    time_t time_crashed_;    // first crash within inspection window
+    int nr_crashed_;         // number of times crashed within window
+
+    uid_t uid_;
+    gid_t gid_;
+    std::vector<gid_t> supp_gids_;
+
+    std::string seclabel_;
+
+    std::vector<SocketInfo> sockets_;
+    std::vector<ServiceEnvironmentInfo> envvars_;
+
+    Action onrestart_;  // Commands to execute on restart.
+
+    std::vector<std::string> writepid_files_;
+
+    // keycodes for triggering this service via /dev/keychord
+    std::vector<int> keycodes_;
+    int keychord_id_;
+
+    IoSchedClass ioprio_class_;
+    int ioprio_pri_;
+
+    std::vector<std::string> args_;
+};
+
+class ServiceManager {
+public:
+    static ServiceManager& GetInstance();
+
+    Service* AddNewService(const std::string& name, const std::string& classname,
+                                           const std::vector<std::string>& args,
+                                           std::string* err);
+    Service* MakeExecOneshotService(const std::vector<std::string>& args);
+    Service* FindServiceByName(const std::string& name) const;
+    Service* FindServiceByPid(pid_t pid) const;
+    Service* FindServiceByKeychord(int keychord_id) const;
+    void ForEachService(void (*func)(Service* svc)) const;
+    void ForEachServiceInClass(const std::string& classname,
+                               void (*func)(Service* svc)) const;
+    void ForEachServiceWithFlags(unsigned matchflags,
+                             void (*func)(Service* svc)) const;
+    void RemoveService(const Service& svc);
+    void DumpState() const;
+private:
+    ServiceManager();
+
+    bool IsValidName(const std::string& name) const;
+
+    static int exec_count_; // Every service needs a unique name.
+    std::vector<std::unique_ptr<Service>> services_;
+};
+
+#endif
diff --git a/init/signal_handler.cpp b/init/signal_handler.cpp
index 5a875bb..867abbc 100644
--- a/init/signal_handler.cpp
+++ b/init/signal_handler.cpp
@@ -31,11 +31,9 @@
 #include "action.h"
 #include "init.h"
 #include "log.h"
+#include "service.h"
 #include "util.h"
 
-#define CRITICAL_CRASH_THRESHOLD    4       /* if we crash >4 times ... */
-#define CRITICAL_CRASH_WINDOW       (4*60)  /* ... in 4 minutes, goto recovery */
-
 static int signal_write_fd = -1;
 static int signal_read_fd = -1;
 
@@ -61,11 +59,11 @@
         return false;
     }
 
-    service* svc = service_find_by_pid(pid);
+    Service* svc = ServiceManager::GetInstance().FindServiceByPid(pid);
 
     std::string name;
     if (svc) {
-        name = android::base::StringPrintf("Service '%s' (pid %d)", svc->name, pid);
+        name = android::base::StringPrintf("Service '%s' (pid %d)", svc->name().c_str(), pid);
     } else {
         name = android::base::StringPrintf("Untracked pid %d", pid);
     }
@@ -76,67 +74,11 @@
         return true;
     }
 
-    // TODO: all the code from here down should be a member function on service.
-
-    if (!(svc->flags & SVC_ONESHOT) || (svc->flags & SVC_RESTART)) {
-        NOTICE("Service '%s' (pid %d) killing any children in process group\n", svc->name, pid);
-        kill(-pid, SIGKILL);
-    }
-
-    // Remove any sockets we may have created.
-    for (socketinfo* si = svc->sockets; si; si = si->next) {
-        char tmp[128];
-        snprintf(tmp, sizeof(tmp), ANDROID_SOCKET_DIR"/%s", si->name);
-        unlink(tmp);
-    }
-
-    if (svc->flags & SVC_EXEC) {
-        INFO("SVC_EXEC pid %d finished...\n", svc->pid);
+    if (svc->Reap()) {
         waiting_for_exec = false;
-        list_remove(&svc->slist);
-        free(svc->name);
-        free(svc);
-        return true;
+        ServiceManager::GetInstance().RemoveService(*svc);
     }
 
-    svc->pid = 0;
-    svc->flags &= (~SVC_RUNNING);
-
-    // Oneshot processes go into the disabled state on exit,
-    // except when manually restarted.
-    if ((svc->flags & SVC_ONESHOT) && !(svc->flags & SVC_RESTART)) {
-        svc->flags |= SVC_DISABLED;
-    }
-
-    // Disabled and reset processes do not get restarted automatically.
-    if (svc->flags & (SVC_DISABLED | SVC_RESET))  {
-        svc->NotifyStateChange("stopped");
-        return true;
-    }
-
-    time_t now = gettime();
-    if ((svc->flags & SVC_CRITICAL) && !(svc->flags & SVC_RESTART)) {
-        if (svc->time_crashed + CRITICAL_CRASH_WINDOW >= now) {
-            if (++svc->nr_crashed > CRITICAL_CRASH_THRESHOLD) {
-                ERROR("critical process '%s' exited %d times in %d minutes; "
-                      "rebooting into recovery mode\n", svc->name,
-                      CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
-                android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
-                return true;
-            }
-        } else {
-            svc->time_crashed = now;
-            svc->nr_crashed = 1;
-        }
-    }
-
-    svc->flags &= (~SVC_RESTART);
-    svc->flags |= SVC_RESTARTING;
-
-    // Execute all onrestart commands for this service.
-    svc->onrestart->ExecuteAllCommands();
-
-    svc->NotifyStateChange("restarting");
     return true;
 }