Merge "Add 'reboot bootloader' to bootloader_message."
diff --git a/otautil/Android.mk b/otautil/Android.mk
index 3acfa53..e602f19 100644
--- a/otautil/Android.mk
+++ b/otautil/Android.mk
@@ -20,16 +20,10 @@
     DirUtil.cpp \
     ZipUtil.cpp
 
-LOCAL_C_INCLUDES := \
-    external/zlib \
-    external/safe-iop/include
-
 LOCAL_STATIC_LIBRARIES := libselinux libbase
 
 LOCAL_MODULE := libotautil
 
-LOCAL_CLANG := true
-
 LOCAL_CFLAGS += -Werror -Wall
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/otautil/SysUtil.cpp b/otautil/SysUtil.cpp
index a8d5f4a..a2133b9 100644
--- a/otautil/SysUtil.cpp
+++ b/otautil/SysUtil.cpp
@@ -16,17 +16,12 @@
 
 #include "SysUtil.h"
 
-#include <assert.h>
 #include <errno.h>
 #include <fcntl.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+#include <stdint.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <unistd.h>
 
 #include <algorithm>
 #include <string>
diff --git a/tests/component/updater_test.cpp b/tests/component/updater_test.cpp
index acc2b40..973c19d 100644
--- a/tests/component/updater_test.cpp
+++ b/tests/component/updater_test.cpp
@@ -14,6 +14,10 @@
  * limitations under the License.
  */
 
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
 #include <string>
 
 #include <android-base/file.h>
@@ -212,10 +216,15 @@
     // Parents create successfully.
     TemporaryFile temp_file3;
     TemporaryDir td;
-    std::string temp_dir = std::string(td.path) + "/aaa/bbb/a.txt";
-    std::string script3("rename(\"" + std::string(temp_file3.path) + "\", \"" +
-                        temp_dir + "\")");
-    expect(temp_dir.c_str(), script3.c_str(), kNoCause);
+    std::string temp_dir(td.path);
+    std::string dst_file = temp_dir + "/aaa/bbb/a.txt";
+    std::string script3("rename(\"" + std::string(temp_file3.path) + "\", \"" + dst_file + "\")");
+    expect(dst_file.c_str(), script3.c_str(), kNoCause);
+
+    // Clean up the temp files under td.
+    ASSERT_EQ(0, unlink(dst_file.c_str()));
+    ASSERT_EQ(0, rmdir((temp_dir + "/aaa/bbb").c_str()));
+    ASSERT_EQ(0, rmdir((temp_dir + "/aaa").c_str()));
 }
 
 TEST_F(UpdaterTest, symlink) {
@@ -227,7 +236,31 @@
     std::string script1("symlink(\"" + std::string(temp_file1.path) + "\", \"\")");
     expect(nullptr, script1.c_str(), kSymlinkFailure);
 
-    // symlink failed to remove old src.
-    std::string script2("symlink(\"" + std::string(temp_file1.path) + "\", \"/proc\")");
+    std::string script2("symlink(\"" + std::string(temp_file1.path) + "\", \"src1\", \"\")");
     expect(nullptr, script2.c_str(), kSymlinkFailure);
+
+    // symlink failed to remove old src.
+    std::string script3("symlink(\"" + std::string(temp_file1.path) + "\", \"/proc\")");
+    expect(nullptr, script3.c_str(), kSymlinkFailure);
+
+    // symlink can create symlinks.
+    TemporaryFile temp_file;
+    std::string content = "magicvalue";
+    ASSERT_TRUE(android::base::WriteStringToFile(content, temp_file.path));
+
+    TemporaryDir td;
+    std::string src1 = std::string(td.path) + "/symlink1";
+    std::string src2 = std::string(td.path) + "/symlink2";
+    std::string script4("symlink(\"" + std::string(temp_file.path) + "\", \"" +
+                        src1 + "\", \"" + src2 + "\")");
+    expect("t", script4.c_str(), kNoCause);
+
+    // Verify the created symlinks.
+    struct stat sb;
+    ASSERT_TRUE(lstat(src1.c_str(), &sb) == 0 && S_ISLNK(sb.st_mode));
+    ASSERT_TRUE(lstat(src2.c_str(), &sb) == 0 && S_ISLNK(sb.st_mode));
+
+    // Clean up the leftovers.
+    ASSERT_EQ(0, unlink(src1.c_str()));
+    ASSERT_EQ(0, unlink(src2.c_str()));
 }
diff --git a/update_verifier/Android.mk b/update_verifier/Android.mk
index 8f5194d..8449c75 100644
--- a/update_verifier/Android.mk
+++ b/update_verifier/Android.mk
@@ -18,8 +18,15 @@
 
 LOCAL_CLANG := true
 LOCAL_SRC_FILES := update_verifier.cpp
+
 LOCAL_MODULE := update_verifier
-LOCAL_SHARED_LIBRARIES := libhardware libbase
+LOCAL_SHARED_LIBRARIES := \
+    libbase \
+    libcutils \
+    libhardware \
+    liblog
+
 LOCAL_CFLAGS := -Werror
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/..
 
 include $(BUILD_EXECUTABLE)
diff --git a/update_verifier/update_verifier.cpp b/update_verifier/update_verifier.cpp
index 0a040c5..93ac605 100644
--- a/update_verifier/update_verifier.cpp
+++ b/update_verifier/update_verifier.cpp
@@ -22,22 +22,121 @@
  * It relies on dm-verity to capture any corruption on the partitions being
  * verified. dm-verity must be in enforcing mode, so that it will reboot the
  * device on dm-verity failures. When that happens, the bootloader should
- * mark the slot as unbootable and stops trying. We should never see a device
- * started in dm-verity logging mode but with isSlotMarkedSuccessful equals to
- * 0.
+ * mark the slot as unbootable and stops trying. Other dm-verity modes (
+ * for example, veritymode=EIO) are not accepted and simply lead to a
+ * verification failure.
  *
  * The current slot will be marked as having booted successfully if the
  * verifier reaches the end after the verification.
  *
- * TODO: The actual verification part will be added later after we have the
- * A/B OTA package format in place.
  */
 
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
 #include <string.h>
 
+#include <string>
+#include <vector>
+
+#include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/parseint.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+#include <cutils/properties.h>
 #include <hardware/boot_control.h>
 
+constexpr auto CARE_MAP_FILE = "/data/ota_package/care_map.txt";
+constexpr int BLOCKSIZE = 4096;
+
+static bool read_blocks(const std::string& blk_device_prefix, const std::string& range_str) {
+    char slot_suffix[PROPERTY_VALUE_MAX];
+    property_get("ro.boot.slot_suffix", slot_suffix, "");
+    std::string blk_device = blk_device_prefix + std::string(slot_suffix);
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY)));
+    if (fd.get() == -1) {
+        PLOG(ERROR) << "Error reading partition " << blk_device;
+        return false;
+    }
+
+    // For block range string, first integer 'count' equals 2 * total number of valid ranges,
+    // followed by 'count' number comma separated integers. Every two integers reprensent a
+    // block range with the first number included in range but second number not included.
+    // For example '4,64536,65343,74149,74150' represents: [64536,65343) and [74149,74150).
+    std::vector<std::string> ranges = android::base::Split(range_str, ",");
+    size_t range_count;
+    bool status = android::base::ParseUint(ranges[0].c_str(), &range_count);
+    if (!status || (range_count == 0) || (range_count % 2 != 0) ||
+            (range_count != ranges.size()-1)) {
+        LOG(ERROR) << "Error in parsing range string.";
+        return false;
+    }
+
+    size_t blk_count = 0;
+    for (size_t i = 1; i < ranges.size(); i += 2) {
+        unsigned int range_start, range_end;
+        bool parse_status = android::base::ParseUint(ranges[i].c_str(), &range_start);
+        parse_status = parse_status && android::base::ParseUint(ranges[i+1].c_str(), &range_end);
+        if (!parse_status || range_start >= range_end) {
+            LOG(ERROR) << "Invalid range pair " << ranges[i] << ", " << ranges[i+1];
+            return false;
+        }
+
+        if (lseek64(fd.get(), static_cast<off64_t>(range_start) * BLOCKSIZE, SEEK_SET) == -1) {
+            PLOG(ERROR) << "lseek to " << range_start << " failed";
+            return false;
+        }
+
+        size_t size = (range_end - range_start) * BLOCKSIZE;
+        std::vector<uint8_t> buf(size);
+        if (!android::base::ReadFully(fd.get(), buf.data(), size)) {
+            PLOG(ERROR) << "Failed to read blocks " << range_start << " to " << range_end;
+            return false;
+        }
+        blk_count += (range_end - range_start);
+    }
+
+    LOG(INFO) << "Finished reading " << blk_count << " blocks on " << blk_device;
+    return true;
+}
+
+static bool verify_image(const std::string& care_map_name) {
+    android::base::unique_fd care_map_fd(TEMP_FAILURE_RETRY(open(care_map_name.c_str(), O_RDONLY)));
+    // If the device is flashed before the current boot, it may not have care_map.txt
+    // in /data/ota_package. To allow the device to continue booting in this situation,
+    // we should print a warning and skip the block verification.
+    if (care_map_fd.get() == -1) {
+        LOG(WARNING) << "Warning: care map " << care_map_name << " not found.";
+        return true;
+    }
+    // Care map file has four lines (two lines if vendor partition is not present):
+    // First line has the block device name, e.g./dev/block/.../by-name/system.
+    // Second line holds all ranges of blocks to verify.
+    // The next two lines have the same format but for vendor partition.
+    std::string file_content;
+    if (!android::base::ReadFdToString(care_map_fd.get(), &file_content)) {
+        LOG(ERROR) << "Error reading care map contents to string.";
+        return false;
+    }
+
+    std::vector<std::string> lines;
+    lines = android::base::Split(android::base::Trim(file_content), "\n");
+    if (lines.size() != 2 && lines.size() != 4) {
+        LOG(ERROR) << "Invalid lines in care_map: found " << lines.size()
+                   << " lines, expecting 2 or 4 lines.";
+        return false;
+    }
+
+    for (size_t i = 0; i < lines.size(); i += 2) {
+        if (!read_blocks(lines[i], lines[i+1])) {
+            return false;
+        }
+    }
+
+    return true;
+}
+
 int main(int argc, char** argv) {
   for (int i = 1; i < argc; i++) {
     LOG(INFO) << "Started with arg " << i << ": " << argv[i];
@@ -59,12 +158,22 @@
 
   if (is_successful == 0) {
     // The current slot has not booted successfully.
-
-    // TODO: Add the actual verification after we have the A/B OTA package
-    // format in place.
-
-    // TODO: Assert the dm-verity mode. Bootloader should never boot a newly
-    // flashed slot (isSlotMarkedSuccessful == 0) with dm-verity logging mode.
+    char verity_mode[PROPERTY_VALUE_MAX];
+    if (property_get("ro.boot.veritymode", verity_mode, "") == -1) {
+      LOG(ERROR) << "Failed to get dm-verity mode.";
+      return -1;
+    } else if (strcasecmp(verity_mode, "eio") == 0) {
+      // We shouldn't see verity in EIO mode if the current slot hasn't booted
+      // successfully before. Therefore, fail the verification when veritymode=eio.
+      LOG(ERROR) << "Found dm-verity in EIO mode, skip verification.";
+      return -1;
+    } else if (strcmp(verity_mode, "enforcing") != 0) {
+      LOG(ERROR) << "Unexpected dm-verity mode : " << verity_mode << ", expecting enforcing.";
+      return -1;
+    } else if (!verify_image(CARE_MAP_FILE)) {
+      LOG(ERROR) << "Failed to verify all blocks in care map file.";
+      return -1;
+    }
 
     int ret = module->markBootSuccessful(module);
     if (ret != 0) {
diff --git a/updater/install.cpp b/updater/install.cpp
index cba95f5..59c54dd 100644
--- a/updater/install.cpp
+++ b/updater/install.cpp
@@ -566,8 +566,9 @@
     }
 }
 
-// symlink target src1 src2 ...
-//    unlinks any previously existing src1, src2, etc before creating symlinks.
+// symlink(target, [src1, src2, ...])
+//   Creates all sources as symlinks to target. It unlinks any previously existing src1, src2, etc
+//   before creating symlinks.
 Value* SymlinkFn(const char* name, State* state, int argc, Expr* argv[]) {
     if (argc == 0) {
         return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1+ args, got %d", name, argc);
@@ -579,33 +580,29 @@
 
     std::vector<std::string> srcs;
     if (!ReadArgs(state, argc-1, argv+1, &srcs)) {
-        return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
+        return ErrorAbort(state, kArgsParsingFailure, "%s(): Failed to parse the argument(s)",
+                          name);
     }
 
-    int bad = 0;
-    for (int i = 0; i < argc-1; ++i) {
-        if (unlink(srcs[i].c_str()) < 0) {
-            if (errno != ENOENT) {
-                printf("%s: failed to remove %s: %s\n",
-                        name, srcs[i].c_str(), strerror(errno));
-                ++bad;
-            }
-        }
-        if (!make_parents(srcs[i])) {
+    size_t bad = 0;
+    for (const auto& src : srcs) {
+        if (unlink(src.c_str()) == -1 && errno != ENOENT) {
+            printf("%s: failed to remove %s: %s\n", name, src.c_str(), strerror(errno));
+            ++bad;
+        } else if (!make_parents(src)) {
             printf("%s: failed to symlink %s to %s: making parents failed\n",
-                    name, srcs[i].c_str(), target.c_str());
+                    name, src.c_str(), target.c_str());
             ++bad;
-        }
-        if (symlink(target.c_str(), srcs[i].c_str()) < 0) {
+        } else if (symlink(target.c_str(), src.c_str()) == -1) {
             printf("%s: failed to symlink %s to %s: %s\n",
-                    name, srcs[i].c_str(), target.c_str(), strerror(errno));
+                    name, src.c_str(), target.c_str(), strerror(errno));
             ++bad;
         }
     }
-    if (bad) {
-        return ErrorAbort(state, kSymlinkFailure, "%s: some symlinks failed", name);
+    if (bad != 0) {
+        return ErrorAbort(state, kSymlinkFailure, "%s: Failed to create %zu symlink(s)", name, bad);
     }
-    return StringValue("");
+    return StringValue("t");
 }
 
 struct perm_parsed_args {