am 223fd1ca: Revert "Make encryption configurable"

* commit '223fd1cad8d627dc36e11da8cdd342c1a810d226':
  Revert "Make encryption configurable"
diff --git a/Android.mk b/Android.mk
index d90b1c2..cf2b291 100644
--- a/Android.mk
+++ b/Android.mk
@@ -22,9 +22,6 @@
 common_c_includes := \
 	system/extras/ext4_utils \
 	system/extras/f2fs_utils \
-	external/openssl/include \
-	external/stlport/stlport \
-	bionic \
 	external/scrypt/lib/crypto \
 	frameworks/native/include \
 	system/security/keystore \
@@ -33,7 +30,6 @@
 
 common_shared_libraries := \
 	libsysutils \
-	libstlport \
 	libbinder \
 	libcutils \
 	liblog \
@@ -54,33 +50,36 @@
 	libmincrypt \
 	libbatteryservice
 
+vold_conlyflags := -std=c11
+vold_cflags := -Werror -Wall -Wno-missing-field-initializers
+
 include $(CLEAR_VARS)
 
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE := libvold
-
+LOCAL_CLANG := true
 LOCAL_SRC_FILES := $(common_src_files)
-
 LOCAL_C_INCLUDES := $(common_c_includes)
-
 LOCAL_SHARED_LIBRARIES := $(common_shared_libraries)
-
 LOCAL_STATIC_LIBRARIES := $(common_static_libraries)
-
 LOCAL_MODULE_TAGS := eng tests
+LOCAL_CFLAGS := $(vold_cflags)
+LOCAL_CONLYFLAGS := $(vold_conlyflags)
 
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
 
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE:= vold
-
+LOCAL_CLANG := true
 LOCAL_SRC_FILES := \
 	main.cpp \
 	$(common_src_files)
 
 LOCAL_C_INCLUDES := $(common_c_includes)
-
-LOCAL_CFLAGS := -Werror=format
+LOCAL_CFLAGS := $(vold_cflags)
+LOCAL_CONLYFLAGS := $(vold_conlyflags)
 
 ifeq ($(TARGET_HW_DISK_ENCRYPTION),true)
 LOCAL_C_INCLUDES += $(TARGET_CRYPTFS_HW_PATH)
@@ -89,21 +88,18 @@
 endif
 
 LOCAL_SHARED_LIBRARIES := $(common_shared_libraries)
-
 LOCAL_STATIC_LIBRARIES := $(common_static_libraries)
 
 include $(BUILD_EXECUTABLE)
 
 include $(CLEAR_VARS)
 
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+LOCAL_CLANG := true
 LOCAL_SRC_FILES:= vdc.c
-
 LOCAL_MODULE:= vdc
-
-LOCAL_C_INCLUDES :=
-
-LOCAL_CFLAGS := 
-
 LOCAL_SHARED_LIBRARIES := libcutils
+LOCAL_CFLAGS := $(vold_cflags)
+LOCAL_CONLYFLAGS := $(vold_conlyflags)
 
 include $(BUILD_EXECUTABLE)
diff --git a/CheckBattery.cpp b/CheckBattery.cpp
index 21d426b..6390d02 100644
--- a/CheckBattery.cpp
+++ b/CheckBattery.cpp
@@ -22,68 +22,6 @@
 
 using namespace android;
 
-namespace
-{
-    // How often to check battery in seconds
-    const int CHECK_PERIOD = 30;
-
-    // How charged should the battery be (percent) to start encrypting
-    const int START_THRESHOLD = 10;
-
-    // How charged should the battery be (percent) to continue encrypting
-    const int CONTINUE_THRESHOLD = 5;
-
-    const String16 serviceName("batteryproperties");
-
-    sp<IBinder> bs;
-    sp<IBatteryPropertiesRegistrar> interface;
-
-    bool singletonInitialized = false;
-    time_t last_checked = {0};
-    int last_result = 100;
-
-    int is_battery_ok(int threshold)
-    {
-        time_t now = time(NULL);
-        if (now == -1 || difftime(now, last_checked) < 5) {
-            goto finish;
-        }
-        last_checked = now;
-
-        if (!singletonInitialized) {
-            bs = defaultServiceManager()->checkService(serviceName);
-            if (bs == NULL) {
-                SLOGE("No batteryproperties service!");
-                goto finish;
-            }
-
-            interface = interface_cast<IBatteryPropertiesRegistrar>(bs);
-            if (interface == NULL) {
-                SLOGE("No IBatteryPropertiesRegistrar interface");
-                goto finish;
-            }
-
-            singletonInitialized = true;
-        }
-
-        {
-            BatteryProperty val;
-            status_t status = interface
-                ->getProperty(android::BATTERY_PROP_CAPACITY, &val);
-            if (status == NO_ERROR) {
-                SLOGD("Capacity is %d", (int)val.valueInt64);
-                last_result = val.valueInt64;
-            } else {
-                SLOGE("Failed to get battery charge");
-                last_result = 100;
-            }
-        }
-
-    finish:
-        return last_result >= threshold;
-    }
-}
-
 extern "C"
 {
     int is_battery_ok_to_start()
diff --git a/CommandListener.cpp b/CommandListener.cpp
index f135a01..551a6ce 100644
--- a/CommandListener.cpp
+++ b/CommandListener.cpp
@@ -23,6 +23,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <fs_mgr.h>
+#include <stdio.h>
 #include <string.h>
 
 #define LOG_TAG "VoldCmdListener"
@@ -216,7 +217,6 @@
     if (!rc) {
         cli->sendMsg(ResponseCode::CommandOkay, "volume operation succeeded", false);
     } else {
-        int erno = errno;
         rc = ResponseCode::convertFromErrno();
         cli->sendMsg(rc, "volume operation failed", true);
     }
diff --git a/Devmapper.cpp b/Devmapper.cpp
index 700e538..703902f 100644
--- a/Devmapper.cpp
+++ b/Devmapper.cpp
@@ -296,7 +296,7 @@
 
 void *Devmapper::_align(void *ptr, unsigned int a)
 {
-        register unsigned long agn = --a;
+        unsigned long agn = --a;
 
         return (void *) (((unsigned long) ptr + agn) & ~agn);
 }
diff --git a/DirectVolume.cpp b/DirectVolume.cpp
index cfa1e0b..64d7744 100644
--- a/DirectVolume.cpp
+++ b/DirectVolume.cpp
@@ -321,11 +321,17 @@
     char msg[255];
     bool enabled;
 
-    if (mVm->shareEnabled(getLabel(), "ums", &enabled) == 0 && enabled) {
+    SLOGD("Volume %s %s disk %d:%d removed\n", getLabel(), getMountpoint(), major, minor);
+    if ((dev_t) MKDEV(major, minor) == mCurrentlyMountedKdev) {
+        /*
+         * Yikes, our mounted disk is going away!
+         */
+
+        doUnmount(major, minor);
+    } else if (mVm->shareEnabled(getLabel(), "ums", &enabled) == 0 && enabled) {
         mVm->unshareVolume(getLabel(), "ums");
     }
 
-    SLOGD("Volume %s %s disk %d:%d removed\n", getLabel(), getMountpoint(), major, minor);
     snprintf(msg, sizeof(msg), "Volume %s %s disk removed (%d:%d)",
              getLabel(), getFuseMountpoint(), major, minor);
     mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeDiskRemoved,
@@ -352,29 +358,12 @@
     if (state != Volume::State_Mounted && state != Volume::State_Shared) {
         return;
     }
-        
+
     if ((dev_t) MKDEV(major, minor) == mCurrentlyMountedKdev) {
         /*
          * Yikes, our mounted partition is going away!
          */
-
-        bool providesAsec = (getFlags() & VOL_PROVIDES_ASEC) != 0;
-        if (providesAsec && mVm->cleanupAsec(this, true)) {
-            SLOGE("Failed to cleanup ASEC - unmount will probably fail!");
-        }
-
-        snprintf(msg, sizeof(msg), "Volume %s %s bad removal (%d:%d)",
-                 getLabel(), getFuseMountpoint(), major, minor);
-        mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeBadRemoval,
-                                             msg, false);
-
-        if (Volume::unmountVol(true, false)) {
-            SLOGE("Failed to unmount volume on bad removal (%s)", 
-                 strerror(errno));
-            // XXX: At this point we're screwed for now
-        } else {
-            SLOGD("Crisis averted");
-        }
+        doUnmount(major, minor);
     } else if (state == Volume::State_Shared) {
         /* removed during mass storage */
         snprintf(msg, sizeof(msg), "Volume %s bad removal (%d:%d)",
@@ -391,6 +380,27 @@
     }
 }
 
+void DirectVolume::doUnmount(int major, int minor) {
+    char msg[255];
+    bool providesAsec = (getFlags() & VOL_PROVIDES_ASEC) != 0;
+    if (providesAsec && mVm->cleanupAsec(this, true)) {
+        SLOGE("Failed to cleanup ASEC - unmount will probably fail!");
+    }
+
+    snprintf(msg, sizeof(msg), "Volume %s %s bad removal (%d:%d)",
+                getLabel(), getFuseMountpoint(), major, minor);
+    mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeBadRemoval,
+                                            msg, false);
+
+    if (Volume::unmountVol(true, false)) {
+        SLOGE("Failed to unmount volume on bad removal (%s)",
+                strerror(errno));
+        // XXX: At this point we're screwed for now
+    } else {
+        SLOGD("Crisis averted");
+    }
+}
+
 /*
  * Called from base to get a list of devicenodes for mounting
  */
diff --git a/DirectVolume.h b/DirectVolume.h
index 5e0df74..96f46af 100644
--- a/DirectVolume.h
+++ b/DirectVolume.h
@@ -84,6 +84,7 @@
     void handlePartitionChanged(const char *devpath, NetlinkEvent *evt);
 
     int doMountVfat(const char *deviceNode, const char *mountPoint);
+    void doUnmount(int major, int minor);
 
 };
 
diff --git a/Ext4.cpp b/Ext4.cpp
index dc31fd0..f5a964a 100644
--- a/Ext4.cpp
+++ b/Ext4.cpp
@@ -112,7 +112,6 @@
 }
 
 int Ext4::format(const char *fsPath, unsigned int numSectors, const char *mountpoint) {
-    int fd;
     const char *args[7];
     int rc;
     int status;
diff --git a/Fat.cpp b/Fat.cpp
index cd4ea5f..6ac1f8a 100644
--- a/Fat.cpp
+++ b/Fat.cpp
@@ -50,7 +50,6 @@
 extern "C" int mount(const char *, const char *, const char *, unsigned long, const void *);
 
 int Fat::check(const char *fsPath) {
-    bool rw = true;
     if (access(FSCK_MSDOS_PATH, X_OK)) {
         SLOGW("Skipping fs checks\n");
         return 0;
@@ -170,7 +169,6 @@
 }
 
 int Fat::format(const char *fsPath, unsigned int numSectors, bool wipe) {
-    int fd;
     const char *args[11];
     int rc;
     int status;
diff --git a/Loop.cpp b/Loop.cpp
index 11c114f..ca26093 100644
--- a/Loop.cpp
+++ b/Loop.cpp
@@ -35,6 +35,7 @@
 #include <sysutils/SocketClient.h>
 #include "Loop.h"
 #include "Asec.h"
+#include "sehandle.h"
 
 int Loop::dumpState(SocketClient *c) {
     int i;
@@ -132,6 +133,7 @@
     for (i = 0; i < LOOP_MAX; i++) {
         struct loop_info64 li;
         int rc;
+        char *secontext = NULL;
 
         sprintf(filename, "/dev/block/loop%d", i);
 
@@ -141,12 +143,29 @@
          */
         mode_t mode = 0660 | S_IFBLK;
         unsigned int dev = (0xff & i) | ((i << 12) & 0xfff00000) | (7 << 8);
+
+        if (sehandle) {
+            rc = selabel_lookup(sehandle, &secontext, filename, S_IFBLK);
+            if (rc == 0)
+                setfscreatecon(secontext);
+        }
+
         if (mknod(filename, mode, dev) < 0) {
             if (errno != EEXIST) {
+                int sverrno = errno;
                 SLOGE("Error creating loop device node (%s)", strerror(errno));
+                if (secontext) {
+                    freecon(secontext);
+                    setfscreatecon(NULL);
+                }
+                errno = sverrno;
                 return -1;
             }
         }
+        if (secontext) {
+            freecon(secontext);
+            setfscreatecon(NULL);
+        }
 
         if ((fd = open(filename, O_RDWR)) < 0) {
             SLOGE("Unable to open %s (%s)", filename, strerror(errno));
diff --git a/NetlinkManager.cpp b/NetlinkManager.cpp
index dbba303..d2e16b2 100644
--- a/NetlinkManager.cpp
+++ b/NetlinkManager.cpp
@@ -16,6 +16,7 @@
 
 #include <stdio.h>
 #include <errno.h>
+#include <string.h>
 
 #include <sys/socket.h>
 #include <sys/select.h>
diff --git a/Process.cpp b/Process.cpp
index 08be28e..b675436 100644
--- a/Process.cpp
+++ b/Process.cpp
@@ -191,7 +191,6 @@
     }
 
     while ((de = readdir(dir))) {
-        int killed = 0;
         int pid = getPid(de->d_name);
         char name[PATH_MAX];
 
diff --git a/Volume.cpp b/Volume.cpp
index ca56d1c..ce4ed1e 100644
--- a/Volume.cpp
+++ b/Volume.cpp
@@ -19,6 +19,7 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <mntent.h>
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -48,6 +49,7 @@
 #include "Fat.h"
 #include "Process.h"
 #include "cryptfs.h"
+#include "sehandle.h"
 
 extern "C" void dos_partition_dec(void const *pp, struct dos_partition *d);
 extern "C" void dos_partition_enc(void *pp, struct dos_partition *d);
@@ -219,13 +221,30 @@
 }
 
 int Volume::createDeviceNode(const char *path, int major, int minor) {
+    char *secontext = NULL;
     mode_t mode = 0660 | S_IFBLK;
     dev_t dev = (major << 8) | minor;
+    int rc;
+    if (sehandle) {
+        rc = selabel_lookup(sehandle, &secontext, path, S_IFBLK);
+        if (rc == 0)
+            setfscreatecon(secontext);
+    }
     if (mknod(path, mode, dev) < 0) {
         if (errno != EEXIST) {
+            int sverrno = errno;
+            if (secontext) {
+                freecon(secontext);
+                setfscreatecon(NULL);
+            }
+            errno = sverrno;
             return -1;
         }
     }
+    if (secontext) {
+        setfscreatecon(NULL);
+        freecon(secontext);
+    }
     return 0;
 }
 
@@ -252,7 +271,7 @@
     dev_t diskNode = getDiskDevice();
     dev_t partNode =
         MKDEV(MAJOR(diskNode),
-              MINOR(diskNode) + (formatEntireDevice ? 1 : mPartIdx));
+              MINOR(diskNode) + (formatEntireDevice ? 0 : mPartIdx));
 
     setState(Volume::State_Formatting);
 
@@ -288,33 +307,27 @@
 }
 
 bool Volume::isMountpointMounted(const char *path) {
-    char device[256];
-    char mount_path[256];
-    char rest[256];
-    FILE *fp;
-    char line[1024];
-
-    if (!(fp = fopen("/proc/mounts", "r"))) {
+    FILE *fp = setmntent("/proc/mounts", "r");
+    if (fp == NULL) {
         SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
         return false;
     }
 
-    while(fgets(line, sizeof(line), fp)) {
-        line[strlen(line)-1] = '\0';
-        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
-        if (!strcmp(mount_path, path)) {
-            fclose(fp);
-            return true;
+    bool found_path = false;
+    mntent* mentry;
+    while ((mentry = getmntent(fp)) != NULL) {
+        if (strcmp(mentry->mnt_dir, path) == 0) {
+            found_path = true;
+            break;
         }
     }
-
-    fclose(fp);
-    return false;
+    endmntent(fp);
+    return found_path;
 }
 
 int Volume::mountVol() {
     dev_t deviceNodes[4];
-    int n, i, rc = 0;
+    int n, i;
     char errmsg[255];
 
     int flags = getFlags();
@@ -436,7 +449,6 @@
         }
 
         errno = 0;
-        int gid;
 
         if (Fat::doMount(devicePath, getMountpoint(), false, false, false,
                 AID_MEDIA_RW, AID_MEDIA_RW, 0007, true)) {
@@ -531,8 +543,6 @@
 }
 
 int Volume::unmountVol(bool force, bool revert) {
-    int i, rc;
-
     int flags = getFlags();
     bool providesAsec = (flags & VOL_PROVIDES_ASEC) != 0;
 
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index 14f1509..4c5bb58 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -14,18 +14,19 @@
  * limitations under the License.
  */
 
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+#include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <fts.h>
-#include <unistd.h>
+#include <mntent.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mount.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <sys/mount.h>
-#include <sys/ioctl.h>
-#include <dirent.h>
+#include <unistd.h>
 
 #include <linux/kdev_t.h>
 
@@ -238,7 +239,9 @@
 }
 
 void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
+#ifdef NETLINK_DEBUG
     const char *devpath = evt->findParam("DEVPATH");
+#endif
 
     /* Lookup a volume to handle this device */
     VolumeCollection::iterator it;
@@ -1200,14 +1203,12 @@
     int dirfd = open(dir, O_DIRECTORY);
     if (dirfd < 0) {
         SLOGE("Couldn't open internal ASEC dir (%s)", strerror(errno));
-        return -1;
+        return false;
     }
 
-    bool ret = false;
-
-    if (!faccessat(dirfd, asecName, F_OK, AT_SYMLINK_NOFOLLOW)) {
-        ret = true;
-    }
+    struct stat sb;
+    bool ret = (fstatat(dirfd, asecName, &sb, AT_SYMLINK_NOFOLLOW) == 0)
+        && S_ISREG(sb.st_mode);
 
     close(dirfd);
 
@@ -1216,8 +1217,6 @@
 
 int VolumeManager::findAsec(const char *id, char *asecPath, size_t asecPathLen,
         const char **directory) const {
-    int dirfd, fd;
-    const int idLen = strlen(id);
     char *asecName;
 
     if (!isLegalAsecId(id)) {
@@ -1297,7 +1296,7 @@
 
     char dmDevice[255];
     bool cleanupDm = false;
-    int fd;
+
     unsigned int nr_sec = 0;
     struct asec_superblock sb;
 
@@ -1466,13 +1465,8 @@
 }
 
 int VolumeManager::listMountedObbs(SocketClient* cli) {
-    char device[256];
-    char mount_path[256];
-    char rest[256];
-    FILE *fp;
-    char line[1024];
-
-    if (!(fp = fopen("/proc/mounts", "r"))) {
+    FILE *fp = setmntent("/proc/mounts", "r");
+    if (fp == NULL) {
         SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
         return -1;
     }
@@ -1484,17 +1478,10 @@
     loopDir[loopDirLen++] = '/';
     loopDir[loopDirLen] = '\0';
 
-    while(fgets(line, sizeof(line), fp)) {
-        line[strlen(line)-1] = '\0';
-
-        /*
-         * Should look like:
-         * /dev/block/loop0 /mnt/obb/fc99df1323fd36424f864dcb76b76d65 ...
-         */
-        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
-
-        if (!strncmp(mount_path, loopDir, loopDirLen)) {
-            int fd = open(device, O_RDONLY);
+    mntent* mentry;
+    while ((mentry = getmntent(fp)) != NULL) {
+        if (!strncmp(mentry->mnt_dir, loopDir, loopDirLen)) {
+            int fd = open(mentry->mnt_fsname, O_RDONLY);
             if (fd >= 0) {
                 struct loop_info64 li;
                 if (ioctl(fd, LOOP_GET_STATUS64, &li) >= 0) {
@@ -1505,8 +1492,7 @@
             }
         }
     }
-
-    fclose(fp);
+    endmntent(fp);
     return 0;
 }
 
@@ -1807,28 +1793,22 @@
 
 bool VolumeManager::isMountpointMounted(const char *mp)
 {
-    char device[256];
-    char mount_path[256];
-    char rest[256];
-    FILE *fp;
-    char line[1024];
-
-    if (!(fp = fopen("/proc/mounts", "r"))) {
+    FILE *fp = setmntent("/proc/mounts", "r");
+    if (fp == NULL) {
         SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
         return false;
     }
 
-    while(fgets(line, sizeof(line), fp)) {
-        line[strlen(line)-1] = '\0';
-        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
-        if (!strcmp(mount_path, mp)) {
-            fclose(fp);
-            return true;
+    bool found_mp = false;
+    mntent* mentry;
+    while ((mentry = getmntent(fp)) != NULL) {
+        if (strcmp(mentry->mnt_dir, mp) == 0) {
+            found_mp = true;
+            break;
         }
     }
-
-    fclose(fp);
-    return false;
+    endmntent(fp);
+    return found_mp;
 }
 
 int VolumeManager::cleanupAsec(Volume *v, bool force) {
diff --git a/cryptfs.c b/cryptfs.c
index a424b69..6f860e4 100644
--- a/cryptfs.c
+++ b/cryptfs.c
@@ -36,6 +36,7 @@
 #include <string.h>
 #include <sys/mount.h>
 #include <openssl/evp.h>
+#include <openssl/sha.h>
 #include <errno.h>
 #include <ext4.h>
 #include <linux/kdev_t.h>
@@ -479,7 +480,7 @@
 static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
 {
   int fd;
-  unsigned int nr_sec, cnt;
+  unsigned int cnt;
   /* starting_off is set to the SEEK_SET offset
    * where the crypto structure starts
    */
@@ -573,6 +574,7 @@
         /* Need to initialize the persistent data area */
         if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
             SLOGE("Cannot seek to persisent data offset\n");
+            free(pdata);
             return;
         }
         /* Write all zeros to the first copy, making it invalid */
@@ -587,6 +589,7 @@
         crypt_ftr->persist_data_offset[0] = pdata_offset;
         crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
         crypt_ftr->minor_version = 1;
+        free(pdata);
     }
 
     if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
@@ -618,7 +621,7 @@
 static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
 {
   int fd;
-  unsigned int nr_sec, cnt;
+  unsigned int cnt;
   off64_t starting_off;
   int rc = -1;
   char *fname = NULL;
@@ -811,7 +814,6 @@
     char *fname;
     off64_t write_offset;
     off64_t erase_offset;
-    int found = 0;
     int fd;
     int ret;
 
@@ -874,13 +876,13 @@
     }
 
     /* Write the new copy first, if successful, then erase the old copy */
-    if (lseek(fd, write_offset, SEEK_SET) < 0) {
+    if (lseek64(fd, write_offset, SEEK_SET) < 0) {
         SLOGE("Cannot seek to write persistent data");
         goto err2;
     }
     if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
         (int) crypt_ftr.persist_data_size) {
-        if (lseek(fd, erase_offset, SEEK_SET) < 0) {
+        if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
             SLOGE("Cannot seek to erase previous persistent data");
             goto err2;
         }
@@ -979,7 +981,7 @@
                                      char *real_blk_name, const char *name, int fd,
                                      char *extra_params)
 {
-  char buffer[DM_CRYPT_BUF_SIZE];
+  _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
   struct dm_ioctl *io;
   struct dm_target_spec *tgt;
   char *crypt_params;
@@ -1036,7 +1038,6 @@
     char buffer[DM_CRYPT_BUF_SIZE];
     struct dm_ioctl *io;
     struct dm_target_versions *v;
-    int i;
 
     io = (struct dm_ioctl *) buffer;
 
@@ -1072,13 +1073,9 @@
                                     char *real_blk_name, char *crypto_blk_name, const char *name)
 {
   char buffer[DM_CRYPT_BUF_SIZE];
-  char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
-  char *crypt_params;
   struct dm_ioctl *io;
-  struct dm_target_spec *tgt;
   unsigned int minor;
   int fd=0;
-  int i;
   int retval = -1;
   int version[3];
   char *extra_params;
@@ -1302,7 +1299,8 @@
     }
 
     /* Initialize the decryption engine */
-    if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
+    EVP_CIPHER_CTX_init(&e_ctx);
+    if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
         SLOGE("EVP_EncryptInit failed\n");
         return -1;
     }
@@ -1314,7 +1312,7 @@
         SLOGE("EVP_EncryptUpdate failed\n");
         return -1;
     }
-    if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
+    if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
         SLOGE("EVP_EncryptFinal failed\n");
         return -1;
     }
@@ -1364,7 +1362,8 @@
   }
 
   /* Initialize the decryption engine */
-  if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
+  EVP_CIPHER_CTX_init(&d_ctx);
+  if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
     return -1;
   }
   EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
@@ -1373,7 +1372,7 @@
                             encrypted_master_key, KEY_LEN_BYTES)) {
     return -1;
   }
-  if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
+  if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
     return -1;
   }
 
@@ -1433,8 +1432,6 @@
         struct crypt_mnt_ftr *crypt_ftr) {
     int fd;
     unsigned char key_buf[KEY_LEN_BYTES];
-    EVP_CIPHER_CTX e_ctx;
-    int encrypted_len, final_len;
 
     /* Get some random bits for a key */
     fd = open("/dev/urandom", O_RDONLY);
@@ -1560,13 +1557,8 @@
 /* returns < 0 on failure */
 static int cryptfs_restart_internal(int restart_main)
 {
-    char fs_type[32];
-    char real_blkdev[MAXPATHLEN];
     char crypto_blkdev[MAXPATHLEN];
-    char fs_options[256];
-    unsigned long mnt_flags;
-    struct stat statbuf;
-    int rc = -1, i;
+    int rc = -1;
     static int restart_successful = 0;
 
     /* Validate that it's OK to call this routine */
@@ -1747,8 +1739,6 @@
   char tmp_mount_point[64];
   unsigned int orig_failed_decrypt_count;
   int rc;
-  kdf_func kdf;
-  void *kdf_params;
   int use_keymaster = 0;
   int upgrade = 0;
   unsigned char* intermediate_key = 0;
@@ -1902,7 +1892,8 @@
     char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
     struct crypt_mnt_ftr sd_crypt_ftr;
     struct stat statbuf;
-    int nr_sec, fd;
+    unsigned int nr_sec;
+    int fd;
 
     sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
 
@@ -2576,7 +2567,6 @@
                                        off64_t tot_size,
                                        off64_t previously_encrypted_upto)
 {
-    u32 i;
     struct encryptGroupsData data;
     struct f2fs_info *f2fs_info = NULL;
     int rc = ENABLE_INPLACE_ERR_OTHER;
@@ -2870,7 +2860,7 @@
                                       int previously_encrypted_upto)
 {
     off64_t cur_encryption_done=0, tot_encryption_size=0;
-    int i, rc = -1;
+    int rc = -1;
 
     if (!is_battery_ok_to_start()) {
         SLOGW("Not starting encryption due to low battery");
@@ -2925,7 +2915,7 @@
     char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
     unsigned long nr_sec;
     unsigned char decrypted_master_key[KEY_LEN_BYTES];
-    int rc=-1, fd, i, ret;
+    int rc=-1, fd, i;
     struct crypt_mnt_ftr crypt_ftr;
     struct crypt_persist_data *pdata;
     char encrypted_state[PROPERTY_VALUE_MAX];
@@ -3313,7 +3303,6 @@
 int cryptfs_changepw(int crypt_type, const char *newpw)
 {
     struct crypt_mnt_ftr crypt_ftr;
-    unsigned char decrypted_master_key[KEY_LEN_BYTES];
 
     /* This is only allowed after we've successfully decrypted the master key */
     if (!master_key_saved) {
@@ -3450,7 +3439,6 @@
  * sequence and its index is greater than or equal to index. Return 0 otherwise.
  */
 static int match_multi_entry(const char *key, const char *field, unsigned index) {
-    unsigned int i;
     unsigned int field_len;
     unsigned int key_index;
     field_len = strlen(field);
@@ -3539,7 +3527,6 @@
 int cryptfs_getfield(const char *fieldname, char *value, int len)
 {
     char temp_value[PROPERTY_VALUE_MAX];
-    char real_blkdev[MAXPATHLEN];
     /* CRYPTO_GETFIELD_OK is success,
      * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
      * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
@@ -3600,9 +3587,6 @@
 /* Set the value of the specified field. */
 int cryptfs_setfield(const char *fieldname, const char *value)
 {
-    struct crypt_persist_data stored_pdata;
-    struct crypt_persist_data *pdata_p;
-    struct crypt_mnt_ftr crypt_ftr;
     char encrypted_state[PROPERTY_VALUE_MAX];
     /* 0 is success, negative values are error */
     int rc = CRYPTO_SETFIELD_ERROR_OTHER;
diff --git a/cryptfs.h b/cryptfs.h
index d873c26..bce1dd3 100644
--- a/cryptfs.h
+++ b/cryptfs.h
@@ -27,7 +27,6 @@
  */
 
 #include <cutils/properties.h>
-#include <openssl/sha.h>
 
 /* The current cryptfs version */
 #define CURRENT_MAJOR_VERSION 1
@@ -84,6 +83,10 @@
 /* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
 #define __le8  unsigned char
 
+#if !defined(SHA256_DIGEST_LENGTH)
+#define SHA256_DIGEST_LENGTH 32
+#endif
+
 struct crypt_mnt_ftr {
   __le32 magic;         /* See above */
   __le16 major_version;
diff --git a/fstrim.c b/fstrim.c
index 895d44f..8a02c77 100644
--- a/fstrim.c
+++ b/fstrim.c
@@ -16,6 +16,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <errno.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/ioctl.h>
diff --git a/main.cpp b/main.cpp
index d4b7d28..c07f48d 100644
--- a/main.cpp
+++ b/main.cpp
@@ -36,6 +36,7 @@
 #include "NetlinkManager.h"
 #include "DirectVolume.h"
 #include "cryptfs.h"
+#include "sehandle.h"
 
 static int process_config(VolumeManager *vm);
 static void coldboot(const char *path);
@@ -43,6 +44,8 @@
 #define FSTAB_PREFIX "/fstab."
 struct fstab *fstab;
 
+struct selabel_handle *sehandle;
+
 int main() {
 
     VolumeManager *vm;
@@ -51,6 +54,10 @@
 
     SLOGI("Vold 2.1 (the revenge) firing up");
 
+    sehandle = selinux_android_file_context_handle();
+    if (sehandle)
+        selinux_android_set_sehandle(sehandle);
+
     mkdir("/dev/block/vold", 0755);
 
     /* For when cryptfs checks and mounts an encrypted filesystem */
diff --git a/sehandle.h b/sehandle.h
new file mode 100644
index 0000000..f59d7eb
--- /dev/null
+++ b/sehandle.h
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+
+#ifndef _SEHANDLE_H
+#define _SEHANDLE_H
+
+#include <selinux/android.h>
+
+extern struct selabel_handle *sehandle;
+
+#endif
diff --git a/tests/Android.mk b/tests/Android.mk
index 8ae4b5d..f974e7f 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -1,36 +1,19 @@
 # Build the unit tests.
 LOCAL_PATH := $(call my-dir)
+
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
-test_src_files := \
-	VolumeManager_test.cpp
+LOCAL_C_INCLUDES := \
+    system/core/fs_mgr/include
 
-shared_libraries := \
-	liblog \
-	libstlport \
-	libcrypto
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libcrypto \
 
-static_libraries := \
-	libvold \
-	libgtest \
-	libgtest_main
+LOCAL_STATIC_LIBRARIES := libvold
+LOCAL_SRC_FILES := VolumeManager_test.cpp
+LOCAL_MODULE := vold_tests
+LOCAL_MODULE_TAGS := eng tests
 
-c_includes := \
-	external/openssl/include \
-	bionic \
-	bionic/libstdc++/include \
-	external/gtest/include \
-	external/stlport/stlport
-
-module_tags := eng tests
-
-$(foreach file,$(test_src_files), \
-    $(eval include $(CLEAR_VARS)) \
-    $(eval LOCAL_SHARED_LIBRARIES := $(shared_libraries)) \
-    $(eval LOCAL_STATIC_LIBRARIES := $(static_libraries)) \
-    $(eval LOCAL_C_INCLUDES := $(c_includes)) \
-    $(eval LOCAL_SRC_FILES := $(file)) \
-    $(eval LOCAL_MODULE := $(notdir $(file:%.cpp=%))) \
-    $(eval LOCAL_MODULE_TAGS := $(module_tags)) \
-    $(eval include $(BUILD_EXECUTABLE)) \
-)
+include $(BUILD_NATIVE_TEST)