init: shutdown services in the opposite order that they started

Currently, the order that we kill to services during shutdown is the
order of services_ in ServiceManager and that is defacto the order in
which they were parsed, which is not a very useful ordering.

Related to this, we have seen a few issues during shutdown that may be
related to services with dependencies on other services, where the
dependency is killed first and the dependent service then misbehaves.

This change allows services to keep track of the order in which they
were started and shutdown then uses that information to kill running
services in the opposite order that they were started.

Bug: 64067984
Test: Boot and reboot bullhead

Change-Id: I6b4cacb03aed2a72ae98a346bce41ed5434a09c2
diff --git a/init/service.h b/init/service.h
index 62a3299..a0dc1b4 100644
--- a/init/service.h
+++ b/init/service.h
@@ -108,6 +108,7 @@
     int priority() const { return priority_; }
     int oom_score_adjust() const { return oom_score_adjust_; }
     bool process_cgroup_empty() const { return process_cgroup_empty_; }
+    unsigned long start_order() const { return start_order_; }
     const std::vector<std::string>& args() const { return args_; }
 
   private:
@@ -149,6 +150,8 @@
     template <typename T>
     bool AddDescriptor(const std::vector<std::string>& args, std::string* err);
 
+    static unsigned long next_start_order_;
+
     std::string name_;
     std::set<std::string> classnames_;
     std::string console_;
@@ -190,6 +193,8 @@
 
     bool process_cgroup_empty_ = false;
 
+    unsigned long start_order_;
+
     std::vector<std::string> args_;
 };
 
@@ -209,6 +214,7 @@
     Service* FindServiceByPid(pid_t pid) const;
     Service* FindServiceByKeychord(int keychord_id) const;
     void ForEachService(const std::function<void(Service*)>& callback) const;
+    void ForEachServiceShutdownOrder(const std::function<void(Service*)>& callback) const;
     void ForEachServiceInClass(const std::string& classname,
                                void (*func)(Service* svc)) const;
     void ForEachServiceWithFlags(unsigned matchflags,