diff options
34 files changed, 572 insertions, 714 deletions
diff --git a/Android.mk b/Android.mk index 5b488ca6d..c2f98c6ed 100644 --- a/Android.mk +++ b/Android.mk @@ -14,18 +14,20 @@ LOCAL_PATH := $(call my-dir) +# libfusesideload (static library) +# =============================== include $(CLEAR_VARS) LOCAL_SRC_FILES := fuse_sideload.cpp LOCAL_CLANG := true LOCAL_CFLAGS := -O2 -g -DADB_HOST=0 -Wall -Wno-unused-parameter LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE - LOCAL_MODULE := libfusesideload - LOCAL_STATIC_LIBRARIES := libcutils libc libmincrypt include $(BUILD_STATIC_LIBRARY) +# recovery (static executable) +# =============================== include $(CLEAR_VARS) LOCAL_SRC_FILES := \ @@ -103,7 +105,8 @@ endif include $(BUILD_EXECUTABLE) -# All the APIs for testing +# libverifier (static library) +# =============================== include $(CLEAR_VARS) LOCAL_CLANG := true LOCAL_MODULE := libverifier diff --git a/applypatch/Android.mk b/applypatch/Android.mk index 887a570db..9e64718c1 100644 --- a/applypatch/Android.mk +++ b/applypatch/Android.mk @@ -14,61 +14,83 @@ LOCAL_PATH := $(call my-dir) +# libapplypatch (static library) +# =============================== include $(CLEAR_VARS) - LOCAL_CLANG := true -LOCAL_SRC_FILES := applypatch.cpp bspatch.cpp freecache.cpp imgpatch.cpp utils.cpp +LOCAL_SRC_FILES := \ + applypatch.cpp \ + bspatch.cpp \ + freecache.cpp \ + imgpatch.cpp \ + utils.cpp LOCAL_MODULE := libapplypatch LOCAL_MODULE_TAGS := eng -LOCAL_C_INCLUDES += bootable/recovery -LOCAL_STATIC_LIBRARIES += libbase libotafault libmtdutils libcrypto_static libbz libz - +LOCAL_C_INCLUDES += \ + $(LOCAL_PATH)/include \ + bootable/recovery +LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include +LOCAL_STATIC_LIBRARIES += \ + libotafault \ + libmtdutils \ + libbase \ + libcrypto_static \ + libbz \ + libz include $(BUILD_STATIC_LIBRARY) +# libimgpatch (static library) +# =============================== include $(CLEAR_VARS) - LOCAL_CLANG := true LOCAL_SRC_FILES := bspatch.cpp imgpatch.cpp utils.cpp LOCAL_MODULE := libimgpatch -LOCAL_C_INCLUDES += bootable/recovery +LOCAL_C_INCLUDES += \ + $(LOCAL_PATH)/include \ + bootable/recovery LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include LOCAL_STATIC_LIBRARIES += libcrypto_static libbz libz - include $(BUILD_STATIC_LIBRARY) -ifeq ($(HOST_OS),linux) +# libimgpatch (host static library) +# =============================== include $(CLEAR_VARS) - LOCAL_CLANG := true LOCAL_SRC_FILES := bspatch.cpp imgpatch.cpp utils.cpp LOCAL_MODULE := libimgpatch -LOCAL_C_INCLUDES += bootable/recovery +LOCAL_MODULE_HOST_OS := linux +LOCAL_C_INCLUDES += \ + $(LOCAL_PATH)/include \ + bootable/recovery LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include LOCAL_STATIC_LIBRARIES += libcrypto_static libbz libz - include $(BUILD_HOST_STATIC_LIBRARY) -endif # HOST_OS == linux +# applypatch (executable) +# =============================== include $(CLEAR_VARS) - LOCAL_CLANG := true LOCAL_SRC_FILES := main.cpp LOCAL_MODULE := applypatch LOCAL_C_INCLUDES += bootable/recovery -LOCAL_STATIC_LIBRARIES += libapplypatch libbase libotafault libmtdutils libcrypto_static libbz \ - libedify \ - +LOCAL_STATIC_LIBRARIES += \ + libapplypatch \ + libbase \ + libedify \ + libotafault \ + libminzip \ + libmtdutils \ + libcrypto_static \ + libbz LOCAL_SHARED_LIBRARIES += libz libcutils libc - include $(BUILD_EXECUTABLE) +# imgdiff (host static executable) +# =============================== include $(CLEAR_VARS) - LOCAL_CLANG := true LOCAL_SRC_FILES := imgdiff.cpp utils.cpp bsdiff.cpp LOCAL_MODULE := imgdiff -LOCAL_FORCE_STATIC_EXECUTABLE := true -LOCAL_C_INCLUDES += external/zlib external/bzip2 LOCAL_STATIC_LIBRARIES += libz libbz - +LOCAL_FORCE_STATIC_EXECUTABLE := true include $(BUILD_HOST_EXECUTABLE) diff --git a/applypatch/Makefile b/applypatch/Makefile new file mode 100644 index 000000000..fb4984303 --- /dev/null +++ b/applypatch/Makefile @@ -0,0 +1,33 @@ +# 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. + +# This file is for building imgdiff in Chrome OS. + +CPPFLAGS += -iquote.. -Iinclude +CXXFLAGS += -std=c++11 -O3 -Wall -Werror +LDLIBS += -lbz2 -lz + +.PHONY: all clean + +all: imgdiff libimgpatch.a + +clean: + rm -f *.o imgdiff libimgpatch.a + +imgdiff: imgdiff.o bsdiff.o utils.o + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDLIBS) -o $@ $^ + +libimgpatch.a utils.o: CXXFLAGS += -fPIC +libimgpatch.a: imgpatch.o bspatch.o utils.o + ${AR} rcs $@ $^ diff --git a/applypatch/applypatch.cpp b/applypatch/applypatch.cpp index 7985fc0c6..c8594c283 100644 --- a/applypatch/applypatch.cpp +++ b/applypatch/applypatch.cpp @@ -31,7 +31,7 @@ #include <android-base/strings.h> #include "openssl/sha.h" -#include "applypatch.h" +#include "applypatch/applypatch.h" #include "mtdutils/mtdutils.h" #include "edify/expr.h" #include "ota_io.h" @@ -77,7 +77,7 @@ int LoadFileContents(const char* filename, FileContents* file) { size_t bytes_read = ota_fread(data.data(), 1, data.size(), f); if (bytes_read != data.size()) { - printf("short read of \"%s\" (%zu bytes of %zd)\n", filename, bytes_read, data.size()); + printf("short read of \"%s\" (%zu bytes of %zu)\n", filename, bytes_read, data.size()); ota_fclose(f); return -1; } @@ -897,7 +897,7 @@ static int GenerateTarget(FileContents* source_file, } else { // We write the decoded output to "<tgt-file>.patch". output_fd = ota_open(tmp_target_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, - S_IRUSR | S_IWUSR); + S_IRUSR | S_IWUSR); if (output_fd < 0) { printf("failed to open output file %s: %s\n", tmp_target_filename.c_str(), strerror(errno)); diff --git a/applypatch/bsdiff.cpp b/applypatch/bsdiff.cpp index 55dbe5cf1..cca1b32fb 100644 --- a/applypatch/bsdiff.cpp +++ b/applypatch/bsdiff.cpp @@ -224,7 +224,6 @@ static void offtout(off_t x,u_char *buf) int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* newdata, off_t newsize, const char* patch_filename) { - int fd; off_t *I; off_t scan,pos,len; off_t lastscan,lastpos,lastoffset; diff --git a/applypatch/bspatch.cpp b/applypatch/bspatch.cpp index ebb55f1d1..a4945da28 100644 --- a/applypatch/bspatch.cpp +++ b/applypatch/bspatch.cpp @@ -30,7 +30,7 @@ #include <bzlib.h> #include "openssl/sha.h" -#include "applypatch.h" +#include "applypatch/applypatch.h" void ShowBSDiffLicense() { puts("The bsdiff library used herein is:\n" @@ -182,7 +182,6 @@ int ApplyBSDiffPatchMem(const unsigned char* old_data, ssize_t old_size, off_t oldpos = 0, newpos = 0; off_t ctrl[3]; - off_t len_read; int i; unsigned char buf[24]; while (newpos < new_size) { diff --git a/applypatch/freecache.cpp b/applypatch/freecache.cpp index c84f42797..331cae265 100644 --- a/applypatch/freecache.cpp +++ b/applypatch/freecache.cpp @@ -32,7 +32,7 @@ #include <android-base/parseint.h> #include <android-base/stringprintf.h> -#include "applypatch.h" +#include "applypatch/applypatch.h" static int EliminateOpenFiles(std::set<std::string>* files) { std::unique_ptr<DIR, decltype(&closedir)> d(opendir("/proc"), closedir); diff --git a/applypatch/imgdiff.cpp b/applypatch/imgdiff.cpp index f22502e38..2aa4a6862 100644 --- a/applypatch/imgdiff.cpp +++ b/applypatch/imgdiff.cpp @@ -407,7 +407,6 @@ unsigned char* ReadImage(const char* filename, while (pos < sz) { unsigned char* p = img+pos; - bool processed_deflate = false; if (sz - pos >= 4 && p[0] == 0x1f && p[1] == 0x8b && p[2] == 0x08 && // deflate compression @@ -461,28 +460,27 @@ unsigned char* ReadImage(const char* filename, strm.next_out = curr->data + curr->len; ret = inflate(&strm, Z_NO_FLUSH); if (ret < 0) { - if (!processed_deflate) { - // This is the first chunk, assume that it's just a spurious - // gzip header instead of a real one. - break; - } - printf("Error: inflate failed [%s] at file offset [%zu]\n" - "imgdiff only supports gzip kernel compression," - " did you try CONFIG_KERNEL_LZO?\n", + printf("Warning: inflate failed [%s] at offset [%zu]," + " treating as a normal chunk\n", strm.msg, chunk_offset); - free(img); - return NULL; + break; } curr->len = allocated - strm.avail_out; if (strm.avail_out == 0) { allocated *= 2; curr->data = reinterpret_cast<unsigned char*>(realloc(curr->data, allocated)); } - processed_deflate = true; } while (ret != Z_STREAM_END); curr->deflate_len = sz - strm.avail_in - pos; inflateEnd(&strm); + + if (ret < 0) { + free(curr->data); + *num_chunks -= 2; + continue; + } + pos += curr->deflate_len; p += curr->deflate_len; ++curr; @@ -598,7 +596,6 @@ int ReconstructDeflateChunk(ImageChunk* chunk) { return -1; } - size_t p = 0; unsigned char* out = reinterpret_cast<unsigned char*>(malloc(BUFFER_SIZE)); // We only check two combinations of encoder parameters: level 6 @@ -844,7 +841,6 @@ int main(int argc, char** argv) { } if (argc != 4) { - usage: printf("usage: %s [-z] [-b <bonus-file>] <src-img> <tgt-img> <patch-file>\n", argv[0]); return 2; diff --git a/applypatch/imgpatch.cpp b/applypatch/imgpatch.cpp index 8824038ea..4251c0120 100644 --- a/applypatch/imgpatch.cpp +++ b/applypatch/imgpatch.cpp @@ -28,7 +28,7 @@ #include "zlib.h" #include "openssl/sha.h" -#include "applypatch.h" +#include "applypatch/applypatch.h" #include "imgdiff.h" #include "utils.h" @@ -130,6 +130,7 @@ int ApplyImagePatch(const unsigned char* old_data, ssize_t old_size, size_t src_len = Read8(deflate_header+8); size_t patch_offset = Read8(deflate_header+16); size_t expanded_len = Read8(deflate_header+24); + size_t target_len = Read8(deflate_header+32); int level = Read4(deflate_header+40); int method = Read4(deflate_header+44); int windowBits = Read4(deflate_header+48); @@ -195,6 +196,11 @@ int ApplyImagePatch(const unsigned char* old_data, ssize_t old_size, &uncompressed_target_data) != 0) { return -1; } + if (uncompressed_target_data.size() != target_len) { + printf("expected target len to be %zu, but it's %zu\n", + target_len, uncompressed_target_data.size()); + return -1; + } // Now compress the target data and append it to the output. diff --git a/applypatch/applypatch.h b/applypatch/include/applypatch/applypatch.h index f392c5534..9ee39d293 100644 --- a/applypatch/applypatch.h +++ b/applypatch/include/applypatch/applypatch.h @@ -17,6 +17,7 @@ #ifndef _APPLYPATCH_H #define _APPLYPATCH_H +#include <stdint.h> #include <sys/stat.h> #include <vector> diff --git a/applypatch/libimgpatch.pc b/applypatch/libimgpatch.pc new file mode 100644 index 000000000..e5002934f --- /dev/null +++ b/applypatch/libimgpatch.pc @@ -0,0 +1,6 @@ +# This file is for libimgpatch in Chrome OS. + +Name: libimgpatch +Description: Apply imgdiff patch +Version: 0.0.1 +Libs: -limgpatch -lbz2 -lz diff --git a/applypatch/main.cpp b/applypatch/main.cpp index 9013760c4..0ff8cbf9a 100644 --- a/applypatch/main.cpp +++ b/applypatch/main.cpp @@ -22,7 +22,7 @@ #include <memory> #include <vector> -#include "applypatch.h" +#include "applypatch/applypatch.h" #include "edify/expr.h" #include "openssl/sha.h" diff --git a/bootloader.cpp b/bootloader.cpp index d80c5e793..a32f8b4c6 100644 --- a/bootloader.cpp +++ b/bootloader.cpp @@ -29,7 +29,7 @@ #include "common.h" #include "mtdutils/mtdutils.h" #include "roots.h" -#include "unique_fd.h" +#include <android-base/unique_fd.h> static int get_bootloader_message_mtd(bootloader_message* out, const Volume* v); static int set_bootloader_message_mtd(const bootloader_message* in, const Volume* v); @@ -191,8 +191,8 @@ static int get_bootloader_message_block(bootloader_message* out, static int set_bootloader_message_block(const bootloader_message* in, const Volume* v) { wait_for_device(v->blk_device); - unique_fd fd(open(v->blk_device, O_WRONLY | O_SYNC)); - if (fd.get() == -1) { + android::base::unique_fd fd(open(v->blk_device, O_WRONLY | O_SYNC)); + if (fd == -1) { LOGE("failed to open \"%s\": %s\n", v->blk_device, strerror(errno)); return -1; } @@ -201,7 +201,7 @@ static int set_bootloader_message_block(const bootloader_message* in, const uint8_t* start = reinterpret_cast<const uint8_t*>(in); size_t total = sizeof(*in); while (written < total) { - ssize_t wrote = TEMP_FAILURE_RETRY(write(fd.get(), start + written, total - written)); + ssize_t wrote = TEMP_FAILURE_RETRY(write(fd, start + written, total - written)); if (wrote == -1) { LOGE("failed to write %" PRId64 " bytes: %s\n", static_cast<off64_t>(written), strerror(errno)); @@ -210,7 +210,7 @@ static int set_bootloader_message_block(const bootloader_message* in, written += wrote; } - if (fsync(fd.get()) == -1) { + if (fsync(fd) == -1) { LOGE("failed to fsync \"%s\": %s\n", v->blk_device, strerror(errno)); return -1; } diff --git a/install.cpp b/install.cpp index 8a82d7bc4..144a353d6 100644 --- a/install.cpp +++ b/install.cpp @@ -124,20 +124,20 @@ try_update_binary(const char* path, ZipArchive* zip, bool* wipe_cache) { // - the name of the package zip file. // - const char** args = (const char**)malloc(sizeof(char*) * 5); + const char* args[5]; args[0] = binary; args[1] = EXPAND(RECOVERY_API_VERSION); // defined in Android.mk - char* temp = (char*)malloc(10); - sprintf(temp, "%d", pipefd[1]); + char temp[16]; + snprintf(temp, sizeof(temp), "%d", pipefd[1]); args[2] = temp; - args[3] = (char*)path; + args[3] = path; args[4] = NULL; pid_t pid = fork(); if (pid == 0) { umask(022); close(pipefd[0]); - execv(binary, (char* const*)args); + execv(binary, const_cast<char**>(args)); fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno)); _exit(-1); } diff --git a/minui/resources.cpp b/minui/resources.cpp index 63a0dff28..8489d60ef 100644 --- a/minui/resources.cpp +++ b/minui/resources.cpp @@ -28,6 +28,7 @@ #include <linux/fb.h> #include <linux/kd.h> +#include <vector> #include <png.h> #include "minui.h" @@ -282,7 +283,7 @@ int res_create_multi_display_surface(const char* name, int* frames, int* fps, goto exit; } - surface = reinterpret_cast<GRSurface**>(malloc(*frames * sizeof(GRSurface*))); + surface = reinterpret_cast<GRSurface**>(calloc(*frames, sizeof(GRSurface*))); if (surface == NULL) { result = -8; goto exit; @@ -317,7 +318,7 @@ exit: if (result < 0) { if (surface) { for (int i = 0; i < *frames; ++i) { - if (surface[i]) free(surface[i]); + free(surface[i]); } free(surface); } @@ -398,18 +399,13 @@ int res_create_localized_alpha_surface(const char* name, png_infop info_ptr = NULL; png_uint_32 width, height; png_byte channels; - unsigned char* row; png_uint_32 y; + std::vector<unsigned char> row; *pSurface = NULL; if (locale == NULL) { - surface = malloc_surface(0); - surface->width = 0; - surface->height = 0; - surface->row_bytes = 0; - surface->pixel_bytes = 1; - goto exit; + return result; } result = open_png(name, &png_ptr, &info_ptr, &width, &height, &channels); @@ -420,13 +416,13 @@ int res_create_localized_alpha_surface(const char* name, goto exit; } - row = reinterpret_cast<unsigned char*>(malloc(width)); + row.resize(width); for (y = 0; y < height; ++y) { - png_read_row(png_ptr, row, NULL); + png_read_row(png_ptr, row.data(), NULL); int w = (row[1] << 8) | row[0]; int h = (row[3] << 8) | row[2]; - int len = row[4]; - char* loc = (char*)row+5; + __unused int len = row[4]; + char* loc = reinterpret_cast<char*>(&row[5]); if (y+1+h >= height || matches_locale(loc, locale)) { printf(" %20s: %s (%d x %d @ %d)\n", name, loc, w, h, y); @@ -443,8 +439,8 @@ int res_create_localized_alpha_surface(const char* name, int i; for (i = 0; i < h; ++i, ++y) { - png_read_row(png_ptr, row, NULL); - memcpy(surface->data + i*w, row, w); + png_read_row(png_ptr, row.data(), NULL); + memcpy(surface->data + i*w, row.data(), w); } *pSurface = reinterpret_cast<GRSurface*>(surface); @@ -452,7 +448,7 @@ int res_create_localized_alpha_surface(const char* name, } else { int i; for (i = 0; i < h; ++i, ++y) { - png_read_row(png_ptr, row, NULL); + png_read_row(png_ptr, row.data(), NULL); } } } diff --git a/minzip/Android.mk b/minzip/Android.mk index 22eabfbb1..3d36fd64e 100644 --- a/minzip/Android.mk +++ b/minzip/Android.mk @@ -4,7 +4,7 @@ include $(CLEAR_VARS) LOCAL_SRC_FILES := \ Hash.c \ SysUtil.c \ - DirUtil.c \ + DirUtil.cpp \ Inlines.c \ Zip.c diff --git a/minzip/DirUtil.c b/minzip/DirUtil.cpp index 97cb2e0ee..823b6ed2f 100644 --- a/minzip/DirUtil.c +++ b/minzip/DirUtil.cpp @@ -24,6 +24,8 @@ #include <dirent.h> #include <limits.h> +#include <string> + #include "DirUtil.h" typedef enum { DMISSING, DDIR, DILLEGAL } DirStatus; @@ -66,43 +68,25 @@ dirCreateHierarchy(const char *path, int mode, errno = ENOENT; return -1; } - - /* Allocate a path that we can modify; stick a slash on - * the end to make things easier. - */ - size_t pathLen = strlen(path); - char *cpath = (char *)malloc(pathLen + 2); - if (cpath == NULL) { - errno = ENOMEM; - return -1; - } - memcpy(cpath, path, pathLen); + // Allocate a path that we can modify; stick a slash on + // the end to make things easier. + std::string cpath = path; if (stripFileName) { - /* Strip everything after the last slash. - */ - char *c = cpath + pathLen - 1; - while (c != cpath && *c != '/') { - c--; - } - if (c == cpath) { - //xxx test this path - /* No directory component. Act like the path was empty. - */ + // Strip everything after the last slash. + size_t pos = cpath.rfind('/'); + if (pos == std::string::npos) { errno = ENOENT; - free(cpath); return -1; } - c[1] = '\0'; // Terminate after the slash we found. + cpath.resize(pos + 1); } else { - /* Make sure that the path ends in a slash. - */ - cpath[pathLen] = '/'; - cpath[pathLen + 1] = '\0'; + // Make sure that the path ends in a slash. + cpath.push_back('/'); } /* See if it already exists. */ - ds = getPathDirStatus(cpath); + ds = getPathDirStatus(cpath.c_str()); if (ds == DDIR) { return 0; } else if (ds == DILLEGAL) { @@ -112,7 +96,8 @@ dirCreateHierarchy(const char *path, int mode, /* Walk up the path from the root and make each level. * If a directory already exists, no big deal. */ - char *p = cpath; + const char *path_start = &cpath[0]; + char *p = &cpath[0]; while (*p != '\0') { /* Skip any slashes, watching out for the end of the string. */ @@ -135,12 +120,11 @@ dirCreateHierarchy(const char *path, int mode, /* Check this part of the path and make a new directory * if necessary. */ - ds = getPathDirStatus(cpath); + ds = getPathDirStatus(path_start); if (ds == DILLEGAL) { /* Could happen if some other process/thread is * messing with the filesystem. */ - free(cpath); return -1; } else if (ds == DMISSING) { int err; @@ -148,11 +132,11 @@ dirCreateHierarchy(const char *path, int mode, char *secontext = NULL; if (sehnd) { - selabel_lookup(sehnd, &secontext, cpath, mode); + selabel_lookup(sehnd, &secontext, path_start, mode); setfscreatecon(secontext); } - err = mkdir(cpath, mode); + err = mkdir(path_start, mode); if (secontext) { freecon(secontext); @@ -160,22 +144,17 @@ dirCreateHierarchy(const char *path, int mode, } if (err != 0) { - free(cpath); return -1; } - if (timestamp != NULL && utime(cpath, timestamp)) { - free(cpath); + if (timestamp != NULL && utime(path_start, timestamp)) { return -1; } } // else, this directory already exists. - - /* Repair the path and continue. - */ + + // Repair the path and continue. *p = '/'; } - free(cpath); - return 0; } diff --git a/minzip/Zip.c b/minzip/Zip.c index bdb565c64..0f89835ca 100644 --- a/minzip/Zip.c +++ b/minzip/Zip.c @@ -91,7 +91,7 @@ enum { static void dumpEntry(const ZipEntry* pEntry) { LOGI(" %p '%.*s'\n", pEntry->fileName,pEntry->fileNameLen,pEntry->fileName); - LOGI(" off=%ld comp=%ld uncomp=%ld how=%d\n", pEntry->offset, + LOGI(" off=%u comp=%u uncomp=%u how=%d\n", pEntry->offset, pEntry->compLen, pEntry->uncompLen, pEntry->compression); } #endif @@ -505,13 +505,11 @@ static bool processDeflatedEntry(const ZipArchive *pArchive, const ZipEntry *pEntry, ProcessZipEntryContentsFunction processFunction, void *cookie) { - long result = -1; + bool success = false; + unsigned long totalOut = 0; unsigned char procBuf[32 * 1024]; z_stream zstream; int zerr; - long compRemaining; - - compRemaining = pEntry->compLen; /* * Initialize the zlib stream. @@ -572,16 +570,17 @@ static bool processDeflatedEntry(const ZipArchive *pArchive, assert(zerr == Z_STREAM_END); /* other errors should've been caught */ // success! - result = zstream.total_out; + totalOut = zstream.total_out; + success = true; z_bail: inflateEnd(&zstream); /* free up any allocated structures */ bail: - if (result != pEntry->uncompLen) { - if (result != -1) // error already shown? - LOGW("Size mismatch on inflated file (%ld vs %ld)\n", - result, pEntry->uncompLen); + if (totalOut != pEntry->uncompLen) { + if (success) { // error already shown? + LOGW("Size mismatch on inflated file (%lu vs %u)\n", totalOut, pEntry->uncompLen); + } return false; } return true; @@ -759,7 +758,7 @@ static const char *targetEntryPath(MzPathHelper *helper, ZipEntry *pEntry) */ needLen = helper->targetDirLen + 1 + pEntry->fileNameLen - helper->zipDirLen + 1; - if (needLen > helper->bufLen) { + if (firstTime || needLen > helper->bufLen) { char *newBuf; needLen *= 2; diff --git a/minzip/Zip.h b/minzip/Zip.h index 86d8db597..e6b19e1f0 100644 --- a/minzip/Zip.h +++ b/minzip/Zip.h @@ -32,9 +32,9 @@ extern "C" { typedef struct ZipEntry { unsigned int fileNameLen; const char* fileName; // not null-terminated - long offset; - long compLen; - long uncompLen; + uint32_t offset; + uint32_t compLen; + uint32_t uncompLen; int compression; long modTime; long crc32; @@ -85,10 +85,10 @@ void mzCloseZipArchive(ZipArchive* pArchive); const ZipEntry* mzFindZipEntry(const ZipArchive* pArchive, const char* entryName); -INLINE long mzGetZipEntryOffset(const ZipEntry* pEntry) { +INLINE uint32_t mzGetZipEntryOffset(const ZipEntry* pEntry) { return pEntry->offset; } -INLINE long mzGetZipEntryUncompLen(const ZipEntry* pEntry) { +INLINE uint32_t mzGetZipEntryUncompLen(const ZipEntry* pEntry) { return pEntry->uncompLen; } diff --git a/otafault/Android.mk b/otafault/Android.mk index ba7add855..d0b1174a4 100644 --- a/otafault/Android.mk +++ b/otafault/Android.mk @@ -32,6 +32,8 @@ LOCAL_WHOLE_STATIC_LIBRARIES := $(otafault_static_libs) include $(BUILD_STATIC_LIBRARY) +# otafault_test (static executable) +# =============================== include $(CLEAR_VARS) LOCAL_SRC_FILES := config.cpp ota_io.cpp test.cpp diff --git a/otafault/ota_io.cpp b/otafault/ota_io.cpp index 04458537b..94be8155a 100644 --- a/otafault/ota_io.cpp +++ b/otafault/ota_io.cpp @@ -92,6 +92,7 @@ size_t ota_fread(void* ptr, size_t size, size_t nitems, FILE* stream) { } } size_t status = fread(ptr, size, nitems, stream); + // If I/O error occurs, set the retry-update flag. if (status != nitems && errno == EIO) { have_eio_error = true; } diff --git a/recovery.cpp b/recovery.cpp index 7620f1a00..2d768ceb4 100644 --- a/recovery.cpp +++ b/recovery.cpp @@ -59,7 +59,6 @@ struct selabel_handle *sehandle; static const struct option OPTIONS[] = { - { "send_intent", required_argument, NULL, 'i' }, { "update_package", required_argument, NULL, 'u' }, { "retry_count", required_argument, NULL, 'n' }, { "wipe_data", no_argument, NULL, 'w' }, @@ -77,7 +76,6 @@ static const struct option OPTIONS[] = { static const char *CACHE_LOG_DIR = "/cache/recovery"; 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 *LAST_INSTALL_FILE = "/cache/recovery/last_install"; static const char *LOCALE_FILE = "/cache/recovery/last_locale"; @@ -110,10 +108,8 @@ static bool has_cache = false; * The recovery tool communicates with the main system through /cache files. * /cache/recovery/command - INPUT - command line for tool, one arg per line * /cache/recovery/log - OUTPUT - combined log file from recovery run(s) - * /cache/recovery/intent - OUTPUT - intent that was passed in * * 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 * --wipe_data - erase user data (and cache), then reboot * --wipe_cache - wipe cache (but not user data), then reboot @@ -470,22 +466,10 @@ static void copy_logs() { } // clear the recovery command and prepare to boot a (hopefully working) system, -// copy our log file to cache as well (for the system to read), and -// record any intent we were asked to communicate back to the system. -// this function is idempotent: call it as many times as you like. +// copy our log file to cache as well (for the system to read). This function is +// idempotent: call it as many times as you like. static void -finish_recovery(const char *send_intent) { - // By this point, we're ready to return to the main system... - if (send_intent != NULL && has_cache) { - FILE *fp = fopen_path(INTENT_FILE, "w"); - if (fp == NULL) { - LOGE("Can't open %s\n", INTENT_FILE); - } else { - fputs(send_intent, fp); - check_and_fclose(fp, INTENT_FILE); - } - } - +finish_recovery() { // Save the locale to cache, so if recovery is next started up // without a --locale argument (eg, directly from the bootloader) // it will use the last-known locale. @@ -972,7 +956,7 @@ static int apply_from_sdcard(Device* device, bool* wipe_cache) { static Device::BuiltinAction prompt_and_wait(Device* device, int status) { for (;;) { - finish_recovery(NULL); + finish_recovery(); switch (status) { case INSTALL_SUCCESS: case INSTALL_NONE: @@ -1214,7 +1198,6 @@ int main(int argc, char **argv) { get_args(&argc, &argv); - const char *send_intent = NULL; const char *update_package = NULL; bool should_wipe_data = false; bool should_wipe_cache = false; @@ -1228,7 +1211,6 @@ int main(int argc, char **argv) { int arg; while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) { switch (arg) { - case 'i': send_intent = optarg; break; case 'n': android::base::ParseInt(optarg, &retry_count, 0); break; case 'u': update_package = optarg; break; case 'w': should_wipe_data = true; break; @@ -1415,7 +1397,7 @@ int main(int argc, char **argv) { } // Save logs and clean up before rebooting or shutting down. - finish_recovery(send_intent); + finish_recovery(); switch (after) { case Device::SHUTDOWN: diff --git a/tests/component/verifier_test.cpp b/tests/component/verifier_test.cpp index 73f6ac9c4..c533b03f6 100644 --- a/tests/component/verifier_test.cpp +++ b/tests/component/verifier_test.cpp @@ -133,13 +133,13 @@ class MockUI : public RecoveryUI { void Init() { } void SetStage(int, int) { } void SetLocale(const char*) { } - void SetBackground(Icon icon) { } + void SetBackground(Icon /*icon*/) { } - void SetProgressType(ProgressType determinate) { } - void ShowProgress(float portion, float seconds) { } - void SetProgress(float fraction) { } + void SetProgressType(ProgressType /*determinate*/) { } + void ShowProgress(float /*portion*/, float /*seconds*/) { } + void SetProgress(float /*fraction*/) { } - void ShowText(bool visible) { } + void ShowText(bool /*visible*/) { } bool IsTextVisible() { return false; } bool WasTextEverVisible() { return false; } void Print(const char* fmt, ...) { @@ -156,9 +156,10 @@ class MockUI : public RecoveryUI { } void ShowFile(const char*) { } - void StartMenu(const char* const * headers, const char* const * items, - int initial_selection) { } - int SelectMenu(int sel) { return 0; } + void StartMenu(const char* const* /*headers*/, + const char* const* /*items*/, + int /*initial_selection*/) { } + int SelectMenu(int /*sel*/) { return 0; } void EndMenu() { } }; diff --git a/tools/ota/Android.mk b/tools/dumpkey/Android.mk index 142c3b257..31549146d 100644 --- a/tools/ota/Android.mk +++ b/tools/dumpkey/Android.mk @@ -15,19 +15,8 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_FORCE_STATIC_EXECUTABLE := true -LOCAL_MODULE := add-property-tag -LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES) -LOCAL_MODULE_TAGS := debug -LOCAL_SRC_FILES := add-property-tag.c -LOCAL_STATIC_LIBRARIES := libc -include $(BUILD_EXECUTABLE) - -include $(CLEAR_VARS) -LOCAL_FORCE_STATIC_EXECUTABLE := true -LOCAL_MODULE := check-lost+found -LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES) -LOCAL_MODULE_TAGS := debug -LOCAL_SRC_FILES := check-lost+found.c -LOCAL_STATIC_LIBRARIES := libcutils libc -include $(BUILD_EXECUTABLE) +LOCAL_MODULE := dumpkey +LOCAL_SRC_FILES := DumpPublicKey.java +LOCAL_JAR_MANIFEST := DumpPublicKey.mf +LOCAL_STATIC_JAVA_LIBRARIES := bouncycastle-host +include $(BUILD_HOST_JAVA_LIBRARY) diff --git a/tools/dumpkey/DumpPublicKey.java b/tools/dumpkey/DumpPublicKey.java new file mode 100644 index 000000000..3eb139842 --- /dev/null +++ b/tools/dumpkey/DumpPublicKey.java @@ -0,0 +1,270 @@ +/* + * Copyright (C) 2008 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. + */ + +package com.android.dumpkey; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +import java.io.FileInputStream; +import java.math.BigInteger; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.KeyStore; +import java.security.Key; +import java.security.PublicKey; +import java.security.Security; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.ECPoint; + +/** + * Command line tool to extract RSA public keys from X.509 certificates + * and output source code with data initializers for the keys. + * @hide + */ +class DumpPublicKey { + /** + * @param key to perform sanity checks on + * @return version number of key. Supported versions are: + * 1: 2048-bit RSA key with e=3 and SHA-1 hash + * 2: 2048-bit RSA key with e=65537 and SHA-1 hash + * 3: 2048-bit RSA key with e=3 and SHA-256 hash + * 4: 2048-bit RSA key with e=65537 and SHA-256 hash + * @throws Exception if the key has the wrong size or public exponent + */ + static int checkRSA(RSAPublicKey key, boolean useSHA256) throws Exception { + BigInteger pubexp = key.getPublicExponent(); + BigInteger modulus = key.getModulus(); + int version; + + if (pubexp.equals(BigInteger.valueOf(3))) { + version = useSHA256 ? 3 : 1; + } else if (pubexp.equals(BigInteger.valueOf(65537))) { + version = useSHA256 ? 4 : 2; + } else { + throw new Exception("Public exponent should be 3 or 65537 but is " + + pubexp.toString(10) + "."); + } + + if (modulus.bitLength() != 2048) { + throw new Exception("Modulus should be 2048 bits long but is " + + modulus.bitLength() + " bits."); + } + + return version; + } + + /** + * @param key to perform sanity checks on + * @return version number of key. Supported versions are: + * 5: 256-bit EC key with curve NIST P-256 + * @throws Exception if the key has the wrong size or public exponent + */ + static int checkEC(ECPublicKey key) throws Exception { + if (key.getParams().getCurve().getField().getFieldSize() != 256) { + throw new Exception("Curve must be NIST P-256"); + } + + return 5; + } + + /** + * Perform sanity check on public key. + */ + static int check(PublicKey key, boolean useSHA256) throws Exception { + if (key instanceof RSAPublicKey) { + return checkRSA((RSAPublicKey) key, useSHA256); + } else if (key instanceof ECPublicKey) { + if (!useSHA256) { + throw new Exception("Must use SHA-256 with EC keys!"); + } + return checkEC((ECPublicKey) key); + } else { + throw new Exception("Unsupported key class: " + key.getClass().getName()); + } + } + + /** + * @param key to output + * @return a String representing this public key. If the key is a + * version 1 key, the string will be a C initializer; this is + * not true for newer key versions. + */ + static String printRSA(RSAPublicKey key, boolean useSHA256) throws Exception { + int version = check(key, useSHA256); + + BigInteger N = key.getModulus(); + + StringBuilder result = new StringBuilder(); + + int nwords = N.bitLength() / 32; // # of 32 bit integers in modulus + + if (version > 1) { + result.append("v"); + result.append(Integer.toString(version)); + result.append(" "); + } + + result.append("{"); + result.append(nwords); + + BigInteger B = BigInteger.valueOf(0x100000000L); // 2^32 + BigInteger N0inv = B.subtract(N.modInverse(B)); // -1 / N[0] mod 2^32 + + result.append(",0x"); + result.append(N0inv.toString(16)); + + BigInteger R = BigInteger.valueOf(2).pow(N.bitLength()); + BigInteger RR = R.multiply(R).mod(N); // 2^4096 mod N + + // Write out modulus as little endian array of integers. + result.append(",{"); + for (int i = 0; i < nwords; ++i) { + long n = N.mod(B).longValue(); + result.append(n); + + if (i != nwords - 1) { + result.append(","); + } + + N = N.divide(B); + } + result.append("}"); + + // Write R^2 as little endian array of integers. + result.append(",{"); + for (int i = 0; i < nwords; ++i) { + long rr = RR.mod(B).longValue(); + result.append(rr); + + if (i != nwords - 1) { + result.append(","); + } + + RR = RR.divide(B); + } + result.append("}"); + + result.append("}"); + return result.toString(); + } + + /** + * @param key to output + * @return a String representing this public key. If the key is a + * version 1 key, the string will be a C initializer; this is + * not true for newer key versions. + */ + static String printEC(ECPublicKey key) throws Exception { + int version = checkEC(key); + + StringBuilder result = new StringBuilder(); + + result.append("v"); + result.append(Integer.toString(version)); + result.append(" "); + + BigInteger X = key.getW().getAffineX(); + BigInteger Y = key.getW().getAffineY(); + int nbytes = key.getParams().getCurve().getField().getFieldSize() / 8; // # of 32 bit integers in X coordinate + + result.append("{"); + result.append(nbytes); + + BigInteger B = BigInteger.valueOf(0x100L); // 2^8 + + // Write out Y coordinate as array of characters. + result.append(",{"); + for (int i = 0; i < nbytes; ++i) { + long n = X.mod(B).longValue(); + result.append(n); + + if (i != nbytes - 1) { + result.append(","); + } + + X = X.divide(B); + } + result.append("}"); + + // Write out Y coordinate as array of characters. + result.append(",{"); + for (int i = 0; i < nbytes; ++i) { + long n = Y.mod(B).longValue(); + result.append(n); + + if (i != nbytes - 1) { + result.append(","); + } + + Y = Y.divide(B); + } + result.append("}"); + + result.append("}"); + return result.toString(); + } + + static String print(PublicKey key, boolean useSHA256) throws Exception { + if (key instanceof RSAPublicKey) { + return printRSA((RSAPublicKey) key, useSHA256); + } else if (key instanceof ECPublicKey) { + return printEC((ECPublicKey) key); + } else { + throw new Exception("Unsupported key class: " + key.getClass().getName()); + } + } + + public static void main(String[] args) { + if (args.length < 1) { + System.err.println("Usage: DumpPublicKey certfile ... > source.c"); + System.exit(1); + } + Security.addProvider(new BouncyCastleProvider()); + try { + for (int i = 0; i < args.length; i++) { + FileInputStream input = new FileInputStream(args[i]); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509Certificate cert = (X509Certificate) cf.generateCertificate(input); + + boolean useSHA256 = false; + String sigAlg = cert.getSigAlgName(); + if ("SHA1withRSA".equals(sigAlg) || "MD5withRSA".equals(sigAlg)) { + // SignApk has historically accepted "MD5withRSA" + // certificates, but treated them as "SHA1withRSA" + // anyway. Continue to do so for backwards + // compatibility. + useSHA256 = false; + } else if ("SHA256withRSA".equals(sigAlg) || "SHA256withECDSA".equals(sigAlg)) { + useSHA256 = true; + } else { + System.err.println(args[i] + ": unsupported signature algorithm \"" + + sigAlg + "\""); + System.exit(1); + } + + PublicKey key = cert.getPublicKey(); + check(key, useSHA256); + System.out.print(print(key, useSHA256)); + System.out.println(i < args.length - 1 ? "," : ""); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + System.exit(0); + } +} diff --git a/tools/dumpkey/DumpPublicKey.mf b/tools/dumpkey/DumpPublicKey.mf new file mode 100644 index 000000000..7bb3bc88d --- /dev/null +++ b/tools/dumpkey/DumpPublicKey.mf @@ -0,0 +1 @@ +Main-Class: com.android.dumpkey.DumpPublicKey diff --git a/tools/ota/add-property-tag.c b/tools/ota/add-property-tag.c deleted file mode 100644 index aab30b2d0..000000000 --- a/tools/ota/add-property-tag.c +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2008 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 <ctype.h> -#include <errno.h> -#include <getopt.h> -#include <limits.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -/* - * Append a tag to a property value in a .prop file if it isn't already there. - * Normally used to modify build properties to record incremental updates. - */ - -// Return nonzero if the tag should be added to this line. -int should_tag(const char *line, const char *propname) { - const char *prop = strstr(line, propname); - if (prop == NULL) return 0; - - // Make sure this is actually the property name (not an accidental hit) - const char *ptr; - for (ptr = line; ptr < prop && isspace(*ptr); ++ptr) ; - if (ptr != prop) return 0; // Must be at the beginning of the line - - for (ptr += strlen(propname); *ptr != '\0' && isspace(*ptr); ++ptr) ; - return (*ptr == '='); // Must be followed by a '=' -} - -// Remove existing tags from the line, return the following number (if any) -int remove_tag(char *line, const char *tag) { - char *pos = strstr(line, tag); - if (pos == NULL) return 0; - - char *end; - int num = strtoul(pos + strlen(tag), &end, 10); - strcpy(pos, end); - return num; -} - -// Write line to output with the tag added, adding a number (if >0) -void write_tagged(FILE *out, const char *line, const char *tag, int number) { - const char *end = line + strlen(line); - while (end > line && isspace(end[-1])) --end; - if (number > 0) { - fprintf(out, "%.*s%s%d%s", (int)(end - line), line, tag, number, end); - } else { - fprintf(out, "%.*s%s%s", (int)(end - line), line, tag, end); - } -} - -int main(int argc, char **argv) { - const char *filename = "/system/build.prop"; - const char *propname = "ro.build.fingerprint"; - const char *tag = NULL; - int do_remove = 0, do_number = 0; - - int opt; - while ((opt = getopt(argc, argv, "f:p:rn")) != -1) { - switch (opt) { - case 'f': filename = optarg; break; - case 'p': propname = optarg; break; - case 'r': do_remove = 1; break; - case 'n': do_number = 1; break; - case '?': return 2; - } - } - - if (argc != optind + 1) { - fprintf(stderr, - "usage: add-property-tag [flags] tag-to-add\n" - "flags: -f /dir/file.prop (default /system/build.prop)\n" - " -p prop.name (default ro.build.fingerprint)\n" - " -r (if set, remove the tag rather than adding it)\n" - " -n (if set, add and increment a number after the tag)\n"); - return 2; - } - - tag = argv[optind]; - FILE *input = fopen(filename, "r"); - if (input == NULL) { - fprintf(stderr, "can't read %s: %s\n", filename, strerror(errno)); - return 1; - } - - char tmpname[PATH_MAX]; - snprintf(tmpname, sizeof(tmpname), "%s.tmp", filename); - FILE *output = fopen(tmpname, "w"); - if (output == NULL) { - fprintf(stderr, "can't write %s: %s\n", tmpname, strerror(errno)); - return 1; - } - - int found = 0; - char line[4096]; - while (fgets(line, sizeof(line), input)) { - if (!should_tag(line, propname)) { - fputs(line, output); // Pass through unmodified - } else { - found = 1; - int number = remove_tag(line, tag); - if (do_remove) { - fputs(line, output); // Remove the tag but don't re-add it - } else { - write_tagged(output, line, tag, number + do_number); - } - } - } - - fclose(input); - fclose(output); - - if (!found) { - fprintf(stderr, "property %s not found in %s\n", propname, filename); - remove(tmpname); - return 1; - } - - if (rename(tmpname, filename)) { - fprintf(stderr, "can't rename %s to %s: %s\n", - tmpname, filename, strerror(errno)); - remove(tmpname); - return 1; - } - - return 0; -} diff --git a/tools/ota/check-lost+found.c b/tools/ota/check-lost+found.c deleted file mode 100644 index 8ce12d39f..000000000 --- a/tools/ota/check-lost+found.c +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2008 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 <dirent.h> -#include <errno.h> -#include <fcntl.h> -#include <limits.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/klog.h> -#include <sys/reboot.h> -#include <sys/stat.h> -#include <sys/types.h> -#include <time.h> -#include <unistd.h> - -#include "private/android_filesystem_config.h" - -// Sentinel file used to track whether we've forced a reboot -static const char *kMarkerFile = "/data/misc/check-lost+found-rebooted-2"; - -// Output file in tombstones directory (first 8K will be uploaded) -static const char *kOutputDir = "/data/tombstones"; -static const char *kOutputFile = "/data/tombstones/check-lost+found-log"; - -// Partitions to check -static const char *kPartitions[] = { "/system", "/data", "/cache", NULL }; - -/* - * 1. If /data/misc/forced-reboot is missing, touch it & force "unclean" boot. - * 2. Write a log entry with the number of files in lost+found directories. - */ - -int main(int argc __attribute__((unused)), char **argv __attribute__((unused))) { - mkdir(kOutputDir, 0755); - chown(kOutputDir, AID_SYSTEM, AID_SYSTEM); - FILE *out = fopen(kOutputFile, "a"); - if (out == NULL) { - fprintf(stderr, "Can't write %s: %s\n", kOutputFile, strerror(errno)); - return 1; - } - - // Note: only the first 8K of log will be uploaded, so be terse. - time_t start = time(NULL); - fprintf(out, "*** check-lost+found ***\nStarted: %s", ctime(&start)); - - struct stat st; - if (stat(kMarkerFile, &st)) { - // No reboot marker -- need to force an unclean reboot. - // But first, try to create the marker file. If that fails, - // skip the reboot, so we don't get caught in an infinite loop. - - int fd = open(kMarkerFile, O_WRONLY|O_CREAT, 0444); - if (fd >= 0 && close(fd) == 0) { - fprintf(out, "Wrote %s, rebooting\n", kMarkerFile); - fflush(out); - sync(); // Make sure the marker file is committed to disk - - // If possible, dirty each of these partitions before rebooting, - // to make sure the filesystem has to do a scan on mount. - int i; - for (i = 0; kPartitions[i] != NULL; ++i) { - char fn[PATH_MAX]; - snprintf(fn, sizeof(fn), "%s/%s", kPartitions[i], "dirty"); - fd = open(fn, O_WRONLY|O_CREAT, 0444); - if (fd >= 0) { // Don't sweat it if we can't write the file. - TEMP_FAILURE_RETRY(write(fd, fn, sizeof(fn))); // write, you know, some data - close(fd); - unlink(fn); - } - } - - reboot(RB_AUTOBOOT); // reboot immediately, with dirty filesystems - fprintf(out, "Reboot failed?!\n"); - exit(1); - } else { - fprintf(out, "Can't write %s: %s\n", kMarkerFile, strerror(errno)); - } - } else { - fprintf(out, "Found %s\n", kMarkerFile); - } - - int i; - for (i = 0; kPartitions[i] != NULL; ++i) { - char fn[PATH_MAX]; - snprintf(fn, sizeof(fn), "%s/%s", kPartitions[i], "lost+found"); - DIR *dir = opendir(fn); - if (dir == NULL) { - fprintf(out, "Can't open %s: %s\n", fn, strerror(errno)); - } else { - int count = 0; - struct dirent *ent; - while ((ent = readdir(dir))) { - if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) - ++count; - } - closedir(dir); - if (count > 0) { - fprintf(out, "OMGZ FOUND %d FILES IN %s\n", count, fn); - } else { - fprintf(out, "%s is clean\n", fn); - } - } - } - - char dmesg[131073]; - int len = klogctl(KLOG_READ_ALL, dmesg, sizeof(dmesg) - 1); - if (len < 0) { - fprintf(out, "Can't read kernel log: %s\n", strerror(errno)); - } else { // To conserve space, only write lines with certain keywords - fprintf(out, "--- Kernel log ---\n"); - dmesg[len] = '\0'; - char *saveptr, *line; - int in_yaffs = 0; - for (line = strtok_r(dmesg, "\n", &saveptr); line != NULL; - line = strtok_r(NULL, "\n", &saveptr)) { - if (strstr(line, "yaffs: dev is")) in_yaffs = 1; - - if (in_yaffs || - strstr(line, "yaffs") || - strstr(line, "mtd") || - strstr(line, "msm_nand")) { - fprintf(out, "%s\n", line); - } - - if (strstr(line, "yaffs_read_super: isCheckpointed")) in_yaffs = 0; - } - } - - return 0; -} diff --git a/tools/ota/convert-to-bmp.py b/tools/ota/convert-to-bmp.py deleted file mode 100644 index 446c09da8..000000000 --- a/tools/ota/convert-to-bmp.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python2.4 - -"""A simple script to convert asset images to BMP files, that supports -RGBA image.""" - -import struct -import Image -import sys - -infile = sys.argv[1] -outfile = sys.argv[2] - -if not outfile.endswith(".bmp"): - print >> sys.stderr, "Warning: I'm expecting to write BMP files." - -im = Image.open(infile) -if im.mode == 'RGB': - im.save(outfile) -elif im.mode == 'RGBA': - # Python Imaging Library doesn't write RGBA BMP files, so we roll - # our own. - - BMP_HEADER_FMT = ("<" # little-endian - "H" # signature - "L" # file size - "HH" # reserved (set to 0) - "L" # offset to start of bitmap data) - ) - - BITMAPINFO_HEADER_FMT= ("<" # little-endian - "L" # size of this struct - "L" # width - "L" # height - "H" # planes (set to 1) - "H" # bit count - "L" # compression (set to 0 for minui) - "L" # size of image data (0 if uncompressed) - "L" # x pixels per meter (1) - "L" # y pixels per meter (1) - "L" # colors used (0) - "L" # important colors (0) - ) - - fileheadersize = struct.calcsize(BMP_HEADER_FMT) - infoheadersize = struct.calcsize(BITMAPINFO_HEADER_FMT) - - header = struct.pack(BMP_HEADER_FMT, - 0x4d42, # "BM" in little-endian - (fileheadersize + infoheadersize + - im.size[0] * im.size[1] * 4), - 0, 0, - fileheadersize + infoheadersize) - - info = struct.pack(BITMAPINFO_HEADER_FMT, - infoheadersize, - im.size[0], - im.size[1], - 1, - 32, - 0, - 0, - 1, - 1, - 0, - 0) - - f = open(outfile, "wb") - f.write(header) - f.write(info) - data = im.tostring() - for j in range(im.size[1]-1, -1, -1): # rows bottom-to-top - for i in range(j*im.size[0]*4, (j+1)*im.size[0]*4, 4): - f.write(data[i+2]) # B - f.write(data[i+1]) # G - f.write(data[i+0]) # R - f.write(data[i+3]) # A - f.close() -else: - print >> sys.stderr, "Don't know how to handle image mode '%s'." % (im.mode,) diff --git a/uncrypt/uncrypt.cpp b/uncrypt/uncrypt.cpp index e783b9e7a..2986606e1 100644 --- a/uncrypt/uncrypt.cpp +++ b/uncrypt/uncrypt.cpp @@ -109,6 +109,7 @@ #include <android-base/logging.h> #include <android-base/stringprintf.h> #include <android-base/strings.h> +#include <android-base/unique_fd.h> #include <cutils/android_reboot.h> #include <cutils/properties.h> #include <cutils/sockets.h> @@ -118,7 +119,6 @@ #include <log/log.h> #include "bootloader.h" -#include "unique_fd.h" #define WINDOW_SIZE 5 @@ -237,8 +237,9 @@ static int produce_block_map(const char* path, const char* map_file, const char* return -1; } std::string tmp_map_file = std::string(map_file) + ".tmp"; - unique_fd mapfd(open(tmp_map_file.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)); - if (!mapfd) { + android::base::unique_fd mapfd(open(tmp_map_file.c_str(), + O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)); + if (mapfd == -1) { ALOGE("failed to open %s: %s\n", tmp_map_file.c_str(), strerror(errno)); return -1; } @@ -264,7 +265,7 @@ static int produce_block_map(const char* path, const char* map_file, const char* std::string s = android::base::StringPrintf("%s\n%" PRId64 " %ld\n", blk_dev, sb.st_size, static_cast<long>(sb.st_blksize)); - if (!android::base::WriteStringToFd(s, mapfd.get())) { + if (!android::base::WriteStringToFd(s, mapfd)) { ALOGE("failed to write %s: %s", tmp_map_file.c_str(), strerror(errno)); return -1; } @@ -276,16 +277,16 @@ static int produce_block_map(const char* path, const char* map_file, const char* int head_block = 0; int head = 0, tail = 0; - unique_fd fd(open(path, O_RDONLY)); - if (!fd) { + android::base::unique_fd fd(open(path, O_RDONLY)); + if (fd == -1) { ALOGE("failed to open %s for reading: %s", path, strerror(errno)); return -1; } - unique_fd wfd(-1); + android::base::unique_fd wfd; if (encrypted) { - wfd = open(blk_dev, O_WRONLY); - if (!wfd) { + wfd.reset(open(blk_dev, O_WRONLY)); + if (wfd == -1) { ALOGE("failed to open fd for writing: %s", strerror(errno)); return -1; } @@ -304,14 +305,14 @@ static int produce_block_map(const char* path, const char* map_file, const char* if ((tail+1) % WINDOW_SIZE == head) { // write out head buffer int block = head_block; - if (ioctl(fd.get(), FIBMAP, &block) != 0) { + if (ioctl(fd, FIBMAP, &block) != 0) { ALOGE("failed to find block %d", head_block); return -1; } add_block_to_ranges(ranges, block); if (encrypted) { - if (write_at_offset(buffers[head].data(), sb.st_blksize, wfd.get(), - static_cast<off64_t>(sb.st_blksize) * block) != 0) { + if (write_at_offset(buffers[head].data(), sb.st_blksize, wfd, + static_cast<off64_t>(sb.st_blksize) * block) != 0) { return -1; } } @@ -323,7 +324,7 @@ static int produce_block_map(const char* path, const char* map_file, const char* if (encrypted) { size_t to_read = static_cast<size_t>( std::min(static_cast<off64_t>(sb.st_blksize), sb.st_size - pos)); - if (!android::base::ReadFully(fd.get(), buffers[tail].data(), to_read)) { + if (!android::base::ReadFully(fd, buffers[tail].data(), to_read)) { ALOGE("failed to read: %s", strerror(errno)); return -1; } @@ -340,14 +341,14 @@ static int produce_block_map(const char* path, const char* map_file, const char* while (head != tail) { // write out head buffer int block = head_block; - if (ioctl(fd.get(), FIBMAP, &block) != 0) { + if (ioctl(fd, FIBMAP, &block) != 0) { ALOGE("failed to find block %d", head_block); return -1; } add_block_to_ranges(ranges, block); if (encrypted) { - if (write_at_offset(buffers[head].data(), sb.st_blksize, wfd.get(), - static_cast<off64_t>(sb.st_blksize) * block) != 0) { + if (write_at_offset(buffers[head].data(), sb.st_blksize, wfd, + static_cast<off64_t>(sb.st_blksize) * block) != 0) { return -1; } } @@ -356,38 +357,36 @@ static int produce_block_map(const char* path, const char* map_file, const char* } if (!android::base::WriteStringToFd( - android::base::StringPrintf("%zu\n", ranges.size() / 2), mapfd.get())) { + android::base::StringPrintf("%zu\n", ranges.size() / 2), mapfd)) { ALOGE("failed to write %s: %s", tmp_map_file.c_str(), strerror(errno)); return -1; } for (size_t i = 0; i < ranges.size(); i += 2) { if (!android::base::WriteStringToFd( - android::base::StringPrintf("%d %d\n", ranges[i], ranges[i+1]), mapfd.get())) { + android::base::StringPrintf("%d %d\n", ranges[i], ranges[i+1]), mapfd)) { ALOGE("failed to write %s: %s", tmp_map_file.c_str(), strerror(errno)); return -1; } } - if (fsync(mapfd.get()) == -1) { + if (fsync(mapfd) == -1) { ALOGE("failed to fsync \"%s\": %s", tmp_map_file.c_str(), strerror(errno)); return -1; } - if (close(mapfd.get() == -1)) { + if (close(mapfd.release()) == -1) { ALOGE("failed to close %s: %s", tmp_map_file.c_str(), strerror(errno)); return -1; } - mapfd = -1; if (encrypted) { - if (fsync(wfd.get()) == -1) { + if (fsync(wfd) == -1) { ALOGE("failed to fsync \"%s\": %s", blk_dev, strerror(errno)); return -1; } - if (close(wfd.get()) == -1) { + if (close(wfd.release()) == -1) { ALOGE("failed to close %s: %s", blk_dev, strerror(errno)); return -1; } - wfd = -1; } if (rename(tmp_map_file.c_str(), map_file) == -1) { @@ -397,20 +396,19 @@ static int produce_block_map(const char* path, const char* map_file, const char* // Sync dir to make rename() result written to disk. std::string file_name = map_file; std::string dir_name = dirname(&file_name[0]); - unique_fd dfd(open(dir_name.c_str(), O_RDONLY | O_DIRECTORY)); - if (!dfd) { + android::base::unique_fd dfd(open(dir_name.c_str(), O_RDONLY | O_DIRECTORY)); + if (dfd == -1) { ALOGE("failed to open dir %s: %s", dir_name.c_str(), strerror(errno)); return -1; } - if (fsync(dfd.get()) == -1) { + if (fsync(dfd) == -1) { ALOGE("failed to fsync %s: %s", dir_name.c_str(), strerror(errno)); return -1; } - if (close(dfd.get() == -1)) { + if (close(dfd.release()) == -1) { ALOGE("failed to close %s: %s", dir_name.c_str(), strerror(errno)); return -1; } - dfd = -1; return 0; } @@ -431,12 +429,12 @@ static int read_bootloader_message(bootloader_message* out) { ALOGE("failed to find /misc partition."); return -1; } - unique_fd fd(open(misc_blk_device.c_str(), O_RDONLY)); - if (!fd) { + android::base::unique_fd fd(open(misc_blk_device.c_str(), O_RDONLY)); + if (fd == -1) { ALOGE("failed to open %s: %s", misc_blk_device.c_str(), strerror(errno)); return -1; } - if (!android::base::ReadFully(fd.get(), out, sizeof(*out))) { + if (!android::base::ReadFully(fd, out, sizeof(*out))) { ALOGE("failed to read %s: %s", misc_blk_device.c_str(), strerror(errno)); return -1; } @@ -449,17 +447,17 @@ static int write_bootloader_message(const bootloader_message* in) { ALOGE("failed to find /misc partition."); return -1; } - unique_fd fd(open(misc_blk_device.c_str(), O_WRONLY | O_SYNC)); - if (!fd) { + android::base::unique_fd fd(open(misc_blk_device.c_str(), O_WRONLY | O_SYNC)); + if (fd == -1) { ALOGE("failed to open %s: %s", misc_blk_device.c_str(), strerror(errno)); return -1; } - if (!android::base::WriteFully(fd.get(), in, sizeof(*in))) { + if (!android::base::WriteFully(fd, in, sizeof(*in))) { ALOGE("failed to write %s: %s", misc_blk_device.c_str(), strerror(errno)); return -1; } // TODO: O_SYNC and fsync() duplicates each other? - if (fsync(fd.get()) == -1) { + if (fsync(fd) == -1) { ALOGE("failed to fsync %s: %s", misc_blk_device.c_str(), strerror(errno)); return -1; } @@ -617,20 +615,20 @@ int main(int argc, char** argv) { // c3. The socket is created by init when starting the service. uncrypt // will use the socket to communicate with its caller. - unique_fd service_socket(android_get_control_socket(UNCRYPT_SOCKET.c_str())); - if (!service_socket) { + android::base::unique_fd service_socket(android_get_control_socket(UNCRYPT_SOCKET.c_str())); + if (service_socket == -1) { ALOGE("failed to open socket \"%s\": %s", UNCRYPT_SOCKET.c_str(), strerror(errno)); return 1; } - fcntl(service_socket.get(), F_SETFD, FD_CLOEXEC); + fcntl(service_socket, F_SETFD, FD_CLOEXEC); - if (listen(service_socket.get(), 1) == -1) { + if (listen(service_socket, 1) == -1) { ALOGE("failed to listen on socket %d: %s", service_socket.get(), strerror(errno)); return 1; } - unique_fd socket_fd(accept4(service_socket.get(), nullptr, nullptr, SOCK_CLOEXEC)); - if (!socket_fd) { + android::base::unique_fd socket_fd(accept4(service_socket, nullptr, nullptr, SOCK_CLOEXEC)); + if (socket_fd == -1) { ALOGE("failed to accept on socket %d: %s", service_socket.get(), strerror(errno)); return 1; } @@ -638,13 +636,13 @@ int main(int argc, char** argv) { bool success = false; switch (action) { case UNCRYPT: - success = uncrypt_wrapper(input_path, map_file, socket_fd.get()); + success = uncrypt_wrapper(input_path, map_file, socket_fd); break; case SETUP_BCB: - success = setup_bcb(socket_fd.get()); + success = setup_bcb(socket_fd); break; case CLEAR_BCB: - success = clear_bcb(socket_fd.get()); + success = clear_bcb(socket_fd); break; default: // Should never happen. ALOGE("Invalid uncrypt action code: %d", action); @@ -655,7 +653,7 @@ int main(int argc, char** argv) { // ensure the client to receive the last status code before the socket gets // destroyed. int code; - if (android::base::ReadFully(socket_fd.get(), &code, 4)) { + if (android::base::ReadFully(socket_fd, &code, 4)) { ALOGI(" received %d, exiting now", code); } else { ALOGE("failed to read the code: %s", strerror(errno)); diff --git a/unique_fd.h b/unique_fd.h deleted file mode 100644 index cc85383f8..000000000 --- a/unique_fd.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2015 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 UNIQUE_FD_H -#define UNIQUE_FD_H - -#include <stdio.h> - -#include <memory> - -class unique_fd { - public: - unique_fd(int fd) : fd_(fd) { } - - unique_fd(unique_fd&& uf) { - fd_ = uf.fd_; - uf.fd_ = -1; - } - - ~unique_fd() { - if (fd_ != -1) { - close(fd_); - } - } - - int get() { - return fd_; - } - - // Movable. - unique_fd& operator=(unique_fd&& uf) { - fd_ = uf.fd_; - uf.fd_ = -1; - return *this; - } - - explicit operator bool() const { - return fd_ != -1; - } - - private: - int fd_; - - // Non-copyable. - unique_fd(const unique_fd&) = delete; - unique_fd& operator=(const unique_fd&) = delete; -}; - -#endif // UNIQUE_FD_H diff --git a/updater/Android.mk b/updater/Android.mk index d7aa613e9..47c56ccd9 100644 --- a/updater/Android.mk +++ b/updater/Android.mk @@ -14,26 +14,50 @@ LOCAL_PATH := $(call my-dir) -updater_src_files := \ - install.cpp \ - blockimg.cpp \ - updater.cpp - -# -# Build a statically-linked binary to include in OTA packages -# +# updater (static executable) +# =============================== +# Build a statically-linked binary to include in OTA packages. include $(CLEAR_VARS) -# Build only in eng, so we don't end up with a copy of this in /system -# on user builds. (TODO: find a better way to build device binaries -# needed only for OTA packages.) -LOCAL_MODULE_TAGS := eng +updater_src_files := \ + install.cpp \ + blockimg.cpp \ + updater.cpp LOCAL_CLANG := true - LOCAL_SRC_FILES := $(updater_src_files) -LOCAL_STATIC_LIBRARIES += libfec libfec_rs libext4_utils_static libsquashfs_utils libcrypto_static +LOCAL_STATIC_LIBRARIES += \ + $(TARGET_RECOVERY_UPDATER_LIBS) \ + $(TARGET_RECOVERY_UPDATER_EXTRA_LIBS) \ + libfec \ + libfec_rs \ + libext4_utils_static \ + libsquashfs_utils \ + libcrypto_static \ + libapplypatch \ + libbase \ + libotafault \ + libedify \ + libmtdutils \ + libminzip \ + libz \ + libbz \ + libcutils \ + liblog \ + libselinux + +tune2fs_static_libraries := \ + libext2_com_err \ + libext2_blkid \ + libext2_quota \ + libext2_uuid_static \ + libext2_e2p \ + libext2fs + +LOCAL_STATIC_LIBRARIES += \ + libtune2fs \ + $(tune2fs_static_libraries) ifeq ($(TARGET_USERIMAGES_USE_EXT4), true) LOCAL_CFLAGS += -DUSE_EXT4 @@ -44,20 +68,6 @@ LOCAL_STATIC_LIBRARIES += \ libz endif -LOCAL_STATIC_LIBRARIES += $(TARGET_RECOVERY_UPDATER_LIBS) $(TARGET_RECOVERY_UPDATER_EXTRA_LIBS) -LOCAL_STATIC_LIBRARIES += libapplypatch libbase libotafault libedify libmtdutils libminzip libz -LOCAL_STATIC_LIBRARIES += libbz -LOCAL_STATIC_LIBRARIES += libcutils liblog libc -LOCAL_STATIC_LIBRARIES += libselinux -tune2fs_static_libraries := \ - libext2_com_err \ - libext2_blkid \ - libext2_quota \ - libext2_uuid_static \ - libext2_e2p \ - libext2fs -LOCAL_STATIC_LIBRARIES += libtune2fs $(tune2fs_static_libraries) - LOCAL_C_INCLUDES += external/e2fsprogs/misc LOCAL_C_INCLUDES += $(LOCAL_PATH)/.. diff --git a/updater/blockimg.cpp b/updater/blockimg.cpp index c20bad904..908e11631 100644 --- a/updater/blockimg.cpp +++ b/updater/blockimg.cpp @@ -40,6 +40,7 @@ #include <android-base/parseint.h> #include <android-base/strings.h> +#include <android-base/unique_fd.h> #include "applypatch/applypatch.h" #include "edify/expr.h" @@ -48,7 +49,6 @@ #include "minzip/Hash.h" #include "ota_io.h" #include "print_sha1.h" -#include "unique_fd.h" #include "updater.h" #define BLOCKSIZE 4096 @@ -368,7 +368,7 @@ struct CommandParameters { std::string stashbase; bool canwrite; int createdstash; - int fd; + android::base::unique_fd fd; bool foundwrites; bool isunresumable; int version; @@ -577,9 +577,7 @@ static int LoadStash(CommandParameters& params, const std::string& base, const s return -1; } - int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY)); - unique_fd fd_holder(fd); - + android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY))); if (fd == -1) { fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno)); return -1; @@ -634,9 +632,9 @@ static int WriteStash(const std::string& base, const std::string& id, int blocks fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str()); - int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)); - unique_fd fd_holder(fd); - + android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), + O_WRONLY | O_CREAT | O_TRUNC, + STASH_FILE_MODE))); if (fd == -1) { fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno)); return -1; @@ -658,9 +656,8 @@ static int WriteStash(const std::string& base, const std::string& id, int blocks } std::string dname = GetStashFileName(base, "", ""); - int dfd = TEMP_FAILURE_RETRY(open(dname.c_str(), O_RDONLY | O_DIRECTORY)); - unique_fd dfd_holder(dfd); - + android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(), + O_RDONLY | O_DIRECTORY))); if (dfd == -1) { fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno)); return -1; @@ -942,8 +939,8 @@ static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& tgthash = params.tokens[params.cpos++]; } - if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd, params.stashbase, - &overlap) == -1) { + if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd, + params.stashbase, &overlap) == -1) { return -1; } @@ -1385,9 +1382,7 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int /* arg return StringValue(strdup("")); } - params.fd = TEMP_FAILURE_RETRY(open(blockdev_filename->data, O_RDWR)); - unique_fd fd_holder(params.fd); - + params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data, O_RDWR))); if (params.fd == -1) { fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno)); return StringValue(strdup("")); @@ -1532,7 +1527,7 @@ pbiudone: if (ota_fsync(params.fd) == -1) { fprintf(stderr, "fsync failed: %s\n", strerror(errno)); } - // params.fd will be automatically closed because of the fd_holder above. + // params.fd will be automatically closed because it's a unique_fd. // Only delete the stash if the update cannot be resumed, or it's // a verification run and we created the stash. @@ -1653,9 +1648,8 @@ Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) return StringValue(strdup("")); } - int fd = open(blockdev_filename->data, O_RDWR); - unique_fd fd_holder(fd); - if (fd < 0) { + android::base::unique_fd fd(ota_open(blockdev_filename->data, O_RDWR)); + if (fd == -1) { ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno)); return StringValue(strdup("")); } @@ -1676,7 +1670,7 @@ Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) { if (read_all(fd, buffer, BLOCKSIZE) == -1) { ErrorAbort(state, "failed to read %s: %s", blockdev_filename->data, - strerror(errno)); + strerror(errno)); return StringValue(strdup("")); } @@ -1707,8 +1701,7 @@ Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) return StringValue(strdup("")); } - int fd = open(arg_filename->data, O_RDONLY); - unique_fd fd_holder(fd); + android::base::unique_fd fd(ota_open(arg_filename->data, O_RDONLY)); if (fd == -1) { ErrorAbort(state, "open \"%s\" failed: %s", arg_filename->data, strerror(errno)); return StringValue(strdup("")); @@ -1718,8 +1711,7 @@ Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) std::vector<uint8_t> block0_buffer(BLOCKSIZE); if (ReadBlocks(blk0, block0_buffer, fd) == -1) { - ErrorAbort(state, "failed to read %s: %s", arg_filename->data, - strerror(errno)); + ErrorAbort(state, "failed to read %s: %s", arg_filename->data, strerror(errno)); return StringValue(strdup("")); } diff --git a/updater/install.cpp b/updater/install.cpp index 6ae1e5fbf..bc4cca913 100644 --- a/updater/install.cpp +++ b/updater/install.cpp @@ -996,7 +996,7 @@ Value* FileGetPropFn(const char* name, State* state, int argc, Expr* argv[]) { } FILE* f; - f = fopen(filename, "rb"); + f = ota_fopen(filename, "rb"); if (f == NULL) { ErrorAbort(state, "%s: failed to open %s: %s", name, filename, strerror(errno)); goto done; @@ -1005,12 +1005,12 @@ Value* FileGetPropFn(const char* name, State* state, int argc, Expr* argv[]) { if (ota_fread(buffer, 1, st.st_size, f) != static_cast<size_t>(st.st_size)) { ErrorAbort(state, "%s: failed to read %lld bytes from %s", name, (long long)st.st_size+1, filename); - fclose(f); + ota_fclose(f); goto done; } buffer[st.st_size] = '\0'; - fclose(f); + ota_fclose(f); char* line; line = strtok(buffer, "\n"); @@ -1440,10 +1440,10 @@ Value* RebootNowFn(const char* name, State* state, int argc, Expr* argv[]) { // zero out the 'command' field of the bootloader message. memset(buffer, 0, sizeof(((struct bootloader_message*)0)->command)); - FILE* f = fopen(filename, "r+b"); + FILE* f = ota_fopen(filename, "r+b"); fseek(f, offsetof(struct bootloader_message, command), SEEK_SET); ota_fwrite(buffer, sizeof(((struct bootloader_message*)0)->command), 1, f); - fclose(f); + ota_fclose(f); free(filename); strcpy(buffer, "reboot,"); @@ -1482,7 +1482,7 @@ Value* SetStageFn(const char* name, State* state, int argc, Expr* argv[]) { // bootloader message that the main recovery uses to save its // arguments in case of the device restarting midway through // package installation. - FILE* f = fopen(filename, "r+b"); + FILE* f = ota_fopen(filename, "r+b"); fseek(f, offsetof(struct bootloader_message, stage), SEEK_SET); int to_write = strlen(stagestr)+1; int max_size = sizeof(((struct bootloader_message*)0)->stage); @@ -1491,7 +1491,7 @@ Value* SetStageFn(const char* name, State* state, int argc, Expr* argv[]) { stagestr[max_size-1] = 0; } ota_fwrite(stagestr, to_write, 1, f); - fclose(f); + ota_fclose(f); free(stagestr); return StringValue(filename); @@ -1508,10 +1508,10 @@ Value* GetStageFn(const char* name, State* state, int argc, Expr* argv[]) { if (ReadArgs(state, argv, 1, &filename) < 0) return NULL; char buffer[sizeof(((struct bootloader_message*)0)->stage)]; - FILE* f = fopen(filename, "rb"); + FILE* f = ota_fopen(filename, "rb"); fseek(f, offsetof(struct bootloader_message, stage), SEEK_SET); ota_fread(buffer, sizeof(buffer), 1, f); - fclose(f); + ota_fclose(f); buffer[sizeof(buffer)-1] = '\0'; return StringValue(strdup(buffer)); |