resolved conflicts for merge of b471f524 to lmp-mr1-dev-plus-aosp

Change-Id: I6efd0d4a0ece0b065d02796916355ad5ae8b4eea
diff --git a/adb/Android.mk b/adb/Android.mk
index 99a7ce6..8ebcbf0 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -110,7 +110,7 @@
 	jdwp_service.c \
 	framebuffer_service.c \
 	remount_service.c \
-	disable_verity_service.c \
+	set_verity_enable_state_service.c \
 	usb_linux_client.c
 
 LOCAL_CFLAGS := \
diff --git a/adb/adb.h b/adb/adb.h
index 044760e..35d8a4d 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -328,8 +328,10 @@
 
 #if !ADB_HOST
 void framebuffer_service(int fd, void *cookie);
+// Allow enable-verity to write to system and vendor block devices
+int make_system_and_vendor_block_devices_writable();
 void remount_service(int fd, void *cookie);
-void disable_verity_service(int fd, void* cookie);
+void set_verity_enabled_state_service(int fd, void* cookie);
 #endif
 
 /* packet allocator */
diff --git a/adb/commandline.c b/adb/commandline.c
index 06c94db..f345787 100644
--- a/adb/commandline.c
+++ b/adb/commandline.c
@@ -190,6 +190,8 @@
         "\n"
         "  adb restore <file>           - restore device contents from the <file> backup archive\n"
         "\n"
+        "  adb disable-verity           - disable dm-verity checking on USERDEBUG builds\n"
+        "  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds\n"
         "  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,\n"
         "                                 and the public key is stored in <file>.pub. Any existing files\n"
         "                                 are overwritten.\n"
@@ -1166,17 +1168,17 @@
     }
 
     /* modifiers and flags */
-    while(argc > 0) {
-        if(!strcmp(argv[0],"server")) {
+    while (argc > 0) {
+        if (!strcmp(argv[0],"server")) {
             is_server = 1;
-        } else if(!strcmp(argv[0],"nodaemon")) {
+        } else if (!strcmp(argv[0],"nodaemon")) {
             no_daemon = 1;
         } else if (!strcmp(argv[0], "fork-server")) {
             /* this is a special flag used only when the ADB client launches the ADB Server */
             is_daemon = 1;
-        } else if(!strcmp(argv[0],"persist")) {
+        } else if (!strcmp(argv[0],"persist")) {
             persist = 1;
-        } else if(!strncmp(argv[0], "-p", 2)) {
+        } else if (!strncmp(argv[0], "-p", 2)) {
             const char *product = NULL;
             if (argv[0][2] == '\0') {
                 if (argc < 2) return usage();
@@ -1196,7 +1198,7 @@
             if (isdigit(argv[0][2])) {
                 serial = argv[0] + 2;
             } else {
-                if(argc < 2 || argv[0][2] != '\0') return usage();
+                if (argc < 2 || argv[0][2] != '\0') return usage();
                 serial = argv[1];
                 argc--;
                 argv++;
@@ -1207,7 +1209,7 @@
             ttype = kTransportLocal;
         } else if (!strcmp(argv[0],"-a")) {
             gListenAll = 1;
-        } else if(!strncmp(argv[0], "-H", 2)) {
+        } else if (!strncmp(argv[0], "-H", 2)) {
             const char *hostname = NULL;
             if (argv[0][2] == '\0') {
                 if (argc < 2) return usage();
@@ -1219,7 +1221,7 @@
             }
             adb_set_tcp_name(hostname);
 
-        } else if(!strncmp(argv[0], "-P", 2)) {
+        } else if (!strncmp(argv[0], "-P", 2)) {
             if (argv[0][2] == '\0') {
                 if (argc < 2) return usage();
                 server_port_str = argv[1];
@@ -1258,20 +1260,51 @@
         } else {
             r = launch_server(server_port);
         }
-        if(r) {
+        if (r) {
             fprintf(stderr,"* could not start server *\n");
         }
         return r;
     }
 
-top:
-    if(argc == 0) {
+    if (argc == 0) {
         return usage();
     }
 
-    /* adb_connect() commands */
+    /* handle wait-for-* prefix */
+    if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
+        char* service = argv[0];
+        if (!strncmp(service, "wait-for-device", strlen("wait-for-device"))) {
+            if (ttype == kTransportUsb) {
+                service = "wait-for-usb";
+            } else if (ttype == kTransportLocal) {
+                service = "wait-for-local";
+            } else {
+                service = "wait-for-any";
+            }
+        }
 
-    if(!strcmp(argv[0], "devices")) {
+        format_host_command(buf, sizeof buf, service, ttype, serial);
+
+        if (adb_command(buf)) {
+            D("failure: %s *\n",adb_error());
+            fprintf(stderr,"error: %s\n", adb_error());
+            return 1;
+        }
+
+        /* Allow a command to be run after wait-for-device,
+            * e.g. 'adb wait-for-device shell'.
+            */
+        if (argc == 1) {
+            return 0;
+        }
+
+        /* Fall through */
+        argc--;
+        argv++;
+    }
+
+    /* adb_connect() commands */
+    if (!strcmp(argv[0], "devices")) {
         char *tmp;
         char *listopt;
         if (argc < 2)
@@ -1284,7 +1317,7 @@
         }
         snprintf(buf, sizeof buf, "host:%s%s", argv[0], listopt);
         tmp = adb_query(buf);
-        if(tmp) {
+        if (tmp) {
             printf("List of devices attached \n");
             printf("%s\n", tmp);
             return 0;
@@ -1292,8 +1325,7 @@
             return 1;
         }
     }
-
-    if(!strcmp(argv[0], "connect")) {
+    else if (!strcmp(argv[0], "connect")) {
         char *tmp;
         if (argc != 2) {
             fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
@@ -1301,15 +1333,14 @@
         }
         snprintf(buf, sizeof buf, "host:connect:%s", argv[1]);
         tmp = adb_query(buf);
-        if(tmp) {
+        if (tmp) {
             printf("%s\n", tmp);
             return 0;
         } else {
             return 1;
         }
     }
-
-    if(!strcmp(argv[0], "disconnect")) {
+    else if (!strcmp(argv[0], "disconnect")) {
         char *tmp;
         if (argc > 2) {
             fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
@@ -1321,19 +1352,17 @@
             snprintf(buf, sizeof buf, "host:disconnect:");
         }
         tmp = adb_query(buf);
-        if(tmp) {
+        if (tmp) {
             printf("%s\n", tmp);
             return 0;
         } else {
             return 1;
         }
     }
-
-    if (!strcmp(argv[0], "emu")) {
+    else if (!strcmp(argv[0], "emu")) {
         return adb_send_emulator_command(argc, argv);
     }
-
-    if(!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) {
+    else if (!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) {
         int r;
         int fd;
 
@@ -1344,7 +1373,7 @@
             fflush(stdout);
         }
 
-        if(argc < 2) {
+        if (argc < 2) {
             D("starting interactive shell\n");
             r = interactive_shell();
             if (h) {
@@ -1367,7 +1396,7 @@
         for(;;) {
             D("interactive shell loop. buff=%s\n", buf);
             fd = adb_connect(buf);
-            if(fd >= 0) {
+            if (fd >= 0) {
                 D("about to read_and_dump(fd=%d)\n", fd);
                 read_and_dump(fd);
                 D("read_and_dump() done.\n");
@@ -1378,7 +1407,7 @@
                 r = -1;
             }
 
-            if(persist) {
+            if (persist) {
                 fprintf(stderr,"\n- waiting for device -\n");
                 adb_sleep_ms(1000);
                 do_cmd(ttype, serial, "wait-for-device", 0);
@@ -1392,8 +1421,7 @@
             }
         }
     }
-
-    if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
+    else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
         int exec_in = !strcmp(argv[0], "exec-in");
         int fd;
 
@@ -1422,30 +1450,31 @@
         adb_close(fd);
         return 0;
     }
-
-    if(!strcmp(argv[0], "kill-server")) {
+    else if (!strcmp(argv[0], "kill-server")) {
         int fd;
         fd = _adb_connect("host:kill");
-        if(fd == -1) {
+        if (fd == -1) {
             fprintf(stderr,"* server not running *\n");
             return 1;
         }
         return 0;
     }
-
-    if(!strcmp(argv[0], "sideload")) {
-        if(argc != 2) return usage();
+    else if (!strcmp(argv[0], "sideload")) {
+        if (argc != 2) return usage();
         if (adb_sideload_host(argv[1])) {
             return 1;
         } else {
             return 0;
         }
     }
-
-    if(!strcmp(argv[0], "remount") || !strcmp(argv[0], "reboot")
-            || !strcmp(argv[0], "reboot-bootloader")
-            || !strcmp(argv[0], "tcpip") || !strcmp(argv[0], "usb")
-            || !strcmp(argv[0], "root") || !strcmp(argv[0], "disable-verity")) {
+    else if (!strcmp(argv[0], "remount") ||
+             !strcmp(argv[0], "reboot") ||
+             !strcmp(argv[0], "reboot-bootloader") ||
+             !strcmp(argv[0], "tcpip") ||
+             !strcmp(argv[0], "usb") ||
+             !strcmp(argv[0], "root") ||
+             !strcmp(argv[0], "disable-verity") ||
+             !strcmp(argv[0], "enable-verity")) {
         char command[100];
         if (!strcmp(argv[0], "reboot-bootloader"))
             snprintf(command, sizeof(command), "reboot:bootloader");
@@ -1454,7 +1483,7 @@
         else
             snprintf(command, sizeof(command), "%s:", argv[0]);
         int fd = adb_connect(command);
-        if(fd >= 0) {
+        if (fd >= 0) {
             read_and_dump(fd);
             adb_close(fd);
             return 0;
@@ -1462,49 +1491,13 @@
         fprintf(stderr,"error: %s\n", adb_error());
         return 1;
     }
-
-    if(!strcmp(argv[0], "bugreport")) {
+    else if (!strcmp(argv[0], "bugreport")) {
         if (argc != 1) return usage();
         do_cmd(ttype, serial, "shell", "bugreport", 0);
         return 0;
     }
-
     /* adb_command() wrapper commands */
-
-    if(!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
-        char* service = argv[0];
-        if (!strncmp(service, "wait-for-device", strlen("wait-for-device"))) {
-            if (ttype == kTransportUsb) {
-                service = "wait-for-usb";
-            } else if (ttype == kTransportLocal) {
-                service = "wait-for-local";
-            } else {
-                service = "wait-for-any";
-            }
-        }
-
-        format_host_command(buf, sizeof buf, service, ttype, serial);
-
-        if (adb_command(buf)) {
-            D("failure: %s *\n",adb_error());
-            fprintf(stderr,"error: %s\n", adb_error());
-            return 1;
-        }
-
-        /* Allow a command to be run after wait-for-device,
-            * e.g. 'adb wait-for-device shell'.
-            */
-        if(argc > 1) {
-            argc--;
-            argv++;
-            goto top;
-        }
-        return 0;
-    }
-
-    if(!strcmp(argv[0], "forward") ||
-       !strcmp(argv[0], "reverse"))
-    {
+    else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
         char host_prefix[64];
         char reverse = (char) !strcmp(argv[0], "reverse");
         char remove = 0;
@@ -1589,21 +1582,18 @@
           snprintf(buf, sizeof buf, "%s:%s:%s;%s", host_prefix, command, argv[1], argv[2]);
         }
 
-        if(adb_command(buf)) {
+        if (adb_command(buf)) {
             fprintf(stderr,"error: %s\n", adb_error());
             return 1;
         }
         return 0;
     }
-
     /* do_sync_*() commands */
-
-    if(!strcmp(argv[0], "ls")) {
-        if(argc != 2) return usage();
+    else if (!strcmp(argv[0], "ls")) {
+        if (argc != 2) return usage();
         return do_sync_ls(argv[1]);
     }
-
-    if(!strcmp(argv[0], "push")) {
+    else if (!strcmp(argv[0], "push")) {
         int show_progress = 0;
         int copy_attrs = 0; // unused
         const char* lpath = NULL, *rpath = NULL;
@@ -1616,8 +1606,7 @@
 
         return usage();
     }
-
-    if(!strcmp(argv[0], "pull")) {
+    else if (!strcmp(argv[0], "pull")) {
         int show_progress = 0;
         int copy_attrs = 0;
         const char* rpath = NULL, *lpath = ".";
@@ -1630,28 +1619,24 @@
 
         return usage();
     }
-
-    if (!strcmp(argv[0], "install")) {
+    else if (!strcmp(argv[0], "install")) {
         if (argc < 2) return usage();
         return install_app(ttype, serial, argc, argv);
     }
-
-    if (!strcmp(argv[0], "install-multiple")) {
+    else if (!strcmp(argv[0], "install-multiple")) {
         if (argc < 2) return usage();
         return install_multiple_app(ttype, serial, argc, argv);
     }
-
-    if (!strcmp(argv[0], "uninstall")) {
+    else if (!strcmp(argv[0], "uninstall")) {
         if (argc < 2) return usage();
         return uninstall_app(ttype, serial, argc, argv);
     }
-
-    if(!strcmp(argv[0], "sync")) {
+    else if (!strcmp(argv[0], "sync")) {
         char *srcarg, *android_srcpath, *data_srcpath, *vendor_srcpath;
         int listonly = 0;
 
         int ret;
-        if(argc < 2) {
+        if (argc < 2) {
             /* No local path was specified. */
             srcarg = NULL;
         } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) {
@@ -1661,20 +1646,20 @@
             } else {
                 srcarg = NULL;
             }
-        } else if(argc == 2) {
+        } else if (argc == 2) {
             /* A local path or "android"/"data" arg was specified. */
             srcarg = argv[1];
         } else {
             return usage();
         }
         ret = find_sync_dirs(srcarg, &android_srcpath, &data_srcpath, &vendor_srcpath);
-        if(ret != 0) return usage();
+        if (ret != 0) return usage();
 
-        if(android_srcpath != NULL)
+        if (android_srcpath != NULL)
             ret = do_sync_sync(android_srcpath, "/system", listonly);
-        if(ret == 0 && vendor_srcpath != NULL)
+        if (ret == 0 && vendor_srcpath != NULL)
             ret = do_sync_sync(vendor_srcpath, "/vendor", listonly);
-        if(ret == 0 && data_srcpath != NULL)
+        if (ret == 0 && data_srcpath != NULL)
             ret = do_sync_sync(data_srcpath, "/data", listonly);
 
         free(android_srcpath);
@@ -1682,10 +1667,8 @@
         free(data_srcpath);
         return ret;
     }
-
     /* passthrough commands */
-
-    if(!strcmp(argv[0],"get-state") ||
+    else if (!strcmp(argv[0],"get-state") ||
         !strcmp(argv[0],"get-serialno") ||
         !strcmp(argv[0],"get-devpath"))
     {
@@ -1693,47 +1676,38 @@
 
         format_host_command(buf, sizeof buf, argv[0], ttype, serial);
         tmp = adb_query(buf);
-        if(tmp) {
+        if (tmp) {
             printf("%s\n", tmp);
             return 0;
         } else {
             return 1;
         }
     }
-
     /* other commands */
-
-    if(!strcmp(argv[0],"status-window")) {
+    else if (!strcmp(argv[0],"status-window")) {
         status_window(ttype, serial);
         return 0;
     }
-
-    if(!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
+    else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
         return logcat(ttype, serial, argc, argv);
     }
-
-    if(!strcmp(argv[0],"ppp")) {
+    else if (!strcmp(argv[0],"ppp")) {
         return ppp(argc, argv);
     }
-
-    if (!strcmp(argv[0], "start-server")) {
+    else if (!strcmp(argv[0], "start-server")) {
         return adb_connect("host:start-server");
     }
-
-    if (!strcmp(argv[0], "backup")) {
+    else if (!strcmp(argv[0], "backup")) {
         return backup(argc, argv);
     }
-
-    if (!strcmp(argv[0], "restore")) {
+    else if (!strcmp(argv[0], "restore")) {
         return restore(argc, argv);
     }
-
-    if (!strcmp(argv[0], "keygen")) {
+    else if (!strcmp(argv[0], "keygen")) {
         if (argc < 2) return usage();
         return adb_auth_keygen(argv[1]);
     }
-
-    if (!strcmp(argv[0], "jdwp")) {
+    else if (!strcmp(argv[0], "jdwp")) {
         int  fd = adb_connect("jdwp");
         if (fd >= 0) {
             read_and_dump(fd);
@@ -1744,14 +1718,12 @@
             return -1;
         }
     }
-
     /* "adb /?" is a common idiom under Windows */
-    if(!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
+    else if (!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
         help();
         return 0;
     }
-
-    if(!strcmp(argv[0], "version")) {
+    else if (!strcmp(argv[0], "version")) {
         version(stdout);
         return 0;
     }
diff --git a/adb/remount_service.c b/adb/remount_service.c
index 36367a7..05d3169 100644
--- a/adb/remount_service.c
+++ b/adb/remount_service.c
@@ -79,29 +79,57 @@
     return false;
 }
 
+static int make_block_device_writable(const char* dir)
+{
+    char *dev = 0;
+    int fd = -1;
+    int OFF = 0;
+    int rc = -1;
+
+    dev = find_mount(dir);
+    if (!dev)
+        goto errout;
+
+    fd = unix_open(dev, O_RDONLY | O_CLOEXEC);
+    if (fd < 0)
+        goto errout;
+
+    if (ioctl(fd, BLKROSET, &OFF)) {
+        goto errout;
+    }
+
+    rc = 0;
+
+errout:
+    if (fd >= 0) {
+        adb_close(fd);
+    }
+
+    if (dev) {
+        free(dev);
+    }
+    return rc;
+}
+
 /* Init mounts /system as read only, remount to enable writes. */
 static int remount(const char* dir, int* dir_ro)
 {
     char *dev;
-    int fd;
     int OFF = 0;
 
     if (dir_ro == 0) {
         return 0;
     }
 
+    if (make_block_device_writable(dir)) {
+        return -1;
+    }
+
     dev = find_mount(dir);
 
     if (!dev)
         return -1;
 
-    fd = unix_open(dev, O_RDONLY | O_CLOEXEC);
-    if (fd < 0)
-        return -1;
-
-    ioctl(fd, BLKROSET, &OFF);
-    adb_close(fd);
-
     *dir_ro = mount(dev, dir, "none", MS_REMOUNT, NULL);
 
     free(dev);
@@ -114,6 +142,28 @@
     writex(fd, str, strlen(str));
 }
 
+int make_system_and_vendor_block_devices_writable(int fd)
+{
+    char buffer[200];
+    if (make_block_device_writable("/system")) {
+        snprintf(buffer, sizeof(buffer),
+                 "Failed to make system block device writable %s\n",
+                 strerror(errno));
+        write_string(fd, buffer);
+        return -1;
+    }
+
+    if (hasVendorPartition() && make_block_device_writable("/vendor")) {
+        snprintf(buffer, sizeof(buffer),
+                 "Failed to make vendor block device writable: %s\n",
+                 strerror(errno));
+        write_string(fd, buffer);
+        return -1;
+    }
+
+    return 0;
+}
+
 void remount_service(int fd, void *cookie)
 {
     char buffer[200];
@@ -167,4 +217,3 @@
 
     adb_close(fd);
 }
-
diff --git a/adb/services.c b/adb/services.c
index 1aeb376..d5a4642 100644
--- a/adb/services.c
+++ b/adb/services.c
@@ -472,7 +472,9 @@
             }
         }
     } else if(!strncmp(name, "disable-verity:", 15)) {
-        ret = create_service_thread(disable_verity_service, NULL);
+        ret = create_service_thread(set_verity_enabled_state_service, (void*)0);
+    } else if(!strncmp(name, "enable-verity:", 15)) {
+        ret = create_service_thread(set_verity_enabled_state_service, (void*)1);
 #endif
     }
     if (ret >= 0) {
diff --git a/adb/set_verity_enable_state_service.c b/adb/set_verity_enable_state_service.c
new file mode 100644
index 0000000..1e22149
--- /dev/null
+++ b/adb/set_verity_enable_state_service.c
@@ -0,0 +1,217 @@
+/*
+ * 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.
+ */
+
+#include "sysdeps.h"
+
+#define  TRACE_TAG  TRACE_ADB
+#include "adb.h"
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <inttypes.h>
+
+#include "cutils/properties.h"
+#include "ext4_sb.h"
+#include <fs_mgr.h>
+
+#define FSTAB_PREFIX "/fstab."
+struct fstab *fstab;
+
+__attribute__((__format__(printf, 2, 3))) __nonnull((2))
+static void write_console(int fd, const char* format, ...)
+{
+    char buffer[256];
+    va_list args;
+    va_start (args, format);
+    vsnprintf (buffer, sizeof(buffer), format, args);
+    va_end (args);
+
+    adb_write(fd, buffer, strnlen(buffer, sizeof(buffer)));
+}
+
+static int get_target_device_size(int fd, const char *blk_device,
+                                  uint64_t *device_size)
+{
+    int data_device;
+    struct ext4_super_block sb;
+    struct fs_info info;
+
+    info.len = 0;  /* Only len is set to 0 to ask the device for real size. */
+
+    data_device = adb_open(blk_device, O_RDONLY | O_CLOEXEC);
+    if (data_device < 0) {
+        write_console(fd, "Error opening block device (%s)\n", strerror(errno));
+        return -1;
+    }
+
+    if (lseek64(data_device, 1024, SEEK_SET) < 0) {
+        write_console(fd, "Error seeking to superblock\n");
+        adb_close(data_device);
+        return -1;
+    }
+
+    if (adb_read(data_device, &sb, sizeof(sb)) != sizeof(sb)) {
+        write_console(fd, "Error reading superblock\n");
+        adb_close(data_device);
+        return -1;
+    }
+
+    ext4_parse_sb(&sb, &info);
+    *device_size = info.len;
+
+    adb_close(data_device);
+    return 0;
+}
+
+/* Turn verity on/off */
+static int set_verity_enabled_state(int fd, const char *block_device,
+                                    const char* mount_point, bool enable)
+{
+    uint32_t magic_number;
+    const uint32_t new_magic = enable ? VERITY_METADATA_MAGIC_NUMBER
+                                      : VERITY_METADATA_MAGIC_DISABLE;
+    uint64_t device_length;
+    int device;
+    int retval = -1;
+
+    device = adb_open(block_device, O_RDWR | O_CLOEXEC);
+    if (device == -1) {
+        write_console(fd, "Could not open block device %s (%s).\n",
+                      block_device, strerror(errno));
+        write_console(fd, "Maybe run adb remount?\n");
+        goto errout;
+    }
+
+    // find the start of the verity metadata
+    if (get_target_device_size(fd, (char*)block_device, &device_length) < 0) {
+        write_console(fd, "Could not get target device size.\n");
+        goto errout;
+    }
+
+    if (lseek64(device, device_length, SEEK_SET) < 0) {
+        write_console(fd,
+                      "Could not seek to start of verity metadata block.\n");
+        goto errout;
+    }
+
+    // check the magic number
+    if (adb_read(device, &magic_number, sizeof(magic_number))
+             != sizeof(magic_number)) {
+        write_console(fd, "Couldn't read magic number!\n");
+        goto errout;
+    }
+
+    if (!enable && magic_number == VERITY_METADATA_MAGIC_DISABLE) {
+        write_console(fd, "Verity already disabled on %s\n", mount_point);
+        goto errout;
+    }
+
+    if (enable && magic_number == VERITY_METADATA_MAGIC_NUMBER) {
+        write_console(fd, "Verity already enabled on %s\n", mount_point);
+        goto errout;
+    }
+
+    if (magic_number != VERITY_METADATA_MAGIC_NUMBER
+            && magic_number != VERITY_METADATA_MAGIC_DISABLE) {
+        write_console(fd,
+                      "Couldn't find verity metadata at offset %"PRIu64"!\n",
+                      device_length);
+        goto errout;
+    }
+
+    if (lseek64(device, device_length, SEEK_SET) < 0) {
+        write_console(fd,
+                      "Could not seek to start of verity metadata block.\n");
+        goto errout;
+    }
+
+    if (adb_write(device, &new_magic, sizeof(new_magic)) != sizeof(new_magic)) {
+        write_console(fd, "Could not set verity %s flag on device %s with error %s\n",
+                      enable ? "enabled" : "disabled",
+                      block_device,
+                      strerror(errno));
+        goto errout;
+    }
+
+    write_console(fd, "Verity %s on %s\n",
+                  enable ? "enabled" : "disabled",
+                  mount_point);
+    retval = 0;
+errout:
+    if (device != -1)
+        adb_close(device);
+    return retval;
+}
+
+void set_verity_enabled_state_service(int fd, void* cookie)
+{
+    bool enable = (cookie != NULL);
+#ifdef ALLOW_ADBD_DISABLE_VERITY
+    char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
+    char propbuf[PROPERTY_VALUE_MAX];
+    int i;
+    bool any_changed = false;
+
+    property_get("ro.secure", propbuf, "0");
+    if (strcmp(propbuf, "1")) {
+        write_console(fd, "verity not enabled - ENG build\n");
+        goto errout;
+    }
+
+    property_get("ro.debuggable", propbuf, "0");
+    if (strcmp(propbuf, "1")) {
+        write_console(fd, "verity cannot be disabled/enabled - USER build\n");
+        goto errout;
+    }
+
+    property_get("ro.hardware", propbuf, "");
+    snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s", propbuf);
+
+    fstab = fs_mgr_read_fstab(fstab_filename);
+    if (!fstab) {
+        write_console(fd, "Failed to open %s\nMaybe run adb root?\n",
+                      fstab_filename);
+        goto errout;
+    }
+
+    if (enable && make_system_and_vendor_block_devices_writable(fd)) {
+        goto errout;
+    }
+
+    /* Loop through entries looking for ones that vold manages */
+    for (i = 0; i < fstab->num_entries; i++) {
+        if(fs_mgr_is_verified(&fstab->recs[i])) {
+            if (!set_verity_enabled_state(fd, fstab->recs[i].blk_device,
+                                          fstab->recs[i].mount_point, enable)) {
+                any_changed = true;
+            }
+       }
+    }
+
+    if (any_changed) {
+        write_console(fd,
+                      "Now reboot your device for settings to take effect\n");
+    }
+#else
+    write_console(fd, "%s-verity only works for userdebug builds\n",
+                  enable ? "enable" : "disable");
+#endif
+
+errout:
+    adb_close(fd);
+}
diff --git a/fs_mgr/fs_mgr_verity.c b/fs_mgr/fs_mgr_verity.c
index 51555a1..a452dce 100644
--- a/fs_mgr/fs_mgr_verity.c
+++ b/fs_mgr/fs_mgr_verity.c
@@ -155,7 +155,7 @@
     unsigned table_length;
     uint64_t device_length;
     int protocol_version;
-    int device;
+    FILE *device;
     int retval = FS_MGR_SETUP_VERITY_FAIL;
     *signature = 0;
     *table = 0;
@@ -238,12 +238,11 @@
         goto out;
     }
 
-    (*table)[table_length] = 0;
     retval = FS_MGR_SETUP_VERITY_SUCCESS;
 
 out:
-    if (device != -1)
-        TEMP_FAILURE_RETRY(close(device));
+    if (device)
+        fclose(device);
 
     if (retval != FS_MGR_SETUP_VERITY_SUCCESS) {
         free(*table);
@@ -378,7 +377,7 @@
 
 int fs_mgr_setup_verity(struct fstab_rec *fstab) {
 
-    int retval = FS_MGR_SETUP_VERITY_FAIL;
+    int retval = -1;
     int fd = -1;
 
     char *verity_blk_name = 0;
@@ -409,12 +408,10 @@
         goto out;
     }
 
-    retval = FS_MGR_SETUP_VERITY_FAIL;
-
     // get the device mapper fd
     if ((fd = open("/dev/device-mapper", O_RDWR)) < 0) {
         ERROR("Error opening device mapper (%s)", strerror(errno));
-        goto out;
+        goto out;;
     }
 
     // create the device
@@ -464,9 +461,9 @@
         close(fd);
     }
 
-    free(verity_table);
-    free(verity_table_signature);
-    free(verity_blk_name);
+    free (verity_table);
+    free (verity_table_signature);
+    free (verity_blk_name);
 
     return retval;
 }
diff --git a/init/init.c b/init/init.c
index 7ddab80..2b82937 100644
--- a/init/init.c
+++ b/init/init.c
@@ -858,6 +858,26 @@
 }
 #endif
 
+static const struct selinux_opt seopts_prop[] = {
+        { SELABEL_OPT_PATH, "/property_contexts" },
+        { SELABEL_OPT_PATH, "/data/security/current/property_contexts" },
+        { 0, NULL }
+};
+
+struct selabel_handle* selinux_android_prop_context_handle(void)
+{
+    int policy_index = selinux_android_use_data_policy() ? 1 : 0;
+    struct selabel_handle* sehandle = selabel_open(SELABEL_CTX_ANDROID_PROP,
+                                                   &seopts_prop[policy_index], 1);
+    if (!sehandle) {
+        ERROR("SELinux:  Could not load property_contexts:  %s\n",
+              strerror(errno));
+        return NULL;
+    }
+    INFO("SELinux: Loaded property contexts from %s\n", seopts_prop[policy_index].value);
+    return sehandle;
+}
+
 void selinux_init_all_handles(void)
 {
     sehandle = selinux_android_file_context_handle();