Merge "Add feature declarations for a VR mode."
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index b52ac77..4d4e0ce 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -94,6 +94,7 @@
     { "power",      "Power Management", ATRACE_TAG_POWER, { } },
     { "pm",         "Package Manager",  ATRACE_TAG_PACKAGE_MANAGER, { } },
     { "ss",         "System Server",    ATRACE_TAG_SYSTEM_SERVER, { } },
+    { "database",   "Database",         ATRACE_TAG_DATABASE, { } },
     { "sched",      "CPU Scheduling",   0, {
         { REQ,      "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
         { REQ,      "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
diff --git a/cmds/atrace/atrace.rc b/cmds/atrace/atrace.rc
index a5916af..c2f8891 100644
--- a/cmds/atrace/atrace.rc
+++ b/cmds/atrace/atrace.rc
@@ -55,6 +55,9 @@
     chmod 0664 /sys/kernel/debug/tracing/events/binder/binder_locked/enable
     chmod 0664 /sys/kernel/debug/tracing/events/binder/binder_unlock/enable
 
+    # Tracing disabled by default
+    write /sys/kernel/debug/tracing/tracing_on 0
+
 # Allow only the shell group to read and truncate the kernel trace.
     chown root shell /sys/kernel/debug/tracing/trace
     chmod 0660 /sys/kernel/debug/tracing/trace
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index 8b04b01..a08014d 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -17,8 +17,10 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <libgen.h>
 #include <limits.h>
 #include <memory>
+#include <regex>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -32,7 +34,7 @@
 #include <sys/wait.h>
 #include <unistd.h>
 
-#include <base/stringprintf.h>
+#include <android-base/stringprintf.h>
 #include <cutils/properties.h>
 
 #include "private/android_filesystem_config.h"
@@ -50,8 +52,6 @@
 static char cmdline_buf[16384] = "(unknown)";
 static const char *dump_traces_path = NULL;
 
-static std::string screenshot_path;
-
 #define PSTORE_LAST_KMSG "/sys/fs/pstore/console-ramoops"
 
 #define RAFT_DIR "/data/misc/raft/"
@@ -270,7 +270,7 @@
 /* End copy from system/core/logd/LogBuffer.cpp */
 
 /* dumps the current system state to stdout */
-static void dumpstate() {
+static void dumpstate(const std::string& screenshot_path) {
     unsigned long timeout;
     time_t now = time(NULL);
     char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX];
@@ -305,6 +305,7 @@
     dump_dev_files("TRUSTY VERSION", "/sys/bus/platform/drivers/trusty", "trusty_version");
     run_command("UPTIME", 10, "uptime", NULL);
     dump_files("UPTIME MMC PERF", mmcblk0, skip_not_stat, dump_stat_from_fd);
+    dump_emmc_ecsd("/d/mmc0/mmc0:0001/ext_csd");
     dump_file("MEMORY INFO", "/proc/meminfo");
     run_command("CPU INFO", 10, "top", "-n", "1", "-d", "1", "-m", "30", "-H", NULL);
     run_command("PROCRANK", 20, SU_PATH, "root", "procrank", NULL);
@@ -331,9 +332,8 @@
     for_each_tid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS");
 
     if (!screenshot_path.empty()) {
-        ALOGI("taking screenshot\n");
-        const char *args[] = { "/system/bin/screencap", "-p", screenshot_path.c_str(), NULL };
-        run_command_always(NULL, 10, args);
+        ALOGI("taking late screenshot\n");
+        take_screenshot(screenshot_path);
         ALOGI("wrote screenshot: %s\n", screenshot_path.c_str());
     }
 
@@ -347,11 +347,12 @@
                                                         "-v", "printable",
                                                         "-d",
                                                         "*:v", NULL);
-    timeout = logcat_timeout("events");
+    timeout = logcat_timeout("events") + logcat_timeout("security");
     if (timeout < 20000) {
         timeout = 20000;
     }
     run_command("EVENT LOG", timeout / 1000, "logcat", "-b", "events",
+                                                       "-b", "security",
                                                        "-v", "threadtime",
                                                        "-v", "printable",
                                                        "-d",
@@ -686,6 +687,7 @@
     int use_socket = 0;
     int do_fb = 0;
     int do_broadcast = 0;
+    int do_early_screenshot = 0;
 
     if (getuid() != 0) {
         // Old versions of the adb client would call the
@@ -741,52 +743,68 @@
         exit(1);
     }
 
+    do_early_screenshot = do_update_progress;
+
     // If we are going to use a socket, do it as early as possible
     // to avoid timeouts from bugreport.
     if (use_socket) {
         redirect_to_socket(stdout, "dumpstate");
     }
 
-    /* redirect output if needed */
-    std::string text_path, zip_path, tmp_path, entry_name;
+    /* full path of the directory where the bug report files will be written */
+    std::string bugreport_dir;
+
+    /* full path of the temporary file containing the bug report */
+    std::string tmp_path;
+
+    /* full path of the temporary file containing the screenshot (when requested) */
+    std::string screenshot_path;
+
+    /* base name (without suffix or extensions) of the bug report files */
+    std::string base_name;
+
+    /* suffix of the bug report files - it's typically the date (when invoked with -d),
+     * although it could be changed by the user using a system property */
+    std::string suffix;
 
     /* pointer to the actual path, be it zip or text */
     std::string path;
 
     time_t now = time(NULL);
 
+    /* redirect output if needed */
     bool is_redirecting = !use_socket && use_outfile;
 
     if (is_redirecting) {
-        text_path = use_outfile;
+        bugreport_dir = dirname(use_outfile);
+        base_name = basename(use_outfile);
         if (do_add_date) {
             char date[80];
-            strftime(date, sizeof(date), "-%Y-%m-%d-%H-%M-%S", localtime(&now));
-            text_path += date;
+            strftime(date, sizeof(date), "%Y-%m-%d-%H-%M-%S", localtime(&now));
+            suffix = date;
+        } else {
+            suffix = "undated";
         }
         if (do_fb) {
-            screenshot_path = text_path + ".png";
+            // TODO: if dumpstate was an object, the paths could be internal variables and then
+            // we could have a function to calculate the derived values, such as:
+            //     screenshot_path = GetPath(".png");
+            screenshot_path = bugreport_dir + "/" + base_name + "-" + suffix + ".png";
         }
-        zip_path = text_path + ".zip";
-        text_path += ".txt";
-        tmp_path = text_path + ".tmp";
-        entry_name = basename(text_path.c_str());
+        tmp_path = bugreport_dir + "/" + base_name + "-" + suffix + ".tmp";
 
-        ALOGD("Temporary path: %s\ntext path: %s\nzip path: %s\nzip entry: %s",
-              tmp_path.c_str(), text_path.c_str(), zip_path.c_str(), entry_name.c_str());
+        ALOGD("Bugreport dir: %s\nBase name: %s\nSuffix: %s\nTemporary path: %s\n"
+                "Screenshot path: %s\n", bugreport_dir.c_str(), base_name.c_str(), suffix.c_str(),
+                tmp_path.c_str(), screenshot_path.c_str());
 
         if (do_update_progress) {
-            if (!entry_name.empty()) {
-                std::vector<std::string> am_args = {
-                     "--receiver-permission", "android.permission.DUMP",
-                     "--es", "android.intent.extra.NAME", entry_name,
-                     "--ei", "android.intent.extra.PID", std::to_string(getpid()),
-                     "--ei", "android.intent.extra.MAX", std::to_string(WEIGHT_TOTAL),
-                };
-                send_broadcast("android.intent.action.BUGREPORT_STARTED", am_args);
-            } else {
-                ALOGE("Skipping started broadcast because entry name could not be inferred\n");
-            }
+            std::vector<std::string> am_args = {
+                 "--receiver-permission", "android.permission.DUMP",
+                 "--es", "android.intent.extra.NAME", suffix,
+                 "--ei", "android.intent.extra.PID", std::to_string(getpid()),
+                 "--ei", "android.intent.extra.MAX", std::to_string(WEIGHT_TOTAL),
+            };
+            send_broadcast("android.intent.action.BUGREPORT_STARTED", am_args);
         }
     }
 
@@ -799,6 +817,21 @@
         }
     }
 
+    if (do_fb && do_early_screenshot) {
+        if (screenshot_path.empty()) {
+            // should not have happened
+            ALOGE("INTERNAL ERROR: skipping early screenshot because path was not set");
+        } else {
+            ALOGI("taking early screenshot\n");
+            take_screenshot(screenshot_path);
+            ALOGI("wrote screenshot: %s\n", screenshot_path.c_str());
+            if (chown(screenshot_path.c_str(), AID_SHELL, AID_SHELL)) {
+                ALOGE("Unable to change ownership of screenshot file %s: %s\n",
+                        screenshot_path.c_str(), strerror(errno));
+            }
+        }
+    }
+
     /* read /proc/cmdline before dropping root */
     FILE *cmdline = fopen("/proc/cmdline", "re");
     if (cmdline) {
@@ -852,15 +885,13 @@
     }
 
     if (is_redirecting) {
-        ALOGD("Temporary path: %s\ntext path: %s\nzip path: %s\nzip entry: %s",
-              tmp_path.c_str(), text_path.c_str(), zip_path.c_str(), entry_name.c_str());
         /* TODO: rather than generating a text file now and zipping it later,
            it would be more efficient to redirect stdout to the zip entry
            directly, but the libziparchive doesn't support that option yet. */
         redirect_to_file(stdout, const_cast<char*>(tmp_path.c_str()));
     }
 
-    dumpstate();
+    dumpstate(do_early_screenshot ? "": screenshot_path);
 
     /* done */
     if (vibrator) {
@@ -877,10 +908,42 @@
 
     /* rename or zip the (now complete) .tmp file to its final location */
     if (use_outfile) {
+
+        /* check if user changed the suffix using system properties */
+        char key[PROPERTY_KEY_MAX];
+        char value[PROPERTY_VALUE_MAX];
+        sprintf(key, "dumpstate.%d.name", getpid());
+        property_get(key, value, "");
+        bool change_suffix= false;
+        if (value[0]) {
+            /* must whitelist which characters are allowed, otherwise it could cross directories */
+            std::regex valid_regex("^[-_a-zA-Z0-9]+$");
+            if (std::regex_match(value, valid_regex)) {
+                change_suffix = true;
+            } else {
+                ALOGE("invalid suffix provided by user: %s", value);
+            }
+        }
+        if (change_suffix) {
+            ALOGI("changing suffix from %s to %s", suffix.c_str(), value);
+            suffix = value;
+            if (!screenshot_path.empty()) {
+                std::string new_screenshot_path =
+                        bugreport_dir + "/" + base_name + "-" + suffix + ".png";
+                if (rename(screenshot_path.c_str(), new_screenshot_path.c_str())) {
+                    ALOGE("rename(%s, %s): %s\n", screenshot_path.c_str(),
+                            new_screenshot_path.c_str(), strerror(errno));
+                } else {
+                    screenshot_path = new_screenshot_path;
+                }
+            }
+        }
+
         bool do_text_file = true;
         if (do_zip_file) {
-            path = zip_path;
-            if (!generate_zip_file(tmp_path, zip_path, entry_name, now)) {
+            ALOGD("Generating .zip bugreport");
+            path = bugreport_dir + "/" + base_name + "-" + suffix + ".zip";
+            if (!generate_zip_file(tmp_path, path, base_name + "-" + suffix + ".txt", now)) {
                 ALOGE("Failed to generate zip file; sending text bugreport instead\n");
                 do_text_file = true;
             } else {
@@ -888,9 +951,10 @@
             }
         }
         if (do_text_file) {
-            path = text_path;
-            if (rename(tmp_path.c_str(), text_path.c_str())) {
-                ALOGE("rename(%s, %s): %s\n", tmp_path.c_str(), text_path.c_str(), strerror(errno));
+            ALOGD("Generating .txt bugreport");
+            path = bugreport_dir + "/" + base_name + "-" + suffix + ".txt";
+            if (rename(tmp_path.c_str(), path.c_str())) {
+                ALOGE("rename(%s, %s): %s\n", tmp_path.c_str(), path.c_str(), strerror(errno));
                 path.clear();
             }
         }
@@ -916,6 +980,7 @@
         }
     }
 
+    ALOGD("Final progress: %d/%d (originally %d)\n", progress, weight_total, WEIGHT_TOTAL);
     ALOGI("done\n");
 
     return 0;
diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h
index 2ba5ccb..df9721d 100644
--- a/cmds/dumpstate/dumpstate.h
+++ b/cmds/dumpstate/dumpstate.h
@@ -51,8 +51,12 @@
  * can be calculated by dividing the all completed weight by the total weight.
  *
  * This value is defined empirically and it need to be adjusted as more sections are added.
- * It does not need to match the exact sum of all sections, but it should to be more than it,
- * otherwise the calculated progress would be more than 100%.
+ *
+ * It does not need to match the exact sum of all sections, but ideally it should to be slight more
+ * than such sum: a value too high will cause the bugreport to finish before the user expected (for
+ * example, jumping from 70% to 100%), while a value too low will cause the progress to fluctuate
+ * down (for example, from 70% to 50%, since the actual max will be automatically increased every
+ * time it is reached).
  */
 static const int WEIGHT_TOTAL = 4000;
 
@@ -65,7 +69,7 @@
  * It would be better to take advantage of the C++ migration and encapsulate the state in an object,
  * but that will be better handled in a major C++ refactoring, which would also get rid of other C
  * idioms (like using std::string instead of char*, removing varargs, etc...) */
-extern int do_update_progress;
+extern int do_update_progress, progress, weight_total;
 
 /* prints the contents of a file */
 int dump_file(const char *title, const char *path);
@@ -135,8 +139,14 @@
 /* Implemented by libdumpstate_board to dump board-specific info */
 void dumpstate_board();
 
+/* Takes a screenshot and save it to the given file */
+void take_screenshot(const std::string& path);
+
 #ifdef __cplusplus
 }
 #endif
 
+/* dump eMMC Extended CSD data */
+void dump_emmc_ecsd(const char *ext_csd_path);
+
 #endif /* _DUMPSTATE_H_ */
diff --git a/cmds/dumpstate/dumpstate.rc b/cmds/dumpstate/dumpstate.rc
index cd5d6c4..e21fd7c 100644
--- a/cmds/dumpstate/dumpstate.rc
+++ b/cmds/dumpstate/dumpstate.rc
@@ -1,5 +1,20 @@
+on boot
+    # Allow bugreports access to eMMC 5.0 stats
+    chown root mount /sys/kernel/debug/mmc0/mmc0:0001/ext_csd
+    chmod 0440 /sys/kernel/debug/mmc0/mmc0:0001/ext_csd
+
 service dumpstate /system/bin/dumpstate -s
     class main
     socket dumpstate stream 0660 shell log
     disabled
     oneshot
+
+# bugreportplus is an enhanced version of bugreport that provides a better
+# user interface (like displaying progress and allowing user to enter details).
+# It's typically triggered by the power button or developer settings.
+# TODO: remove the -p option when screenshot is taken by Shell
+service bugreportplus /system/bin/dumpstate -d -p -B -P -z \
+        -o /data/data/com.android.shell/files/bugreports/bugreport
+    class main
+    disabled
+    oneshot
diff --git a/cmds/dumpstate/utils.cpp b/cmds/dumpstate/utils.cpp
index 8683155..d448c74 100644
--- a/cmds/dumpstate/utils.cpp
+++ b/cmds/dumpstate/utils.cpp
@@ -50,6 +50,7 @@
 
 /* list of native processes to include in the native dumps */
 static const char* native_processes_to_dump[] = {
+        "/system/bin/audioserver",
         "/system/bin/drmserver",
         "/system/bin/mediaserver",
         "/system/bin/sdcard",
@@ -553,7 +554,7 @@
 
 void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
     if (args.size() > 1000) {
-        fprintf(stderr, "send_broadcast: too many arguments (%d)\n", args.size());
+        fprintf(stderr, "send_broadcast: too many arguments (%d)\n", (int) args.size());
         return;
     }
     const char *am_args[1024] = { "/system/bin/am", "broadcast", "--user", "0",
@@ -841,6 +842,7 @@
 /* overall progress */
 int progress = 0;
 int do_update_progress = 0; // Set by dumpstate.cpp
+int weight_total = WEIGHT_TOTAL;
 
 // TODO: make this function thread safe if sections are generated in parallel.
 void update_progress(int delta) {
@@ -850,12 +852,27 @@
 
     char key[PROPERTY_KEY_MAX];
     char value[PROPERTY_VALUE_MAX];
+
+    // adjusts max on the fly
+    if (progress > weight_total) {
+        int new_total = weight_total * 1.2;
+        fprintf(stderr, "Adjusting total weight from %d to %d\n", weight_total, new_total);
+        weight_total = new_total;
+        sprintf(key, "dumpstate.%d.max", getpid());
+        sprintf(value, "%d", weight_total);
+        int status = property_set(key, value);
+        if (status) {
+            ALOGW("Could not update max weight by setting system property %s to %s: %d\n",
+                    key, value, status);
+        }
+    }
+
     sprintf(key, "dumpstate.%d.progress", getpid());
     sprintf(value, "%d", progress);
 
     // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
     // directly for debuggging.
-    fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, WEIGHT_TOTAL);
+    fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
 
     int status = property_set(key, value);
     if (status) {
@@ -863,3 +880,125 @@
                 key, value, status);
     }
 }
+
+void take_screenshot(const std::string& path) {
+    const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
+    run_command_always(NULL, 10, args);
+}
+
+void dump_emmc_ecsd(const char *ext_csd_path) {
+    static const size_t EXT_CSD_REV = 192;
+    static const size_t EXT_PRE_EOL_INFO = 267;
+    static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
+    static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
+    struct hex {
+        char str[2];
+    } buffer[512];
+    int fd, ext_csd_rev, ext_pre_eol_info;
+    ssize_t bytes_read;
+    static const char *ver_str[] = {
+        "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
+    };
+    static const char *eol_str[] = {
+        "Undefined",
+        "Normal",
+        "Warning (consumed 80% of reserve)",
+        "Urgent (consumed 90% of reserve)"
+    };
+
+    printf("------ %s Extended CSD ------\n", ext_csd_path);
+
+    fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
+                                 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
+    if (fd < 0) {
+        printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
+        return;
+    }
+
+    bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
+    close(fd);
+    if (bytes_read < 0) {
+        printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
+        return;
+    }
+    if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
+        printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
+        return;
+    }
+
+    ext_csd_rev = 0;
+    if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
+        printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
+               ext_csd_path, buffer[EXT_CSD_REV].str);
+        return;
+    }
+
+    printf("rev 1.%d (MMC %s)\n",
+           ext_csd_rev,
+           (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
+               ver_str[ext_csd_rev] :
+               "Unknown");
+    if (ext_csd_rev < 7) {
+        printf("\n");
+        return;
+    }
+
+    if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
+        printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
+        return;
+    }
+
+    ext_pre_eol_info = 0;
+    if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
+        printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
+               ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
+        return;
+    }
+    printf("PRE_EOL_INFO %d (MMC %s)\n",
+           ext_pre_eol_info,
+           eol_str[(ext_pre_eol_info < (int)
+                       (sizeof(eol_str) / sizeof(eol_str[0]))) ?
+                           ext_pre_eol_info : 0]);
+
+    for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
+            lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
+            ++lifetime) {
+        int ext_device_life_time_est;
+        static const char *est_str[] = {
+            "Undefined",
+            "0-10% of device lifetime used",
+            "10-20% of device lifetime used",
+            "20-30% of device lifetime used",
+            "30-40% of device lifetime used",
+            "40-50% of device lifetime used",
+            "50-60% of device lifetime used",
+            "60-70% of device lifetime used",
+            "70-80% of device lifetime used",
+            "80-90% of device lifetime used",
+            "90-100% of device lifetime used",
+            "Exceeded the maximum estimated device lifetime",
+        };
+
+        if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
+            printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
+            break;
+        }
+
+        ext_device_life_time_est = 0;
+        if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
+            printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
+                   ext_csd_path,
+                   (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
+                   buffer[lifetime].str);
+            continue;
+        }
+        printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
+               (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
+               ext_device_life_time_est,
+               est_str[(ext_device_life_time_est < (int)
+                           (sizeof(est_str) / sizeof(est_str[0]))) ?
+                               ext_device_life_time_est : 0]);
+    }
+
+    printf("\n");
+}
diff --git a/cmds/installd/Android.mk b/cmds/installd/Android.mk
index eaeeb22..488de0f 100644
--- a/cmds/installd/Android.mk
+++ b/cmds/installd/Android.mk
@@ -1,6 +1,6 @@
 LOCAL_PATH := $(call my-dir)
 
-common_src_files := commands.cpp utils.cpp
+common_src_files := commands.cpp globals.cpp utils.cpp
 common_cflags := -Wall -Werror
 
 #
@@ -41,3 +41,7 @@
 LOCAL_INIT_RC := installd.rc
 LOCAL_CLANG := true
 include $(BUILD_EXECUTABLE)
+
+# Tests.
+
+include $(LOCAL_PATH)/tests/Android.mk
\ No newline at end of file
diff --git a/cmds/installd/commands.cpp b/cmds/installd/commands.cpp
index 2fd5cd2..7544e4d 100644
--- a/cmds/installd/commands.cpp
+++ b/cmds/installd/commands.cpp
@@ -14,32 +14,40 @@
 ** limitations under the License.
 */
 
-#include "installd.h"
+#include "commands.h"
 
-#include <base/stringprintf.h>
-#include <base/logging.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <sys/capability.h>
+#include <sys/file.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <android-base/stringprintf.h>
+#include <android-base/logging.h>
+#include <cutils/fs.h>
+#include <cutils/log.h>               // TODO: Move everything to base/logging.
 #include <cutils/sched_policy.h>
 #include <diskusage/dirsize.h>
 #include <logwrap/logwrap.h>
-#include <system/thread_defs.h>
+#include <private/android_filesystem_config.h>
 #include <selinux/android.h>
+#include <system/thread_defs.h>
 
-#include <inttypes.h>
-#include <sys/capability.h>
-#include <sys/file.h>
-#include <unistd.h>
+#include <globals.h>
+#include <installd_deps.h>
+#include <utils.h>
+
+#ifndef LOG_TAG
+#define LOG_TAG "installd"
+#endif
 
 using android::base::StringPrintf;
 
-/* Directory records that are used in execution of commands. */
-dir_rec_t android_data_dir;
-dir_rec_t android_asec_dir;
-dir_rec_t android_app_dir;
-dir_rec_t android_app_private_dir;
-dir_rec_t android_app_lib_dir;
-dir_rec_t android_media_dir;
-dir_rec_t android_mnt_expand_dir;
-dir_rec_array_t android_system_dirs;
+namespace android {
+namespace installd {
 
 static const char* kCpPath = "/system/bin/cp";
 
@@ -419,8 +427,8 @@
         return -1;
     }
 
-    if (create_cache_path(src_dex, src, instruction_set)) return -1;
-    if (create_cache_path(dst_dex, dst, instruction_set)) return -1;
+    if (!create_cache_path(src_dex, src, instruction_set)) return -1;
+    if (!create_cache_path(dst_dex, dst, instruction_set)) return -1;
 
     ALOGV("move %s -> %s\n", src_dex, dst_dex);
     if (rename(src_dex, dst_dex) < 0) {
@@ -440,7 +448,7 @@
         return -1;
     }
 
-    if (create_cache_path(dex_path, path, instruction_set)) return -1;
+    if (!create_cache_path(dex_path, path, instruction_set)) return -1;
 
     ALOGV("unlink %s\n", dex_path);
     if (unlink(dex_path) < 0) {
@@ -494,7 +502,7 @@
     }
 
     /* count the cached dexfile as code */
-    if (!create_cache_path(path, apkpath, instruction_set)) {
+    if (create_cache_path(path, apkpath, instruction_set)) {
         if (stat(path, &s) == 0) {
             codesize += stat_size(&s);
         }
@@ -588,51 +596,11 @@
     return 0;
 }
 
-int create_cache_path(char path[PKG_PATH_MAX], const char *src, const char *instruction_set)
-{
-    char *tmp;
-    int srclen;
-    int dstlen;
-
-    srclen = strlen(src);
-
-        /* demand that we are an absolute path */
-    if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
-        return -1;
-    }
-
-    if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
-        return -1;
-    }
-
-    dstlen = srclen + strlen(DALVIK_CACHE_PREFIX) +
-        strlen(instruction_set) +
-        strlen(DALVIK_CACHE_POSTFIX) + 2;
-
-    if (dstlen > PKG_PATH_MAX) {
-        return -1;
-    }
-
-    sprintf(path,"%s%s/%s%s",
-            DALVIK_CACHE_PREFIX,
-            instruction_set,
-            src + 1, /* skip the leading / */
-            DALVIK_CACHE_POSTFIX);
-
-    for(tmp = path + strlen(DALVIK_CACHE_PREFIX) + strlen(instruction_set) + 1; *tmp; tmp++) {
-        if (*tmp == '/') {
-            *tmp = '@';
-        }
-    }
-
-    return 0;
-}
-
 static int split_count(const char *str)
 {
   char *ctx;
   int count = 0;
-  char buf[PROPERTY_VALUE_MAX];
+  char buf[kPropertyValueMax];
 
   strncpy(buf, str, sizeof(buf));
   char *pBuf = buf;
@@ -661,7 +629,7 @@
 }
 
 static void run_patchoat(int input_fd, int oat_fd, const char* input_file_name,
-    const char* output_file_name, const char *pkgname __unused, const char *instruction_set)
+    const char* output_file_name, const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
 {
     static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
     static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
@@ -701,8 +669,8 @@
 }
 
 static bool check_boolean_property(const char* property_name, bool default_value = false) {
-    char tmp_property_value[PROPERTY_VALUE_MAX];
-    bool have_property = property_get(property_name, tmp_property_value, nullptr) > 0;
+    char tmp_property_value[kPropertyValueMax];
+    bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
     if (!have_property) {
         return default_value;
     }
@@ -721,50 +689,50 @@
         return;
     }
 
-    char dex2oat_Xms_flag[PROPERTY_VALUE_MAX];
-    bool have_dex2oat_Xms_flag = property_get("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
+    char dex2oat_Xms_flag[kPropertyValueMax];
+    bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
 
-    char dex2oat_Xmx_flag[PROPERTY_VALUE_MAX];
-    bool have_dex2oat_Xmx_flag = property_get("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
+    char dex2oat_Xmx_flag[kPropertyValueMax];
+    bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
 
-    char dex2oat_compiler_filter_flag[PROPERTY_VALUE_MAX];
-    bool have_dex2oat_compiler_filter_flag = property_get("dalvik.vm.dex2oat-filter",
+    char dex2oat_compiler_filter_flag[kPropertyValueMax];
+    bool have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
                                                           dex2oat_compiler_filter_flag, NULL) > 0;
 
-    char dex2oat_threads_buf[PROPERTY_VALUE_MAX];
-    bool have_dex2oat_threads_flag = property_get(post_bootcomplete
+    char dex2oat_threads_buf[kPropertyValueMax];
+    bool have_dex2oat_threads_flag = get_property(post_bootcomplete
                                                       ? "dalvik.vm.dex2oat-threads"
                                                       : "dalvik.vm.boot-dex2oat-threads",
                                                   dex2oat_threads_buf,
                                                   NULL) > 0;
-    char dex2oat_threads_arg[PROPERTY_VALUE_MAX + 2];
+    char dex2oat_threads_arg[kPropertyValueMax + 2];
     if (have_dex2oat_threads_flag) {
         sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
     }
 
-    char dex2oat_isa_features_key[PROPERTY_KEY_MAX];
+    char dex2oat_isa_features_key[kPropertyKeyMax];
     sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
-    char dex2oat_isa_features[PROPERTY_VALUE_MAX];
-    bool have_dex2oat_isa_features = property_get(dex2oat_isa_features_key,
+    char dex2oat_isa_features[kPropertyValueMax];
+    bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
                                                   dex2oat_isa_features, NULL) > 0;
 
-    char dex2oat_isa_variant_key[PROPERTY_KEY_MAX];
+    char dex2oat_isa_variant_key[kPropertyKeyMax];
     sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
-    char dex2oat_isa_variant[PROPERTY_VALUE_MAX];
-    bool have_dex2oat_isa_variant = property_get(dex2oat_isa_variant_key,
+    char dex2oat_isa_variant[kPropertyValueMax];
+    bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
                                                  dex2oat_isa_variant, NULL) > 0;
 
     const char *dex2oat_norelocation = "-Xnorelocate";
     bool have_dex2oat_relocation_skip_flag = false;
 
-    char dex2oat_flags[PROPERTY_VALUE_MAX];
-    int dex2oat_flags_count = property_get("dalvik.vm.dex2oat-flags",
+    char dex2oat_flags[kPropertyValueMax];
+    int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
                                  dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
     ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
 
     // If we booting without the real /data, don't spend time compiling.
-    char vold_decrypt[PROPERTY_VALUE_MAX];
-    bool have_vold_decrypt = property_get("vold.decrypt", vold_decrypt, "") > 0;
+    char vold_decrypt[kPropertyValueMax];
+    bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
     bool skip_compilation = (have_vold_decrypt &&
                              (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
                              (strcmp(vold_decrypt, "1") == 0)));
@@ -782,11 +750,11 @@
     char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
     char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
     char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
-    char instruction_set_variant_arg[strlen("--instruction-set-variant=") + PROPERTY_VALUE_MAX];
-    char instruction_set_features_arg[strlen("--instruction-set-features=") + PROPERTY_VALUE_MAX];
-    char dex2oat_Xms_arg[strlen("-Xms") + PROPERTY_VALUE_MAX];
-    char dex2oat_Xmx_arg[strlen("-Xmx") + PROPERTY_VALUE_MAX];
-    char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + PROPERTY_VALUE_MAX];
+    char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
+    char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
+    char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
+    char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
+    char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
     bool have_dex2oat_swap_fd = false;
     char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
 
@@ -826,9 +794,9 @@
 
     // Check whether all apps should be compiled debuggable.
     if (!debuggable) {
-        char prop_buf[PROPERTY_VALUE_MAX];
+        char prop_buf[kPropertyValueMax];
         debuggable =
-                (property_get("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
+                (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
                 (prop_buf[0] == '1');
     }
 
@@ -896,32 +864,6 @@
     ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
 }
 
-static int wait_child(pid_t pid)
-{
-    int status;
-    pid_t got_pid;
-
-    while (1) {
-        got_pid = waitpid(pid, &status, 0);
-        if (got_pid == -1 && errno == EINTR) {
-            printf("waitpid interrupted, retrying\n");
-        } else {
-            break;
-        }
-    }
-    if (got_pid != pid) {
-        ALOGW("waitpid failed: wanted %d, got %d: %s\n",
-            (int) pid, (int) got_pid, strerror(errno));
-        return 1;
-    }
-
-    if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
-        return 0;
-    } else {
-        return status;      /* always nonzero */
-    }
-}
-
 /*
  * Whether dexopt should use a swap file when compiling an APK.
  *
@@ -943,8 +885,8 @@
     }
 
     // Check the "override" property. If it exists, return value == "true".
-    char dex2oat_prop_buf[PROPERTY_VALUE_MAX];
-    if (property_get("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
+    char dex2oat_prop_buf[kPropertyValueMax];
+    if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
         if (strcmp(dex2oat_prop_buf, "true") == 0) {
             return true;
         } else {
@@ -968,42 +910,6 @@
     return kDefaultProvideSwapFile;
 }
 
-/*
- * Computes the odex file for the given apk_path and instruction_set.
- * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
- *
- * Returns false if it failed to determine the odex file path.
- */
-static bool calculate_odex_file_path(char path[PKG_PATH_MAX],
-                                     const char *apk_path,
-                                     const char *instruction_set)
-{
-    if (strlen(apk_path) + strlen("oat/") + strlen(instruction_set)
-        + strlen("/") + strlen("odex") + 1 > PKG_PATH_MAX) {
-      ALOGE("apk_path '%s' may be too long to form odex file path.\n", apk_path);
-      return false;
-    }
-
-    strcpy(path, apk_path);
-    char *end = strrchr(path, '/');
-    if (end == NULL) {
-      ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
-      return false;
-    }
-    const char *apk_end = apk_path + (end - path); // strrchr(apk_path, '/');
-
-    strcpy(end + 1, "oat/");       // path = /system/framework/oat/\0
-    strcat(path, instruction_set); // path = /system/framework/oat/<isa>\0
-    strcat(path, apk_end);         // path = /system/framework/oat/<isa>/whatever.jar\0
-    end = strrchr(path, '.');
-    if (end == NULL) {
-      ALOGE("apk_path '%s' has no extension.\n", apk_path);
-      return false;
-    }
-    strcpy(end + 1, "odex");
-    return true;
-}
-
 static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
     if (set_to_bg) {
         if (set_sched_policy(0, SP_BACKGROUND) < 0) {
@@ -1050,11 +956,11 @@
             ALOGE("invalid oat_dir '%s'\n", oat_dir);
             return -1;
         }
-        if (calculate_oat_file_path(out_path, oat_dir, apk_path, instruction_set)) {
+        if (!calculate_oat_file_path(out_path, oat_dir, apk_path, instruction_set)) {
             return -1;
         }
     } else {
-        if (create_cache_path(out_path, apk_path, instruction_set)) {
+        if (!create_cache_path(out_path, apk_path, instruction_set)) {
             return -1;
         }
     }
@@ -1211,7 +1117,11 @@
 int mark_boot_complete(const char* instruction_set)
 {
   char boot_marker_path[PKG_PATH_MAX];
-  sprintf(boot_marker_path,"%s%s/.booting", DALVIK_CACHE_PREFIX, instruction_set);
+  sprintf(boot_marker_path,
+          "%s/%s/%s/.booting",
+          android_data_dir.path,
+          DALVIK_CACHE,
+          instruction_set);
 
   ALOGV("mark_boot_complete : %s", boot_marker_path);
   if (unlink(boot_marker_path) != 0) {
@@ -1749,29 +1659,5 @@
     return 0;
 }
 
-int calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir, const char *apk_path,
-        const char *instruction_set) {
-    char *file_name_start;
-    char *file_name_end;
-
-    file_name_start = strrchr(apk_path, '/');
-    if (file_name_start == NULL) {
-         ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
-        return -1;
-    }
-    file_name_end = strrchr(apk_path, '.');
-    if (file_name_end < file_name_start) {
-        ALOGE("apk_path '%s' has no extension\n", apk_path);
-        return -1;
-    }
-
-    // Calculate file_name
-    int file_name_len = file_name_end - file_name_start - 1;
-    char file_name[file_name_len + 1];
-    memcpy(file_name, file_name_start + 1, file_name_len);
-    file_name[file_name_len] = '\0';
-
-    // <apk_parent_dir>/oat/<isa>/<file_name>.odex
-    snprintf(path, PKG_PATH_MAX, "%s/%s/%s.odex", oat_dir, instruction_set, file_name);
-    return 0;
-}
+}  // namespace installd
+}  // namespace android
diff --git a/cmds/installd/commands.h b/cmds/installd/commands.h
new file mode 100644
index 0000000..55a6e62
--- /dev/null
+++ b/cmds/installd/commands.h
@@ -0,0 +1,70 @@
+/*
+**
+** Copyright 2008, 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 COMMANDS_H_
+#define COMMANDS_H_
+
+#include <inttypes.h>
+#include <unistd.h>
+
+#include <cutils/multiuser.h>
+
+#include <installd_constants.h>
+
+namespace android {
+namespace installd {
+
+int install(const char *uuid, const char *pkgname, uid_t uid, gid_t gid, const char *seinfo);
+int uninstall(const char *uuid, const char *pkgname, userid_t userid);
+int renamepkg(const char *oldpkgname, const char *newpkgname);
+int fix_uid(const char *uuid, const char *pkgname, uid_t uid, gid_t gid);
+int delete_user_data(const char *uuid, const char *pkgname, userid_t userid);
+int make_user_data(const char *uuid, const char *pkgname, uid_t uid,
+        userid_t userid, const char* seinfo);
+int copy_complete_app(const char* from_uuid, const char *to_uuid,
+        const char *package_name, const char *data_app_name, appid_t appid,
+        const char* seinfo);
+int make_user_config(userid_t userid);
+int delete_user(const char *uuid, userid_t userid);
+int delete_cache(const char *uuid, const char *pkgname, userid_t userid);
+int delete_code_cache(const char *uuid, const char *pkgname, userid_t userid);
+int move_dex(const char *src, const char *dst, const char *instruction_set);
+int rm_dex(const char *path, const char *instruction_set);
+int protect(char *pkgname, gid_t gid);
+int get_size(const char *uuid, const char *pkgname, int userid,
+        const char *apkpath, const char *libdirpath,
+        const char *fwdlock_apkpath, const char *asecpath,
+        const char *instruction_set, int64_t *codesize, int64_t *datasize,
+        int64_t *cachesize, int64_t *asecsize);
+int free_cache(const char *uuid, int64_t free_size);
+int dexopt(const char *apk_path, uid_t uid, const char *pkgName, const char *instruction_set,
+           int dexopt_needed, const char* oat_dir, int dexopt_flags);
+int mark_boot_complete(const char *instruction_set);
+int movefiles();
+int linklib(const char* uuid, const char* pkgname, const char* asecLibDir, int userId);
+int idmap(const char *target_path, const char *overlay_path, uid_t uid);
+int restorecon_data(const char *uuid, const char* pkgName, const char* seinfo, uid_t uid);
+int create_oat_dir(const char* oat_dir, const char *instruction_set);
+int rm_package_dir(const char* apk_path);
+int move_package_dir(char path[PKG_PATH_MAX], const char *oat_dir, const char *apk_path,
+                            const char *instruction_set);
+int link_file(const char *relative_path, const char *from_base, const char *to_base);
+
+}  // namespace installd
+}  // namespace android
+
+#endif  // COMMANDS_H_
diff --git a/cmds/installd/globals.cpp b/cmds/installd/globals.cpp
new file mode 100644
index 0000000..bee2790
--- /dev/null
+++ b/cmds/installd/globals.cpp
@@ -0,0 +1,132 @@
+/*
+** Copyright 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 <stdlib.h>
+#include <string.h>
+
+#include <cutils/log.h>               // TODO: Move everything to base::logging.
+
+#include <globals.h>
+#include <installd_constants.h>
+#include <utils.h>
+
+#ifndef LOG_TAG
+#define LOG_TAG "installd"
+#endif
+
+namespace android {
+namespace installd {
+
+/* Directory records that are used in execution of commands. */
+dir_rec_t android_app_dir;
+dir_rec_t android_app_ephemeral_dir;
+dir_rec_t android_app_lib_dir;
+dir_rec_t android_app_private_dir;
+dir_rec_t android_asec_dir;
+dir_rec_t android_data_dir;
+dir_rec_t android_media_dir;
+dir_rec_t android_mnt_expand_dir;
+
+dir_rec_array_t android_system_dirs;
+
+/**
+ * Initialize all the global variables that are used elsewhere. Returns 0 upon
+ * success and -1 on error.
+ */
+void free_globals() {
+    size_t i;
+
+    for (i = 0; i < android_system_dirs.count; i++) {
+        if (android_system_dirs.dirs[i].path != NULL) {
+            free(android_system_dirs.dirs[i].path);
+        }
+    }
+
+    free(android_system_dirs.dirs);
+}
+
+bool init_globals_from_data_and_root(const char* data, const char* root) {
+    // Get the android data directory.
+    if (get_path_from_string(&android_data_dir, data) < 0) {
+        return false;
+    }
+
+    // Get the android app directory.
+    if (copy_and_append(&android_app_dir, &android_data_dir, APP_SUBDIR) < 0) {
+        return false;
+    }
+
+    // Get the android protected app directory.
+    if (copy_and_append(&android_app_private_dir, &android_data_dir, PRIVATE_APP_SUBDIR) < 0) {
+        return false;
+    }
+
+    // Get the android ephemeral app directory.
+    if (copy_and_append(&android_app_ephemeral_dir, &android_data_dir, EPHEMERAL_APP_SUBDIR) < 0) {
+        return -1;
+    }
+
+    // Get the android app native library directory.
+    if (copy_and_append(&android_app_lib_dir, &android_data_dir, APP_LIB_SUBDIR) < 0) {
+        return false;
+    }
+
+    // Get the sd-card ASEC mount point.
+    if (get_path_from_env(&android_asec_dir, "ASEC_MOUNTPOINT") < 0) {
+        return false;
+    }
+
+    // Get the android media directory.
+    if (copy_and_append(&android_media_dir, &android_data_dir, MEDIA_SUBDIR) < 0) {
+        return false;
+    }
+
+    // Get the android external app directory.
+    if (get_path_from_string(&android_mnt_expand_dir, "/mnt/expand/") < 0) {
+        return false;
+    }
+
+    // Take note of the system and vendor directories.
+    android_system_dirs.count = 4;
+
+    android_system_dirs.dirs = (dir_rec_t*) calloc(android_system_dirs.count, sizeof(dir_rec_t));
+    if (android_system_dirs.dirs == NULL) {
+        ALOGE("Couldn't allocate array for dirs; aborting\n");
+        return false;
+    }
+
+    dir_rec_t android_root_dir;
+    if (get_path_from_string(&android_root_dir, root) < 0) {
+        return false;
+    }
+
+    android_system_dirs.dirs[0].path = build_string2(android_root_dir.path, APP_SUBDIR);
+    android_system_dirs.dirs[0].len = strlen(android_system_dirs.dirs[0].path);
+
+    android_system_dirs.dirs[1].path = build_string2(android_root_dir.path, PRIV_APP_SUBDIR);
+    android_system_dirs.dirs[1].len = strlen(android_system_dirs.dirs[1].path);
+
+    android_system_dirs.dirs[2].path = strdup("/vendor/app/");
+    android_system_dirs.dirs[2].len = strlen(android_system_dirs.dirs[2].path);
+
+    android_system_dirs.dirs[3].path = strdup("/oem/app/");
+    android_system_dirs.dirs[3].len = strlen(android_system_dirs.dirs[3].path);
+
+    return true;
+}
+
+}  // namespace installd
+}  // namespace android
diff --git a/cmds/installd/globals.h b/cmds/installd/globals.h
new file mode 100644
index 0000000..2e61f85
--- /dev/null
+++ b/cmds/installd/globals.h
@@ -0,0 +1,55 @@
+/*
+**
+** Copyright 2008, 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 GLOBALS_H_
+#define GLOBALS_H_
+
+#include <inttypes.h>
+
+namespace android {
+namespace installd {
+
+/* data structures */
+
+struct dir_rec_t {
+    char* path;
+    size_t len;
+};
+
+struct dir_rec_array_t {
+    size_t count;
+    dir_rec_t* dirs;
+};
+
+extern dir_rec_t android_app_dir;
+extern dir_rec_t android_app_ephemeral_dir;
+extern dir_rec_t android_app_lib_dir;
+extern dir_rec_t android_app_private_dir;
+extern dir_rec_t android_asec_dir;
+extern dir_rec_t android_data_dir;
+extern dir_rec_t android_media_dir;
+extern dir_rec_t android_mnt_expand_dir;
+
+extern dir_rec_array_t android_system_dirs;
+
+void free_globals();
+bool init_globals_from_data_and_root(const char* data, const char* root);
+
+}  // namespace installd
+}  // namespace android
+
+#endif  // GLOBALS_H_
diff --git a/cmds/installd/installd.cpp b/cmds/installd/installd.cpp
index 52f7b9c..17ae521 100644
--- a/cmds/installd/installd.cpp
+++ b/cmds/installd/installd.cpp
@@ -14,19 +14,167 @@
 ** limitations under the License.
 */
 
-#include "installd.h"
-
-#include <base/logging.h>
-
-#include <sys/capability.h>
-#include <sys/prctl.h>
+#include <fcntl.h>
 #include <selinux/android.h>
 #include <selinux/avc.h>
+#include <sys/capability.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+
+#include <android-base/logging.h>
+#include <cutils/fs.h>
+#include <cutils/log.h>               // TODO: Move everything to base::logging.
+#include <cutils/properties.h>
+#include <cutils/sockets.h>
+#include <private/android_filesystem_config.h>
+
+#include <commands.h>
+#include <globals.h>
+#include <installd_constants.h>
+#include <installd_deps.h>  // Need to fill in requirements of commands.
+#include <utils.h>
+
+#ifndef LOG_TAG
+#define LOG_TAG "installd"
+#endif
+#define SOCKET_PATH "installd"
 
 #define BUFFER_MAX    1024  /* input buffer for commands */
 #define TOKEN_MAX     16    /* max number of arguments in buffer */
 #define REPLY_MAX     256   /* largest reply allowed */
 
+
+namespace android {
+namespace installd {
+
+// Check that installd-deps sizes match cutils sizes.
+static_assert(kPropertyKeyMax == PROPERTY_KEY_MAX, "Size mismatch.");
+static_assert(kPropertyValueMax == PROPERTY_VALUE_MAX, "Size mismatch.");
+
+////////////////////////
+// Plug-in functions. //
+////////////////////////
+
+int get_property(const char *key, char *value, const char *default_value) {
+    return property_get(key, value, default_value);
+}
+
+// Compute the output path of
+bool calculate_oat_file_path(char path[PKG_PATH_MAX],
+                             const char *oat_dir,
+                             const char *apk_path,
+                             const char *instruction_set) {
+    char *file_name_start;
+    char *file_name_end;
+
+    file_name_start = strrchr(apk_path, '/');
+    if (file_name_start == NULL) {
+        ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
+        return false;
+    }
+    file_name_end = strrchr(apk_path, '.');
+    if (file_name_end < file_name_start) {
+        ALOGE("apk_path '%s' has no extension\n", apk_path);
+        return false;
+    }
+
+    // Calculate file_name
+    int file_name_len = file_name_end - file_name_start - 1;
+    char file_name[file_name_len + 1];
+    memcpy(file_name, file_name_start + 1, file_name_len);
+    file_name[file_name_len] = '\0';
+
+    // <apk_parent_dir>/oat/<isa>/<file_name>.odex
+    snprintf(path, PKG_PATH_MAX, "%s/%s/%s.odex", oat_dir, instruction_set, file_name);
+    return true;
+}
+
+/*
+ * Computes the odex file for the given apk_path and instruction_set.
+ * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
+ *
+ * Returns false if it failed to determine the odex file path.
+ */
+bool calculate_odex_file_path(char path[PKG_PATH_MAX],
+                              const char *apk_path,
+                              const char *instruction_set) {
+    if (strlen(apk_path) + strlen("oat/") + strlen(instruction_set)
+            + strlen("/") + strlen("odex") + 1 > PKG_PATH_MAX) {
+        ALOGE("apk_path '%s' may be too long to form odex file path.\n", apk_path);
+        return false;
+    }
+
+    strcpy(path, apk_path);
+    char *end = strrchr(path, '/');
+    if (end == NULL) {
+        ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
+        return false;
+    }
+    const char *apk_end = apk_path + (end - path); // strrchr(apk_path, '/');
+
+    strcpy(end + 1, "oat/");       // path = /system/framework/oat/\0
+    strcat(path, instruction_set); // path = /system/framework/oat/<isa>\0
+    strcat(path, apk_end);         // path = /system/framework/oat/<isa>/whatever.jar\0
+    end = strrchr(path, '.');
+    if (end == NULL) {
+        ALOGE("apk_path '%s' has no extension.\n", apk_path);
+        return false;
+    }
+    strcpy(end + 1, "odex");
+    return true;
+}
+
+bool create_cache_path(char path[PKG_PATH_MAX],
+                       const char *src,
+                       const char *instruction_set) {
+    size_t srclen = strlen(src);
+
+        /* demand that we are an absolute path */
+    if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
+        return false;
+    }
+
+    if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
+        return false;
+    }
+
+    size_t dstlen =
+        android_data_dir.len +
+        strlen(DALVIK_CACHE) +
+        1 +
+        strlen(instruction_set) +
+        srclen +
+        strlen(DALVIK_CACHE_POSTFIX) + 2;
+
+    if (dstlen > PKG_PATH_MAX) {
+        return false;
+    }
+
+    sprintf(path,"%s%s/%s/%s%s",
+            android_data_dir.path,
+            DALVIK_CACHE,
+            instruction_set,
+            src + 1, /* skip the leading / */
+            DALVIK_CACHE_POSTFIX);
+
+    char* tmp =
+            path +
+            android_data_dir.len +
+            strlen(DALVIK_CACHE) +
+            1 +
+            strlen(instruction_set) + 1;
+
+    for(; *tmp; tmp++) {
+        if (*tmp == '/') {
+            *tmp = '@';
+        }
+    }
+
+    return true;
+}
+
+
 static char* parse_null(char* arg) {
     if (strcmp(arg, "!") == 0) {
         return nullptr;
@@ -35,59 +183,59 @@
     }
 }
 
-static int do_ping(char **arg __unused, char reply[REPLY_MAX] __unused)
+static int do_ping(char **arg ATTRIBUTE_UNUSED, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return 0;
 }
 
-static int do_install(char **arg, char reply[REPLY_MAX] __unused)
+static int do_install(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return install(parse_null(arg[0]), arg[1], atoi(arg[2]), atoi(arg[3]), arg[4]); /* uuid, pkgname, uid, gid, seinfo */
 }
 
-static int do_dexopt(char **arg, char reply[REPLY_MAX] __unused)
+static int do_dexopt(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     /* apk_path, uid, pkgname, instruction_set, dexopt_needed, oat_dir, dexopt_flags */
     return dexopt(arg[0], atoi(arg[1]), arg[2], arg[3], atoi(arg[4]),
                   arg[5], atoi(arg[6]));
 }
 
-static int do_mark_boot_complete(char **arg, char reply[REPLY_MAX] __unused)
+static int do_mark_boot_complete(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return mark_boot_complete(arg[0] /* instruction set */);
 }
 
-static int do_move_dex(char **arg, char reply[REPLY_MAX] __unused)
+static int do_move_dex(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return move_dex(arg[0], arg[1], arg[2]); /* src, dst, instruction_set */
 }
 
-static int do_rm_dex(char **arg, char reply[REPLY_MAX] __unused)
+static int do_rm_dex(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return rm_dex(arg[0], arg[1]); /* pkgname, instruction_set */
 }
 
-static int do_remove(char **arg, char reply[REPLY_MAX] __unused)
+static int do_remove(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return uninstall(parse_null(arg[0]), arg[1], atoi(arg[2])); /* uuid, pkgname, userid */
 }
 
-static int do_fixuid(char **arg, char reply[REPLY_MAX] __unused)
+static int do_fixuid(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return fix_uid(parse_null(arg[0]), arg[1], atoi(arg[2]), atoi(arg[3])); /* uuid, pkgname, uid, gid */
 }
 
-static int do_free_cache(char **arg, char reply[REPLY_MAX] __unused) /* TODO int:free_size */
+static int do_free_cache(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED) /* TODO int:free_size */
 {
     return free_cache(parse_null(arg[0]), (int64_t)atoll(arg[1])); /* uuid, free_size */
 }
 
-static int do_rm_cache(char **arg, char reply[REPLY_MAX] __unused)
+static int do_rm_cache(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return delete_cache(parse_null(arg[0]), arg[1], atoi(arg[2])); /* uuid, pkgname, userid */
 }
 
-static int do_rm_code_cache(char **arg, char reply[REPLY_MAX] __unused)
+static int do_rm_code_cache(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return delete_code_cache(parse_null(arg[0]), arg[1], atoi(arg[2])); /* uuid, pkgname, userid */
 }
@@ -113,67 +261,67 @@
     return res;
 }
 
-static int do_rm_user_data(char **arg, char reply[REPLY_MAX] __unused)
+static int do_rm_user_data(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return delete_user_data(parse_null(arg[0]), arg[1], atoi(arg[2])); /* uuid, pkgname, userid */
 }
 
-static int do_cp_complete_app(char **arg, char reply[REPLY_MAX] __unused)
+static int do_cp_complete_app(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     // from_uuid, to_uuid, package_name, data_app_name, appid, seinfo
     return copy_complete_app(parse_null(arg[0]), parse_null(arg[1]), arg[2], arg[3], atoi(arg[4]), arg[5]);
 }
 
-static int do_mk_user_data(char **arg, char reply[REPLY_MAX] __unused)
+static int do_mk_user_data(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return make_user_data(parse_null(arg[0]), arg[1], atoi(arg[2]), atoi(arg[3]), arg[4]);
                              /* uuid, pkgname, uid, userid, seinfo */
 }
 
-static int do_mk_user_config(char **arg, char reply[REPLY_MAX] __unused)
+static int do_mk_user_config(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return make_user_config(atoi(arg[0])); /* userid */
 }
 
-static int do_rm_user(char **arg, char reply[REPLY_MAX] __unused)
+static int do_rm_user(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return delete_user(parse_null(arg[0]), atoi(arg[1])); /* uuid, userid */
 }
 
-static int do_movefiles(char **arg __unused, char reply[REPLY_MAX] __unused)
+static int do_movefiles(char **arg ATTRIBUTE_UNUSED, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return movefiles();
 }
 
-static int do_linklib(char **arg, char reply[REPLY_MAX] __unused)
+static int do_linklib(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return linklib(parse_null(arg[0]), arg[1], arg[2], atoi(arg[3]));
 }
 
-static int do_idmap(char **arg, char reply[REPLY_MAX] __unused)
+static int do_idmap(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return idmap(arg[0], arg[1], atoi(arg[2]));
 }
 
-static int do_restorecon_data(char **arg, char reply[REPLY_MAX] __attribute__((unused)))
+static int do_restorecon_data(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     return restorecon_data(parse_null(arg[0]), arg[1], arg[2], atoi(arg[3]));
                              /* uuid, pkgName, seinfo, uid*/
 }
 
-static int do_create_oat_dir(char **arg, char reply[REPLY_MAX] __unused)
+static int do_create_oat_dir(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     /* oat_dir, instruction_set */
     return create_oat_dir(arg[0], arg[1]);
 }
 
-static int do_rm_package_dir(char **arg, char reply[REPLY_MAX] __unused)
+static int do_rm_package_dir(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     /* oat_dir */
     return rm_package_dir(arg[0]);
 }
 
-static int do_link_file(char **arg, char reply[REPLY_MAX] __unused)
+static int do_link_file(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
 {
     /* relative_path, from_base, to_base */
     return link_file(arg[0], arg[1], arg[2]);
@@ -314,89 +462,22 @@
     return 0;
 }
 
-/**
- * Initialize all the global variables that are used elsewhere. Returns 0 upon
- * success and -1 on error.
- */
-void free_globals() {
-    size_t i;
-
-    for (i = 0; i < android_system_dirs.count; i++) {
-        if (android_system_dirs.dirs[i].path != NULL) {
-            free(android_system_dirs.dirs[i].path);
-        }
+bool initialize_globals() {
+    const char* data_path = getenv("ANDROID_DATA");
+    if (data_path == nullptr) {
+        ALOGE("Could not find ANDROID_DATA");
+        return false;
+    }
+    const char* root_path = getenv("ANDROID_ROOT");
+    if (root_path == nullptr) {
+        ALOGE("Could not find ANDROID_ROOT");
+        return false;
     }
 
-    free(android_system_dirs.dirs);
+    return init_globals_from_data_and_root(data_path, root_path);
 }
 
-int initialize_globals() {
-    // Get the android data directory.
-    if (get_path_from_env(&android_data_dir, "ANDROID_DATA") < 0) {
-        return -1;
-    }
-
-    // Get the android app directory.
-    if (copy_and_append(&android_app_dir, &android_data_dir, APP_SUBDIR) < 0) {
-        return -1;
-    }
-
-    // Get the android protected app directory.
-    if (copy_and_append(&android_app_private_dir, &android_data_dir, PRIVATE_APP_SUBDIR) < 0) {
-        return -1;
-    }
-
-    // Get the android app native library directory.
-    if (copy_and_append(&android_app_lib_dir, &android_data_dir, APP_LIB_SUBDIR) < 0) {
-        return -1;
-    }
-
-    // Get the sd-card ASEC mount point.
-    if (get_path_from_env(&android_asec_dir, "ASEC_MOUNTPOINT") < 0) {
-        return -1;
-    }
-
-    // Get the android media directory.
-    if (copy_and_append(&android_media_dir, &android_data_dir, MEDIA_SUBDIR) < 0) {
-        return -1;
-    }
-
-    // Get the android external app directory.
-    if (get_path_from_string(&android_mnt_expand_dir, "/mnt/expand/") < 0) {
-        return -1;
-    }
-
-    // Take note of the system and vendor directories.
-    android_system_dirs.count = 4;
-
-    android_system_dirs.dirs = (dir_rec_t*) calloc(android_system_dirs.count, sizeof(dir_rec_t));
-    if (android_system_dirs.dirs == NULL) {
-        ALOGE("Couldn't allocate array for dirs; aborting\n");
-        return -1;
-    }
-
-    dir_rec_t android_root_dir;
-    if (get_path_from_env(&android_root_dir, "ANDROID_ROOT") < 0) {
-        ALOGE("Missing ANDROID_ROOT; aborting\n");
-        return -1;
-    }
-
-    android_system_dirs.dirs[0].path = build_string2(android_root_dir.path, APP_SUBDIR);
-    android_system_dirs.dirs[0].len = strlen(android_system_dirs.dirs[0].path);
-
-    android_system_dirs.dirs[1].path = build_string2(android_root_dir.path, PRIV_APP_SUBDIR);
-    android_system_dirs.dirs[1].len = strlen(android_system_dirs.dirs[1].path);
-
-    android_system_dirs.dirs[2].path = strdup("/vendor/app/");
-    android_system_dirs.dirs[2].len = strlen(android_system_dirs.dirs[2].path);
-
-    android_system_dirs.dirs[3].path = strdup("/oem/app/");
-    android_system_dirs.dirs[3].len = strlen(android_system_dirs.dirs[3].path);
-
-    return 0;
-}
-
-int initialize_directories() {
+static int initialize_directories() {
     int res = -1;
 
     // Read current filesystem layout version to handle upgrade paths
@@ -650,7 +731,7 @@
     return 0;
 }
 
-int main(const int argc __unused, char *argv[]) {
+static int installd_main(const int argc ATTRIBUTE_UNUSED, char *argv[]) {
     char buf[BUFFER_MAX];
     struct sockaddr addr;
     socklen_t alen;
@@ -666,7 +747,7 @@
     cb.func_log = log_callback;
     selinux_set_callback(SELINUX_CB_LOG, cb);
 
-    if (initialize_globals() < 0) {
+    if (!initialize_globals()) {
         ALOGE("Could not initialize globals; exiting.\n");
         exit(1);
     }
@@ -728,3 +809,10 @@
 
     return 0;
 }
+
+}  // namespace installd
+}  // namespace android
+
+int main(const int argc, char *argv[]) {
+    return android::installd::installd_main(argc, argv);
+}
diff --git a/cmds/installd/installd.h b/cmds/installd/installd.h
deleted file mode 100644
index d911c49..0000000
--- a/cmds/installd/installd.h
+++ /dev/null
@@ -1,280 +0,0 @@
-/*
-**
-** Copyright 2008, 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.
-*/
-
-#define LOG_TAG "installd"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <inttypes.h>
-#include <sys/stat.h>
-#include <dirent.h>
-#include <unistd.h>
-#include <ctype.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <utime.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <string>
-#include <vector>
-
-#include <cutils/fs.h>
-#include <cutils/sockets.h>
-#include <cutils/log.h>
-#include <cutils/properties.h>
-#include <cutils/multiuser.h>
-
-#include <private/android_filesystem_config.h>
-
-#if defined(__APPLE__)
-#include <sys/mount.h>
-#else
-#include <sys/statfs.h>
-#endif
-
-#define SOCKET_PATH "installd"
-
-
-/* elements combined with a valid package name to form paths */
-
-#define PRIMARY_USER_PREFIX    "data/"
-#define SECONDARY_USER_PREFIX  "user/"
-
-#define PKG_DIR_POSTFIX        ""
-
-#define PKG_LIB_POSTFIX        "/lib"
-
-#define CACHE_DIR_POSTFIX      "/cache"
-#define CODE_CACHE_DIR_POSTFIX "/code_cache"
-
-#define APP_SUBDIR             "app/" // sub-directory under ANDROID_DATA
-#define PRIV_APP_SUBDIR        "priv-app/" // sub-directory under ANDROID_DATA
-
-#define APP_LIB_SUBDIR         "app-lib/" // sub-directory under ANDROID_DATA
-
-#define MEDIA_SUBDIR           "media/" // sub-directory under ANDROID_DATA
-
-/* other handy constants */
-
-#define PRIVATE_APP_SUBDIR     "app-private/" // sub-directory under ANDROID_DATA
-
-#define DALVIK_CACHE_PREFIX    "/data/dalvik-cache/"
-#define DALVIK_CACHE_POSTFIX   "/classes.dex"
-
-#define UPDATE_COMMANDS_DIR_PREFIX  "/system/etc/updatecmds/"
-
-#define IDMAP_PREFIX           "/data/resource-cache/"
-#define IDMAP_SUFFIX           "@idmap"
-
-#define PKG_NAME_MAX  128   /* largest allowed package name */
-#define PKG_PATH_MAX  256   /* max size of any path we use */
-
-/* dexopt needed flags matching those in dalvik.system.DexFile */
-#define DEXOPT_DEX2OAT_NEEDED        1
-#define DEXOPT_PATCHOAT_NEEDED       2
-#define DEXOPT_SELF_PATCHOAT_NEEDED  3
-
-/****************************************************************************
- * IMPORTANT: These values are passed from Java code. Keep them in sync with
- * frameworks/base/services/core/java/com/android/server/pm/Installer.java
- ***************************************************************************/
-constexpr int DEXOPT_PUBLIC       = 1 << 1;
-constexpr int DEXOPT_SAFEMODE     = 1 << 2;
-constexpr int DEXOPT_DEBUGGABLE   = 1 << 3;
-constexpr int DEXOPT_BOOTCOMPLETE = 1 << 4;
-constexpr int DEXOPT_USEJIT       = 1 << 5;
-
-/* all known values for dexopt flags */
-constexpr int DEXOPT_MASK =
-    DEXOPT_PUBLIC
-    | DEXOPT_SAFEMODE
-    | DEXOPT_DEBUGGABLE
-    | DEXOPT_BOOTCOMPLETE
-    | DEXOPT_USEJIT;
-
-#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
-
-/* data structures */
-
-typedef struct {
-    char* path;
-    size_t len;
-} dir_rec_t;
-
-typedef struct {
-    size_t count;
-    dir_rec_t* dirs;
-} dir_rec_array_t;
-
-extern dir_rec_t android_app_dir;
-extern dir_rec_t android_app_private_dir;
-extern dir_rec_t android_app_lib_dir;
-extern dir_rec_t android_data_dir;
-extern dir_rec_t android_asec_dir;
-extern dir_rec_t android_media_dir;
-extern dir_rec_t android_mnt_expand_dir;
-extern dir_rec_array_t android_system_dirs;
-
-typedef struct cache_dir_struct {
-    struct cache_dir_struct* parent;
-    int32_t childCount;
-    int32_t hiddenCount;
-    int32_t deleted;
-    char name[];
-} cache_dir_t;
-
-typedef struct {
-    cache_dir_t* dir;
-    time_t modTime;
-    char name[];
-} cache_file_t;
-
-typedef struct {
-    size_t numDirs;
-    size_t availDirs;
-    cache_dir_t** dirs;
-    size_t numFiles;
-    size_t availFiles;
-    cache_file_t** files;
-    size_t numCollected;
-    void* memBlocks;
-    int8_t* curMemBlockAvail;
-    int8_t* curMemBlockEnd;
-} cache_t;
-
-/* util.c */
-
-int create_pkg_path(char path[PKG_PATH_MAX],
-                    const char *pkgname,
-                    const char *postfix,
-                    userid_t userid);
-
-std::string create_data_path(const char* volume_uuid);
-
-std::string create_data_app_path(const char* volume_uuid);
-
-std::string create_data_app_package_path(const char* volume_uuid, const char* package_name);
-
-// TODO: finish refactoring to "_ce"
-std::string create_data_user_path(const char* volume_uuid, userid_t userid);
-std::string create_data_user_de_path(const char* volume_uuid, userid_t userid);
-
-std::string create_data_user_package_path(const char* volume_uuid,
-        userid_t user, const char* package_name);
-std::string create_data_user_de_package_path(const char* volume_uuid,
-        userid_t user, const char* package_name);
-
-std::string create_data_media_path(const char* volume_uuid, userid_t userid);
-
-std::vector<userid_t> get_known_users(const char* volume_uuid);
-
-int create_user_config_path(char path[PKG_PATH_MAX], userid_t userid);
-
-int create_move_path(char path[PKG_PATH_MAX],
-                     const char* pkgname,
-                     const char* leaf,
-                     userid_t userid);
-
-int is_valid_package_name(const char* pkgname);
-
-int create_cache_path(char path[PKG_PATH_MAX], const char *src,
-                      const char *instruction_set);
-
-int delete_dir_contents(const std::string& pathname);
-int delete_dir_contents_and_dir(const std::string& pathname);
-
-int delete_dir_contents(const char *pathname,
-                        int also_delete_dir,
-                        int (*exclusion_predicate)(const char *name, const int is_dir));
-
-int delete_dir_contents_fd(int dfd, const char *name);
-
-int copy_dir_files(const char *srcname, const char *dstname, uid_t owner, gid_t group);
-
-int lookup_media_dir(char basepath[PATH_MAX], const char *dir);
-
-int64_t data_disk_free(const std::string& data_path);
-
-cache_t* start_cache_collection();
-
-void add_cache_files(cache_t* cache, const char *basepath, const char *cachedir);
-
-void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size);
-
-void finish_cache_collection(cache_t* cache);
-
-int validate_system_app_path(const char* path);
-
-int get_path_from_env(dir_rec_t* rec, const char* var);
-
-int get_path_from_string(dir_rec_t* rec, const char* path);
-
-int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix);
-
-int validate_apk_path(const char *path);
-int validate_apk_path_subdirs(const char *path);
-
-int append_and_increment(char** dst, const char* src, size_t* dst_size);
-
-char *build_string2(const char *s1, const char *s2);
-char *build_string3(const char *s1, const char *s2, const char *s3);
-
-int ensure_dir(const char* path, mode_t mode, uid_t uid, gid_t gid);
-int ensure_media_user_dirs(const char* uuid, userid_t userid);
-int ensure_config_user_dirs(userid_t userid);
-
-/* commands.c */
-
-int install(const char *uuid, const char *pkgname, uid_t uid, gid_t gid, const char *seinfo);
-int uninstall(const char *uuid, const char *pkgname, userid_t userid);
-int renamepkg(const char *oldpkgname, const char *newpkgname);
-int fix_uid(const char *uuid, const char *pkgname, uid_t uid, gid_t gid);
-int delete_user_data(const char *uuid, const char *pkgname, userid_t userid);
-int make_user_data(const char *uuid, const char *pkgname, uid_t uid,
-        userid_t userid, const char* seinfo);
-int copy_complete_app(const char* from_uuid, const char *to_uuid,
-        const char *package_name, const char *data_app_name, appid_t appid,
-        const char* seinfo);
-int make_user_config(userid_t userid);
-int delete_user(const char *uuid, userid_t userid);
-int delete_cache(const char *uuid, const char *pkgname, userid_t userid);
-int delete_code_cache(const char *uuid, const char *pkgname, userid_t userid);
-int move_dex(const char *src, const char *dst, const char *instruction_set);
-int rm_dex(const char *path, const char *instruction_set);
-int protect(char *pkgname, gid_t gid);
-int get_size(const char *uuid, const char *pkgname, int userid,
-        const char *apkpath, const char *libdirpath,
-        const char *fwdlock_apkpath, const char *asecpath,
-        const char *instruction_set, int64_t *codesize, int64_t *datasize,
-        int64_t *cachesize, int64_t *asecsize);
-int free_cache(const char *uuid, int64_t free_size);
-int dexopt(const char *apk_path, uid_t uid, const char *pkgName, const char *instruction_set,
-           int dexopt_needed, const char* oat_dir, int dexopt_flags);
-int mark_boot_complete(const char *instruction_set);
-int movefiles();
-int linklib(const char* uuid, const char* pkgname, const char* asecLibDir, int userId);
-int idmap(const char *target_path, const char *overlay_path, uid_t uid);
-int restorecon_data(const char *uuid, const char* pkgName, const char* seinfo, uid_t uid);
-int create_oat_dir(const char* oat_dir, const char *instruction_set);
-int rm_package_dir(const char* apk_path);
-int calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir, const char *apk_path,
-                            const char *instruction_set);
-int move_package_dir(char path[PKG_PATH_MAX], const char *oat_dir, const char *apk_path,
-                            const char *instruction_set);
-int link_file(const char *relative_path, const char *from_base, const char *to_base);
diff --git a/cmds/installd/installd_constants.h b/cmds/installd/installd_constants.h
new file mode 100644
index 0000000..058db4c
--- /dev/null
+++ b/cmds/installd/installd_constants.h
@@ -0,0 +1,88 @@
+/*
+**
+** Copyright 2008, 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 INSTALLD_CONSTANTS_H_
+#define INSTALLD_CONSTANTS_H_
+
+namespace android {
+namespace installd {
+
+/* elements combined with a valid package name to form paths */
+
+constexpr const char* PRIMARY_USER_PREFIX = "data/";
+constexpr const char* SECONDARY_USER_PREFIX = "user/";
+
+constexpr const char* PKG_DIR_POSTFIX = "";
+
+constexpr const char* PKG_LIB_POSTFIX = "/lib";
+
+constexpr const char* CACHE_DIR_POSTFIX = "/cache";
+constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
+
+constexpr const char* APP_SUBDIR = "app/"; // sub-directory under ANDROID_DATA
+constexpr const char* PRIV_APP_SUBDIR = "priv-app/"; // sub-directory under ANDROID_DATA
+constexpr const char* EPHEMERAL_APP_SUBDIR = "app-ephemeral/"; // sub-directory under ANDROID_DATA
+
+constexpr const char* APP_LIB_SUBDIR = "app-lib/"; // sub-directory under ANDROID_DATA
+
+constexpr const char* MEDIA_SUBDIR = "media/"; // sub-directory under ANDROID_DATA
+
+/* other handy constants */
+
+constexpr const char* PRIVATE_APP_SUBDIR = "app-private/"; // sub-directory under ANDROID_DATA
+
+// This is used as a string literal, can't be constants. TODO: std::string...
+#define DALVIK_CACHE "dalvik-cache"
+constexpr const char* DALVIK_CACHE_POSTFIX = "/classes.dex";
+
+constexpr const char* UPDATE_COMMANDS_DIR_PREFIX = "/system/etc/updatecmds/";
+
+constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
+constexpr const char* IDMAP_SUFFIX = "@idmap";
+
+constexpr size_t PKG_NAME_MAX = 128u;   /* largest allowed package name */
+constexpr size_t PKG_PATH_MAX = 256u;   /* max size of any path we use */
+
+/* dexopt needed flags matching those in dalvik.system.DexFile */
+constexpr int DEXOPT_DEX2OAT_NEEDED       = 1;
+constexpr int DEXOPT_PATCHOAT_NEEDED      = 2;
+constexpr int DEXOPT_SELF_PATCHOAT_NEEDED = 3;
+
+/****************************************************************************
+ * IMPORTANT: These values are passed from Java code. Keep them in sync with
+ * frameworks/base/services/core/java/com/android/server/pm/Installer.java
+ ***************************************************************************/
+constexpr int DEXOPT_PUBLIC       = 1 << 1;
+constexpr int DEXOPT_SAFEMODE     = 1 << 2;
+constexpr int DEXOPT_DEBUGGABLE   = 1 << 3;
+constexpr int DEXOPT_BOOTCOMPLETE = 1 << 4;
+constexpr int DEXOPT_USEJIT       = 1 << 5;
+
+/* all known values for dexopt flags */
+constexpr int DEXOPT_MASK =
+    DEXOPT_PUBLIC
+    | DEXOPT_SAFEMODE
+    | DEXOPT_DEBUGGABLE
+    | DEXOPT_BOOTCOMPLETE
+    | DEXOPT_USEJIT;
+
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
+
+}  // namespace installd
+}  // namespace android
+
+#endif  // INSTALLD_CONSTANTS_H_
diff --git a/cmds/installd/installd_deps.h b/cmds/installd/installd_deps.h
new file mode 100644
index 0000000..5ff46e6
--- /dev/null
+++ b/cmds/installd/installd_deps.h
@@ -0,0 +1,66 @@
+/*
+**
+** Copyright 2008, 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 INSTALLD_DEPS_H_
+#define INSTALLD_DEPS_H_
+
+#include <inttypes.h>
+
+#include <installd_constants.h>
+
+namespace android {
+namespace installd {
+
+// Dependencies for a full binary. These functions need to be provided to
+// figure out parts of the configuration.
+
+// Retrieve a system property. Same API as cutils, just renamed.
+extern int get_property(const char *key,
+                        char *value,
+                        const char *default_value);
+// Size constants. Should be checked to be equal to the cutils requirements.
+constexpr size_t kPropertyKeyMax = 32u;
+constexpr size_t kPropertyValueMax = 92u;
+
+// Compute the output path for dex2oat.
+extern bool calculate_oat_file_path(char path[PKG_PATH_MAX],
+                                    const char *oat_dir,
+                                    const char *apk_path,
+                                    const char *instruction_set);
+// Compute the output path for patchoat.
+//
+// Computes the odex file for the given apk_path and instruction_set, e.g.,
+// /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
+//
+// Returns false if it failed to determine the odex file path.
+//
+extern bool calculate_odex_file_path(char path[PKG_PATH_MAX],
+                                     const char *apk_path,
+                                     const char *instruction_set);
+
+// Compute the output path into the dalvik cache.
+extern bool create_cache_path(char path[PKG_PATH_MAX],
+                              const char *src,
+                              const char *instruction_set);
+
+// Initialize globals. May be implemented with the helper in globals.h.
+extern bool initialize_globals();
+
+}  // namespace installd
+}  // namespace android
+
+#endif  // INSTALLD_DEPS_H_
diff --git a/cmds/installd/tests/installd_utils_test.cpp b/cmds/installd/tests/installd_utils_test.cpp
index 5e397f9..ff69f4b 100644
--- a/cmds/installd/tests/installd_utils_test.cpp
+++ b/cmds/installd/tests/installd_utils_test.cpp
@@ -19,7 +19,9 @@
 
 #include <gtest/gtest.h>
 
-#include "installd.h"
+#include <commands.h>
+#include <globals.h>
+#include <utils.h>
 
 #undef LOG_TAG
 #define LOG_TAG "utils_test"
@@ -44,6 +46,7 @@
         "shared_prefs_shared_prefs_shared_prefs_shared_prefs_shared_prefs_shared_prefs_"
 
 namespace android {
+namespace installd {
 
 class UtilsTest : public testing::Test {
 protected:
@@ -319,8 +322,8 @@
     EXPECT_EQ(0, create_pkg_path(path, pkgname, "", 0))
             << "Should successfully be able to create package name.";
 
-    const char *prefix = TEST_DATA_DIR PRIMARY_USER_PREFIX;
-    size_t offset = strlen(prefix);
+    std::string prefix = std::string(TEST_DATA_DIR) + PRIMARY_USER_PREFIX;
+    size_t offset = prefix.length();
 
     EXPECT_STREQ(pkgname, path + offset)
              << "Package path should be a really long string of a's";
@@ -358,7 +361,10 @@
     EXPECT_EQ(0, create_pkg_path(path, "com.example.package", "", 0))
             << "Should return error because postfix is too long.";
 
-    EXPECT_STREQ(TEST_DATA_DIR PRIMARY_USER_PREFIX "com.example.package", path)
+    std::string p = std::string(TEST_DATA_DIR)
+                    + PRIMARY_USER_PREFIX
+                    + "com.example.package";
+    EXPECT_STREQ(p.c_str(), path)
             << "Package path should be in /data/data/";
 }
 
@@ -368,7 +374,10 @@
     EXPECT_EQ(0, create_pkg_path(path, "com.example.package", "", 1))
             << "Should successfully create package path.";
 
-    EXPECT_STREQ(TEST_DATA_DIR SECONDARY_USER_PREFIX "1/com.example.package", path)
+    std::string p = std::string(TEST_DATA_DIR)
+                    + SECONDARY_USER_PREFIX
+                    + "1/com.example.package";
+    EXPECT_STREQ(p.c_str(), path)
             << "Package path should be in /data/user/";
 }
 
@@ -499,4 +508,5 @@
             create_data_user_package_path("57f8f4bc-abf4-655f-bf67-946fc0f9f25b", 10, "com.example"));
 }
 
-}
+}  // namespace installd
+}  // namespace android
diff --git a/cmds/installd/utils.cpp b/cmds/installd/utils.cpp
index 549a420..92a9565 100644
--- a/cmds/installd/utils.cpp
+++ b/cmds/installd/utils.cpp
@@ -14,15 +14,38 @@
 ** limitations under the License.
 */
 
-#include "installd.h"
+#include "utils.h"
 
-#include <base/stringprintf.h>
-#include <base/logging.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
 
+#if defined(__APPLE__)
+#include <sys/mount.h>
+#else
+#include <sys/statfs.h>
+#endif
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <cutils/fs.h>
+#include <cutils/log.h>
+#include <private/android_filesystem_config.h>
+
+#include "globals.h"  // extern variables.
+
+#ifndef LOG_TAG
+#define LOG_TAG "installd"
+#endif
 #define CACHE_NOISY(x) //x
 
 using android::base::StringPrintf;
 
+namespace android {
+namespace installd {
+
 /**
  * Check that given string is valid filename, and that it attempts no
  * parent or child directory traversal.
@@ -184,7 +207,7 @@
 int create_move_path(char path[PKG_PATH_MAX],
     const char* pkgname,
     const char* leaf,
-    userid_t userid __unused)
+    userid_t userid ATTRIBUTE_UNUSED)
 {
     if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
             >= PKG_PATH_MAX) {
@@ -1079,6 +1102,8 @@
         dir = &android_app_dir;
     } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
         dir = &android_app_private_dir;
+    } else if (!strncmp(path, android_app_ephemeral_dir.path, android_app_ephemeral_dir.len)) {
+        dir = &android_app_ephemeral_dir;
     } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
         dir = &android_asec_dir;
     } else if (!strncmp(path, android_mnt_expand_dir.path, android_mnt_expand_dir.len)) {
@@ -1168,3 +1193,32 @@
 
    return 0;
 }
+
+int wait_child(pid_t pid)
+{
+    int status;
+    pid_t got_pid;
+
+    while (1) {
+        got_pid = waitpid(pid, &status, 0);
+        if (got_pid == -1 && errno == EINTR) {
+            printf("waitpid interrupted, retrying\n");
+        } else {
+            break;
+        }
+    }
+    if (got_pid != pid) {
+        ALOGW("waitpid failed: wanted %d, got %d: %s\n",
+            (int) pid, (int) got_pid, strerror(errno));
+        return 1;
+    }
+
+    if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
+        return 0;
+    } else {
+        return status;      /* always nonzero */
+    }
+}
+
+}  // namespace installd
+}  // namespace android
diff --git a/cmds/installd/utils.h b/cmds/installd/utils.h
new file mode 100644
index 0000000..4d6b66e
--- /dev/null
+++ b/cmds/installd/utils.h
@@ -0,0 +1,146 @@
+/*
+**
+** Copyright 2008, 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 UTILS_H_
+#define UTILS_H_
+
+#include <string>
+#include <vector>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <unistd.h>
+#include <utime.h>
+
+#include <cutils/multiuser.h>
+
+#include <installd_constants.h>
+
+namespace android {
+namespace installd {
+
+struct dir_rec_t;
+
+typedef struct cache_dir_struct {
+    struct cache_dir_struct* parent;
+    int32_t childCount;
+    int32_t hiddenCount;
+    int32_t deleted;
+    char name[];
+} cache_dir_t;
+
+typedef struct {
+    cache_dir_t* dir;
+    time_t modTime;
+    char name[];
+} cache_file_t;
+
+typedef struct {
+    size_t numDirs;
+    size_t availDirs;
+    cache_dir_t** dirs;
+    size_t numFiles;
+    size_t availFiles;
+    cache_file_t** files;
+    size_t numCollected;
+    void* memBlocks;
+    int8_t* curMemBlockAvail;
+    int8_t* curMemBlockEnd;
+} cache_t;
+
+int create_pkg_path(char path[PKG_PATH_MAX],
+                    const char *pkgname,
+                    const char *postfix,
+                    userid_t userid);
+
+std::string create_data_path(const char* volume_uuid);
+
+std::string create_data_app_path(const char* volume_uuid);
+
+std::string create_data_app_package_path(const char* volume_uuid, const char* package_name);
+
+// TODO: finish refactoring to "_ce"
+std::string create_data_user_path(const char* volume_uuid, userid_t userid);
+std::string create_data_user_de_path(const char* volume_uuid, userid_t userid);
+
+std::string create_data_user_package_path(const char* volume_uuid,
+        userid_t user, const char* package_name);
+std::string create_data_user_de_package_path(const char* volume_uuid,
+        userid_t user, const char* package_name);
+
+std::string create_data_media_path(const char* volume_uuid, userid_t userid);
+
+std::vector<userid_t> get_known_users(const char* volume_uuid);
+
+int create_user_config_path(char path[PKG_PATH_MAX], userid_t userid);
+
+int create_move_path(char path[PKG_PATH_MAX],
+                     const char* pkgname,
+                     const char* leaf,
+                     userid_t userid);
+
+int is_valid_package_name(const char* pkgname);
+
+int delete_dir_contents(const std::string& pathname);
+int delete_dir_contents_and_dir(const std::string& pathname);
+
+int delete_dir_contents(const char *pathname,
+                        int also_delete_dir,
+                        int (*exclusion_predicate)(const char *name, const int is_dir));
+
+int delete_dir_contents_fd(int dfd, const char *name);
+
+int copy_dir_files(const char *srcname, const char *dstname, uid_t owner, gid_t group);
+
+int lookup_media_dir(char basepath[PATH_MAX], const char *dir);
+
+int64_t data_disk_free(const std::string& data_path);
+
+cache_t* start_cache_collection();
+
+void add_cache_files(cache_t* cache, const char *basepath, const char *cachedir);
+
+void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size);
+
+void finish_cache_collection(cache_t* cache);
+
+int validate_system_app_path(const char* path);
+
+int get_path_from_env(dir_rec_t* rec, const char* var);
+
+int get_path_from_string(dir_rec_t* rec, const char* path);
+
+int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix);
+
+int validate_apk_path(const char *path);
+int validate_apk_path_subdirs(const char *path);
+
+int append_and_increment(char** dst, const char* src, size_t* dst_size);
+
+char *build_string2(const char *s1, const char *s2);
+char *build_string3(const char *s1, const char *s2, const char *s3);
+
+int ensure_dir(const char* path, mode_t mode, uid_t uid, gid_t gid);
+int ensure_media_user_dirs(const char* uuid, userid_t userid);
+int ensure_config_user_dirs(userid_t userid);
+
+int wait_child(pid_t pid);
+
+}  // namespace installd
+}  // namespace android
+
+#endif  // UTILS_H_
diff --git a/cmds/servicemanager/servicemanager.rc b/cmds/servicemanager/servicemanager.rc
index a6a4d03..0d07a70 100644
--- a/cmds/servicemanager/servicemanager.rc
+++ b/cmds/servicemanager/servicemanager.rc
@@ -5,6 +5,7 @@
     critical
     onrestart restart healthd
     onrestart restart zygote
+    onrestart restart audioserver
     onrestart restart media
     onrestart restart surfaceflinger
     onrestart restart inputflinger
diff --git a/data/etc/android.hardware.sensor.ambient_temperature.xml b/data/etc/android.hardware.sensor.ambient_temperature.xml
new file mode 100644
index 0000000..8ad140e
--- /dev/null
+++ b/data/etc/android.hardware.sensor.ambient_temperature.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- Feature for devices with an ambient temperature sensor. -->
+<permissions>
+    <feature name="android.hardware.sensor.ambient_temperature" />
+</permissions>
diff --git a/data/etc/android.hardware.sensor.relative_humidity.xml b/data/etc/android.hardware.sensor.relative_humidity.xml
new file mode 100644
index 0000000..b9432d3
--- /dev/null
+++ b/data/etc/android.hardware.sensor.relative_humidity.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<!-- Feature for devices with a relative humidity sensor. -->
+<permissions>
+    <feature name="android.hardware.sensor.relative_humidity" />
+</permissions>
diff --git a/data/etc/android.software.picture_in_picture.xml b/data/etc/android.software.picture_in_picture.xml
new file mode 100644
index 0000000..d5e058d
--- /dev/null
+++ b/data/etc/android.software.picture_in_picture.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+
+<permissions>
+    <feature name="android.software.picture_in_picture" />
+</permissions>
diff --git a/include/android/input.h b/include/android/input.h
index 5ab4e29..5eeb7fc 100644
--- a/include/android/input.h
+++ b/include/android/input.h
@@ -644,6 +644,13 @@
      */
     AMOTION_EVENT_AXIS_TILT = 25,
     /**
+     * Axis constant:  Generic scroll axis of a motion event.
+     *
+     * - This is used for scroll axis motion events that can't be classified as strictly
+     *   vertical or horizontal. The movement of a rotating scroller is an example of this.
+     */
+    AMOTION_EVENT_AXIS_SCROLL = 26,
+    /**
      * Axis constant: Generic 1 axis of a motion event.
      * The interpretation of a generic axis is device-specific.
      */
@@ -817,6 +824,8 @@
     AINPUT_SOURCE_TOUCH_NAVIGATION = 0x00200000 | AINPUT_SOURCE_CLASS_NONE,
     /** joystick */
     AINPUT_SOURCE_JOYSTICK = 0x01000000 | AINPUT_SOURCE_CLASS_JOYSTICK,
+    /** rotary encoder */
+    AINPUT_SOURCE_ROTARY_ENCODER = 0x00400000 | AINPUT_SOURCE_CLASS_NONE,
 
     /** any */
     AINPUT_SOURCE_ANY = 0xffffff00,
diff --git a/include/binder/IBinder.h b/include/binder/IBinder.h
index 97f1fc2..5f1e87c 100644
--- a/include/binder/IBinder.h
+++ b/include/binder/IBinder.h
@@ -23,8 +23,12 @@
 #include <utils/Vector.h>
 
 
+// linux/binder.h already defines this, but we can't just include it from there
+// because there are host builds that include this file.
+#ifndef B_PACK_CHARS
 #define B_PACK_CHARS(c1, c2, c3, c4) \
     ((((c1)<<24)) | (((c2)<<16)) | (((c3)<<8)) | (c4))
+#endif  // B_PACK_CHARS
 
 // ---------------------------------------------------------------------------
 namespace android {
diff --git a/include/binder/Parcel.h b/include/binder/Parcel.h
index 16a4790..0abf8f3 100644
--- a/include/binder/Parcel.h
+++ b/include/binder/Parcel.h
@@ -109,6 +109,7 @@
     status_t            writeCString(const char* str);
     status_t            writeString8(const String8& str);
     status_t            writeString16(const String16& str);
+    status_t            writeString16(const std::unique_ptr<String16>& str);
     status_t            writeString16(const char16_t* str, size_t len);
     status_t            writeStrongBinder(const sp<IBinder>& val);
     status_t            writeWeakBinder(const wp<IBinder>& val);
@@ -118,19 +119,35 @@
     status_t            writeChar(char16_t val);
     status_t            writeByte(int8_t val);
 
+    status_t            writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val);
     status_t            writeByteVector(const std::vector<int8_t>& val);
+    status_t            writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val);
     status_t            writeInt32Vector(const std::vector<int32_t>& val);
+    status_t            writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val);
     status_t            writeInt64Vector(const std::vector<int64_t>& val);
+    status_t            writeFloatVector(const std::unique_ptr<std::vector<float>>& val);
     status_t            writeFloatVector(const std::vector<float>& val);
+    status_t            writeDoubleVector(const std::unique_ptr<std::vector<double>>& val);
     status_t            writeDoubleVector(const std::vector<double>& val);
+    status_t            writeBoolVector(const std::unique_ptr<std::vector<bool>>& val);
     status_t            writeBoolVector(const std::vector<bool>& val);
+    status_t            writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val);
     status_t            writeCharVector(const std::vector<char16_t>& val);
+    status_t            writeString16Vector(
+                            const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val);
     status_t            writeString16Vector(const std::vector<String16>& val);
 
+    status_t            writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val);
     status_t            writeStrongBinderVector(const std::vector<sp<IBinder>>& val);
 
     template<typename T>
+    status_t            writeParcelableVector(const std::unique_ptr<std::vector<std::unique_ptr<T>>>& val);
+    template<typename T>
     status_t            writeParcelableVector(const std::vector<T>& val);
+
+    template<typename T>
+    status_t            writeNullableParcelable(const std::unique_ptr<T>& parcelable);
+
     status_t            writeParcelable(const Parcelable& parcelable);
 
     template<typename T>
@@ -164,6 +181,8 @@
     // Place a vector of file desciptors into the parcel. Each descriptor is
     // dup'd as in writeDupFileDescriptor
     status_t            writeUniqueFileDescriptorVector(
+                            const std::unique_ptr<std::vector<ScopedFd>>& val);
+    status_t            writeUniqueFileDescriptorVector(
                             const std::vector<ScopedFd>& val);
 
     // Writes a blob to the parcel.
@@ -215,27 +234,45 @@
     String8             readString8() const;
     String16            readString16() const;
     status_t            readString16(String16* pArg) const;
+    status_t            readString16(std::unique_ptr<String16>* pArg) const;
     const char16_t*     readString16Inplace(size_t* outLen) const;
     sp<IBinder>         readStrongBinder() const;
     status_t            readStrongBinder(sp<IBinder>* val) const;
     wp<IBinder>         readWeakBinder() const;
 
     template<typename T>
+    status_t            readParcelableVector(
+                            std::unique_ptr<std::vector<std::unique_ptr<T>>>* val) const;
+    template<typename T>
     status_t            readParcelableVector(std::vector<T>* val) const;
+
     status_t            readParcelable(Parcelable* parcelable) const;
 
     template<typename T>
+    status_t            readParcelable(std::unique_ptr<T>* parcelable) const;
+
+    template<typename T>
     status_t            readStrongBinder(sp<T>* val) const;
 
+    status_t            readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const;
     status_t            readStrongBinderVector(std::vector<sp<IBinder>>* val) const;
 
+    status_t            readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const;
     status_t            readByteVector(std::vector<int8_t>* val) const;
+    status_t            readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const;
     status_t            readInt32Vector(std::vector<int32_t>* val) const;
+    status_t            readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const;
     status_t            readInt64Vector(std::vector<int64_t>* val) const;
+    status_t            readFloatVector(std::unique_ptr<std::vector<float>>* val) const;
     status_t            readFloatVector(std::vector<float>* val) const;
+    status_t            readDoubleVector(std::unique_ptr<std::vector<double>>* val) const;
     status_t            readDoubleVector(std::vector<double>* val) const;
+    status_t            readBoolVector(std::unique_ptr<std::vector<bool>>* val) const;
     status_t            readBoolVector(std::vector<bool>* val) const;
+    status_t            readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const;
     status_t            readCharVector(std::vector<char16_t>* val) const;
+    status_t            readString16Vector(
+                            std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const;
     status_t            readString16Vector(std::vector<String16>* val) const;
 
     template<typename T>
@@ -269,6 +306,8 @@
 
     // Retrieve a vector of smart file descriptors from the parcel.
     status_t            readUniqueFileDescriptorVector(
+                            std::unique_ptr<std::vector<ScopedFd>>* val) const;
+    status_t            readUniqueFileDescriptorVector(
                             std::vector<ScopedFd>* val) const;
 
     // Reads a blob from the parcel.
@@ -326,16 +365,28 @@
     template<class T>
     status_t            writeAligned(T val);
 
+    status_t            writeRawNullableParcelable(const Parcelable*
+                                                   parcelable);
+
     template<typename T, typename U>
     status_t            unsafeReadTypedVector(std::vector<T>* val,
                                               status_t(Parcel::*read_func)(U*) const) const;
     template<typename T>
+    status_t            readNullableTypedVector(std::unique_ptr<std::vector<T>>* val,
+                                                status_t(Parcel::*read_func)(T*) const) const;
+    template<typename T>
     status_t            readTypedVector(std::vector<T>* val,
                                         status_t(Parcel::*read_func)(T*) const) const;
     template<typename T, typename U>
     status_t            unsafeWriteTypedVector(const std::vector<T>& val,
                                                status_t(Parcel::*write_func)(U));
     template<typename T>
+    status_t            writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
+                                                 status_t(Parcel::*write_func)(const T&));
+    template<typename T>
+    status_t            writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
+                                                 status_t(Parcel::*write_func)(T));
+    template<typename T>
     status_t            writeTypedVector(const std::vector<T>& val,
                                          status_t(Parcel::*write_func)(const T&));
     template<typename T>
@@ -506,9 +557,8 @@
 
 template<typename T, typename U>
 status_t Parcel::unsafeReadTypedVector(
-        std::vector<T>* val, status_t(Parcel::*read_func)(U*) const) const {
-    val->clear();
-
+        std::vector<T>* val,
+        status_t(Parcel::*read_func)(U*) const) const {
     int32_t size;
     status_t status = this->readInt32(&size);
 
@@ -539,6 +589,30 @@
     return unsafeReadTypedVector(val, read_func);
 }
 
+template<typename T>
+status_t Parcel::readNullableTypedVector(std::unique_ptr<std::vector<T>>* val,
+                                         status_t(Parcel::*read_func)(T*) const) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    val->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    val->reset(new std::vector<T>());
+
+    status = unsafeReadTypedVector(val->get(), read_func);
+
+    if (status != OK) {
+        val->reset();
+    }
+
+    return status;
+}
+
 template<typename T, typename U>
 status_t Parcel::unsafeWriteTypedVector(const std::vector<T>& val,
                                         status_t(Parcel::*write_func)(U)) {
@@ -565,24 +639,104 @@
 
 template<typename T>
 status_t Parcel::writeTypedVector(const std::vector<T>& val,
-                          status_t(Parcel::*write_func)(const T&)) {
+                                  status_t(Parcel::*write_func)(const T&)) {
     return unsafeWriteTypedVector(val, write_func);
 }
 
 template<typename T>
 status_t Parcel::writeTypedVector(const std::vector<T>& val,
-                          status_t(Parcel::*write_func)(T)) {
+                                  status_t(Parcel::*write_func)(T)) {
     return unsafeWriteTypedVector(val, write_func);
 }
 
 template<typename T>
+status_t Parcel::writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
+                                          status_t(Parcel::*write_func)(const T&)) {
+    if (val.get() == nullptr) {
+        return this->writeInt32(-1);
+    }
+
+    return unsafeWriteTypedVector(*val, write_func);
+}
+
+template<typename T>
+status_t Parcel::writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
+                                          status_t(Parcel::*write_func)(T)) {
+    if (val.get() == nullptr) {
+        return this->writeInt32(-1);
+    }
+
+    return unsafeWriteTypedVector(*val, write_func);
+}
+
+template<typename T>
 status_t Parcel::readParcelableVector(std::vector<T>* val) const {
-    return unsafeReadTypedVector(val, &Parcel::readParcelable);
+    return unsafeReadTypedVector<T, Parcelable>(val, &Parcel::readParcelable);
+}
+
+template<typename T>
+status_t Parcel::readParcelableVector(std::unique_ptr<std::vector<std::unique_ptr<T>>>* val) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    val->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    val->reset(new std::vector<T>());
+
+    status = unsafeReadTypedVector(val->get(), &Parcel::readParcelable);
+
+    if (status != OK) {
+        val->reset();
+    }
+
+    return status;
+}
+
+template<typename T>
+status_t Parcel::readParcelable(std::unique_ptr<T>* parcelable) const {
+    const int32_t start = dataPosition();
+    int32_t present;
+    status_t status = readInt32(&present);
+    parcelable->reset();
+
+    if (status != OK || !present) {
+        return status;
+    }
+
+    setDataPosition(start);
+    parcelable->reset(new T());
+
+    status = readParcelable(parcelable->get());
+
+    if (status != OK) {
+        parcelable->reset();
+    }
+
+    return status;
+}
+
+template<typename T>
+status_t Parcel::writeNullableParcelable(const std::unique_ptr<T>& parcelable) {
+    return writeRawNullableParcelable(parcelable.get());
 }
 
 template<typename T>
 status_t Parcel::writeParcelableVector(const std::vector<T>& val) {
-    return unsafeWriteTypedVector(val, &Parcel::writeParcelable);
+    return unsafeWriteTypedVector<T,const Parcelable&>(val, &Parcel::writeParcelable);
+}
+
+template<typename T>
+status_t Parcel::writeParcelableVector(const std::unique_ptr<std::vector<std::unique_ptr<T>>>& val) {
+    if (val.get() == nullptr) {
+        return this->writeInt32(-1);
+    }
+
+    return unsafeWriteTypedVector(*val, &Parcel::writeParcelable);
 }
 
 // ---------------------------------------------------------------------------
diff --git a/include/binder/PersistableBundle.h b/include/binder/PersistableBundle.h
new file mode 100644
index 0000000..fe5619f
--- /dev/null
+++ b/include/binder/PersistableBundle.h
@@ -0,0 +1,118 @@
+/*
+ * 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 ANDROID_PERSISTABLE_BUNDLE_H
+#define ANDROID_PERSISTABLE_BUNDLE_H
+
+#include <map>
+#include <vector>
+
+#include <binder/Parcelable.h>
+#include <utils/String16.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+
+namespace os {
+
+/*
+ * C++ implementation of PersistableBundle, a mapping from String values to
+ * various types that can be saved to persistent and later restored.
+ */
+class PersistableBundle : public Parcelable {
+public:
+    PersistableBundle() = default;
+    virtual ~PersistableBundle() = default;
+    PersistableBundle(const PersistableBundle& bundle) = default;
+
+    status_t writeToParcel(Parcel* parcel) const override;
+    status_t readFromParcel(const Parcel* parcel) override;
+
+    bool empty() const;
+    size_t size() const;
+    size_t erase(const String16& key);
+
+    /*
+     * Setters for PersistableBundle. Adds a a key-value pair instantiated with
+     * |key| and |value| into the member map appropriate for the type of |value|.
+     * If there is already an existing value for |key|, |value| will replace it.
+     */
+    void putBoolean(const String16& key, bool value);
+    void putInt(const String16& key, int32_t value);
+    void putLong(const String16& key, int64_t value);
+    void putDouble(const String16& key, double value);
+    void putString(const String16& key, const String16& value);
+    void putBooleanVector(const String16& key, const std::vector<bool>& value);
+    void putIntVector(const String16& key, const std::vector<int32_t>& value);
+    void putLongVector(const String16& key, const std::vector<int64_t>& value);
+    void putDoubleVector(const String16& key, const std::vector<double>& value);
+    void putStringVector(const String16& key, const std::vector<String16>& value);
+    void putPersistableBundle(const String16& key, const PersistableBundle& value);
+
+    /*
+     * Getters for PersistableBundle. If |key| exists, these methods write the
+     * value associated with |key| into |out|, and return true. Otherwise, these
+     * methods return false.
+     */
+    bool getBoolean(const String16& key, bool* out) const;
+    bool getInt(const String16& key, int32_t* out) const;
+    bool getLong(const String16& key, int64_t* out) const;
+    bool getDouble(const String16& key, double* out) const;
+    bool getString(const String16& key, String16* out) const;
+    bool getBooleanVector(const String16& key, std::vector<bool>* out) const;
+    bool getIntVector(const String16& key, std::vector<int32_t>* out) const;
+    bool getLongVector(const String16& key, std::vector<int64_t>* out) const;
+    bool getDoubleVector(const String16& key, std::vector<double>* out) const;
+    bool getStringVector(const String16& key, std::vector<String16>* out) const;
+    bool getPersistableBundle(const String16& key, PersistableBundle* out) const;
+
+    friend bool operator==(const PersistableBundle& lhs, const PersistableBundle& rhs) {
+        return (lhs.mBoolMap == rhs.mBoolMap && lhs.mIntMap == rhs.mIntMap &&
+                lhs.mLongMap == rhs.mLongMap && lhs.mDoubleMap == rhs.mDoubleMap &&
+                lhs.mStringMap == rhs.mStringMap && lhs.mBoolVectorMap == rhs.mBoolVectorMap &&
+                lhs.mIntVectorMap == rhs.mIntVectorMap &&
+                lhs.mLongVectorMap == rhs.mLongVectorMap &&
+                lhs.mDoubleVectorMap == rhs.mDoubleVectorMap &&
+                lhs.mStringVectorMap == rhs.mStringVectorMap &&
+                lhs.mPersistableBundleMap == rhs.mPersistableBundleMap);
+    }
+
+    friend bool operator!=(const PersistableBundle& lhs, const PersistableBundle& rhs) {
+        return !(lhs == rhs);
+    }
+
+private:
+    status_t writeToParcelInner(Parcel* parcel) const;
+    status_t readFromParcelInner(const Parcel* parcel, size_t length);
+
+    std::map<String16, bool> mBoolMap;
+    std::map<String16, int32_t> mIntMap;
+    std::map<String16, int64_t> mLongMap;
+    std::map<String16, double> mDoubleMap;
+    std::map<String16, String16> mStringMap;
+    std::map<String16, std::vector<bool>> mBoolVectorMap;
+    std::map<String16, std::vector<int32_t>> mIntVectorMap;
+    std::map<String16, std::vector<int64_t>> mLongVectorMap;
+    std::map<String16, std::vector<double>> mDoubleVectorMap;
+    std::map<String16, std::vector<String16>> mStringVectorMap;
+    std::map<String16, PersistableBundle> mPersistableBundleMap;
+};
+
+}  // namespace os
+
+}  // namespace android
+
+#endif  // ANDROID_PERSISTABLE_BUNDLE_H
diff --git a/include/binder/Status.h b/include/binder/Status.h
index 04738f8..203a01e 100644
--- a/include/binder/Status.h
+++ b/include/binder/Status.h
@@ -60,31 +60,42 @@
         EX_ILLEGAL_STATE = -5,
         EX_NETWORK_MAIN_THREAD = -6,
         EX_UNSUPPORTED_OPERATION = -7,
-        EX_TRANSACTION_FAILED = -8,
+        EX_SERVICE_SPECIFIC = -8,
 
         // This is special and Java specific; see Parcel.java.
         EX_HAS_REPLY_HEADER = -128,
+        // This is special, and indicates to C++ binder proxies that the
+        // transaction has failed at a low level.
+        EX_TRANSACTION_FAILED = -129,
     };
 
-    // Allow authors to explicitly pick whether their integer is a status_t or
-    // exception code.
-    static Status fromExceptionCode(int32_t exception_code);
-    static Status fromStatusT(status_t status);
     // A more readable alias for the default constructor.
     static Status ok();
+    // Authors should explicitly pick whether their integer is:
+    //  - an exception code (EX_* above)
+    //  - service specific error code
+    //  - status_t
+    //
+    //  Prefer a generic exception code when possible, then a service specific
+    //  code, and finally a status_t for low level failures or legacy support.
+    //  Exception codes and service specific errors map to nicer exceptions for
+    //  Java clients.
+    static Status fromExceptionCode(int32_t exceptionCode);
+    static Status fromExceptionCode(int32_t exceptionCode,
+                                    const String8& message);
+    static Status fromServiceSpecificError(int32_t serviceSpecificErrorCode);
+    static Status fromServiceSpecificError(int32_t serviceSpecificErrorCode,
+                                           const String8& message);
+    static Status fromStatusT(status_t status);
 
     Status() = default;
-    Status(int32_t exception_code, const String8& message);
-    Status(int32_t exception_code, const char* message);
-
+    ~Status() = default;
 
     // Status objects are copyable and contain just simple data.
     Status(const Status& status) = default;
     Status(Status&& status) = default;
     Status& operator=(const Status& status) = default;
 
-    ~Status() = default;
-
     // Bear in mind that if the client or service is a Java endpoint, this
     // is not the logic which will provide/interpret the data here.
     status_t readFromParcel(const Parcel& parcel);
@@ -92,16 +103,22 @@
 
     // Set one of the pre-defined exception types defined above.
     void setException(int32_t ex, const String8& message);
-    // A few of the status_t values map to exception codes, but most of them
-    // simply map to "transaction failed."
+    // Set a service specific exception with error code.
+    void setServiceSpecificError(int32_t errorCode, const String8& message);
+    // Setting a |status| != OK causes generated code to return |status|
+    // from Binder transactions, rather than writing an exception into the
+    // reply Parcel.  This is the least preferable way of reporting errors.
     void setFromStatusT(status_t status);
 
     // Get information about an exception.
-    // Any argument may be given as nullptr.
-    void getException(int32_t* returned_exception,
-                      String8* returned_message) const;
     int32_t exceptionCode() const  { return mException; }
     const String8& exceptionMessage() const { return mMessage; }
+    status_t transactionError() const {
+        return mException == EX_TRANSACTION_FAILED ? mErrorCode : OK;
+    }
+    int32_t serviceSpecificErrorCode() const {
+        return mException == EX_SERVICE_SPECIFIC ? mErrorCode : 0;
+    }
 
     bool isOk() const { return mException == EX_NONE; }
 
@@ -109,9 +126,18 @@
     String8 toString8() const;
 
 private:
-    // We always write |mException| to the parcel.
-    // If |mException| !=  EX_NONE, we write message as well.
+    Status(int32_t exceptionCode, int32_t errorCode);
+    Status(int32_t exceptionCode, int32_t errorCode, const String8& message);
+
+    // If |mException| == EX_TRANSACTION_FAILED, generated code will return
+    // |mErrorCode| as the result of the transaction rather than write an
+    // exception to the reply parcel.
+    //
+    // Otherwise, we always write |mException| to the parcel.
+    // If |mException| !=  EX_NONE, we write |mMessage| as well.
+    // If |mException| == EX_SERVICE_SPECIFIC we write |mErrorCode| as well.
     int32_t mException = EX_NONE;
+    int32_t mErrorCode = 0;
     String8 mMessage;
 };  // class Status
 
diff --git a/include/media/drm/DrmAPI.h b/include/media/drm/DrmAPI.h
index 272881b..985d919 100644
--- a/include/media/drm/DrmAPI.h
+++ b/include/media/drm/DrmAPI.h
@@ -220,9 +220,6 @@
                                                   Vector<uint8_t> &certificate,
                                                   Vector<uint8_t> &wrapped_key) = 0;
 
-        // Remove device provisioning.
-        virtual status_t unprovisionDevice() = 0;
-
         // A means of enforcing the contractual requirement for a concurrent stream
         // limit per subscriber across devices is provided via SecureStop.  SecureStop
         // is a means of securely monitoring the lifetime of sessions. Since playback
diff --git a/include/media/openmax/OMX_AsString.h b/include/media/openmax/OMX_AsString.h
index ae8430d..5bfec61 100644
--- a/include/media/openmax/OMX_AsString.h
+++ b/include/media/openmax/OMX_AsString.h
@@ -714,6 +714,8 @@
         case OMX_VIDEO_CodingVP8:        return "VP8";
         case OMX_VIDEO_CodingVP9:        return "VP9";
         case OMX_VIDEO_CodingHEVC:       return "HEVC";
+        case OMX_VIDEO_CodingDolbyAVC:   return "DolbyAVC";
+        case OMX_VIDEO_CodingDolbyHEVC:  return "DolbyHEVC";
         default:                         return def;
     }
 }
diff --git a/include/media/openmax/OMX_Video.h b/include/media/openmax/OMX_Video.h
index decc410..7b6df89 100644
--- a/include/media/openmax/OMX_Video.h
+++ b/include/media/openmax/OMX_Video.h
@@ -88,6 +88,8 @@
     OMX_VIDEO_CodingVP8,        /**< Google VP8, formerly known as On2 VP8 */
     OMX_VIDEO_CodingVP9,        /**< Google VP9 */
     OMX_VIDEO_CodingHEVC,       /**< ITU H.265/HEVC */
+    OMX_VIDEO_CodingDolbyAVC,   /**< DolbyVision H.264/AVC */
+    OMX_VIDEO_CodingDolbyHEVC,  /**< DolbyVision H.265/HEVC */
     OMX_VIDEO_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */
     OMX_VIDEO_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */
     OMX_VIDEO_CodingMax = 0x7FFFFFFF
diff --git a/libs/binder/Android.mk b/libs/binder/Android.mk
index e8f0981..41bf618 100644
--- a/libs/binder/Android.mk
+++ b/libs/binder/Android.mk
@@ -28,13 +28,14 @@
     IPermissionController.cpp \
     IProcessInfoService.cpp \
     IResultReceiver.cpp \
-    ProcessInfoService.cpp \
     IServiceManager.cpp \
-    MemoryDealer.cpp \
     MemoryBase.cpp \
+    MemoryDealer.cpp \
     MemoryHeapBase.cpp \
     Parcel.cpp \
     PermissionCache.cpp \
+    PersistableBundle.cpp \
+    ProcessInfoService.cpp \
     ProcessState.cpp \
     Static.cpp \
     Status.cpp \
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index 13ecc87..10cdee6 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -741,6 +741,15 @@
     return NULL;
 }
 
+status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val)
+{
+    if (!val) {
+        return writeInt32(-1);
+    }
+
+    return writeByteVector(*val);
+}
+
 status_t Parcel::writeByteVector(const std::vector<int8_t>& val)
 {
     status_t status;
@@ -769,36 +778,72 @@
     return writeTypedVector(val, &Parcel::writeInt32);
 }
 
+status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeInt32);
+}
+
 status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val)
 {
     return writeTypedVector(val, &Parcel::writeInt64);
 }
 
+status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeInt64);
+}
+
 status_t Parcel::writeFloatVector(const std::vector<float>& val)
 {
     return writeTypedVector(val, &Parcel::writeFloat);
 }
 
+status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeFloat);
+}
+
 status_t Parcel::writeDoubleVector(const std::vector<double>& val)
 {
     return writeTypedVector(val, &Parcel::writeDouble);
 }
 
+status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeDouble);
+}
+
 status_t Parcel::writeBoolVector(const std::vector<bool>& val)
 {
     return writeTypedVector(val, &Parcel::writeBool);
 }
 
+status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeBool);
+}
+
 status_t Parcel::writeCharVector(const std::vector<char16_t>& val)
 {
     return writeTypedVector(val, &Parcel::writeChar);
 }
 
+status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeChar);
+}
+
 status_t Parcel::writeString16Vector(const std::vector<String16>& val)
 {
     return writeTypedVector(val, &Parcel::writeString16);
 }
 
+status_t Parcel::writeString16Vector(
+        const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeString16);
+}
+
 status_t Parcel::writeInt32(int32_t val)
 {
     return writeAligned(val);
@@ -915,6 +960,15 @@
     return err;
 }
 
+status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
+{
+    if (!str) {
+        return writeInt32(-1);
+    }
+
+    return writeString16(*str);
+}
+
 status_t Parcel::writeString16(const String16& str)
 {
     return writeString16(str.string(), str.size());
@@ -948,6 +1002,15 @@
     return writeTypedVector(val, &Parcel::writeStrongBinder);
 }
 
+status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeStrongBinder);
+}
+
+status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readStrongBinder);
+}
+
 status_t Parcel::readStrongBinderVector(std::vector<sp<IBinder>>* val) const {
     return readTypedVector(val, &Parcel::readStrongBinder);
 }
@@ -957,6 +1020,14 @@
     return flatten_binder(ProcessState::self(), val, this);
 }
 
+status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
+    if (!parcelable) {
+        return writeInt32(0);
+    }
+
+    return writeParcelable(*parcelable);
+}
+
 status_t Parcel::writeParcelable(const Parcelable& parcelable) {
     status_t status = writeInt32(1);  // parcelable is not null.
     if (status != OK) {
@@ -1020,6 +1091,10 @@
     return writeTypedVector(val, &Parcel::writeUniqueFileDescriptor);
 }
 
+status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<ScopedFd>>& val) {
+    return writeNullableTypedVector(val, &Parcel::writeUniqueFileDescriptor);
+}
+
 status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
 {
     if (len > INT32_MAX) {
@@ -1285,25 +1360,83 @@
     return status;
 }
 
+status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    val->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    val->reset(new std::vector<int8_t>());
+
+    status = readByteVector(val->get());
+
+    if (status != OK) {
+        val->reset();
+    }
+
+    return status;
+}
+
+status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readInt32);
+}
+
 status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const {
     return readTypedVector(val, &Parcel::readInt32);
 }
 
+status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readInt64);
+}
+
 status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const {
     return readTypedVector(val, &Parcel::readInt64);
 }
 
+status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readFloat);
+}
+
 status_t Parcel::readFloatVector(std::vector<float>* val) const {
     return readTypedVector(val, &Parcel::readFloat);
 }
 
+status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readDouble);
+}
+
 status_t Parcel::readDoubleVector(std::vector<double>* val) const {
     return readTypedVector(val, &Parcel::readDouble);
 }
 
-status_t Parcel::readBoolVector(std::vector<bool>* val) const {
-    val->clear();
+status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    val->reset();
 
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    val->reset(new std::vector<bool>());
+
+    status = readBoolVector(val->get());
+
+    if (status != OK) {
+        val->reset();
+    }
+
+    return status;
+}
+
+status_t Parcel::readBoolVector(std::vector<bool>* val) const {
     int32_t size;
     status_t status = readInt32(&size);
 
@@ -1333,10 +1466,19 @@
     return OK;
 }
 
+status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readChar);
+}
+
 status_t Parcel::readCharVector(std::vector<char16_t>* val) const {
     return readTypedVector(val, &Parcel::readChar);
 }
 
+status_t Parcel::readString16Vector(
+        std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readString16);
+}
+
 status_t Parcel::readString16Vector(std::vector<String16>* val) const {
     return readTypedVector(val, &Parcel::readString16);
 }
@@ -1536,6 +1678,29 @@
     return String16();
 }
 
+status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
+{
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    pArg->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    pArg->reset(new String16());
+
+    status = readString16(pArg->get());
+
+    if (status != OK) {
+        pArg->reset();
+    }
+
+    return status;
+}
+
 status_t Parcel::readString16(String16* pArg) const
 {
     size_t len;
@@ -1659,6 +1824,10 @@
 }
 
 
+status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<ScopedFd>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readUniqueFileDescriptor);
+}
+
 status_t Parcel::readUniqueFileDescriptorVector(std::vector<ScopedFd>* val) const {
     return readTypedVector(val, &Parcel::readUniqueFileDescriptor);
 }
@@ -1987,6 +2156,9 @@
         pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
         gParcelGlobalAllocSize += desired;
         gParcelGlobalAllocSize -= mDataCapacity;
+        if (!mData) {
+            gParcelGlobalAllocCount++;
+        }
         pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
         mData = data;
         mDataCapacity = desired;
@@ -2118,7 +2290,6 @@
                 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
                 gParcelGlobalAllocSize += desired;
                 gParcelGlobalAllocSize -= mDataCapacity;
-                gParcelGlobalAllocCount++;
                 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
                 mData = data;
                 mDataCapacity = desired;
diff --git a/libs/binder/PersistableBundle.cpp b/libs/binder/PersistableBundle.cpp
new file mode 100644
index 0000000..aef791c
--- /dev/null
+++ b/libs/binder/PersistableBundle.cpp
@@ -0,0 +1,434 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "PersistableBundle"
+
+#include <binder/PersistableBundle.h>
+
+#include <limits>
+
+#include <binder/IBinder.h>
+#include <binder/Parcel.h>
+#include <log/log.h>
+#include <utils/Errors.h>
+
+using android::BAD_TYPE;
+using android::BAD_VALUE;
+using android::NO_ERROR;
+using android::Parcel;
+using android::sp;
+using android::status_t;
+using android::UNEXPECTED_NULL;
+
+enum {
+    // Keep in sync with BUNDLE_MAGIC in frameworks/base/core/java/android/os/BaseBundle.java.
+    BUNDLE_MAGIC = 0x4C444E42,
+};
+
+enum {
+    // Keep in sync with frameworks/base/core/java/android/os/Parcel.java.
+    VAL_STRING = 0,
+    VAL_INTEGER = 1,
+    VAL_LONG = 6,
+    VAL_DOUBLE = 8,
+    VAL_BOOLEAN = 9,
+    VAL_STRINGARRAY = 14,
+    VAL_INTARRAY = 18,
+    VAL_LONGARRAY = 19,
+    VAL_BOOLEANARRAY = 23,
+    VAL_PERSISTABLEBUNDLE = 25,
+    VAL_DOUBLEARRAY = 28,
+};
+
+namespace {
+template <typename T>
+bool getValue(const android::String16& key, T* out, const std::map<android::String16, T>& map) {
+    const auto& it = map.find(key);
+    if (it == map.end()) return false;
+    *out = it->second;
+    return true;
+}
+}  // namespace
+
+namespace android {
+
+namespace os {
+
+#define RETURN_IF_FAILED(calledOnce)                                     \
+    {                                                                    \
+        status_t returnStatus = calledOnce;                              \
+        if (returnStatus) {                                              \
+            ALOGE("Failed at %s:%d (%s)", __FILE__, __LINE__, __func__); \
+            return returnStatus;                                         \
+         }                                                               \
+    }
+
+#define RETURN_IF_ENTRY_ERASED(map, key)                                 \
+    {                                                                    \
+        size_t num_erased = map.erase(key);                              \
+        if (num_erased) {                                                \
+            ALOGE("Failed at %s:%d (%s)", __FILE__, __LINE__, __func__); \
+            return num_erased;                                           \
+         }                                                               \
+    }
+
+status_t PersistableBundle::writeToParcel(Parcel* parcel) const {
+    /*
+     * Keep implementation in sync with writeToParcelInner() in
+     * frameworks/base/core/java/android/os/BaseBundle.java.
+     */
+
+    // Special case for empty bundles.
+    if (empty()) {
+        RETURN_IF_FAILED(parcel->writeInt32(0));
+        return NO_ERROR;
+    }
+
+    size_t length_pos = parcel->dataPosition();
+    RETURN_IF_FAILED(parcel->writeInt32(1));  // dummy, will hold length
+    RETURN_IF_FAILED(parcel->writeInt32(BUNDLE_MAGIC));
+
+    size_t start_pos = parcel->dataPosition();
+    RETURN_IF_FAILED(writeToParcelInner(parcel));
+    size_t end_pos = parcel->dataPosition();
+
+    // Backpatch length. This length value includes the length header.
+    parcel->setDataPosition(length_pos);
+    size_t length = end_pos - start_pos;
+    if (length > std::numeric_limits<int32_t>::max()) {
+        ALOGE("Parcel length (%zu) too large to store in 32-bit signed int", length);
+        return BAD_VALUE;
+    }
+    RETURN_IF_FAILED(parcel->writeInt32(static_cast<int32_t>(length)));
+    parcel->setDataPosition(end_pos);
+    return NO_ERROR;
+}
+
+status_t PersistableBundle::readFromParcel(const Parcel* parcel) {
+    /*
+     * Keep implementation in sync with readFromParcelInner() in
+     * frameworks/base/core/java/android/os/BaseBundle.java.
+     */
+    int32_t length = parcel->readInt32();
+    if (length < 0) {
+        ALOGE("Bad length in parcel: %d", length);
+        return UNEXPECTED_NULL;
+    }
+
+    return readFromParcelInner(parcel, static_cast<size_t>(length));
+}
+
+bool PersistableBundle::empty() const {
+    return size() == 0u;
+}
+
+size_t PersistableBundle::size() const {
+    return (mBoolMap.size() +
+            mIntMap.size() +
+            mLongMap.size() +
+            mDoubleMap.size() +
+            mStringMap.size() +
+            mBoolVectorMap.size() +
+            mIntVectorMap.size() +
+            mLongVectorMap.size() +
+            mDoubleVectorMap.size() +
+            mStringVectorMap.size() +
+            mPersistableBundleMap.size());
+}
+
+size_t PersistableBundle::erase(const String16& key) {
+    RETURN_IF_ENTRY_ERASED(mBoolMap, key);
+    RETURN_IF_ENTRY_ERASED(mIntMap, key);
+    RETURN_IF_ENTRY_ERASED(mLongMap, key);
+    RETURN_IF_ENTRY_ERASED(mDoubleMap, key);
+    RETURN_IF_ENTRY_ERASED(mStringMap, key);
+    RETURN_IF_ENTRY_ERASED(mBoolVectorMap, key);
+    RETURN_IF_ENTRY_ERASED(mIntVectorMap, key);
+    RETURN_IF_ENTRY_ERASED(mLongVectorMap, key);
+    RETURN_IF_ENTRY_ERASED(mDoubleVectorMap, key);
+    RETURN_IF_ENTRY_ERASED(mStringVectorMap, key);
+    return mPersistableBundleMap.erase(key);
+}
+
+void PersistableBundle::putBoolean(const String16& key, bool value) {
+    erase(key);
+    mBoolMap[key] = value;
+}
+
+void PersistableBundle::putInt(const String16& key, int32_t value) {
+    erase(key);
+    mIntMap[key] = value;
+}
+
+void PersistableBundle::putLong(const String16& key, int64_t value) {
+    erase(key);
+    mLongMap[key] = value;
+}
+
+void PersistableBundle::putDouble(const String16& key, double value) {
+    erase(key);
+    mDoubleMap[key] = value;
+}
+
+void PersistableBundle::putString(const String16& key, const String16& value) {
+    erase(key);
+    mStringMap[key] = value;
+}
+
+void PersistableBundle::putBooleanVector(const String16& key, const std::vector<bool>& value) {
+    erase(key);
+    mBoolVectorMap[key] = value;
+}
+
+void PersistableBundle::putIntVector(const String16& key, const std::vector<int32_t>& value) {
+    erase(key);
+    mIntVectorMap[key] = value;
+}
+
+void PersistableBundle::putLongVector(const String16& key, const std::vector<int64_t>& value) {
+    erase(key);
+    mLongVectorMap[key] = value;
+}
+
+void PersistableBundle::putDoubleVector(const String16& key, const std::vector<double>& value) {
+    erase(key);
+    mDoubleVectorMap[key] = value;
+}
+
+void PersistableBundle::putStringVector(const String16& key, const std::vector<String16>& value) {
+    erase(key);
+    mStringVectorMap[key] = value;
+}
+
+void PersistableBundle::putPersistableBundle(const String16& key, const PersistableBundle& value) {
+    erase(key);
+    mPersistableBundleMap[key] = value;
+}
+
+bool PersistableBundle::getBoolean(const String16& key, bool* out) const {
+    return getValue(key, out, mBoolMap);
+}
+
+bool PersistableBundle::getInt(const String16& key, int32_t* out) const {
+    return getValue(key, out, mIntMap);
+}
+
+bool PersistableBundle::getLong(const String16& key, int64_t* out) const {
+    return getValue(key, out, mLongMap);
+}
+
+bool PersistableBundle::getDouble(const String16& key, double* out) const {
+    return getValue(key, out, mDoubleMap);
+}
+
+bool PersistableBundle::getString(const String16& key, String16* out) const {
+    return getValue(key, out, mStringMap);
+}
+
+bool PersistableBundle::getBooleanVector(const String16& key, std::vector<bool>* out) const {
+    return getValue(key, out, mBoolVectorMap);
+}
+
+bool PersistableBundle::getIntVector(const String16& key, std::vector<int32_t>* out) const {
+    return getValue(key, out, mIntVectorMap);
+}
+
+bool PersistableBundle::getLongVector(const String16& key, std::vector<int64_t>* out) const {
+    return getValue(key, out, mLongVectorMap);
+}
+
+bool PersistableBundle::getDoubleVector(const String16& key, std::vector<double>* out) const {
+    return getValue(key, out, mDoubleVectorMap);
+}
+
+bool PersistableBundle::getStringVector(const String16& key, std::vector<String16>* out) const {
+    return getValue(key, out, mStringVectorMap);
+}
+
+bool PersistableBundle::getPersistableBundle(const String16& key, PersistableBundle* out) const {
+    return getValue(key, out, mPersistableBundleMap);
+}
+
+status_t PersistableBundle::writeToParcelInner(Parcel* parcel) const {
+    /*
+     * To keep this implementation in sync with writeArrayMapInternal() in
+     * frameworks/base/core/java/android/os/Parcel.java, the number of key
+     * value pairs must be written into the parcel before writing the key-value
+     * pairs themselves.
+     */
+    size_t num_entries = size();
+    if (num_entries > std::numeric_limits<int32_t>::max()) {
+        ALOGE("The size of this PersistableBundle (%zu) too large to store in 32-bit signed int",
+              num_entries);
+        return BAD_VALUE;
+    }
+    RETURN_IF_FAILED(parcel->writeInt32(static_cast<int32_t>(num_entries)));
+
+    for (const auto& key_val_pair : mBoolMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_BOOLEAN));
+        RETURN_IF_FAILED(parcel->writeBool(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mIntMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_INTEGER));
+        RETURN_IF_FAILED(parcel->writeInt32(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mLongMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_LONG));
+        RETURN_IF_FAILED(parcel->writeInt64(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mDoubleMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_DOUBLE));
+        RETURN_IF_FAILED(parcel->writeDouble(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mStringMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_STRING));
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mBoolVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_BOOLEANARRAY));
+        RETURN_IF_FAILED(parcel->writeBoolVector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mIntVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_INTARRAY));
+        RETURN_IF_FAILED(parcel->writeInt32Vector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mLongVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_LONGARRAY));
+        RETURN_IF_FAILED(parcel->writeInt64Vector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mDoubleVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_DOUBLEARRAY));
+        RETURN_IF_FAILED(parcel->writeDoubleVector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mStringVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_STRINGARRAY));
+        RETURN_IF_FAILED(parcel->writeString16Vector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mPersistableBundleMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_PERSISTABLEBUNDLE));
+        RETURN_IF_FAILED(key_val_pair.second.writeToParcel(parcel));
+    }
+    return NO_ERROR;
+}
+
+status_t PersistableBundle::readFromParcelInner(const Parcel* parcel, size_t length) {
+    /*
+     * Note: we don't actually use length for anything other than an empty PersistableBundle
+     * check, since we do not actually need to copy in an entire Parcel, unlike in the Java
+     * implementation.
+     */
+    if (length == 0) {
+        // Empty PersistableBundle or end of data.
+        return NO_ERROR;
+    }
+
+    int32_t magic;
+    RETURN_IF_FAILED(parcel->readInt32(&magic));
+    if (magic != BUNDLE_MAGIC) {
+        ALOGE("Bad magic number for PersistableBundle: 0x%08x", magic);
+        return BAD_VALUE;
+    }
+
+    /*
+     * To keep this implementation in sync with unparcel() in
+     * frameworks/base/core/java/android/os/BaseBundle.java, the number of
+     * key-value pairs must be read from the parcel before reading the key-value
+     * pairs themselves.
+     */
+    int32_t num_entries;
+    RETURN_IF_FAILED(parcel->readInt32(&num_entries));
+
+    for (; num_entries > 0; --num_entries) {
+        size_t start_pos = parcel->dataPosition();
+        String16 key;
+        int32_t value_type;
+        RETURN_IF_FAILED(parcel->readString16(&key));
+        RETURN_IF_FAILED(parcel->readInt32(&value_type));
+
+        /*
+         * We assume that both the C++ and Java APIs ensure that all keys in a PersistableBundle
+         * are unique.
+         */
+        switch (value_type) {
+            case VAL_STRING: {
+                RETURN_IF_FAILED(parcel->readString16(&mStringMap[key]));
+                break;
+            }
+            case VAL_INTEGER: {
+                RETURN_IF_FAILED(parcel->readInt32(&mIntMap[key]));
+                break;
+            }
+            case VAL_LONG: {
+                RETURN_IF_FAILED(parcel->readInt64(&mLongMap[key]));
+                break;
+            }
+            case VAL_DOUBLE: {
+                RETURN_IF_FAILED(parcel->readDouble(&mDoubleMap[key]));
+                break;
+            }
+            case VAL_BOOLEAN: {
+                RETURN_IF_FAILED(parcel->readBool(&mBoolMap[key]));
+                break;
+            }
+            case VAL_STRINGARRAY: {
+                RETURN_IF_FAILED(parcel->readString16Vector(&mStringVectorMap[key]));
+                break;
+            }
+            case VAL_INTARRAY: {
+                RETURN_IF_FAILED(parcel->readInt32Vector(&mIntVectorMap[key]));
+                break;
+            }
+            case VAL_LONGARRAY: {
+                RETURN_IF_FAILED(parcel->readInt64Vector(&mLongVectorMap[key]));
+                break;
+            }
+            case VAL_BOOLEANARRAY: {
+                RETURN_IF_FAILED(parcel->readBoolVector(&mBoolVectorMap[key]));
+                break;
+            }
+            case VAL_PERSISTABLEBUNDLE: {
+                RETURN_IF_FAILED(mPersistableBundleMap[key].readFromParcel(parcel));
+                break;
+            }
+            case VAL_DOUBLEARRAY: {
+                RETURN_IF_FAILED(parcel->readDoubleVector(&mDoubleVectorMap[key]));
+                break;
+            }
+            default: {
+                ALOGE("Unrecognized type: %d", value_type);
+                return BAD_TYPE;
+                break;
+            }
+        }
+    }
+
+    return NO_ERROR;
+}
+
+}  // namespace os
+
+}  // namespace android
diff --git a/libs/binder/Status.cpp b/libs/binder/Status.cpp
index 41fff3d..d3520d6 100644
--- a/libs/binder/Status.cpp
+++ b/libs/binder/Status.cpp
@@ -19,8 +19,26 @@
 namespace android {
 namespace binder {
 
-Status Status::fromExceptionCode(int32_t exception_code) {
-    return Status(exception_code, "");
+Status Status::ok() {
+    return Status();
+}
+
+Status Status::fromExceptionCode(int32_t exceptionCode) {
+    return Status(exceptionCode, OK);
+}
+
+Status Status::fromExceptionCode(int32_t exceptionCode,
+                                 const String8& message) {
+    return Status(exceptionCode, OK, message);
+}
+
+Status Status::fromServiceSpecificError(int32_t serviceSpecificErrorCode) {
+    return Status(EX_SERVICE_SPECIFIC, serviceSpecificErrorCode);
+}
+
+Status Status::fromServiceSpecificError(int32_t serviceSpecificErrorCode,
+                                        const String8& message) {
+    return Status(EX_SERVICE_SPECIFIC, serviceSpecificErrorCode, message);
 }
 
 Status Status::fromStatusT(status_t status) {
@@ -29,16 +47,13 @@
     return ret;
 }
 
-Status Status::ok() {
-    return Status();
-}
+Status::Status(int32_t exceptionCode, int32_t errorCode)
+    : mException(exceptionCode),
+      mErrorCode(errorCode) {}
 
-Status::Status(int32_t exception_code, const String8& message)
-    : mException(exception_code),
-      mMessage(message) {}
-
-Status::Status(int32_t exception_code, const char* message)
-    : mException(exception_code),
+Status::Status(int32_t exceptionCode, int32_t errorCode, const String8& message)
+    : mException(exceptionCode),
+      mErrorCode(errorCode),
       mMessage(message) {}
 
 status_t Status::readFromParcel(const Parcel& parcel) {
@@ -69,12 +84,32 @@
     }
 
     // The remote threw an exception.  Get the message back.
-    mMessage = String8(parcel.readString16());
+    String16 message;
+    status = parcel.readString16(&message);
+    if (status != OK) {
+        setFromStatusT(status);
+        return status;
+    }
+    mMessage = String8(message);
+
+    if (mException == EX_SERVICE_SPECIFIC) {
+        status = parcel.readInt32(&mErrorCode);
+    }
+    if (status != OK) {
+        setFromStatusT(status);
+        return status;
+    }
 
     return status;
 }
 
 status_t Status::writeToParcel(Parcel* parcel) const {
+    // Something really bad has happened, and we're not going to even
+    // try returning rich error data.
+    if (mException == EX_TRANSACTION_FAILED) {
+        return mErrorCode;
+    }
+
     status_t status = parcel->writeInt32(mException);
     if (status != OK) { return status; }
     if (mException == EX_NONE) {
@@ -82,39 +117,29 @@
         return status;
     }
     status = parcel->writeString16(String16(mMessage));
-    return status;
-}
-
-void Status::setFromStatusT(status_t status) {
-    switch (status) {
-        case NO_ERROR:
-            mException = EX_NONE;
-            mMessage.clear();
-            break;
-        case UNEXPECTED_NULL:
-            mException = EX_NULL_POINTER;
-            mMessage.setTo("Unexpected null reference in Parcel");
-            break;
-        default:
-            mException = EX_TRANSACTION_FAILED;
-            mMessage.setTo("Transaction failed");
-            break;
+    if (mException != EX_SERVICE_SPECIFIC) {
+        // We have no more information to write.
+        return status;
     }
+    status = parcel->writeInt32(mErrorCode);
+    return status;
 }
 
 void Status::setException(int32_t ex, const String8& message) {
     mException = ex;
+    mErrorCode = NO_ERROR;  // an exception, not a transaction failure.
     mMessage.setTo(message);
 }
 
-void Status::getException(int32_t* returned_exception,
-                          String8* returned_message) const {
-    if (returned_exception) {
-        *returned_exception = mException;
-    }
-    if (returned_message) {
-        returned_message->setTo(mMessage);
-    }
+void Status::setServiceSpecificError(int32_t errorCode, const String8& message) {
+    setException(EX_SERVICE_SPECIFIC, message);
+    mErrorCode = errorCode;
+}
+
+void Status::setFromStatusT(status_t status) {
+    mException = (status == NO_ERROR) ? EX_NONE : EX_TRANSACTION_FAILED;
+    mErrorCode = status;
+    mMessage.clear();
 }
 
 String8 Status::toString8() const {
@@ -123,6 +148,10 @@
         ret.append("No error");
     } else {
         ret.appendFormat("Status(%d): '", mException);
+        if (mException == EX_SERVICE_SPECIFIC ||
+            mException == EX_TRANSACTION_FAILED) {
+            ret.appendFormat("%d: ", mErrorCode);
+        }
         ret.append(String8(mMessage));
         ret.append("'");
     }
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index ef01745..9271ed8 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -809,15 +809,6 @@
         mCore->validateConsistencyLocked();
     } // Autolock scope
 
-    // Wait without lock held
-    if (mCore->mConnectedApi == NATIVE_WINDOW_API_EGL) {
-        // Waiting here allows for two full buffers to be queued but not a
-        // third. In the event that frames take varying time, this makes a
-        // small trade-off in favor of latency rather than throughput.
-        mLastQueueBufferFence->waitForever("Throttling EGL Production");
-        mLastQueueBufferFence = fence;
-    }
-
     // Don't send the GraphicBuffer through the callback, and don't send
     // the slot number, since the consumer shouldn't need it
     item.mGraphicBuffer.clear();
@@ -841,6 +832,15 @@
         mCallbackCondition.broadcast();
     }
 
+    // Wait without lock held
+    if (mCore->mConnectedApi == NATIVE_WINDOW_API_EGL) {
+        // Waiting here allows for two full buffers to be queued but not a
+        // third. In the event that frames take varying time, this makes a
+        // small trade-off in favor of latency rather than throughput.
+        mLastQueueBufferFence->waitForever("Throttling EGL Production");
+        mLastQueueBufferFence = fence;
+    }
+
     return NO_ERROR;
 }
 
diff --git a/opengl/libs/Android.mk b/opengl/libs/Android.mk
index 5e02ef1..3f9e332 100644
--- a/opengl/libs/Android.mk
+++ b/opengl/libs/Android.mk
@@ -101,11 +101,12 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= 		\
-	GLES2/gl2.cpp.arm 	\
+LOCAL_SRC_FILES:= \
+	GLES2/gl2.cpp   \
 #
 
 LOCAL_CLANG := false
+LOCAL_ARM_MODE := arm
 LOCAL_SHARED_LIBRARIES += libcutils libutils liblog libEGL
 LOCAL_MODULE:= libGLESv2
 
@@ -120,14 +121,32 @@
 # TODO: This is to work around b/20093774. Remove after root cause is fixed
 LOCAL_LDFLAGS_arm += -Wl,--hash-style,both
 
-# Symlink libGLESv3.so -> libGLESv2.so
-# Platform modules should link against libGLESv2.so (-lGLESv2), but NDK apps
-# will be linked against libGLESv3.so.
-# Note we defer the evaluation of the LOCAL_POST_INSTALL_CMD,
-# so $(LOCAL_INSTALLED_MODULE) will be expanded to correct value,
-# even for both 32-bit and 64-bit installed files in multilib build.
-LOCAL_POST_INSTALL_CMD = \
-    $(hide) ln -sf $(notdir $(LOCAL_INSTALLED_MODULE)) $(dir $(LOCAL_INSTALLED_MODULE))libGLESv3.so
+include $(BUILD_SHARED_LIBRARY)
+
+###############################################################################
+# Build the wrapper OpenGL ES 3.x library (this is just different name for v2)
+#
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+	GLES2/gl2.cpp   \
+#
+
+LOCAL_CLANG := false
+LOCAL_ARM_MODE := arm
+LOCAL_SHARED_LIBRARIES += libcutils libutils liblog libEGL
+LOCAL_MODULE:= libGLESv3
+LOCAL_SHARED_LIBRARIES += libdl
+# we need to access the private Bionic header <bionic_tls.h>
+LOCAL_C_INCLUDES += bionic/libc/private
+
+LOCAL_CFLAGS += -DLOG_TAG=\"libGLESv3\"
+LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+LOCAL_CFLAGS += -fvisibility=hidden
+
+# TODO: This is to work around b/20093774. Remove after root cause is fixed
+LOCAL_LDFLAGS_arm += -Wl,--hash-style,both
 
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/services/inputflinger/EventHub.cpp b/services/inputflinger/EventHub.cpp
index 5859606..2a53dec 100644
--- a/services/inputflinger/EventHub.cpp
+++ b/services/inputflinger/EventHub.cpp
@@ -1191,6 +1191,15 @@
         device->classes |= INPUT_DEVICE_CLASS_CURSOR;
     }
 
+    // See if this is a rotary encoder type device.
+    String8 deviceType = String8();
+    if (device->configuration &&
+        device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
+            if (!deviceType.compare(String8("rotaryEncoder"))) {
+                device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
+            }
+    }
+
     // See if this is a touch pad.
     // Is this a new modern multi-touch driver?
     if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
diff --git a/services/inputflinger/EventHub.h b/services/inputflinger/EventHub.h
index 0f94c77..6869253 100644
--- a/services/inputflinger/EventHub.h
+++ b/services/inputflinger/EventHub.h
@@ -137,6 +137,9 @@
     /* The input device is an external stylus (has data we want to fuse with touch data). */
     INPUT_DEVICE_CLASS_EXTERNAL_STYLUS = 0x00000800,
 
+    /* The input device has a rotary encoder */
+    INPUT_DEVICE_CLASS_ROTARY_ENCODER = 0x00001000,
+
     /* The input device is virtual (not a real device, not part of UI configuration). */
     INPUT_DEVICE_CLASS_VIRTUAL       = 0x40000000,
 
diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp
index e10a101..2aee8ad 100644
--- a/services/inputflinger/InputReader.cpp
+++ b/services/inputflinger/InputReader.cpp
@@ -450,6 +450,11 @@
         device->addMapper(new SwitchInputMapper(device));
     }
 
+    // Scroll wheel-like devices.
+    if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
+        device->addMapper(new RotaryEncoderInputMapper(device));
+    }
+
     // Vibrator-like devices.
     if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
         device->addMapper(new VibratorInputMapper(device));
@@ -2728,6 +2733,92 @@
     }
 }
 
+// --- RotaryEncoderInputMapper ---
+
+RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
+        InputMapper(device) {
+    mSource = AINPUT_SOURCE_ROTARY_ENCODER;
+}
+
+RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
+}
+
+uint32_t RotaryEncoderInputMapper::getSources() {
+    return mSource;
+}
+
+void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
+    InputMapper::populateDeviceInfo(info);
+
+    if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
+        info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
+    }
+}
+
+void RotaryEncoderInputMapper::dump(String8& dump) {
+    dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
+    dump.appendFormat(INDENT3 "HaveWheel: %s\n",
+            toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
+}
+
+void RotaryEncoderInputMapper::configure(nsecs_t when,
+        const InputReaderConfiguration* config, uint32_t changes) {
+    InputMapper::configure(when, config, changes);
+    if (!changes) {
+        mRotaryEncoderScrollAccumulator.configure(getDevice());
+    }
+}
+
+void RotaryEncoderInputMapper::reset(nsecs_t when) {
+    mRotaryEncoderScrollAccumulator.reset(getDevice());
+
+    InputMapper::reset(when);
+}
+
+void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
+    mRotaryEncoderScrollAccumulator.process(rawEvent);
+
+    if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
+        sync(rawEvent->when);
+    }
+}
+
+void RotaryEncoderInputMapper::sync(nsecs_t when) {
+    PointerCoords pointerCoords;
+    pointerCoords.clear();
+
+    PointerProperties pointerProperties;
+    pointerProperties.clear();
+    pointerProperties.id = 0;
+    pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
+
+    float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
+    bool scrolled = scroll != 0;
+
+    // This is not a pointer, so it's not associated with a display.
+    int32_t displayId = ADISPLAY_ID_NONE;
+
+    // Moving the rotary encoder should wake the device (if specified).
+    uint32_t policyFlags = 0;
+    if (scrolled && getDevice()->isExternal()) {
+        policyFlags |= POLICY_FLAG_WAKE;
+    }
+
+    // Send motion event.
+    if (scrolled) {
+        int32_t metaState = mContext->getGlobalMetaState();
+        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll);
+
+        NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
+                AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
+                AMOTION_EVENT_EDGE_FLAG_NONE,
+                displayId, 1, &pointerProperties, &pointerCoords,
+                0, 0, 0);
+        getListener()->notifyMotion(&scrollArgs);
+    }
+
+    mRotaryEncoderScrollAccumulator.finishSync();
+}
 
 // --- TouchInputMapper ---
 
diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h
index 3a5c76f..1de9d19 100644
--- a/services/inputflinger/InputReader.h
+++ b/services/inputflinger/InputReader.h
@@ -1231,6 +1231,26 @@
 };
 
 
+class RotaryEncoderInputMapper : public InputMapper {
+public:
+    RotaryEncoderInputMapper(InputDevice* device);
+    virtual ~RotaryEncoderInputMapper();
+
+    virtual uint32_t getSources();
+    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
+    virtual void dump(String8& dump);
+    virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
+    virtual void reset(nsecs_t when);
+    virtual void process(const RawEvent* rawEvent);
+
+private:
+    CursorScrollAccumulator mRotaryEncoderScrollAccumulator;
+
+    int32_t mSource;
+
+    void sync(nsecs_t when);
+};
+
 class TouchInputMapper : public InputMapper {
 public:
     TouchInputMapper(InputDevice* device);
diff --git a/services/surfaceflinger/DispSync.cpp b/services/surfaceflinger/DispSync.cpp
index 5ba387d..e0d7339 100644
--- a/services/surfaceflinger/DispSync.cpp
+++ b/services/surfaceflinger/DispSync.cpp
@@ -322,6 +322,7 @@
     mNumResyncSamples = 0;
     mFirstResyncSample = 0;
     mNumResyncSamplesSincePresent = 0;
+    mNumPresentWithoutResyncSamples = 0;
     resetErrorLocked();
 }
 
@@ -346,6 +347,15 @@
 
     updateErrorLocked();
 
+    // This is a workaround for b/25845510.
+    // If we have no resync samples after many presents, something is wrong with
+    // HW vsync. Tell SF to disable HW vsync now and re-enable it next time.
+    if (mNumResyncSamples == 0 &&
+        mNumPresentWithoutResyncSamples++ > MAX_PRESENT_WITHOUT_RESYNC_SAMPLES) {
+        mNumPresentWithoutResyncSamples = 0;
+        return false;
+    }
+
     return !mModelUpdated || mError > kErrorThreshold;
 }
 
@@ -354,6 +364,7 @@
 
     mModelUpdated = false;
     mNumResyncSamples = 0;
+    mNumPresentWithoutResyncSamples = 0;
 }
 
 bool DispSync::addResyncSample(nsecs_t timestamp) {
diff --git a/services/surfaceflinger/DispSync.h b/services/surfaceflinger/DispSync.h
index a8524b9..1ee0865 100644
--- a/services/surfaceflinger/DispSync.h
+++ b/services/surfaceflinger/DispSync.h
@@ -140,6 +140,7 @@
     enum { MIN_RESYNC_SAMPLES_FOR_UPDATE = 3 };
     enum { NUM_PRESENT_SAMPLES = 8 };
     enum { MAX_RESYNC_SAMPLES_WITHOUT_PRESENT = 4 };
+    enum { MAX_PRESENT_WITHOUT_RESYNC_SAMPLES = 8 };
 
     // mPeriod is the computed period of the modeled vsync events in
     // nanoseconds.
@@ -168,6 +169,7 @@
     size_t mFirstResyncSample;
     size_t mNumResyncSamples;
     int mNumResyncSamplesSincePresent;
+    int mNumPresentWithoutResyncSamples;
 
     // These member variables store information about the present fences used
     // to validate the currently computed model.
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 2b6e0ec..d484708 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -147,10 +147,6 @@
 }
 
 Layer::~Layer() {
-    sp<Client> c(mClientRef.promote());
-    if (c != 0) {
-        c->detachLayer(this);
-    }
     mFlinger->deleteTextureAsync(mTextureName);
     mFrameTracker.logAndResetStats(mName);
 }
@@ -252,6 +248,10 @@
 // the layer has been remove from the current state list (and just before
 // it's removed from the drawing state list)
 void Layer::onRemoved() {
+    sp<Client> c(mClientRef.promote());
+    if (c != 0) {
+        c->detachLayer(this);
+    }
     mSurfaceFlingerConsumer->abandon();
 }
 
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 093ca12..1e33847 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -2241,7 +2241,7 @@
         if (what & layer_state_t::eLayerChanged) {
             // NOTE: index needs to be calculated before we update the state
             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
-            if (layer->setLayer(s.z)) {
+            if (layer->setLayer(s.z) && idx >= 0) {
                 mCurrentState.layersSortedByZ.removeAt(idx);
                 mCurrentState.layersSortedByZ.add(layer);
                 // we need traversal (state changed)
@@ -2277,7 +2277,7 @@
         if (what & layer_state_t::eLayerStackChanged) {
             // NOTE: index needs to be calculated before we update the state
             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
-            if (layer->setLayerStack(s.layerStack)) {
+            if (layer->setLayerStack(s.layerStack) && idx >= 0) {
                 mCurrentState.layersSortedByZ.removeAt(idx);
                 mCurrentState.layersSortedByZ.add(layer);
                 // we need traversal (state changed)