am 3dba40da: (-s ours) am d4208f9f: remove the notion of "root path"; support mixed flash types (do not merge)

Merge commit '3dba40da1e533c6f419857e4274d9d9dd55868b6'

* commit '3dba40da1e533c6f419857e4274d9d9dd55868b6':
  remove the notion of "root path"; support mixed flash types (do not merge)
diff --git a/Android.mk b/Android.mk
index e6c3547..e8e7a79 100644
--- a/Android.mk
+++ b/Android.mk
@@ -15,6 +15,8 @@
     verifier.c \
     encryptedfs_provisioning.c
 
+LOCAL_SRC_FILES += test_roots.c
+
 LOCAL_MODULE := recovery
 
 LOCAL_FORCE_STATIC_EXECUTABLE := true
@@ -22,6 +24,14 @@
 RECOVERY_API_VERSION := 3
 LOCAL_CFLAGS += -DRECOVERY_API_VERSION=$(RECOVERY_API_VERSION)
 
+LOCAL_STATIC_LIBRARIES :=
+
+ifeq ($(TARGET_USERIMAGES_USE_EXT4), true)
+LOCAL_CFLAGS += -DUSE_EXT4
+LOCAL_C_INCLUDES += system/extras/ext4_utils
+LOCAL_STATIC_LIBRARIES += libext4_utils libz
+endif
+
 # This binary is in the recovery ramdisk, which is otherwise a copy of root.
 # It gets copied there in config/Makefile.  LOCAL_MODULE_TAGS suppresses
 # a (redundant) copy of the binary in /system/bin for user builds.
@@ -29,19 +39,15 @@
 
 LOCAL_MODULE_TAGS := eng
 
-LOCAL_STATIC_LIBRARIES :=
 ifeq ($(TARGET_RECOVERY_UI_LIB),)
   LOCAL_SRC_FILES += default_recovery_ui.c
 else
   LOCAL_STATIC_LIBRARIES += $(TARGET_RECOVERY_UI_LIB)
 endif
-LOCAL_STATIC_LIBRARIES += libext4_utils libz
 LOCAL_STATIC_LIBRARIES += libminzip libunz libmtdutils libmincrypt
 LOCAL_STATIC_LIBRARIES += libminui libpixelflinger_static libpng libcutils
 LOCAL_STATIC_LIBRARIES += libstdc++ libc
 
-LOCAL_C_INCLUDES += system/extras/ext4_utils
-
 include $(BUILD_EXECUTABLE)
 
 
@@ -61,6 +67,7 @@
 
 
 include $(commands_recovery_local_path)/minui/Android.mk
+include $(commands_recovery_local_path)/minelf/Android.mk
 include $(commands_recovery_local_path)/minzip/Android.mk
 include $(commands_recovery_local_path)/mtdutils/Android.mk
 include $(commands_recovery_local_path)/tools/Android.mk
diff --git a/applypatch/Android.mk b/applypatch/Android.mk
index e91e4bf..eff1d77 100644
--- a/applypatch/Android.mk
+++ b/applypatch/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_SRC_FILES := main.c
 LOCAL_MODULE := applypatch
 LOCAL_C_INCLUDES += bootable/recovery
-LOCAL_STATIC_LIBRARIES += libapplypatch libmtdutils libmincrypt libbz
+LOCAL_STATIC_LIBRARIES += libapplypatch libmtdutils libmincrypt libbz libminelf
 LOCAL_SHARED_LIBRARIES += libz libcutils libstdc++ libc
 
 include $(BUILD_EXECUTABLE)
@@ -43,7 +43,7 @@
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 LOCAL_MODULE_TAGS := eng
 LOCAL_C_INCLUDES += bootable/recovery
-LOCAL_STATIC_LIBRARIES += libapplypatch libmtdutils libmincrypt libbz
+LOCAL_STATIC_LIBRARIES += libapplypatch libmtdutils libmincrypt libbz libminelf
 LOCAL_STATIC_LIBRARIES += libz libcutils libstdc++ libc
 
 include $(BUILD_EXECUTABLE)
diff --git a/applypatch/applypatch.c b/applypatch/applypatch.c
index fd8153a..1060913 100644
--- a/applypatch/applypatch.c
+++ b/applypatch/applypatch.c
@@ -30,16 +30,21 @@
 #include "mtdutils/mtdutils.h"
 #include "edify/expr.h"
 
-static int SaveFileContents(const char* filename, FileContents file);
+int SaveFileContents(const char* filename, FileContents file);
 static int LoadPartitionContents(const char* filename, FileContents* file);
 int ParseSha1(const char* str, uint8_t* digest);
 static ssize_t FileSink(unsigned char* data, ssize_t len, void* token);
 
 static int mtd_partitions_scanned = 0;
 
-// Read a file into memory; store it and its associated metadata in
-// *file.  Return 0 on success.
-int LoadFileContents(const char* filename, FileContents* file) {
+// Read a file into memory; optionally (retouch_flag == RETOUCH_DO_MASK) mask
+// the retouched entries back to their original value (such that SHA-1 checks
+// don't fail due to randomization); store the file contents and associated
+// metadata in *file.
+//
+// Return 0 on success.
+int LoadFileContents(const char* filename, FileContents* file,
+                     int retouch_flag) {
     file->data = NULL;
 
     // A special 'filename' beginning with "MTD:" or "EMMC:" means to
@@ -75,6 +80,20 @@
     }
     fclose(f);
 
+    // apply_patch[_check] functions are blind to randomization. Randomization
+    // is taken care of in [Undo]RetouchBinariesFn. If there is a mismatch
+    // within a file, this means the file is assumed "corrupt" for simplicity.
+    if (retouch_flag) {
+        int32_t desired_offset = 0;
+        if (retouch_mask_data(file->data, file->size,
+                              &desired_offset, NULL) != RETOUCH_DATA_MATCHED) {
+            printf("error trying to mask retouch entries\n");
+            free(file->data);
+            file->data = NULL;
+            return -1;
+        }
+    }
+
     SHA(file->data, file->size, file->sha1);
     return 0;
 }
@@ -303,7 +322,7 @@
 
 // Save the contents of the given FileContents object under the given
 // filename.  Return 0 on success.
-static int SaveFileContents(const char* filename, FileContents file) {
+int SaveFileContents(const char* filename, FileContents file) {
     int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
     if (fd < 0) {
         printf("failed to open \"%s\" for write: %s\n",
@@ -477,7 +496,7 @@
     // LoadFileContents is successful.  (Useful for reading
     // partitions, where the filename encodes the sha1s; no need to
     // check them twice.)
-    if (LoadFileContents(filename, &file) != 0 ||
+    if (LoadFileContents(filename, &file, RETOUCH_DO_MASK) != 0 ||
         (num_patches > 0 &&
          FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
         printf("file \"%s\" doesn't have any of expected "
@@ -491,7 +510,7 @@
         // exists and matches the sha1 we're looking for, the check still
         // passes.
 
-        if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
+        if (LoadFileContents(CACHE_TEMP_SOURCE, &file, RETOUCH_DO_MASK) != 0) {
             printf("failed to load cache file\n");
             return 1;
         }
@@ -617,7 +636,8 @@
     int made_copy = 0;
 
     // We try to load the target file into the source_file object.
-    if (LoadFileContents(target_filename, &source_file) == 0) {
+    if (LoadFileContents(target_filename, &source_file,
+                         RETOUCH_DO_MASK) == 0) {
         if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
             // The early-exit case:  the patch was already applied, this file
             // has the desired hash, nothing for us to do.
@@ -633,7 +653,8 @@
         // Need to load the source file:  either we failed to load the
         // target file, or we did but it's different from the source file.
         free(source_file.data);
-        LoadFileContents(source_filename, &source_file);
+        LoadFileContents(source_filename, &source_file,
+                         RETOUCH_DO_MASK);
     }
 
     if (source_file.data != NULL) {
@@ -648,7 +669,8 @@
         free(source_file.data);
         printf("source file is bad; trying copy\n");
 
-        if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
+        if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file,
+                             RETOUCH_DO_MASK) < 0) {
             // fail.
             printf("failed to read copy file\n");
             return 1;
diff --git a/applypatch/applypatch.h b/applypatch/applypatch.h
index 10c0125..a78c89b 100644
--- a/applypatch/applypatch.h
+++ b/applypatch/applypatch.h
@@ -19,6 +19,7 @@
 
 #include <sys/stat.h>
 #include "mincrypt/sha.h"
+#include "minelf/Retouch.h"
 #include "edify/expr.h"
 
 typedef struct _Patch {
@@ -59,10 +60,12 @@
                      int num_patches,
                      char** const patch_sha1_str);
 
-// Read a file into memory; store it and its associated metadata in
-// *file.  Return 0 on success.
-int LoadFileContents(const char* filename, FileContents* file);
+int LoadFileContents(const char* filename, FileContents* file,
+                     int retouch_flag);
+int SaveFileContents(const char* filename, FileContents file);
 void FreeFileContents(FileContents* file);
+int FindMatchingPatch(uint8_t* sha1, char** const patch_sha1_str,
+                      int num_patches);
 
 // bsdiff.c
 void ShowBSDiffLicense();
diff --git a/applypatch/main.c b/applypatch/main.c
index 3917f86..7025a2e 100644
--- a/applypatch/main.c
+++ b/applypatch/main.c
@@ -74,7 +74,7 @@
             (*patches)[i] = NULL;
         } else {
             FileContents fc;
-            if (LoadFileContents(colon, &fc) != 0) {
+            if (LoadFileContents(colon, &fc, RETOUCH_DONT_MASK) != 0) {
                 goto abort;
             }
             (*patches)[i] = malloc(sizeof(Value));
diff --git a/bootloader.c b/bootloader.c
index 7da3f4e..1e66c3e 100644
--- a/bootloader.c
+++ b/bootloader.c
@@ -23,103 +23,145 @@
 #include <stdio.h>
 #include <string.h>
 
-static int get_bootloader_message_mtd(struct bootloader_message *out, const Volume* v);
-static int set_bootloader_message_mtd(const struct bootloader_message *in, const Volume* v);
-static int get_bootloader_message_block(struct bootloader_message *out, const Volume* v);
-static int set_bootloader_message_block(const struct bootloader_message *in, const Volume* v);
+static const char *CACHE_NAME = "CACHE:";
+static const char *MISC_NAME = "MISC:";
 
-int get_bootloader_message(struct bootloader_message *out) {
-    Volume* v = volume_for_path("/misc");
-    if (strcmp(v->fs_type, "mtd") == 0) {
-        return get_bootloader_message_mtd(out, v);
-    } else if (strcmp(v->fs_type, "block") == 0) {
-        return get_bootloader_message_block(out, v);
+#ifdef LOG_VERBOSE
+static void dump_data(const char *data, int len) {
+    int pos;
+    for (pos = 0; pos < len; ) {
+        printf("%05x: %02x", pos, data[pos]);
+        for (++pos; pos < len && (pos % 24) != 0; ++pos) {
+            printf(" %02x", data[pos]);
+        }
+        printf("\n");
     }
-    LOGE("unknown misc partition fs_type \"%s\"\n", v->fs_type);
-    return -1;
+}
+#endif
+
+#ifdef USE_EXT4
+// Strictly speaking this doesn't have anything to do with ext4; we
+// really just mean "misc is an emmc partition".  We should have a
+// more configurable way have describing partitions, filesystems, etc.
+
+static const char* MISC_PARTITION =
+    "/dev/block/platform/sdhci-tegra.3/by-name/misc";
+
+int get_bootloader_message(struct bootloader_message* out) {
+    FILE* f = fopen(MISC_PARTITION, "rb");
+    if (f == NULL) {
+        LOGE("Can't open %s\n(%s)\n", MISC_PARTITION, strerror(errno));
+        return -1;
+    }
+    struct bootloader_message temp;
+    int count = fread(&temp, sizeof(temp), 1, f);
+    if (count != 1) {
+        LOGE("Failed reading %s\n(%s)\n", MISC_PARTITION, strerror(errno));
+        return -1;
+    }
+    if (fclose(f) != 0) {
+        LOGE("Failed closing %s\n(%s)\n", MISC_PARTITION, strerror(errno));
+        return -1;
+    }
+    memcpy(out, &temp, sizeof(temp));
+    return 0;
 }
 
-int set_bootloader_message(const struct bootloader_message *in) {
-    Volume* v = volume_for_path("/misc");
-    if (strcmp(v->fs_type, "mtd") == 0) {
-        return set_bootloader_message_mtd(in, v);
-    } else if (strcmp(v->fs_type, "block") == 0) {
-        return set_bootloader_message_block(in, v);
+int set_bootloader_message(const struct bootloader_message* in) {
+    FILE* f = fopen(MISC_PARTITION, "wb");
+    if (f == NULL) {
+        LOGE("Can't open %s\n(%s)\n", MISC_PARTITION, strerror(errno));
+        return -1;
     }
-    LOGE("unknown misc partition fs_type \"%s\"\n", v->fs_type);
-    return -1;
+    int count = fwrite(in, sizeof(*in), 1, f);
+    if (count != 1) {
+        LOGE("Failed writing %s\n(%s)\n", MISC_PARTITION, strerror(errno));
+        return -1;
+    }
+    if (fclose(f) != 0) {
+        LOGE("Failed closing %s\n(%s)\n", MISC_PARTITION, strerror(errno));
+        return -1;
+    }
+    return 0;
 }
 
-// ------------------------------
-// for misc partitions on MTD
-// ------------------------------
+#else  // MTD partitions
 
 static const int MISC_PAGES = 3;         // number of pages to save
 static const int MISC_COMMAND_PAGE = 1;  // bootloader command is this page
 
-static int get_bootloader_message_mtd(struct bootloader_message *out,
-                                      const Volume* v) {
+int get_bootloader_message(struct bootloader_message *out) {
     size_t write_size;
-    mtd_scan_partitions();
-    const MtdPartition *part = mtd_find_partition_by_name(v->device);
+    const MtdPartition *part = get_root_mtd_partition(MISC_NAME);
     if (part == NULL || mtd_partition_info(part, NULL, NULL, &write_size)) {
-        LOGE("Can't find %s\n", v->device);
+        LOGE("Can't find %s\n", MISC_NAME);
         return -1;
     }
 
     MtdReadContext *read = mtd_read_partition(part);
     if (read == NULL) {
-        LOGE("Can't open %s\n(%s)\n", v->device, strerror(errno));
+        LOGE("Can't open %s\n(%s)\n", MISC_NAME, strerror(errno));
         return -1;
     }
 
     const ssize_t size = write_size * MISC_PAGES;
     char data[size];
     ssize_t r = mtd_read_data(read, data, size);
-    if (r != size) LOGE("Can't read %s\n(%s)\n", v->device, strerror(errno));
+    if (r != size) LOGE("Can't read %s\n(%s)\n", MISC_NAME, strerror(errno));
     mtd_read_close(read);
     if (r != size) return -1;
 
+#ifdef LOG_VERBOSE
+    printf("\n--- get_bootloader_message ---\n");
+    dump_data(data, size);
+    printf("\n");
+#endif
+
     memcpy(out, &data[write_size * MISC_COMMAND_PAGE], sizeof(*out));
     return 0;
 }
-static int set_bootloader_message_mtd(const struct bootloader_message *in,
-                                      const Volume* v) {
+
+int set_bootloader_message(const struct bootloader_message *in) {
     size_t write_size;
-    mtd_scan_partitions();
-    const MtdPartition *part = mtd_find_partition_by_name(v->device);
+    const MtdPartition *part = get_root_mtd_partition(MISC_NAME);
     if (part == NULL || mtd_partition_info(part, NULL, NULL, &write_size)) {
-        LOGE("Can't find %s\n", v->device);
+        LOGE("Can't find %s\n", MISC_NAME);
         return -1;
     }
 
     MtdReadContext *read = mtd_read_partition(part);
     if (read == NULL) {
-        LOGE("Can't open %s\n(%s)\n", v->device, strerror(errno));
+        LOGE("Can't open %s\n(%s)\n", MISC_NAME, strerror(errno));
         return -1;
     }
 
     ssize_t size = write_size * MISC_PAGES;
     char data[size];
     ssize_t r = mtd_read_data(read, data, size);
-    if (r != size) LOGE("Can't read %s\n(%s)\n", v->device, strerror(errno));
+    if (r != size) LOGE("Can't read %s\n(%s)\n", MISC_NAME, strerror(errno));
     mtd_read_close(read);
     if (r != size) return -1;
 
     memcpy(&data[write_size * MISC_COMMAND_PAGE], in, sizeof(*in));
 
+#ifdef LOG_VERBOSE
+    printf("\n--- set_bootloader_message ---\n");
+    dump_data(data, size);
+    printf("\n");
+#endif
+
     MtdWriteContext *write = mtd_write_partition(part);
     if (write == NULL) {
-        LOGE("Can't open %s\n(%s)\n", v->device, strerror(errno));
+        LOGE("Can't open %s\n(%s)\n", MISC_NAME, strerror(errno));
         return -1;
     }
     if (mtd_write_data(write, data, size) != size) {
-        LOGE("Can't write %s\n(%s)\n", v->device, strerror(errno));
+        LOGE("Can't write %s\n(%s)\n", MISC_NAME, strerror(errno));
         mtd_write_close(write);
         return -1;
     }
     if (mtd_write_close(write)) {
-        LOGE("Can't finish %s\n(%s)\n", v->device, strerror(errno));
+        LOGE("Can't finish %s\n(%s)\n", MISC_NAME, strerror(errno));
         return -1;
     }
 
@@ -127,47 +169,4 @@
     return 0;
 }
 
-
-// ------------------------------------
-// for misc partitions on block devices
-// ------------------------------------
-
-static int get_bootloader_message_block(struct bootloader_message *out,
-                                        const Volume* v) {
-    FILE* f = fopen(v->device, "rb");
-    if (f == NULL) {
-        LOGE("Can't open %s\n(%s)\n", v->device, strerror(errno));
-        return -1;
-    }
-    struct bootloader_message temp;
-    int count = fread(&temp, sizeof(temp), 1, f);
-    if (count != 1) {
-        LOGE("Failed reading %s\n(%s)\n", v->device, strerror(errno));
-        return -1;
-    }
-    if (fclose(f) != 0) {
-        LOGE("Failed closing %s\n(%s)\n", v->device, strerror(errno));
-        return -1;
-    }
-    memcpy(out, &temp, sizeof(temp));
-    return 0;
-}
-
-static int set_bootloader_message_block(const struct bootloader_message *in,
-                                        const Volume* v) {
-    FILE* f = fopen(v->device, "wb");
-    if (f == NULL) {
-        LOGE("Can't open %s\n(%s)\n", v->device, strerror(errno));
-        return -1;
-    }
-    int count = fwrite(in, sizeof(*in), 1, f);
-    if (count != 1) {
-        LOGE("Failed writing %s\n(%s)\n", v->device, strerror(errno));
-        return -1;
-    }
-    if (fclose(f) != 0) {
-        LOGE("Failed closing %s\n(%s)\n", v->device, strerror(errno));
-        return -1;
-    }
-    return 0;
-}
+#endif
diff --git a/common.h b/common.h
index 97e87ee..0c250f4 100644
--- a/common.h
+++ b/common.h
@@ -87,17 +87,4 @@
 #define STRINGIFY(x) #x
 #define EXPAND(x) STRINGIFY(x)
 
-typedef struct {
-    const char* mount_point;  // eg. "/cache".  must live in the root directory.
-
-    const char* fs_type;      // "yaffs2" or "ext4" or "vfat"
-
-    const char* device;       // MTD partition name if fs_type == "yaffs"
-                              // block device if fs_type == "ext4" or "vfat"
-
-    const char* device2;      // alternative device to try if fs_type
-                              // == "ext4" or "vfat" and mounting
-                              // 'device' fails
-} Volume;
-
 #endif  // RECOVERY_COMMON_H
diff --git a/default_recovery_ui.c b/default_recovery_ui.c
index ce12787..bcba888 100644
--- a/default_recovery_ui.c
+++ b/default_recovery_ui.c
@@ -24,7 +24,7 @@
                          NULL };
 
 char* MENU_ITEMS[] = { "reboot system now",
-                       "apply update from sdcard",
+                       "apply update from external storage",
                        "wipe data/factory reset",
                        "wipe cache partition",
                        NULL };
diff --git a/encryptedfs_provisioning.c b/encryptedfs_provisioning.c
index 601c817..2bcfec1 100644
--- a/encryptedfs_provisioning.c
+++ b/encryptedfs_provisioning.c
@@ -186,7 +186,7 @@
 int read_encrypted_fs_info(encrypted_fs_info *encrypted_fs_data) {
     int result;
     int value;
-    result = ensure_path_mounted("/data");
+    result = ensure_root_path_mounted("DATA:");
     if (result != 0) {
         LOGE("Secure FS: error mounting userdata partition.");
         return ENCRYPTED_FS_ERROR;
@@ -221,7 +221,7 @@
         return ENCRYPTED_FS_ERROR;
     }
 
-    result = ensure_path_unmounted("/data");
+    result = ensure_root_path_unmounted("DATA:");
     if (result != 0) {
         LOGE("Secure FS: error unmounting data partition.");
         return ENCRYPTED_FS_ERROR;
@@ -232,7 +232,7 @@
 
 int restore_encrypted_fs_info(encrypted_fs_info *encrypted_fs_data) {
     int result;
-    result = ensure_path_mounted("/data");
+    result = ensure_root_path_mounted("DATA:");
     if (result != 0) {
         LOGE("Secure FS: error mounting userdata partition.");
         return ENCRYPTED_FS_ERROR;
@@ -273,7 +273,7 @@
         return result;
     }
 
-    result = ensure_path_unmounted("/data");
+    result = ensure_root_path_unmounted("DATA:");
     if (result != 0) {
         LOGE("Secure FS: error unmounting data partition.");
         return ENCRYPTED_FS_ERROR;
@@ -281,3 +281,4 @@
 
     return ENCRYPTED_FS_OK;
 }
+
diff --git a/install.c b/install.c
index 5bb3a78..a56dbd0 100644
--- a/install.c
+++ b/install.c
@@ -234,19 +234,26 @@
 }
 
 int
-install_package(const char *path)
+install_package(const char *root_path)
 {
     ui_set_background(BACKGROUND_ICON_INSTALLING);
     ui_print("Finding update package...\n");
     ui_show_indeterminate_progress();
-    LOGI("Update location: %s\n", path);
+    LOGI("Update location: %s\n", root_path);
 
-    if (ensure_path_mounted(path) != 0) {
-        LOGE("Can't mount %s\n", path);
+    if (ensure_root_path_mounted(root_path) != 0) {
+        LOGE("Can't mount %s\n", root_path);
+        return INSTALL_CORRUPT;
+    }
+
+    char path[PATH_MAX] = "";
+    if (translate_root_path(root_path, path, sizeof(path)) == NULL) {
+        LOGE("Bad path %s\n", root_path);
         return INSTALL_CORRUPT;
     }
 
     ui_print("Opening update package...\n");
+    LOGI("Update file path: %s\n", path);
 
     int numKeys;
     RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
diff --git a/minelf/Android.mk b/minelf/Android.mk
new file mode 100644
index 0000000..0f41ff5
--- /dev/null
+++ b/minelf/Android.mk
@@ -0,0 +1,27 @@
+# Copyright (C) 2009 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+	Retouch.c
+
+LOCAL_C_INCLUDES += bootable/recovery
+
+LOCAL_MODULE := libminelf
+
+LOCAL_CFLAGS += -Wall
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/minelf/Retouch.c b/minelf/Retouch.c
new file mode 100644
index 0000000..33809cd
--- /dev/null
+++ b/minelf/Retouch.c
@@ -0,0 +1,406 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
+#include <strings.h>
+#include "Retouch.h"
+#include "applypatch/applypatch.h"
+
+typedef struct {
+    int32_t mmap_addr;
+    char tag[4]; /* 'P', 'R', 'E', ' ' */
+} prelink_info_t __attribute__((packed));
+
+#define false 0
+#define true 1
+
+static int32_t offs_prev;
+static uint32_t cont_prev;
+
+static void init_compression_state(void) {
+    offs_prev = 0;
+    cont_prev = 0;
+}
+
+// For details on the encoding used for relocation lists, please
+// refer to build/tools/retouch/retouch-prepare.c. The intent is to
+// save space by removing most of the inherent redundancy.
+
+static void decode_bytes(uint8_t *encoded_bytes, int encoded_size,
+                         int32_t *dst_offset, uint32_t *dst_contents) {
+    if (encoded_size == 2) {
+        *dst_offset = offs_prev + (((encoded_bytes[0]&0x60)>>5)+1)*4;
+
+        // if the original was negative, we need to 1-pad before applying delta
+        int32_t tmp = (((encoded_bytes[0] & 0x0000001f) << 8) |
+                       encoded_bytes[1]);
+        if (tmp & 0x1000) tmp = 0xffffe000 | tmp;
+        *dst_contents = cont_prev + tmp;
+    } else if (encoded_size == 3) {
+        *dst_offset = offs_prev + (((encoded_bytes[0]&0x30)>>4)+1)*4;
+
+        // if the original was negative, we need to 1-pad before applying delta
+        int32_t tmp = (((encoded_bytes[0] & 0x0000000f) << 16) |
+                       (encoded_bytes[1] << 8) |
+                       encoded_bytes[2]);
+        if (tmp & 0x80000) tmp = 0xfff00000 | tmp;
+        *dst_contents = cont_prev + tmp;
+    } else {
+        *dst_offset =
+          (encoded_bytes[0]<<24) |
+          (encoded_bytes[1]<<16) |
+          (encoded_bytes[2]<<8) |
+          encoded_bytes[3];
+        if (*dst_offset == 0x3fffffff) *dst_offset = -1;
+        *dst_contents =
+          (encoded_bytes[4]<<24) |
+          (encoded_bytes[5]<<16) |
+          (encoded_bytes[6]<<8) |
+          encoded_bytes[7];
+    }
+}
+
+static uint8_t *decode_in_memory(uint8_t *encoded_bytes,
+                                 int32_t *offset, uint32_t *contents) {
+    int input_size, charIx;
+    uint8_t input[8];
+
+    input[0] = *(encoded_bytes++);
+    if (input[0] & 0x80)
+        input_size = 2;
+    else if (input[0] & 0x40)
+        input_size = 3;
+    else
+        input_size = 8;
+
+    // we already read one byte..
+    charIx = 1;
+    while (charIx < input_size) {
+        input[charIx++] = *(encoded_bytes++);
+    }
+
+    // depends on the decoder state!
+    decode_bytes(input, input_size, offset, contents);
+
+    offs_prev = *offset;
+    cont_prev = *contents;
+
+    return encoded_bytes;
+}
+
+int retouch_mask_data(uint8_t *binary_object,
+                      int32_t binary_size,
+                      int32_t *desired_offset,
+                      int32_t *retouch_offset) {
+    retouch_info_t *r_info;
+    prelink_info_t *p_info;
+
+    int32_t target_offset = 0;
+    if (desired_offset) target_offset = *desired_offset;
+
+    int32_t p_offs = binary_size-sizeof(prelink_info_t); // prelink_info_t
+    int32_t r_offs = p_offs-sizeof(retouch_info_t); // retouch_info_t
+    int32_t b_offs; // retouch data blob
+
+    // If not retouched, we say it was a match. This might get invoked on
+    // non-retouched binaries, so that's why we need to do this.
+    if (retouch_offset != NULL) *retouch_offset = target_offset;
+    if (r_offs < 0) return (desired_offset == NULL) ?
+                      RETOUCH_DATA_NOTAPPLICABLE : RETOUCH_DATA_MATCHED;
+    p_info = (prelink_info_t *)(binary_object+p_offs);
+    r_info = (retouch_info_t *)(binary_object+r_offs);
+    if (strncmp(p_info->tag, "PRE ", 4) ||
+        strncmp(r_info->tag, "RETOUCH ", 8))
+        return (desired_offset == NULL) ?
+          RETOUCH_DATA_NOTAPPLICABLE : RETOUCH_DATA_MATCHED;
+
+    b_offs = r_offs-r_info->blob_size;
+    if (b_offs < 0) {
+        printf("negative binary offset: %d = %d - %d\n",
+               b_offs, r_offs, r_info->blob_size);
+        return RETOUCH_DATA_ERROR;
+    }
+    uint8_t *b_ptr = binary_object+b_offs;
+
+    // Retouched: let's go through the work then.
+    int32_t offset_candidate = target_offset;
+    bool offset_set = false, offset_mismatch = false;
+    init_compression_state();
+    while (b_ptr < (uint8_t *)r_info) {
+        int32_t retouch_entry_offset;
+        uint32_t *retouch_entry;
+        uint32_t retouch_original_value;
+
+        b_ptr = decode_in_memory(b_ptr,
+                                 &retouch_entry_offset,
+                                 &retouch_original_value);
+        if (retouch_entry_offset < (-1) ||
+            retouch_entry_offset >= b_offs) {
+            printf("bad retouch_entry_offset: %d", retouch_entry_offset);
+            return RETOUCH_DATA_ERROR;
+        }
+
+        // "-1" means this is the value in prelink_info_t, which also gets
+        // randomized.
+        if (retouch_entry_offset == -1)
+            retouch_entry = (uint32_t *)&(p_info->mmap_addr);
+        else
+            retouch_entry = (uint32_t *)(binary_object+retouch_entry_offset);
+
+        if (desired_offset)
+            *retouch_entry = retouch_original_value + target_offset;
+
+        // Infer the randomization shift, compare to previously inferred.
+        int32_t offset_of_this_entry = (int32_t)(*retouch_entry-
+                                                 retouch_original_value);
+        if (!offset_set) {
+            offset_candidate = offset_of_this_entry;
+            offset_set = true;
+        } else {
+            if (offset_candidate != offset_of_this_entry) {
+                offset_mismatch = true;
+                printf("offset is mismatched: %d, this entry is %d,"
+                       " original 0x%x @ 0x%x",
+                       offset_candidate, offset_of_this_entry,
+                       retouch_original_value, retouch_entry_offset);
+            }
+        }
+    }
+    if (b_ptr > (uint8_t *)r_info) {
+        printf("b_ptr went too far: %p, while r_info is %p",
+               b_ptr, r_info);
+        return RETOUCH_DATA_ERROR;
+    }
+
+    if (offset_mismatch) return RETOUCH_DATA_MISMATCHED;
+    if (retouch_offset != NULL) *retouch_offset = offset_candidate;
+    return RETOUCH_DATA_MATCHED;
+}
+
+// On success, _override is set to the offset that was actually applied.
+// This implies that once we randomize to an offset we stick with it.
+// This in turn is necessary in order to guarantee recovery after crash.
+bool retouch_one_library(const char *binary_name,
+                         const char *binary_sha1,
+                         int32_t retouch_offset,
+                         int32_t *retouch_offset_override) {
+    bool success = true;
+    int result;
+
+    FileContents file;
+    file.data = NULL;
+
+    char binary_name_atomic[strlen(binary_name)+10];
+    strcpy(binary_name_atomic, binary_name);
+    strcat(binary_name_atomic, ".atomic");
+
+    // We need a path that exists for calling statfs() later.
+    //
+    // Assume that binary_name (eg "/system/app/Foo.apk") is located
+    // on the same filesystem as its top-level directory ("/system").
+    char target_fs[strlen(binary_name)+1];
+    char* slash = strchr(binary_name+1, '/');
+    if (slash != NULL) {
+        int count = slash - binary_name;
+        strncpy(target_fs, binary_name, count);
+        target_fs[count] = '\0';
+    } else {
+        strcpy(target_fs, binary_name);
+    }
+
+    result = LoadFileContents(binary_name, &file, RETOUCH_DONT_MASK);
+
+    if (result == 0) {
+        // Figure out the *apparent* offset to which this file has been
+        // retouched. If it looks good, we will skip processing (we might
+        // have crashed and during this recovery pass we don't want to
+        // overwrite a valuable saved file in /cache---which would happen
+        // if we blindly retouch everything again). NOTE: This implies
+        // that we might have to override the supplied retouch offset. We
+        // can do the override only once though: everything should match
+        // afterward.
+
+        int32_t inferred_offset;
+        int retouch_probe_result = retouch_mask_data(file.data,
+                                                     file.size,
+                                                     NULL,
+                                                     &inferred_offset);
+
+        if (retouch_probe_result == RETOUCH_DATA_MATCHED) {
+            if ((retouch_offset == inferred_offset) ||
+                ((retouch_offset != 0 && inferred_offset != 0) &&
+                 (retouch_offset_override != NULL))) {
+                // This file is OK already and we are allowed to override.
+                // Let's just return the offset override value. It is critical
+                // to skip regardless of override: a broken file might need
+                // recovery down the list and we should not mess up the saved
+                // copy by doing unnecessary retouching.
+                //
+                // NOTE: If retouching was already started with a different
+                // value, we will not be allowed to override. This happens
+                // if on the retouch list there is a patched binary (which is
+                // masked in apply_patch()) before there is a non-patched
+                // binary.
+                if (retouch_offset_override != NULL)
+                    *retouch_offset_override = inferred_offset;
+                success = true;
+                goto out;
+            } else {
+                // Retouch to zero (mask the retouching), to make sure that
+                // the SHA-1 check will pass below.
+                int32_t zero = 0;
+                retouch_mask_data(file.data, file.size, &zero, NULL);
+                SHA(file.data, file.size, file.sha1);
+            }
+        }
+
+        if (retouch_probe_result == RETOUCH_DATA_NOTAPPLICABLE) {
+            // In the case of not retouchable, fake it. We do not want
+            // to do the normal processing and overwrite the backup file:
+            // we might be recovering!
+            //
+            // We return a zero override, which tells the caller that we
+            // simply skipped the file.
+            if (retouch_offset_override != NULL)
+                *retouch_offset_override = 0;
+            success = true;
+            goto out;
+        }
+
+        // If we get here, either there was a mismatch in the offset, or
+        // the file has not been processed yet. Continue with normal
+        // processing.
+    }
+
+    if (result != 0 || FindMatchingPatch(file.sha1, &binary_sha1, 1) < 0) {
+        free(file.data);
+        printf("Attempting to recover source from '%s' ...\n",
+               CACHE_TEMP_SOURCE);
+        result = LoadFileContents(CACHE_TEMP_SOURCE, &file, RETOUCH_DO_MASK);
+        if (result != 0 || FindMatchingPatch(file.sha1, &binary_sha1, 1) < 0) {
+            printf(" failed.\n");
+            success = false;
+            goto out;
+        }
+        printf(" succeeded.\n");
+    }
+
+    // Retouch in-memory before worrying about backing up the original.
+    //
+    // Recovery steps will be oblivious to the actual retouch offset used,
+    // so might as well write out the already-retouched copy. Then, in the
+    // usual case, we will just swap the file locally, with no more writes
+    // needed. In the no-free-space case, we will then write the same to the
+    // original location.
+
+    result = retouch_mask_data(file.data, file.size, &retouch_offset, NULL);
+    if (result != RETOUCH_DATA_MATCHED) {
+        success = false;
+        goto out;
+    }
+    if (retouch_offset_override != NULL)
+        *retouch_offset_override = retouch_offset;
+
+    // How much free space do we need?
+    bool enough_space = false;
+    size_t free_space = FreeSpaceForFile(target_fs);
+    // 50% margin when estimating the space needed.
+    enough_space = (free_space > (file.size * 3 / 2));
+
+    // The experts say we have to allow for a retry of the
+    // whole process to avoid filesystem weirdness.
+    int retry = 1;
+    bool made_copy = false;
+    do {
+        // First figure out where to store a copy of the original.
+        // Ideally leave the original itself intact until the
+        // atomic swap. If no room on the same partition, fall back
+        // to the cache partition and remove the original.
+
+        if (!enough_space) {
+            printf("Target is %ldB; free space is %ldB: not enough.\n",
+                   (long)file.size, (long)free_space);
+
+            retry = 0;
+            if (MakeFreeSpaceOnCache(file.size) < 0) {
+                printf("Not enough free space on '/cache'.\n");
+                success = false;
+                goto out;
+            }
+            if (SaveFileContents(CACHE_TEMP_SOURCE, file) < 0) {
+                printf("Failed to back up source file.\n");
+                success = false;
+                goto out;
+            }
+            made_copy = true;
+            unlink(binary_name);
+
+            size_t free_space = FreeSpaceForFile(target_fs);
+            printf("(now %ld bytes free for target)\n", (long)free_space);
+        }
+
+        result = SaveFileContents(binary_name_atomic, file);
+        if (result != 0) {
+            // Maybe the filesystem was optimistic: retry.
+            enough_space = false;
+            unlink(binary_name_atomic);
+            printf("Saving the retouched contents failed; retrying.\n");
+            continue;
+        }
+
+        // Succeeded; no need to retry.
+        break;
+    } while (retry-- > 0);
+
+    // Give the .atomic file the same owner, group, and mode of the
+    // original source file.
+    if (chmod(binary_name_atomic, file.st.st_mode) != 0) {
+        printf("chmod of \"%s\" failed: %s\n",
+               binary_name_atomic, strerror(errno));
+        success = false;
+        goto out;
+    }
+    if (chown(binary_name_atomic, file.st.st_uid, file.st.st_gid) != 0) {
+        printf("chown of \"%s\" failed: %s\n",
+               binary_name_atomic,
+               strerror(errno));
+        success = false;
+        goto out;
+    }
+
+    // Finally, rename the .atomic file to replace the target file.
+    if (rename(binary_name_atomic, binary_name) != 0) {
+        printf("rename of .atomic to \"%s\" failed: %s\n",
+               binary_name, strerror(errno));
+        success = false;
+        goto out;
+    }
+
+    // If this run created a copy, and we're here, we can delete it.
+    if (made_copy) unlink(CACHE_TEMP_SOURCE);
+
+  out:
+    // clean up
+    free(file.data);
+    unlink(binary_name_atomic);
+
+    return success;
+}
diff --git a/minelf/Retouch.h b/minelf/Retouch.h
new file mode 100644
index 0000000..048d78e
--- /dev/null
+++ b/minelf/Retouch.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _MINELF_RETOUCH
+#define _MINELF_RETOUCH
+
+#include <stdbool.h>
+#include <sys/types.h>
+
+typedef struct {
+  char tag[8];        /* "RETOUCH ", not zero-terminated */
+  uint32_t blob_size; /* in bytes, located right before this struct */
+} retouch_info_t __attribute__((packed));
+
+// Retouch a file. Use CACHED_SOURCE_TEMP to store a copy.
+bool retouch_one_library(const char *binary_name,
+                         const char *binary_sha1,
+                         int32_t retouch_offset,
+                         int32_t *retouch_offset_override);
+
+#define RETOUCH_DONT_MASK           0
+#define RETOUCH_DO_MASK             1
+
+#define RETOUCH_DATA_ERROR          0 // This is bad. Should not happen.
+#define RETOUCH_DATA_MATCHED        1 // Up to an uniform random offset.
+#define RETOUCH_DATA_MISMATCHED     2 // Partially randomized, or total mess.
+#define RETOUCH_DATA_NOTAPPLICABLE  3 // Not retouched. Only when inferring.
+
+// Mask retouching in-memory. Used before apply_patch[_check].
+// Also used to determine status of retouching after a crash.
+//
+// If desired_offset is not NULL, then apply retouching instead,
+// and return that in retouch_offset.
+int retouch_mask_data(uint8_t *binary_object,
+                      int32_t binary_size,
+                      int32_t *desired_offset,
+                      int32_t *retouch_offset);
+#endif
diff --git a/recovery.c b/recovery.c
index f5636d8..286f1e5 100644
--- a/recovery.c
+++ b/recovery.c
@@ -50,12 +50,12 @@
   { NULL, 0, NULL, 0 },
 };
 
-static const char *COMMAND_FILE = "/cache/recovery/command";
-static const char *INTENT_FILE = "/cache/recovery/intent";
-static const char *LOG_FILE = "/cache/recovery/log";
-static const char *SDCARD_ROOT = "/sdcard";
+static const char *COMMAND_FILE = "CACHE:recovery/command";
+static const char *INTENT_FILE = "CACHE:recovery/intent";
+static const char *LOG_FILE = "CACHE:recovery/log";
+static const char *SDCARD_ROOT = "SDCARD:";
 static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
-static const char *SIDELOAD_TEMP_DIR = "/tmp/sideload";
+static const char *SIDELOAD_TEMP_DIR = "TMP:sideload";
 
 /*
  * The recovery tool communicates with the main system through /cache files.
@@ -65,7 +65,7 @@
  *
  * The arguments which may be supplied in the recovery.command file:
  *   --send_intent=anystring - write the text out to recovery.intent
- *   --update_package=path - verify install an OTA package file
+ *   --update_package=root:path - verify install an OTA package file
  *   --wipe_data - erase user data (and cache), then reboot
  *   --wipe_cache - wipe cache (but not user data), then reboot
  *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
@@ -80,8 +80,8 @@
  * 3. main system reboots into recovery
  * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
  *    -- after this, rebooting will restart the erase --
- * 5. erase_volume() reformats /data
- * 6. erase_volume() reformats /cache
+ * 5. erase_root() reformats /data
+ * 6. erase_root() reformats /cache
  * 7. finish_recovery() erases BCB
  *    -- after this, rebooting will restart the main system --
  * 8. main() calls reboot() to boot main system
@@ -109,7 +109,7 @@
  *    8d. bootloader tries to flash firmware
  *    8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
  *        -- after this, rebooting will reformat cache & restart main system --
- *    8f. erase_volume() reformats /cache
+ *    8f. erase_root() reformats /cache
  *    8g. finish_recovery() erases BCB
  *        -- after this, rebooting will (try to) restart the main system --
  * 9. main() calls reboot() to boot main system
@@ -125,8 +125,8 @@
  * 5. read_encrypted_fs_info() retrieves encrypted file systems settings from /data
  *    Settings include: property to specify the Encrypted FS istatus and
  *    FS encryption key if enabled (not yet implemented)
- * 6. erase_volume() reformats /data
- * 7. erase_volume() reformats /cache
+ * 6. erase_root() reformats /data
+ * 7. erase_root() reformats /cache
  * 8. restore_encrypted_fs_info() writes required encrypted file systems settings to /data
  *    Settings include: property to specify the Encrypted FS status and
  *    FS encryption key if enabled (not yet implemented)
@@ -138,11 +138,17 @@
 static const int MAX_ARG_LENGTH = 4096;
 static const int MAX_ARGS = 100;
 
-// open a given path, mounting partitions as necessary
+// open a file given in root:path format, mounting partitions as necessary
 static FILE*
-fopen_path(const char *path, const char *mode) {
-    if (ensure_path_mounted(path) != 0) {
-        LOGE("Can't mount %s\n", path);
+fopen_root_path(const char *root_path, const char *mode) {
+    if (ensure_root_path_mounted(root_path) != 0) {
+        LOGE("Can't mount %s\n", root_path);
+        return NULL;
+    }
+
+    char path[PATH_MAX] = "";
+    if (translate_root_path(root_path, path, sizeof(path)) == NULL) {
+        LOGE("Bad path %s\n", root_path);
         return NULL;
     }
 
@@ -199,7 +205,7 @@
 
     // --- if that doesn't work, try the command file
     if (*argc <= 1) {
-        FILE *fp = fopen_path(COMMAND_FILE, "r");
+        FILE *fp = fopen_root_path(COMMAND_FILE, "r");
         if (fp != NULL) {
             char *argv0 = (*argv)[0];
             *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
@@ -245,7 +251,7 @@
 finish_recovery(const char *send_intent) {
     // By this point, we're ready to return to the main system...
     if (send_intent != NULL) {
-        FILE *fp = fopen_path(INTENT_FILE, "w");
+        FILE *fp = fopen_root_path(INTENT_FILE, "w");
         if (fp == NULL) {
             LOGE("Can't open %s\n", INTENT_FILE);
         } else {
@@ -255,7 +261,7 @@
     }
 
     // Copy logs to cache so the system can find out what happened.
-    FILE *log = fopen_path(LOG_FILE, "a");
+    FILE *log = fopen_root_path(LOG_FILE, "a");
     if (log == NULL) {
         LOGE("Can't open %s\n", LOG_FILE);
     } else {
@@ -279,8 +285,10 @@
     set_bootloader_message(&boot);
 
     // Remove the command file, so recovery won't repeat indefinitely.
-    if (ensure_path_mounted(COMMAND_FILE) != 0 ||
-        (unlink(COMMAND_FILE) && errno != ENOENT)) {
+    char path[PATH_MAX] = "";
+    if (ensure_root_path_mounted(COMMAND_FILE) != 0 ||
+        translate_root_path(COMMAND_FILE, path, sizeof(path)) == NULL ||
+        (unlink(path) && errno != ENOENT)) {
         LOGW("Can't unlink %s\n", COMMAND_FILE);
     }
 
@@ -288,54 +296,64 @@
 }
 
 static int
-erase_volume(const char *volume) {
+erase_root(const char *root) {
     ui_set_background(BACKGROUND_ICON_INSTALLING);
     ui_show_indeterminate_progress();
-    ui_print("Formatting %s...\n", volume);
-    return format_volume(volume);
+    ui_print("Formatting %s...\n", root);
+    return format_root_device(root);
 }
 
 static char*
-copy_sideloaded_package(const char* original_path) {
-  if (ensure_path_mounted(original_path) != 0) {
-    LOGE("Can't mount %s\n", original_path);
+copy_sideloaded_package(const char* original_root_path) {
+  if (ensure_root_path_mounted(original_root_path) != 0) {
+    LOGE("Can't mount %s\n", original_root_path);
     return NULL;
   }
 
-  if (ensure_path_mounted(SIDELOAD_TEMP_DIR) != 0) {
+  char original_path[PATH_MAX] = "";
+  if (translate_root_path(original_root_path, original_path,
+                          sizeof(original_path)) == NULL) {
+    LOGE("Bad path %s\n", original_root_path);
+    return NULL;
+  }
+
+  if (ensure_root_path_mounted(SIDELOAD_TEMP_DIR) != 0) {
     LOGE("Can't mount %s\n", SIDELOAD_TEMP_DIR);
     return NULL;
   }
 
-  if (mkdir(SIDELOAD_TEMP_DIR, 0700) != 0) {
+  char copy_path[PATH_MAX] = "";
+  if (translate_root_path(SIDELOAD_TEMP_DIR, copy_path,
+                          sizeof(copy_path)) == NULL) {
+    LOGE("Bad path %s\n", SIDELOAD_TEMP_DIR);
+    return NULL;
+  }
+
+  if (mkdir(copy_path, 0700) != 0) {
     if (errno != EEXIST) {
       LOGE("Can't mkdir %s (%s)\n", SIDELOAD_TEMP_DIR, strerror(errno));
       return NULL;
     }
   }
 
-  // verify that SIDELOAD_TEMP_DIR is exactly what we expect: a
-  // directory, owned by root, readable and writable only by root.
   struct stat st;
-  if (stat(SIDELOAD_TEMP_DIR, &st) != 0) {
-    LOGE("failed to stat %s (%s)\n", SIDELOAD_TEMP_DIR, strerror(errno));
+  if (stat(copy_path, &st) != 0) {
+    LOGE("failed to stat %s (%s)\n", copy_path, strerror(errno));
     return NULL;
   }
   if (!S_ISDIR(st.st_mode)) {
-    LOGE("%s isn't a directory\n", SIDELOAD_TEMP_DIR);
+    LOGE("%s isn't a directory\n", copy_path);
     return NULL;
   }
   if ((st.st_mode & 0777) != 0700) {
-    LOGE("%s has perms %o\n", SIDELOAD_TEMP_DIR, st.st_mode);
+    LOGE("%s has perms %o\n", copy_path, st.st_mode);
     return NULL;
   }
   if (st.st_uid != 0) {
-    LOGE("%s owned by %lu; not root\n", SIDELOAD_TEMP_DIR, st.st_uid);
+    LOGE("%s owned by %lu; not root\n", copy_path, st.st_uid);
     return NULL;
   }
 
-  char copy_path[PATH_MAX];
-  strcpy(copy_path, SIDELOAD_TEMP_DIR);
   strcat(copy_path, "/package.zip");
 
   char* buffer = malloc(BUFSIZ);
@@ -382,7 +400,10 @@
     return NULL;
   }
 
-  return strdup(copy_path);
+  char* copy_root_path = malloc(strlen(SIDELOAD_TEMP_DIR) + 20);
+  strcpy(copy_root_path, SIDELOAD_TEMP_DIR);
+  strcat(copy_root_path, "/package.zip");
+  return copy_root_path;
 }
 
 static char**
@@ -455,14 +476,15 @@
 }
 
 static int
-sdcard_directory(const char* path) {
+sdcard_directory(const char* root_path) {
     const char* MENU_HEADERS[] = { "Choose a package to install:",
-                                   path,
+                                   root_path,
                                    "",
                                    NULL };
     DIR* d;
     struct dirent* de;
-    d = opendir(path);
+    char path[PATH_MAX];
+    d = opendir(translate_root_path(root_path, path, sizeof(path)));
     if (d == NULL) {
         LOGE("error opening %s: %s\n", path, strerror(errno));
         return 0;
@@ -535,28 +557,20 @@
         } else if (item[item_len-1] == '/') {
             // recurse down into a subdirectory
             char new_path[PATH_MAX];
-            strlcpy(new_path, path, PATH_MAX);
-            strlcat(new_path, "/", PATH_MAX);
+            strlcpy(new_path, root_path, PATH_MAX);
             strlcat(new_path, item, PATH_MAX);
-            new_path[strlen(new_path)-1] = '\0';  // truncate the trailing '/'
             result = sdcard_directory(new_path);
             if (result >= 0) break;
         } else {
             // selected a zip file:  attempt to install it, and return
             // the status to the caller.
             char new_path[PATH_MAX];
-            strlcpy(new_path, path, PATH_MAX);
+            strlcpy(new_path, root_path, PATH_MAX);
             strlcat(new_path, item, PATH_MAX);
 
-            ui_print("\n-- Install %s ...\n", path);
+            ui_print("\n-- Install %s ...\n", new_path);
             set_sdcard_update_bootloader_message();
-            char* copy = copy_sideloaded_package(new_path);
-            if (copy) {
-                result = install_package(copy);
-                free(copy);
-            } else {
-                result = INSTALL_ERROR;
-            }
+            result = install_package(new_path);
             break;
         }
     } while (true);
@@ -603,8 +617,8 @@
 
     ui_print("\n-- Wiping data...\n");
     device_wipe_data();
-    erase_volume("/data");
-    erase_volume("/cache");
+    erase_root("DATA:");
+    erase_root("CACHE:");
     ui_print("Data wipe complete.\n");
 }
 
@@ -634,7 +648,7 @@
 
             case ITEM_WIPE_CACHE:
                 ui_print("\n-- Wiping cache...\n");
-                erase_volume("/cache");
+                erase_root("CACHE:");
                 ui_print("Cache wipe complete.\n");
                 if (!ui_text_visible()) return;
                 break;
@@ -672,7 +686,6 @@
     printf("Starting recovery on %s", ctime(&start));
 
     ui_init();
-    load_volume_table();
     get_args(&argc, &argv);
 
     int previous_runs = 0;
@@ -733,10 +746,10 @@
         }
 
         if (status != INSTALL_ERROR) {
-            if (erase_volume("/data")) {
+            if (erase_root("DATA:")) {
                 ui_print("Data wipe failed.\n");
                 status = INSTALL_ERROR;
-            } else if (erase_volume("/cache")) {
+            } else if (erase_root("CACHE:")) {
                 ui_print("Cache wipe failed.\n");
                 status = INSTALL_ERROR;
             } else if ((encrypted_fs_data.mode == MODE_ENCRYPTED_FS_ENABLED) &&
@@ -753,11 +766,11 @@
         if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
     } else if (wipe_data) {
         if (device_wipe_data()) status = INSTALL_ERROR;
-        if (erase_volume("/data")) status = INSTALL_ERROR;
-        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
+        if (erase_root("DATA:")) status = INSTALL_ERROR;
+        if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR;
         if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
     } else if (wipe_cache) {
-        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
+        if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR;
         if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n");
     } else {
         status = INSTALL_ERROR;  // No command specified
@@ -767,7 +780,7 @@
     if (status != INSTALL_SUCCESS || ui_text_visible()) {
         // Mount the sdcard when the menu is enabled so you can "adb
         // push" packages to the sdcard and immediately install them.
-        ensure_path_mounted(SDCARD_ROOT);
+        ensure_root_path_mounted(SDCARD_ROOT);
         prompt_and_wait();
     }
 
diff --git a/recovery_ui.h b/recovery_ui.h
index e451bdf..77ce7f9 100644
--- a/recovery_ui.h
+++ b/recovery_ui.h
@@ -66,7 +66,8 @@
 #define SELECT_ITEM         -4
 
 #define ITEM_REBOOT          0
-#define ITEM_APPLY_SDCARD    1
+#define ITEM_APPLY_EXT       1
+#define ITEM_APPLY_SDCARD    1  // historical synonym for ITEM_APPLY_EXT
 #define ITEM_WIPE_DATA       2
 #define ITEM_WIPE_CACHE      3
 
diff --git a/roots.c b/roots.c
index fb495fe..9691ad3 100644
--- a/roots.c
+++ b/roots.c
@@ -20,213 +20,330 @@
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <ctype.h>
 
 #include "mtdutils/mtdutils.h"
 #include "mtdutils/mounts.h"
+
+#ifdef USE_EXT4
+#include "make_ext4fs.h"
+#endif
+
+#include "minzip/Zip.h"
 #include "roots.h"
 #include "common.h"
-#include "make_ext4fs.h"
 
-static int num_volumes = 0;
-static Volume* device_volumes = NULL;
+typedef struct {
+    const char *name;
+    const char *device;
+    const char *device2;  // If the first one doesn't work (may be NULL)
+    const char *partition_name;
+    const char *mount_point;
+    const char *filesystem;
+} RootInfo;
 
-void load_volume_table() {
-    int alloc = 2;
-    device_volumes = malloc(alloc * sizeof(Volume));
+/* Canonical pointers.
+xxx may just want to use enums
+ */
+static const char g_mtd_device[] = "@\0g_mtd_device";
+static const char g_raw[] = "@\0g_raw";
+static const char g_package_file[] = "@\0g_package_file";
+static const char g_ramdisk[] = "@\0g_ramdisk";
 
-    FILE* fstab = fopen("/etc/recovery.fstab", "r");
-    if (fstab == NULL) {
-        LOGE("failed to open /etc/recovery.fstab (%s)\n", strerror(errno));
-        return;
+static RootInfo g_roots[] = {
+    { "SDCARD:", "/dev/block/mmcblk0p1", "/dev/block/mmcblk0", NULL, "/sdcard", "vfat" },
+    { "TMP:", NULL, NULL, NULL, "/tmp", g_ramdisk },
+
+#ifdef USE_EXT4
+    { "CACHE:", "/dev/block/platform/sdhci-tegra.3/by-name/cache", NULL, NULL,
+      "/cache", "ext4" },
+    { "DATA:", "/dev/block/platform/sdhci-tegra.3/by-name/userdata", NULL, NULL,
+      "/data", "ext4" },
+    { "EXT:", "/dev/block/sda1", NULL, NULL, "/sdcard", "vfat" },
+#else
+    { "CACHE:", g_mtd_device, NULL, "cache", "/cache", "yaffs2" },
+    { "DATA:", g_mtd_device, NULL, "userdata", "/data", "yaffs2" },
+    { "EXT:", "/dev/block/mmcblk0p1", "/dev/block/mmcblk0", NULL, "/sdcard", "vfat" },
+    { "MISC:", g_mtd_device, NULL, "misc", NULL, g_raw },
+#endif
+
+};
+#define NUM_ROOTS (sizeof(g_roots) / sizeof(g_roots[0]))
+
+static const RootInfo *
+get_root_info_for_path(const char *root_path)
+{
+    const char *c;
+
+    /* Find the first colon.
+     */
+    c = root_path;
+    while (*c != '\0' && *c != ':') {
+        c++;
     }
-
-    char buffer[1024];
-    int i;
-    while (fgets(buffer, sizeof(buffer)-1, fstab)) {
-        for (i = 0; buffer[i] && isspace(buffer[i]); ++i);
-        if (buffer[i] == '\0' || buffer[i] == '#') continue;
-
-        char* original = strdup(buffer);
-
-        char* mount_point = strtok(buffer+i, " \t\n");
-        char* fs_type = strtok(NULL, " \t\n");
-        char* device = strtok(NULL, " \t\n");
-        // lines may optionally have a second device, to use if
-        // mounting the first one fails.
-        char* device2 = strtok(NULL, " \t\n");
-
-        if (mount_point && fs_type && device) {
-            while (num_volumes >= alloc) {
-                alloc *= 2;
-                device_volumes = realloc(device_volumes, alloc*sizeof(Volume));
-            }
-            device_volumes[num_volumes].mount_point = strdup(mount_point);
-            device_volumes[num_volumes].fs_type = strdup(fs_type);
-            device_volumes[num_volumes].device = strdup(device);
-            device_volumes[num_volumes].device2 =
-                device2 ? strdup(device2) : NULL;
-            ++num_volumes;
-        } else {
-            LOGE("skipping malformed recovery.fstab line: %s\n", original);
-        }
-        free(original);
+    if (*c == '\0') {
+        return NULL;
     }
-
-    fclose(fstab);
-
-    printf("recovery filesystem table\n");
-    printf("=========================\n");
-    for (i = 0; i < num_volumes; ++i) {
-        Volume* v = &device_volumes[i];
-        printf("  %d %s %s %s %s\n", i, v->mount_point, v->fs_type,
-               v->device, v->device2);
-    }
-    printf("\n");
-}
-
-Volume* volume_for_path(const char* path) {
-    int i;
-    for (i = 0; i < num_volumes; ++i) {
-        Volume* v = device_volumes+i;
-        int len = strlen(v->mount_point);
-        if (strncmp(path, v->mount_point, len) == 0 &&
-            (path[len] == '\0' || path[len] == '/')) {
-            return v;
+    size_t len = c - root_path + 1;
+    size_t i;
+    for (i = 0; i < NUM_ROOTS; i++) {
+        RootInfo *info = &g_roots[i];
+        if (strncmp(info->name, root_path, len) == 0) {
+            return info;
         }
     }
     return NULL;
 }
 
-int ensure_path_mounted(const char* path) {
-    Volume* v = volume_for_path(path);
-    if (v == NULL) {
-        LOGE("unknown volume for path [%s]\n", path);
-        return -1;
+/* Takes a string like "SYSTEM:lib" and turns it into a string
+ * like "/system/lib".  The translated path is put in out_buf,
+ * and out_buf is returned if the translation succeeded.
+ */
+const char *
+translate_root_path(const char *root_path, char *out_buf, size_t out_buf_len)
+{
+    if (out_buf_len < 1) {
+        return NULL;
     }
 
-    int result;
-    result = scan_mounted_volumes();
-    if (result < 0) {
-        LOGE("failed to scan mounted volumes\n");
-        return -1;
+    const RootInfo *info = get_root_info_for_path(root_path);
+    if (info == NULL || info->mount_point == NULL) {
+        return NULL;
     }
 
-    const MountedVolume* mv =
-        find_mounted_volume_by_mount_point(v->mount_point);
-    if (mv) {
-        // volume is already mounted
+    /* Find the relative part of the non-root part of the path.
+     */
+    root_path += strlen(info->name);  // strip off the "root:"
+    while (*root_path != '\0' && *root_path == '/') {
+        root_path++;
+    }
+
+    size_t mp_len = strlen(info->mount_point);
+    size_t rp_len = strlen(root_path);
+    if (mp_len + 1 + rp_len + 1 > out_buf_len) {
+        return NULL;
+    }
+
+    /* Glue the mount point to the relative part of the path.
+     */
+    memcpy(out_buf, info->mount_point, mp_len);
+    if (out_buf[mp_len - 1] != '/') out_buf[mp_len++] = '/';
+
+    memcpy(out_buf + mp_len, root_path, rp_len);
+    out_buf[mp_len + rp_len] = '\0';
+
+    return out_buf;
+}
+
+static int
+internal_root_mounted(const RootInfo *info)
+{
+    if (info->mount_point == NULL) {
+        return -1;
+    }
+    if (info->filesystem == g_ramdisk) {
+      return 0;
+    }
+
+    /* See if this root is already mounted.
+     */
+    int ret = scan_mounted_volumes();
+    if (ret < 0) {
+        return ret;
+    }
+    const MountedVolume *volume;
+    volume = find_mounted_volume_by_mount_point(info->mount_point);
+    if (volume != NULL) {
+        /* It's already mounted.
+         */
         return 0;
     }
-
-    mkdir(v->mount_point, 0755);  // in case it doesn't already exist
-
-    if (strcmp(v->fs_type, "yaffs2") == 0) {
-        // mount an MTD partition as a YAFFS2 filesystem.
-        mtd_scan_partitions();
-        const MtdPartition* partition;
-        partition = mtd_find_partition_by_name(v->device);
-        if (partition == NULL) {
-            LOGE("failed to find \"%s\" partition to mount at \"%s\"\n",
-                 v->device, v->mount_point);
-            return -1;
-        }
-        return mtd_mount_partition(partition, v->mount_point, v->fs_type, 0);
-    } else if (strcmp(v->fs_type, "ext4") == 0 ||
-               strcmp(v->fs_type, "vfat") == 0) {
-        result = mount(v->device, v->mount_point, v->fs_type,
-                       MS_NOATIME | MS_NODEV | MS_NODIRATIME, "");
-        if (result == 0) return 0;
-
-        if (v->device2) {
-            LOGW("failed to mount %s (%s); trying %s\n",
-                 v->device, strerror(errno), v->device2);
-            result = mount(v->device2, v->mount_point, v->fs_type,
-                           MS_NOATIME | MS_NODEV | MS_NODIRATIME, "");
-            if (result == 0) return 0;
-        }
-
-        LOGE("failed to mount %s (%s)\n", v->mount_point, strerror(errno));
-        return -1;
-    }
-
-    LOGE("unknown fs_type \"%s\" for %s\n", v->fs_type, v->mount_point);
     return -1;
 }
 
-int ensure_path_unmounted(const char* path) {
-    Volume* v = volume_for_path(path);
-    if (v == NULL) {
-        LOGE("unknown volume for path [%s]\n", path);
+int
+is_root_path_mounted(const char *root_path)
+{
+    const RootInfo *info = get_root_info_for_path(root_path);
+    if (info == NULL) {
         return -1;
     }
-
-    int result;
-    result = scan_mounted_volumes();
-    if (result < 0) {
-        LOGE("failed to scan mounted volumes\n");
-        return -1;
-    }
-
-    const MountedVolume* mv =
-        find_mounted_volume_by_mount_point(v->mount_point);
-    if (mv == NULL) {
-        // volume is already unmounted
-        return 0;
-    }
-
-    return unmount_mounted_volume(mv);
+    return internal_root_mounted(info) >= 0;
 }
 
-int format_volume(const char* volume) {
-    Volume* v = volume_for_path(volume);
-    if (v == NULL) {
-        LOGE("unknown volume \"%s\"\n", volume);
-        return -1;
-    }
-    if (strcmp(v->mount_point, volume) != 0) {
-        LOGE("can't give path \"%s\" to format_volume\n", volume);
+int
+ensure_root_path_mounted(const char *root_path)
+{
+    const RootInfo *info = get_root_info_for_path(root_path);
+    if (info == NULL) {
         return -1;
     }
 
-    if (ensure_path_unmounted(volume) != 0) {
-        LOGE("format_volume failed to unmount \"%s\"\n", v->mount_point);
-        return -1;
+    int ret = internal_root_mounted(info);
+    if (ret >= 0) {
+        /* It's already mounted.
+         */
+        return 0;
     }
 
-    if (strcmp(v->fs_type, "yaffs2") == 0 || strcmp(v->fs_type, "mtd") == 0) {
+    /* It's not mounted.
+     */
+    if (info->device == g_mtd_device) {
+        if (info->partition_name == NULL) {
+            return -1;
+        }
+//TODO: make the mtd stuff scan once when it needs to
         mtd_scan_partitions();
-        const MtdPartition* partition = mtd_find_partition_by_name(v->device);
+        const MtdPartition *partition;
+        partition = mtd_find_partition_by_name(info->partition_name);
         if (partition == NULL) {
-            LOGE("format_volume: no MTD partition \"%s\"\n", v->device);
             return -1;
         }
+        return mtd_mount_partition(partition, info->mount_point,
+                info->filesystem, 0);
+    }
 
-        MtdWriteContext *write = mtd_write_partition(partition);
-        if (write == NULL) {
-            LOGW("format_volume: can't open MTD \"%s\"\n", v->device);
+    if (info->device == NULL || info->mount_point == NULL ||
+        info->filesystem == NULL ||
+        info->filesystem == g_raw ||
+        info->filesystem == g_package_file) {
+        return -1;
+    }
+
+    mkdir(info->mount_point, 0755);  // in case it doesn't already exist
+    if (mount(info->device, info->mount_point, info->filesystem,
+              MS_NOATIME | MS_NODEV | MS_NODIRATIME, "")) {
+        if (info->device2 == NULL) {
+            LOGE("Can't mount %s\n(%s)\n", info->device, strerror(errno));
             return -1;
-        } else if (mtd_erase_blocks(write, -1) == (off_t) -1) {
-            LOGW("format_volume: can't erase MTD \"%s\"\n", v->device);
-            mtd_write_close(write);
-            return -1;
-        } else if (mtd_write_close(write)) {
-            LOGW("format_volume: can't close MTD \"%s\"\n", v->device);
+        } else if (mount(info->device2, info->mount_point, info->filesystem,
+                MS_NOATIME | MS_NODEV | MS_NODIRATIME, "")) {
+            LOGE("Can't mount %s (or %s)\n(%s)\n",
+                    info->device, info->device2, strerror(errno));
             return -1;
         }
+    }
+    return 0;
+}
+
+int
+ensure_root_path_unmounted(const char *root_path)
+{
+    const RootInfo *info = get_root_info_for_path(root_path);
+    if (info == NULL) {
+        return -1;
+    }
+    if (info->mount_point == NULL) {
+        /* This root can't be mounted, so by definition it isn't.
+         */
+        return 0;
+    }
+//xxx if TMP: (or similar) just return error
+
+    /* See if this root is already mounted.
+     */
+    int ret = scan_mounted_volumes();
+    if (ret < 0) {
+        return ret;
+    }
+    const MountedVolume *volume;
+    volume = find_mounted_volume_by_mount_point(info->mount_point);
+    if (volume == NULL) {
+        /* It's not mounted.
+         */
         return 0;
     }
 
-    if (strcmp(v->fs_type, "ext4") == 0) {
+    return unmount_mounted_volume(volume);
+}
+
+const MtdPartition *
+get_root_mtd_partition(const char *root_path)
+{
+    const RootInfo *info = get_root_info_for_path(root_path);
+    if (info == NULL || info->device != g_mtd_device ||
+            info->partition_name == NULL)
+    {
+        return NULL;
+    }
+    mtd_scan_partitions();
+    return mtd_find_partition_by_name(info->partition_name);
+}
+
+int
+format_root_device(const char *root)
+{
+    /* Be a little safer here; require that "root" is just
+     * a device with no relative path after it.
+     */
+    const char *c = root;
+    while (*c != '\0' && *c != ':') {
+        c++;
+    }
+    if (c[0] != ':' || c[1] != '\0') {
+        LOGW("format_root_device: bad root name \"%s\"\n", root);
+        return -1;
+    }
+
+    const RootInfo *info = get_root_info_for_path(root);
+    if (info == NULL || info->device == NULL) {
+        LOGW("format_root_device: can't resolve \"%s\"\n", root);
+        return -1;
+    }
+    if (info->mount_point != NULL) {
+        /* Don't try to format a mounted device.
+         */
+        int ret = ensure_root_path_unmounted(root);
+        if (ret < 0) {
+            LOGW("format_root_device: can't unmount \"%s\"\n", root);
+            return ret;
+        }
+    }
+
+    /* Format the device.
+     */
+    if (info->device == g_mtd_device) {
+        mtd_scan_partitions();
+        const MtdPartition *partition;
+        partition = mtd_find_partition_by_name(info->partition_name);
+        if (partition == NULL) {
+            LOGW("format_root_device: can't find mtd partition \"%s\"\n",
+                    info->partition_name);
+            return -1;
+        }
+        if (info->filesystem == g_raw || !strcmp(info->filesystem, "yaffs2")) {
+            MtdWriteContext *write = mtd_write_partition(partition);
+            if (write == NULL) {
+                LOGW("format_root_device: can't open \"%s\"\n", root);
+                return -1;
+            } else if (mtd_erase_blocks(write, -1) == (off_t) -1) {
+                LOGW("format_root_device: can't erase \"%s\"\n", root);
+                mtd_write_close(write);
+                return -1;
+            } else if (mtd_write_close(write)) {
+                LOGW("format_root_device: can't close \"%s\"\n", root);
+                return -1;
+            } else {
+                return 0;
+            }
+        }
+    }
+
+#ifdef USE_EXT4
+    if (strcmp(info->filesystem, "ext4") == 0) {
+        LOGW("starting to reformat ext4\n");
         reset_ext4fs_info();
-        int result = make_ext4fs(v->device, NULL, NULL, 0, 0, 0);
+        int result = make_ext4fs(info->device, NULL, NULL, 0, 0, 0);
+        LOGW("finished reformat ext4: result = %d\n", result);
         if (result != 0) {
-            LOGE("format_volume: make_extf4fs failed on %s\n", v->device);
+            LOGW("make_ext4fs failed: %d\n", result);
             return -1;
         }
         return 0;
     }
+#endif
 
-    LOGE("format_volume: fs_type \"%s\" unsupported\n", v->fs_type);
+//TODO: handle other device types (sdcard, etc.)
+
+    LOGW("format_root_device: unknown device \"%s\"\n", root);
     return -1;
 }
diff --git a/roots.h b/roots.h
index cf59bfd..e85191d 100644
--- a/roots.h
+++ b/roots.h
@@ -17,25 +17,33 @@
 #ifndef RECOVERY_ROOTS_H_
 #define RECOVERY_ROOTS_H_
 
-#include "common.h"
+#include "minzip/Zip.h"
+#include "mtdutils/mtdutils.h"
 
-// Load and parse volume data from /etc/recovery.fstab.
-void load_volume_table();
+/* Any of the "root_path" arguments can be paths with relative
+ * components, like "SYSTEM:a/b/c".
+ */
 
-// Return the Volume* record for this path (or NULL).
-Volume* volume_for_path(const char* path);
+/* Takes a string like "SYSTEM:lib" and turns it into a string
+ * like "/system/lib".  The translated path is put in out_buf,
+ * and out_buf is returned if the translation succeeded.
+ */
+const char *translate_root_path(const char *root_path,
+        char *out_buf, size_t out_buf_len);
 
-// Make sure that the volume 'path' is on is mounted.  Returns 0 on
-// success (volume is mounted).
-int ensure_path_mounted(const char* path);
+/* Returns negative on error, positive if it's mounted, zero if it isn't.
+ */
+int is_root_path_mounted(const char *root_path);
 
-// Make sure that the volume 'path' is on is mounted.  Returns 0 on
-// success (volume is unmounted);
-int ensure_path_unmounted(const char* path);
+int ensure_root_path_mounted(const char *root_path);
 
-// Reformat the given volume (must be the mount point only, eg
-// "/cache"), no paths permitted.  Attempts to unmount the volume if
-// it is mounted.
-int format_volume(const char* volume);
+int ensure_root_path_unmounted(const char *root_path);
+
+const MtdPartition *get_root_mtd_partition(const char *root_path);
+
+/* "root" must be the exact name of the root; no relative path is permitted.
+ * If the named root is mounted, this will attempt to unmount it first.
+ */
+int format_root_device(const char *root);
 
 #endif  // RECOVERY_ROOTS_H_
diff --git a/test_roots.c b/test_roots.c
new file mode 100644
index 0000000..f49f55e
--- /dev/null
+++ b/test_roots.c
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2007 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 <sys/stat.h>
+#include "roots.h"
+#include "common.h"
+
+#define CANARY_FILE "/system/build.prop"
+#define CANARY_FILE_ROOT_PATH "SYSTEM:build.prop"
+
+int
+file_exists(const char *path)
+{
+    struct stat st;
+    int ret;
+    ret = stat(path, &st);
+    if (ret == 0) {
+        return S_ISREG(st.st_mode);
+    }
+    return 0;
+}
+
+int
+test_roots()
+{
+    int ret;
+
+    /* Make sure that /system isn't mounted yet.
+     */
+    if (file_exists(CANARY_FILE)) return -__LINE__;
+    if (is_root_path_mounted(CANARY_FILE_ROOT_PATH)) return -__LINE__;
+
+    /* Try to mount the root.
+     */
+    ret = ensure_root_path_mounted(CANARY_FILE_ROOT_PATH);
+    if (ret < 0) return -__LINE__;
+
+    /* Make sure we can see the file now and that we know the root is mounted.
+     */
+    if (!file_exists(CANARY_FILE)) return -__LINE__;
+    if (!is_root_path_mounted(CANARY_FILE_ROOT_PATH)) return -__LINE__;
+
+    /* Make sure that the root path corresponds to the regular path.
+     */
+    struct stat st1, st2;
+    char buf[128];
+    const char *path = translate_root_path(CANARY_FILE_ROOT_PATH,
+            buf, sizeof(buf));
+    if (path == NULL) return -__LINE__;
+    ret = stat(CANARY_FILE, &st1);
+    if (ret != 0) return -__LINE__;
+    ret = stat(path, &st2);
+    if (ret != 0) return -__LINE__;
+    if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) return -__LINE__;
+
+    /* Try to unmount the root.
+     */
+    ret = ensure_root_path_unmounted(CANARY_FILE_ROOT_PATH);
+    if (ret < 0) return -__LINE__;
+
+    /* Make sure that we can't see the file anymore and that
+     * we don't think the root is mounted.
+     */
+    if (file_exists(CANARY_FILE)) return -__LINE__;
+    if (is_root_path_mounted(CANARY_FILE_ROOT_PATH)) return -__LINE__;
+
+    return 0;
+}
diff --git a/updater/Android.mk b/updater/Android.mk
index dcc6a49..e3d62bc 100644
--- a/updater/Android.mk
+++ b/updater/Android.mk
@@ -27,6 +27,7 @@
 LOCAL_STATIC_LIBRARIES += $(TARGET_RECOVERY_UPDATER_LIBS) $(TARGET_RECOVERY_UPDATER_EXTRA_LIBS)
 LOCAL_STATIC_LIBRARIES += libapplypatch libedify libmtdutils libminzip libz
 LOCAL_STATIC_LIBRARIES += libmincrypt libbz
+LOCAL_STATIC_LIBRARIES += libminelf
 LOCAL_STATIC_LIBRARIES += libcutils libstdc++ libc
 LOCAL_C_INCLUDES += $(LOCAL_PATH)/..
 
@@ -51,7 +52,7 @@
 
 junk := $(shell mkdir -p $(dir $(inc));\
 	        echo $(TARGET_RECOVERY_UPDATER_LIBS) > $(inc).temp;\
-	        diff -q $(inc).temp $(inc).list || cp -f $(inc).temp $(inc).list)
+	        diff -q $(inc).temp $(inc).list 2>/dev/null || cp -f $(inc).temp $(inc).list)
 
 $(inc) : libs := $(TARGET_RECOVERY_UPDATER_LIBS)
 $(inc) : $(inc).list
diff --git a/updater/install.c b/updater/install.c
index a596dc6..685b979 100644
--- a/updater/install.c
+++ b/updater/install.c
@@ -25,12 +25,15 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 #include <unistd.h>
+#include <fcntl.h>
+#include <time.h>
 
 #include "cutils/misc.h"
 #include "cutils/properties.h"
 #include "edify/expr.h"
 #include "mincrypt/sha.h"
 #include "minzip/DirUtil.h"
+#include "minelf/Retouch.h"
 #include "mtdutils/mounts.h"
 #include "mtdutils/mtdutils.h"
 #include "updater.h"
@@ -429,6 +432,121 @@
 }
 
 
+// retouch_binaries(lib1, lib2, ...)
+Value* RetouchBinariesFn(const char* name, State* state,
+                         int argc, Expr* argv[]) {
+    UpdaterInfo* ui = (UpdaterInfo*)(state->cookie);
+
+    char **retouch_entries  = ReadVarArgs(state, argc, argv);
+    if (retouch_entries == NULL) {
+        return StringValue(strdup("t"));
+    }
+
+    // some randomness from the clock
+    int32_t override_base;
+    bool override_set = false;
+    int32_t random_base = time(NULL) % 1024;
+    // some more randomness from /dev/random
+    FILE *f_random = fopen("/dev/random", "rb");
+    uint16_t random_bits = 0;
+    if (f_random != NULL) {
+        fread(&random_bits, 2, 1, f_random);
+        random_bits = random_bits % 1024;
+        fclose(f_random);
+    }
+    random_base = (random_base + random_bits) % 1024;
+    fprintf(ui->cmd_pipe, "ui_print Random offset: 0x%x\n", random_base);
+    fprintf(ui->cmd_pipe, "ui_print\n");
+
+    // make sure we never randomize to zero; this let's us look at a file
+    // and know for sure whether it has been processed; important in the
+    // crash recovery process
+    if (random_base == 0) random_base = 1;
+    // make sure our randomization is page-aligned
+    random_base *= -0x1000;
+    override_base = random_base;
+
+    int i = 0;
+    bool success = true;
+    while (i < (argc - 1)) {
+        success = success && retouch_one_library(retouch_entries[i],
+                                                 retouch_entries[i+1],
+                                                 random_base,
+                                                 override_set ?
+                                                   NULL :
+                                                   &override_base);
+        if (!success)
+            ErrorAbort(state, "Failed to retouch '%s'.", retouch_entries[i]);
+
+        free(retouch_entries[i]);
+        free(retouch_entries[i+1]);
+        i += 2;
+
+        if (success && override_base != 0) {
+            random_base = override_base;
+            override_set = true;
+        }
+    }
+    if (i < argc) {
+        free(retouch_entries[i]);
+        success = false;
+    }
+    free(retouch_entries);
+
+    if (!success) {
+      Value* v = malloc(sizeof(Value));
+      v->type = VAL_STRING;
+      v->data = NULL;
+      v->size = -1;
+      return v;
+    }
+    return StringValue(strdup("t"));
+}
+
+
+// undo_retouch_binaries(lib1, lib2, ...)
+Value* UndoRetouchBinariesFn(const char* name, State* state,
+                             int argc, Expr* argv[]) {
+    UpdaterInfo* ui = (UpdaterInfo*)(state->cookie);
+
+    char **retouch_entries  = ReadVarArgs(state, argc, argv);
+    if (retouch_entries == NULL) {
+        return StringValue(strdup("t"));
+    }
+
+    int i = 0;
+    bool success = true;
+    int32_t override_base;
+    while (i < (argc-1)) {
+        success = success && retouch_one_library(retouch_entries[i],
+                                                 retouch_entries[i+1],
+                                                 0 /* undo => offset==0 */,
+                                                 NULL);
+        if (!success)
+            ErrorAbort(state, "Failed to unretouch '%s'.",
+                       retouch_entries[i]);
+
+        free(retouch_entries[i]);
+        free(retouch_entries[i+1]);
+        i += 2;
+    }
+    if (i < argc) {
+        free(retouch_entries[i]);
+        success = false;
+    }
+    free(retouch_entries);
+
+    if (!success) {
+      Value* v = malloc(sizeof(Value));
+      v->type = VAL_STRING;
+      v->data = NULL;
+      v->size = -1;
+      return v;
+    }
+    return StringValue(strdup("t"));
+}
+
+
 // symlink target src1 src2 ...
 //    unlinks any previously existing src1, src2, etc before creating symlinks.
 Value* SymlinkFn(const char* name, State* state, int argc, Expr* argv[]) {
@@ -1007,7 +1125,7 @@
     return args[i];
 }
 
-// Read a local file and return its contents (the char* returned
+// Read a local file and return its contents (the Value* returned
 // is actually a FileContents*).
 Value* ReadFileFn(const char* name, State* state, int argc, Expr* argv[]) {
     if (argc != 1) {
@@ -1020,7 +1138,7 @@
     v->type = VAL_BLOB;
 
     FileContents fc;
-    if (LoadFileContents(filename, &fc) != 0) {
+    if (LoadFileContents(filename, &fc, RETOUCH_DONT_MASK) != 0) {
         ErrorAbort(state, "%s() loading \"%s\" failed: %s",
                    name, filename, strerror(errno));
         free(filename);
@@ -1047,6 +1165,8 @@
     RegisterFunction("delete_recursive", DeleteFn);
     RegisterFunction("package_extract_dir", PackageExtractDirFn);
     RegisterFunction("package_extract_file", PackageExtractFileFn);
+    RegisterFunction("retouch_binaries", RetouchBinariesFn);
+    RegisterFunction("undo_retouch_binaries", UndoRetouchBinariesFn);
     RegisterFunction("symlink", SymlinkFn);
     RegisterFunction("set_perm", SetPermFn);
     RegisterFunction("set_perm_recursive", SetPermFn);