Merge "logcatd: trampoline persist.logd.logpersistd to logd.logpersistd"
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 3cad427..31e60ca 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -58,3 +58,4 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/grep $(PRODUCT_OUT)/system/bin/toolbox)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/hw/gatekeeper.$(TARGET_DEVICE).so)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib64/hw/gatekeeper.$(TARGET_DEVICE).so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/vendor)
diff --git a/base/Android.bp b/base/Android.bp
new file mode 100644
index 0000000..7bf4c79
--- /dev/null
+++ b/base/Android.bp
@@ -0,0 +1,96 @@
+//
+// 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.
+//
+
+libbase_cppflags = [
+    "-Wall",
+    "-Wextra",
+    "-Werror",
+]
+
+cc_library {
+    name: "libbase",
+    clang: true,
+    host_supported: true,
+    srcs: [
+        "file.cpp",
+        "logging.cpp",
+        "parsenetaddress.cpp",
+        "stringprintf.cpp",
+        "strings.cpp",
+        "test_utils.cpp",
+    ],
+    local_include_dirs: ["include"],
+    cppflags: libbase_cppflags,
+    export_include_dirs: ["include"],
+    shared_libs: ["liblog"],
+    target: {
+        android: {
+            srcs: ["errors_unix.cpp"],
+            cppflags: ["-Wexit-time-destructors"],
+        },
+        darwin: {
+            srcs: ["errors_unix.cpp"],
+            cppflags: ["-Wexit-time-destructors"],
+        },
+        linux: {
+            srcs: ["errors_unix.cpp"],
+            cppflags: ["-Wexit-time-destructors"],
+        },
+        windows: {
+            srcs: [
+                "errors_windows.cpp",
+                "utf8.cpp",
+            ],
+            enabled: true,
+        },
+    },
+}
+
+// Tests
+// ------------------------------------------------------------------------------
+cc_test {
+    name: "libbase_test",
+    host_supported: true,
+    clang: true,
+    srcs: [
+        "errors_test.cpp",
+        "file_test.cpp",
+        "logging_test.cpp",
+        "parseint_test.cpp",
+        "parsenetaddress_test.cpp",
+        "stringprintf_test.cpp",
+        "strings_test.cpp",
+        "test_main.cpp",
+    ],
+    target: {
+        windows: {
+            srcs: ["utf8_test.cpp"],
+            enabled: true,
+        },
+    },
+    local_include_dirs: ["."],
+    cppflags: libbase_cppflags,
+    shared_libs: ["libbase"],
+    compile_multilib: "both",
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+}
diff --git a/base/Android.mk b/base/Android.mk
deleted file mode 100644
index 1693e74..0000000
--- a/base/Android.mk
+++ /dev/null
@@ -1,140 +0,0 @@
-#
-# 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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-libbase_src_files := \
-    file.cpp \
-    logging.cpp \
-    parsenetaddress.cpp \
-    stringprintf.cpp \
-    strings.cpp \
-    test_utils.cpp \
-
-libbase_linux_src_files := \
-    errors_unix.cpp \
-
-libbase_darwin_src_files := \
-    errors_unix.cpp \
-
-libbase_windows_src_files := \
-    errors_windows.cpp \
-    utf8.cpp \
-
-libbase_test_src_files := \
-    errors_test.cpp \
-    file_test.cpp \
-    logging_test.cpp \
-    parseint_test.cpp \
-    parsenetaddress_test.cpp \
-    stringprintf_test.cpp \
-    strings_test.cpp \
-    test_main.cpp \
-
-libbase_test_windows_src_files := \
-    utf8_test.cpp \
-
-libbase_cppflags := \
-    -Wall \
-    -Wextra \
-    -Werror \
-
-libbase_linux_cppflags := \
-    -Wexit-time-destructors \
-
-libbase_darwin_cppflags := \
-    -Wexit-time-destructors \
-
-# Device
-# ------------------------------------------------------------------------------
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase
-LOCAL_CLANG := true
-LOCAL_SRC_FILES := $(libbase_src_files) $(libbase_linux_src_files)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CPPFLAGS := $(libbase_cppflags) $(libbase_linux_cppflags)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_MULTILIB := both
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase
-LOCAL_CLANG := true
-LOCAL_WHOLE_STATIC_LIBRARIES := libbase
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_MULTILIB := both
-include $(BUILD_SHARED_LIBRARY)
-
-# Host
-# ------------------------------------------------------------------------------
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase
-LOCAL_SRC_FILES := $(libbase_src_files)
-LOCAL_SRC_FILES_darwin := $(libbase_darwin_src_files)
-LOCAL_SRC_FILES_linux := $(libbase_linux_src_files)
-LOCAL_SRC_FILES_windows := $(libbase_windows_src_files)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CPPFLAGS := $(libbase_cppflags)
-LOCAL_CPPFLAGS_darwin := $(libbase_darwin_cppflags)
-LOCAL_CPPFLAGS_linux := $(libbase_linux_cppflags)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase
-LOCAL_WHOLE_STATIC_LIBRARIES := libbase
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-# Tests
-# ------------------------------------------------------------------------------
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase_test
-LOCAL_CLANG := true
-LOCAL_SRC_FILES := $(libbase_test_src_files)
-LOCAL_SRC_FILES_darwin := $(libbase_test_darwin_src_files)
-LOCAL_SRC_FILES_linux := $(libbase_test_linux_src_files)
-LOCAL_SRC_FILES_windows := $(libbase_test_windows_src_files)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)
-LOCAL_CPPFLAGS := $(libbase_cppflags)
-LOCAL_SHARED_LIBRARIES := libbase
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase_test
-LOCAL_MODULE_HOST_OS := darwin linux windows
-LOCAL_SRC_FILES := $(libbase_test_src_files)
-LOCAL_SRC_FILES_darwin := $(libbase_test_darwin_src_files)
-LOCAL_SRC_FILES_linux := $(libbase_test_linux_src_files)
-LOCAL_SRC_FILES_windows := $(libbase_test_windows_src_files)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)
-LOCAL_CPPFLAGS := $(libbase_cppflags)
-LOCAL_SHARED_LIBRARIES := libbase
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/debuggerd/Android.soong.mk b/debuggerd/Android.mk
similarity index 100%
rename from debuggerd/Android.soong.mk
rename to debuggerd/Android.mk
diff --git a/include/utils/RefBase.h b/include/utils/RefBase.h
index 14d9cb1..c82e7d9 100644
--- a/include/utils/RefBase.h
+++ b/include/utils/RefBase.h
@@ -196,9 +196,10 @@
 
 private:
     friend class ReferenceMover;
-    inline static void renameRefs(size_t n, const ReferenceRenamer& renamer) { }
-    inline static void renameRefId(T* ref,
-            const void* old_id, const void* new_id) { }
+    inline static void renameRefs(size_t /*n*/,
+            const ReferenceRenamer& /*renamer*/) { }
+    inline static void renameRefId(T* /*ref*/,
+            const void* /*old_id*/ , const void* /*new_id*/) { }
 
 private:
     mutable std::atomic<int32_t> mCount;
diff --git a/init/service.cpp b/init/service.cpp
index 03c0064..c636677 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -52,6 +52,43 @@
 #define CRITICAL_CRASH_THRESHOLD    4       // if we crash >4 times ...
 #define CRITICAL_CRASH_WINDOW       (4*60)  // ... in 4 minutes, goto recovery
 
+static std::string ComputeContextFromExecutable(std::string& service_name,
+                                                const std::string& service_path) {
+    std::string computed_context;
+
+    char* raw_con = nullptr;
+    char* raw_filecon = nullptr;
+
+    if (getcon(&raw_con) == -1) {
+        LOG(ERROR) << "could not get context while starting '" << service_name << "'";
+        return "";
+    }
+    std::unique_ptr<char> mycon(raw_con);
+
+    if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
+        LOG(ERROR) << "could not get file context while starting '" << service_name << "'";
+        return "";
+    }
+    std::unique_ptr<char> filecon(raw_filecon);
+
+    char* new_con = nullptr;
+    int rc = security_compute_create(mycon.get(), filecon.get(),
+                                     string_to_security_class("process"), &new_con);
+    if (rc == 0) {
+        computed_context = new_con;
+        free(new_con);
+    }
+    if (rc == 0 && computed_context == mycon.get()) {
+        LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined";
+        return "";
+    }
+    if (rc < 0) {
+        LOG(ERROR) << "could not get context while starting '" << service_name << "'";
+        return "";
+    }
+    return computed_context;
+}
+
 static void SetUpPidNamespace(const std::string& service_name) {
     constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
 
@@ -92,6 +129,19 @@
     }
 }
 
+static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
+    std::vector<std::string> expanded_args;
+    expanded_args.resize(args.size());
+    strs->push_back(const_cast<char*>(args[0].c_str()));
+    for (std::size_t i = 1; i < args.size(); ++i) {
+        if (!expand_props(args[i], &expanded_args[i])) {
+            LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
+        }
+        strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
+    }
+    strs->push_back(nullptr);
+}
+
 SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
 }
 
@@ -154,6 +204,50 @@
     killProcessGroup(uid_, pid_, signal);
 }
 
+void Service::CreateSockets(const std::string& context) {
+    for (const auto& si : sockets_) {
+        int socket_type = ((si.type == "stream" ? SOCK_STREAM :
+                            (si.type == "dgram" ? SOCK_DGRAM :
+                             SOCK_SEQPACKET)));
+        const char* socketcon = !si.socketcon.empty() ? si.socketcon.c_str() : context.c_str();
+
+        int s = create_socket(si.name.c_str(), socket_type, si.perm, si.uid, si.gid, socketcon);
+        if (s >= 0) {
+            PublishSocket(si.name, s);
+        }
+    }
+}
+
+void Service::SetProcessAttributes() {
+    setpgid(0, getpid());
+
+    if (gid_) {
+        if (setgid(gid_) != 0) {
+            PLOG(FATAL) << "setgid failed";
+        }
+    }
+    if (!supp_gids_.empty()) {
+        if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
+            PLOG(FATAL) << "setgroups failed";
+        }
+    }
+    if (uid_) {
+        if (setuid(uid_) != 0) {
+            PLOG(FATAL) << "setuid failed";
+        }
+    }
+    if (!seclabel_.empty()) {
+        if (setexeccon(seclabel_.c_str()) < 0) {
+            PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "')";
+        }
+    }
+    if (priority_ != 0) {
+        if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
+            PLOG(FATAL) << "setpriority failed";
+        }
+    }
+}
+
 bool Service::Reap() {
     if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
         KillProcessGroup(SIGKILL);
@@ -441,50 +535,18 @@
     if (!seclabel_.empty()) {
         scon = seclabel_;
     } else {
-        char* mycon = nullptr;
-        char* fcon = nullptr;
-
-        LOG(INFO) << "computing context for service '" << args_[0] << "'";
-        int rc = getcon(&mycon);
-        if (rc < 0) {
-            LOG(ERROR) << "could not get context while starting '" << name_ << "'";
-            return false;
-        }
-
-        rc = getfilecon(args_[0].c_str(), &fcon);
-        if (rc < 0) {
-            LOG(ERROR) << "could not get file context while starting '" << name_ << "'";
-            free(mycon);
-            return false;
-        }
-
-        char* ret_scon = nullptr;
-        rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
-                                     &ret_scon);
-        if (rc == 0) {
-            scon = ret_scon;
-            free(ret_scon);
-        }
-        if (rc == 0 && scon == mycon) {
-            LOG(ERROR) << "Service " << name_ << " does not have a SELinux domain defined.";
-            free(mycon);
-            free(fcon);
-            return false;
-        }
-        free(mycon);
-        free(fcon);
-        if (rc < 0) {
-            LOG(ERROR) << "could not get context while starting '" << name_ << "'";
+        LOG(INFO) << "computing context for service '" << name_ << "'";
+        scon = ComputeContextFromExecutable(name_, args_[0]);
+        if (scon == "") {
             return false;
         }
     }
 
-    LOG(VERBOSE) << "Starting service '" << name_ << "'...";
+    LOG(VERBOSE) << "starting service '" << name_ << "'...";
 
     pid_t pid = -1;
     if (namespace_flags_) {
-        pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD,
-                    nullptr);
+        pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
     } else {
         pid = fork();
     }
@@ -502,19 +564,7 @@
             add_environment(ei.name.c_str(), ei.value.c_str());
         }
 
-        for (const auto& si : sockets_) {
-            int socket_type = ((si.type == "stream" ? SOCK_STREAM :
-                                (si.type == "dgram" ? SOCK_DGRAM :
-                                 SOCK_SEQPACKET)));
-            const char* socketcon =
-                !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
-
-            int s = create_socket(si.name.c_str(), socket_type, si.perm,
-                                  si.uid, si.gid, socketcon);
-            if (s >= 0) {
-                PublishSocket(si.name, s);
-            }
-        }
+        CreateSockets(scon);
 
         std::string pid_str = StringPrintf("%d", getpid());
         for (const auto& file : writepid_files_) {
@@ -525,7 +575,7 @@
 
         if (ioprio_class_ != IoSchedClass_NONE) {
             if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
-                PLOG(ERROR) << "Failed to set pid " << getpid()
+                PLOG(ERROR) << "failed to set pid " << getpid()
                             << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
             }
         }
@@ -537,53 +587,12 @@
             ZapStdio();
         }
 
-        setpgid(0, getpid());
+        // As requested, set our gid, supplemental gids, uid, context, and
+        // priority. Aborts on failure.
+        SetProcessAttributes();
 
-        // As requested, set our gid, supplemental gids, and uid.
-        if (gid_) {
-            if (setgid(gid_) != 0) {
-                PLOG(ERROR) << "setgid failed";
-                _exit(127);
-            }
-        }
-        if (!supp_gids_.empty()) {
-            if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
-                PLOG(ERROR) << "setgroups failed";
-                _exit(127);
-            }
-        }
-        if (uid_) {
-            if (setuid(uid_) != 0) {
-                PLOG(ERROR) << "setuid failed";
-                _exit(127);
-            }
-        }
-        if (!seclabel_.empty()) {
-            if (setexeccon(seclabel_.c_str()) < 0) {
-                PLOG(ERROR) << "cannot setexeccon('" << seclabel_ << "')";
-                _exit(127);
-            }
-        }
-        if (priority_ != 0) {
-            if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
-                PLOG(ERROR) << "setpriority failed";
-                _exit(127);
-            }
-        }
-
-        std::vector<std::string> expanded_args;
         std::vector<char*> strs;
-        expanded_args.resize(args_.size());
-        strs.push_back(const_cast<char*>(args_[0].c_str()));
-        for (std::size_t i = 1; i < args_.size(); ++i) {
-            if (!expand_props(args_[i], &expanded_args[i])) {
-                LOG(ERROR) << args_[0] << ": cannot expand '" << args_[i] << "'";
-                _exit(127);
-            }
-            strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
-        }
-        strs.push_back(nullptr);
-
+        ExpandArgs(args_, &strs);
         if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
             PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
         }
@@ -603,13 +612,14 @@
 
     errno = -createProcessGroup(uid_, pid_);
     if (errno != 0) {
-        PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '" << name_ << "'";
+        PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
+                    << name_ << "'";
     }
 
     if ((flags_ & SVC_EXEC) != 0) {
-        LOG(INFO) << android::base::StringPrintf("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...",
-                                                 pid_, uid_, gid_, supp_gids_.size(),
-                                                 !seclabel_.empty() ? seclabel_.c_str() : "default");
+        LOG(INFO) << android::base::StringPrintf(
+            "SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...", pid_, uid_, gid_,
+            supp_gids_.size(), !seclabel_.empty() ? seclabel_.c_str() : "default");
     }
 
     NotifyStateChange("running");
diff --git a/init/service.h b/init/service.h
index 38c5d64..aa73aaf 100644
--- a/init/service.h
+++ b/init/service.h
@@ -113,6 +113,8 @@
     void OpenConsole() const;
     void PublishSocket(const std::string& name, int fd) const;
     void KillProcessGroup(int signal);
+    void CreateSockets(const std::string& scon);
+    void SetProcessAttributes();
 
     bool ParseClass(const std::vector<std::string>& args, std::string* err);
     bool ParseConsole(const std::vector<std::string>& args, std::string* err);
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
new file mode 100644
index 0000000..93d997b
--- /dev/null
+++ b/libbacktrace/Android.bp
@@ -0,0 +1,121 @@
+//
+// Copyright (C) 2014 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.
+//
+
+cc_defaults {
+    name: "libbacktrace_common",
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+    conlyflags: ["-std=gnu99"],
+    cppflags: ["-std=gnu++11"],
+
+    clang_cflags: ["-Wno-inline-asm"],
+
+    // The latest clang (r230699) does not allow SP/PC to be declared in inline asm lists.
+    include_dirs: ["external/libunwind/include/tdep"],
+
+    // TODO: LLVM_DEVICE_BUILD_MK
+    // TODO: LLVM_HOST_BUILD_MK
+
+    target: {
+        host: {
+            // -fno-omit-frame-pointer should be set for host build. Because currently
+            // libunwind can't recognize .debug_frame using dwarf version 4, and it relies
+            // on stack frame pointer to do unwinding on x86.
+            // $(LLVM_HOST_BUILD_MK) overwrites -fno-omit-frame-pointer. so the below line
+            // must be after the include.
+            cflags: [
+                "-Wno-extern-c-compat",
+                "-fno-omit-frame-pointer",
+            ],
+        },
+
+        darwin: {
+            enabled: false,
+        },
+    },
+
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    }
+}
+
+libbacktrace_sources = [
+    "Backtrace.cpp",
+    "BacktraceCurrent.cpp",
+    "BacktracePtrace.cpp",
+    "thread_utils.c",
+    "ThreadEntry.cpp",
+    "UnwindCurrent.cpp",
+    "UnwindMap.cpp",
+    "UnwindPtrace.cpp",
+]
+
+cc_library {
+    name: "libbacktrace",
+    defaults: ["libbacktrace_common"],
+    host_supported: true,
+
+    srcs: [
+        "BacktraceMap.cpp",
+    ],
+
+    target: {
+        darwin: {
+            enabled: true,
+        },
+        linux: {
+            srcs: libbacktrace_sources,
+
+            shared_libs: [
+                "libbase",
+                "liblog",
+                "libunwind",
+            ],
+
+            static_libs: ["libcutils"],
+        },
+        android: {
+            srcs: libbacktrace_sources,
+
+            shared_libs: [
+                "libbase",
+                "liblog",
+                "libunwind",
+            ],
+
+            static_libs: ["libcutils"],
+        },
+    },
+}
+
+cc_library_shared {
+    name: "libbacktrace_test",
+    defaults: ["libbacktrace_common"],
+    host_supported: true,
+    strip: {
+        none: true,
+    },
+    cflags: ["-O0"],
+    srcs: ["backtrace_testlib.c"],
+}
diff --git a/libbacktrace/Android.mk b/libbacktrace/Android.mk
index 356ab8b..9bb113a 100644
--- a/libbacktrace/Android.mk
+++ b/libbacktrace/Android.mk
@@ -44,53 +44,6 @@
 include $(LLVM_ROOT_PATH)/llvm.mk
 
 #-------------------------------------------------------------------------
-# The libbacktrace library.
-#-------------------------------------------------------------------------
-libbacktrace_src_files := \
-	Backtrace.cpp \
-	BacktraceCurrent.cpp \
-	BacktraceMap.cpp \
-	BacktracePtrace.cpp \
-	thread_utils.c \
-	ThreadEntry.cpp \
-	UnwindCurrent.cpp \
-	UnwindMap.cpp \
-	UnwindPtrace.cpp \
-
-libbacktrace_shared_libraries := \
-	libbase \
-	liblog \
-	libunwind \
-
-libbacktrace_static_libraries := \
-	libcutils
-
-module := libbacktrace
-module_tag := optional
-build_type := target
-build_target := SHARED_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-libbacktrace_multilib := both
-include $(LOCAL_PATH)/Android.build.mk
-
-libbacktrace_shared_libraries :=
-
-libbacktrace_static_libraries := \
-	libbase \
-	liblog \
-	libunwind \
-	liblzma \
-
-module := libbacktrace
-build_type := target
-build_target := STATIC_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-libbacktrace_multilib := both
-include $(LOCAL_PATH)/Android.build.mk
-
-#-------------------------------------------------------------------------
 # The libbacktrace_offline shared library.
 #-------------------------------------------------------------------------
 libbacktrace_offline_src_files := \
@@ -135,26 +88,6 @@
 include $(LOCAL_PATH)/Android.build.mk
 
 #-------------------------------------------------------------------------
-# The libbacktrace_test library needed by backtrace_test.
-#-------------------------------------------------------------------------
-libbacktrace_test_cflags := \
-	-O0 \
-
-libbacktrace_test_src_files := \
-	backtrace_testlib.c \
-
-libbacktrace_test_strip_module := false
-
-module := libbacktrace_test
-module_tag := debug
-build_type := target
-build_target := SHARED_LIBRARY
-libbacktrace_test_multilib := both
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-include $(LOCAL_PATH)/Android.build.mk
-
-#-------------------------------------------------------------------------
 # The backtrace_test executable.
 #-------------------------------------------------------------------------
 backtrace_test_cflags := \
@@ -219,22 +152,3 @@
 include $(LOCAL_PATH)/Android.build.mk
 build_type := host
 include $(LOCAL_PATH)/Android.build.mk
-
-#----------------------------------------------------------------------------
-# Special truncated libbacktrace library for mac.
-#----------------------------------------------------------------------------
-ifeq ($(HOST_OS),darwin)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libbacktrace
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := \
-	BacktraceMap.cpp \
-
-LOCAL_MULTILIB := both
-
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-endif # HOST_OS-darwin
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
new file mode 100644
index 0000000..4f26034
--- /dev/null
+++ b/libcutils/Android.bp
@@ -0,0 +1,155 @@
+//
+// Copyright (C) 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.
+//
+
+// some files must not be compiled when building against Mingw
+// they correspond to features not used by our host development tools
+// which are also hard or even impossible to port to native Win32
+libcutils_nonwindows_sources = [
+    "fs.c",
+    "multiuser.c",
+    "socket_inaddr_any_server_unix.c",
+    "socket_local_client_unix.c",
+    "socket_local_server_unix.c",
+    "socket_loopback_client_unix.c",
+    "socket_loopback_server_unix.c",
+    "socket_network_client_unix.c",
+    "sockets_unix.cpp",
+    "str_parms.c",
+]
+
+cc_library {
+    name: "libcutils",
+    host_supported: true,
+    srcs: [
+        "config_utils.c",
+        "fs_config.c",
+        "canned_fs_config.c",
+        "hashmap.c",
+        "iosched_policy.c",
+        "load_file.c",
+        "native_handle.c",
+        "open_memstream.c",
+        "process_name.c",
+        "record_stream.c",
+        "sched_policy.c",
+        "sockets.cpp",
+        "strdup16to8.c",
+        "strdup8to16.c",
+        "strlcpy.c",
+        "threads.c",
+    ],
+
+    target: {
+        host: {
+            srcs: ["dlmalloc_stubs.c"],
+        },
+        not_windows: {
+            srcs: libcutils_nonwindows_sources + [
+                "ashmem-host.c",
+                "trace-host.c",
+            ],
+        },
+        windows: {
+            srcs: [
+                "socket_inaddr_any_server_windows.c",
+                "socket_network_client_windows.c",
+                "sockets_windows.cpp",
+            ],
+
+            enabled: true,
+            shared: {
+                enabled: false,
+            },
+        },
+
+        android: {
+            srcs: libcutils_nonwindows_sources + [
+                "android_reboot.c",
+                "ashmem-dev.c",
+                "debugger.c",
+                "klog.cpp",
+                "partition_utils.c",
+                "properties.c",
+                "qtaguid.c",
+                "trace-dev.c",
+                "uevent.c",
+            ],
+
+            // TODO: remove liblog as whole static library, once we don't have prebuilt that requires
+            // liblog symbols present in libcutils.
+            whole_static_libs: [
+                "liblog",
+            ],
+
+            static_libs: ["libdebuggerd_client"],
+            export_static_lib_headers: ["libdebuggerd_client"],
+
+            cflags: [
+                "-std=gnu90",
+            ],
+        },
+
+        android_arm: {
+            srcs: ["arch-arm/memset32.S"],
+        },
+        android_arm64: {
+            srcs: ["arch-arm64/android_memset.S"],
+        },
+
+        android_mips: {
+            srcs: ["arch-mips/android_memset.c"],
+        },
+        android_mips64: {
+            srcs: ["arch-mips/android_memset.c"],
+        },
+
+        android_x86: {
+            srcs: [
+                "arch-x86/android_memset16.S",
+                "arch-x86/android_memset32.S",
+            ],
+        },
+
+        android_x86_64: {
+            srcs: [
+                "arch-x86_64/android_memset16.S",
+                "arch-x86_64/android_memset32.S",
+            ],
+        },
+    },
+
+    shared_libs: ["liblog"],
+    product_variables: {
+        cpusets: {
+            cflags: ["-DUSE_CPUSETS"],
+        },
+        schedboost: {
+            cflags: ["-DUSE_SCHEDBOOST"],
+        },
+    },
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-Wextra",
+    ],
+
+    clang: true,
+    sanitize: {
+        misc_undefined: ["integer"],
+    },
+}
+
+subdirs = ["tests"]
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
deleted file mode 100644
index c830182..0000000
--- a/libcutils/Android.mk
+++ /dev/null
@@ -1,153 +0,0 @@
-#
-# Copyright (C) 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.
-#
-LOCAL_PATH := $(my-dir)
-include $(CLEAR_VARS)
-
-libcutils_common_sources := \
-        config_utils.c \
-        fs_config.c \
-        canned_fs_config.c \
-        hashmap.c \
-        iosched_policy.c \
-        load_file.c \
-        native_handle.c \
-        open_memstream.c \
-        process_name.c \
-        record_stream.c \
-        sched_policy.c \
-        sockets.cpp \
-        strdup16to8.c \
-        strdup8to16.c \
-        strlcpy.c \
-        threads.c \
-
-# some files must not be compiled when building against Mingw
-# they correspond to features not used by our host development tools
-# which are also hard or even impossible to port to native Win32
-libcutils_nonwindows_sources := \
-        fs.c \
-        multiuser.c \
-        socket_inaddr_any_server_unix.c \
-        socket_local_client_unix.c \
-        socket_local_server_unix.c \
-        socket_loopback_client_unix.c \
-        socket_loopback_server_unix.c \
-        socket_network_client_unix.c \
-        sockets_unix.cpp \
-        str_parms.c \
-
-libcutils_nonwindows_host_sources := \
-        ashmem-host.c \
-        trace-host.c \
-
-libcutils_windows_host_sources := \
-        socket_inaddr_any_server_windows.c \
-        socket_network_client_windows.c \
-        sockets_windows.cpp \
-
-# Shared and static library for host
-# Note: when linking this library on Windows, you must also link to Winsock2
-# using "LOCAL_LDLIBS_windows := -lws2_32".
-# ========================================================
-LOCAL_MODULE := libcutils
-LOCAL_SRC_FILES := $(libcutils_common_sources) dlmalloc_stubs.c
-LOCAL_SRC_FILES_darwin := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
-LOCAL_SRC_FILES_linux := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
-LOCAL_SRC_FILES_windows := $(libcutils_windows_host_sources)
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_CFLAGS := -Werror -Wall -Wextra
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils
-LOCAL_SRC_FILES := $(libcutils_common_sources) dlmalloc_stubs.c
-LOCAL_SRC_FILES_darwin := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
-LOCAL_SRC_FILES_linux := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_CFLAGS := -Werror -Wall -Wextra
-LOCAL_MULTILIB := both
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-
-
-# Shared and static library for target
-# ========================================================
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils
-LOCAL_SRC_FILES := $(libcutils_common_sources) \
-        $(libcutils_nonwindows_sources) \
-        android_reboot.c \
-        ashmem-dev.c \
-        debugger.c \
-        klog.cpp \
-        partition_utils.c \
-        properties.c \
-        qtaguid.c \
-        trace-dev.c \
-        uevent.c \
-
-LOCAL_SRC_FILES_arm += arch-arm/memset32.S
-LOCAL_SRC_FILES_arm64 += arch-arm64/android_memset.S
-
-LOCAL_SRC_FILES_mips += arch-mips/android_memset.c
-LOCAL_SRC_FILES_mips64 += arch-mips/android_memset.c
-
-LOCAL_SRC_FILES_x86 += \
-        arch-x86/android_memset16.S \
-        arch-x86/android_memset32.S \
-
-LOCAL_SRC_FILES_x86_64 += \
-        arch-x86_64/android_memset16.S \
-        arch-x86_64/android_memset32.S \
-
-LOCAL_C_INCLUDES := $(libcutils_c_includes)
-LOCAL_EXPORT_STATIC_LIBRARY_HEADERS := libdebuggerd_client
-LOCAL_STATIC_LIBRARIES := liblog libdebuggerd_client
-ifneq ($(ENABLE_CPUSETS),)
-LOCAL_CFLAGS += -DUSE_CPUSETS
-endif
-ifneq ($(ENABLE_SCHEDBOOST),)
-LOCAL_CFLAGS += -DUSE_SCHEDBOOST
-endif
-LOCAL_CFLAGS += -Werror -Wall -Wextra -std=gnu90
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils
-# TODO: remove liblog as whole static library, once we don't have prebuilt that requires
-# liblog symbols present in libcutils.
-LOCAL_WHOLE_STATIC_LIBRARIES := libcutils liblog
-LOCAL_EXPORT_STATIC_LIBRARY_HEADERS := libdebuggerd_client
-LOCAL_STATIC_LIBRARIES := libdebuggerd_client
-LOCAL_SHARED_LIBRARIES := liblog
-ifneq ($(ENABLE_CPUSETS),)
-LOCAL_CFLAGS += -DUSE_CPUSETS
-endif
-ifneq ($(ENABLE_SCHEDBOOST),)
-LOCAL_CFLAGS += -DUSE_SCHEDBOOST
-endif
-LOCAL_CFLAGS += -Werror -Wall -Wextra
-LOCAL_C_INCLUDES := $(libcutils_c_includes)
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-include $(BUILD_SHARED_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/libcutils/tests/Android.bp b/libcutils/tests/Android.bp
new file mode 100644
index 0000000..530c747
--- /dev/null
+++ b/libcutils/tests/Android.bp
@@ -0,0 +1,72 @@
+// Copyright (C) 2014 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.
+
+cc_defaults {
+    name: "libcutils_test_default",
+    srcs: ["sockets_test.cpp"],
+
+    target: {
+        android: {
+            srcs: [
+                "MemsetTest.cpp",
+                "PropertiesTest.cpp",
+                "trace-dev_test.cpp",
+            ],
+        },
+
+        not_windows: {
+            srcs: ["test_str_parms.cpp"],
+        },
+    },
+
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+}
+
+test_libraries = [
+    "libcutils",
+    "liblog",
+    "libbase",
+]
+
+cc_test {
+    name: "libcutils_test",
+    defaults: ["libcutils_test_default"],
+    host_supported: true,
+    shared_libs: test_libraries,
+}
+
+cc_test {
+    name: "libcutils_test_static",
+    defaults: ["libcutils_test_default"],
+    static_libs: ["libc"] + test_libraries,
+    stl: "libc++_static",
+
+    target: {
+        android: {
+            static_executable: true,
+        },
+        windows: {
+            host_ldlibs: ["-lws2_32"],
+
+            enabled: true,
+        },
+    },
+}
diff --git a/libcutils/tests/Android.mk b/libcutils/tests/Android.mk
deleted file mode 100644
index 52cf5f4..0000000
--- a/libcutils/tests/Android.mk
+++ /dev/null
@@ -1,81 +0,0 @@
-# Copyright (C) 2014 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.
-
-LOCAL_PATH := $(call my-dir)
-
-test_src_files := \
-    sockets_test.cpp \
-
-test_src_files_nonwindows := \
-    test_str_parms.cpp \
-
-test_target_only_src_files := \
-    MemsetTest.cpp \
-    PropertiesTest.cpp \
-    trace-dev_test.cpp \
-
-test_libraries := libcutils liblog libbase
-
-
-#
-# Target.
-#
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test
-LOCAL_SRC_FILES := $(test_src_files) $(test_target_only_src_files)
-LOCAL_SHARED_LIBRARIES := $(test_libraries)
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test_static
-LOCAL_FORCE_STATIC_EXECUTABLE := true
-LOCAL_SRC_FILES := $(test_src_files) $(test_target_only_src_files)
-LOCAL_STATIC_LIBRARIES := libc $(test_libraries)
-LOCAL_CXX_STL := libc++_static
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_NATIVE_TEST)
-
-
-#
-# Host.
-#
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test
-LOCAL_SRC_FILES := $(test_src_files) $(test_src_files_nonwindows)
-LOCAL_SHARED_LIBRARIES := $(test_libraries)
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_HOST_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test_static
-LOCAL_SRC_FILES := $(test_src_files)
-LOCAL_SRC_FILES_darwin := $(test_src_files_nonwindows)
-LOCAL_SRC_FILES_linux := $(test_src_files_nonwindows)
-LOCAL_STATIC_LIBRARIES := $(test_libraries)
-LOCAL_LDLIBS_windows := -lws2_32
-LOCAL_CXX_STL := libc++_static
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/liblog/Android.soong.mk b/liblog/Android.mk
similarity index 100%
rename from liblog/Android.soong.mk
rename to liblog/Android.mk
diff --git a/libutils/Android.bp b/libutils/Android.bp
new file mode 100644
index 0000000..1038db4
--- /dev/null
+++ b/libutils/Android.bp
@@ -0,0 +1,119 @@
+// Copyright (C) 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.
+
+cc_library {
+    name: "libutils",
+    host_supported: true,
+
+    srcs: [
+        "CallStack.cpp",
+        "FileMap.cpp",
+        "JenkinsHash.cpp",
+        "LinearTransform.cpp",
+        "Log.cpp",
+        "NativeHandle.cpp",
+        "Printer.cpp",
+        "PropertyMap.cpp",
+        "RefBase.cpp",
+        "SharedBuffer.cpp",
+        "Static.cpp",
+        "StopWatch.cpp",
+        "String8.cpp",
+        "String16.cpp",
+        "SystemClock.cpp",
+        "Threads.cpp",
+        "Timers.cpp",
+        "Tokenizer.cpp",
+        "Unicode.cpp",
+        "VectorImpl.cpp",
+        "misc.cpp",
+    ],
+
+    cflags: ["-Werror"],
+    include_dirs: ["external/safe-iop/include"],
+
+    arch: {
+        mips: {
+            cflags: ["-DALIGN_DOUBLE"],
+        },
+    },
+
+    target: {
+        android: {
+            srcs: [
+                "BlobCache.cpp",
+                "Looper.cpp",
+                "ProcessCallStack.cpp",
+                "Trace.cpp",
+            ],
+
+            cflags: ["-fvisibility=protected"],
+
+            shared_libs: [
+                "libbacktrace",
+                "libcutils",
+                "libdl",
+                "liblog",
+            ],
+
+            sanitize: {
+                misc_undefined: ["integer"],
+            },
+        },
+
+        host: {
+            cflags: ["-DLIBUTILS_NATIVE=1"],
+
+            shared: {
+                enabled: false,
+            },
+        },
+
+        linux: {
+            srcs: [
+                "Looper.cpp",
+                "ProcessCallStack.cpp",
+            ],
+        },
+
+        darwin: {
+            cflags: ["-Wno-unused-parameter"],
+        },
+
+        // Under MinGW, ctype.h doesn't need multi-byte support
+        windows: {
+            cflags: ["-DMB_CUR_MAX=1"],
+
+            enabled: true,
+        },
+    },
+
+    clang: true,
+}
+
+// Include subdirectory makefiles
+// ============================================================
+
+cc_test {
+    name: "SharedBufferTest",
+    host_supported: true,
+    static_libs: [
+        "libutils",
+        "libcutils",
+    ],
+    shared_libs: ["liblog"],
+    srcs: ["SharedBufferTest.cpp"],
+}
+
+subdirs = ["tests"]
diff --git a/libutils/Android.mk b/libutils/Android.mk
deleted file mode 100644
index 6f88a6d..0000000
--- a/libutils/Android.mk
+++ /dev/null
@@ -1,127 +0,0 @@
-# Copyright (C) 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.
-
-LOCAL_PATH:= $(call my-dir)
-
-commonSources:= \
-	CallStack.cpp \
-	FileMap.cpp \
-	JenkinsHash.cpp \
-	LinearTransform.cpp \
-	Log.cpp \
-	NativeHandle.cpp \
-	Printer.cpp \
-	PropertyMap.cpp \
-	RefBase.cpp \
-	SharedBuffer.cpp \
-	Static.cpp \
-	StopWatch.cpp \
-	String8.cpp \
-	String16.cpp \
-	SystemClock.cpp \
-	Threads.cpp \
-	Timers.cpp \
-	Tokenizer.cpp \
-	Unicode.cpp \
-	VectorImpl.cpp \
-	misc.cpp \
-
-host_commonCflags := -DLIBUTILS_NATIVE=1 $(TOOL_CFLAGS) -Werror
-
-# For the host
-# =====================================================
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= $(commonSources)
-LOCAL_SRC_FILES_linux := Looper.cpp ProcessCallStack.cpp
-LOCAL_CFLAGS_darwin := -Wno-unused-parameter
-LOCAL_MODULE:= libutils
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_CFLAGS += $(host_commonCflags)
-# Under MinGW, ctype.h doesn't need multi-byte support
-LOCAL_CFLAGS_windows := -DMB_CUR_MAX=1
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-LOCAL_C_INCLUDES += external/safe-iop/include
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-
-# For the device, static
-# =====================================================
-include $(CLEAR_VARS)
-
-
-# we have the common sources, plus some device-specific stuff
-LOCAL_SRC_FILES:= \
-	$(commonSources) \
-	BlobCache.cpp \
-	Looper.cpp \
-	ProcessCallStack.cpp \
-	Trace.cpp
-
-ifeq ($(TARGET_ARCH),mips)
-LOCAL_CFLAGS += -DALIGN_DOUBLE
-endif
-LOCAL_CFLAGS += -Werror -fvisibility=protected
-
-LOCAL_STATIC_LIBRARIES := \
-	libcutils \
-	libc
-
-LOCAL_SHARED_LIBRARIES := \
-        libbacktrace \
-        liblog \
-        libdl
-
-LOCAL_MODULE := libutils
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-LOCAL_C_INCLUDES += external/safe-iop/include
-include $(BUILD_STATIC_LIBRARY)
-
-# For the device, shared
-# =====================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE:= libutils
-LOCAL_WHOLE_STATIC_LIBRARIES := libutils
-LOCAL_SHARED_LIBRARIES := \
-        libbacktrace \
-        libcutils \
-        libdl \
-        liblog
-LOCAL_CFLAGS := -Werror
-LOCAL_C_INCLUDES += external/safe-iop/include
-
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-include $(BUILD_SHARED_LIBRARY)
-
-# Include subdirectory makefiles
-# ============================================================
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := SharedBufferTest
-LOCAL_STATIC_LIBRARIES := libutils libcutils
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_SRC_FILES := SharedBufferTest.cpp
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := SharedBufferTest
-LOCAL_STATIC_LIBRARIES := libutils libcutils
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_SRC_FILES := SharedBufferTest.cpp
-include $(BUILD_HOST_NATIVE_TEST)
-
-# Build the tests in the tests/ subdirectory.
-include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/libutils/tests/Android.bp b/libutils/tests/Android.bp
new file mode 100644
index 0000000..9e2fd5f
--- /dev/null
+++ b/libutils/tests/Android.bp
@@ -0,0 +1,49 @@
+//
+// Copyright (C) 2014 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.
+//
+
+// Build the unit tests.
+
+cc_test {
+    name: "libutils_tests",
+
+    srcs: [
+        "BlobCache_test.cpp",
+        "BitSet_test.cpp",
+        "Looper_test.cpp",
+        "LruCache_test.cpp",
+        "String8_test.cpp",
+        "StrongPointer_test.cpp",
+        "SystemClock_test.cpp",
+        "Unicode_test.cpp",
+        "Vector_test.cpp",
+    ],
+
+    shared_libs: [
+        "libz",
+        "liblog",
+        "libcutils",
+        "libutils",
+    ],
+}
+
+cc_test_host {
+    name: "libutils_tests_host",
+    srcs: ["Vector_test.cpp"],
+    static_libs: [
+        "libutils",
+        "liblog",
+    ],
+}
diff --git a/libutils/tests/Android.mk b/libutils/tests/Android.mk
deleted file mode 100644
index 21fe19c..0000000
--- a/libutils/tests/Android.mk
+++ /dev/null
@@ -1,49 +0,0 @@
-#
-# Copyright (C) 2014 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.
-#
-
-# Build the unit tests.
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libutils_tests
-
-LOCAL_SRC_FILES := \
-    BlobCache_test.cpp \
-    BitSet_test.cpp \
-    Looper_test.cpp \
-    LruCache_test.cpp \
-    String8_test.cpp \
-    StrongPointer_test.cpp \
-    SystemClock_test.cpp \
-    Unicode_test.cpp \
-    Vector_test.cpp \
-
-LOCAL_SHARED_LIBRARIES := \
-    libz \
-    liblog \
-    libcutils \
-    libutils \
-
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libutils_tests_host
-LOCAL_SRC_FILES := Vector_test.cpp
-LOCAL_STATIC_LIBRARIES := libutils liblog
-
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libziparchive/Android.bp b/libziparchive/Android.bp
new file mode 100644
index 0000000..5ed0fe8
--- /dev/null
+++ b/libziparchive/Android.bp
@@ -0,0 +1,111 @@
+//
+// Copyright (C) 2013 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.
+
+cc_defaults {
+    name: "libziparchive_flags",
+    cflags: [
+        // ZLIB_CONST turns on const for input buffers, which is pretty standard.
+        "-DZLIB_CONST",
+        "-Werror",
+        "-Wall",
+    ],
+    cppflags: [
+        "-Wold-style-cast",
+        // Incorrectly warns when C++11 empty brace {} initializer is used.
+        // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61489
+        "-Wno-missing-field-initializers",
+    ],
+}
+
+cc_defaults {
+    name: "libziparchive_defaults",
+    srcs: [
+        "zip_archive.cc",
+        "zip_archive_stream_entry.cc",
+        "zip_writer.cc",
+    ],
+
+    target: {
+        windows: {
+            cflags: ["-mno-ms-bitfields"],
+
+            enabled: true,
+        },
+    },
+
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+}
+
+
+cc_library {
+    name: "libziparchive",
+    host_supported: true,
+    defaults: ["libziparchive_defaults", "libziparchive_flags"],
+    static_libs: ["libutils"],
+    shared_libs: ["liblog", "libbase"],
+    target: {
+        android: {
+            static_libs: ["libz"],
+        },
+        host: {
+            shared_libs: ["libz-host"],
+        },
+    },
+}
+
+// Also provide libziparchive-host until everything is switched over to using libziparchive
+cc_library {
+    name: "libziparchive-host",
+    host_supported: true,
+    device_supported: false,
+    defaults: ["libziparchive_defaults", "libziparchive_flags"],
+    shared_libs: ["libz-host"],
+    static_libs: ["libutils"],
+}
+
+// Tests.
+cc_test {
+    name: "ziparchive-tests",
+    host_supported: true,
+    defaults: ["libziparchive_flags"],
+
+    srcs: [
+        "entry_name_utils_test.cc",
+        "zip_archive_test.cc",
+        "zip_writer_test.cc",
+    ],
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libziparchive",
+        "libz",
+        "libutils",
+    ],
+
+    target: {
+        host: {
+            cppflags: ["-Wno-unnamed-type-template-args"],
+        },
+        windows: {
+            enabled: true,
+        },
+    },
+}
diff --git a/libziparchive/Android.mk b/libziparchive/Android.mk
deleted file mode 100644
index 3cd8b87..0000000
--- a/libziparchive/Android.mk
+++ /dev/null
@@ -1,106 +0,0 @@
-#
-# Copyright (C) 2013 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.
-
-LOCAL_PATH := $(call my-dir)
-
-libziparchive_source_files := \
-    zip_archive.cc \
-    zip_archive_stream_entry.cc \
-    zip_writer.cc \
-
-libziparchive_test_files := \
-    entry_name_utils_test.cc \
-    zip_archive_test.cc \
-    zip_writer_test.cc \
-
-# ZLIB_CONST turns on const for input buffers, which is pretty standard.
-libziparchive_common_c_flags := \
-    -DZLIB_CONST \
-    -Werror \
-    -Wall \
-
-# Incorrectly warns when C++11 empty brace {} initializer is used.
-# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61489
-libziparchive_common_cpp_flags := \
-    -Wold-style-cast \
-    -Wno-missing-field-initializers \
-
-include $(CLEAR_VARS)
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_SRC_FILES := $(libziparchive_source_files)
-LOCAL_STATIC_LIBRARIES := libz
-LOCAL_SHARED_LIBRARIES := libutils libbase
-LOCAL_MODULE:= libziparchive
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CPPFLAGS := $(libziparchive_common_cpp_flags)
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_SRC_FILES := $(libziparchive_source_files)
-LOCAL_STATIC_LIBRARIES := libz libutils libbase
-LOCAL_MODULE:= libziparchive-host
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CFLAGS_windows := -mno-ms-bitfields
-LOCAL_CPPFLAGS := $(libziparchive_common_cpp_flags)
-
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_SRC_FILES := $(libziparchive_source_files)
-LOCAL_STATIC_LIBRARIES := libutils
-LOCAL_SHARED_LIBRARIES := libz-host liblog libbase
-LOCAL_MODULE:= libziparchive-host
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CPPFLAGS := $(libziparchive_common_cpp_flags)
-LOCAL_MULTILIB := both
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-# Tests.
-include $(CLEAR_VARS)
-LOCAL_MODULE := ziparchive-tests
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CPPFLAGS := $(libziparchive_common_cpp_flags)
-LOCAL_SRC_FILES := $(libziparchive_test_files)
-LOCAL_SHARED_LIBRARIES := \
-    libbase \
-    liblog \
-
-LOCAL_STATIC_LIBRARIES := \
-    libziparchive \
-    libz \
-    libutils \
-
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := ziparchive-tests-host
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CPPFLAGS := -Wno-unnamed-type-template-args $(libziparchive_common_cpp_flags)
-LOCAL_SRC_FILES := $(libziparchive_test_files)
-LOCAL_STATIC_LIBRARIES := \
-    libziparchive-host \
-    libz \
-    libbase \
-    libutils \
-    liblog \
-
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index d53af2f..e060a2c 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -58,7 +58,7 @@
     ln -sf /system/etc $(TARGET_ROOT_OUT)/etc; \
     ln -sf /sys/kernel/debug $(TARGET_ROOT_OUT)/d; \
     ln -sf /storage/self/primary $(TARGET_ROOT_OUT)/sdcard
-ifdef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE
+ifdef BOARD_USES_VENDORIMAGE
   LOCAL_POST_INSTALL_CMD += ; mkdir -p $(TARGET_ROOT_OUT)/vendor
 else
   LOCAL_POST_INSTALL_CMD += ; ln -sf /system/vendor $(TARGET_ROOT_OUT)/vendor
diff --git a/rootdir/init.rc b/rootdir/init.rc
index a359713..b96ff4c 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -112,7 +112,6 @@
     write /proc/sys/kernel/sched_tunable_scaling 0
     write /proc/sys/kernel/sched_latency_ns 10000000
     write /proc/sys/kernel/sched_wakeup_granularity_ns 2000000
-    write /proc/sys/kernel/sched_compat_yield 1
     write /proc/sys/kernel/sched_child_runs_first 0
 
     write /proc/sys/kernel/randomize_va_space 2
diff --git a/run-as/Android.mk b/run-as/Android.mk
index 3774acc..2e305d7 100644
--- a/run-as/Android.mk
+++ b/run-as/Android.mk
@@ -1,12 +1,8 @@
 LOCAL_PATH:= $(call my-dir)
+
 include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := run-as.c package.c
-
-LOCAL_SHARED_LIBRARIES := libselinux
-
-LOCAL_MODULE := run-as
-
 LOCAL_CFLAGS := -Werror
-
+LOCAL_MODULE := run-as
+LOCAL_SHARED_LIBRARIES := libselinux libpackagelistparser
+LOCAL_SRC_FILES := run-as.cpp
 include $(BUILD_EXECUTABLE)
diff --git a/run-as/package.c b/run-as/package.c
deleted file mode 100644
index aea89e5..0000000
--- a/run-as/package.c
+++ /dev/null
@@ -1,556 +0,0 @@
-/*
-**
-** Copyright 2010, 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 <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <private/android_filesystem_config.h>
-#include "package.h"
-
-/*
- *  WARNING WARNING WARNING WARNING
- *
- *  The following code runs as root on production devices, before
- *  the run-as command has dropped the uid/gid. Hence be very
- *  conservative and keep in mind the following:
- *
- *  - Performance does not matter here, clarity and safety of the code
- *    does however. Documentation is a must.
- *
- *  - Avoid calling C library functions with complex implementations
- *    like malloc() and printf(). You want to depend on simple system
- *    calls instead, which behaviour is not going to be altered in
- *    unpredictible ways by environment variables or system properties.
- *
- *  - Do not trust user input and/or the filesystem whenever possible.
- *
- */
-
-/* The file containing the list of installed packages on the system */
-#define PACKAGES_LIST_FILE  "/data/system/packages.list"
-
-/* Copy 'srclen' string bytes from 'src' into buffer 'dst' of size 'dstlen'
- * This function always zero-terminate the destination buffer unless
- * 'dstlen' is 0, even in case of overflow.
- * Returns a pointer into the src string, leaving off where the copy
- * has stopped. The copy will stop when dstlen, srclen or a null
- * character on src has been reached.
- */
-static const char*
-string_copy(char* dst, size_t dstlen, const char* src, size_t srclen)
-{
-    const char* srcend = src + srclen;
-    const char* dstend = dst + dstlen;
-
-    if (dstlen == 0)
-        return src;
-
-    dstend--; /* make room for terminating zero */
-
-    while (dst < dstend && src < srcend && *src != '\0')
-        *dst++ = *src++;
-
-    *dst = '\0'; /* zero-terminate result */
-    return src;
-}
-
-/* Open 'filename' and map it into our address-space.
- * Returns buffer address, or NULL on error
- * On exit, *filesize will be set to the file's size, or 0 on error
- */
-static void*
-map_file(const char* filename, size_t* filesize)
-{
-    int  fd, ret, old_errno;
-    struct stat  st;
-    size_t  length = 0;
-    void*   address = NULL;
-    gid_t   oldegid;
-
-    *filesize = 0;
-
-    /*
-     * Temporarily switch effective GID to allow us to read
-     * the packages file
-     */
-
-    oldegid = getegid();
-    if (setegid(AID_PACKAGE_INFO) < 0) {
-        return NULL;
-    }
-
-    /* open the file for reading */
-    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
-    if (fd < 0) {
-        return NULL;
-    }
-
-    /* restore back to our old egid */
-    if (setegid(oldegid) < 0) {
-        goto EXIT;
-    }
-
-    /* get its size */
-    ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
-    if (ret < 0)
-        goto EXIT;
-
-    /* Ensure that the file is owned by the system user */
-    if ((st.st_uid != AID_SYSTEM) || (st.st_gid != AID_PACKAGE_INFO)) {
-        goto EXIT;
-    }
-
-    /* Ensure that the file has sane permissions */
-    if ((st.st_mode & S_IWOTH) != 0) {
-        goto EXIT;
-    }
-
-    /* Ensure that the size is not ridiculously large */
-    length = (size_t)st.st_size;
-    if ((off_t)length != st.st_size) {
-        errno = ENOMEM;
-        goto EXIT;
-    }
-
-    /* Memory-map the file now */
-    do {
-        address = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
-    } while (address == MAP_FAILED && errno == EINTR);
-    if (address == MAP_FAILED) {
-        address = NULL;
-        goto EXIT;
-    }
-
-    /* We're good, return size */
-    *filesize = length;
-
-EXIT:
-    /* close the file, preserve old errno for better diagnostics */
-    old_errno = errno;
-    close(fd);
-    errno = old_errno;
-
-    return address;
-}
-
-/* unmap the file, but preserve errno */
-static void
-unmap_file(void*  address, size_t  size)
-{
-    int old_errno = errno;
-    TEMP_FAILURE_RETRY(munmap(address, size));
-    errno = old_errno;
-}
-
-/* Check that a given directory:
- * - exists
- * - is owned by a given uid/gid
- * - is a real directory, not a symlink
- * - isn't readable or writable by others
- *
- * Return 0 on success, or -1 on error.
- * errno is set to EINVAL in case of failed check.
- */
-static int
-check_directory_ownership(const char* path, uid_t uid)
-{
-    int ret;
-    struct stat st;
-
-    do {
-        ret = lstat(path, &st);
-    } while (ret < 0 && errno == EINTR);
-
-    if (ret < 0)
-        return -1;
-
-    /* must be a real directory, not a symlink */
-    if (!S_ISDIR(st.st_mode))
-        goto BAD;
-
-    /* must be owned by specific uid/gid */
-    if (st.st_uid != uid || st.st_gid != uid)
-        goto BAD;
-
-    /* must not be readable or writable by others */
-    if ((st.st_mode & (S_IROTH|S_IWOTH)) != 0)
-        goto BAD;
-
-    /* everything ok */
-    return 0;
-
-BAD:
-    errno = EINVAL;
-    return -1;
-}
-
-/* This function is used to check the data directory path for safety.
- * We check that every sub-directory is owned by the 'system' user
- * and exists and is not a symlink. We also check that the full directory
- * path is properly owned by the user ID.
- *
- * Return 0 on success, -1 on error.
- */
-int
-check_data_path(const char* dataPath, uid_t  uid)
-{
-    int  nn;
-
-    /* the path should be absolute */
-    if (dataPath[0] != '/') {
-        errno = EINVAL;
-        return -1;
-    }
-
-    /* look for all sub-paths, we do that by finding
-     * directory separators in the input path and
-     * checking each sub-path independently
-     */
-    for (nn = 1; dataPath[nn] != '\0'; nn++)
-    {
-        char subpath[PATH_MAX];
-
-        /* skip non-separator characters */
-        if (dataPath[nn] != '/')
-            continue;
-
-        /* handle trailing separator case */
-        if (dataPath[nn+1] == '\0') {
-            break;
-        }
-
-        /* found a separator, check that dataPath is not too long. */
-        if (nn >= (int)(sizeof subpath)) {
-            errno = EINVAL;
-            return -1;
-        }
-
-        /* reject any '..' subpath */
-        if (nn >= 3               &&
-            dataPath[nn-3] == '/' &&
-            dataPath[nn-2] == '.' &&
-            dataPath[nn-1] == '.') {
-            errno = EINVAL;
-            return -1;
-        }
-
-        /* copy to 'subpath', then check ownership */
-        memcpy(subpath, dataPath, nn);
-        subpath[nn] = '\0';
-
-        if (check_directory_ownership(subpath, AID_SYSTEM) < 0)
-            return -1;
-    }
-
-    /* All sub-paths were checked, now verify that the full data
-     * directory is owned by the application uid
-     */
-    if (check_directory_ownership(dataPath, uid) < 0)
-        return -1;
-
-    /* all clear */
-    return 0;
-}
-
-/* Return TRUE iff a character is a space or tab */
-static inline int
-is_space(char c)
-{
-    return (c == ' ' || c == '\t');
-}
-
-/* Skip any space or tab character from 'p' until 'end' is reached.
- * Return new position.
- */
-static const char*
-skip_spaces(const char*  p, const char*  end)
-{
-    while (p < end && is_space(*p))
-        p++;
-
-    return p;
-}
-
-/* Skip any non-space and non-tab character from 'p' until 'end'.
- * Return new position.
- */
-static const char*
-skip_non_spaces(const char* p, const char* end)
-{
-    while (p < end && !is_space(*p))
-        p++;
-
-    return p;
-}
-
-/* Find the first occurence of 'ch' between 'p' and 'end'
- * Return its position, or 'end' if none is found.
- */
-static const char*
-find_first(const char* p, const char* end, char ch)
-{
-    while (p < end && *p != ch)
-        p++;
-
-    return p;
-}
-
-/* Check that the non-space string starting at 'p' and eventually
- * ending at 'end' equals 'name'. Return new position (after name)
- * on success, or NULL on failure.
- *
- * This function fails is 'name' is NULL, empty or contains any space.
- */
-static const char*
-compare_name(const char* p, const char* end, const char* name)
-{
-    /* 'name' must not be NULL or empty */
-    if (name == NULL || name[0] == '\0' || p == end)
-        return NULL;
-
-    /* compare characters to those in 'name', excluding spaces */
-    while (*name) {
-        /* note, we don't check for *p == '\0' since
-         * it will be caught in the next conditional.
-         */
-        if (p >= end || is_space(*p))
-            goto BAD;
-
-        if (*p != *name)
-            goto BAD;
-
-        p++;
-        name++;
-    }
-
-    /* must be followed by end of line or space */
-    if (p < end && !is_space(*p))
-        goto BAD;
-
-    return p;
-
-BAD:
-    return NULL;
-}
-
-/* Parse one or more whitespace characters starting from '*pp'
- * until 'end' is reached. Updates '*pp' on exit.
- *
- * Return 0 on success, -1 on failure.
- */
-static int
-parse_spaces(const char** pp, const char* end)
-{
-    const char* p = *pp;
-
-    if (p >= end || !is_space(*p)) {
-        errno = EINVAL;
-        return -1;
-    }
-    p   = skip_spaces(p, end);
-    *pp = p;
-    return 0;
-}
-
-/* Parse a positive decimal number starting from '*pp' until 'end'
- * is reached. Adjust '*pp' on exit. Return decimal value or -1
- * in case of error.
- *
- * If the value is larger than INT_MAX, -1 will be returned,
- * and errno set to EOVERFLOW.
- *
- * If '*pp' does not start with a decimal digit, -1 is returned
- * and errno set to EINVAL.
- */
-static int
-parse_positive_decimal(const char** pp, const char* end)
-{
-    const char* p = *pp;
-    int value = 0;
-    int overflow = 0;
-
-    if (p >= end || *p < '0' || *p > '9') {
-        errno = EINVAL;
-        return -1;
-    }
-
-    while (p < end) {
-        int      ch = *p;
-        unsigned d  = (unsigned)(ch - '0');
-        int      val2;
-
-        if (d >= 10U) /* d is unsigned, no lower bound check */
-            break;
-
-        val2 = value*10 + (int)d;
-        if (val2 < value)
-            overflow = 1;
-        value = val2;
-        p++;
-    }
-    *pp = p;
-
-    if (overflow) {
-        errno = EOVERFLOW;
-        value = -1;
-    }
-    return value;
-}
-
-/* Read the system's package database and extract information about
- * 'pkgname'. Return 0 in case of success, or -1 in case of error.
- *
- * If the package is unknown, return -1 and set errno to ENOENT
- * If the package database is corrupted, return -1 and set errno to EINVAL
- */
-int
-get_package_info(const char* pkgName, uid_t userId, PackageInfo *info)
-{
-    char*        buffer;
-    size_t       buffer_len;
-    const char*  p;
-    const char*  buffer_end;
-    int          result = -1;
-
-    info->uid          = 0;
-    info->isDebuggable = 0;
-    info->dataDir[0]   = '\0';
-    info->seinfo[0]    = '\0';
-
-    buffer = map_file(PACKAGES_LIST_FILE, &buffer_len);
-    if (buffer == NULL)
-        return -1;
-
-    p          = buffer;
-    buffer_end = buffer + buffer_len;
-
-    /* expect the following format on each line of the control file:
-     *
-     *  <pkgName> <uid> <debugFlag> <dataDir> <seinfo>
-     *
-     * where:
-     *  <pkgName>    is the package's name
-     *  <uid>        is the application-specific user Id (decimal)
-     *  <debugFlag>  is 1 if the package is debuggable, or 0 otherwise
-     *  <dataDir>    is the path to the package's data directory (e.g. /data/data/com.example.foo)
-     *  <seinfo>     is the seinfo label associated with the package
-     *
-     * The file is generated in com.android.server.PackageManagerService.Settings.writeLP()
-     */
-
-    while (p < buffer_end) {
-        /* find end of current line and start of next one */
-        const char*  end  = find_first(p, buffer_end, '\n');
-        const char*  next = (end < buffer_end) ? end + 1 : buffer_end;
-        const char*  q;
-        int          uid, debugFlag;
-
-        /* first field is the package name */
-        p = compare_name(p, end, pkgName);
-        if (p == NULL)
-            goto NEXT_LINE;
-
-        /* skip spaces */
-        if (parse_spaces(&p, end) < 0)
-            goto BAD_FORMAT;
-
-        /* second field is the pid */
-        uid = parse_positive_decimal(&p, end);
-        if (uid < 0)
-            return -1;
-
-        info->uid = (uid_t) uid;
-
-        /* skip spaces */
-        if (parse_spaces(&p, end) < 0)
-            goto BAD_FORMAT;
-
-        /* third field is debug flag (0 or 1) */
-        debugFlag = parse_positive_decimal(&p, end);
-        switch (debugFlag) {
-        case 0:
-            info->isDebuggable = 0;
-            break;
-        case 1:
-            info->isDebuggable = 1;
-            break;
-        default:
-            goto BAD_FORMAT;
-        }
-
-        /* skip spaces */
-        if (parse_spaces(&p, end) < 0)
-            goto BAD_FORMAT;
-
-        /* fourth field is data directory path and must not contain
-         * spaces.
-         */
-        q = skip_non_spaces(p, end);
-        if (q == p)
-            goto BAD_FORMAT;
-
-        /* If userId == 0 (i.e. user is device owner) we can use dataDir value
-         * from packages.list, otherwise compose data directory as
-         * /data/user/$uid/$packageId
-         */
-        if (userId == 0) {
-            p = string_copy(info->dataDir, sizeof info->dataDir, p, q - p);
-        } else {
-            snprintf(info->dataDir,
-                     sizeof info->dataDir,
-                     "/data/user/%d/%s",
-                     userId,
-                     pkgName);
-            p = q;
-        }
-
-        /* skip spaces */
-        if (parse_spaces(&p, end) < 0)
-            goto BAD_FORMAT;
-
-        /* fifth field is the seinfo string */
-        q = skip_non_spaces(p, end);
-        if (q == p)
-            goto BAD_FORMAT;
-
-        string_copy(info->seinfo, sizeof info->seinfo, p, q - p);
-
-        /* Ignore the rest */
-        result = 0;
-        goto EXIT;
-
-    NEXT_LINE:
-        p = next;
-    }
-
-    /* the package is unknown */
-    errno = ENOENT;
-    result = -1;
-    goto EXIT;
-
-BAD_FORMAT:
-    errno = EINVAL;
-    result = -1;
-
-EXIT:
-    unmap_file(buffer, buffer_len);
-    return result;
-}
diff --git a/run-as/package.h b/run-as/package.h
deleted file mode 100644
index eeb5913..0000000
--- a/run-as/package.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
-**
-** Copyright 2010, 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 RUN_AS_PACKAGE_H
-#define RUN_AS_PACKAGE_H
-
-#include <limits.h>
-#include <sys/types.h>
-
-typedef enum {
-    PACKAGE_IS_DEBUGGABLE = 0,
-    PACKAGE_IS_NOT_DEBUGGABLE,
-    PACKAGE_IS_UNKNOWN,
-} PackageStatus;
-
-typedef struct {
-    uid_t  uid;
-    char   isDebuggable;
-    char   dataDir[PATH_MAX];
-    char   seinfo[PATH_MAX];
-} PackageInfo;
-
-/* see documentation in package.c for these functions */
-
-extern int  get_package_info(const char* packageName,
-                             uid_t userId,
-                             PackageInfo*  info);
-
-extern int  check_data_path(const char* dataDir, uid_t uid);
-
-#endif /* RUN_AS_PACKAGE_H */
diff --git a/run-as/run-as.c b/run-as/run-as.c
deleted file mode 100644
index f0fd2fe..0000000
--- a/run-as/run-as.c
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
-**
-** Copyright 2010, 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 PROGNAME "run-as"
-#define LOG_TAG  PROGNAME
-
-#include <dirent.h>
-#include <errno.h>
-#include <paths.h>
-#include <pwd.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/capability.h>
-#include <sys/cdefs.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <private/android_filesystem_config.h>
-#include <selinux/android.h>
-
-#include "package.h"
-
-/*
- *  WARNING WARNING WARNING WARNING
- *
- *  This program runs with CAP_SETUID and CAP_SETGID capabilities on Android
- *  production devices. Be very conservative when modifying it to avoid any
- *  serious security issue. Keep in mind the following:
- *
- *  - This program should only run for the 'root' or 'shell' users
- *
- *  - Avoid anything that is more complex than simple system calls
- *    until the uid/gid has been dropped to that of a normal user
- *    or you are sure to exit.
- *
- *    This avoids depending on environment variables, system properties
- *    and other external factors that may affect the C library in
- *    unpredictable ways.
- *
- *  - Do not trust user input and/or the filesystem whenever possible.
- *
- *  Read README.TXT for more details.
- *
- *
- *
- * The purpose of this program is to run a command as a specific
- * application user-id. Typical usage is:
- *
- *   run-as <package-name> <command> <args>
- *
- *  The 'run-as' binary is installed with CAP_SETUID and CAP_SETGID file
- *  capabilities, but will check the following:
- *
- *  - that it is invoked from the 'shell' or 'root' user (abort otherwise)
- *  - that '<package-name>' is the name of an installed and debuggable package
- *  - that the package's data directory is well-formed (see package.c)
- *
- *  If so, it will drop to the application's user id / group id, cd to the
- *  package's data directory, then run the command there.
- *
- *  NOTE: In the future it might not be possible to cd to the package's data
- *  directory under that package's user id / group id, in which case this
- *  utility will need to be changed accordingly.
- *
- *  This can be useful for a number of different things on production devices:
- *
- *  - Allow application developers to look at their own applicative data
- *    during development.
- *
- *  - Run the 'gdbserver' binary executable to allow native debugging
- */
-
-__noreturn static void
-panic(const char* format, ...)
-{
-    va_list args;
-    int e = errno;
-
-    fprintf(stderr, "%s: ", PROGNAME);
-    va_start(args, format);
-    vfprintf(stderr, format, args);
-    va_end(args);
-    exit(e ? -e : 1);
-}
-
-static void
-usage(void)
-{
-    panic("Usage:\n    " PROGNAME " <package-name> [--user <uid>] <command> [<args>]\n");
-}
-
-int main(int argc, char **argv)
-{
-    const char* pkgname;
-    uid_t myuid, uid, gid, userAppId = 0;
-    int commandArgvOfs = 2, userId = 0;
-    PackageInfo info;
-    struct __user_cap_header_struct capheader;
-    struct __user_cap_data_struct capdata[2];
-
-    /* check arguments */
-    if (argc < 2) {
-        usage();
-    }
-
-    /* check userid of caller - must be 'shell' or 'root' */
-    myuid = getuid();
-    if (myuid != AID_SHELL && myuid != AID_ROOT) {
-        panic("only 'shell' or 'root' users can run this program\n");
-    }
-
-    memset(&capheader, 0, sizeof(capheader));
-    memset(&capdata, 0, sizeof(capdata));
-    capheader.version = _LINUX_CAPABILITY_VERSION_3;
-    capdata[CAP_TO_INDEX(CAP_SETUID)].effective |= CAP_TO_MASK(CAP_SETUID);
-    capdata[CAP_TO_INDEX(CAP_SETGID)].effective |= CAP_TO_MASK(CAP_SETGID);
-    capdata[CAP_TO_INDEX(CAP_SETUID)].permitted |= CAP_TO_MASK(CAP_SETUID);
-    capdata[CAP_TO_INDEX(CAP_SETGID)].permitted |= CAP_TO_MASK(CAP_SETGID);
-
-    if (capset(&capheader, &capdata[0]) < 0) {
-        panic("Could not set capabilities: %s\n", strerror(errno));
-    }
-
-    pkgname = argv[1];
-
-    /* get user_id from command line if provided */
-    if ((argc >= 4) && !strcmp(argv[2], "--user")) {
-        userId = atoi(argv[3]);
-        if (userId < 0)
-            panic("Negative user id %d is provided\n", userId);
-        commandArgvOfs += 2;
-    }
-
-    /* retrieve package information from system (does setegid) */
-    if (get_package_info(pkgname, userId, &info) < 0) {
-        panic("Package '%s' is unknown\n", pkgname);
-    }
-
-    /* verify that user id is not too big. */
-    if ((UID_MAX - info.uid) / AID_USER < (uid_t)userId) {
-        panic("User id %d is too big\n", userId);
-    }
-
-    /* calculate user app ID. */
-    userAppId = (AID_USER * userId) + info.uid;
-
-    /* reject system packages */
-    if (userAppId < AID_APP) {
-        panic("Package '%s' is not an application\n", pkgname);
-    }
-
-    /* reject any non-debuggable package */
-    if (!info.isDebuggable) {
-        panic("Package '%s' is not debuggable\n", pkgname);
-    }
-
-    /* check that the data directory path is valid */
-    if (check_data_path(info.dataDir, userAppId) < 0) {
-        panic("Package '%s' has corrupt installation\n", pkgname);
-    }
-
-    /* Ensure that we change all real/effective/saved IDs at the
-     * same time to avoid nasty surprises.
-     */
-    uid = gid = userAppId;
-    if(setresgid(gid,gid,gid) || setresuid(uid,uid,uid)) {
-        panic("Permission denied\n");
-    }
-
-    /* Required if caller has uid and gid all non-zero */
-    memset(&capdata, 0, sizeof(capdata));
-    if (capset(&capheader, &capdata[0]) < 0) {
-        panic("Could not clear all capabilities: %s\n", strerror(errno));
-    }
-
-    if (selinux_android_setcontext(uid, 0, info.seinfo, pkgname) < 0) {
-        panic("Could not set SELinux security context: %s\n", strerror(errno));
-    }
-
-    // cd into the data directory, and set $HOME correspondingly.
-    if (TEMP_FAILURE_RETRY(chdir(info.dataDir)) < 0) {
-        panic("Could not cd to package's data directory: %s\n", strerror(errno));
-    }
-    setenv("HOME", info.dataDir, 1);
-
-    // Reset parts of the environment, like su would.
-    setenv("PATH", _PATH_DEFPATH, 1);
-    unsetenv("IFS");
-
-    // Set the user-specific parts for this user.
-    struct passwd* pw = getpwuid(uid);
-    setenv("LOGNAME", pw->pw_name, 1);
-    setenv("SHELL", pw->pw_shell, 1);
-    setenv("USER", pw->pw_name, 1);
-
-    /* User specified command for exec. */
-    if ((argc >= commandArgvOfs + 1) &&
-        (execvp(argv[commandArgvOfs], argv+commandArgvOfs) < 0)) {
-        panic("exec failed for %s: %s\n", argv[commandArgvOfs], strerror(errno));
-    }
-
-    /* Default exec shell. */
-    execlp("/system/bin/sh", "sh", NULL);
-
-    panic("exec failed: %s\n", strerror(errno));
-}
diff --git a/run-as/run-as.cpp b/run-as/run-as.cpp
new file mode 100644
index 0000000..50b47b9
--- /dev/null
+++ b/run-as/run-as.cpp
@@ -0,0 +1,246 @@
+/*
+ * Copyright (C) 2010 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 <errno.h>
+#include <error.h>
+#include <paths.h>
+#include <pwd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/capability.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <packagelistparser/packagelistparser.h>
+#include <private/android_filesystem_config.h>
+#include <selinux/android.h>
+
+// The purpose of this program is to run a command as a specific
+// application user-id. Typical usage is:
+//
+//   run-as <package-name> <command> <args>
+//
+//  The 'run-as' binary is installed with CAP_SETUID and CAP_SETGID file
+//  capabilities, but will check the following:
+//
+//  - that it is invoked from the 'shell' or 'root' user (abort otherwise)
+//  - that '<package-name>' is the name of an installed and debuggable package
+//  - that the package's data directory is well-formed
+//
+//  If so, it will drop to the application's user id / group id, cd to the
+//  package's data directory, then run the command there.
+//
+//  This can be useful for a number of different things on production devices:
+//
+//  - Allow application developers to look at their own application data
+//    during development.
+//
+//  - Run the 'gdbserver' binary executable to allow native debugging
+//
+
+static bool packagelist_parse_callback(pkg_info* this_package, void* userdata) {
+  pkg_info* p = reinterpret_cast<pkg_info*>(userdata);
+  if (strcmp(p->name, this_package->name) == 0) {
+    *p = *this_package;
+    return false; // Stop searching.
+  }
+  packagelist_free(this_package);
+  return true; // Keep searching.
+}
+
+static bool check_directory(const char* path, uid_t uid) {
+  struct stat st;
+  if (TEMP_FAILURE_RETRY(lstat(path, &st)) == -1) return false;
+
+  // /data/user/0 is a known safe symlink.
+  if (strcmp("/data/user/0", path) == 0) return true;
+
+  // Must be a real directory, not a symlink.
+  if (!S_ISDIR(st.st_mode)) return false;
+
+  // Must be owned by specific uid/gid.
+  if (st.st_uid != uid || st.st_gid != uid) return false;
+
+  // Must not be readable or writable by others.
+  if ((st.st_mode & (S_IROTH|S_IWOTH)) != 0) return false;
+
+  return true;
+}
+
+// This function is used to check the data directory path for safety.
+// We check that every sub-directory is owned by the 'system' user
+// and exists and is not a symlink. We also check that the full directory
+// path is properly owned by the user ID.
+static bool check_data_path(const char* data_path, uid_t uid) {
+  // The path should be absolute.
+  if (data_path[0] != '/') return false;
+
+  // Look for all sub-paths, we do that by finding
+  // directory separators in the input path and
+  // checking each sub-path independently.
+  for (int nn = 1; data_path[nn] != '\0'; nn++) {
+    char subpath[PATH_MAX];
+
+    /* skip non-separator characters */
+    if (data_path[nn] != '/') continue;
+
+    /* handle trailing separator case */
+    if (data_path[nn+1] == '\0') break;
+
+    /* found a separator, check that data_path is not too long. */
+    if (nn >= (int)(sizeof subpath)) return false;
+
+    /* reject any '..' subpath */
+    if (nn >= 3               &&
+        data_path[nn-3] == '/' &&
+        data_path[nn-2] == '.' &&
+        data_path[nn-1] == '.') {
+      return false;
+    }
+
+    /* copy to 'subpath', then check ownership */
+    memcpy(subpath, data_path, nn);
+    subpath[nn] = '\0';
+
+    if (!check_directory(subpath, AID_SYSTEM)) return false;
+  }
+
+  // All sub-paths were checked, now verify that the full data
+  // directory is owned by the application uid.
+  return check_directory(data_path, uid);
+}
+
+int main(int argc, char* argv[]) {
+  // Check arguments.
+  if (argc < 2) {
+    error(1, 0, "usage: run-as <package-name> [--user <uid>] <command> [<args>]\n");
+  }
+
+  // This program runs with CAP_SETUID and CAP_SETGID capabilities on Android
+  // production devices. Check user id of caller --- must be 'shell' or 'root'.
+  if (getuid() != AID_SHELL && getuid() != AID_ROOT) {
+    error(1, 0, "only 'shell' or 'root' users can run this program");
+  }
+
+  __user_cap_header_struct capheader;
+  __user_cap_data_struct capdata[2];
+  memset(&capheader, 0, sizeof(capheader));
+  memset(&capdata, 0, sizeof(capdata));
+  capheader.version = _LINUX_CAPABILITY_VERSION_3;
+  capdata[CAP_TO_INDEX(CAP_SETUID)].effective |= CAP_TO_MASK(CAP_SETUID);
+  capdata[CAP_TO_INDEX(CAP_SETGID)].effective |= CAP_TO_MASK(CAP_SETGID);
+  capdata[CAP_TO_INDEX(CAP_SETUID)].permitted |= CAP_TO_MASK(CAP_SETUID);
+  capdata[CAP_TO_INDEX(CAP_SETGID)].permitted |= CAP_TO_MASK(CAP_SETGID);
+  if (capset(&capheader, &capdata[0]) == -1) {
+    error(1, errno, "couldn't set capabilities");
+  }
+
+  char* pkgname = argv[1];
+  int cmd_argv_offset = 2;
+
+  // Get user_id from command line if provided.
+  int userId = 0;
+  if ((argc >= 4) && !strcmp(argv[2], "--user")) {
+    userId = atoi(argv[3]);
+    if (userId < 0) error(1, 0, "negative user id: %d", userId);
+    cmd_argv_offset += 2;
+  }
+
+  // Retrieve package information from system, switching egid so we can read the file.
+  gid_t old_egid = getegid();
+  if (setegid(AID_PACKAGE_INFO) == -1) error(1, errno, "setegid(AID_PACKAGE_INFO) failed");
+  pkg_info info;
+  memset(&info, 0, sizeof(info));
+  info.name = pkgname;
+  if (!packagelist_parse(packagelist_parse_callback, &info)) {
+    error(1, errno, "packagelist_parse failed");
+  }
+  if (info.uid == 0) {
+    error(1, 0, "unknown package: %s", pkgname);
+  }
+  if (setegid(old_egid) == -1) error(1, errno, "couldn't restore egid");
+
+  // Verify that user id is not too big.
+  if ((UID_MAX - info.uid) / AID_USER < (uid_t)userId) {
+    error(1, 0, "user id too big: %d", userId);
+  }
+
+  // Calculate user app ID.
+  uid_t userAppId = (AID_USER * userId) + info.uid;
+
+  // Reject system packages.
+  if (userAppId < AID_APP) {
+    error(1, 0, "package not an application: %s", pkgname);
+  }
+
+  // Reject any non-debuggable package.
+  if (!info.debuggable) {
+    error(1, 0, "package not debuggable: %s", pkgname);
+  }
+
+  // Check that the data directory path is valid.
+  if (!check_data_path(info.data_dir, userAppId)) {
+    error(1, 0, "package has corrupt installation: %s", pkgname);
+  }
+
+  // Ensure that we change all real/effective/saved IDs at the
+  // same time to avoid nasty surprises.
+  uid_t uid = userAppId;
+  uid_t gid = userAppId;
+  if (setresgid(gid, gid, gid) == -1) {
+    error(1, errno, "setresgid failed");
+  }
+  if (setresuid(uid, uid, uid) == -1) {
+    error(1, errno, "setresuid failed");
+  }
+
+  // Required if caller has uid and gid all non-zero.
+  memset(&capdata, 0, sizeof(capdata));
+  if (capset(&capheader, &capdata[0]) == -1) {
+    error(1, errno, "couldn't clear all capabilities");
+  }
+
+  if (selinux_android_setcontext(uid, 0, info.seinfo, pkgname) < 0) {
+    error(1, errno, "couldn't set SELinux security context");
+  }
+
+  // cd into the data directory, and set $HOME correspondingly.
+  if (TEMP_FAILURE_RETRY(chdir(info.data_dir)) == -1) {
+    error(1, errno, "couldn't chdir to package's data directory");
+  }
+  setenv("HOME", info.data_dir, 1);
+
+  // Reset parts of the environment, like su would.
+  setenv("PATH", _PATH_DEFPATH, 1);
+  unsetenv("IFS");
+
+  // Set the user-specific parts for this user.
+  passwd* pw = getpwuid(uid);
+  setenv("LOGNAME", pw->pw_name, 1);
+  setenv("SHELL", pw->pw_shell, 1);
+  setenv("USER", pw->pw_name, 1);
+
+  // User specified command for exec.
+  if ((argc >= cmd_argv_offset + 1) &&
+      (execvp(argv[cmd_argv_offset], argv+cmd_argv_offset) == -1)) {
+    error(1, errno, "exec failed for %s", argv[cmd_argv_offset]);
+  }
+
+  // Default exec shell.
+  execlp(_PATH_BSHELL, "sh", NULL);
+  error(1, errno, "exec failed");
+}