diff options
Diffstat (limited to '')
-rw-r--r-- | README.md | 13 | ||||
-rw-r--r-- | bootloader_message/bootloader_message.cpp | 18 | ||||
-rw-r--r-- | bootloader_message/include/bootloader_message/bootloader_message.h | 4 | ||||
-rw-r--r-- | minui/resources.cpp | 2 | ||||
-rw-r--r-- | otautil/Android.mk | 6 | ||||
-rw-r--r-- | otautil/SysUtil.cpp | 346 | ||||
-rw-r--r-- | otautil/SysUtil.h | 47 | ||||
-rw-r--r-- | tests/Android.mk | 24 | ||||
-rw-r--r-- | tests/component/updater_test.cpp | 55 | ||||
-rw-r--r-- | tests/manual/recovery_test.cpp | 87 | ||||
-rw-r--r-- | tests/unit/recovery_test.cpp | 91 | ||||
-rw-r--r-- | tests/unit/sysutil_test.cpp | 140 | ||||
-rw-r--r-- | tests/unit/zip_test.cpp | 109 | ||||
-rw-r--r-- | uncrypt/uncrypt.cpp | 20 | ||||
-rw-r--r-- | update_verifier/Android.mk | 9 | ||||
-rw-r--r-- | update_verifier/update_verifier.cpp | 131 | ||||
-rw-r--r-- | updater/install.cpp | 81 |
17 files changed, 773 insertions, 410 deletions
@@ -27,3 +27,16 @@ Running the tests # Or 64-bit device adb shell /data/nativetest64/recovery_unit_test/recovery_unit_test adb shell /data/nativetest64/recovery_component_test/recovery_component_test + +Running the manual tests +------------------------ + +`recovery-refresh` and `recovery-persist` executables exist only on systems without +/cache partition. And we need to follow special steps to run tests for them. + +- Execute the test on an A/B device first. The test should fail but it will log + some contents to pmsg. + +- Reboot the device immediately and run the test again. The test should save the + contents of pmsg buffer into /data/misc/recovery/inject.txt. Test will pass if + this file has expected contents. diff --git a/bootloader_message/bootloader_message.cpp b/bootloader_message/bootloader_message.cpp index 59c2b2e01..f6f8005f6 100644 --- a/bootloader_message/bootloader_message.cpp +++ b/bootloader_message/bootloader_message.cpp @@ -163,6 +163,19 @@ bool write_bootloader_message(const std::vector<std::string>& options, std::stri return write_bootloader_message(boot, err); } +bool write_reboot_bootloader(std::string* err) { + bootloader_message boot; + if (!read_bootloader_message(&boot, err)) { + return false; + } + if (boot.command[0] != '\0') { + *err = "Bootloader command pending."; + return false; + } + strlcpy(boot.command, "bootonce-bootloader", sizeof(boot.command)); + return write_bootloader_message(boot, err); +} + bool read_wipe_package(std::string* package_data, size_t size, std::string* err) { package_data->resize(size); return read_misc_partition(&(*package_data)[0], size, WIPE_PACKAGE_OFFSET_IN_MISC, err); @@ -173,6 +186,11 @@ bool write_wipe_package(const std::string& package_data, std::string* err) { WIPE_PACKAGE_OFFSET_IN_MISC, err); } +extern "C" bool write_reboot_bootloader(void) { + std::string err; + return write_reboot_bootloader(&err); +} + extern "C" bool write_bootloader_message(const char* options) { std::string err; return write_bootloader_message({options}, &err); diff --git a/bootloader_message/include/bootloader_message/bootloader_message.h b/bootloader_message/include/bootloader_message/bootloader_message.h index 07ecf8576..5a5dd8793 100644 --- a/bootloader_message/include/bootloader_message/bootloader_message.h +++ b/bootloader_message/include/bootloader_message/bootloader_message.h @@ -183,6 +183,9 @@ bool write_bootloader_message(const bootloader_message& boot, std::string* err); bool write_bootloader_message(const std::vector<std::string>& options, std::string* err); bool clear_bootloader_message(std::string* err); +// Writes the reboot-bootloader reboot reason to the bootloader_message. +bool write_reboot_bootloader(std::string* err); + bool read_wipe_package(std::string* package_data, size_t size, std::string* err); bool write_wipe_package(const std::string& package_data, std::string* err); @@ -192,6 +195,7 @@ bool write_wipe_package(const std::string& package_data, std::string* err); // C Interface. bool write_bootloader_message(const char* options); +bool write_reboot_bootloader(void); #endif // ifdef __cplusplus diff --git a/minui/resources.cpp b/minui/resources.cpp index 730b05f13..455ef2784 100644 --- a/minui/resources.cpp +++ b/minui/resources.cpp @@ -269,7 +269,7 @@ int res_create_multi_display_surface(const char* name, int* frames, int* fps, printf(" found fps = %d\n", *fps); } - if (frames <= 0 || fps <= 0) { + if (*frames <= 0 || *fps <= 0) { printf("bad number of frames (%d) and/or FPS (%d)\n", *frames, *fps); result = -10; goto exit; diff --git a/otautil/Android.mk b/otautil/Android.mk index 3acfa533e..e602f19ee 100644 --- a/otautil/Android.mk +++ b/otautil/Android.mk @@ -20,16 +20,10 @@ LOCAL_SRC_FILES := \ 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 2936c5ca4..a2133b953 100644 --- a/otautil/SysUtil.cpp +++ b/otautil/SysUtil.cpp @@ -1,212 +1,212 @@ /* * Copyright 2006 The Android Open Source Project * - * System utilities. + * 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 <assert.h> + +#include "SysUtil.h" + #include <errno.h> #include <fcntl.h> -#include <limits.h> -#include <stdbool.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 <android-base/logging.h> +#include <algorithm> +#include <string> +#include <vector> -#include "SysUtil.h" +#include <android-base/file.h> +#include <android-base/logging.h> +#include <android-base/strings.h> +#include <android-base/unique_fd.h> static bool sysMapFD(int fd, MemMapping* pMap) { - assert(pMap != NULL); + CHECK(pMap != nullptr); - struct stat sb; - if (fstat(fd, &sb) == -1) { - PLOG(ERROR) << "fstat(" << fd << ") failed"; - return false; - } + struct stat sb; + if (fstat(fd, &sb) == -1) { + PLOG(ERROR) << "fstat(" << fd << ") failed"; + return false; + } - void* memPtr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); - if (memPtr == MAP_FAILED) { - PLOG(ERROR) << "mmap(" << sb.st_size << ", R, PRIVATE, " << fd << ", 0) failed"; - return false; - } + void* memPtr = mmap(nullptr, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (memPtr == MAP_FAILED) { + PLOG(ERROR) << "mmap(" << sb.st_size << ", R, PRIVATE, " << fd << ", 0) failed"; + return false; + } - pMap->addr = reinterpret_cast<unsigned char*>(memPtr); - pMap->length = sb.st_size; - pMap->range_count = 1; - pMap->ranges = reinterpret_cast<MappedRange*>(malloc(sizeof(MappedRange))); - if (pMap->ranges == NULL) { - PLOG(ERROR) << "malloc failed"; - munmap(memPtr, sb.st_size); - return false; - } - pMap->ranges[0].addr = memPtr; - pMap->ranges[0].length = sb.st_size; + pMap->addr = static_cast<unsigned char*>(memPtr); + pMap->length = sb.st_size; + pMap->ranges.push_back({ memPtr, static_cast<size_t>(sb.st_size) }); - return true; + return true; } -static int sysMapBlockFile(FILE* mapf, MemMapping* pMap) -{ - char block_dev[PATH_MAX+1]; - size_t size; - unsigned int blksize; - size_t blocks; - unsigned int range_count; - unsigned int i; - - if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) { - PLOG(ERROR) << "failed to read block device from header"; - return -1; +// A "block map" which looks like this (from uncrypt/uncrypt.cpp): +// +// /dev/block/platform/msm_sdcc.1/by-name/userdata # block device +// 49652 4096 # file size in bytes, block size +// 3 # count of block ranges +// 1000 1008 # block range 0 +// 2100 2102 # ... block range 1 +// 30 33 # ... block range 2 +// +// Each block range represents a half-open interval; the line "30 33" +// reprents the blocks [30, 31, 32]. +static int sysMapBlockFile(const char* filename, MemMapping* pMap) { + CHECK(pMap != nullptr); + + std::string content; + if (!android::base::ReadFileToString(filename, &content)) { + PLOG(ERROR) << "Failed to read " << filename; + return -1; + } + + std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n"); + if (lines.size() < 4) { + LOG(ERROR) << "Block map file is too short: " << lines.size(); + return -1; + } + + size_t size; + unsigned int blksize; + if (sscanf(lines[1].c_str(), "%zu %u", &size, &blksize) != 2) { + LOG(ERROR) << "Failed to parse file size and block size: " << lines[1]; + return -1; + } + + size_t range_count; + if (sscanf(lines[2].c_str(), "%zu", &range_count) != 1) { + LOG(ERROR) << "Failed to parse block map header: " << lines[2]; + return -1; + } + + size_t blocks; + if (blksize != 0) { + blocks = ((size - 1) / blksize) + 1; + } + if (size == 0 || blksize == 0 || blocks > SIZE_MAX / blksize || range_count == 0 || + lines.size() != 3 + range_count) { + LOG(ERROR) << "Invalid data in block map file: size " << size << ", blksize " << blksize + << ", range_count " << range_count << ", lines " << lines.size(); + return -1; + } + + // Reserve enough contiguous address space for the whole file. + void* reserve = mmap64(nullptr, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); + if (reserve == MAP_FAILED) { + PLOG(ERROR) << "failed to reserve address space"; + return -1; + } + + const std::string& block_dev = lines[0]; + android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(block_dev.c_str(), O_RDONLY))); + if (fd == -1) { + PLOG(ERROR) << "failed to open block device " << block_dev; + munmap(reserve, blocks * blksize); + return -1; + } + + pMap->ranges.resize(range_count); + + unsigned char* next = static_cast<unsigned char*>(reserve); + size_t remaining_size = blocks * blksize; + bool success = true; + for (size_t i = 0; i < range_count; ++i) { + const std::string& line = lines[i + 3]; + + size_t start, end; + if (sscanf(line.c_str(), "%zu %zu\n", &start, &end) != 2) { + LOG(ERROR) << "failed to parse range " << i << " in block map: " << line; + success = false; + break; } - for (i = 0; i < sizeof(block_dev); ++i) { - if (block_dev[i] == '\n') { - block_dev[i] = 0; - break; - } + size_t length = (end - start) * blksize; + if (end <= start || (end - start) > SIZE_MAX / blksize || length > remaining_size) { + LOG(ERROR) << "unexpected range in block map: " << start << " " << end; + success = false; + break; } - if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) { - LOG(ERROR) << "failed to parse block map header"; - return -1; - } - if (blksize != 0) { - blocks = ((size-1) / blksize) + 1; - } - if (size == 0 || blksize == 0 || blocks > SIZE_MAX / blksize || range_count == 0) { - LOG(ERROR) << "invalid data in block map file: size " << size << ", blksize " << blksize - << ", range_count " << range_count; - return -1; + void* addr = mmap64(next, length, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, + static_cast<off64_t>(start) * blksize); + if (addr == MAP_FAILED) { + PLOG(ERROR) << "failed to map block " << i; + success = false; + break; } + pMap->ranges[i].addr = addr; + pMap->ranges[i].length = length; - pMap->range_count = range_count; - pMap->ranges = reinterpret_cast<MappedRange*>(calloc(range_count, sizeof(MappedRange))); - if (pMap->ranges == NULL) { - PLOG(ERROR) << "calloc(" << range_count << ", " << sizeof(MappedRange) << ") failed"; - return -1; - } + next += length; + remaining_size -= length; + } + if (success && remaining_size != 0) { + LOG(ERROR) << "ranges in block map are invalid: remaining_size = " << remaining_size; + success = false; + } + if (!success) { + munmap(reserve, blocks * blksize); + return -1; + } - // Reserve enough contiguous address space for the whole file. - unsigned char* reserve = reinterpret_cast<unsigned char*>(mmap64(NULL, blocks * blksize, - PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0)); - if (reserve == MAP_FAILED) { - PLOG(ERROR) << "failed to reserve address space"; - free(pMap->ranges); - return -1; - } + pMap->addr = static_cast<unsigned char*>(reserve); + pMap->length = size; - int fd = open(block_dev, O_RDONLY); - if (fd < 0) { - PLOG(ERROR) << "failed to open block device " << block_dev; - munmap(reserve, blocks * blksize); - free(pMap->ranges); - return -1; - } + LOG(INFO) << "mmapped " << range_count << " ranges"; - unsigned char* next = reserve; - size_t remaining_size = blocks * blksize; - bool success = true; - for (i = 0; i < range_count; ++i) { - size_t start, end; - if (fscanf(mapf, "%zu %zu\n", &start, &end) != 2) { - LOG(ERROR) << "failed to parse range " << i << " in block map"; - success = false; - break; - } - size_t length = (end - start) * blksize; - if (end <= start || (end - start) > SIZE_MAX / blksize || length > remaining_size) { - LOG(ERROR) << "unexpected range in block map: " << start << " " << end; - success = false; - break; - } - - void* addr = mmap64(next, length, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize); - if (addr == MAP_FAILED) { - PLOG(ERROR) << "failed to map block " << i; - success = false; - break; - } - pMap->ranges[i].addr = addr; - pMap->ranges[i].length = length; - - next += length; - remaining_size -= length; - } - if (success && remaining_size != 0) { - LOG(ERROR) << "ranges in block map are invalid: remaining_size = " << remaining_size; - success = false; - } - if (!success) { - close(fd); - munmap(reserve, blocks * blksize); - free(pMap->ranges); - return -1; - } + return 0; +} - close(fd); - pMap->addr = reserve; - pMap->length = size; +int sysMapFile(const char* fn, MemMapping* pMap) { + if (fn == nullptr || pMap == nullptr) { + LOG(ERROR) << "Invalid argument(s)"; + return -1; + } - LOG(INFO) << "mmapped " << range_count << " ranges"; + *pMap = {}; - return 0; -} + if (fn[0] == '@') { + if (sysMapBlockFile(fn + 1, pMap) != 0) { + LOG(ERROR) << "Map of '" << fn << "' failed"; + return -1; + } + } else { + // This is a regular file. + android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(fn, O_RDONLY))); + if (fd == -1) { + PLOG(ERROR) << "Unable to open '" << fn << "'"; + return -1; + } -int sysMapFile(const char* fn, MemMapping* pMap) -{ - memset(pMap, 0, sizeof(*pMap)); - - if (fn && fn[0] == '@') { - // A map of blocks - FILE* mapf = fopen(fn+1, "r"); - if (mapf == NULL) { - PLOG(ERROR) << "Unable to open '" << (fn+1) << "'"; - return -1; - } - - if (sysMapBlockFile(mapf, pMap) != 0) { - LOG(ERROR) << "Map of '" << fn << "' failed"; - fclose(mapf); - return -1; - } - - fclose(mapf); - } else { - // This is a regular file. - int fd = open(fn, O_RDONLY); - if (fd == -1) { - PLOG(ERROR) << "Unable to open '" << fn << "'"; - return -1; - } - - if (!sysMapFD(fd, pMap)) { - LOG(ERROR) << "Map of '" << fn << "' failed"; - close(fd); - return -1; - } - - close(fd); + if (!sysMapFD(fd, pMap)) { + LOG(ERROR) << "Map of '" << fn << "' failed"; + return -1; } - return 0; + } + return 0; } /* * Release a memory mapping. */ -void sysReleaseMap(MemMapping* pMap) -{ - int i; - for (i = 0; i < pMap->range_count; ++i) { - if (munmap(pMap->ranges[i].addr, pMap->ranges[i].length) < 0) { - PLOG(ERROR) << "munmap(" << pMap->ranges[i].addr << ", " << pMap->ranges[i].length - << ") failed"; - } +void sysReleaseMap(MemMapping* pMap) { + std::for_each(pMap->ranges.cbegin(), pMap->ranges.cend(), [](const MappedRange& range) { + if (munmap(range.addr, range.length) == -1) { + PLOG(ERROR) << "munmap(" << range.addr << ", " << range.length << ") failed"; } - free(pMap->ranges); - pMap->ranges = NULL; - pMap->range_count = 0; + }); + pMap->ranges.clear(); } diff --git a/otautil/SysUtil.h b/otautil/SysUtil.h index 7adff1e54..6a79bf31f 100644 --- a/otautil/SysUtil.h +++ b/otautil/SysUtil.h @@ -1,33 +1,40 @@ /* * Copyright 2006 The Android Open Source Project * - * System utilities. + * 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 _MINZIP_SYSUTIL -#define _MINZIP_SYSUTIL -#include <stdio.h> +#ifndef _OTAUTIL_SYSUTIL +#define _OTAUTIL_SYSUTIL + #include <sys/types.h> -#ifdef __cplusplus -extern "C" { -#endif +#include <vector> -typedef struct MappedRange { - void* addr; - size_t length; -} MappedRange; +struct MappedRange { + void* addr; + size_t length; +}; /* * Use this to keep track of mapped segments. */ -typedef struct MemMapping { - unsigned char* addr; /* start of data */ - size_t length; /* length of data */ +struct MemMapping { + unsigned char* addr; /* start of data */ + size_t length; /* length of data */ - int range_count; - MappedRange* ranges; -} MemMapping; + std::vector<MappedRange> ranges; +}; /* * Map a file into a private, read-only memory segment. If 'fn' @@ -45,8 +52,4 @@ int sysMapFile(const char* fn, MemMapping* pMap); */ void sysReleaseMap(MemMapping* pMap); -#ifdef __cplusplus -} -#endif - -#endif /*_MINZIP_SYSUTIL*/ +#endif // _OTAUTIL_SYSUTIL diff --git a/tests/Android.mk b/tests/Android.mk index 8f19992b6..e87a22964 100644 --- a/tests/Android.mk +++ b/tests/Android.mk @@ -18,7 +18,6 @@ LOCAL_PATH := $(call my-dir) # Unit tests include $(CLEAR_VARS) -LOCAL_CLANG := true LOCAL_CFLAGS := -Werror LOCAL_MODULE := recovery_unit_test LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk @@ -32,18 +31,31 @@ LOCAL_STATIC_LIBRARIES := \ libselinux \ libbase -LOCAL_SRC_FILES := unit/asn1_decoder_test.cpp -LOCAL_SRC_FILES += unit/recovery_test.cpp -LOCAL_SRC_FILES += unit/locale_test.cpp -LOCAL_SRC_FILES += unit/zip_test.cpp +LOCAL_SRC_FILES := \ + unit/asn1_decoder_test.cpp \ + unit/locale_test.cpp \ + unit/sysutil_test.cpp \ + unit/zip_test.cpp + LOCAL_C_INCLUDES := bootable/recovery LOCAL_SHARED_LIBRARIES := liblog include $(BUILD_NATIVE_TEST) -# Component tests +# Manual tests include $(CLEAR_VARS) LOCAL_CLANG := true LOCAL_CFLAGS := -Werror +LOCAL_MODULE := recovery_manual_test +LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk +LOCAL_STATIC_LIBRARIES := libbase + +LOCAL_SRC_FILES := manual/recovery_test.cpp +LOCAL_SHARED_LIBRARIES := liblog +include $(BUILD_NATIVE_TEST) + +# Component tests +include $(CLEAR_VARS) +LOCAL_CFLAGS := -Werror LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk LOCAL_MODULE := recovery_component_test LOCAL_C_INCLUDES := bootable/recovery diff --git a/tests/component/updater_test.cpp b/tests/component/updater_test.cpp index f922933cd..973c19de3 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> @@ -208,4 +212,55 @@ TEST_F(UpdaterTest, rename) { // Already renamed. expect(temp_file2.path, script2.c_str(), kNoCause); + + // Parents create successfully. + TemporaryFile temp_file3; + TemporaryDir td; + 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) { + // symlink expects 1+ argument. + expect(nullptr, "symlink()", kArgsParsingFailure); + + // symlink should fail if src is an empty string. + TemporaryFile temp_file1; + std::string script1("symlink(\"" + std::string(temp_file1.path) + "\", \"\")"); + expect(nullptr, script1.c_str(), kSymlinkFailure); + + 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/tests/manual/recovery_test.cpp b/tests/manual/recovery_test.cpp new file mode 100644 index 000000000..e83849546 --- /dev/null +++ b/tests/manual/recovery_test.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2016 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 <fcntl.h> +#include <string.h> +#include <sys/types.h> +#include <unistd.h> + +#include <string> + +#include <android-base/file.h> +#include <android/log.h> +#include <gtest/gtest.h> +#include <private/android_logger.h> + +static const std::string myFilename = "/data/misc/recovery/inject.txt"; +static const std::string myContent = "Hello World\nWelcome to my recovery\n"; + +// Failure is expected on systems that do not deliver either the +// recovery-persist or recovery-refresh executables. Tests also require +// a reboot sequence of test to truly verify. + +static ssize_t __pmsg_fn(log_id_t logId, char prio, const char *filename, + const char *buf, size_t len, void *arg) { + EXPECT_EQ(LOG_ID_SYSTEM, logId); + EXPECT_EQ(ANDROID_LOG_INFO, prio); + EXPECT_NE(std::string::npos, myFilename.find(filename)); + EXPECT_EQ(myContent, buf); + EXPECT_EQ(myContent.size(), len); + EXPECT_EQ(nullptr, arg); + return len; +} + +// recovery.refresh - May fail. Requires recovery.inject, two reboots, +// then expect success after second reboot. +TEST(recovery, refresh) { + EXPECT_EQ(0, access("/system/bin/recovery-refresh", F_OK)); + + ssize_t ret = __android_log_pmsg_file_read( + LOG_ID_SYSTEM, ANDROID_LOG_INFO, "recovery/", __pmsg_fn, nullptr); + if (ret == -ENOENT) { + EXPECT_LT(0, __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO, + myFilename.c_str(), myContent.c_str(), myContent.size())); + + fprintf(stderr, "injected test data, requires two intervening reboots " + "to check for replication\n"); + } + EXPECT_EQ(static_cast<ssize_t>(myContent.size()), ret); +} + +// recovery.persist - Requires recovery.inject, then a reboot, then +// expect success after for this test on that boot. +TEST(recovery, persist) { + EXPECT_EQ(0, access("/system/bin/recovery-persist", F_OK)); + + ssize_t ret = __android_log_pmsg_file_read( + LOG_ID_SYSTEM, ANDROID_LOG_INFO, "recovery/", __pmsg_fn, nullptr); + if (ret == -ENOENT) { + EXPECT_LT(0, __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO, + myFilename.c_str(), myContent.c_str(), myContent.size())); + + fprintf(stderr, "injected test data, requires intervening reboot " + "to check for storage\n"); + } + + std::string buf; + EXPECT_TRUE(android::base::ReadFileToString(myFilename, &buf)); + EXPECT_EQ(myContent, buf); + if (access(myFilename.c_str(), O_RDONLY) == 0) { + fprintf(stderr, "Removing persistent test data, " + "check if reconstructed on reboot\n"); + } + EXPECT_EQ(0, unlink(myFilename.c_str())); +} diff --git a/tests/unit/recovery_test.cpp b/tests/unit/recovery_test.cpp deleted file mode 100644 index 28b845fb9..000000000 --- a/tests/unit/recovery_test.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2016 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 <fcntl.h> -#include <string.h> -#include <sys/types.h> -#include <unistd.h> - -#include <android/log.h> -#include <gtest/gtest.h> -#include <private/android_logger.h> - -static const char myFilename[] = "/data/misc/recovery/inject.txt"; -static const char myContent[] = "Hello World\nWelcome to my recovery\n"; - -// Failure is expected on systems that do not deliver either the -// recovery-persist or recovery-refresh executables. Tests also require -// a reboot sequence of test to truly verify. - -static ssize_t __pmsg_fn(log_id_t logId, char prio, const char *filename, - const char *buf, size_t len, void *arg) { - EXPECT_EQ(LOG_ID_SYSTEM, logId); - EXPECT_EQ(ANDROID_LOG_INFO, prio); - EXPECT_EQ(0, NULL == strstr(myFilename,filename)); - EXPECT_EQ(0, strcmp(myContent, buf)); - EXPECT_EQ(sizeof(myContent), len); - EXPECT_EQ(0, NULL != arg); - return len; -} - -// recovery.refresh - May fail. Requires recovery.inject, two reboots, -// then expect success after second reboot. -TEST(recovery, refresh) { - EXPECT_EQ(0, access("/system/bin/recovery-refresh", F_OK)); - - ssize_t ret = __android_log_pmsg_file_read( - LOG_ID_SYSTEM, ANDROID_LOG_INFO, "recovery/", __pmsg_fn, NULL); - if (ret == -ENOENT) { - EXPECT_LT(0, __android_log_pmsg_file_write( - LOG_ID_SYSTEM, ANDROID_LOG_INFO, - myFilename, myContent, sizeof(myContent))); - fprintf(stderr, "injected test data, " - "requires two intervening reboots " - "to check for replication\n"); - } - EXPECT_EQ((ssize_t)sizeof(myContent), ret); -} - -// recovery.persist - Requires recovery.inject, then a reboot, then -// expect success after for this test on that boot. -TEST(recovery, persist) { - EXPECT_EQ(0, access("/system/bin/recovery-persist", F_OK)); - - ssize_t ret = __android_log_pmsg_file_read( - LOG_ID_SYSTEM, ANDROID_LOG_INFO, "recovery/", __pmsg_fn, NULL); - if (ret == -ENOENT) { - EXPECT_LT(0, __android_log_pmsg_file_write( - LOG_ID_SYSTEM, ANDROID_LOG_INFO, - myFilename, myContent, sizeof(myContent))); - fprintf(stderr, "injected test data, " - "requires intervening reboot " - "to check for storage\n"); - } - - int fd = open(myFilename, O_RDONLY); - EXPECT_LE(0, fd); - - char buf[sizeof(myContent) + 32]; - ret = read(fd, buf, sizeof(buf)); - close(fd); - EXPECT_EQ(ret, (ssize_t)sizeof(myContent)); - EXPECT_EQ(0, strcmp(myContent, buf)); - if (fd >= 0) { - fprintf(stderr, "Removing persistent test data, " - "check if reconstructed on reboot\n"); - } - EXPECT_EQ(0, unlink(myFilename)); -} diff --git a/tests/unit/sysutil_test.cpp b/tests/unit/sysutil_test.cpp new file mode 100644 index 000000000..f4699664b --- /dev/null +++ b/tests/unit/sysutil_test.cpp @@ -0,0 +1,140 @@ +/* + * Copyright 2016 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 <gtest/gtest.h> + +#include <string> + +#include <android-base/file.h> +#include <android-base/test_utils.h> + +#include "otautil/SysUtil.h" + +TEST(SysUtilTest, InvalidArgs) { + MemMapping mapping; + + // Invalid argument. + ASSERT_EQ(-1, sysMapFile(nullptr, &mapping)); + ASSERT_EQ(-1, sysMapFile("/somefile", nullptr)); +} + +TEST(SysUtilTest, sysMapFileRegularFile) { + TemporaryFile temp_file1; + std::string content = "abc"; + ASSERT_TRUE(android::base::WriteStringToFile(content, temp_file1.path)); + + // sysMapFile() should map the file to one range. + MemMapping mapping; + ASSERT_EQ(0, sysMapFile(temp_file1.path, &mapping)); + ASSERT_NE(nullptr, mapping.addr); + ASSERT_EQ(content.size(), mapping.length); + ASSERT_EQ(1U, mapping.ranges.size()); + + sysReleaseMap(&mapping); + ASSERT_EQ(0U, mapping.ranges.size()); +} + +TEST(SysUtilTest, sysMapFileBlockMap) { + // Create a file that has 10 blocks. + TemporaryFile package; + std::string content; + constexpr size_t file_size = 4096 * 10; + content.reserve(file_size); + ASSERT_TRUE(android::base::WriteStringToFile(content, package.path)); + + TemporaryFile block_map_file; + std::string filename = std::string("@") + block_map_file.path; + MemMapping mapping; + + // One range. + std::string block_map_content = std::string(package.path) + "\n40960 4096\n1\n0 10\n"; + ASSERT_TRUE(android::base::WriteStringToFile(block_map_content, block_map_file.path)); + + ASSERT_EQ(0, sysMapFile(filename.c_str(), &mapping)); + ASSERT_EQ(file_size, mapping.length); + ASSERT_EQ(1U, mapping.ranges.size()); + + // It's okay to not have the trailing '\n'. + block_map_content = std::string(package.path) + "\n40960 4096\n1\n0 10"; + ASSERT_TRUE(android::base::WriteStringToFile(block_map_content, block_map_file.path)); + + ASSERT_EQ(0, sysMapFile(filename.c_str(), &mapping)); + ASSERT_EQ(file_size, mapping.length); + ASSERT_EQ(1U, mapping.ranges.size()); + + // Or having multiple trailing '\n's. + block_map_content = std::string(package.path) + "\n40960 4096\n1\n0 10\n\n\n"; + ASSERT_TRUE(android::base::WriteStringToFile(block_map_content, block_map_file.path)); + + ASSERT_EQ(0, sysMapFile(filename.c_str(), &mapping)); + ASSERT_EQ(file_size, mapping.length); + ASSERT_EQ(1U, mapping.ranges.size()); + + // Multiple ranges. + block_map_content = std::string(package.path) + "\n40960 4096\n3\n0 3\n3 5\n5 10\n"; + ASSERT_TRUE(android::base::WriteStringToFile(block_map_content, block_map_file.path)); + + ASSERT_EQ(0, sysMapFile(filename.c_str(), &mapping)); + ASSERT_EQ(file_size, mapping.length); + ASSERT_EQ(3U, mapping.ranges.size()); + + sysReleaseMap(&mapping); + ASSERT_EQ(0U, mapping.ranges.size()); +} + +TEST(SysUtilTest, sysMapFileBlockMapInvalidBlockMap) { + MemMapping mapping; + TemporaryFile temp_file; + std::string filename = std::string("@") + temp_file.path; + + // Block map file is too short. + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\n4096 4096\n0\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + // Block map file has unexpected number of lines. + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\n4096 4096\n1\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\n4096 4096\n2\n0 1\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + // Invalid size/blksize/range_count. + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\nabc 4096\n1\n0 1\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\n4096 4096\n\n0 1\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + // size/blksize/range_count don't match. + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\n0 4096\n1\n0 1\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\n4096 0\n1\n0 1\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + ASSERT_TRUE(android::base::WriteStringToFile("/somefile\n4096 4096\n0\n0 1\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + // Invalid block dev path. + ASSERT_TRUE(android::base::WriteStringToFile("/doesntexist\n4096 4096\n1\n0 1\n", temp_file.path)); + ASSERT_EQ(-1, sysMapFile(filename.c_str(), &mapping)); + + sysReleaseMap(&mapping); + ASSERT_EQ(0U, mapping.ranges.size()); +} diff --git a/tests/unit/zip_test.cpp b/tests/unit/zip_test.cpp index b617446b8..49729467d 100644 --- a/tests/unit/zip_test.cpp +++ b/tests/unit/zip_test.cpp @@ -16,78 +16,69 @@ #include <errno.h> #include <fcntl.h> -#include <pthread.h> #include <unistd.h> #include <memory> #include <vector> #include <android-base/file.h> -#include <android-base/stringprintf.h> -#include <android-base/unique_fd.h> #include <android-base/test_utils.h> #include <gtest/gtest.h> #include <otautil/SysUtil.h> #include <otautil/ZipUtil.h> #include <ziparchive/zip_archive.h> -static const std::string DATA_PATH(getenv("ANDROID_DATA")); -static const std::string TESTDATA_PATH("/recovery/testdata/"); - -static const std::vector<uint8_t> kATxtContents { - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - '\n' -}; - -static const std::vector<uint8_t> kBTxtContents { - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - '\n' -}; - -TEST(otazip, ExtractPackageRecursive) { - TemporaryDir td; - ASSERT_NE(td.path, nullptr); - ZipArchiveHandle handle; - std::string zip_path = DATA_PATH + TESTDATA_PATH + "/ziptest_valid.zip"; - ASSERT_EQ(0, OpenArchive(zip_path.c_str(), &handle)); - // Extract the whole package into a temp directory. - ExtractPackageRecursive(handle, "", td.path, nullptr, nullptr); - // Make sure all the files are extracted correctly. - std::string path(td.path); - android::base::unique_fd fd(open((path + "/a.txt").c_str(), O_RDONLY)); - ASSERT_NE(fd, -1); - std::vector<uint8_t> read_data; - read_data.resize(kATxtContents.size()); - // The content of the file is the same as expected. - ASSERT_TRUE(android::base::ReadFully(fd.get(), read_data.data(), read_data.size())); - ASSERT_EQ(0, memcmp(read_data.data(), kATxtContents.data(), kATxtContents.size())); - - fd.reset(open((path + "/b.txt").c_str(), O_RDONLY)); - ASSERT_NE(fd, -1); - fd.reset(open((path + "/b/c.txt").c_str(), O_RDONLY)); - ASSERT_NE(fd, -1); - fd.reset(open((path + "/b/d.txt").c_str(), O_RDONLY)); - ASSERT_NE(fd, -1); - read_data.resize(kBTxtContents.size()); - ASSERT_TRUE(android::base::ReadFully(fd.get(), read_data.data(), read_data.size())); - ASSERT_EQ(0, memcmp(read_data.data(), kBTxtContents.data(), kBTxtContents.size())); +#include "common/test_constants.h" + +static const std::string kATxtContents("abcdefghabcdefgh\n"); +static const std::string kBTxtContents("abcdefgh\n"); + +TEST(ZipTest, ExtractPackageRecursive) { + std::string zip_path = from_testdata_base("ziptest_valid.zip"); + ZipArchiveHandle handle; + ASSERT_EQ(0, OpenArchive(zip_path.c_str(), &handle)); + + // Extract the whole package into a temp directory. + TemporaryDir td; + ASSERT_NE(nullptr, td.path); + ExtractPackageRecursive(handle, "", td.path, nullptr, nullptr); + + // Make sure all the files are extracted correctly. + std::string path(td.path); + ASSERT_EQ(0, access((path + "/a.txt").c_str(), O_RDONLY)); + ASSERT_EQ(0, access((path + "/b.txt").c_str(), O_RDONLY)); + ASSERT_EQ(0, access((path + "/b/c.txt").c_str(), O_RDONLY)); + ASSERT_EQ(0, access((path + "/b/d.txt").c_str(), O_RDONLY)); + + // The content of the file is the same as expected. + std::string content1; + ASSERT_TRUE(android::base::ReadFileToString(path + "/a.txt", &content1)); + ASSERT_EQ(kATxtContents, content1); + + std::string content2; + ASSERT_TRUE(android::base::ReadFileToString(path + "/b/d.txt", &content2)); + ASSERT_EQ(kBTxtContents, content2); } -TEST(otazip, OpenFromMemory) { - MemMapping map; - std::string zip_path = DATA_PATH + TESTDATA_PATH + "/ziptest_dummy-update.zip"; - ASSERT_EQ(0, sysMapFile(zip_path.c_str(), &map)); - // Map an update package into memory and open the archive from there. - ZipArchiveHandle handle; - ASSERT_EQ(0, OpenArchiveFromMemory(map.addr, map.length, zip_path.c_str(), &handle)); - static constexpr const char* BINARY_PATH = "META-INF/com/google/android/update-binary"; - ZipString binary_path(BINARY_PATH); - ZipEntry binary_entry; - // Make sure the package opens correctly and its entry can be read. - ASSERT_EQ(0, FindEntry(handle, binary_path, &binary_entry)); - TemporaryFile tmp_binary; - ASSERT_NE(-1, tmp_binary.fd); - ASSERT_EQ(0, ExtractEntryToFile(handle, &binary_entry, tmp_binary.fd)); +TEST(ZipTest, OpenFromMemory) { + MemMapping map; + std::string zip_path = from_testdata_base("ziptest_dummy-update.zip"); + ASSERT_EQ(0, sysMapFile(zip_path.c_str(), &map)); + + // Map an update package into memory and open the archive from there. + ZipArchiveHandle handle; + ASSERT_EQ(0, OpenArchiveFromMemory(map.addr, map.length, zip_path.c_str(), &handle)); + + static constexpr const char* BINARY_PATH = "META-INF/com/google/android/update-binary"; + ZipString binary_path(BINARY_PATH); + ZipEntry binary_entry; + // Make sure the package opens correctly and its entry can be read. + ASSERT_EQ(0, FindEntry(handle, binary_path, &binary_entry)); + + TemporaryFile tmp_binary; + ASSERT_NE(-1, tmp_binary.fd); + ASSERT_EQ(0, ExtractEntryToFile(handle, &binary_entry, tmp_binary.fd)); + + sysReleaseMap(&map); } diff --git a/uncrypt/uncrypt.cpp b/uncrypt/uncrypt.cpp index a5d692bbb..e1b6a1c20 100644 --- a/uncrypt/uncrypt.cpp +++ b/uncrypt/uncrypt.cpp @@ -210,6 +210,11 @@ static const char* find_block_device(const char* path, bool* encryptable, bool* } static bool write_status_to_socket(int status, int socket) { + // If socket equals -1, uncrypt is in debug mode without socket communication. + // Skip writing and return success. + if (socket == -1) { + return true; + } int status_out = htonl(status); return android::base::WriteFully(socket, &status_out, sizeof(int)); } @@ -566,7 +571,7 @@ static void usage(const char* exename) { } int main(int argc, char** argv) { - enum { UNCRYPT, SETUP_BCB, CLEAR_BCB } action; + enum { UNCRYPT, SETUP_BCB, CLEAR_BCB, UNCRYPT_DEBUG } action; const char* input_path = nullptr; const char* map_file = CACHE_BLOCK_MAP.c_str(); @@ -579,7 +584,7 @@ int main(int argc, char** argv) { } else if (argc == 3) { input_path = argv[1]; map_file = argv[2]; - action = UNCRYPT; + action = UNCRYPT_DEBUG; } else { usage(argv[0]); return 2; @@ -593,6 +598,17 @@ int main(int argc, char** argv) { return 1; } + if (action == UNCRYPT_DEBUG) { + LOG(INFO) << "uncrypt called in debug mode, skip socket communication\n"; + bool success = uncrypt_wrapper(input_path, map_file, -1); + if (success) { + LOG(INFO) << "uncrypt succeeded\n"; + } else{ + LOG(INFO) << "uncrypt failed\n"; + } + return success ? 0 : 1; + } + // c3. The socket is created by init when starting the service. uncrypt // will use the socket to communicate with its caller. android::base::unique_fd service_socket(android_get_control_socket(UNCRYPT_SOCKET.c_str())); diff --git a/update_verifier/Android.mk b/update_verifier/Android.mk index 8f5194db6..8449c758d 100644 --- a/update_verifier/Android.mk +++ b/update_verifier/Android.mk @@ -18,8 +18,15 @@ include $(CLEAR_VARS) 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 0a040c564..93ac605b1 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 @@ int main(int argc, char** argv) { 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 ed55ea517..59c54dd4c 100644 --- a/updater/install.cpp +++ b/updater/install.cpp @@ -95,25 +95,33 @@ void uiPrintf(State* _Nonnull state, const char* _Nonnull format, ...) { uiPrint(state, error_msg); } +static bool is_dir(const std::string& dirpath) { + struct stat st; + return stat(dirpath.c_str(), &st) == 0 && S_ISDIR(st.st_mode); +} + // Create all parent directories of name, if necessary. -static int make_parents(char* name) { - char* p; - for (p = name + (strlen(name)-1); p > name; --p) { - if (*p != '/') continue; - *p = '\0'; - if (make_parents(name) < 0) return -1; - int result = mkdir(name, 0700); - if (result == 0) printf("created [%s]\n", name); - *p = '/'; - if (result == 0 || errno == EEXIST) { - // successfully created or already existed; we're done - return 0; - } else { - printf("failed to mkdir %s: %s\n", name, strerror(errno)); - return -1; +static bool make_parents(const std::string& name) { + size_t prev_end = 0; + while (prev_end < name.size()) { + size_t next_end = name.find('/', prev_end + 1); + if (next_end == std::string::npos) { + break; + } + std::string dir_path = name.substr(0, next_end); + if (!is_dir(dir_path)) { + int result = mkdir(dir_path.c_str(), 0700); + if (result != 0) { + printf("failed to mkdir %s when make parents for %s: %s\n", dir_path.c_str(), + name.c_str(), strerror(errno)); + return false; + } + + printf("created [%s]\n", dir_path.c_str()); } + prev_end = next_end; } - return 0; + return true; } // mount(fs_type, partition_type, location, mount_point) @@ -342,7 +350,7 @@ Value* RenameFn(const char* name, State* state, int argc, Expr* argv[]) { return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name); } const std::string& src_name = args[0]; - std::string& dst_name = args[1]; + const std::string& dst_name = args[1]; if (src_name.empty()) { return ErrorAbort(state, kArgsParsingFailure, "src_name argument to %s() can't be empty", @@ -352,7 +360,7 @@ Value* RenameFn(const char* name, State* state, int argc, Expr* argv[]) { return ErrorAbort(state, kArgsParsingFailure, "dst_name argument to %s() can't be empty", name); } - if (make_parents(&dst_name[0]) != 0) { + if (!make_parents(dst_name)) { return ErrorAbort(state, kFileRenameFailure, "Creating parent of %s failed, error %s", dst_name.c_str(), strerror(errno)); } else if (access(dst_name.c_str(), F_OK) == 0 && access(src_name.c_str(), F_OK) != 0) { @@ -558,8 +566,9 @@ Value* PackageExtractFileFn(const char* name, State* state, } } -// 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); @@ -571,33 +580,29 @@ Value* SymlinkFn(const char* name, State* state, int argc, Expr* argv[]) { 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][0])) { + 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 { |