Merge "base: fix out of date documentation with PropertySet()"
diff --git a/adb/client/commandline.cpp b/adb/client/commandline.cpp
index 728e5c1..7211f72 100644
--- a/adb/client/commandline.cpp
+++ b/adb/client/commandline.cpp
@@ -1669,17 +1669,29 @@
             return 0;
         }
     } else if (!strcmp(argv[0], "rescue")) {
+        // adb rescue getprop
         // adb rescue getprop <prop>
         // adb rescue install <filename>
         // adb rescue wipe userdata
-        if (argc != 3) error_exit("rescue requires two arguments");
+        if (argc < 2) error_exit("rescue requires at least one argument");
         if (!strcmp(argv[1], "getprop")) {
-            return adb_connect_command(android::base::StringPrintf("rescue-getprop:%s", argv[2]));
+            if (argc == 2) {
+                return adb_connect_command("rescue-getprop:");
+            }
+            if (argc == 3) {
+                return adb_connect_command(
+                        android::base::StringPrintf("rescue-getprop:%s", argv[2]));
+            }
+            error_exit("invalid rescue getprop arguments");
         } else if (!strcmp(argv[1], "install")) {
+            if (argc != 3) error_exit("rescue install requires two arguments");
             if (adb_sideload_install(argv[2], true /* rescue_mode */) != 0) {
                 return 1;
             }
-        } else if (!strcmp(argv[1], "wipe") && !strcmp(argv[2], "userdata")) {
+        } else if (!strcmp(argv[1], "wipe")) {
+            if (argc != 3 || strcmp(argv[2], "userdata") != 0) {
+                error_exit("invalid rescue wipe arguments");
+            }
             return adb_wipe_devices();
         } else {
             error_exit("invalid rescue argument");
@@ -1811,7 +1823,7 @@
         if (argc < 2) error_exit("install-multiple requires an argument");
         return install_multiple_app(argc, argv);
     } else if (!strcmp(argv[0], "install-multi-package")) {
-        if (argc < 3) error_exit("install-multi-package requires an argument");
+        if (argc < 2) error_exit("install-multi-package requires an argument");
         return install_multi_package(argc, argv);
     } else if (!strcmp(argv[0], "uninstall")) {
         if (argc < 2) error_exit("uninstall requires an argument");
diff --git a/adb/daemon/usb.cpp b/adb/daemon/usb.cpp
index 96ee6b2..1abae87 100644
--- a/adb/daemon/usb.cpp
+++ b/adb/daemon/usb.cpp
@@ -370,6 +370,38 @@
                         bound = false;
                         running = false;
                         break;
+
+                    case FUNCTIONFS_SETUP: {
+                        LOG(INFO) << "received FUNCTIONFS_SETUP control transfer: bRequestType = "
+                                  << static_cast<int>(event.u.setup.bRequestType)
+                                  << ", bRequest = " << static_cast<int>(event.u.setup.bRequest)
+                                  << ", wValue = " << static_cast<int>(event.u.setup.wValue)
+                                  << ", wIndex = " << static_cast<int>(event.u.setup.wIndex)
+                                  << ", wLength = " << static_cast<int>(event.u.setup.wLength);
+
+                        if ((event.u.setup.bRequestType & USB_DIR_IN)) {
+                            LOG(INFO) << "acking device-to-host control transfer";
+                            ssize_t rc = adb_write(control_fd_.get(), "", 0);
+                            if (rc != 0) {
+                                PLOG(ERROR) << "failed to write empty packet to host";
+                                break;
+                            }
+                        } else {
+                            std::string buf;
+                            buf.resize(event.u.setup.wLength + 1);
+
+                            ssize_t rc = adb_read(control_fd_.get(), buf.data(), buf.size());
+                            if (rc != event.u.setup.wLength) {
+                                LOG(ERROR)
+                                        << "read " << rc
+                                        << " bytes when trying to read control request, expected "
+                                        << event.u.setup.wLength;
+                            }
+
+                            LOG(INFO) << "control request contents: " << buf;
+                            break;
+                        }
+                    }
                 }
             }
 
diff --git a/adb/daemon/usb_ffs.cpp b/adb/daemon/usb_ffs.cpp
index 07b4ba8..a64ce40 100644
--- a/adb/daemon/usb_ffs.cpp
+++ b/adb/daemon/usb_ffs.cpp
@@ -37,9 +37,12 @@
 // Number of buffers needed to fit MAX_PAYLOAD, with an extra for ZLPs.
 #define USB_FFS_NUM_BUFS ((4 * MAX_PAYLOAD / USB_FFS_BULK_SIZE) + 1)
 
+#define USB_EXT_PROP_UNICODE 1
+
 #define cpu_to_le16(x) htole16(x)
 #define cpu_to_le32(x) htole32(x)
 
+// clang-format off
 struct func_desc {
     struct usb_interface_descriptor intf;
     struct usb_endpoint_descriptor_no_audio source;
@@ -64,6 +67,34 @@
     struct func_desc fs_descs, hs_descs;
 } __attribute__((packed));
 
+template <size_t PropertyNameLength, size_t PropertyDataLength>
+struct usb_os_desc_ext_prop {
+    uint32_t dwSize = sizeof(*this);
+    uint32_t dwPropertyDataType = cpu_to_le32(USB_EXT_PROP_UNICODE);
+
+    // Property name and value are transmitted as UTF-16, but the kernel only
+    // accepts ASCII values and performs the conversion for us.
+    uint16_t wPropertyNameLength = cpu_to_le16(PropertyNameLength);
+    char bPropertyName[PropertyNameLength];
+
+    uint32_t dwPropertyDataLength = cpu_to_le32(PropertyDataLength);
+    char bProperty[PropertyDataLength];
+} __attribute__((packed));
+
+using usb_os_desc_guid_t = usb_os_desc_ext_prop<20, 39>;
+usb_os_desc_guid_t os_desc_guid = {
+    .bPropertyName = "DeviceInterfaceGUID",
+    .bProperty = "{64379D6C-D531-4BED-BBEC-5A16FC07D6BC}",
+};
+
+struct usb_ext_prop_values {
+    usb_os_desc_guid_t guid;
+} __attribute__((packed));
+
+usb_ext_prop_values os_prop_values = {
+    .guid = os_desc_guid,
+};
+
 struct desc_v2 {
     struct usb_functionfs_descs_head_v2 header;
     // The rest of the structure depends on the flags in the header.
@@ -75,9 +106,10 @@
     struct ss_func_desc ss_descs;
     struct usb_os_desc_header os_header;
     struct usb_ext_compat_desc os_desc;
+    struct usb_os_desc_header os_prop_header;
+    struct usb_ext_prop_values os_prop_values;
 } __attribute__((packed));
 
-// clang-format off
 static struct func_desc fs_descriptors = {
     .intf = {
         .bLength = sizeof(fs_descriptors.intf),
@@ -172,13 +204,13 @@
 struct usb_ext_compat_desc os_desc_compat = {
     .bFirstInterfaceNumber = 0,
     .Reserved1 = cpu_to_le32(1),
-    .CompatibleID = {0},
+    .CompatibleID = { 'W', 'I', 'N', 'U', 'S', 'B', '\0', '\0'},
     .SubCompatibleID = {0},
     .Reserved2 = {0},
 };
 
 static struct usb_os_desc_header os_desc_header = {
-    .interface = cpu_to_le32(1),
+    .interface = cpu_to_le32(0),
     .dwLength = cpu_to_le32(sizeof(os_desc_header) + sizeof(os_desc_compat)),
     .bcdVersion = cpu_to_le32(1),
     .wIndex = cpu_to_le32(4),
@@ -186,6 +218,14 @@
     .Reserved = cpu_to_le32(0),
 };
 
+static struct usb_os_desc_header os_prop_header = {
+    .interface = cpu_to_le32(0),
+    .dwLength = cpu_to_le32(sizeof(os_desc_header) + sizeof(os_prop_values)),
+    .bcdVersion = cpu_to_le32(1),
+    .wIndex = cpu_to_le32(5),
+    .wCount = cpu_to_le16(1),
+};
+
 #define STR_INTERFACE_ "ADB Interface"
 
 static const struct {
@@ -221,12 +261,14 @@
     v2_descriptor.fs_count = 3;
     v2_descriptor.hs_count = 3;
     v2_descriptor.ss_count = 5;
-    v2_descriptor.os_count = 1;
+    v2_descriptor.os_count = 2;
     v2_descriptor.fs_descs = fs_descriptors;
     v2_descriptor.hs_descs = hs_descriptors;
     v2_descriptor.ss_descs = ss_descriptors;
     v2_descriptor.os_header = os_desc_header;
     v2_descriptor.os_desc = os_desc_compat;
+    v2_descriptor.os_prop_header = os_prop_header;
+    v2_descriptor.os_prop_values = os_prop_values;
 
     if (out_control->get() < 0) {  // might have already done this before
         LOG(INFO) << "opening control endpoint " << USB_FFS_ADB_EP0;
@@ -257,6 +299,7 @@
         }
         // Signal only when writing the descriptors to ffs
         android::base::SetProperty("sys.usb.ffs.ready", "1");
+        *out_control = std::move(control);
     }
 
     bulk_out.reset(adb_open(USB_FFS_ADB_OUT, O_RDONLY));
@@ -271,7 +314,6 @@
         return false;
     }
 
-    *out_control = std::move(control);
     *out_bulk_in = std::move(bulk_in);
     *out_bulk_out = std::move(bulk_out);
     return true;
diff --git a/base/mapped_file.cpp b/base/mapped_file.cpp
index f689bfa..f60de56 100644
--- a/base/mapped_file.cpp
+++ b/base/mapped_file.cpp
@@ -79,7 +79,7 @@
   if (base_ != nullptr) UnmapViewOfFile(base_);
   if (handle_ != nullptr) CloseHandle(handle_);
 #else
-  if (base_ != nullptr) munmap(base_, size_);
+  if (base_ != nullptr) munmap(base_, size_ + offset_);
 #endif
 
   base_ = nullptr;
diff --git a/fastboot/usb_windows.cpp b/fastboot/usb_windows.cpp
index b00edb3..bf840f8 100644
--- a/fastboot/usb_windows.cpp
+++ b/fastboot/usb_windows.cpp
@@ -195,25 +195,28 @@
 ssize_t WindowsUsbTransport::Read(void* data, size_t len) {
     unsigned long time_out = 0;
     unsigned long read = 0;
+    size_t count = 0;
     int ret;
 
     DBG("usb_read %zu\n", len);
     if (nullptr != handle_) {
-        while (1) {
-            int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
+        while (len > 0) {
+            size_t xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
 
             ret = AdbReadEndpointSync(handle_->adb_read_pipe, data, xfer, &read, time_out);
             errno = GetLastError();
-            DBG("usb_read got: %ld, expected: %d, errno: %d\n", read, xfer, errno);
-            if (ret) {
-                return read;
-            } else {
+            DBG("usb_read got: %lu, expected: %zu, errno: %d\n", read, xfer, errno);
+            if (ret == 0) {
                 // assume ERROR_INVALID_HANDLE indicates we are disconnected
                 if (errno == ERROR_INVALID_HANDLE)
                     usb_kick(handle_.get());
                 break;
             }
-            // else we timed out - try again
+            count += read;
+            len -= read;
+            data = (char*)data + read;
+
+            if (xfer != read || len == 0) return count;
         }
     } else {
         DBG("usb_read NULL handle\n");
diff --git a/fs_mgr/fs_mgr_overlayfs.cpp b/fs_mgr/fs_mgr_overlayfs.cpp
index a649975..ed8cce6 100644
--- a/fs_mgr/fs_mgr_overlayfs.cpp
+++ b/fs_mgr/fs_mgr_overlayfs.cpp
@@ -90,7 +90,7 @@
     return {};
 }
 
-bool fs_mgr_overlayfs_setup(const char*, const char*, bool* change) {
+bool fs_mgr_overlayfs_setup(const char*, const char*, bool* change, bool) {
     if (change) *change = false;
     return false;
 }
@@ -903,7 +903,8 @@
 
 // Returns false if setup not permitted, errno set to last error.
 // If something is altered, set *change.
-bool fs_mgr_overlayfs_setup(const char* backing, const char* mount_point, bool* change) {
+bool fs_mgr_overlayfs_setup(const char* backing, const char* mount_point, bool* change,
+                            bool force) {
     if (change) *change = false;
     auto ret = false;
     if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) return ret;
@@ -927,7 +928,7 @@
             continue;
         }
         save_errno = errno;
-        auto verity_enabled = fs_mgr_is_verity_enabled(*it);
+        auto verity_enabled = !force && fs_mgr_is_verity_enabled(*it);
         if (errno == ENOENT || errno == ENXIO) errno = save_errno;
         if (verity_enabled) {
             it = candidates.erase(it);
diff --git a/fs_mgr/fs_mgr_remount.cpp b/fs_mgr/fs_mgr_remount.cpp
index d264d9a..149bee3 100644
--- a/fs_mgr/fs_mgr_remount.cpp
+++ b/fs_mgr/fs_mgr_remount.cpp
@@ -250,53 +250,42 @@
     // Check verity and optionally setup overlayfs backing.
     auto reboot_later = false;
     auto user_please_reboot_later = false;
-    auto uses_overlayfs = fs_mgr_overlayfs_valid() != OverlayfsValidResult::kNotSupported;
     auto setup_overlayfs = false;
+    auto just_disabled_verity = false;
     for (auto it = partitions.begin(); it != partitions.end();) {
         auto& entry = *it;
         auto& mount_point = entry.mount_point;
         if (fs_mgr_is_verity_enabled(entry)) {
             retval = VERITY_PARTITION;
+            auto ret = false;
             if (android::base::GetProperty("ro.boot.vbmeta.device_state", "") != "locked") {
                 if (AvbOps* ops = avb_ops_user_new()) {
-                    auto ret = avb_user_verity_set(
+                    ret = avb_user_verity_set(
                             ops, android::base::GetProperty("ro.boot.slot_suffix", "").c_str(),
                             false);
                     avb_ops_user_free(ops);
-                    if (ret) {
-                        LOG(WARNING) << "Disabling verity for " << mount_point;
-                        reboot_later = can_reboot;
-                        if (reboot_later) {
-                            // w/o overlayfs available, also check for dedupe
-                            if (!uses_overlayfs) {
-                                ++it;
-                                continue;
-                            }
-                            reboot();
-                        }
-                        user_please_reboot_later = true;
-                    } else if (fs_mgr_set_blk_ro(entry.blk_device, false)) {
-                        fec::io fh(entry.blk_device.c_str(), O_RDWR);
-                        if (fh && fh.set_verity_status(false)) {
-                            LOG(WARNING) << "Disabling verity for " << mount_point;
-                            reboot_later = can_reboot;
-                            if (reboot_later && !uses_overlayfs) {
-                                ++it;
-                                continue;
-                            }
-                            user_please_reboot_later = true;
-                        }
-                    }
+                }
+                if (!ret && fs_mgr_set_blk_ro(entry.blk_device, false)) {
+                    fec::io fh(entry.blk_device.c_str(), O_RDWR);
+                    ret = fh && fh.set_verity_status(false);
+                }
+                if (ret) {
+                    LOG(WARNING) << "Disabling verity for " << mount_point;
+                    just_disabled_verity = true;
+                    reboot_later = can_reboot;
+                    user_please_reboot_later = true;
                 }
             }
-            LOG(ERROR) << "Skipping " << mount_point << " for remount";
-            it = partitions.erase(it);
-            continue;
+            if (!ret) {
+                LOG(ERROR) << "Skipping " << mount_point << " for remount";
+                it = partitions.erase(it);
+                continue;
+            }
         }
 
         auto change = false;
         errno = 0;
-        if (fs_mgr_overlayfs_setup(nullptr, mount_point.c_str(), &change)) {
+        if (fs_mgr_overlayfs_setup(nullptr, mount_point.c_str(), &change, just_disabled_verity)) {
             if (change) {
                 LOG(INFO) << "Using overlayfs for " << mount_point;
                 reboot_later = can_reboot;
@@ -312,7 +301,7 @@
         ++it;
     }
 
-    if (partitions.empty()) {
+    if (partitions.empty() || just_disabled_verity) {
         if (reboot_later) reboot(setup_overlayfs);
         if (user_please_reboot_later) {
             LOG(INFO) << "Now reboot your device for settings to take effect";
diff --git a/fs_mgr/include/fs_mgr_overlayfs.h b/fs_mgr/include/fs_mgr_overlayfs.h
index 6aaf1f3..9a7381f 100644
--- a/fs_mgr/include/fs_mgr_overlayfs.h
+++ b/fs_mgr/include/fs_mgr_overlayfs.h
@@ -26,7 +26,7 @@
 bool fs_mgr_overlayfs_mount_all(android::fs_mgr::Fstab* fstab);
 std::vector<std::string> fs_mgr_overlayfs_required_devices(android::fs_mgr::Fstab* fstab);
 bool fs_mgr_overlayfs_setup(const char* backing = nullptr, const char* mount_point = nullptr,
-                            bool* change = nullptr);
+                            bool* change = nullptr, bool force = true);
 bool fs_mgr_overlayfs_teardown(const char* mount_point = nullptr, bool* change = nullptr);
 bool fs_mgr_overlayfs_is_setup();
 bool fs_mgr_has_shared_blocks(const std::string& mount_point, const std::string& dev);
diff --git a/fs_mgr/tests/adb-remount-test.sh b/fs_mgr/tests/adb-remount-test.sh
index 4e101c3..c2a0f33 100755
--- a/fs_mgr/tests/adb-remount-test.sh
+++ b/fs_mgr/tests/adb-remount-test.sh
@@ -51,7 +51,7 @@
 start_time=`date +%s`
 ACTIVE_SLOT=
 
-ADB_WAIT=3m
+ADB_WAIT=4m
 FASTBOOT_WAIT=2m
 
 ##
@@ -1331,7 +1331,7 @@
   echo "${ORANGE}[  WARNING ]${NORMAL} adb after fastboot"
   adb_wait ${ADB_WAIT} ||
     fixup_from_recovery ||
-    die "did not reboot after flash `usb_status`"
+    die "did not reboot after formatting ${scratch_partition} `usb_status`"
   if ${overlayfs_needed}; then
     adb_root &&
       D=`adb_sh df -k </dev/null` &&
@@ -1426,7 +1426,7 @@
     die "fastboot flash ${scratch_partition}"
   adb_wait ${ADB_WAIT} &&
     adb_root ||
-    die "did not reboot after flash"
+    die "did not reboot after flashing empty ${scratch_partition} `usb_status`"
   T=`adb_date`
   D=`adb disable-verity 2>&1`
   err=${?}
diff --git a/init/Android.bp b/init/Android.bp
index 232d7e3..eaa7fd7 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -127,6 +127,7 @@
         "selabel.cpp",
         "selinux.cpp",
         "service.cpp",
+        "service_utils.cpp",
         "sigchld_handler.cpp",
         "subcontext.cpp",
         "subcontext.proto",
@@ -259,6 +260,7 @@
         "rlimit_parser.cpp",
         "tokenizer.cpp",
         "service.cpp",
+        "service_utils.cpp",
         "subcontext.cpp",
         "subcontext.proto",
         "util.cpp",
diff --git a/init/service.cpp b/init/service.cpp
index 3e865a7..8fe5b30 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -21,12 +21,10 @@
 #include <linux/input.h>
 #include <linux/securebits.h>
 #include <sched.h>
-#include <sys/mount.h>
 #include <sys/prctl.h>
 #include <sys/resource.h>
 #include <sys/stat.h>
 #include <sys/time.h>
-#include <sys/wait.h>
 #include <termios.h>
 #include <unistd.h>
 
@@ -36,7 +34,6 @@
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
-#include <android-base/unique_fd.h>
 #include <hidl-util/FQName.h>
 #include <processgroup/processgroup.h>
 #include <selinux/selinux.h>
@@ -65,7 +62,6 @@
 using android::base::Split;
 using android::base::StartsWith;
 using android::base::StringPrintf;
-using android::base::unique_fd;
 using android::base::WriteStringToFile;
 
 namespace android {
@@ -107,87 +103,6 @@
     return computed_context;
 }
 
-Result<Success> Service::SetUpMountNamespace() const {
-    constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
-
-    // Recursively remount / as slave like zygote does so unmounting and mounting /proc
-    // doesn't interfere with the parent namespace's /proc mount. This will also
-    // prevent any other mounts/unmounts initiated by the service from interfering
-    // with the parent namespace but will still allow mount events from the parent
-    // namespace to propagate to the child.
-    if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
-        return ErrnoError() << "Could not remount(/) recursively as slave";
-    }
-
-    // umount() then mount() /proc and/or /sys
-    // Note that it is not sufficient to mount with MS_REMOUNT.
-    if (namespace_flags_ & CLONE_NEWPID) {
-        if (umount("/proc") == -1) {
-            return ErrnoError() << "Could not umount(/proc)";
-        }
-        if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
-            return ErrnoError() << "Could not mount(/proc)";
-        }
-    }
-    bool remount_sys = std::any_of(namespaces_to_enter_.begin(), namespaces_to_enter_.end(),
-                                   [](const auto& entry) { return entry.first == CLONE_NEWNET; });
-    if (remount_sys) {
-        if (umount2("/sys", MNT_DETACH) == -1) {
-            return ErrnoError() << "Could not umount(/sys)";
-        }
-        if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
-            return ErrnoError() << "Could not mount(/sys)";
-        }
-    }
-    return Success();
-}
-
-Result<Success> Service::SetUpPidNamespace() const {
-    if (prctl(PR_SET_NAME, name_.c_str()) == -1) {
-        return ErrnoError() << "Could not set name";
-    }
-
-    pid_t child_pid = fork();
-    if (child_pid == -1) {
-        return ErrnoError() << "Could not fork init inside the PID namespace";
-    }
-
-    if (child_pid > 0) {
-        // So that we exit with the right status.
-        static int init_exitstatus = 0;
-        signal(SIGTERM, [](int) { _exit(init_exitstatus); });
-
-        pid_t waited_pid;
-        int status;
-        while ((waited_pid = wait(&status)) > 0) {
-             // This loop will end when there are no processes left inside the
-             // PID namespace or when the init process inside the PID namespace
-             // gets a signal.
-            if (waited_pid == child_pid) {
-                init_exitstatus = status;
-            }
-        }
-        if (!WIFEXITED(init_exitstatus)) {
-            _exit(EXIT_FAILURE);
-        }
-        _exit(WEXITSTATUS(init_exitstatus));
-    }
-    return Success();
-}
-
-Result<Success> Service::EnterNamespaces() const {
-    for (const auto& [nstype, path] : namespaces_to_enter_) {
-        auto fd = unique_fd{open(path.c_str(), O_RDONLY | O_CLOEXEC)};
-        if (fd == -1) {
-            return ErrnoError() << "Could not open namespace at " << path;
-        }
-        if (setns(fd, nstype) == -1) {
-            return ErrnoError() << "Could not setns() namespace at " << path;
-        }
-    }
-    return Success();
-}
-
 static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
     std::vector<std::string> expanded_args;
     std::vector<char*> c_strings;
@@ -230,16 +145,16 @@
       flags_(flags),
       pid_(0),
       crash_count_(0),
-      uid_(uid),
-      gid_(gid),
-      supp_gids_(supp_gids),
-      namespace_flags_(namespace_flags),
+      proc_attr_{.ioprio_class = IoSchedClass_NONE,
+                 .ioprio_pri = 0,
+                 .uid = uid,
+                 .gid = gid,
+                 .supp_gids = supp_gids,
+                 .priority = 0},
+      namespaces_{.flags = namespace_flags},
       seclabel_(seclabel),
       onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
                  "onrestart", {}),
-      ioprio_class_(IoSchedClass_NONE),
-      ioprio_pri_(0),
-      priority_(0),
       oom_score_adjust_(-1000),
       start_order_(0),
       args_(args) {}
@@ -272,24 +187,18 @@
                   << ") process group...";
         int r;
         if (signal == SIGTERM) {
-            r = killProcessGroupOnce(uid_, pid_, signal);
+            r = killProcessGroupOnce(proc_attr_.uid, pid_, signal);
         } else {
-            r = killProcessGroup(uid_, pid_, signal);
+            r = killProcessGroup(proc_attr_.uid, pid_, signal);
         }
 
         if (r == 0) process_cgroup_empty_ = true;
     }
 }
 
-void Service::SetProcessAttributes() {
-    for (const auto& rlimit : rlimits_) {
-        if (setrlimit(rlimit.first, &rlimit.second) == -1) {
-            LOG(FATAL) << StringPrintf("setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed",
-                                       rlimit.first, rlimit.second.rlim_cur, rlimit.second.rlim_max);
-        }
-    }
+void Service::SetProcessAttributesAndCaps() {
     // Keep capabilites on uid change.
-    if (capabilities_ && uid_) {
+    if (capabilities_ && proc_attr_.uid) {
         // If Android is running in a container, some securebits might already
         // be locked, so don't change those.
         unsigned long securebits = prctl(PR_GET_SECUREBITS);
@@ -302,37 +211,21 @@
         }
     }
 
-    // TODO: work out why this fails for `console` then upgrade to FATAL.
-    if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
+    if (auto result = SetProcessAttributes(proc_attr_); !result) {
+        LOG(FATAL) << "cannot set attribute for " << name_ << ": " << result.error();
+    }
 
-    if (gid_) {
-        if (setgid(gid_) != 0) {
-            PLOG(FATAL) << "setgid failed for " << name_;
-        }
-    }
-    if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
-        PLOG(FATAL) << "setgroups failed for " << name_;
-    }
-    if (uid_) {
-        if (setuid(uid_) != 0) {
-            PLOG(FATAL) << "setuid failed for " << name_;
-        }
-    }
     if (!seclabel_.empty()) {
         if (setexeccon(seclabel_.c_str()) < 0) {
             PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
         }
     }
-    if (priority_ != 0) {
-        if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
-            PLOG(FATAL) << "setpriority failed for " << name_;
-        }
-    }
+
     if (capabilities_) {
         if (!SetCapsForExec(*capabilities_)) {
             LOG(FATAL) << "cannot set capabilities for " << name_;
         }
-    } else if (uid_) {
+    } else if (proc_attr_.uid) {
         // Inheritable caps can be non-zero when running in a container.
         if (!DropInheritableCaps()) {
             LOG(FATAL) << "cannot drop inheritable caps for " << name_;
@@ -458,7 +351,7 @@
 
 Result<Success> Service::ParseConsole(std::vector<std::string>&& args) {
     flags_ |= SVC_CONSOLE;
-    console_ = args.size() > 1 ? "/dev/" + args[1] : "";
+    proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
     return Success();
 }
 
@@ -477,13 +370,13 @@
     if (args[1] != "net") {
         return Error() << "Init only supports entering network namespaces";
     }
-    if (!namespaces_to_enter_.empty()) {
+    if (!namespaces_.namespaces_to_enter.empty()) {
         return Error() << "Only one network namespace may be entered";
     }
     // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
     // present. Therefore, they also require mount namespaces.
-    namespace_flags_ |= CLONE_NEWNS;
-    namespaces_to_enter_.emplace_back(CLONE_NEWNET, std::move(args[2]));
+    namespaces_.flags |= CLONE_NEWNS;
+    namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
     return Success();
 }
 
@@ -492,22 +385,22 @@
     if (!gid) {
         return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
     }
-    gid_ = *gid;
+    proc_attr_.gid = *gid;
 
     for (std::size_t n = 2; n < args.size(); n++) {
         gid = DecodeUid(args[n]);
         if (!gid) {
             return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
         }
-        supp_gids_.emplace_back(*gid);
+        proc_attr_.supp_gids.emplace_back(*gid);
     }
     return Success();
 }
 
 Result<Success> Service::ParsePriority(std::vector<std::string>&& args) {
-    priority_ = 0;
-    if (!ParseInt(args[1], &priority_,
-                  static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
+    proc_attr_.priority = 0;
+    if (!ParseInt(args[1], &proc_attr_.priority,
+                  static_cast<int>(ANDROID_PRIORITY_HIGHEST),  // highest is negative
                   static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
         return Error() << StringPrintf("process priority value must be range %d - %d",
                                        ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
@@ -547,16 +440,16 @@
 }
 
 Result<Success> Service::ParseIoprio(std::vector<std::string>&& args) {
-    if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
+    if (!ParseInt(args[2], &proc_attr_.ioprio_pri, 0, 7)) {
         return Error() << "priority value must be range 0 - 7";
     }
 
     if (args[1] == "rt") {
-        ioprio_class_ = IoSchedClass_RT;
+        proc_attr_.ioprio_class = IoSchedClass_RT;
     } else if (args[1] == "be") {
-        ioprio_class_ = IoSchedClass_BE;
+        proc_attr_.ioprio_class = IoSchedClass_BE;
     } else if (args[1] == "idle") {
-        ioprio_class_ = IoSchedClass_IDLE;
+        proc_attr_.ioprio_class = IoSchedClass_IDLE;
     } else {
         return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
     }
@@ -613,11 +506,11 @@
 Result<Success> Service::ParseNamespace(std::vector<std::string>&& args) {
     for (size_t i = 1; i < args.size(); i++) {
         if (args[i] == "pid") {
-            namespace_flags_ |= CLONE_NEWPID;
+            namespaces_.flags |= CLONE_NEWPID;
             // PID namespaces require mount namespaces.
-            namespace_flags_ |= CLONE_NEWNS;
+            namespaces_.flags |= CLONE_NEWNS;
         } else if (args[i] == "mnt") {
-            namespace_flags_ |= CLONE_NEWNS;
+            namespaces_.flags |= CLONE_NEWNS;
         } else {
             return Error() << "namespace must be 'pid' or 'mnt'";
         }
@@ -674,7 +567,7 @@
     auto rlimit = ParseRlimit(args);
     if (!rlimit) return rlimit.error();
 
-    rlimits_.emplace_back(*rlimit);
+    proc_attr_.rlimits.emplace_back(*rlimit);
     return Success();
 }
 
@@ -784,7 +677,7 @@
     if (!uid) {
         return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
     }
-    uid_ = *uid;
+    proc_attr_.uid = *uid;
     return Success();
 }
 
@@ -885,8 +778,8 @@
     flags_ |= SVC_EXEC;
     is_exec_service_running_ = true;
 
-    LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << uid_ << " gid "
-              << gid_ << "+" << supp_gids_.size() << " context "
+    LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << proc_attr_.uid
+              << " gid " << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
               << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
 
     return Success();
@@ -920,16 +813,16 @@
 
     bool needs_console = (flags_ & SVC_CONSOLE);
     if (needs_console) {
-        if (console_.empty()) {
-            console_ = default_console;
+        if (proc_attr_.console.empty()) {
+            proc_attr_.console = default_console;
         }
 
         // Make sure that open call succeeds to ensure a console driver is
         // properly registered for the device node
-        int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
+        int console_fd = open(proc_attr_.console.c_str(), O_RDWR | O_CLOEXEC);
         if (console_fd < 0) {
             flags_ |= SVC_DISABLED;
-            return ErrnoError() << "Couldn't open console '" << console_ << "'";
+            return ErrnoError() << "Couldn't open console '" << proc_attr_.console << "'";
         }
         close(console_fd);
     }
@@ -964,8 +857,8 @@
     LOG(INFO) << "starting service '" << name_ << "'...";
 
     pid_t pid = -1;
-    if (namespace_flags_) {
-        pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
+    if (namespaces_.flags) {
+        pid = clone(nullptr, nullptr, namespaces_.flags | SIGCHLD, nullptr);
     } else {
         pid = fork();
     }
@@ -973,33 +866,9 @@
     if (pid == 0) {
         umask(077);
 
-        if (auto result = EnterNamespaces(); !result) {
-            LOG(FATAL) << "Service '" << name_ << "' could not enter namespaces: " << result.error();
-        }
-
-#if defined(__ANDROID__)
-        if (pre_apexd_) {
-            if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
-                LOG(FATAL) << "Service '" << name_ << "' could not enter "
-                           << "into the bootstrap mount namespace";
-            }
-        }
-#endif
-
-        if (namespace_flags_ & CLONE_NEWNS) {
-            if (auto result = SetUpMountNamespace(); !result) {
-                LOG(FATAL) << "Service '" << name_
-                           << "' could not set up mount namespace: " << result.error();
-            }
-        }
-
-        if (namespace_flags_ & CLONE_NEWPID) {
-            // This will fork again to run an init process inside the PID
-            // namespace.
-            if (auto result = SetUpPidNamespace(); !result) {
-                LOG(FATAL) << "Service '" << name_
-                           << "' could not set up PID namespace: " << result.error();
-            }
+        if (auto result = EnterNamespaces(namespaces_, name_, pre_apexd_); !result) {
+            LOG(FATAL) << "Service '" << name_
+                       << "' failed to set up namespaces: " << result.error();
         }
 
         for (const auto& [key, value] : environment_vars_) {
@@ -1009,58 +878,13 @@
         std::for_each(descriptors_.begin(), descriptors_.end(),
                       std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
 
-        // See if there were "writepid" instructions to write to files under cpuset path.
-        std::string cpuset_path;
-        if (CgroupGetControllerPath("cpuset", &cpuset_path)) {
-            auto cpuset_predicate = [&cpuset_path](const std::string& path) {
-                return StartsWith(path, cpuset_path + "/");
-            };
-            auto iter =
-                    std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
-            if (iter == writepid_files_.end()) {
-                // There were no "writepid" instructions for cpusets, check if the system default
-                // cpuset is specified to be used for the process.
-                std::string default_cpuset = GetProperty("ro.cpuset.default", "");
-                if (!default_cpuset.empty()) {
-                    // Make sure the cpuset name starts and ends with '/'.
-                    // A single '/' means the 'root' cpuset.
-                    if (default_cpuset.front() != '/') {
-                        default_cpuset.insert(0, 1, '/');
-                    }
-                    if (default_cpuset.back() != '/') {
-                        default_cpuset.push_back('/');
-                    }
-                    writepid_files_.push_back(
-                            StringPrintf("%s%stasks", cpuset_path.c_str(), default_cpuset.c_str()));
-                }
-            }
-        } else {
-            LOG(ERROR) << "cpuset cgroup controller is not mounted!";
-        }
-        std::string pid_str = std::to_string(getpid());
-        for (const auto& file : writepid_files_) {
-            if (!WriteStringToFile(pid_str, file)) {
-                PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
-            }
-        }
-
-        if (ioprio_class_ != IoSchedClass_NONE) {
-            if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
-                PLOG(ERROR) << "failed to set pid " << getpid()
-                            << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
-            }
-        }
-
-        if (needs_console) {
-            setsid();
-            OpenConsole();
-        } else {
-            ZapStdio();
+        if (auto result = WritePidToFiles(&writepid_files_); !result) {
+            LOG(ERROR) << "failed to write pid to files: " << result.error();
         }
 
         // As requested, set our gid, supplemental gids, uid, context, and
         // priority. Aborts on failure.
-        SetProcessAttributes();
+        SetProcessAttributesAndCaps();
 
         if (!ExpandArgsAndExecv(args_, sigstop_)) {
             PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
@@ -1090,19 +914,19 @@
 
     bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
                       limit_percent_ != -1 || !limit_property_.empty();
-    errno = -createProcessGroup(uid_, pid_, use_memcg);
+    errno = -createProcessGroup(proc_attr_.uid, pid_, use_memcg);
     if (errno != 0) {
-        PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
-                    << name_ << "'";
+        PLOG(ERROR) << "createProcessGroup(" << proc_attr_.uid << ", " << pid_
+                    << ") failed for service '" << name_ << "'";
     } else if (use_memcg) {
         if (swappiness_ != -1) {
-            if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
+            if (!setProcessGroupSwappiness(proc_attr_.uid, pid_, swappiness_)) {
                 PLOG(ERROR) << "setProcessGroupSwappiness failed";
             }
         }
 
         if (soft_limit_in_bytes_ != -1) {
-            if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
+            if (!setProcessGroupSoftLimit(proc_attr_.uid, pid_, soft_limit_in_bytes_)) {
                 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
             }
         }
@@ -1129,7 +953,7 @@
         }
 
         if (computed_limit_in_bytes != size_t(-1)) {
-            if (!setProcessGroupLimit(uid_, pid_, computed_limit_in_bytes)) {
+            if (!setProcessGroupLimit(proc_attr_.uid, pid_, computed_limit_in_bytes)) {
                 PLOG(ERROR) << "setProcessGroupLimit failed";
             }
         }
@@ -1249,25 +1073,6 @@
     }
 }
 
-void Service::ZapStdio() const {
-    int fd;
-    fd = open("/dev/null", O_RDWR);
-    dup2(fd, 0);
-    dup2(fd, 1);
-    dup2(fd, 2);
-    close(fd);
-}
-
-void Service::OpenConsole() const {
-    int fd = open(console_.c_str(), O_RDWR);
-    if (fd == -1) fd = open("/dev/null", O_RDWR);
-    ioctl(fd, TIOCSCTTY, 0);
-    dup2(fd, 0);
-    dup2(fd, 1);
-    dup2(fd, 2);
-    close(fd);
-}
-
 ServiceList::ServiceList() {}
 
 ServiceList& ServiceList::GetInstance() {
diff --git a/init/service.h b/init/service.h
index ae29f28..93b5a5c 100644
--- a/init/service.h
+++ b/init/service.h
@@ -36,6 +36,7 @@
 #include "descriptors.h"
 #include "keyword_map.h"
 #include "parser.h"
+#include "service_utils.h"
 #include "subcontext.h"
 
 #define SVC_DISABLED 0x001        // do not autostart with class
@@ -107,16 +108,16 @@
     pid_t pid() const { return pid_; }
     android::base::boot_clock::time_point time_started() const { return time_started_; }
     int crash_count() const { return crash_count_; }
-    uid_t uid() const { return uid_; }
-    gid_t gid() const { return gid_; }
-    unsigned namespace_flags() const { return namespace_flags_; }
-    const std::vector<gid_t>& supp_gids() const { return supp_gids_; }
+    uid_t uid() const { return proc_attr_.uid; }
+    gid_t gid() const { return proc_attr_.gid; }
+    unsigned namespace_flags() const { return namespaces_.flags; }
+    const std::vector<gid_t>& supp_gids() const { return proc_attr_.supp_gids; }
     const std::string& seclabel() const { return seclabel_; }
     const std::vector<int>& keycodes() const { return keycodes_; }
-    IoSchedClass ioprio_class() const { return ioprio_class_; }
-    int ioprio_pri() const { return ioprio_pri_; }
+    IoSchedClass ioprio_class() const { return proc_attr_.ioprio_class; }
+    int ioprio_pri() const { return proc_attr_.ioprio_pri; }
     const std::set<std::string>& interfaces() const { return interfaces_; }
-    int priority() const { return priority_; }
+    int priority() const { return proc_attr_.priority; }
     int oom_score_adjust() const { return oom_score_adjust_; }
     bool is_override() const { return override_; }
     bool process_cgroup_empty() const { return process_cgroup_empty_; }
@@ -132,15 +133,10 @@
     using OptionParser = Result<Success> (Service::*)(std::vector<std::string>&& args);
     class OptionParserMap;
 
-    Result<Success> SetUpMountNamespace() const;
-    Result<Success> SetUpPidNamespace() const;
-    Result<Success> EnterNamespaces() const;
     void NotifyStateChange(const std::string& new_state) const;
     void StopOrReset(int how);
-    void ZapStdio() const;
-    void OpenConsole() const;
     void KillProcessGroup(int signal);
-    void SetProcessAttributes();
+    void SetProcessAttributesAndCaps();
 
     Result<Success> ParseCapabilities(std::vector<std::string>&& args);
     Result<Success> ParseClass(std::vector<std::string>&& args);
@@ -184,7 +180,6 @@
 
     std::string name_;
     std::set<std::string> classnames_;
-    std::string console_;
 
     unsigned flags_;
     pid_t pid_;
@@ -192,13 +187,9 @@
     android::base::boot_clock::time_point time_crashed_;  // first crash within inspection window
     int crash_count_;                     // number of times crashed within window
 
-    uid_t uid_;
-    gid_t gid_;
-    std::vector<gid_t> supp_gids_;
     std::optional<CapSet> capabilities_;
-    unsigned namespace_flags_;
-    // Pair of namespace type, path to namespace.
-    std::vector<std::pair<int, std::string>> namespaces_to_enter_;
+    ProcessAttributes proc_attr_;
+    NamespaceInfo namespaces_;
 
     std::string seclabel_;
 
@@ -214,10 +205,6 @@
     // keycodes for triggering this service via /dev/input/input*
     std::vector<int> keycodes_;
 
-    IoSchedClass ioprio_class_;
-    int ioprio_pri_;
-    int priority_;
-
     int oom_score_adjust_;
 
     int swappiness_ = -1;
@@ -233,8 +220,6 @@
 
     unsigned long start_order_;
 
-    std::vector<std::pair<int, rlimit>> rlimits_;
-
     bool sigstop_ = false;
 
     std::chrono::seconds restart_period_ = 5s;
diff --git a/init/service_utils.cpp b/init/service_utils.cpp
new file mode 100644
index 0000000..17fc9c8
--- /dev/null
+++ b/init/service_utils.cpp
@@ -0,0 +1,265 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "service_utils.h"
+
+#include <grp.h>
+#include <sys/mount.h>
+#include <sys/prctl.h>
+#include <sys/wait.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+#include <processgroup/processgroup.h>
+
+#include "mount_namespace.h"
+
+using android::base::GetProperty;
+using android::base::StartsWith;
+using android::base::StringPrintf;
+using android::base::unique_fd;
+using android::base::WriteStringToFile;
+
+namespace android {
+namespace init {
+
+namespace {
+
+Result<Success> EnterNamespace(int nstype, const char* path) {
+    auto fd = unique_fd{open(path, O_RDONLY | O_CLOEXEC)};
+    if (fd == -1) {
+        return ErrnoError() << "Could not open namespace at " << path;
+    }
+    if (setns(fd, nstype) == -1) {
+        return ErrnoError() << "Could not setns() namespace at " << path;
+    }
+    return Success();
+}
+
+Result<Success> SetUpMountNamespace(bool remount_proc, bool remount_sys) {
+    constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
+
+    // Recursively remount / as slave like zygote does so unmounting and mounting /proc
+    // doesn't interfere with the parent namespace's /proc mount. This will also
+    // prevent any other mounts/unmounts initiated by the service from interfering
+    // with the parent namespace but will still allow mount events from the parent
+    // namespace to propagate to the child.
+    if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
+        return ErrnoError() << "Could not remount(/) recursively as slave";
+    }
+
+    // umount() then mount() /proc and/or /sys
+    // Note that it is not sufficient to mount with MS_REMOUNT.
+    if (remount_proc) {
+        if (umount("/proc") == -1) {
+            return ErrnoError() << "Could not umount(/proc)";
+        }
+        if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
+            return ErrnoError() << "Could not mount(/proc)";
+        }
+    }
+    if (remount_sys) {
+        if (umount2("/sys", MNT_DETACH) == -1) {
+            return ErrnoError() << "Could not umount(/sys)";
+        }
+        if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
+            return ErrnoError() << "Could not mount(/sys)";
+        }
+    }
+    return Success();
+}
+
+Result<Success> SetUpPidNamespace(const char* name) {
+    if (prctl(PR_SET_NAME, name) == -1) {
+        return ErrnoError() << "Could not set name";
+    }
+
+    pid_t child_pid = fork();
+    if (child_pid == -1) {
+        return ErrnoError() << "Could not fork init inside the PID namespace";
+    }
+
+    if (child_pid > 0) {
+        // So that we exit with the right status.
+        static int init_exitstatus = 0;
+        signal(SIGTERM, [](int) { _exit(init_exitstatus); });
+
+        pid_t waited_pid;
+        int status;
+        while ((waited_pid = wait(&status)) > 0) {
+            // This loop will end when there are no processes left inside the
+            // PID namespace or when the init process inside the PID namespace
+            // gets a signal.
+            if (waited_pid == child_pid) {
+                init_exitstatus = status;
+            }
+        }
+        if (!WIFEXITED(init_exitstatus)) {
+            _exit(EXIT_FAILURE);
+        }
+        _exit(WEXITSTATUS(init_exitstatus));
+    }
+    return Success();
+}
+
+void ZapStdio() {
+    int fd;
+    fd = open("/dev/null", O_RDWR);
+    dup2(fd, 0);
+    dup2(fd, 1);
+    dup2(fd, 2);
+    close(fd);
+}
+
+void OpenConsole(const std::string& console) {
+    int fd = open(console.c_str(), O_RDWR);
+    if (fd == -1) fd = open("/dev/null", O_RDWR);
+    ioctl(fd, TIOCSCTTY, 0);
+    dup2(fd, 0);
+    dup2(fd, 1);
+    dup2(fd, 2);
+    close(fd);
+}
+
+}  // namespace
+
+Result<Success> EnterNamespaces(const NamespaceInfo& info, const std::string& name,
+                                bool pre_apexd) {
+    for (const auto& [nstype, path] : info.namespaces_to_enter) {
+        if (auto result = EnterNamespace(nstype, path.c_str()); !result) {
+            return result;
+        }
+    }
+
+#if defined(__ANDROID__)
+    if (pre_apexd) {
+        if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
+            return Error() << "could not enter into the bootstrap mount namespace";
+        }
+    }
+#endif
+
+    if (info.flags & CLONE_NEWNS) {
+        bool remount_proc = info.flags & CLONE_NEWPID;
+        bool remount_sys =
+                std::any_of(info.namespaces_to_enter.begin(), info.namespaces_to_enter.end(),
+                            [](const auto& entry) { return entry.first == CLONE_NEWNET; });
+        if (auto result = SetUpMountNamespace(remount_proc, remount_sys); !result) {
+            return result;
+        }
+    }
+
+    if (info.flags & CLONE_NEWPID) {
+        // This will fork again to run an init process inside the PID namespace.
+        if (auto result = SetUpPidNamespace(name.c_str()); !result) {
+            return result;
+        }
+    }
+
+    return Success();
+}
+
+Result<Success> SetProcessAttributes(const ProcessAttributes& attr) {
+    if (attr.ioprio_class != IoSchedClass_NONE) {
+        if (android_set_ioprio(getpid(), attr.ioprio_class, attr.ioprio_pri)) {
+            PLOG(ERROR) << "failed to set pid " << getpid() << " ioprio=" << attr.ioprio_class
+                        << "," << attr.ioprio_pri;
+        }
+    }
+
+    if (!attr.console.empty()) {
+        setsid();
+        OpenConsole(attr.console);
+    } else {
+        if (setpgid(0, getpid()) == -1) {
+            return ErrnoError() << "setpgid failed";
+        }
+        ZapStdio();
+    }
+
+    for (const auto& rlimit : attr.rlimits) {
+        if (setrlimit(rlimit.first, &rlimit.second) == -1) {
+            return ErrnoError() << StringPrintf(
+                           "setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed", rlimit.first,
+                           rlimit.second.rlim_cur, rlimit.second.rlim_max);
+        }
+    }
+
+    if (attr.gid) {
+        if (setgid(attr.gid) != 0) {
+            return ErrnoError() << "setgid failed";
+        }
+    }
+    if (setgroups(attr.supp_gids.size(), const_cast<gid_t*>(&attr.supp_gids[0])) != 0) {
+        return ErrnoError() << "setgroups failed";
+    }
+    if (attr.uid) {
+        if (setuid(attr.uid) != 0) {
+            return ErrnoError() << "setuid failed";
+        }
+    }
+
+    if (attr.priority != 0) {
+        if (setpriority(PRIO_PROCESS, 0, attr.priority) != 0) {
+            return ErrnoError() << "setpriority failed";
+        }
+    }
+    return Success();
+}
+
+Result<Success> WritePidToFiles(std::vector<std::string>* files) {
+    // See if there were "writepid" instructions to write to files under cpuset path.
+    std::string cpuset_path;
+    if (CgroupGetControllerPath("cpuset", &cpuset_path)) {
+        auto cpuset_predicate = [&cpuset_path](const std::string& path) {
+            return StartsWith(path, cpuset_path + "/");
+        };
+        auto iter = std::find_if(files->begin(), files->end(), cpuset_predicate);
+        if (iter == files->end()) {
+            // There were no "writepid" instructions for cpusets, check if the system default
+            // cpuset is specified to be used for the process.
+            std::string default_cpuset = GetProperty("ro.cpuset.default", "");
+            if (!default_cpuset.empty()) {
+                // Make sure the cpuset name starts and ends with '/'.
+                // A single '/' means the 'root' cpuset.
+                if (default_cpuset.front() != '/') {
+                    default_cpuset.insert(0, 1, '/');
+                }
+                if (default_cpuset.back() != '/') {
+                    default_cpuset.push_back('/');
+                }
+                files->push_back(
+                        StringPrintf("%s%stasks", cpuset_path.c_str(), default_cpuset.c_str()));
+            }
+        }
+    } else {
+        LOG(ERROR) << "cpuset cgroup controller is not mounted!";
+    }
+    std::string pid_str = std::to_string(getpid());
+    for (const auto& file : *files) {
+        if (!WriteStringToFile(pid_str, file)) {
+            return ErrnoError() << "couldn't write " << pid_str << " to " << file;
+        }
+    }
+    return Success();
+}
+
+}  // namespace init
+}  // namespace android
diff --git a/init/service_utils.h b/init/service_utils.h
new file mode 100644
index 0000000..f7502a9
--- /dev/null
+++ b/init/service_utils.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#pragma once
+
+#include <sys/resource.h>
+#include <sys/types.h>
+
+#include <string>
+#include <vector>
+
+#include <cutils/iosched_policy.h>
+
+#include "result.h"
+
+namespace android {
+namespace init {
+
+struct NamespaceInfo {
+    unsigned flags;
+    // Pair of namespace type, path to name.
+    std::vector<std::pair<int, std::string>> namespaces_to_enter;
+};
+Result<Success> EnterNamespaces(const NamespaceInfo& info, const std::string& name, bool pre_apexd);
+
+struct ProcessAttributes {
+    std::string console;
+    IoSchedClass ioprio_class;
+    int ioprio_pri;
+    std::vector<std::pair<int, rlimit>> rlimits;
+    uid_t uid;
+    gid_t gid;
+    std::vector<gid_t> supp_gids;
+    int priority;
+};
+Result<Success> SetProcessAttributes(const ProcessAttributes& attr);
+
+Result<Success> WritePidToFiles(std::vector<std::string>* files);
+
+}  // namespace init
+}  // namespace android
diff --git a/libappfuse/FuseBridgeLoop.cc b/libappfuse/FuseBridgeLoop.cc
index ac94e69..f1ca446 100644
--- a/libappfuse/FuseBridgeLoop.cc
+++ b/libappfuse/FuseBridgeLoop.cc
@@ -353,8 +353,8 @@
         }
         if (entry->IsClosing()) {
             const int mount_id = entry->mount_id();
-            callback->OnClosed(mount_id);
             bridges_.erase(mount_id);
+            callback->OnClosed(mount_id);
             if (bridges_.size() == 0) {
                 // All bridges are now closed.
                 return false;
diff --git a/libunwindstack/Unwinder.cpp b/libunwindstack/Unwinder.cpp
index 37323dc..c95f852 100644
--- a/libunwindstack/Unwinder.cpp
+++ b/libunwindstack/Unwinder.cpp
@@ -63,7 +63,10 @@
   if (info != nullptr) {
     frame->map_start = info->start;
     frame->map_end = info->end;
-    frame->map_elf_start_offset = info->elf_start_offset;
+    // Since this is a dex file frame, the elf_start_offset is not set
+    // by any of the normal code paths. Use the offset of the map since
+    // that matches the actual offset.
+    frame->map_elf_start_offset = info->offset;
     frame->map_exact_offset = info->offset;
     frame->map_load_bias = info->load_bias;
     frame->map_flags = info->flags;
diff --git a/libunwindstack/tests/UnwinderTest.cpp b/libunwindstack/tests/UnwinderTest.cpp
index 30e57a1..1463167 100644
--- a/libunwindstack/tests/UnwinderTest.cpp
+++ b/libunwindstack/tests/UnwinderTest.cpp
@@ -132,6 +132,10 @@
     const auto& info6 = *--maps_->end();
     info6->memory_backed_elf = true;
 
+    AddMapInfo(0xd0000, 0xd1000, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC, "/fake/fake.apk");
+    const auto& info7 = *--maps_->end();
+    info7->load_bias = 0;
+
     process_memory_.reset(new MemoryFake);
   }
 
@@ -1015,6 +1019,50 @@
   EXPECT_EQ(PROT_READ | PROT_WRITE, frame->map_flags);
 }
 
+TEST_F(UnwinderTest, dex_pc_in_map_non_zero_offset) {
+  ElfInterfaceFake::FakePushFunctionData(FunctionData("Frame0", 0));
+  regs_.set_pc(0x1000);
+  regs_.set_sp(0x10000);
+  regs_.FakeSetDexPc(0xd0400);
+
+  Unwinder unwinder(64, maps_.get(), &regs_, process_memory_);
+  unwinder.Unwind();
+  EXPECT_EQ(ERROR_NONE, unwinder.LastErrorCode());
+  EXPECT_FALSE(unwinder.elf_from_memory_not_file());
+
+  ASSERT_EQ(2U, unwinder.NumFrames());
+
+  auto* frame = &unwinder.frames()[0];
+  EXPECT_EQ(0U, frame->num);
+  EXPECT_EQ(0x400U, frame->rel_pc);
+  EXPECT_EQ(0xd0400U, frame->pc);
+  EXPECT_EQ(0x10000U, frame->sp);
+  EXPECT_EQ("", frame->function_name);
+  EXPECT_EQ(0U, frame->function_offset);
+  EXPECT_EQ("/fake/fake.apk", frame->map_name);
+  EXPECT_EQ(0x1000U, frame->map_elf_start_offset);
+  EXPECT_EQ(0x1000U, frame->map_exact_offset);
+  EXPECT_EQ(0xd0000U, frame->map_start);
+  EXPECT_EQ(0xd1000U, frame->map_end);
+  EXPECT_EQ(0U, frame->map_load_bias);
+  EXPECT_EQ(PROT_READ | PROT_WRITE | PROT_EXEC, frame->map_flags);
+
+  frame = &unwinder.frames()[1];
+  EXPECT_EQ(1U, frame->num);
+  EXPECT_EQ(0U, frame->rel_pc);
+  EXPECT_EQ(0x1000U, frame->pc);
+  EXPECT_EQ(0x10000U, frame->sp);
+  EXPECT_EQ("Frame0", frame->function_name);
+  EXPECT_EQ(0U, frame->function_offset);
+  EXPECT_EQ("/system/fake/libc.so", frame->map_name);
+  EXPECT_EQ(0U, frame->map_elf_start_offset);
+  EXPECT_EQ(0U, frame->map_exact_offset);
+  EXPECT_EQ(0x1000U, frame->map_start);
+  EXPECT_EQ(0x8000U, frame->map_end);
+  EXPECT_EQ(0U, frame->map_load_bias);
+  EXPECT_EQ(PROT_READ | PROT_WRITE, frame->map_flags);
+}
+
 TEST_F(UnwinderTest, dex_pc_not_in_map) {
   ElfInterfaceFake::FakePushFunctionData(FunctionData("Frame0", 0));
   regs_.set_pc(0x1000);