summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Android.mk12
-rw-r--r--adb_install.cpp2
-rw-r--r--applypatch/Android.mk23
-rw-r--r--applypatch/applypatch.cpp (renamed from applypatch/applypatch.c)362
-rw-r--r--applypatch/applypatch.h2
-rw-r--r--applypatch/bsdiff.cpp (renamed from applypatch/bsdiff.c)48
-rw-r--r--applypatch/bspatch.cpp (renamed from applypatch/bspatch.c)5
-rw-r--r--applypatch/freecache.cpp (renamed from applypatch/freecache.c)28
-rw-r--r--applypatch/imgdiff.cpp (renamed from applypatch/imgdiff.c)84
-rw-r--r--applypatch/imgpatch.cpp (renamed from applypatch/imgpatch.c)4
-rw-r--r--applypatch/main.cpp (renamed from applypatch/main.c)56
-rw-r--r--applypatch/utils.cpp (renamed from applypatch/utils.c)6
-rw-r--r--bootloader.h18
-rw-r--r--common.h8
-rw-r--r--edify/Android.mk20
-rw-r--r--edify/expr.cpp (renamed from edify/expr.c)30
-rw-r--r--edify/expr.h10
-rw-r--r--edify/main.cpp (renamed from edify/main.c)0
-rw-r--r--edify/parser.y8
-rw-r--r--etc/init.rc1
-rw-r--r--fuse_sdcard_provider.cpp (renamed from fuse_sdcard_provider.c)12
-rw-r--r--fuse_sdcard_provider.h6
-rw-r--r--fuse_sideload.cpp (renamed from fuse_sideload.c)15
-rw-r--r--fuse_sideload.h6
-rw-r--r--install.cpp4
-rw-r--r--minadbd/Android.mk1
-rw-r--r--minadbd/adb_main.cpp6
-rw-r--r--minadbd/services.cpp6
-rw-r--r--minui/Android.mk1
-rw-r--r--minzip/Android.mk4
-rw-r--r--minzip/Hash.c4
-rw-r--r--minzip/Hash.h8
-rw-r--r--minzip/SysUtil.c104
-rw-r--r--minzip/Zip.c23
-rw-r--r--mtdutils/Android.mk2
-rw-r--r--print_sha1.h43
-rw-r--r--recovery.cpp76
l---------res-560dpi1
-rw-r--r--roots.cpp28
-rw-r--r--roots.h13
-rw-r--r--screen_ui.cpp35
-rw-r--r--screen_ui.h2
-rw-r--r--tests/Android.mk1
-rw-r--r--ui.cpp4
-rw-r--r--ui.h4
-rw-r--r--uncrypt/Android.mk4
-rw-r--r--uncrypt/uncrypt.cpp38
-rw-r--r--unique_fd.h73
-rw-r--r--updater/Android.mk24
-rw-r--r--updater/blockimg.cpp (renamed from updater/blockimg.c)1348
-rw-r--r--updater/install.cpp (renamed from updater/install.c)179
-rw-r--r--updater/updater.cpp (renamed from updater/updater.c)2
-rw-r--r--verifier_test.cpp6
53 files changed, 1373 insertions, 1437 deletions
diff --git a/Android.mk b/Android.mk
index b31f73017..d96849f65 100644
--- a/Android.mk
+++ b/Android.mk
@@ -14,11 +14,10 @@
LOCAL_PATH := $(call my-dir)
-
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := fuse_sideload.c
-
+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
@@ -34,7 +33,7 @@ LOCAL_SRC_FILES := \
asn1_decoder.cpp \
bootloader.cpp \
device.cpp \
- fuse_sdcard_provider.c \
+ fuse_sdcard_provider.cpp \
install.cpp \
recovery.cpp \
roots.cpp \
@@ -55,6 +54,7 @@ RECOVERY_API_VERSION := 3
RECOVERY_FSTAB_VERSION := 2
LOCAL_CFLAGS += -DRECOVERY_API_VERSION=$(RECOVERY_API_VERSION)
LOCAL_CFLAGS += -Wno-unused-parameter
+LOCAL_CLANG := true
LOCAL_C_INCLUDES += \
system/vold \
@@ -77,7 +77,6 @@ LOCAL_STATIC_LIBRARIES := \
libcutils \
liblog \
libselinux \
- libstdc++ \
libm \
libc
@@ -99,6 +98,7 @@ include $(BUILD_EXECUTABLE)
# All the APIs for testing
include $(CLEAR_VARS)
+LOCAL_CLANG := true
LOCAL_MODULE := libverifier
LOCAL_MODULE_TAGS := tests
LOCAL_SRC_FILES := \
@@ -106,6 +106,7 @@ LOCAL_SRC_FILES := \
include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
+LOCAL_CLANG := true
LOCAL_MODULE := verifier_test
LOCAL_FORCE_STATIC_EXECUTABLE := true
LOCAL_MODULE_TAGS := tests
@@ -120,7 +121,6 @@ LOCAL_STATIC_LIBRARIES := \
libminui \
libminzip \
libcutils \
- libstdc++ \
libc
include $(BUILD_EXECUTABLE)
diff --git a/adb_install.cpp b/adb_install.cpp
index e3b94ea59..4cfcb2ab8 100644
--- a/adb_install.cpp
+++ b/adb_install.cpp
@@ -91,7 +91,7 @@ apply_from_adb(RecoveryUI* ui_, bool* wipe_cache, const char* install_file) {
// FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the host
// connects and starts serving a package. Poll for its
// appearance. (Note that inotify doesn't work with FUSE.)
- int result;
+ int result = INSTALL_ERROR;
int status;
bool waited = false;
struct stat st;
diff --git a/applypatch/Android.mk b/applypatch/Android.mk
index 4984093dd..cc17a13ae 100644
--- a/applypatch/Android.mk
+++ b/applypatch/Android.mk
@@ -13,41 +13,46 @@
# limitations under the License.
LOCAL_PATH := $(call my-dir)
+
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := applypatch.c bspatch.c freecache.c imgpatch.c utils.c
+LOCAL_CLANG := true
+LOCAL_SRC_FILES := applypatch.cpp bspatch.cpp freecache.cpp imgpatch.cpp utils.cpp
LOCAL_MODULE := libapplypatch
LOCAL_MODULE_TAGS := eng
LOCAL_C_INCLUDES += external/bzip2 external/zlib bootable/recovery
-LOCAL_STATIC_LIBRARIES += libmtdutils libmincrypt libbz libz
+LOCAL_STATIC_LIBRARIES += libbase libmtdutils libmincrypt libbz libz
include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := main.c
+LOCAL_CLANG := true
+LOCAL_SRC_FILES := main.cpp
LOCAL_MODULE := applypatch
LOCAL_C_INCLUDES += bootable/recovery
-LOCAL_STATIC_LIBRARIES += libapplypatch libmtdutils libmincrypt libbz
-LOCAL_SHARED_LIBRARIES += libz libcutils libstdc++ libc
+LOCAL_STATIC_LIBRARIES += libapplypatch libbase libmtdutils libmincrypt libbz
+LOCAL_SHARED_LIBRARIES += libz libcutils libc
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := main.c
+LOCAL_CLANG := true
+LOCAL_SRC_FILES := main.cpp
LOCAL_MODULE := applypatch_static
LOCAL_FORCE_STATIC_EXECUTABLE := true
LOCAL_MODULE_TAGS := eng
LOCAL_C_INCLUDES += bootable/recovery
-LOCAL_STATIC_LIBRARIES += libapplypatch libmtdutils libmincrypt libbz
-LOCAL_STATIC_LIBRARIES += libz libcutils libstdc++ libc
+LOCAL_STATIC_LIBRARIES += libapplypatch libbase libmtdutils libmincrypt libbz
+LOCAL_STATIC_LIBRARIES += libz libcutils libc
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := imgdiff.c utils.c bsdiff.c
+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
diff --git a/applypatch/applypatch.c b/applypatch/applypatch.cpp
index 2358d4292..1767761a8 100644
--- a/applypatch/applypatch.c
+++ b/applypatch/applypatch.cpp
@@ -15,6 +15,7 @@
*/
#include <errno.h>
+#include <fcntl.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
@@ -22,14 +23,15 @@
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/types.h>
-#include <fcntl.h>
#include <unistd.h>
-#include <stdbool.h>
+
+#include <base/strings.h>
#include "mincrypt/sha.h"
#include "applypatch.h"
#include "mtdutils/mtdutils.h"
#include "edify/expr.h"
+#include "print_sha1.h"
static int LoadPartitionContents(const char* filename, FileContents* file);
static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
@@ -43,7 +45,7 @@ static int GenerateTarget(FileContents* source_file,
size_t target_size,
const Value* bonus_data);
-static int mtd_partitions_scanned = 0;
+static bool mtd_partitions_scanned = false;
// Read a file into memory; store the file contents and associated
// metadata in *file.
@@ -65,7 +67,7 @@ int LoadFileContents(const char* filename, FileContents* file) {
}
file->size = file->st.st_size;
- file->data = malloc(file->size);
+ file->data = reinterpret_cast<unsigned char*>(malloc(file->size));
FILE* f = fopen(filename, "rb");
if (f == NULL) {
@@ -75,10 +77,9 @@ int LoadFileContents(const char* filename, FileContents* file) {
return -1;
}
- ssize_t bytes_read = fread(file->data, 1, file->size, f);
- if (bytes_read != file->size) {
- printf("short read of \"%s\" (%ld bytes of %ld)\n",
- filename, (long)bytes_read, (long)file->size);
+ size_t bytes_read = fread(file->data, 1, file->size, f);
+ if (bytes_read != static_cast<size_t>(file->size)) {
+ printf("short read of \"%s\" (%zu bytes of %zd)\n", filename, bytes_read, file->size);
free(file->data);
file->data = NULL;
return -1;
@@ -89,21 +90,6 @@ int LoadFileContents(const char* filename, FileContents* file) {
return 0;
}
-static size_t* size_array;
-// comparison function for qsort()ing an int array of indexes into
-// size_array[].
-static int compare_size_indices(const void* a, const void* b) {
- int aa = *(int*)a;
- int bb = *(int*)b;
- if (size_array[aa] < size_array[bb]) {
- return -1;
- } else if (size_array[aa] > size_array[bb]) {
- return 1;
- } else {
- return 0;
- }
-}
-
// Load the contents of an MTD or EMMC partition into the provided
// FileContents. filename should be a string of the form
// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
@@ -122,85 +108,74 @@ static int compare_size_indices(const void* a, const void* b) {
enum PartitionType { MTD, EMMC };
static int LoadPartitionContents(const char* filename, FileContents* file) {
- char* copy = strdup(filename);
- const char* magic = strtok(copy, ":");
+ std::string copy(filename);
+ std::vector<std::string> pieces = android::base::Split(copy, ":");
+ if (pieces.size() < 4 || pieces.size() % 2 != 0) {
+ printf("LoadPartitionContents called with bad filename (%s)\n", filename);
+ return -1;
+ }
enum PartitionType type;
-
- if (strcmp(magic, "MTD") == 0) {
+ if (pieces[0] == "MTD") {
type = MTD;
- } else if (strcmp(magic, "EMMC") == 0) {
+ } else if (pieces[0] == "EMMC") {
type = EMMC;
} else {
- printf("LoadPartitionContents called with bad filename (%s)\n",
- filename);
+ printf("LoadPartitionContents called with bad filename (%s)\n", filename);
return -1;
}
- const char* partition = strtok(NULL, ":");
-
- int i;
- int colons = 0;
- for (i = 0; filename[i] != '\0'; ++i) {
- if (filename[i] == ':') {
- ++colons;
- }
- }
- if (colons < 3 || colons%2 == 0) {
- printf("LoadPartitionContents called with bad filename (%s)\n",
- filename);
- }
+ const char* partition = pieces[1].c_str();
- int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
- int* index = malloc(pairs * sizeof(int));
- size_t* size = malloc(pairs * sizeof(size_t));
- char** sha1sum = malloc(pairs * sizeof(char*));
+ size_t pairs = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
+ std::vector<size_t> index(pairs);
+ std::vector<size_t> size(pairs);
+ std::vector<std::string> sha1sum(pairs);
- for (i = 0; i < pairs; ++i) {
- const char* size_str = strtok(NULL, ":");
- size[i] = strtol(size_str, NULL, 10);
+ for (size_t i = 0; i < pairs; ++i) {
+ size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
if (size[i] == 0) {
printf("LoadPartitionContents called with bad size (%s)\n", filename);
return -1;
}
- sha1sum[i] = strtok(NULL, ":");
+ sha1sum[i] = pieces[i*2+3].c_str();
index[i] = i;
}
- // sort the index[] array so it indexes the pairs in order of
- // increasing size.
- size_array = size;
- qsort(index, pairs, sizeof(int), compare_size_indices);
+ // Sort the index[] array so it indexes the pairs in order of increasing size.
+ sort(index.begin(), index.end(),
+ [&](const size_t& i, const size_t& j) {
+ return (size[i] < size[j]);
+ }
+ );
MtdReadContext* ctx = NULL;
FILE* dev = NULL;
switch (type) {
- case MTD:
+ case MTD: {
if (!mtd_partitions_scanned) {
mtd_scan_partitions();
- mtd_partitions_scanned = 1;
+ mtd_partitions_scanned = true;
}
const MtdPartition* mtd = mtd_find_partition_by_name(partition);
if (mtd == NULL) {
- printf("mtd partition \"%s\" not found (loading %s)\n",
- partition, filename);
+ printf("mtd partition \"%s\" not found (loading %s)\n", partition, filename);
return -1;
}
ctx = mtd_read_partition(mtd);
if (ctx == NULL) {
- printf("failed to initialize read of mtd partition \"%s\"\n",
- partition);
+ printf("failed to initialize read of mtd partition \"%s\"\n", partition);
return -1;
}
break;
+ }
case EMMC:
dev = fopen(partition, "rb");
if (dev == NULL) {
- printf("failed to open emmc partition \"%s\": %s\n",
- partition, strerror(errno));
+ printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
return -1;
}
}
@@ -209,15 +184,15 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
SHA_init(&sha_ctx);
uint8_t parsed_sha[SHA_DIGEST_SIZE];
- // allocate enough memory to hold the largest size.
- file->data = malloc(size[index[pairs-1]]);
+ // Allocate enough memory to hold the largest size.
+ file->data = reinterpret_cast<unsigned char*>(malloc(size[index[pairs-1]]));
char* p = (char*)file->data;
file->size = 0; // # bytes read so far
+ bool found = false;
- for (i = 0; i < pairs; ++i) {
- // Read enough additional bytes to get us up to the next size
- // (again, we're trying the possibilities in order of increasing
- // size).
+ for (size_t i = 0; i < pairs; ++i) {
+ // Read enough additional bytes to get us up to the next size. (Again,
+ // we're trying the possibilities in order of increasing size).
size_t next = size[index[i]] - file->size;
size_t read = 0;
if (next > 0) {
@@ -247,9 +222,8 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
const uint8_t* sha_so_far = SHA_final(&temp_ctx);
- if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
- printf("failed to parse sha1 %s in %s\n",
- sha1sum[index[i]], filename);
+ if (ParseSha1(sha1sum[index[i]].c_str(), parsed_sha) != 0) {
+ printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]].c_str(), filename);
free(file->data);
file->data = NULL;
return -1;
@@ -259,7 +233,8 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
// we have a match. stop reading the partition; we'll return
// the data we've read so far.
printf("partition read matched size %zu sha %s\n",
- size[index[i]], sha1sum[index[i]]);
+ size[index[i]], sha1sum[index[i]].c_str());
+ found = true;
break;
}
@@ -277,18 +252,16 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
}
- if (i == pairs) {
- // Ran off the end of the list of (size,sha1) pairs without
- // finding a match.
- printf("contents of partition \"%s\" didn't match %s\n",
- partition, filename);
+ if (!found) {
+ // Ran off the end of the list of (size,sha1) pairs without finding a match.
+ printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
free(file->data);
file->data = NULL;
return -1;
}
const uint8_t* sha_final = SHA_final(&sha_ctx);
- for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
+ for (size_t i = 0; i < SHA_DIGEST_SIZE; ++i) {
file->sha1[i] = sha_final[i];
}
@@ -297,11 +270,6 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
file->st.st_uid = 0;
file->st.st_gid = 0;
- free(copy);
- free(index);
- free(size);
- free(sha1sum);
-
return 0;
}
@@ -311,16 +279,14 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
int SaveFileContents(const char* filename, const FileContents* file) {
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
if (fd < 0) {
- printf("failed to open \"%s\" for write: %s\n",
- filename, strerror(errno));
+ printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
return -1;
}
ssize_t bytes_written = FileSink(file->data, file->size, &fd);
if (bytes_written != file->size) {
- printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
- filename, (long)bytes_written, (long)file->size,
- strerror(errno));
+ printf("short write of \"%s\" (%zd bytes of %zd) (%s)\n",
+ filename, bytes_written, file->size, strerror(errno));
close(fd);
return -1;
}
@@ -346,54 +312,51 @@ int SaveFileContents(const char* filename, const FileContents* file) {
}
// Write a memory buffer to 'target' partition, a string of the form
-// "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on
-// success.
-int WriteToPartition(unsigned char* data, size_t len,
- const char* target) {
- char* copy = strdup(target);
- const char* magic = strtok(copy, ":");
+// "MTD:<partition>[:...]" or "EMMC:<partition_device>[:...]". The target name
+// might contain multiple colons, but WriteToPartition() only uses the first
+// two and ignores the rest. Return 0 on success.
+int WriteToPartition(unsigned char* data, size_t len, const char* target) {
+ std::string copy(target);
+ std::vector<std::string> pieces = android::base::Split(copy, ":");
+
+ if (pieces.size() < 2) {
+ printf("WriteToPartition called with bad target (%s)\n", target);
+ return -1;
+ }
enum PartitionType type;
- if (strcmp(magic, "MTD") == 0) {
+ if (pieces[0] == "MTD") {
type = MTD;
- } else if (strcmp(magic, "EMMC") == 0) {
+ } else if (pieces[0] == "EMMC") {
type = EMMC;
} else {
printf("WriteToPartition called with bad target (%s)\n", target);
return -1;
}
- const char* partition = strtok(NULL, ":");
-
- if (partition == NULL) {
- printf("bad partition target name \"%s\"\n", target);
- return -1;
- }
+ const char* partition = pieces[1].c_str();
switch (type) {
- case MTD:
+ case MTD: {
if (!mtd_partitions_scanned) {
mtd_scan_partitions();
- mtd_partitions_scanned = 1;
+ mtd_partitions_scanned = true;
}
const MtdPartition* mtd = mtd_find_partition_by_name(partition);
if (mtd == NULL) {
- printf("mtd partition \"%s\" not found for writing\n",
- partition);
+ printf("mtd partition \"%s\" not found for writing\n", partition);
return -1;
}
MtdWriteContext* ctx = mtd_write_partition(mtd);
if (ctx == NULL) {
- printf("failed to init mtd partition \"%s\" for writing\n",
- partition);
+ printf("failed to init mtd partition \"%s\" for writing\n", partition);
return -1;
}
- size_t written = mtd_write_data(ctx, (char*)data, len);
+ size_t written = mtd_write_data(ctx, reinterpret_cast<char*>(data), len);
if (written != len) {
- printf("only wrote %zu of %zu bytes to MTD %s\n",
- written, len, partition);
+ printf("only wrote %zu of %zu bytes to MTD %s\n", written, len, partition);
mtd_write_close(ctx);
return -1;
}
@@ -409,22 +372,20 @@ int WriteToPartition(unsigned char* data, size_t len,
return -1;
}
break;
+ }
- case EMMC:
- {
+ case EMMC: {
size_t start = 0;
- int success = 0;
+ bool success = false;
int fd = open(partition, O_RDWR | O_SYNC);
if (fd < 0) {
printf("failed to open %s: %s\n", partition, strerror(errno));
return -1;
}
- int attempt;
- for (attempt = 0; attempt < 2; ++attempt) {
+ for (size_t attempt = 0; attempt < 2; ++attempt) {
if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
- printf("failed seek on %s: %s\n",
- partition, strerror(errno));
+ printf("failed seek on %s: %s\n", partition, strerror(errno));
return -1;
}
while (start < len) {
@@ -439,23 +400,20 @@ int WriteToPartition(unsigned char* data, size_t len,
start += written;
}
if (fsync(fd) != 0) {
- printf("failed to sync to %s (%s)\n",
- partition, strerror(errno));
+ printf("failed to sync to %s (%s)\n", partition, strerror(errno));
return -1;
}
if (close(fd) != 0) {
- printf("failed to close %s (%s)\n",
- partition, strerror(errno));
+ printf("failed to close %s (%s)\n", partition, strerror(errno));
return -1;
}
fd = open(partition, O_RDONLY);
if (fd < 0) {
- printf("failed to reopen %s for verify (%s)\n",
- partition, strerror(errno));
+ printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
return -1;
}
- // drop caches so our subsequent verification read
+ // Drop caches so our subsequent verification read
// won't just be reading the cache.
sync();
int dc = open("/proc/sys/vm/drop_caches", O_WRONLY);
@@ -475,10 +433,11 @@ int WriteToPartition(unsigned char* data, size_t len,
}
unsigned char buffer[4096];
start = len;
- size_t p;
- for (p = 0; p < len; p += sizeof(buffer)) {
+ for (size_t p = 0; p < len; p += sizeof(buffer)) {
size_t to_read = len - p;
- if (to_read > sizeof(buffer)) to_read = sizeof(buffer);
+ if (to_read > sizeof(buffer)) {
+ to_read = sizeof(buffer);
+ }
size_t so_far = 0;
while (so_far < to_read) {
@@ -489,14 +448,14 @@ int WriteToPartition(unsigned char* data, size_t len,
partition, p, strerror(errno));
return -1;
}
- if ((size_t)read_count < to_read) {
+ if (static_cast<size_t>(read_count) < to_read) {
printf("short verify read %s at %zu: %zd %zu %s\n",
partition, p, read_count, to_read, strerror(errno));
}
so_far += read_count;
}
- if (memcmp(buffer, data+p, to_read)) {
+ if (memcmp(buffer, data+p, to_read) != 0) {
printf("verification failed starting at %zu\n", p);
start = p;
break;
@@ -504,7 +463,7 @@ int WriteToPartition(unsigned char* data, size_t len,
}
if (start == len) {
- printf("verification read succeeded (attempt %d)\n", attempt+1);
+ printf("verification read succeeded (attempt %zu)\n", attempt+1);
success = true;
break;
}
@@ -524,7 +483,6 @@ int WriteToPartition(unsigned char* data, size_t len,
}
}
- free(copy);
return 0;
}
@@ -534,10 +492,9 @@ int WriteToPartition(unsigned char* data, size_t len,
// the form "<digest>:<anything>". Return 0 on success, -1 on any
// error.
int ParseSha1(const char* str, uint8_t* digest) {
- int i;
const char* ps = str;
uint8_t* pd = digest;
- for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
+ for (int i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
int digit;
if (*ps >= '0' && *ps <= '9') {
digit = *ps - '0';
@@ -564,9 +521,8 @@ int ParseSha1(const char* str, uint8_t* digest) {
// found.
int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
int num_patches) {
- int i;
uint8_t patch_sha1[SHA_DIGEST_SIZE];
- for (i = 0; i < num_patches; ++i) {
+ for (int i = 0; i < num_patches; ++i) {
if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
return i;
@@ -578,8 +534,8 @@ int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
// Returns 0 if the contents of the file (argv[2]) or the cached file
// match any of the sha1's on the command line (argv[3:]). Returns
// nonzero otherwise.
-int applypatch_check(const char* filename,
- int num_patches, char** const patch_sha1_str) {
+int applypatch_check(const char* filename, int num_patches,
+ char** const patch_sha1_str) {
FileContents file;
file.data = NULL;
@@ -624,13 +580,13 @@ int ShowLicenses() {
}
ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
- int fd = *(int *)token;
+ int fd = *reinterpret_cast<int *>(token);
ssize_t done = 0;
ssize_t wrote;
- while (done < (ssize_t) len) {
+ while (done < len) {
wrote = TEMP_FAILURE_RETRY(write(fd, data+done, len-done));
if (wrote == -1) {
- printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
+ printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
return done;
}
done += wrote;
@@ -645,7 +601,7 @@ typedef struct {
} MemorySinkInfo;
ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
- MemorySinkInfo* msi = (MemorySinkInfo*)token;
+ MemorySinkInfo* msi = reinterpret_cast<MemorySinkInfo*>(token);
if (msi->size - msi->pos < len) {
return -1;
}
@@ -674,15 +630,6 @@ int CacheSizeCheck(size_t bytes) {
}
}
-static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
- int i;
- const char* hex = "0123456789abcdef";
- for (i = 0; i < 4; ++i) {
- putchar(hex[(sha1[i]>>4) & 0xf]);
- putchar(hex[sha1[i] & 0xf]);
- }
-}
-
// This function applies binary patches to files in a way that is safe
// (the original file is not touched until we have the desired
// replacement for it) and idempotent (it's okay to run this program
@@ -695,7 +642,7 @@ static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
// entries in <patch_sha1_str>, the corresponding patch from
// <patch_data> (which must be a VAL_BLOB) is applied to produce a
// new file (the type of patch is automatically detected from the
-// blob daat). If that new file has sha1 hash <target_sha1_str>,
+// blob data). If that new file has sha1 hash <target_sha1_str>,
// moves it to replace <target_filename>, and exits successfully.
// Note that if <source_filename> and <target_filename> are not the
// same, <source_filename> is NOT deleted on success.
@@ -706,7 +653,7 @@ static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
// status.
//
// <source_filename> may refer to a partition to read the source data.
-// See the comments for the LoadPartition Contents() function above
+// See the comments for the LoadPartitionContents() function above
// for the format of such a filename.
int applypatch(const char* source_filename,
@@ -719,8 +666,7 @@ int applypatch(const char* source_filename,
Value* bonus_data) {
printf("patch %s: ", source_filename);
- if (target_filename[0] == '-' &&
- target_filename[1] == '\0') {
+ if (target_filename[0] == '-' && target_filename[1] == '\0') {
target_filename = source_filename;
}
@@ -742,9 +688,7 @@ int applypatch(const char* source_filename,
if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
// The early-exit case: the patch was already applied, this file
// has the desired hash, nothing for us to do.
- printf("already ");
- print_short_sha1(target_sha1);
- putchar('\n');
+ printf("already %s\n", short_sha1(target_sha1).c_str());
free(source_file.data);
return 0;
}
@@ -761,8 +705,7 @@ int applypatch(const char* source_filename,
}
if (source_file.data != NULL) {
- int to_use = FindMatchingPatch(source_file.sha1,
- patch_sha1_str, num_patches);
+ int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str, num_patches);
if (to_use >= 0) {
source_patch_value = patch_data[to_use];
}
@@ -779,8 +722,7 @@ int applypatch(const char* source_filename,
return 1;
}
- int to_use = FindMatchingPatch(copy_file.sha1,
- patch_sha1_str, num_patches);
+ int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str, num_patches);
if (to_use >= 0) {
copy_patch_value = patch_data[to_use];
}
@@ -803,6 +745,67 @@ int applypatch(const char* source_filename,
return result;
}
+/*
+ * This function flashes a given image to the target partition. It verifies
+ * the target cheksum first, and will return if target has the desired hash.
+ * It checks the checksum of the given source image before flashing, and
+ * verifies the target partition afterwards. The function is idempotent.
+ * Returns zero on success.
+ */
+int applypatch_flash(const char* source_filename, const char* target_filename,
+ const char* target_sha1_str, size_t target_size) {
+ printf("flash %s: ", target_filename);
+
+ uint8_t target_sha1[SHA_DIGEST_SIZE];
+ if (ParseSha1(target_sha1_str, target_sha1) != 0) {
+ printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
+ return 1;
+ }
+
+ FileContents source_file;
+ source_file.data = NULL;
+ std::string target_str(target_filename);
+
+ std::vector<std::string> pieces = android::base::Split(target_str, ":");
+ if (pieces.size() != 2 || (pieces[0] != "MTD" && pieces[0] != "EMMC")) {
+ printf("invalid target name \"%s\"", target_filename);
+ return 1;
+ }
+
+ // Load the target into the source_file object to see if already applied.
+ pieces.push_back(std::to_string(target_size));
+ pieces.push_back(target_sha1_str);
+ std::string fullname = android::base::Join(pieces, ':');
+ if (LoadPartitionContents(fullname.c_str(), &source_file) == 0 &&
+ memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
+ // The early-exit case: the image was already applied, this partition
+ // has the desired hash, nothing for us to do.
+ printf("already %s\n", short_sha1(target_sha1).c_str());
+ free(source_file.data);
+ return 0;
+ }
+
+ if (LoadFileContents(source_filename, &source_file) == 0) {
+ if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
+ // The source doesn't have desired checksum.
+ printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
+ printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
+ short_sha1(source_file.sha1).c_str());
+ free(source_file.data);
+ return 1;
+ }
+ }
+
+ if (WriteToPartition(source_file.data, target_size, target_filename) != 0) {
+ printf("write of copied data to %s failed\n", target_filename);
+ free(source_file.data);
+ return 1;
+ }
+
+ free(source_file.data);
+ return 0;
+}
+
static int GenerateTarget(FileContents* source_file,
const Value* source_patch_value,
FileContents* copy_file,
@@ -865,8 +868,8 @@ static int GenerateTarget(FileContents* source_file,
(free_space > (256 << 10)) && // 256k (two-block) minimum
(free_space > (target_size * 3 / 2)); // 50% margin of error
if (!enough_space) {
- printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
- (long)target_size, (long)free_space, retry, enough_space);
+ printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
+ target_size, free_space, retry, enough_space);
}
}
@@ -884,8 +887,7 @@ static int GenerateTarget(FileContents* source_file,
// It's impossible to free space on the target filesystem by
// deleting the source if the source is a partition. If
// we're ever in a state where we need to do this, fail.
- printf("not enough free space for target but source "
- "is partition\n");
+ printf("not enough free space for target but source is partition\n");
return 1;
}
@@ -902,7 +904,7 @@ static int GenerateTarget(FileContents* source_file,
unlink(source_filename);
size_t free_space = FreeSpaceForFile(target_fs);
- printf("(now %ld bytes free for target) ", (long)free_space);
+ printf("(now %zu bytes free for target) ", free_space);
}
}
@@ -927,10 +929,9 @@ static int GenerateTarget(FileContents* source_file,
if (strncmp(target_filename, "MTD:", 4) == 0 ||
strncmp(target_filename, "EMMC:", 5) == 0) {
// We store the decoded output in memory.
- msi.buffer = malloc(target_size);
+ msi.buffer = reinterpret_cast<unsigned char*>(malloc(target_size));
if (msi.buffer == NULL) {
- printf("failed to alloc %ld bytes for output\n",
- (long)target_size);
+ printf("failed to alloc %zu bytes for output\n", target_size);
return 1;
}
msi.pos = 0;
@@ -939,12 +940,11 @@ static int GenerateTarget(FileContents* source_file,
token = &msi;
} else {
// We write the decoded output to "<tgt-file>.patch".
- outname = (char*)malloc(strlen(target_filename) + 10);
+ outname = reinterpret_cast<char*>(malloc(strlen(target_filename) + 10));
strcpy(outname, target_filename);
strcat(outname, ".patch");
- output = open(outname, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
- S_IRUSR | S_IWUSR);
+ output = open(outname, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
if (output < 0) {
printf("failed to open output file %s: %s\n",
outname, strerror(errno));
@@ -1006,9 +1006,7 @@ static int GenerateTarget(FileContents* source_file,
printf("patch did not produce expected sha1\n");
return 1;
} else {
- printf("now ");
- print_short_sha1(target_sha1);
- putchar('\n');
+ printf("now %s\n", short_sha1(target_sha1).c_str());
}
if (output < 0) {
@@ -1025,23 +1023,23 @@ static int GenerateTarget(FileContents* source_file,
printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
return 1;
}
- if (chown(outname, source_to_use->st.st_uid,
- source_to_use->st.st_gid) != 0) {
+ if (chown(outname, source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
return 1;
}
// Finally, rename the .patch file to replace the target file.
if (rename(outname, target_filename) != 0) {
- printf("rename of .patch to \"%s\" failed: %s\n",
- target_filename, strerror(errno));
+ printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
return 1;
}
}
// If this run of applypatch created the copy, and we're here, we
// can delete it.
- if (made_copy) unlink(CACHE_TEMP_SOURCE);
+ if (made_copy) {
+ unlink(CACHE_TEMP_SOURCE);
+ }
// Success!
return 0;
diff --git a/applypatch/applypatch.h b/applypatch/applypatch.h
index edec84812..415bc1b3c 100644
--- a/applypatch/applypatch.h
+++ b/applypatch/applypatch.h
@@ -48,6 +48,8 @@ size_t FreeSpaceForFile(const char* filename);
int CacheSizeCheck(size_t bytes);
int ParseSha1(const char* str, uint8_t* digest);
+int applypatch_flash(const char* source_filename, const char* target_filename,
+ const char* target_sha1_str, size_t target_size);
int applypatch(const char* source_filename,
const char* target_filename,
const char* target_sha1_str,
diff --git a/applypatch/bsdiff.c b/applypatch/bsdiff.cpp
index b6d342b7a..55dbe5cf1 100644
--- a/applypatch/bsdiff.c
+++ b/applypatch/bsdiff.cpp
@@ -156,24 +156,24 @@ static void qsufsort(off_t *I,off_t *V,u_char *old,off_t oldsize)
for(i=0;i<oldsize+1;i++) I[V[i]]=i;
}
-static off_t matchlen(u_char *old,off_t oldsize,u_char *new,off_t newsize)
+static off_t matchlen(u_char *olddata,off_t oldsize,u_char *newdata,off_t newsize)
{
off_t i;
for(i=0;(i<oldsize)&&(i<newsize);i++)
- if(old[i]!=new[i]) break;
+ if(olddata[i]!=newdata[i]) break;
return i;
}
static off_t search(off_t *I,u_char *old,off_t oldsize,
- u_char *new,off_t newsize,off_t st,off_t en,off_t *pos)
+ u_char *newdata,off_t newsize,off_t st,off_t en,off_t *pos)
{
off_t x,y;
if(en-st<2) {
- x=matchlen(old+I[st],oldsize-I[st],new,newsize);
- y=matchlen(old+I[en],oldsize-I[en],new,newsize);
+ x=matchlen(old+I[st],oldsize-I[st],newdata,newsize);
+ y=matchlen(old+I[en],oldsize-I[en],newdata,newsize);
if(x>y) {
*pos=I[st];
@@ -185,10 +185,10 @@ static off_t search(off_t *I,u_char *old,off_t oldsize,
};
x=st+(en-st)/2;
- if(memcmp(old+I[x],new,MIN(oldsize-I[x],newsize))<0) {
- return search(I,old,oldsize,new,newsize,x,en,pos);
+ if(memcmp(old+I[x],newdata,MIN(oldsize-I[x],newsize))<0) {
+ return search(I,old,oldsize,newdata,newsize,x,en,pos);
} else {
- return search(I,old,oldsize,new,newsize,st,x,pos);
+ return search(I,old,oldsize,newdata,newsize,st,x,pos);
};
}
@@ -212,8 +212,8 @@ static void offtout(off_t x,u_char *buf)
// This is main() from bsdiff.c, with the following changes:
//
-// - old, oldsize, new, newsize are arguments; we don't load this
-// data from files. old and new are owned by the caller; we
+// - old, oldsize, newdata, newsize are arguments; we don't load this
+// data from files. old and newdata are owned by the caller; we
// don't free them at the end.
//
// - the "I" block of memory is owned by the caller, who passes a
@@ -221,7 +221,7 @@ static void offtout(off_t x,u_char *buf)
// bsdiff() multiple times with the same 'old' data, we only do
// the qsufsort() step the first time.
//
-int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* new, off_t newsize,
+int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* newdata, off_t newsize,
const char* patch_filename)
{
int fd;
@@ -242,15 +242,15 @@ int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* new, off_t newsize,
if (*IP == NULL) {
off_t* V;
- *IP = malloc((oldsize+1) * sizeof(off_t));
- V = malloc((oldsize+1) * sizeof(off_t));
+ *IP = reinterpret_cast<off_t*>(malloc((oldsize+1) * sizeof(off_t)));
+ V = reinterpret_cast<off_t*>(malloc((oldsize+1) * sizeof(off_t)));
qsufsort(*IP, V, old, oldsize);
free(V);
}
I = *IP;
- if(((db=malloc(newsize+1))==NULL) ||
- ((eb=malloc(newsize+1))==NULL)) err(1,NULL);
+ if(((db=reinterpret_cast<u_char*>(malloc(newsize+1)))==NULL) ||
+ ((eb=reinterpret_cast<u_char*>(malloc(newsize+1)))==NULL)) err(1,NULL);
dblen=0;
eblen=0;
@@ -284,26 +284,26 @@ int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* new, off_t newsize,
oldscore=0;
for(scsc=scan+=len;scan<newsize;scan++) {
- len=search(I,old,oldsize,new+scan,newsize-scan,
+ len=search(I,old,oldsize,newdata+scan,newsize-scan,
0,oldsize,&pos);
for(;scsc<scan+len;scsc++)
if((scsc+lastoffset<oldsize) &&
- (old[scsc+lastoffset] == new[scsc]))
+ (old[scsc+lastoffset] == newdata[scsc]))
oldscore++;
if(((len==oldscore) && (len!=0)) ||
(len>oldscore+8)) break;
if((scan+lastoffset<oldsize) &&
- (old[scan+lastoffset] == new[scan]))
+ (old[scan+lastoffset] == newdata[scan]))
oldscore--;
};
if((len!=oldscore) || (scan==newsize)) {
s=0;Sf=0;lenf=0;
for(i=0;(lastscan+i<scan)&&(lastpos+i<oldsize);) {
- if(old[lastpos+i]==new[lastscan+i]) s++;
+ if(old[lastpos+i]==newdata[lastscan+i]) s++;
i++;
if(s*2-i>Sf*2-lenf) { Sf=s; lenf=i; };
};
@@ -312,7 +312,7 @@ int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* new, off_t newsize,
if(scan<newsize) {
s=0;Sb=0;
for(i=1;(scan>=lastscan+i)&&(pos>=i);i++) {
- if(old[pos-i]==new[scan-i]) s++;
+ if(old[pos-i]==newdata[scan-i]) s++;
if(s*2-i>Sb*2-lenb) { Sb=s; lenb=i; };
};
};
@@ -321,9 +321,9 @@ int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* new, off_t newsize,
overlap=(lastscan+lenf)-(scan-lenb);
s=0;Ss=0;lens=0;
for(i=0;i<overlap;i++) {
- if(new[lastscan+lenf-overlap+i]==
+ if(newdata[lastscan+lenf-overlap+i]==
old[lastpos+lenf-overlap+i]) s++;
- if(new[scan-lenb+i]==
+ if(newdata[scan-lenb+i]==
old[pos-lenb+i]) s--;
if(s>Ss) { Ss=s; lens=i+1; };
};
@@ -333,9 +333,9 @@ int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* new, off_t newsize,
};
for(i=0;i<lenf;i++)
- db[dblen+i]=new[lastscan+i]-old[lastpos+i];
+ db[dblen+i]=newdata[lastscan+i]-old[lastpos+i];
for(i=0;i<(scan-lenb)-(lastscan+lenf);i++)
- eb[eblen+i]=new[lastscan+lenf+i];
+ eb[eblen+i]=newdata[lastscan+lenf+i];
dblen+=lenf;
eblen+=(scan-lenb)-(lastscan+lenf);
diff --git a/applypatch/bspatch.c b/applypatch/bspatch.cpp
index b57760eda..9d201b477 100644
--- a/applypatch/bspatch.c
+++ b/applypatch/bspatch.cpp
@@ -182,10 +182,9 @@ int ApplyBSDiffPatchMem(const unsigned char* old_data, ssize_t old_size,
printf("failed to bzinit extra stream (%d)\n", bzerr);
}
- *new_data = malloc(*new_size);
+ *new_data = reinterpret_cast<unsigned char*>(malloc(*new_size));
if (*new_data == NULL) {
- printf("failed to allocate %ld bytes of memory for output file\n",
- (long)*new_size);
+ printf("failed to allocate %zd bytes of memory for output file\n", *new_size);
return 1;
}
diff --git a/applypatch/freecache.c b/applypatch/freecache.cpp
index 9827fda06..2eb2f55ef 100644
--- a/applypatch/freecache.c
+++ b/applypatch/freecache.cpp
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <errno.h>
#include <libgen.h>
#include <stdio.h>
@@ -76,7 +92,7 @@ int FindExpendableFiles(char*** names, int* entries) {
struct dirent* de;
int size = 32;
*entries = 0;
- *names = malloc(size * sizeof(char*));
+ *names = reinterpret_cast<char**>(malloc(size * sizeof(char*)));
char path[FILENAME_MAX];
@@ -84,8 +100,7 @@ int FindExpendableFiles(char*** names, int* entries) {
// directories.
const char* dirs[2] = {"/cache", "/cache/recovery/otatest"};
- unsigned int i;
- for (i = 0; i < sizeof(dirs)/sizeof(dirs[0]); ++i) {
+ for (size_t i = 0; i < sizeof(dirs)/sizeof(dirs[0]); ++i) {
d = opendir(dirs[i]);
if (d == NULL) {
printf("error opening %s: %s\n", dirs[i], strerror(errno));
@@ -107,7 +122,7 @@ int FindExpendableFiles(char*** names, int* entries) {
if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
if (*entries >= size) {
size *= 2;
- *names = realloc(*names, size * sizeof(char*));
+ *names = reinterpret_cast<char**>(realloc(*names, size * sizeof(char*)));
}
(*names)[(*entries)++] = strdup(path);
}
@@ -127,8 +142,7 @@ int FindExpendableFiles(char*** names, int* entries) {
int MakeFreeSpaceOnCache(size_t bytes_needed) {
size_t free_now = FreeSpaceForFile("/cache");
- printf("%ld bytes free on /cache (%ld needed)\n",
- (long)free_now, (long)bytes_needed);
+ printf("%zu bytes free on /cache (%zu needed)\n", free_now, bytes_needed);
if (free_now >= bytes_needed) {
return 0;
@@ -158,7 +172,7 @@ int MakeFreeSpaceOnCache(size_t bytes_needed) {
if (names[i]) {
unlink(names[i]);
free_now = FreeSpaceForFile("/cache");
- printf("deleted %s; now %ld bytes free\n", names[i], (long)free_now);
+ printf("deleted %s; now %zu bytes free\n", names[i], free_now);
free(names[i]);
}
}
diff --git a/applypatch/imgdiff.c b/applypatch/imgdiff.cpp
index 3bac8be91..4d83ffb2e 100644
--- a/applypatch/imgdiff.c
+++ b/applypatch/imgdiff.cpp
@@ -122,6 +122,7 @@
*/
#include <errno.h>
+#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -179,7 +180,7 @@ static int fileentry_compare(const void* a, const void* b) {
}
// from bsdiff.c
-int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* new, off_t newsize,
+int bsdiff(u_char* old, off_t oldsize, off_t** IP, u_char* newdata, off_t newsize,
const char* patch_filename);
unsigned char* ReadZip(const char* filename,
@@ -191,9 +192,10 @@ unsigned char* ReadZip(const char* filename,
return NULL;
}
- unsigned char* img = malloc(st.st_size);
+ size_t sz = static_cast<size_t>(st.st_size);
+ unsigned char* img = reinterpret_cast<unsigned char*>(malloc(sz));
FILE* f = fopen(filename, "rb");
- if (fread(img, 1, st.st_size, f) != st.st_size) {
+ if (fread(img, 1, sz, f) != sz) {
printf("failed to read \"%s\" %s\n", filename, strerror(errno));
fclose(f);
return NULL;
@@ -218,7 +220,8 @@ unsigned char* ReadZip(const char* filename,
int cdcount = Read2(img+i+8);
int cdoffset = Read4(img+i+16);
- ZipFileEntry* temp_entries = malloc(cdcount * sizeof(ZipFileEntry));
+ ZipFileEntry* temp_entries = reinterpret_cast<ZipFileEntry*>(malloc(
+ cdcount * sizeof(ZipFileEntry)));
int entrycount = 0;
unsigned char* cd = img+cdoffset;
@@ -235,7 +238,7 @@ unsigned char* ReadZip(const char* filename,
int mlen = Read2(cd+32); // file comment len
int hoffset = Read4(cd+42); // local header offset
- char* filename = malloc(nlen+1);
+ char* filename = reinterpret_cast<char*>(malloc(nlen+1));
memcpy(filename, cd+46, nlen);
filename[nlen] = '\0';
@@ -284,7 +287,7 @@ unsigned char* ReadZip(const char* filename,
#endif
*num_chunks = 0;
- *chunks = malloc((entrycount*2+2) * sizeof(ImageChunk));
+ *chunks = reinterpret_cast<ImageChunk*>(malloc((entrycount*2+2) * sizeof(ImageChunk)));
ImageChunk* curr = *chunks;
if (include_pseudo_chunk) {
@@ -311,7 +314,7 @@ unsigned char* ReadZip(const char* filename,
curr->I = NULL;
curr->len = temp_entries[nextentry].uncomp_len;
- curr->data = malloc(curr->len);
+ curr->data = reinterpret_cast<unsigned char*>(malloc(curr->len));
z_stream strm;
strm.zalloc = Z_NULL;
@@ -381,9 +384,10 @@ unsigned char* ReadImage(const char* filename,
return NULL;
}
- unsigned char* img = malloc(st.st_size + 4);
+ size_t sz = static_cast<size_t>(st.st_size);
+ unsigned char* img = reinterpret_cast<unsigned char*>(malloc(sz + 4));
FILE* f = fopen(filename, "rb");
- if (fread(img, 1, st.st_size, f) != st.st_size) {
+ if (fread(img, 1, sz, f) != sz) {
printf("failed to read \"%s\" %s\n", filename, strerror(errno));
fclose(f);
return NULL;
@@ -393,17 +397,17 @@ unsigned char* ReadImage(const char* filename,
// append 4 zero bytes to the data so we can always search for the
// four-byte string 1f8b0800 starting at any point in the actual
// file data, without special-casing the end of the data.
- memset(img+st.st_size, 0, 4);
+ memset(img+sz, 0, 4);
size_t pos = 0;
*num_chunks = 0;
*chunks = NULL;
- while (pos < st.st_size) {
+ while (pos < sz) {
unsigned char* p = img+pos;
- if (st.st_size - pos >= 4 &&
+ if (sz - pos >= 4 &&
p[0] == 0x1f && p[1] == 0x8b &&
p[2] == 0x08 && // deflate compression
p[3] == 0x00) { // no header flags
@@ -411,7 +415,8 @@ unsigned char* ReadImage(const char* filename,
size_t chunk_offset = pos;
*num_chunks += 3;
- *chunks = realloc(*chunks, *num_chunks * sizeof(ImageChunk));
+ *chunks = reinterpret_cast<ImageChunk*>(realloc(*chunks,
+ *num_chunks * sizeof(ImageChunk)));
ImageChunk* curr = *chunks + (*num_chunks-3);
// create a normal chunk for the header.
@@ -435,7 +440,7 @@ unsigned char* ReadImage(const char* filename,
size_t allocated = 32768;
curr->len = 0;
- curr->data = malloc(allocated);
+ curr->data = reinterpret_cast<unsigned char*>(malloc(allocated));
curr->start = pos;
curr->deflate_data = p;
@@ -443,7 +448,7 @@ unsigned char* ReadImage(const char* filename,
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
- strm.avail_in = st.st_size - pos;
+ strm.avail_in = sz - pos;
strm.next_in = p;
// -15 means we are decoding a 'raw' deflate stream; zlib will
@@ -465,11 +470,11 @@ unsigned char* ReadImage(const char* filename,
curr->len = allocated - strm.avail_out;
if (strm.avail_out == 0) {
allocated *= 2;
- curr->data = realloc(curr->data, allocated);
+ curr->data = reinterpret_cast<unsigned char*>(realloc(curr->data, allocated));
}
} while (ret != Z_STREAM_END);
- curr->deflate_len = st.st_size - strm.avail_in - pos;
+ curr->deflate_len = sz - strm.avail_in - pos;
inflateEnd(&strm);
pos += curr->deflate_len;
p += curr->deflate_len;
@@ -493,8 +498,8 @@ unsigned char* ReadImage(const char* filename,
// the decompression.
size_t footer_size = Read4(p-4);
if (footer_size != curr[-2].len) {
- printf("Error: footer size %d != decompressed size %d\n",
- footer_size, curr[-2].len);
+ printf("Error: footer size %zu != decompressed size %zu\n",
+ footer_size, curr[-2].len);
free(img);
return NULL;
}
@@ -502,7 +507,7 @@ unsigned char* ReadImage(const char* filename,
// Reallocate the list for every chunk; we expect the number of
// chunks to be small (5 for typical boot and recovery images).
++*num_chunks;
- *chunks = realloc(*chunks, *num_chunks * sizeof(ImageChunk));
+ *chunks = reinterpret_cast<ImageChunk*>(realloc(*chunks, *num_chunks * sizeof(ImageChunk)));
ImageChunk* curr = *chunks + (*num_chunks-1);
curr->start = pos;
curr->I = NULL;
@@ -512,7 +517,7 @@ unsigned char* ReadImage(const char* filename,
curr->type = CHUNK_NORMAL;
curr->data = p;
- for (curr->len = 0; curr->len < (st.st_size - pos); ++curr->len) {
+ for (curr->len = 0; curr->len < (sz - pos); ++curr->len) {
if (p[curr->len] == 0x1f &&
p[curr->len+1] == 0x8b &&
p[curr->len+2] == 0x08 &&
@@ -587,7 +592,7 @@ int ReconstructDeflateChunk(ImageChunk* chunk) {
}
size_t p = 0;
- unsigned char* out = malloc(BUFFER_SIZE);
+ unsigned char* out = reinterpret_cast<unsigned char*>(malloc(BUFFER_SIZE));
// We only check two combinations of encoder parameters: level 6
// (the default) and level 9 (the maximum).
@@ -638,9 +643,11 @@ unsigned char* MakePatch(ImageChunk* src, ImageChunk* tgt, size_t* size) {
return NULL;
}
- unsigned char* data = malloc(st.st_size);
+ size_t sz = static_cast<size_t>(st.st_size);
+ // TODO: Memory leak on error return.
+ unsigned char* data = reinterpret_cast<unsigned char*>(malloc(sz));
- if (tgt->type == CHUNK_NORMAL && tgt->len <= st.st_size) {
+ if (tgt->type == CHUNK_NORMAL && tgt->len <= sz) {
unlink(ptemp);
tgt->type = CHUNK_RAW;
@@ -648,14 +655,14 @@ unsigned char* MakePatch(ImageChunk* src, ImageChunk* tgt, size_t* size) {
return tgt->data;
}
- *size = st.st_size;
+ *size = sz;
FILE* f = fopen(ptemp, "rb");
if (f == NULL) {
printf("failed to open patch %s: %s\n", ptemp, strerror(errno));
return NULL;
}
- if (fread(data, 1, st.st_size, f) != st.st_size) {
+ if (fread(data, 1, sz, f) != sz) {
printf("failed to read patch %s: %s\n", ptemp, strerror(errno));
return NULL;
}
@@ -781,9 +788,8 @@ ImageChunk* FindChunkByName(const char* name,
}
void DumpChunks(ImageChunk* chunks, int num_chunks) {
- int i;
- for (i = 0; i < num_chunks; ++i) {
- printf("chunk %d: type %d start %d len %d\n",
+ for (int i = 0; i < num_chunks; ++i) {
+ printf("chunk %d: type %d start %zu len %zu\n",
i, chunks[i].type, chunks[i].start, chunks[i].len);
}
}
@@ -806,7 +812,7 @@ int main(int argc, char** argv) {
return 1;
}
bonus_size = st.st_size;
- bonus_data = malloc(bonus_size);
+ bonus_data = reinterpret_cast<unsigned char*>(malloc(bonus_size));
FILE* f = fopen(argv[2], "rb");
if (f == NULL) {
printf("failed to open bonus file %s: %s\n", argv[2], strerror(errno));
@@ -953,8 +959,9 @@ int main(int argc, char** argv) {
DumpChunks(src_chunks, num_src_chunks);
printf("Construct patches for %d chunks...\n", num_tgt_chunks);
- unsigned char** patch_data = malloc(num_tgt_chunks * sizeof(unsigned char*));
- size_t* patch_size = malloc(num_tgt_chunks * sizeof(size_t));
+ unsigned char** patch_data = reinterpret_cast<unsigned char**>(malloc(
+ num_tgt_chunks * sizeof(unsigned char*)));
+ size_t* patch_size = reinterpret_cast<size_t*>(malloc(num_tgt_chunks * sizeof(size_t)));
for (i = 0; i < num_tgt_chunks; ++i) {
if (zip_mode) {
ImageChunk* src;
@@ -967,15 +974,16 @@ int main(int argc, char** argv) {
}
} else {
if (i == 1 && bonus_data) {
- printf(" using %d bytes of bonus data for chunk %d\n", bonus_size, i);
- src_chunks[i].data = realloc(src_chunks[i].data, src_chunks[i].len + bonus_size);
+ printf(" using %zu bytes of bonus data for chunk %d\n", bonus_size, i);
+ src_chunks[i].data = reinterpret_cast<unsigned char*>(realloc(src_chunks[i].data,
+ src_chunks[i].len + bonus_size));
memcpy(src_chunks[i].data+src_chunks[i].len, bonus_data, bonus_size);
src_chunks[i].len += bonus_size;
}
patch_data[i] = MakePatch(src_chunks+i, tgt_chunks+i, patch_size+i);
}
- printf("patch %3d is %d bytes (of %d)\n",
+ printf("patch %3d is %zu bytes (of %zu)\n",
i, patch_size[i], tgt_chunks[i].source_len);
}
@@ -1012,7 +1020,7 @@ int main(int argc, char** argv) {
switch (tgt_chunks[i].type) {
case CHUNK_NORMAL:
- printf("chunk %3d: normal (%10d, %10d) %10d\n", i,
+ printf("chunk %3d: normal (%10zu, %10zu) %10zu\n", i,
tgt_chunks[i].start, tgt_chunks[i].len, patch_size[i]);
Write8(tgt_chunks[i].source_start, f);
Write8(tgt_chunks[i].source_len, f);
@@ -1021,7 +1029,7 @@ int main(int argc, char** argv) {
break;
case CHUNK_DEFLATE:
- printf("chunk %3d: deflate (%10d, %10d) %10d %s\n", i,
+ printf("chunk %3d: deflate (%10zu, %10zu) %10zu %s\n", i,
tgt_chunks[i].start, tgt_chunks[i].deflate_len, patch_size[i],
tgt_chunks[i].filename);
Write8(tgt_chunks[i].source_start, f);
@@ -1038,7 +1046,7 @@ int main(int argc, char** argv) {
break;
case CHUNK_RAW:
- printf("chunk %3d: raw (%10d, %10d)\n", i,
+ printf("chunk %3d: raw (%10zu, %10zu)\n", i,
tgt_chunks[i].start, tgt_chunks[i].len);
Write4(patch_size[i], f);
fwrite(patch_data[i], 1, patch_size[i], f);
diff --git a/applypatch/imgpatch.c b/applypatch/imgpatch.cpp
index 09b0a7397..26888f8ee 100644
--- a/applypatch/imgpatch.c
+++ b/applypatch/imgpatch.cpp
@@ -132,7 +132,7 @@ int ApplyImagePatch(const unsigned char* old_data, ssize_t old_size __unused,
// must be appended from the bonus_data value.
size_t bonus_size = (i == 1 && bonus_data != NULL) ? bonus_data->size : 0;
- unsigned char* expanded_source = malloc(expanded_len);
+ unsigned char* expanded_source = reinterpret_cast<unsigned char*>(malloc(expanded_len));
if (expanded_source == NULL) {
printf("failed to allocate %zu bytes for expanded_source\n",
expanded_len);
@@ -196,7 +196,7 @@ int ApplyImagePatch(const unsigned char* old_data, ssize_t old_size __unused,
// ... unless the buffer is too small, in which case we'll
// allocate a fresh one.
free(temp_data);
- temp_data = malloc(32768);
+ temp_data = reinterpret_cast<unsigned char*>(malloc(32768));
temp_size = 32768;
}
diff --git a/applypatch/main.c b/applypatch/main.cpp
index 8e9fe80ef..966d8b91f 100644
--- a/applypatch/main.c
+++ b/applypatch/main.cpp
@@ -23,14 +23,14 @@
#include "edify/expr.h"
#include "mincrypt/sha.h"
-int CheckMode(int argc, char** argv) {
+static int CheckMode(int argc, char** argv) {
if (argc < 3) {
return 2;
}
return applypatch_check(argv[2], argc-3, argv+3);
}
-int SpaceMode(int argc, char** argv) {
+static int SpaceMode(int argc, char** argv) {
if (argc != 3) {
return 2;
}
@@ -45,19 +45,18 @@ int SpaceMode(int argc, char** argv) {
// Parse arguments (which should be of the form "<sha1>" or
// "<sha1>:<filename>" into the new parallel arrays *sha1s and
-// *patches (loading file contents into the patches). Returns 0 on
+// *patches (loading file contents into the patches). Returns true on
// success.
-static int ParsePatchArgs(int argc, char** argv,
- char*** sha1s, Value*** patches, int* num_patches) {
+static bool ParsePatchArgs(int argc, char** argv, char*** sha1s,
+ Value*** patches, int* num_patches) {
*num_patches = argc;
- *sha1s = malloc(*num_patches * sizeof(char*));
- *patches = malloc(*num_patches * sizeof(Value*));
+ *sha1s = reinterpret_cast<char**>(malloc(*num_patches * sizeof(char*)));
+ *patches = reinterpret_cast<Value**>(malloc(*num_patches * sizeof(Value*)));
memset(*patches, 0, *num_patches * sizeof(Value*));
uint8_t digest[SHA_DIGEST_SIZE];
- int i;
- for (i = 0; i < *num_patches; ++i) {
+ for (int i = 0; i < *num_patches; ++i) {
char* colon = strchr(argv[i], ':');
if (colon != NULL) {
*colon = '\0';
@@ -66,7 +65,7 @@ static int ParsePatchArgs(int argc, char** argv,
if (ParseSha1(argv[i], digest) != 0) {
printf("failed to parse sha1 \"%s\"\n", argv[i]);
- return -1;
+ return false;
}
(*sha1s)[i] = argv[i];
@@ -77,17 +76,17 @@ static int ParsePatchArgs(int argc, char** argv,
if (LoadFileContents(colon, &fc) != 0) {
goto abort;
}
- (*patches)[i] = malloc(sizeof(Value));
+ (*patches)[i] = reinterpret_cast<Value*>(malloc(sizeof(Value)));
(*patches)[i]->type = VAL_BLOB;
(*patches)[i]->size = fc.size;
- (*patches)[i]->data = (char*)fc.data;
+ (*patches)[i]->data = reinterpret_cast<char*>(fc.data);
}
}
- return 0;
+ return true;
abort:
- for (i = 0; i < *num_patches; ++i) {
+ for (int i = 0; i < *num_patches; ++i) {
Value* p = (*patches)[i];
if (p != NULL) {
free(p->data);
@@ -96,10 +95,15 @@ static int ParsePatchArgs(int argc, char** argv,
}
free(*sha1s);
free(*patches);
- return -1;
+ return false;
+}
+
+static int FlashMode(const char* src_filename, const char* tgt_filename,
+ const char* tgt_sha1, size_t tgt_size) {
+ return applypatch_flash(src_filename, tgt_filename, tgt_sha1, tgt_size);
}
-int PatchMode(int argc, char** argv) {
+static int PatchMode(int argc, char** argv) {
Value* bonus = NULL;
if (argc >= 3 && strcmp(argv[1], "-b") == 0) {
FileContents fc;
@@ -107,7 +111,7 @@ int PatchMode(int argc, char** argv) {
printf("failed to load bonus file %s\n", argv[2]);
return 1;
}
- bonus = malloc(sizeof(Value));
+ bonus = reinterpret_cast<Value*>(malloc(sizeof(Value)));
bonus->type = VAL_BLOB;
bonus->size = fc.size;
bonus->data = (char*)fc.data;
@@ -115,7 +119,7 @@ int PatchMode(int argc, char** argv) {
argv += 2;
}
- if (argc < 6) {
+ if (argc < 4) {
return 2;
}
@@ -126,10 +130,20 @@ int PatchMode(int argc, char** argv) {
return 1;
}
+ // If no <src-sha1>:<patch> is provided, it is in flash mode.
+ if (argc == 5) {
+ if (bonus != NULL) {
+ printf("bonus file not supported in flash mode\n");
+ return 1;
+ }
+ return FlashMode(argv[1], argv[2], argv[3], target_size);
+ }
+
+
char** sha1s;
Value** patches;
int num_patches;
- if (ParsePatchArgs(argc-5, argv+5, &sha1s, &patches, &num_patches) != 0) {
+ if (!ParsePatchArgs(argc-5, argv+5, &sha1s, &patches, &num_patches)) {
printf("failed to parse patch args\n");
return 1;
}
@@ -163,6 +177,10 @@ int PatchMode(int argc, char** argv) {
// - if the sha1 hash of <tgt-file> is <tgt-sha1>, does nothing and exits
// successfully.
//
+// - otherwise, if no <src-sha1>:<patch> is provided, flashes <tgt-file> with
+// <src-file>. <tgt-file> must be a partition name, while <src-file> must
+// be a regular image file. <src-file> will not be deleted on success.
+//
// - otherwise, if the sha1 hash of <src-file> is <src-sha1>, applies the
// bsdiff <patch> to <src-file> to produce a new file (the type of patch
// is automatically detected from the file header). If that new
diff --git a/applypatch/utils.c b/applypatch/utils.cpp
index 41ff676dc..4a80be75f 100644
--- a/applypatch/utils.c
+++ b/applypatch/utils.cpp
@@ -39,13 +39,13 @@ void Write8(long long value, FILE* f) {
}
int Read2(void* pv) {
- unsigned char* p = pv;
+ unsigned char* p = reinterpret_cast<unsigned char*>(pv);
return (int)(((unsigned int)p[1] << 8) |
(unsigned int)p[0]);
}
int Read4(void* pv) {
- unsigned char* p = pv;
+ unsigned char* p = reinterpret_cast<unsigned char*>(pv);
return (int)(((unsigned int)p[3] << 24) |
((unsigned int)p[2] << 16) |
((unsigned int)p[1] << 8) |
@@ -53,7 +53,7 @@ int Read4(void* pv) {
}
long long Read8(void* pv) {
- unsigned char* p = pv;
+ unsigned char* p = reinterpret_cast<unsigned char*>(pv);
return (long long)(((unsigned long long)p[7] << 56) |
((unsigned long long)p[6] << 48) |
((unsigned long long)p[5] << 40) |
diff --git a/bootloader.h b/bootloader.h
index c2895dd91..742a4abfb 100644
--- a/bootloader.h
+++ b/bootloader.h
@@ -17,10 +17,6 @@
#ifndef _RECOVERY_BOOTLOADER_H
#define _RECOVERY_BOOTLOADER_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
/* Bootloader Message
*
* This structure describes the content of a block in flash
@@ -43,6 +39,13 @@ extern "C" {
* multiple times, so that the UI can reflect which invocation of the
* package it is. If the value is of the format "#/#" (eg, "1/3"),
* the UI will add a simple indicator of that status.
+ *
+ * The slot_suffix field is used for A/B implementations where the
+ * bootloader does not set the androidboot.ro.boot.slot_suffix kernel
+ * commandline parameter. This is used by fs_mgr to mount /system and
+ * other partitions with the slotselect flag set in fstab. A/B
+ * implementations are free to use all 32 bytes and may store private
+ * data past the first NUL-byte in this field.
*/
struct bootloader_message {
char command[32];
@@ -55,7 +58,8 @@ struct bootloader_message {
// stage string (for multistage packages) and possible future
// expansion.
char stage[32];
- char reserved[224];
+ char slot_suffix[32];
+ char reserved[192];
};
/* Read and write the bootloader command from the "misc" partition.
@@ -64,8 +68,4 @@ struct bootloader_message {
int get_bootloader_message(struct bootloader_message *out);
int set_bootloader_message(const struct bootloader_message *in);
-#ifdef __cplusplus
-}
-#endif
-
#endif
diff --git a/common.h b/common.h
index b818ceb84..de8b409fd 100644
--- a/common.h
+++ b/common.h
@@ -21,10 +21,6 @@
#include <stdio.h>
#include <stdarg.h>
-#ifdef __cplusplus
-extern "C" {
-#endif
-
#define LOGE(...) ui_print("E:" __VA_ARGS__)
#define LOGW(...) fprintf(stdout, "W:" __VA_ARGS__)
#define LOGI(...) fprintf(stdout, "I:" __VA_ARGS__)
@@ -50,8 +46,4 @@ void ui_print(const char* format, ...);
bool is_ro_debuggable();
-#ifdef __cplusplus
-}
-#endif
-
#endif // RECOVERY_COMMON_H
diff --git a/edify/Android.mk b/edify/Android.mk
index 03c04e432..9b859d42e 100644
--- a/edify/Android.mk
+++ b/edify/Android.mk
@@ -5,12 +5,7 @@ LOCAL_PATH := $(call my-dir)
edify_src_files := \
lexer.l \
parser.y \
- expr.c
-
-# "-x c" forces the lex/yacc files to be compiled as c the build system
-# otherwise forces them to be c++. Need to also add an explicit -std because the
-# build system will soon default C++ to -std=c++11.
-edify_cflags := -x c -std=gnu89
+ expr.cpp
#
# Build the host-side command line tool
@@ -19,12 +14,14 @@ include $(CLEAR_VARS)
LOCAL_SRC_FILES := \
$(edify_src_files) \
- main.c
+ main.cpp
-LOCAL_CFLAGS := $(edify_cflags) -g -O0
+LOCAL_CPPFLAGS := -g -O0
LOCAL_MODULE := edify
LOCAL_YACCFLAGS := -v
-LOCAL_CFLAGS += -Wno-unused-parameter
+LOCAL_CPPFLAGS += -Wno-unused-parameter
+LOCAL_CPPFLAGS += -Wno-deprecated-register
+LOCAL_CLANG := true
include $(BUILD_HOST_EXECUTABLE)
@@ -35,8 +32,9 @@ include $(CLEAR_VARS)
LOCAL_SRC_FILES := $(edify_src_files)
-LOCAL_CFLAGS := $(edify_cflags)
-LOCAL_CFLAGS += -Wno-unused-parameter
+LOCAL_CPPFLAGS := -Wno-unused-parameter
+LOCAL_CPPFLAGS += -Wno-deprecated-register
LOCAL_MODULE := libedify
+LOCAL_CLANG := true
include $(BUILD_STATIC_LIBRARY)
diff --git a/edify/expr.c b/edify/expr.cpp
index 79f6282d8..cd1e08726 100644
--- a/edify/expr.c
+++ b/edify/expr.cpp
@@ -51,7 +51,7 @@ Value* EvaluateValue(State* state, Expr* expr) {
Value* StringValue(char* str) {
if (str == NULL) return NULL;
- Value* v = malloc(sizeof(Value));
+ Value* v = reinterpret_cast<Value*>(malloc(sizeof(Value)));
v->type = VAL_STRING;
v->size = strlen(str);
v->data = str;
@@ -68,7 +68,7 @@ Value* ConcatFn(const char* name, State* state, int argc, Expr* argv[]) {
if (argc == 0) {
return StringValue(strdup(""));
}
- char** strings = malloc(argc * sizeof(char*));
+ char** strings = reinterpret_cast<char**>(malloc(argc * sizeof(char*)));
int i;
for (i = 0; i < argc; ++i) {
strings[i] = NULL;
@@ -83,8 +83,9 @@ Value* ConcatFn(const char* name, State* state, int argc, Expr* argv[]) {
length += strlen(strings[i]);
}
- result = malloc(length+1);
- int p = 0;
+ result = reinterpret_cast<char*>(malloc(length+1));
+ int p;
+ p = 0;
for (i = 0; i < argc; ++i) {
strcpy(result+p, strings[i]);
p += strlen(strings[i]);
@@ -149,7 +150,7 @@ Value* AssertFn(const char* name, State* state, int argc, Expr* argv[]) {
if (!b) {
int prefix_len;
int len = argv[i]->end - argv[i]->start;
- char* err_src = malloc(len + 20);
+ char* err_src = reinterpret_cast<char*>(malloc(len + 20));
strcpy(err_src, "assert failed: ");
prefix_len = strlen(err_src);
memcpy(err_src + prefix_len, state->script + argv[i]->start, len);
@@ -290,7 +291,8 @@ Value* LessThanIntFn(const char* name, State* state, int argc, Expr* argv[]) {
goto done;
}
- long r_int = strtol(right, &end, 10);
+ long r_int;
+ r_int = strtol(right, &end, 10);
if (right[0] == '\0' || *end != '\0') {
goto done;
}
@@ -325,11 +327,11 @@ Value* Literal(const char* name, State* state, int argc, Expr* argv[]) {
Expr* Build(Function fn, YYLTYPE loc, int count, ...) {
va_list v;
va_start(v, count);
- Expr* e = malloc(sizeof(Expr));
+ Expr* e = reinterpret_cast<Expr*>(malloc(sizeof(Expr)));
e->fn = fn;
e->name = "(operator)";
e->argc = count;
- e->argv = malloc(count * sizeof(Expr*));
+ e->argv = reinterpret_cast<Expr**>(malloc(count * sizeof(Expr*)));
int i;
for (i = 0; i < count; ++i) {
e->argv[i] = va_arg(v, Expr*);
@@ -351,7 +353,7 @@ NamedFunction* fn_table = NULL;
void RegisterFunction(const char* name, Function fn) {
if (fn_entries >= fn_size) {
fn_size = fn_size*2 + 1;
- fn_table = realloc(fn_table, fn_size * sizeof(NamedFunction));
+ fn_table = reinterpret_cast<NamedFunction*>(realloc(fn_table, fn_size * sizeof(NamedFunction)));
}
fn_table[fn_entries].name = name;
fn_table[fn_entries].fn = fn;
@@ -371,8 +373,8 @@ void FinishRegistration() {
Function FindFunction(const char* name) {
NamedFunction key;
key.name = name;
- NamedFunction* nf = bsearch(&key, fn_table, fn_entries,
- sizeof(NamedFunction), fn_entry_compare);
+ NamedFunction* nf = reinterpret_cast<NamedFunction*>(bsearch(&key, fn_table, fn_entries,
+ sizeof(NamedFunction), fn_entry_compare));
if (nf == NULL) {
return NULL;
}
@@ -401,7 +403,7 @@ void RegisterBuiltins() {
// zero or more char** to put them in). If any expression evaluates
// to NULL, free the rest and return -1. Return 0 on success.
int ReadArgs(State* state, Expr* argv[], int count, ...) {
- char** args = malloc(count * sizeof(char*));
+ char** args = reinterpret_cast<char**>(malloc(count * sizeof(char*)));
va_list v;
va_start(v, count);
int i;
@@ -427,7 +429,7 @@ int ReadArgs(State* state, Expr* argv[], int count, ...) {
// zero or more Value** to put them in). If any expression evaluates
// to NULL, free the rest and return -1. Return 0 on success.
int ReadValueArgs(State* state, Expr* argv[], int count, ...) {
- Value** args = malloc(count * sizeof(Value*));
+ Value** args = reinterpret_cast<Value**>(malloc(count * sizeof(Value*)));
va_list v;
va_start(v, count);
int i;
@@ -494,7 +496,7 @@ Value** ReadValueVarArgs(State* state, int argc, Expr* argv[]) {
// Use printf-style arguments to compose an error message to put into
// *state. Returns NULL.
Value* ErrorAbort(State* state, const char* format, ...) {
- char* buffer = malloc(4096);
+ char* buffer = reinterpret_cast<char*>(malloc(4096));
va_list v;
va_start(v, format);
vsnprintf(buffer, 4096, format, v);
diff --git a/edify/expr.h b/edify/expr.h
index a9ed2f9c5..36f8e9612 100644
--- a/edify/expr.h
+++ b/edify/expr.h
@@ -21,10 +21,6 @@
#include "yydefs.h"
-#ifdef __cplusplus
-extern "C" {
-#endif
-
#define MAX_STRING_LEN 1024
typedef struct Expr Expr;
@@ -59,7 +55,7 @@ typedef Value* (*Function)(const char* name, State* state,
struct Expr {
Function fn;
- char* name;
+ const char* name;
int argc;
Expr** argv;
int start, end;
@@ -166,8 +162,4 @@ void FreeValue(Value* v);
int parse_string(const char* str, Expr** root, int* error_count);
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
#endif // _EXPRESSION_H
diff --git a/edify/main.c b/edify/main.cpp
index b1baa0b13..b1baa0b13 100644
--- a/edify/main.c
+++ b/edify/main.cpp
diff --git a/edify/parser.y b/edify/parser.y
index f8fb2d12f..098a6370a 100644
--- a/edify/parser.y
+++ b/edify/parser.y
@@ -70,7 +70,7 @@ input: expr { *root = $1; }
;
expr: STRING {
- $$ = malloc(sizeof(Expr));
+ $$ = reinterpret_cast<Expr*>(malloc(sizeof(Expr)));
$$->fn = Literal;
$$->name = $1;
$$->argc = 0;
@@ -91,7 +91,7 @@ expr: STRING {
| IF expr THEN expr ENDIF { $$ = Build(IfElseFn, @$, 2, $2, $4); }
| IF expr THEN expr ELSE expr ENDIF { $$ = Build(IfElseFn, @$, 3, $2, $4, $6); }
| STRING '(' arglist ')' {
- $$ = malloc(sizeof(Expr));
+ $$ = reinterpret_cast<Expr*>(malloc(sizeof(Expr)));
$$->fn = FindFunction($1);
if ($$->fn == NULL) {
char buffer[256];
@@ -113,12 +113,12 @@ arglist: /* empty */ {
}
| expr {
$$.argc = 1;
- $$.argv = malloc(sizeof(Expr*));
+ $$.argv = reinterpret_cast<Expr**>(malloc(sizeof(Expr*)));
$$.argv[0] = $1;
}
| arglist ',' expr {
$$.argc = $1.argc + 1;
- $$.argv = realloc($$.argv, $$.argc * sizeof(Expr*));
+ $$.argv = reinterpret_cast<Expr**>(realloc($$.argv, $$.argc * sizeof(Expr*)));
$$.argv[$$.argc-1] = $3;
}
;
diff --git a/etc/init.rc b/etc/init.rc
index 427727768..dc1865986 100644
--- a/etc/init.rc
+++ b/etc/init.rc
@@ -5,7 +5,6 @@ on early-init
start healthd
on init
- export PATH /sbin:/system/bin
export ANDROID_ROOT /system
export ANDROID_DATA /data
export EXTERNAL_STORAGE /sdcard
diff --git a/fuse_sdcard_provider.c b/fuse_sdcard_provider.cpp
index 4565c7b5b..eb6454f1d 100644
--- a/fuse_sdcard_provider.c
+++ b/fuse_sdcard_provider.cpp
@@ -34,7 +34,7 @@ struct file_data {
};
static int read_block_file(void* cookie, uint32_t block, uint8_t* buffer, uint32_t fetch_size) {
- struct file_data* fd = (struct file_data*)cookie;
+ file_data* fd = reinterpret_cast<file_data*>(cookie);
off64_t offset = ((off64_t) block) * fd->block_size;
if (TEMP_FAILURE_RETRY(lseek64(fd->fd, offset, SEEK_SET)) == -1) {
@@ -56,7 +56,7 @@ static int read_block_file(void* cookie, uint32_t block, uint8_t* buffer, uint32
}
static void close_file(void* cookie) {
- struct file_data* fd = (struct file_data*)cookie;
+ file_data* fd = reinterpret_cast<file_data*>(cookie);
close(fd->fd);
}
@@ -67,7 +67,7 @@ struct token {
};
static void* run_sdcard_fuse(void* cookie) {
- struct token* t = (struct token*)cookie;
+ token* t = reinterpret_cast<token*>(cookie);
struct stat sb;
if (stat(t->path, &sb) < 0) {
@@ -100,7 +100,7 @@ static void* run_sdcard_fuse(void* cookie) {
#define SDCARD_INSTALL_TIMEOUT 10
void* start_sdcard_fuse(const char* path) {
- struct token* t = malloc(sizeof(struct token));
+ token* t = new token;
t->path = path;
pthread_create(&(t->th), NULL, run_sdcard_fuse, t);
@@ -128,7 +128,7 @@ void* start_sdcard_fuse(const char* path) {
void finish_sdcard_fuse(void* cookie) {
if (cookie == NULL) return;
- struct token* t = (struct token*)cookie;
+ token* t = reinterpret_cast<token*>(cookie);
// Calling stat() on this magic filename signals the fuse
// filesystem to shut down.
@@ -136,5 +136,5 @@ void finish_sdcard_fuse(void* cookie) {
stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
pthread_join(t->th, NULL);
- free(t);
+ delete t;
}
diff --git a/fuse_sdcard_provider.h b/fuse_sdcard_provider.h
index dbfbcd521..dc2982ca0 100644
--- a/fuse_sdcard_provider.h
+++ b/fuse_sdcard_provider.h
@@ -17,13 +17,7 @@
#ifndef __FUSE_SDCARD_PROVIDER_H
#define __FUSE_SDCARD_PROVIDER_H
-#include <sys/cdefs.h>
-
-__BEGIN_DECLS
-
void* start_sdcard_fuse(const char* path);
void finish_sdcard_fuse(void* token);
-__END_DECLS
-
#endif
diff --git a/fuse_sideload.c b/fuse_sideload.cpp
index 48e6cc53a..9c3e75f89 100644
--- a/fuse_sideload.c
+++ b/fuse_sideload.cpp
@@ -116,7 +116,7 @@ static void fuse_reply(struct fuse_data* fd, __u64 unique, const void *data, siz
}
static int handle_init(void* data, struct fuse_data* fd, const struct fuse_in_header* hdr) {
- const struct fuse_init_in* req = data;
+ const struct fuse_init_in* req = reinterpret_cast<const struct fuse_init_in*>(data);
struct fuse_init_out out;
size_t fuse_struct_size;
@@ -170,8 +170,7 @@ static void fill_attr(struct fuse_attr* attr, struct fuse_data* fd,
attr->mode = mode;
}
-static int handle_getattr(void* data, struct fuse_data* fd, const struct fuse_in_header* hdr) {
- const struct fuse_getattr_in* req = data;
+static int handle_getattr(void* /* data */, struct fuse_data* fd, const struct fuse_in_header* hdr) {
struct fuse_attr_out out;
memset(&out, 0, sizeof(out));
out.attr_valid = 10;
@@ -197,12 +196,12 @@ static int handle_lookup(void* data, struct fuse_data* fd,
out.entry_valid = 10;
out.attr_valid = 10;
- if (strncmp(FUSE_SIDELOAD_HOST_FILENAME, data,
+ if (strncmp(FUSE_SIDELOAD_HOST_FILENAME, reinterpret_cast<const char*>(data),
sizeof(FUSE_SIDELOAD_HOST_FILENAME)) == 0) {
out.nodeid = PACKAGE_FILE_ID;
out.generation = PACKAGE_FILE_ID;
fill_attr(&(out.attr), fd, PACKAGE_FILE_ID, fd->file_size, S_IFREG | 0444);
- } else if (strncmp(FUSE_SIDELOAD_HOST_EXIT_FLAG, data,
+ } else if (strncmp(FUSE_SIDELOAD_HOST_EXIT_FLAG, reinterpret_cast<const char*>(data),
sizeof(FUSE_SIDELOAD_HOST_EXIT_FLAG)) == 0) {
out.nodeid = EXIT_FLAG_ID;
out.generation = EXIT_FLAG_ID;
@@ -215,9 +214,7 @@ static int handle_lookup(void* data, struct fuse_data* fd,
return (out.nodeid == EXIT_FLAG_ID) ? NO_STATUS_EXIT : NO_STATUS;
}
-static int handle_open(void* data, struct fuse_data* fd, const struct fuse_in_header* hdr) {
- const struct fuse_open_in* req = data;
-
+static int handle_open(void* /* data */, struct fuse_data* fd, const struct fuse_in_header* hdr) {
if (hdr->nodeid == EXIT_FLAG_ID) return -EPERM;
if (hdr->nodeid != PACKAGE_FILE_ID) return -ENOENT;
@@ -292,7 +289,7 @@ static int fetch_block(struct fuse_data* fd, uint32_t block) {
}
static int handle_read(void* data, struct fuse_data* fd, const struct fuse_in_header* hdr) {
- const struct fuse_read_in* req = data;
+ const struct fuse_read_in* req = reinterpret_cast<const struct fuse_read_in*>(data);
struct fuse_out_header outhdr;
struct iovec vec[3];
int vec_used;
diff --git a/fuse_sideload.h b/fuse_sideload.h
index f9e3bf0d3..c0b16efbe 100644
--- a/fuse_sideload.h
+++ b/fuse_sideload.h
@@ -17,10 +17,6 @@
#ifndef __FUSE_SIDELOAD_H
#define __FUSE_SIDELOAD_H
-#include <sys/cdefs.h>
-
-__BEGIN_DECLS
-
// define the filenames created by the sideload FUSE filesystem
#define FUSE_SIDELOAD_HOST_MOUNTPOINT "/sideload"
#define FUSE_SIDELOAD_HOST_FILENAME "package.zip"
@@ -39,6 +35,4 @@ struct provider_vtab {
int run_fuse_sideload(struct provider_vtab* vtab, void* cookie,
uint64_t file_size, uint32_t block_size);
-__END_DECLS
-
#endif
diff --git a/install.cpp b/install.cpp
index c7d382f3e..7d88ed72a 100644
--- a/install.cpp
+++ b/install.cpp
@@ -164,9 +164,9 @@ try_update_binary(const char* path, ZipArchive* zip, bool* wipe_cache) {
} else if (strcmp(command, "ui_print") == 0) {
char* str = strtok(NULL, "\n");
if (str) {
- ui->Print("%s", str);
+ ui->PrintOnScreenOnly("%s", str);
} else {
- ui->Print("\n");
+ ui->PrintOnScreenOnly("\n");
}
fflush(stdout);
} else if (strcmp(command, "wipe_cache") == 0) {
diff --git a/minadbd/Android.mk b/minadbd/Android.mk
index a7a3e087d..3db3b4114 100644
--- a/minadbd/Android.mk
+++ b/minadbd/Android.mk
@@ -15,6 +15,7 @@ LOCAL_SRC_FILES := \
fuse_adb_provider.cpp \
services.cpp \
+LOCAL_CLANG := true
LOCAL_MODULE := libminadbd
LOCAL_CFLAGS := $(minadbd_cflags)
LOCAL_CONLY_FLAGS := -Wimplicit-function-declaration
diff --git a/minadbd/adb_main.cpp b/minadbd/adb_main.cpp
index 7fae99a9a..514f19699 100644
--- a/minadbd/adb_main.cpp
+++ b/minadbd/adb_main.cpp
@@ -27,13 +27,9 @@
#include "adb_auth.h"
#include "transport.h"
-int adb_main(int is_daemon, int server_port)
-{
- atexit(usb_cleanup);
-
+int adb_main(int is_daemon, int server_port, int /* reply_fd */) {
adb_device_banner = "sideload";
- // No SIGCHLD. Let the service subproc handle its children.
signal(SIGPIPE, SIG_IGN);
// We can't require authentication for sideloading. http://b/22025550.
diff --git a/minadbd/services.cpp b/minadbd/services.cpp
index dd1fd7c4b..859463caf 100644
--- a/minadbd/services.cpp
+++ b/minadbd/services.cpp
@@ -61,8 +61,7 @@ static void sideload_host_service(int sfd, void* data) {
exit(result == 0 ? 0 : 1);
}
-static int create_service_thread(void (*func)(int, void *), void *cookie)
-{
+static int create_service_thread(void (*func)(int, void *), void *cookie) {
int s[2];
if(adb_socketpair(s)) {
printf("cannot create service socket pair\n");
@@ -75,8 +74,7 @@ static int create_service_thread(void (*func)(int, void *), void *cookie)
sti->cookie = cookie;
sti->fd = s[1];
- adb_thread_t t;
- if (adb_thread_create( &t, service_bootstrap_func, sti)){
+ if (!adb_thread_create(service_bootstrap_func, sti)) {
free(sti);
adb_close(s[0]);
adb_close(s[1]);
diff --git a/minui/Android.mk b/minui/Android.mk
index 97724fbf0..3057f452c 100644
--- a/minui/Android.mk
+++ b/minui/Android.mk
@@ -41,6 +41,7 @@ include $(BUILD_STATIC_LIBRARY)
# Used by OEMs for factory test images.
include $(CLEAR_VARS)
+LOCAL_CLANG := true
LOCAL_MODULE := libminui
LOCAL_WHOLE_STATIC_LIBRARIES += libminui
LOCAL_SHARED_LIBRARIES := libpng
diff --git a/minzip/Android.mk b/minzip/Android.mk
index 045f35570..22eabfbb1 100644
--- a/minzip/Android.mk
+++ b/minzip/Android.mk
@@ -16,6 +16,8 @@ LOCAL_STATIC_LIBRARIES := libselinux
LOCAL_MODULE := libminzip
-LOCAL_CFLAGS += -Wall
+LOCAL_CLANG := true
+
+LOCAL_CFLAGS += -Werror -Wall
include $(BUILD_STATIC_LIBRARY)
diff --git a/minzip/Hash.c b/minzip/Hash.c
index 8f8ed68e5..49bcb3161 100644
--- a/minzip/Hash.c
+++ b/minzip/Hash.c
@@ -361,7 +361,7 @@ void mzHashTableProbeCount(HashTable* pHashTable, HashCalcFunc calcFunc,
{
const void* data = (const void*)mzHashIterData(&iter);
int count;
-
+
count = countProbes(pHashTable, (*calcFunc)(data), data, cmpFunc);
numEntries++;
@@ -373,7 +373,7 @@ void mzHashTableProbeCount(HashTable* pHashTable, HashCalcFunc calcFunc,
totalProbe += count;
}
- LOGI("Probe: min=%d max=%d, total=%d in %d (%d), avg=%.3f\n",
+ LOGV("Probe: min=%d max=%d, total=%d in %d (%d), avg=%.3f\n",
minProbe, maxProbe, totalProbe, numEntries, pHashTable->tableSize,
(float) totalProbe / (float) numEntries);
}
diff --git a/minzip/Hash.h b/minzip/Hash.h
index 8194537f3..e83eac414 100644
--- a/minzip/Hash.h
+++ b/minzip/Hash.h
@@ -15,6 +15,10 @@
#include <stdbool.h>
#include <assert.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
/* compute the hash of an item with a specific type */
typedef unsigned int (*HashCompute)(const void* item);
@@ -183,4 +187,8 @@ typedef unsigned int (*HashCalcFunc)(const void* item);
void mzHashTableProbeCount(HashTable* pHashTable, HashCalcFunc calcFunc,
HashCompareFunc cmpFunc);
+#ifdef __cplusplus
+}
+#endif
+
#endif /*_MINZIP_HASH*/
diff --git a/minzip/SysUtil.c b/minzip/SysUtil.c
index b160c9e3d..09ec8768f 100644
--- a/minzip/SysUtil.c
+++ b/minzip/SysUtil.c
@@ -3,86 +3,46 @@
*
* System utilities.
*/
-#include <stdlib.h>
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdbool.h>
#include <stdio.h>
-#include <unistd.h>
+#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
-#include <sys/types.h>
#include <sys/stat.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <errno.h>
-#include <assert.h>
+#include <sys/types.h>
+#include <unistd.h>
#define LOG_TAG "sysutil"
#include "Log.h"
#include "SysUtil.h"
-static int getFileStartAndLength(int fd, off_t *start_, size_t *length_)
-{
- off_t start, end;
- size_t length;
-
- assert(start_ != NULL);
- assert(length_ != NULL);
-
- // TODO: isn't start always 0 for the single call site? just use fstat instead?
-
- start = TEMP_FAILURE_RETRY(lseek(fd, 0L, SEEK_CUR));
- end = TEMP_FAILURE_RETRY(lseek(fd, 0L, SEEK_END));
-
- if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1 ||
- start == (off_t) -1 || end == (off_t) -1) {
- LOGE("could not determine length of file\n");
- return -1;
- }
-
- length = end - start;
- if (length == 0) {
- LOGE("file is empty\n");
- return -1;
- }
-
- *start_ = start;
- *length_ = length;
-
- return 0;
-}
-
-/*
- * Map a file (from fd's current offset) into a private, read-only memory
- * segment. The file offset must be a multiple of the page size.
- *
- * On success, returns 0 and fills out "pMap". On failure, returns a nonzero
- * value and does not disturb "pMap".
- */
-static int sysMapFD(int fd, MemMapping* pMap)
-{
- off_t start;
- size_t length;
- void* memPtr;
-
+static bool sysMapFD(int fd, MemMapping* pMap) {
assert(pMap != NULL);
- if (getFileStartAndLength(fd, &start, &length) < 0)
- return -1;
+ struct stat sb;
+ if (fstat(fd, &sb) == -1) {
+ LOGE("fstat(%d) failed: %s\n", fd, strerror(errno));
+ return false;
+ }
- memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start);
+ void* memPtr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (memPtr == MAP_FAILED) {
- LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length,
- fd, (int) start, strerror(errno));
- return -1;
+ LOGE("mmap(%d, R, PRIVATE, %d, 0) failed: %s\n", (int) sb.st_size, fd, strerror(errno));
+ return false;
}
pMap->addr = memPtr;
- pMap->length = length;
+ pMap->length = sb.st_size;
pMap->range_count = 1;
pMap->ranges = malloc(sizeof(MappedRange));
pMap->ranges[0].addr = memPtr;
- pMap->ranges[0].length = length;
+ pMap->ranges[0].length = sb.st_size;
- return 0;
+ return true;
}
static int sysMapBlockFile(FILE* mapf, MemMapping* pMap)
@@ -95,7 +55,7 @@ static int sysMapBlockFile(FILE* mapf, MemMapping* pMap)
unsigned int i;
if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) {
- LOGW("failed to read block device from header\n");
+ LOGE("failed to read block device from header\n");
return -1;
}
for (i = 0; i < sizeof(block_dev); ++i) {
@@ -106,7 +66,7 @@ static int sysMapBlockFile(FILE* mapf, MemMapping* pMap)
}
if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) {
- LOGW("failed to parse block map header\n");
+ LOGE("failed to parse block map header\n");
return -1;
}
@@ -120,7 +80,7 @@ static int sysMapBlockFile(FILE* mapf, MemMapping* pMap)
unsigned char* reserve;
reserve = mmap64(NULL, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
if (reserve == MAP_FAILED) {
- LOGW("failed to reserve address space: %s\n", strerror(errno));
+ LOGE("failed to reserve address space: %s\n", strerror(errno));
return -1;
}
@@ -129,7 +89,7 @@ static int sysMapBlockFile(FILE* mapf, MemMapping* pMap)
int fd = open(block_dev, O_RDONLY);
if (fd < 0) {
- LOGW("failed to open block device %s: %s\n", block_dev, strerror(errno));
+ LOGE("failed to open block device %s: %s\n", block_dev, strerror(errno));
return -1;
}
@@ -137,13 +97,13 @@ static int sysMapBlockFile(FILE* mapf, MemMapping* pMap)
for (i = 0; i < range_count; ++i) {
int start, end;
if (fscanf(mapf, "%d %d\n", &start, &end) != 2) {
- LOGW("failed to parse range %d in block map\n", i);
+ LOGE("failed to parse range %d in block map\n", i);
return -1;
}
void* addr = mmap64(next, (end-start)*blksize, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize);
if (addr == MAP_FAILED) {
- LOGW("failed to map block %d: %s\n", i, strerror(errno));
+ LOGE("failed to map block %d: %s\n", i, strerror(errno));
return -1;
}
pMap->ranges[i].addr = addr;
@@ -168,25 +128,25 @@ int sysMapFile(const char* fn, MemMapping* pMap)
// A map of blocks
FILE* mapf = fopen(fn+1, "r");
if (mapf == NULL) {
- LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno));
+ LOGE("Unable to open '%s': %s\n", fn+1, strerror(errno));
return -1;
}
if (sysMapBlockFile(mapf, pMap) != 0) {
- LOGW("Map of '%s' failed\n", fn);
+ LOGE("Map of '%s' failed\n", fn);
return -1;
}
fclose(mapf);
} else {
// This is a regular file.
- int fd = open(fn, O_RDONLY, 0);
- if (fd < 0) {
+ int fd = open(fn, O_RDONLY);
+ if (fd == -1) {
LOGE("Unable to open '%s': %s\n", fn, strerror(errno));
return -1;
}
- if (sysMapFD(fd, pMap) != 0) {
+ if (!sysMapFD(fd, pMap)) {
LOGE("Map of '%s' failed\n", fn);
close(fd);
return -1;
@@ -205,7 +165,7 @@ 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) {
- LOGW("munmap(%p, %d) failed: %s\n",
+ LOGE("munmap(%p, %d) failed: %s\n",
pMap->ranges[i].addr, (int)pMap->ranges[i].length, strerror(errno));
}
}
diff --git a/minzip/Zip.c b/minzip/Zip.c
index 40712e03a..bdb565c64 100644
--- a/minzip/Zip.c
+++ b/minzip/Zip.c
@@ -198,10 +198,10 @@ static bool parseZipArchive(ZipArchive* pArchive)
*/
val = get4LE(pArchive->addr);
if (val == ENDSIG) {
- LOGI("Found Zip archive, but it looks empty\n");
+ LOGW("Found Zip archive, but it looks empty\n");
goto bail;
} else if (val != LOCSIG) {
- LOGV("Not a Zip archive (found 0x%08x)\n", val);
+ LOGW("Not a Zip archive (found 0x%08x)\n", val);
goto bail;
}
@@ -217,7 +217,7 @@ static bool parseZipArchive(ZipArchive* pArchive)
ptr--;
}
if (ptr < (const unsigned char*) pArchive->addr) {
- LOGI("Could not find end-of-central-directory in Zip\n");
+ LOGW("Could not find end-of-central-directory in Zip\n");
goto bail;
}
@@ -429,7 +429,7 @@ int mzOpenZipArchive(unsigned char* addr, size_t length, ZipArchive* pArchive)
if (length < ENDHDR) {
err = -1;
- LOGV("File '%s' too small to be zip (%zd)\n", fileName, map.length);
+ LOGW("Archive %p is too small to be zip (%zd)\n", pArchive, length);
goto bail;
}
@@ -438,7 +438,7 @@ int mzOpenZipArchive(unsigned char* addr, size_t length, ZipArchive* pArchive)
if (!parseZipArchive(pArchive)) {
err = -1;
- LOGV("Parsing '%s' failed\n", fileName);
+ LOGW("Parsing archive %p failed\n", pArchive);
goto bail;
}
@@ -506,7 +506,6 @@ static bool processDeflatedEntry(const ZipArchive *pArchive,
void *cookie)
{
long result = -1;
- unsigned char readBuf[32 * 1024];
unsigned char procBuf[32 * 1024];
z_stream zstream;
int zerr;
@@ -549,7 +548,7 @@ static bool processDeflatedEntry(const ZipArchive *pArchive,
/* uncompress the data */
zerr = inflate(&zstream, Z_NO_FLUSH);
if (zerr != Z_OK && zerr != Z_STREAM_END) {
- LOGD("zlib inflate call failed (zerr=%d)\n", zerr);
+ LOGW("zlib inflate call failed (zerr=%d)\n", zerr);
goto z_bail;
}
@@ -603,7 +602,6 @@ bool mzProcessZipEntryContents(const ZipArchive *pArchive,
void *cookie)
{
bool ret = false;
- off_t oldOff;
switch (pEntry->compression) {
case STORED:
@@ -621,13 +619,6 @@ bool mzProcessZipEntryContents(const ZipArchive *pArchive,
return ret;
}
-static bool crcProcessFunction(const unsigned char *data, int dataLen,
- void *crc)
-{
- *(unsigned long *)crc = crc32(*(unsigned long *)crc, data, dataLen);
- return true;
-}
-
typedef struct {
char *buf;
int bufLen;
@@ -1016,7 +1007,7 @@ bool mzExtractRecursive(const ZipArchive *pArchive,
if (callback != NULL) callback(targetFile, cookie);
}
- LOGD("Extracted %d file(s)\n", extractCount);
+ LOGV("Extracted %d file(s)\n", extractCount);
free(helper.buf);
free(zpath);
diff --git a/mtdutils/Android.mk b/mtdutils/Android.mk
index f04355b5e..b7d35c27a 100644
--- a/mtdutils/Android.mk
+++ b/mtdutils/Android.mk
@@ -6,10 +6,12 @@ LOCAL_SRC_FILES := \
mounts.c
LOCAL_MODULE := libmtdutils
+LOCAL_CLANG := true
include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
+LOCAL_CLANG := true
LOCAL_SRC_FILES := flash_image.c
LOCAL_MODULE := flash_image
LOCAL_MODULE_TAGS := eng
diff --git a/print_sha1.h b/print_sha1.h
new file mode 100644
index 000000000..9e37c5fe3
--- /dev/null
+++ b/print_sha1.h
@@ -0,0 +1,43 @@
+/*
+ * 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 RECOVERY_PRINT_SHA1_H
+#define RECOVERY_PRINT_SHA1_H
+
+#include <stdint.h>
+#include <string>
+
+#include "mincrypt/sha.h"
+
+static std::string print_sha1(const uint8_t sha1[SHA_DIGEST_SIZE], size_t len) {
+ const char* hex = "0123456789abcdef";
+ std::string result = "";
+ for (size_t i = 0; i < len; ++i) {
+ result.push_back(hex[(sha1[i]>>4) & 0xf]);
+ result.push_back(hex[sha1[i] & 0xf]);
+ }
+ return result;
+}
+
+static std::string print_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
+ return print_sha1(sha1, SHA_DIGEST_SIZE);
+}
+
+static std::string short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
+ return print_sha1(sha1, 4);
+}
+
+#endif // RECOVERY_PRINT_SHA1_H
diff --git a/recovery.cpp b/recovery.cpp
index b7a545898..c683bae1d 100644
--- a/recovery.cpp
+++ b/recovery.cpp
@@ -31,24 +31,24 @@
#include <time.h>
#include <unistd.h>
+#include <adb.h>
#include <base/file.h>
#include <base/stringprintf.h>
+#include <cutils/android_reboot.h>
+#include <cutils/properties.h>
+#include "adb_install.h"
#include "bootloader.h"
#include "common.h"
-#include "cutils/properties.h"
-#include "cutils/android_reboot.h"
+#include "device.h"
+#include "fuse_sdcard_provider.h"
+#include "fuse_sideload.h"
#include "install.h"
#include "minui/minui.h"
#include "minzip/DirUtil.h"
#include "roots.h"
#include "ui.h"
#include "screen_ui.h"
-#include "device.h"
-#include "adb_install.h"
-#include "adb.h"
-#include "fuse_sideload.h"
-#include "fuse_sdcard_provider.h"
struct selabel_handle *sehandle;
@@ -326,14 +326,18 @@ static void rotate_logs(int max) {
ensure_path_mounted(LAST_KMSG_FILE);
for (int i = max-1; i >= 0; --i) {
- std::string old_log = android::base::StringPrintf((i == 0) ? "%s" : "%s.%d",
- LAST_LOG_FILE, i);
+ std::string old_log = android::base::StringPrintf("%s", LAST_LOG_FILE);
+ if (i > 0) {
+ old_log += "." + std::to_string(i);
+ }
std::string new_log = android::base::StringPrintf("%s.%d", LAST_LOG_FILE, i+1);
// Ignore errors if old_log doesn't exist.
rename(old_log.c_str(), new_log.c_str());
- std::string old_kmsg = android::base::StringPrintf((i == 0) ? "%s" : "%s.%d",
- LAST_KMSG_FILE, i);
+ std::string old_kmsg = android::base::StringPrintf("%s", LAST_KMSG_FILE);
+ if (i > 0) {
+ old_kmsg += "." + std::to_string(i);
+ }
std::string new_kmsg = android::base::StringPrintf("%s.%d", LAST_KMSG_FILE, i+1);
rename(old_kmsg.c_str(), new_kmsg.c_str());
}
@@ -706,7 +710,10 @@ static void choose_recovery_file(Device* device) {
// Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
for (int i = 0; i < KEEP_LOG_COUNT; i++) {
char* log_file;
- if (asprintf(&log_file, (i == 0) ? "%s" : "%s.%d", LAST_LOG_FILE, i) == -1) {
+ int ret;
+ ret = (i == 0) ? asprintf(&log_file, "%s", LAST_LOG_FILE) :
+ asprintf(&log_file, "%s.%d", LAST_LOG_FILE, i);
+ if (ret == -1) {
// memory allocation failure - return early. Should never happen.
return;
}
@@ -717,7 +724,9 @@ static void choose_recovery_file(Device* device) {
}
char* kmsg_file;
- if (asprintf(&kmsg_file, (i == 0) ? "%s" : "%s.%d", LAST_KMSG_FILE, i) == -1) {
+ ret = (i == 0) ? asprintf(&kmsg_file, "%s", LAST_KMSG_FILE) :
+ asprintf(&kmsg_file, "%s.%d", LAST_KMSG_FILE, i);
+ if (ret == -1) {
// memory allocation failure - return early. Should never happen.
return;
}
@@ -758,6 +767,7 @@ static int apply_from_sdcard(Device* device, bool* wipe_cache) {
char* path = browse_directory(SDCARD_ROOT, device);
if (path == NULL) {
ui->Print("\n-- No package file selected.\n");
+ ensure_path_unmounted(SDCARD_ROOT);
return INSTALL_ERROR;
}
@@ -853,9 +863,24 @@ prompt_and_wait(Device* device, int status) {
break;
case Device::MOUNT_SYSTEM:
- if (ensure_path_mounted("/system") != -1) {
- ui->Print("Mounted /system.\n");
+ char system_root_image[PROPERTY_VALUE_MAX];
+ property_get("ro.build.system_root_image", system_root_image, "");
+
+ // For a system image built with the root directory (i.e.
+ // system_root_image == "true"), we mount it to /system_root, and symlink /system
+ // to /system_root/system to make adb shell work (the symlink is created through
+ // the build system).
+ // Bug: 22855115
+ if (strcmp(system_root_image, "true") == 0) {
+ if (ensure_path_mounted_at("/", "/system_root") != -1) {
+ ui->Print("Mounted /system.\n");
+ }
+ } else {
+ if (ensure_path_mounted("/system") != -1) {
+ ui->Print("Mounted /system.\n");
+ }
}
+
break;
}
}
@@ -917,7 +942,7 @@ main(int argc, char **argv) {
// only way recovery should be run with this argument is when it
// starts a copy of itself from the apply_from_adb() function.
if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
- adb_main(0, DEFAULT_ADB_PORT);
+ adb_main(0, DEFAULT_ADB_PORT, -1);
return 0;
}
@@ -1011,11 +1036,15 @@ main(int argc, char **argv) {
if (strncmp(update_package, "CACHE:", 6) == 0) {
int len = strlen(update_package) + 10;
char* modified_path = (char*)malloc(len);
- strlcpy(modified_path, "/cache/", len);
- strlcat(modified_path, update_package+6, len);
- printf("(replacing path \"%s\" with \"%s\")\n",
- update_package, modified_path);
- update_package = modified_path;
+ if (modified_path) {
+ strlcpy(modified_path, "/cache/", len);
+ strlcat(modified_path, update_package+6, len);
+ printf("(replacing path \"%s\" with \"%s\")\n",
+ update_package, modified_path);
+ update_package = modified_path;
+ }
+ else
+ printf("modified_path allocation failed\n");
}
}
printf("\n");
@@ -1114,6 +1143,9 @@ main(int argc, char **argv) {
property_set(ANDROID_RB_PROPERTY, "reboot,");
break;
}
- sleep(5); // should reboot before this finishes
+ while (true) {
+ pause();
+ }
+ // Should be unreachable.
return EXIT_SUCCESS;
}
diff --git a/res-560dpi b/res-560dpi
new file mode 120000
index 000000000..8576a9b95
--- /dev/null
+++ b/res-560dpi
@@ -0,0 +1 @@
+res-xxhdpi \ No newline at end of file
diff --git a/roots.cpp b/roots.cpp
index 2bd457efe..12c6b5ee2 100644
--- a/roots.cpp
+++ b/roots.cpp
@@ -30,10 +30,8 @@
#include "roots.h"
#include "common.h"
#include "make_ext4fs.h"
-extern "C" {
#include "wipe.h"
#include "cryptfs.h"
-}
static struct fstab *fstab = NULL;
@@ -72,7 +70,8 @@ Volume* volume_for_path(const char* path) {
return fs_mgr_get_entry_for_mount_point(fstab, path);
}
-int ensure_path_mounted(const char* path) {
+// Mount the volume specified by path at the given mount_point.
+int ensure_path_mounted_at(const char* path, const char* mount_point) {
Volume* v = volume_for_path(path);
if (v == NULL) {
LOGE("unknown volume for path [%s]\n", path);
@@ -90,14 +89,18 @@ int ensure_path_mounted(const char* path) {
return -1;
}
+ if (!mount_point) {
+ mount_point = v->mount_point;
+ }
+
const MountedVolume* mv =
- find_mounted_volume_by_mount_point(v->mount_point);
+ find_mounted_volume_by_mount_point(mount_point);
if (mv) {
// volume is already mounted
return 0;
}
- mkdir(v->mount_point, 0755); // in case it doesn't already exist
+ mkdir(mount_point, 0755); // in case it doesn't already exist
if (strcmp(v->fs_type, "yaffs2") == 0) {
// mount an MTD partition as a YAFFS2 filesystem.
@@ -106,25 +109,30 @@ int ensure_path_mounted(const char* path) {
partition = mtd_find_partition_by_name(v->blk_device);
if (partition == NULL) {
LOGE("failed to find \"%s\" partition to mount at \"%s\"\n",
- v->blk_device, v->mount_point);
+ v->blk_device, mount_point);
return -1;
}
- return mtd_mount_partition(partition, v->mount_point, v->fs_type, 0);
+ return mtd_mount_partition(partition, mount_point, v->fs_type, 0);
} else if (strcmp(v->fs_type, "ext4") == 0 ||
strcmp(v->fs_type, "squashfs") == 0 ||
strcmp(v->fs_type, "vfat") == 0) {
- result = mount(v->blk_device, v->mount_point, v->fs_type,
+ result = mount(v->blk_device, mount_point, v->fs_type,
v->flags, v->fs_options);
if (result == 0) return 0;
- LOGE("failed to mount %s (%s)\n", v->mount_point, strerror(errno));
+ LOGE("failed to mount %s (%s)\n", mount_point, strerror(errno));
return -1;
}
- LOGE("unknown fs_type \"%s\" for %s\n", v->fs_type, v->mount_point);
+ LOGE("unknown fs_type \"%s\" for %s\n", v->fs_type, mount_point);
return -1;
}
+int ensure_path_mounted(const char* path) {
+ // Mount at the default mount point.
+ return ensure_path_mounted_at(path, nullptr);
+}
+
int ensure_path_unmounted(const char* path) {
Volume* v = volume_for_path(path);
if (v == NULL) {
diff --git a/roots.h b/roots.h
index 230d9ded3..6e3b24355 100644
--- a/roots.h
+++ b/roots.h
@@ -19,10 +19,6 @@
#include "common.h"
-#ifdef __cplusplus
-extern "C" {
-#endif
-
// Load and parse volume data from /etc/recovery.fstab.
void load_volume_table();
@@ -33,7 +29,10 @@ Volume* volume_for_path(const char* path);
// success (volume is mounted).
int ensure_path_mounted(const char* path);
-// Make sure that the volume 'path' is on is mounted. Returns 0 on
+// Similar to ensure_path_mounted, but allows one to specify the mount_point.
+int ensure_path_mounted_at(const char* path, const char* mount_point);
+
+// Make sure that the volume 'path' is on is unmounted. Returns 0 on
// success (volume is unmounted);
int ensure_path_unmounted(const char* path);
@@ -46,8 +45,4 @@ int format_volume(const char* volume);
// mounted (/tmp and /cache) are mounted. Returns 0 on success.
int setup_install_mounts();
-#ifdef __cplusplus
-}
-#endif
-
#endif // RECOVERY_ROOTS_H_
diff --git a/screen_ui.cpp b/screen_ui.cpp
index ff9591514..ddf85c19e 100644
--- a/screen_ui.cpp
+++ b/screen_ui.cpp
@@ -30,8 +30,10 @@
#include <vector>
-#include "base/strings.h"
-#include "cutils/properties.h"
+#include <base/strings.h>
+#include <base/stringprintf.h>
+#include <cutils/properties.h>
+
#include "common.h"
#include "device.h"
#include "minui/minui.h"
@@ -506,18 +508,17 @@ void ScreenRecoveryUI::SetStage(int current, int max) {
pthread_mutex_unlock(&updateMutex);
}
-void ScreenRecoveryUI::Print(const char *fmt, ...) {
- char buf[256];
- va_list ap;
- va_start(ap, fmt);
- vsnprintf(buf, 256, fmt, ap);
- va_end(ap);
+void ScreenRecoveryUI::PrintV(const char* fmt, bool copy_to_stdout, va_list ap) {
+ std::string str;
+ android::base::StringAppendV(&str, fmt, ap);
- fputs(buf, stdout);
+ if (copy_to_stdout) {
+ fputs(str.c_str(), stdout);
+ }
pthread_mutex_lock(&updateMutex);
if (text_rows_ > 0 && text_cols_ > 0) {
- for (const char* ptr = buf; *ptr != '\0'; ++ptr) {
+ for (const char* ptr = str.c_str(); *ptr != '\0'; ++ptr) {
if (*ptr == '\n' || text_col_ >= text_cols_) {
text_[text_row_][text_col_] = '\0';
text_col_ = 0;
@@ -532,6 +533,20 @@ void ScreenRecoveryUI::Print(const char *fmt, ...) {
pthread_mutex_unlock(&updateMutex);
}
+void ScreenRecoveryUI::Print(const char* fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ PrintV(fmt, true, ap);
+ va_end(ap);
+}
+
+void ScreenRecoveryUI::PrintOnScreenOnly(const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ PrintV(fmt, false, ap);
+ va_end(ap);
+}
+
void ScreenRecoveryUI::PutChar(char ch) {
pthread_mutex_lock(&updateMutex);
if (ch != '\n') text_[text_row_][text_col_++] = ch;
diff --git a/screen_ui.h b/screen_ui.h
index ea05bf15f..8e18864d7 100644
--- a/screen_ui.h
+++ b/screen_ui.h
@@ -49,6 +49,7 @@ class ScreenRecoveryUI : public RecoveryUI {
// printing messages
void Print(const char* fmt, ...) __printflike(2, 3);
+ void PrintOnScreenOnly(const char* fmt, ...) __printflike(2, 3);
void ShowFile(const char* filename);
// menu display
@@ -125,6 +126,7 @@ class ScreenRecoveryUI : public RecoveryUI {
void ProgressThreadLoop();
void ShowFile(FILE*);
+ void PrintV(const char*, bool, va_list);
void PutChar(char);
void ClearText();
diff --git a/tests/Android.mk b/tests/Android.mk
index 02a272a24..4ce00b457 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -17,6 +17,7 @@
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
+LOCAL_CLANG := true
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
LOCAL_STATIC_LIBRARIES := libverifier
LOCAL_SRC_FILES := asn1_decoder_test.cpp
diff --git a/ui.cpp b/ui.cpp
index 1a0b079cc..2efb759db 100644
--- a/ui.cpp
+++ b/ui.cpp
@@ -28,6 +28,7 @@
#include <time.h>
#include <unistd.h>
+#include <cutils/properties.h>
#include <cutils/android_reboot.h>
#include "common.h"
@@ -174,7 +175,8 @@ void RecoveryUI::ProcessKey(int key_code, int updown) {
case RecoveryUI::REBOOT:
if (reboot_enabled) {
- android_reboot(ANDROID_RB_RESTART, 0, 0);
+ property_set(ANDROID_RB_PROPERTY, "reboot,");
+ while (true) { pause(); }
}
break;
diff --git a/ui.h b/ui.h
index 4dcaa0f8d..ca72911db 100644
--- a/ui.h
+++ b/ui.h
@@ -62,8 +62,10 @@ class RecoveryUI {
virtual bool WasTextEverVisible() = 0;
// Write a message to the on-screen log (shown if the user has
- // toggled on the text display).
+ // toggled on the text display). Print() will also dump the message
+ // to stdout / log file, while PrintOnScreenOnly() not.
virtual void Print(const char* fmt, ...) __printflike(2, 3) = 0;
+ virtual void PrintOnScreenOnly(const char* fmt, ...) __printflike(2, 3) = 0;
virtual void ShowFile(const char* filename) = 0;
diff --git a/uncrypt/Android.mk b/uncrypt/Android.mk
index c7d4d3746..f31db4243 100644
--- a/uncrypt/Android.mk
+++ b/uncrypt/Android.mk
@@ -16,8 +16,12 @@ LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
+LOCAL_CLANG := true
+
LOCAL_SRC_FILES := uncrypt.cpp
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/..
+
LOCAL_MODULE := uncrypt
LOCAL_STATIC_LIBRARIES := libbase liblog libfs_mgr libcutils
diff --git a/uncrypt/uncrypt.cpp b/uncrypt/uncrypt.cpp
index 46da86d61..aef480035 100644
--- a/uncrypt/uncrypt.cpp
+++ b/uncrypt/uncrypt.cpp
@@ -51,13 +51,19 @@
#include <sys/types.h>
#include <unistd.h>
+#include <memory>
+
#include <base/file.h>
#include <base/strings.h>
+#include <cutils/android_reboot.h>
#include <cutils/properties.h>
#include <fs_mgr.h>
+
#define LOG_TAG "uncrypt"
#include <log/log.h>
+#include "unique_fd.h"
+
#define WINDOW_SIZE 5
static const std::string cache_block_map = "/cache/recovery/block.map";
@@ -181,6 +187,7 @@ static int produce_block_map(const char* path, const char* map_file, const char*
return -1;
}
FILE* mapf = fdopen(mapfd, "w");
+ unique_file mapf_holder(mapf);
// Make sure we can write to the status_file.
if (!android::base::WriteStringToFd("0\n", status_fd)) {
@@ -189,8 +196,7 @@ static int produce_block_map(const char* path, const char* map_file, const char*
}
struct stat sb;
- int ret = stat(path, &sb);
- if (ret != 0) {
+ if (stat(path, &sb) != 0) {
ALOGE("failed to stat %s\n", path);
return -1;
}
@@ -219,15 +225,18 @@ static int produce_block_map(const char* path, const char* map_file, const char*
size_t pos = 0;
int fd = open(path, O_RDONLY);
- if (fd < 0) {
+ unique_fd fd_holder(fd);
+ if (fd == -1) {
ALOGE("failed to open fd for reading: %s\n", strerror(errno));
return -1;
}
int wfd = -1;
+ unique_fd wfd_holder(wfd);
if (encrypted) {
wfd = open(blk_dev, O_WRONLY | O_SYNC);
- if (wfd < 0) {
+ wfd_holder = unique_fd(wfd);
+ if (wfd == -1) {
ALOGE("failed to open fd for writing: %s\n", strerror(errno));
return -1;
}
@@ -245,8 +254,7 @@ 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;
- ret = ioctl(fd, FIBMAP, &block);
- if (ret != 0) {
+ if (ioctl(fd, FIBMAP, &block) != 0) {
ALOGE("failed to find block %d\n", head_block);
return -1;
}
@@ -286,8 +294,7 @@ 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;
- ret = ioctl(fd, FIBMAP, &block);
- if (ret != 0) {
+ if (ioctl(fd, FIBMAP, &block) != 0) {
ALOGE("failed to find block %d\n", head_block);
return -1;
}
@@ -311,14 +318,11 @@ static int produce_block_map(const char* path, const char* map_file, const char*
ALOGE("failed to fsync \"%s\": %s\n", map_file, strerror(errno));
return -1;
}
- fclose(mapf);
- close(fd);
if (encrypted) {
if (fsync(wfd) == -1) {
ALOGE("failed to fsync \"%s\": %s\n", blk_dev, strerror(errno));
return -1;
}
- close(wfd);
}
return 0;
@@ -331,6 +335,8 @@ static void wipe_misc() {
if (!v->mount_point) continue;
if (strcmp(v->mount_point, "/misc") == 0) {
int fd = open(v->blk_device, O_WRONLY | O_SYNC);
+ unique_fd fd_holder(fd);
+
uint8_t zeroes[1088]; // sizeof(bootloader_message) from recovery
memset(zeroes, 0, sizeof(zeroes));
@@ -347,10 +353,8 @@ static void wipe_misc() {
}
if (fsync(fd) == -1) {
ALOGE("failed to fsync \"%s\": %s\n", v->blk_device, strerror(errno));
- close(fd);
return;
}
- close(fd);
}
}
}
@@ -358,7 +362,9 @@ static void wipe_misc() {
static void reboot_to_recovery() {
ALOGI("rebooting to recovery");
property_set("sys.powerctl", "reboot,recovery");
- sleep(10);
+ while (true) {
+ pause();
+ }
ALOGE("reboot didn't succeed?");
}
@@ -433,6 +439,7 @@ int main(int argc, char** argv) {
ALOGE("failed to open pipe \"%s\": %s\n", status_file.c_str(), strerror(errno));
return 1;
}
+ unique_fd status_fd_holder(status_fd);
if (argc == 3) {
// when command-line args are given this binary is being used
@@ -443,7 +450,6 @@ int main(int argc, char** argv) {
std::string package;
if (!find_uncrypt_package(package)) {
android::base::WriteStringToFd("-1\n", status_fd);
- close(status_fd);
return 1;
}
input_path = package.c_str();
@@ -453,12 +459,10 @@ int main(int argc, char** argv) {
int status = uncrypt(input_path, map_file, status_fd);
if (status != 0) {
android::base::WriteStringToFd("-1\n", status_fd);
- close(status_fd);
return 1;
}
android::base::WriteStringToFd("100\n", status_fd);
- close(status_fd);
}
return 0;
diff --git a/unique_fd.h b/unique_fd.h
new file mode 100644
index 000000000..98a7c7b67
--- /dev/null
+++ b/unique_fd.h
@@ -0,0 +1,73 @@
+/*
+ * 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;
+};
+
+// Custom deleter for unique_file to avoid fclose(NULL).
+struct safe_fclose {
+ void operator()(FILE *fp) const {
+ if (fp) {
+ fclose(fp);
+ };
+ }
+};
+
+using unique_file = std::unique_ptr<FILE, safe_fclose>;
+
+#endif // UNIQUE_FD_H
diff --git a/updater/Android.mk b/updater/Android.mk
index ff02a33b0..82fa7e265 100644
--- a/updater/Android.mk
+++ b/updater/Android.mk
@@ -1,11 +1,23 @@
# Copyright 2009 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
LOCAL_PATH := $(call my-dir)
updater_src_files := \
- install.c \
- blockimg.c \
- updater.c
+ install.cpp \
+ blockimg.cpp \
+ updater.cpp
#
# Build a statically-linked binary to include in OTA packages
@@ -17,6 +29,8 @@ include $(CLEAR_VARS)
# needed only for OTA packages.)
LOCAL_MODULE_TAGS := eng
+LOCAL_CLANG := true
+
LOCAL_SRC_FILES := $(updater_src_files)
ifeq ($(TARGET_USERIMAGES_USE_EXT4), true)
@@ -30,9 +44,9 @@ LOCAL_STATIC_LIBRARIES += \
endif
LOCAL_STATIC_LIBRARIES += $(TARGET_RECOVERY_UPDATER_LIBS) $(TARGET_RECOVERY_UPDATER_EXTRA_LIBS)
-LOCAL_STATIC_LIBRARIES += libapplypatch libedify libmtdutils libminzip libz
+LOCAL_STATIC_LIBRARIES += libapplypatch libbase libedify libmtdutils libminzip libz
LOCAL_STATIC_LIBRARIES += libmincrypt libbz
-LOCAL_STATIC_LIBRARIES += libcutils liblog libstdc++ libc
+LOCAL_STATIC_LIBRARIES += libcutils liblog libc
LOCAL_STATIC_LIBRARIES += libselinux
tune2fs_static_libraries := \
libext2_com_err \
diff --git a/updater/blockimg.c b/updater/blockimg.cpp
index b006d10c5..5f5f9bd72 100644
--- a/updater/blockimg.c
+++ b/updater/blockimg.cpp
@@ -19,7 +19,7 @@
#include <dirent.h>
#include <fcntl.h>
#include <inttypes.h>
-#include <libgen.h>
+#include <linux/fs.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
@@ -32,10 +32,18 @@
#include <time.h>
#include <unistd.h>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <base/strings.h>
+
#include "applypatch/applypatch.h"
#include "edify/expr.h"
#include "mincrypt/sha.h"
#include "minzip/Hash.h"
+#include "print_sha1.h"
+#include "unique_fd.h"
#include "updater.h"
#define BLOCKSIZE 4096
@@ -45,70 +53,100 @@
// erase to mean fill the region with zeroes.
#define DEBUG_ERASE 0
-#ifndef BLKDISCARD
-#define BLKDISCARD _IO(0x12,119)
-#endif
-
#define STASH_DIRECTORY_BASE "/cache/recovery"
#define STASH_DIRECTORY_MODE 0700
#define STASH_FILE_MODE 0600
-char* PrintSha1(const uint8_t* digest);
+struct RangeSet {
+ size_t count; // Limit is INT_MAX.
+ size_t size;
+ std::vector<size_t> pos; // Actual limit is INT_MAX.
+};
-typedef struct {
- int count;
- int size;
- int pos[0];
-} RangeSet;
-
-static RangeSet* parse_range(char* text) {
- char* save;
- int num;
- num = strtol(strtok_r(text, ",", &save), NULL, 0);
-
- RangeSet* out = malloc(sizeof(RangeSet) + num * sizeof(int));
- if (out == NULL) {
- fprintf(stderr, "failed to allocate range of %zu bytes\n",
- sizeof(RangeSet) + num * sizeof(int));
+static void parse_range(const char* range_text, RangeSet& rs) {
+
+ if (range_text == nullptr) {
+ fprintf(stderr, "failed to parse range: null range\n");
exit(1);
}
- out->count = num / 2;
- out->size = 0;
- int i;
- for (i = 0; i < num; ++i) {
- out->pos[i] = strtol(strtok_r(NULL, ",", &save), NULL, 0);
- if (i%2) {
- out->size += out->pos[i];
- } else {
- out->size -= out->pos[i];
- }
+
+ std::vector<std::string> pieces = android::base::Split(std::string(range_text), ",");
+ long int val;
+
+ if (pieces.size() < 3) {
+ goto err;
}
- return out;
-}
+ errno = 0;
+ val = strtol(pieces[0].c_str(), nullptr, 0);
-static int range_overlaps(RangeSet* r1, RangeSet* r2) {
- int i, j, r1_0, r1_1, r2_0, r2_1;
+ if (errno != 0 || val < 2 || val > INT_MAX) {
+ goto err;
+ } else if (val % 2) {
+ goto err; // must be even
+ } else if (val != static_cast<long int>(pieces.size() - 1)) {
+ goto err;
+ }
- if (!r1 || !r2) {
- return 0;
+ size_t num;
+ num = static_cast<size_t>(val);
+
+ rs.pos.resize(num);
+ rs.count = num / 2;
+ rs.size = 0;
+
+ for (size_t i = 0; i < num; i += 2) {
+ const char* token = pieces[i+1].c_str();
+ errno = 0;
+ val = strtol(token, nullptr, 0);
+ if (errno != 0 || val < 0 || val > INT_MAX) {
+ goto err;
+ }
+ rs.pos[i] = static_cast<size_t>(val);
+
+ token = pieces[i+2].c_str();
+ errno = 0;
+ val = strtol(token, nullptr, 0);
+ if (errno != 0 || val < 0 || val > INT_MAX) {
+ goto err;
+ }
+ rs.pos[i+1] = static_cast<size_t>(val);
+
+ if (rs.pos[i] >= rs.pos[i+1]) {
+ goto err; // empty or negative range
+ }
+
+ size_t sz = rs.pos[i+1] - rs.pos[i];
+ if (rs.size > SIZE_MAX - sz) {
+ goto err; // overflow
+ }
+
+ rs.size += sz;
}
- for (i = 0; i < r1->count; ++i) {
- r1_0 = r1->pos[i * 2];
- r1_1 = r1->pos[i * 2 + 1];
+ return;
+
+err:
+ fprintf(stderr, "failed to parse range '%s'\n", range_text);
+ exit(1);
+}
+
+static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
+ for (size_t i = 0; i < r1.count; ++i) {
+ size_t r1_0 = r1.pos[i * 2];
+ size_t r1_1 = r1.pos[i * 2 + 1];
- for (j = 0; j < r2->count; ++j) {
- r2_0 = r2->pos[j * 2];
- r2_1 = r2->pos[j * 2 + 1];
+ for (size_t j = 0; j < r2.count; ++j) {
+ size_t r2_0 = r2.pos[j * 2];
+ size_t r2_1 = r2.pos[j * 2 + 1];
if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
- return 1;
+ return true;
}
}
}
- return 0;
+ return false;
}
static int read_all(int fd, uint8_t* data, size_t size) {
@@ -135,11 +173,6 @@ static int write_all(int fd, const uint8_t* data, size_t size) {
written += w;
}
- if (fsync(fd) == -1) {
- fprintf(stderr, "fsync failed: %s\n", strerror(errno));
- return -1;
- }
-
return 0;
}
@@ -159,24 +192,26 @@ static void allocate(size_t size, uint8_t** buffer, size_t* buffer_alloc) {
free(*buffer);
*buffer = (uint8_t*) malloc(size);
- if (*buffer == NULL) {
+ if (*buffer == nullptr) {
fprintf(stderr, "failed to allocate %zu bytes\n", size);
exit(1);
}
*buffer_alloc = size;
}
-typedef struct {
+struct RangeSinkState {
+ RangeSinkState(RangeSet& rs) : tgt(rs) { };
+
int fd;
- RangeSet* tgt;
- int p_block;
+ const RangeSet& tgt;
+ size_t p_block;
size_t p_remain;
-} RangeSinkState;
+};
static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
- RangeSinkState* rss = (RangeSinkState*) token;
+ RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
- if (rss->p_remain <= 0) {
+ if (rss->p_remain == 0) {
fprintf(stderr, "range sink write overrun");
return 0;
}
@@ -202,11 +237,11 @@ static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
if (rss->p_remain == 0) {
// move to the next block
++rss->p_block;
- if (rss->p_block < rss->tgt->count) {
- rss->p_remain = (rss->tgt->pos[rss->p_block * 2 + 1] -
- rss->tgt->pos[rss->p_block * 2]) * BLOCKSIZE;
+ if (rss->p_block < rss->tgt.count) {
+ rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
+ rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
- if (!check_lseek(rss->fd, (off64_t)rss->tgt->pos[rss->p_block*2] * BLOCKSIZE,
+ if (!check_lseek(rss->fd, (off64_t)rss->tgt.pos[rss->p_block*2] * BLOCKSIZE,
SEEK_SET)) {
break;
}
@@ -242,7 +277,7 @@ static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
// condition. When the background thread is done writing, it clears
// rss and signals the condition again.
-typedef struct {
+struct NewThreadInfo {
ZipArchive* za;
const ZipEntry* entry;
@@ -250,16 +285,16 @@ typedef struct {
pthread_mutex_t mu;
pthread_cond_t cv;
-} NewThreadInfo;
+};
static bool receive_new_data(const unsigned char* data, int size, void* cookie) {
- NewThreadInfo* nti = (NewThreadInfo*) cookie;
+ NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
while (size > 0) {
- // Wait for nti->rss to be non-NULL, indicating some of this
+ // Wait for nti->rss to be non-null, indicating some of this
// data is wanted.
pthread_mutex_lock(&nti->mu);
- while (nti->rss == NULL) {
+ while (nti->rss == nullptr) {
pthread_cond_wait(&nti->cv, &nti->mu);
}
pthread_mutex_unlock(&nti->mu);
@@ -270,11 +305,11 @@ static bool receive_new_data(const unsigned char* data, int size, void* cookie)
data += written;
size -= written;
- if (nti->rss->p_block == nti->rss->tgt->count) {
+ if (nti->rss->p_block == nti->rss->tgt.count) {
// we have written all the bytes desired by this rss.
pthread_mutex_lock(&nti->mu);
- nti->rss = NULL;
+ nti->rss = nullptr;
pthread_cond_broadcast(&nti->cv);
pthread_mutex_unlock(&nti->mu);
}
@@ -286,24 +321,22 @@ static bool receive_new_data(const unsigned char* data, int size, void* cookie)
static void* unzip_new_data(void* cookie) {
NewThreadInfo* nti = (NewThreadInfo*) cookie;
mzProcessZipEntryContents(nti->za, nti->entry, receive_new_data, nti);
- return NULL;
+ return nullptr;
}
-static int ReadBlocks(RangeSet* src, uint8_t* buffer, int fd) {
- int i;
+static int ReadBlocks(const RangeSet& src, uint8_t* buffer, int fd) {
size_t p = 0;
- size_t size;
- if (!src || !buffer) {
+ if (!buffer) {
return -1;
}
- for (i = 0; i < src->count; ++i) {
- if (!check_lseek(fd, (off64_t) src->pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
+ for (size_t i = 0; i < src.count; ++i) {
+ if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
return -1;
}
- size = (src->pos[i * 2 + 1] - src->pos[i * 2]) * BLOCKSIZE;
+ size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
if (read_all(fd, buffer + p, size) == -1) {
return -1;
@@ -315,21 +348,18 @@ static int ReadBlocks(RangeSet* src, uint8_t* buffer, int fd) {
return 0;
}
-static int WriteBlocks(RangeSet* tgt, uint8_t* buffer, int fd) {
- int i;
- size_t p = 0;
- size_t size;
-
- if (!tgt || !buffer) {
+static int WriteBlocks(const RangeSet& tgt, uint8_t* buffer, int fd) {
+ if (!buffer) {
return -1;
}
- for (i = 0; i < tgt->count; ++i) {
- if (!check_lseek(fd, (off64_t) tgt->pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
+ size_t p = 0;
+ for (size_t i = 0; i < tgt.count; ++i) {
+ if (!check_lseek(fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
return -1;
}
- size = (tgt->pos[i * 2 + 1] - tgt->pos[i * 2]) * BLOCKSIZE;
+ size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
if (write_all(fd, buffer + p, size) == -1) {
return -1;
@@ -349,540 +379,396 @@ static int WriteBlocks(RangeSet* tgt, uint8_t* buffer, int fd) {
//
// The source range is loaded into the provided buffer, reallocating
// it to make it larger if necessary. The target ranges are returned
-// in *tgt, if tgt is non-NULL.
-
-static int LoadSrcTgtVersion1(char** wordsave, RangeSet** tgt, int* src_blocks,
- uint8_t** buffer, size_t* buffer_alloc, int fd) {
- char* word;
- int rc;
+// in *tgt, if tgt is non-null.
- word = strtok_r(NULL, " ", wordsave);
- RangeSet* src = parse_range(word);
+static int LoadSrcTgtVersion1(char** wordsave, RangeSet* tgt, size_t& src_blocks,
+ uint8_t** buffer, size_t* buffer_alloc, int fd) {
+ char* word = strtok_r(nullptr, " ", wordsave);
+ RangeSet src;
+ parse_range(word, src);
- if (tgt != NULL) {
- word = strtok_r(NULL, " ", wordsave);
- *tgt = parse_range(word);
+ if (tgt != nullptr) {
+ word = strtok_r(nullptr, " ", wordsave);
+ parse_range(word, *tgt);
}
- allocate(src->size * BLOCKSIZE, buffer, buffer_alloc);
- rc = ReadBlocks(src, *buffer, fd);
- *src_blocks = src->size;
+ allocate(src.size * BLOCKSIZE, buffer, buffer_alloc);
+ int rc = ReadBlocks(src, *buffer, fd);
+ src_blocks = src.size;
- free(src);
return rc;
}
-static int VerifyBlocks(const char *expected, const uint8_t *buffer,
- size_t blocks, int printerror) {
- char* hexdigest = NULL;
- int rc = -1;
+static int VerifyBlocks(const std::string& expected, const uint8_t* buffer,
+ const size_t blocks, bool printerror) {
uint8_t digest[SHA_DIGEST_SIZE];
- if (!expected || !buffer) {
- return rc;
+ if (!buffer) {
+ return -1;
}
SHA_hash(buffer, blocks * BLOCKSIZE, digest);
- hexdigest = PrintSha1(digest);
- if (hexdigest != NULL) {
- rc = strcmp(expected, hexdigest);
+ std::string hexdigest = print_sha1(digest);
- if (rc != 0 && printerror) {
+ if (hexdigest != expected) {
+ if (printerror) {
fprintf(stderr, "failed to verify blocks (expected %s, read %s)\n",
- expected, hexdigest);
+ expected.c_str(), hexdigest.c_str());
}
-
- free(hexdigest);
+ return -1;
}
- return rc;
+ return 0;
}
-static char* GetStashFileName(const char* base, const char* id, const char* postfix) {
- char* fn;
- int len;
- int res;
-
- if (base == NULL) {
- return NULL;
- }
-
- if (id == NULL) {
- id = "";
- }
-
- if (postfix == NULL) {
- postfix = "";
- }
-
- len = strlen(STASH_DIRECTORY_BASE) + 1 + strlen(base) + 1 + strlen(id) + strlen(postfix) + 1;
- fn = malloc(len);
-
- if (fn == NULL) {
- fprintf(stderr, "failed to malloc %d bytes for fn\n", len);
- return NULL;
+static std::string GetStashFileName(const std::string& base, const std::string& id,
+ const std::string& postfix) {
+ if (base.empty()) {
+ return "";
}
- res = snprintf(fn, len, STASH_DIRECTORY_BASE "/%s/%s%s", base, id, postfix);
-
- if (res < 0 || res >= len) {
- fprintf(stderr, "failed to format file name (return value %d)\n", res);
- free(fn);
- return NULL;
- }
+ std::string fn(STASH_DIRECTORY_BASE);
+ fn += "/" + base + "/" + id + postfix;
return fn;
}
-typedef void (*StashCallback)(const char*, void*);
+typedef void (*StashCallback)(const std::string&, void*);
// Does a best effort enumeration of stash files. Ignores possible non-file
// items in the stash directory and continues despite of errors. Calls the
// 'callback' function for each file and passes 'data' to the function as a
// parameter.
-static void EnumerateStash(const char* dirname, StashCallback callback, void* data) {
- char* fn;
- DIR* directory;
- int len;
- int res;
- struct dirent* item;
-
- if (dirname == NULL || callback == NULL) {
+static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
+ if (dirname.empty() || callback == nullptr) {
return;
}
- directory = opendir(dirname);
+ std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
- if (directory == NULL) {
+ if (directory == nullptr) {
if (errno != ENOENT) {
- fprintf(stderr, "opendir \"%s\" failed: %s\n", dirname, strerror(errno));
+ fprintf(stderr, "opendir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
}
return;
}
- while ((item = readdir(directory)) != NULL) {
+ struct dirent* item;
+ while ((item = readdir(directory.get())) != nullptr) {
if (item->d_type != DT_REG) {
continue;
}
- len = strlen(dirname) + 1 + strlen(item->d_name) + 1;
- fn = malloc(len);
-
- if (fn == NULL) {
- fprintf(stderr, "failed to malloc %d bytes for fn\n", len);
- continue;
- }
-
- res = snprintf(fn, len, "%s/%s", dirname, item->d_name);
-
- if (res < 0 || res >= len) {
- fprintf(stderr, "failed to format file name (return value %d)\n", res);
- free(fn);
- continue;
- }
-
+ std::string fn = dirname + "/" + std::string(item->d_name);
callback(fn, data);
- free(fn);
- }
-
- if (closedir(directory) == -1) {
- fprintf(stderr, "closedir \"%s\" failed: %s\n", dirname, strerror(errno));
}
}
-static void UpdateFileSize(const char* fn, void* data) {
- int* size = (int*) data;
- struct stat st;
-
- if (!fn || !data) {
+static void UpdateFileSize(const std::string& fn, void* data) {
+ if (fn.empty() || !data) {
return;
}
- if (stat(fn, &st) == -1) {
- fprintf(stderr, "stat \"%s\" failed: %s\n", fn, strerror(errno));
+ struct stat sb;
+ if (stat(fn.c_str(), &sb) == -1) {
+ fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
return;
}
- *size += st.st_size;
+ int* size = reinterpret_cast<int*>(data);
+ *size += sb.st_size;
}
// Deletes the stash directory and all files in it. Assumes that it only
// contains files. There is nothing we can do about unlikely, but possible
// errors, so they are merely logged.
-static void DeleteFile(const char* fn, void* data) {
- if (fn) {
- fprintf(stderr, "deleting %s\n", fn);
+static void DeleteFile(const std::string& fn, void* /* data */) {
+ if (!fn.empty()) {
+ fprintf(stderr, "deleting %s\n", fn.c_str());
- if (unlink(fn) == -1 && errno != ENOENT) {
- fprintf(stderr, "unlink \"%s\" failed: %s\n", fn, strerror(errno));
+ if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
+ fprintf(stderr, "unlink \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
}
}
}
-static void DeletePartial(const char* fn, void* data) {
- if (fn && strstr(fn, ".partial") != NULL) {
+static void DeletePartial(const std::string& fn, void* data) {
+ if (android::base::EndsWith(fn, ".partial")) {
DeleteFile(fn, data);
}
}
-static void DeleteStash(const char* base) {
- char* dirname;
-
- if (base == NULL) {
+static void DeleteStash(const std::string& base) {
+ if (base.empty()) {
return;
}
- dirname = GetStashFileName(base, NULL, NULL);
-
- if (dirname == NULL) {
- return;
- }
+ fprintf(stderr, "deleting stash %s\n", base.c_str());
- fprintf(stderr, "deleting stash %s\n", base);
- EnumerateStash(dirname, DeleteFile, NULL);
+ std::string dirname = GetStashFileName(base, "", "");
+ EnumerateStash(dirname, DeleteFile, nullptr);
- if (rmdir(dirname) == -1) {
+ if (rmdir(dirname.c_str()) == -1) {
if (errno != ENOENT && errno != ENOTDIR) {
- fprintf(stderr, "rmdir \"%s\" failed: %s\n", dirname, strerror(errno));
+ fprintf(stderr, "rmdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
}
}
-
- free(dirname);
}
-static int LoadStash(const char* base, const char* id, int verify, int* blocks, uint8_t** buffer,
- size_t* buffer_alloc, int printnoent) {
- char *fn = NULL;
- int blockcount = 0;
- int fd = -1;
- int rc = -1;
- int res;
- struct stat st;
-
- if (!base || !id || !buffer || !buffer_alloc) {
- goto lsout;
+static int LoadStash(const std::string& base, const std::string& id, bool verify, size_t* blocks,
+ uint8_t** buffer, size_t* buffer_alloc, bool printnoent) {
+ if (base.empty() || !buffer || !buffer_alloc) {
+ return -1;
}
+ size_t blockcount = 0;
+
if (!blocks) {
blocks = &blockcount;
}
- fn = GetStashFileName(base, id, NULL);
-
- if (fn == NULL) {
- goto lsout;
- }
+ std::string fn = GetStashFileName(base, id, "");
- res = stat(fn, &st);
+ struct stat sb;
+ int res = stat(fn.c_str(), &sb);
if (res == -1) {
if (errno != ENOENT || printnoent) {
- fprintf(stderr, "stat \"%s\" failed: %s\n", fn, strerror(errno));
+ fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
}
- goto lsout;
+ return -1;
}
- fprintf(stderr, " loading %s\n", fn);
+ fprintf(stderr, " loading %s\n", fn.c_str());
- if ((st.st_size % BLOCKSIZE) != 0) {
- fprintf(stderr, "%s size %zd not multiple of block size %d", fn, st.st_size, BLOCKSIZE);
- goto lsout;
+ if ((sb.st_size % BLOCKSIZE) != 0) {
+ fprintf(stderr, "%s size %" PRId64 " not multiple of block size %d",
+ fn.c_str(), static_cast<int64_t>(sb.st_size), BLOCKSIZE);
+ return -1;
}
- fd = TEMP_FAILURE_RETRY(open(fn, O_RDONLY));
+ int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY));
+ unique_fd fd_holder(fd);
if (fd == -1) {
- fprintf(stderr, "open \"%s\" failed: %s\n", fn, strerror(errno));
- goto lsout;
- }
-
- allocate(st.st_size, buffer, buffer_alloc);
-
- if (read_all(fd, *buffer, st.st_size) == -1) {
- goto lsout;
+ fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
+ return -1;
}
- *blocks = st.st_size / BLOCKSIZE;
+ allocate(sb.st_size, buffer, buffer_alloc);
- if (verify && VerifyBlocks(id, *buffer, *blocks, 1) != 0) {
- fprintf(stderr, "unexpected contents in %s\n", fn);
- DeleteFile(fn, NULL);
- goto lsout;
+ if (read_all(fd, *buffer, sb.st_size) == -1) {
+ return -1;
}
- rc = 0;
-
-lsout:
- if (fd != -1) {
- close(fd);
- }
+ *blocks = sb.st_size / BLOCKSIZE;
- if (fn) {
- free(fn);
+ if (verify && VerifyBlocks(id, *buffer, *blocks, true) != 0) {
+ fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
+ DeleteFile(fn, nullptr);
+ return -1;
}
- return rc;
+ return 0;
}
-static int WriteStash(const char* base, const char* id, int blocks, uint8_t* buffer,
- int checkspace, int *exists) {
- char *fn = NULL;
- char *cn = NULL;
- int fd = -1;
- int rc = -1;
- int dfd = -1;
- int res;
- struct stat st;
-
- if (base == NULL || buffer == NULL) {
- goto wsout;
+static int WriteStash(const std::string& base, const std::string& id, int blocks, uint8_t* buffer,
+ bool checkspace, bool *exists) {
+ if (base.empty() || buffer == nullptr) {
+ return -1;
}
if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
fprintf(stderr, "not enough space to write stash\n");
- goto wsout;
+ return -1;
}
- fn = GetStashFileName(base, id, ".partial");
- cn = GetStashFileName(base, id, NULL);
-
- if (fn == NULL || cn == NULL) {
- goto wsout;
- }
+ std::string fn = GetStashFileName(base, id, ".partial");
+ std::string cn = GetStashFileName(base, id, "");
if (exists) {
- res = stat(cn, &st);
+ struct stat sb;
+ int res = stat(cn.c_str(), &sb);
if (res == 0) {
// The file already exists and since the name is the hash of the contents,
// it's safe to assume the contents are identical (accidental hash collisions
// are unlikely)
- fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn);
- *exists = 1;
- rc = 0;
- goto wsout;
+ fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
+ *exists = true;
+ return 0;
}
- *exists = 0;
+ *exists = false;
}
- fprintf(stderr, " writing %d blocks to %s\n", blocks, cn);
+ fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
- fd = TEMP_FAILURE_RETRY(open(fn, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, STASH_FILE_MODE));
+ int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE));
+ unique_fd fd_holder(fd);
if (fd == -1) {
- fprintf(stderr, "failed to create \"%s\": %s\n", fn, strerror(errno));
- goto wsout;
+ fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
+ return -1;
}
if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
- goto wsout;
+ return -1;
}
if (fsync(fd) == -1) {
- fprintf(stderr, "fsync \"%s\" failed: %s\n", fn, strerror(errno));
- goto wsout;
+ fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
+ return -1;
}
- if (rename(fn, cn) == -1) {
- fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn, cn, strerror(errno));
- goto wsout;
+ if (rename(fn.c_str(), cn.c_str()) == -1) {
+ fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
+ strerror(errno));
+ return -1;
}
- const char* dname;
- dname = dirname(cn);
- dfd = TEMP_FAILURE_RETRY(open(dname, O_RDONLY | O_DIRECTORY));
+ std::string dname = GetStashFileName(base, "", "");
+ int dfd = TEMP_FAILURE_RETRY(open(dname.c_str(), O_RDONLY | O_DIRECTORY));
+ unique_fd dfd_holder(dfd);
if (dfd == -1) {
- fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname, strerror(errno));
- goto wsout;
+ fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
+ return -1;
}
if (fsync(dfd) == -1) {
- fprintf(stderr, "fsync \"%s\" failed: %s\n", dname, strerror(errno));
- goto wsout;
- }
-
- rc = 0;
-
-wsout:
- if (fd != -1) {
- close(fd);
- }
-
- if (dfd != -1) {
- close(dfd);
- }
-
- if (fn) {
- free(fn);
- }
-
- if (cn) {
- free(cn);
+ fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
+ return -1;
}
- return rc;
+ return 0;
}
// Creates a directory for storing stash files and checks if the /cache partition
// hash enough space for the expected amount of blocks we need to store. Returns
// >0 if we created the directory, zero if it existed already, and <0 of failure.
-static int CreateStash(State* state, int maxblocks, const char* blockdev, char** base) {
- char* dirname = NULL;
- const uint8_t* digest;
- int rc = -1;
- int res;
- int size = 0;
- SHA_CTX ctx;
- struct stat st;
-
- if (blockdev == NULL || base == NULL) {
- goto csout;
+static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
+ if (blockdev == nullptr) {
+ return -1;
}
// Stash directory should be different for each partition to avoid conflicts
// when updating multiple partitions at the same time, so we use the hash of
// the block device name as the base directory
+ SHA_CTX ctx;
SHA_init(&ctx);
SHA_update(&ctx, blockdev, strlen(blockdev));
- digest = SHA_final(&ctx);
- *base = PrintSha1(digest);
-
- if (*base == NULL) {
- goto csout;
- }
-
- dirname = GetStashFileName(*base, NULL, NULL);
+ const uint8_t* digest = SHA_final(&ctx);
+ base = print_sha1(digest);
- if (dirname == NULL) {
- goto csout;
- }
-
- res = stat(dirname, &st);
+ std::string dirname = GetStashFileName(base, "", "");
+ struct stat sb;
+ int res = stat(dirname.c_str(), &sb);
if (res == -1 && errno != ENOENT) {
- ErrorAbort(state, "stat \"%s\" failed: %s\n", dirname, strerror(errno));
- goto csout;
+ ErrorAbort(state, "stat \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
+ return -1;
} else if (res != 0) {
- fprintf(stderr, "creating stash %s\n", dirname);
- res = mkdir(dirname, STASH_DIRECTORY_MODE);
+ fprintf(stderr, "creating stash %s\n", dirname.c_str());
+ res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
if (res != 0) {
- ErrorAbort(state, "mkdir \"%s\" failed: %s\n", dirname, strerror(errno));
- goto csout;
+ ErrorAbort(state, "mkdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
+ return -1;
}
if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
ErrorAbort(state, "not enough space for stash\n");
- goto csout;
+ return -1;
}
- rc = 1; // Created directory
- goto csout;
+ return 1; // Created directory
}
- fprintf(stderr, "using existing stash %s\n", dirname);
+ fprintf(stderr, "using existing stash %s\n", dirname.c_str());
// If the directory already exists, calculate the space already allocated to
// stash files and check if there's enough for all required blocks. Delete any
// partially completed stash files first.
- EnumerateStash(dirname, DeletePartial, NULL);
+ EnumerateStash(dirname, DeletePartial, nullptr);
+ int size = 0;
EnumerateStash(dirname, UpdateFileSize, &size);
- size = (maxblocks * BLOCKSIZE) - size;
+ size = maxblocks * BLOCKSIZE - size;
if (size > 0 && CacheSizeCheck(size) != 0) {
ErrorAbort(state, "not enough space for stash (%d more needed)\n", size);
- goto csout;
- }
-
- rc = 0; // Using existing directory
-
-csout:
- if (dirname) {
- free(dirname);
+ return -1;
}
- return rc;
+ return 0; // Using existing directory
}
-static int SaveStash(const char* base, char** wordsave, uint8_t** buffer, size_t* buffer_alloc,
- int fd, int usehash, int* isunresumable) {
- char *id = NULL;
- int res = -1;
- int blocks = 0;
-
- if (!wordsave || !buffer || !buffer_alloc || !isunresumable) {
+static int SaveStash(const std::string& base, char** wordsave, uint8_t** buffer,
+ size_t* buffer_alloc, int fd, bool usehash) {
+ if (!wordsave || !buffer || !buffer_alloc) {
return -1;
}
- id = strtok_r(NULL, " ", wordsave);
-
- if (id == NULL) {
+ char *id_tok = strtok_r(nullptr, " ", wordsave);
+ if (id_tok == nullptr) {
fprintf(stderr, "missing id field in stash command\n");
return -1;
}
+ std::string id(id_tok);
- if (usehash && LoadStash(base, id, 1, &blocks, buffer, buffer_alloc, 0) == 0) {
+ size_t blocks = 0;
+ if (usehash && LoadStash(base, id, true, &blocks, buffer, buffer_alloc, false) == 0) {
// Stash file already exists and has expected contents. Do not
// read from source again, as the source may have been already
// overwritten during a previous attempt.
return 0;
}
- if (LoadSrcTgtVersion1(wordsave, NULL, &blocks, buffer, buffer_alloc, fd) == -1) {
+ if (LoadSrcTgtVersion1(wordsave, nullptr, blocks, buffer, buffer_alloc, fd) == -1) {
return -1;
}
- if (usehash && VerifyBlocks(id, *buffer, blocks, 1) != 0) {
+ if (usehash && VerifyBlocks(id, *buffer, blocks, true) != 0) {
// Source blocks have unexpected contents. If we actually need this
// data later, this is an unrecoverable error. However, the command
// that uses the data may have already completed previously, so the
// possible failure will occur during source block verification.
- fprintf(stderr, "failed to load source blocks for stash %s\n", id);
+ fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
return 0;
}
- fprintf(stderr, "stashing %d blocks to %s\n", blocks, id);
- return WriteStash(base, id, blocks, *buffer, 0, NULL);
+ fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
+ return WriteStash(base, id, blocks, *buffer, false, nullptr);
}
-static int FreeStash(const char* base, const char* id) {
- char *fn = NULL;
-
- if (base == NULL || id == NULL) {
+static int FreeStash(const std::string& base, const char* id) {
+ if (base.empty() || id == nullptr) {
return -1;
}
- fn = GetStashFileName(base, id, NULL);
-
- if (fn == NULL) {
- return -1;
- }
+ std::string fn = GetStashFileName(base, std::string(id), "");
- DeleteFile(fn, NULL);
- free(fn);
+ DeleteFile(fn, nullptr);
return 0;
}
-static void MoveRange(uint8_t* dest, RangeSet* locs, const uint8_t* source) {
+static void MoveRange(uint8_t* dest, const RangeSet& locs, const uint8_t* source) {
// source contains packed data, which we want to move to the
// locations given in *locs in the dest buffer. source and dest
// may be the same buffer.
- int start = locs->size;
- int i;
- for (i = locs->count-1; i >= 0; --i) {
- int blocks = locs->pos[i*2+1] - locs->pos[i*2];
+ size_t start = locs.size;
+ for (int i = locs.count-1; i >= 0; --i) {
+ size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
start -= blocks;
- memmove(dest + (locs->pos[i*2] * BLOCKSIZE), source + (start * BLOCKSIZE),
+ memmove(dest + (locs.pos[i*2] * BLOCKSIZE), source + (start * BLOCKSIZE),
blocks * BLOCKSIZE);
}
}
@@ -905,64 +791,59 @@ static void MoveRange(uint8_t* dest, RangeSet* locs, const uint8_t* source) {
// reallocated if needed to accommodate the source data. *tgt is the
// target RangeSet. Any stashes required are loaded using LoadStash.
-static int LoadSrcTgtVersion2(char** wordsave, RangeSet** tgt, int* src_blocks,
- uint8_t** buffer, size_t* buffer_alloc, int fd,
- const char* stashbase, int* overlap) {
+static int LoadSrcTgtVersion2(char** wordsave, RangeSet* tgt, size_t& src_blocks, uint8_t** buffer,
+ size_t* buffer_alloc, int fd, const std::string& stashbase, bool* overlap) {
char* word;
char* colonsave;
char* colon;
- int id;
- int res;
- RangeSet* locs;
+ RangeSet locs;
size_t stashalloc = 0;
- uint8_t* stash = NULL;
+ uint8_t* stash = nullptr;
- if (tgt != NULL) {
- word = strtok_r(NULL, " ", wordsave);
- *tgt = parse_range(word);
+ if (tgt != nullptr) {
+ word = strtok_r(nullptr, " ", wordsave);
+ parse_range(word, *tgt);
}
- word = strtok_r(NULL, " ", wordsave);
- *src_blocks = strtol(word, NULL, 0);
+ word = strtok_r(nullptr, " ", wordsave);
+ src_blocks = strtol(word, nullptr, 0);
- allocate(*src_blocks * BLOCKSIZE, buffer, buffer_alloc);
+ allocate(src_blocks * BLOCKSIZE, buffer, buffer_alloc);
- word = strtok_r(NULL, " ", wordsave);
+ word = strtok_r(nullptr, " ", wordsave);
if (word[0] == '-' && word[1] == '\0') {
// no source ranges, only stashes
} else {
- RangeSet* src = parse_range(word);
- res = ReadBlocks(src, *buffer, fd);
+ RangeSet src;
+ parse_range(word, src);
+ int res = ReadBlocks(src, *buffer, fd);
if (overlap && tgt) {
*overlap = range_overlaps(src, *tgt);
}
- free(src);
-
if (res == -1) {
return -1;
}
- word = strtok_r(NULL, " ", wordsave);
- if (word == NULL) {
+ word = strtok_r(nullptr, " ", wordsave);
+ if (word == nullptr) {
// no stashes, only source range
return 0;
}
- locs = parse_range(word);
+ parse_range(word, locs);
MoveRange(*buffer, locs, *buffer);
- free(locs);
}
- while ((word = strtok_r(NULL, " ", wordsave)) != NULL) {
+ while ((word = strtok_r(nullptr, " ", wordsave)) != nullptr) {
// Each word is a an index into the stash table, a colon, and
// then a rangeset describing where in the source block that
// stashed data should go.
- colonsave = NULL;
+ colonsave = nullptr;
colon = strtok_r(word, ":", &colonsave);
- res = LoadStash(stashbase, colon, 0, NULL, &stash, &stashalloc, 1);
+ int res = LoadStash(stashbase, std::string(colon), false, nullptr, &stash, &stashalloc, true);
if (res == -1) {
// These source blocks will fail verification if used later, but we
@@ -971,11 +852,10 @@ static int LoadSrcTgtVersion2(char** wordsave, RangeSet** tgt, int* src_blocks,
continue;
}
- colon = strtok_r(NULL, ":", &colonsave);
- locs = parse_range(colon);
+ colon = strtok_r(nullptr, ":", &colonsave);
+ parse_range(colon, locs);
MoveRange(*buffer, locs, stash);
- free(locs);
}
if (stash) {
@@ -986,24 +866,24 @@ static int LoadSrcTgtVersion2(char** wordsave, RangeSet** tgt, int* src_blocks,
}
// Parameters for transfer list command functions
-typedef struct {
+struct CommandParameters {
char* cmdname;
char* cpos;
char* freestash;
- char* stashbase;
- int canwrite;
+ std::string stashbase;
+ bool canwrite;
int createdstash;
int fd;
- int foundwrites;
- int isunresumable;
+ bool foundwrites;
+ bool isunresumable;
int version;
- int written;
+ size_t written;
NewThreadInfo nti;
pthread_t thread;
size_t bufsize;
uint8_t* buffer;
uint8_t* patch_start;
-} CommandParameters;
+};
// Do a source/target load for move/bsdiff/imgdiff in version 3.
//
@@ -1022,468 +902,367 @@ typedef struct {
// If the return value is 0, source blocks have expected content and the command
// can be performed.
-static int LoadSrcTgtVersion3(CommandParameters* params, RangeSet** tgt, int* src_blocks,
- int onehash, int* overlap) {
- char* srchash = NULL;
- char* tgthash = NULL;
- int stash_exists = 0;
- int overlap_blocks = 0;
- int rc = -1;
- uint8_t* tgtbuffer = NULL;
+static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet* tgt, size_t& src_blocks,
+ bool onehash, bool& overlap) {
- if (!params|| !tgt || !src_blocks || !overlap) {
- goto v3out;
+ if (!tgt) {
+ return -1;
}
- srchash = strtok_r(NULL, " ", &params->cpos);
-
- if (srchash == NULL) {
+ char* srchash = strtok_r(nullptr, " ", &params.cpos);
+ if (srchash == nullptr) {
fprintf(stderr, "missing source hash\n");
- goto v3out;
+ return -1;
}
+ char* tgthash = nullptr;
if (onehash) {
tgthash = srchash;
} else {
- tgthash = strtok_r(NULL, " ", &params->cpos);
+ tgthash = strtok_r(nullptr, " ", &params.cpos);
- if (tgthash == NULL) {
+ if (tgthash == nullptr) {
fprintf(stderr, "missing target hash\n");
- goto v3out;
+ return -1;
}
}
- if (LoadSrcTgtVersion2(&params->cpos, tgt, src_blocks, &params->buffer, &params->bufsize,
- params->fd, params->stashbase, overlap) == -1) {
- goto v3out;
+ if (LoadSrcTgtVersion2(&params.cpos, tgt, src_blocks, &params.buffer, &params.bufsize,
+ params.fd, params.stashbase, &overlap) == -1) {
+ return -1;
}
- tgtbuffer = (uint8_t*) malloc((*tgt)->size * BLOCKSIZE);
-
- if (tgtbuffer == NULL) {
- fprintf(stderr, "failed to allocate %d bytes\n", (*tgt)->size * BLOCKSIZE);
- goto v3out;
- }
+ std::vector<uint8_t> tgtbuffer(tgt->size * BLOCKSIZE);
- if (ReadBlocks(*tgt, tgtbuffer, params->fd) == -1) {
- goto v3out;
+ if (ReadBlocks(*tgt, tgtbuffer.data(), params.fd) == -1) {
+ return -1;
}
- if (VerifyBlocks(tgthash, tgtbuffer, (*tgt)->size, 0) == 0) {
+ if (VerifyBlocks(tgthash, tgtbuffer.data(), tgt->size, false) == 0) {
// Target blocks already have expected content, command should be skipped
- rc = 1;
- goto v3out;
+ fprintf(stderr, "verified, to return 1");
+ return 1;
}
- if (VerifyBlocks(srchash, params->buffer, *src_blocks, 1) == 0) {
+ if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
// If source and target blocks overlap, stash the source blocks so we can
// resume from possible write errors
- if (*overlap) {
- fprintf(stderr, "stashing %d overlapping blocks to %s\n", *src_blocks,
- srchash);
+ if (overlap) {
+ fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks, srchash);
- if (WriteStash(params->stashbase, srchash, *src_blocks, params->buffer, 1,
- &stash_exists) != 0) {
+ bool stash_exists = false;
+ if (WriteStash(params.stashbase, std::string(srchash), src_blocks, params.buffer, true,
+ &stash_exists) != 0) {
fprintf(stderr, "failed to stash overlapping source blocks\n");
- goto v3out;
+ return -1;
}
// Can be deleted when the write has completed
if (!stash_exists) {
- params->freestash = srchash;
+ params.freestash = srchash;
}
}
// Source blocks have expected content, command can proceed
- rc = 0;
- goto v3out;
+ return 0;
}
- if (*overlap && LoadStash(params->stashbase, srchash, 1, NULL, &params->buffer,
- &params->bufsize, 1) == 0) {
+ if (overlap && LoadStash(params.stashbase, std::string(srchash), true, nullptr, &params.buffer,
+ &params.bufsize, true) == 0) {
// Overlapping source blocks were previously stashed, command can proceed.
// We are recovering from an interrupted command, so we don't know if the
// stash can safely be deleted after this command.
- rc = 0;
- goto v3out;
+ return 0;
}
// Valid source data not available, update cannot be resumed
fprintf(stderr, "partition has unexpected contents\n");
- params->isunresumable = 1;
-
-v3out:
- if (tgtbuffer) {
- free(tgtbuffer);
- }
+ params.isunresumable = true;
- return rc;
+ return -1;
}
-static int PerformCommandMove(CommandParameters* params) {
- int blocks = 0;
- int overlap = 0;
- int rc = -1;
+static int PerformCommandMove(CommandParameters& params) {
+ size_t blocks = 0;
+ bool overlap = false;
int status = 0;
- RangeSet* tgt = NULL;
-
- if (!params) {
- goto pcmout;
- }
+ RangeSet tgt;
- if (params->version == 1) {
- status = LoadSrcTgtVersion1(&params->cpos, &tgt, &blocks, &params->buffer,
- &params->bufsize, params->fd);
- } else if (params->version == 2) {
- status = LoadSrcTgtVersion2(&params->cpos, &tgt, &blocks, &params->buffer,
- &params->bufsize, params->fd, params->stashbase, NULL);
- } else if (params->version >= 3) {
- status = LoadSrcTgtVersion3(params, &tgt, &blocks, 1, &overlap);
+ if (params.version == 1) {
+ status = LoadSrcTgtVersion1(&params.cpos, &tgt, blocks, &params.buffer,
+ &params.bufsize, params.fd);
+ } else if (params.version == 2) {
+ status = LoadSrcTgtVersion2(&params.cpos, &tgt, blocks, &params.buffer,
+ &params.bufsize, params.fd, params.stashbase, nullptr);
+ } else if (params.version >= 3) {
+ status = LoadSrcTgtVersion3(params, &tgt, blocks, true, overlap);
}
if (status == -1) {
fprintf(stderr, "failed to read blocks for move\n");
- goto pcmout;
+ return -1;
}
if (status == 0) {
- params->foundwrites = 1;
- } else if (params->foundwrites) {
- fprintf(stderr, "warning: commands executed out of order [%s]\n", params->cmdname);
+ params.foundwrites = true;
+ } else if (params.foundwrites) {
+ fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
}
- if (params->canwrite) {
+ if (params.canwrite) {
if (status == 0) {
- fprintf(stderr, " moving %d blocks\n", blocks);
+ fprintf(stderr, " moving %zu blocks\n", blocks);
- if (WriteBlocks(tgt, params->buffer, params->fd) == -1) {
- goto pcmout;
+ if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
+ return -1;
}
} else {
- fprintf(stderr, "skipping %d already moved blocks\n", blocks);
+ fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
}
}
- if (params->freestash) {
- FreeStash(params->stashbase, params->freestash);
- params->freestash = NULL;
+ if (params.freestash) {
+ FreeStash(params.stashbase, params.freestash);
+ params.freestash = nullptr;
}
- params->written += tgt->size;
- rc = 0;
-
-pcmout:
- if (tgt) {
- free(tgt);
- }
+ params.written += tgt.size;
- return rc;
+ return 0;
}
-static int PerformCommandStash(CommandParameters* params) {
- if (!params) {
- return -1;
- }
-
- return SaveStash(params->stashbase, &params->cpos, &params->buffer, &params->bufsize,
- params->fd, (params->version >= 3), &params->isunresumable);
+static int PerformCommandStash(CommandParameters& params) {
+ return SaveStash(params.stashbase, &params.cpos, &params.buffer, &params.bufsize,
+ params.fd, (params.version >= 3));
}
-static int PerformCommandFree(CommandParameters* params) {
- if (!params) {
- return -1;
- }
-
- if (params->createdstash || params->canwrite) {
- return FreeStash(params->stashbase, params->cpos);
+static int PerformCommandFree(CommandParameters& params) {
+ if (params.createdstash || params.canwrite) {
+ return FreeStash(params.stashbase, params.cpos);
}
return 0;
}
-static int PerformCommandZero(CommandParameters* params) {
- char* range = NULL;
- int i;
- int j;
- int rc = -1;
- RangeSet* tgt = NULL;
-
- if (!params) {
- goto pczout;
- }
-
- range = strtok_r(NULL, " ", &params->cpos);
+static int PerformCommandZero(CommandParameters& params) {
+ char* range = strtok_r(nullptr, " ", &params.cpos);
- if (range == NULL) {
+ if (range == nullptr) {
fprintf(stderr, "missing target blocks for zero\n");
- goto pczout;
+ return -1;
}
- tgt = parse_range(range);
+ RangeSet tgt;
+ parse_range(range, tgt);
- fprintf(stderr, " zeroing %d blocks\n", tgt->size);
+ fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
- allocate(BLOCKSIZE, &params->buffer, &params->bufsize);
- memset(params->buffer, 0, BLOCKSIZE);
+ allocate(BLOCKSIZE, &params.buffer, &params.bufsize);
+ memset(params.buffer, 0, BLOCKSIZE);
- if (params->canwrite) {
- for (i = 0; i < tgt->count; ++i) {
- if (!check_lseek(params->fd, (off64_t) tgt->pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
- goto pczout;
+ if (params.canwrite) {
+ for (size_t i = 0; i < tgt.count; ++i) {
+ if (!check_lseek(params.fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
+ return -1;
}
- for (j = tgt->pos[i * 2]; j < tgt->pos[i * 2 + 1]; ++j) {
- if (write_all(params->fd, params->buffer, BLOCKSIZE) == -1) {
- goto pczout;
+ for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
+ if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
+ return -1;
}
}
}
}
- if (params->cmdname[0] == 'z') {
+ if (params.cmdname[0] == 'z') {
// Update only for the zero command, as the erase command will call
// this if DEBUG_ERASE is defined.
- params->written += tgt->size;
- }
-
- rc = 0;
-
-pczout:
- if (tgt) {
- free(tgt);
+ params.written += tgt.size;
}
- return rc;
+ return 0;
}
-static int PerformCommandNew(CommandParameters* params) {
- char* range = NULL;
- int rc = -1;
- RangeSet* tgt = NULL;
- RangeSinkState rss;
-
- if (!params) {
- goto pcnout;
- }
-
- range = strtok_r(NULL, " ", &params->cpos);
+static int PerformCommandNew(CommandParameters& params) {
+ char* range = strtok_r(nullptr, " ", &params.cpos);
- if (range == NULL) {
- goto pcnout;
+ if (range == nullptr) {
+ return -1;
}
- tgt = parse_range(range);
+ RangeSet tgt;
+ parse_range(range, tgt);
- if (params->canwrite) {
- fprintf(stderr, " writing %d blocks of new data\n", tgt->size);
+ if (params.canwrite) {
+ fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
- rss.fd = params->fd;
- rss.tgt = tgt;
+ RangeSinkState rss(tgt);
+ rss.fd = params.fd;
rss.p_block = 0;
- rss.p_remain = (tgt->pos[1] - tgt->pos[0]) * BLOCKSIZE;
+ rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
- if (!check_lseek(params->fd, (off64_t) tgt->pos[0] * BLOCKSIZE, SEEK_SET)) {
- goto pcnout;
+ if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
+ return -1;
}
- pthread_mutex_lock(&params->nti.mu);
- params->nti.rss = &rss;
- pthread_cond_broadcast(&params->nti.cv);
+ pthread_mutex_lock(&params.nti.mu);
+ params.nti.rss = &rss;
+ pthread_cond_broadcast(&params.nti.cv);
- while (params->nti.rss) {
- pthread_cond_wait(&params->nti.cv, &params->nti.mu);
+ while (params.nti.rss) {
+ pthread_cond_wait(&params.nti.cv, &params.nti.mu);
}
- pthread_mutex_unlock(&params->nti.mu);
+ pthread_mutex_unlock(&params.nti.mu);
}
- params->written += tgt->size;
- rc = 0;
-
-pcnout:
- if (tgt) {
- free(tgt);
- }
+ params.written += tgt.size;
- return rc;
+ return 0;
}
-static int PerformCommandDiff(CommandParameters* params) {
- char* logparams = NULL;
- char* value = NULL;
- int blocks = 0;
- int overlap = 0;
- int rc = -1;
- int status = 0;
- RangeSet* tgt = NULL;
- RangeSinkState rss;
- size_t len = 0;
- size_t offset = 0;
- Value patch_value;
-
- if (!params) {
- goto pcdout;
- }
+static int PerformCommandDiff(CommandParameters& params) {
+ char* value = nullptr;
+ bool overlap = false;
+ RangeSet tgt;
- logparams = strdup(params->cpos);
- value = strtok_r(NULL, " ", &params->cpos);
+ const std::string logparams(params.cpos);
+ value = strtok_r(nullptr, " ", &params.cpos);
- if (value == NULL) {
- fprintf(stderr, "missing patch offset for %s\n", params->cmdname);
- goto pcdout;
+ if (value == nullptr) {
+ fprintf(stderr, "missing patch offset for %s\n", params.cmdname);
+ return -1;
}
- offset = strtoul(value, NULL, 0);
+ size_t offset = strtoul(value, nullptr, 0);
- value = strtok_r(NULL, " ", &params->cpos);
+ value = strtok_r(nullptr, " ", &params.cpos);
- if (value == NULL) {
- fprintf(stderr, "missing patch length for %s\n", params->cmdname);
- goto pcdout;
+ if (value == nullptr) {
+ fprintf(stderr, "missing patch length for %s\n", params.cmdname);
+ return -1;
}
- len = strtoul(value, NULL, 0);
+ size_t len = strtoul(value, nullptr, 0);
- if (params->version == 1) {
- status = LoadSrcTgtVersion1(&params->cpos, &tgt, &blocks, &params->buffer,
- &params->bufsize, params->fd);
- } else if (params->version == 2) {
- status = LoadSrcTgtVersion2(&params->cpos, &tgt, &blocks, &params->buffer,
- &params->bufsize, params->fd, params->stashbase, NULL);
- } else if (params->version >= 3) {
- status = LoadSrcTgtVersion3(params, &tgt, &blocks, 0, &overlap);
+ size_t blocks = 0;
+ int status = 0;
+ if (params.version == 1) {
+ status = LoadSrcTgtVersion1(&params.cpos, &tgt, blocks, &params.buffer,
+ &params.bufsize, params.fd);
+ } else if (params.version == 2) {
+ status = LoadSrcTgtVersion2(&params.cpos, &tgt, blocks, &params.buffer,
+ &params.bufsize, params.fd, params.stashbase, nullptr);
+ } else if (params.version >= 3) {
+ status = LoadSrcTgtVersion3(params, &tgt, blocks, false, overlap);
}
if (status == -1) {
fprintf(stderr, "failed to read blocks for diff\n");
- goto pcdout;
+ return -1;
}
if (status == 0) {
- params->foundwrites = 1;
- } else if (params->foundwrites) {
- fprintf(stderr, "warning: commands executed out of order [%s]\n", params->cmdname);
+ params.foundwrites = true;
+ } else if (params.foundwrites) {
+ fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
}
- if (params->canwrite) {
+ if (params.canwrite) {
if (status == 0) {
- fprintf(stderr, "patching %d blocks to %d\n", blocks, tgt->size);
+ fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
+ Value patch_value;
patch_value.type = VAL_BLOB;
patch_value.size = len;
- patch_value.data = (char*) (params->patch_start + offset);
+ patch_value.data = (char*) (params.patch_start + offset);
- rss.fd = params->fd;
- rss.tgt = tgt;
+ RangeSinkState rss(tgt);
+ rss.fd = params.fd;
rss.p_block = 0;
- rss.p_remain = (tgt->pos[1] - tgt->pos[0]) * BLOCKSIZE;
+ rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
- if (!check_lseek(params->fd, (off64_t) tgt->pos[0] * BLOCKSIZE, SEEK_SET)) {
- goto pcdout;
+ if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
+ return -1;
}
- if (params->cmdname[0] == 'i') { // imgdiff
- ApplyImagePatch(params->buffer, blocks * BLOCKSIZE, &patch_value,
- &RangeSinkWrite, &rss, NULL, NULL);
+ if (params.cmdname[0] == 'i') { // imgdiff
+ ApplyImagePatch(params.buffer, blocks * BLOCKSIZE, &patch_value,
+ &RangeSinkWrite, &rss, nullptr, nullptr);
} else {
- ApplyBSDiffPatch(params->buffer, blocks * BLOCKSIZE, &patch_value,
- 0, &RangeSinkWrite, &rss, NULL);
+ ApplyBSDiffPatch(params.buffer, blocks * BLOCKSIZE, &patch_value,
+ 0, &RangeSinkWrite, &rss, nullptr);
}
// We expect the output of the patcher to fill the tgt ranges exactly.
- if (rss.p_block != tgt->count || rss.p_remain != 0) {
+ if (rss.p_block != tgt.count || rss.p_remain != 0) {
fprintf(stderr, "range sink underrun?\n");
}
} else {
- fprintf(stderr, "skipping %d blocks already patched to %d [%s]\n",
- blocks, tgt->size, logparams);
+ fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
+ blocks, tgt.size, logparams.c_str());
}
}
- if (params->freestash) {
- FreeStash(params->stashbase, params->freestash);
- params->freestash = NULL;
- }
-
- params->written += tgt->size;
- rc = 0;
-
-pcdout:
- if (logparams) {
- free(logparams);
+ if (params.freestash) {
+ FreeStash(params.stashbase, params.freestash);
+ params.freestash = nullptr;
}
- if (tgt) {
- free(tgt);
- }
+ params.written += tgt.size;
- return rc;
+ return 0;
}
-static int PerformCommandErase(CommandParameters* params) {
- char* range = NULL;
- int i;
- int rc = -1;
- RangeSet* tgt = NULL;
- struct stat st;
- uint64_t blocks[2];
-
+static int PerformCommandErase(CommandParameters& params) {
if (DEBUG_ERASE) {
return PerformCommandZero(params);
}
- if (!params) {
- goto pceout;
- }
-
- if (fstat(params->fd, &st) == -1) {
+ struct stat sb;
+ if (fstat(params.fd, &sb) == -1) {
fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
- goto pceout;
+ return -1;
}
- if (!S_ISBLK(st.st_mode)) {
+ if (!S_ISBLK(sb.st_mode)) {
fprintf(stderr, "not a block device; skipping erase\n");
- goto pceout;
+ return -1;
}
- range = strtok_r(NULL, " ", &params->cpos);
+ char* range = strtok_r(nullptr, " ", &params.cpos);
- if (range == NULL) {
- fprintf(stderr, "missing target blocks for zero\n");
- goto pceout;
+ if (range == nullptr) {
+ fprintf(stderr, "missing target blocks for erase\n");
+ return -1;
}
- tgt = parse_range(range);
+ RangeSet tgt;
+ parse_range(range, tgt);
- if (params->canwrite) {
- fprintf(stderr, " erasing %d blocks\n", tgt->size);
+ if (params.canwrite) {
+ fprintf(stderr, " erasing %zu blocks\n", tgt.size);
- for (i = 0; i < tgt->count; ++i) {
+ for (size_t i = 0; i < tgt.count; ++i) {
+ uint64_t blocks[2];
// offset in bytes
- blocks[0] = tgt->pos[i * 2] * (uint64_t) BLOCKSIZE;
+ blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
// length in bytes
- blocks[1] = (tgt->pos[i * 2 + 1] - tgt->pos[i * 2]) * (uint64_t) BLOCKSIZE;
+ blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
- if (ioctl(params->fd, BLKDISCARD, &blocks) == -1) {
+ if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
- goto pceout;
+ return -1;
}
}
}
- rc = 0;
-
-pceout:
- if (tgt) {
- free(tgt);
- }
-
- return rc;
+ return 0;
}
// Definitions for transfer list command functions
-typedef int (*CommandFunction)(CommandParameters*);
+typedef int (*CommandFunction)(CommandParameters&);
typedef struct {
const char* name;
@@ -1518,32 +1297,28 @@ static unsigned int HashString(const char *s) {
// - new data stream (filename within package.zip)
// - patch stream (filename within package.zip, must be uncompressed)
-static Value* PerformBlockImageUpdate(const char* name, State* state, int argc, Expr* argv[],
- const Command* commands, int cmdcount, int dryrun) {
+static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
+ const Command* commands, size_t cmdcount, bool dryrun) {
- char* line = NULL;
- char* linesave = NULL;
- char* logcmd = NULL;
- char* transfer_list = NULL;
+ char* line = nullptr;
+ char* linesave = nullptr;
+ char* transfer_list = nullptr;
CommandParameters params;
- const Command* cmd = NULL;
- const ZipEntry* new_entry = NULL;
- const ZipEntry* patch_entry = NULL;
- FILE* cmd_pipe = NULL;
- HashTable* cmdht = NULL;
- int i;
+ const Command* cmd = nullptr;
+ const ZipEntry* new_entry = nullptr;
+ const ZipEntry* patch_entry = nullptr;
+ FILE* cmd_pipe = nullptr;
+ HashTable* cmdht = nullptr;
int res;
int rc = -1;
- int stash_max_blocks = 0;
int total_blocks = 0;
pthread_attr_t attr;
- unsigned int cmdhash;
- UpdaterInfo* ui = NULL;
- Value* blockdev_filename = NULL;
- Value* new_data_fn = NULL;
- Value* patch_data_fn = NULL;
- Value* transfer_list_value = NULL;
- ZipArchive* za = NULL;
+ UpdaterInfo* ui = nullptr;
+ Value* blockdev_filename = nullptr;
+ Value* new_data_fn = nullptr;
+ Value* patch_data_fn = nullptr;
+ Value* transfer_list_value = nullptr;
+ ZipArchive* za = nullptr;
memset(&params, 0, sizeof(params));
params.canwrite = !dryrun;
@@ -1574,20 +1349,20 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
ui = (UpdaterInfo*) state->cookie;
- if (ui == NULL) {
+ if (ui == nullptr) {
goto pbiudone;
}
cmd_pipe = ui->cmd_pipe;
za = ui->package_zip;
- if (cmd_pipe == NULL || za == NULL) {
+ if (cmd_pipe == nullptr || za == nullptr) {
goto pbiudone;
}
patch_entry = mzFindZipEntry(za, patch_data_fn->data);
- if (patch_entry == NULL) {
+ if (patch_entry == nullptr) {
fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
goto pbiudone;
}
@@ -1595,7 +1370,7 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
new_entry = mzFindZipEntry(za, new_data_fn->data);
- if (new_entry == NULL) {
+ if (new_entry == nullptr) {
fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
goto pbiudone;
}
@@ -1611,8 +1386,8 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
params.nti.za = za;
params.nti.entry = new_entry;
- pthread_mutex_init(&params.nti.mu, NULL);
- pthread_cond_init(&params.nti.cv, NULL);
+ pthread_mutex_init(&params.nti.mu, nullptr);
+ pthread_cond_init(&params.nti.cv, nullptr);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
@@ -1625,9 +1400,9 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
// The data in transfer_list_value is not necessarily null-terminated, so we need
// to copy it to a new buffer and add the null that strtok_r will need.
- transfer_list = malloc(transfer_list_value->size + 1);
+ transfer_list = reinterpret_cast<char*>(malloc(transfer_list_value->size + 1));
- if (transfer_list == NULL) {
+ if (transfer_list == nullptr) {
fprintf(stderr, "failed to allocate %zd bytes for transfer list\n",
transfer_list_value->size + 1);
goto pbiudone;
@@ -1638,7 +1413,7 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
// First line in transfer list is the version number
line = strtok_r(transfer_list, "\n", &linesave);
- params.version = strtol(line, NULL, 0);
+ params.version = strtol(line, nullptr, 0);
if (params.version < 1 || params.version > 3) {
fprintf(stderr, "unexpected transfer list version [%s]\n", line);
@@ -1648,8 +1423,8 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
fprintf(stderr, "blockimg version is %d\n", params.version);
// Second line in transfer list is the total number of blocks we expect to write
- line = strtok_r(NULL, "\n", &linesave);
- total_blocks = strtol(line, NULL, 0);
+ line = strtok_r(nullptr, "\n", &linesave);
+ total_blocks = strtol(line, nullptr, 0);
if (total_blocks < 0) {
ErrorAbort(state, "unexpected block count [%s]\n", line);
@@ -1661,12 +1436,12 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
if (params.version >= 2) {
// Third line is how many stash entries are needed simultaneously
- line = strtok_r(NULL, "\n", &linesave);
+ line = strtok_r(nullptr, "\n", &linesave);
fprintf(stderr, "maximum stash entries %s\n", line);
// Fourth line is the maximum number of blocks that will be stashed simultaneously
- line = strtok_r(NULL, "\n", &linesave);
- stash_max_blocks = strtol(line, NULL, 0);
+ line = strtok_r(nullptr, "\n", &linesave);
+ int stash_max_blocks = strtol(line, nullptr, 0);
if (stash_max_blocks < 0) {
ErrorAbort(state, "unexpected maximum stash blocks [%s]\n", line);
@@ -1674,8 +1449,7 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
}
if (stash_max_blocks >= 0) {
- res = CreateStash(state, stash_max_blocks, blockdev_filename->data,
- &params.stashbase);
+ res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
if (res == -1) {
goto pbiudone;
@@ -1686,55 +1460,53 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
}
// Build a hash table of the available commands
- cmdht = mzHashTableCreate(cmdcount, NULL);
+ cmdht = mzHashTableCreate(cmdcount, nullptr);
- for (i = 0; i < cmdcount; ++i) {
- cmdhash = HashString(commands[i].name);
+ for (size_t i = 0; i < cmdcount; ++i) {
+ unsigned int cmdhash = HashString(commands[i].name);
mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
}
// Subsequent lines are all individual transfer commands
- for (line = strtok_r(NULL, "\n", &linesave); line;
- line = strtok_r(NULL, "\n", &linesave)) {
+ for (line = strtok_r(nullptr, "\n", &linesave); line;
+ line = strtok_r(nullptr, "\n", &linesave)) {
- logcmd = strdup(line);
+ const std::string logcmd(line);
params.cmdname = strtok_r(line, " ", &params.cpos);
- if (params.cmdname == NULL) {
+ if (params.cmdname == nullptr) {
fprintf(stderr, "missing command [%s]\n", line);
goto pbiudone;
}
- cmdhash = HashString(params.cmdname);
+ unsigned int cmdhash = HashString(params.cmdname);
cmd = (const Command*) mzHashTableLookup(cmdht, cmdhash, params.cmdname,
CompareCommandNames, false);
- if (cmd == NULL) {
+ if (cmd == nullptr) {
fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
goto pbiudone;
}
- if (cmd->f != NULL && cmd->f(&params) == -1) {
- fprintf(stderr, "failed to execute command [%s]\n",
- logcmd ? logcmd : params.cmdname);
+ if (cmd->f != nullptr && cmd->f(params) == -1) {
+ fprintf(stderr, "failed to execute command [%s]\n", logcmd.c_str());
goto pbiudone;
}
- if (logcmd) {
- free(logcmd);
- logcmd = NULL;
- }
-
if (params.canwrite) {
+ if (fsync(params.fd) == -1) {
+ fprintf(stderr, "fsync failed: %s\n", strerror(errno));
+ goto pbiudone;
+ }
fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
fflush(cmd_pipe);
}
}
if (params.canwrite) {
- pthread_join(params.thread, NULL);
+ pthread_join(params.thread, nullptr);
- fprintf(stderr, "wrote %d blocks; expected %d\n", params.written, total_blocks);
+ fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
fprintf(stderr, "max alloc needed was %zu\n", params.bufsize);
// Delete stash only after successfully completing the update, as it
@@ -1754,10 +1526,6 @@ pbiudone:
close(params.fd);
}
- if (logcmd) {
- free(logcmd);
- }
-
if (cmdht) {
mzHashTableFree(cmdht);
}
@@ -1792,10 +1560,6 @@ pbiudone:
DeleteStash(params.stashbase);
}
- if (params.stashbase) {
- free(params.stashbase);
- }
-
return StringValue(rc == 0 ? strdup("t") : strdup(""));
}
@@ -1853,21 +1617,21 @@ pbiudone:
// the source data.
Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
- // Commands which are not tested are set to NULL to skip them completely
+ // Commands which are not tested are set to nullptr to skip them completely
const Command commands[] = {
{ "bsdiff", PerformCommandDiff },
- { "erase", NULL },
+ { "erase", nullptr },
{ "free", PerformCommandFree },
{ "imgdiff", PerformCommandDiff },
{ "move", PerformCommandMove },
- { "new", NULL },
+ { "new", nullptr },
{ "stash", PerformCommandStash },
- { "zero", NULL }
+ { "zero", nullptr }
};
// Perform a dry run without writing to test if an update can proceed
return PerformBlockImageUpdate(name, state, argc, argv, commands,
- sizeof(commands) / sizeof(commands[0]), 1);
+ sizeof(commands) / sizeof(commands[0]), true);
}
Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
@@ -1883,15 +1647,17 @@ Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]
};
return PerformBlockImageUpdate(name, state, argc, argv, commands,
- sizeof(commands) / sizeof(commands[0]), 0);
+ sizeof(commands) / sizeof(commands[0]), false);
}
-Value* RangeSha1Fn(const char* name, State* state, int argc, Expr* argv[]) {
+Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Value* blockdev_filename;
Value* ranges;
- const uint8_t* digest = NULL;
+ const uint8_t* digest = nullptr;
+ RangeSet rs;
+
if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
- return NULL;
+ return nullptr;
}
if (blockdev_filename->type != VAL_STRING) {
@@ -1903,30 +1669,30 @@ Value* RangeSha1Fn(const char* name, State* state, int argc, Expr* argv[]) {
goto done;
}
- int fd = open(blockdev_filename->data, O_RDWR);
+ int fd;
+ fd = open(blockdev_filename->data, O_RDWR);
if (fd < 0) {
ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno));
goto done;
}
- RangeSet* rs = parse_range(ranges->data);
+ parse_range(ranges->data, rs);
uint8_t buffer[BLOCKSIZE];
SHA_CTX ctx;
SHA_init(&ctx);
- int i, j;
- for (i = 0; i < rs->count; ++i) {
- if (!check_lseek(fd, (off64_t)rs->pos[i*2] * BLOCKSIZE, SEEK_SET)) {
+ for (size_t i = 0; i < rs.count; ++i) {
+ if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
ErrorAbort(state, "failed to seek %s: %s", blockdev_filename->data,
- strerror(errno));
+ strerror(errno));
goto done;
}
- for (j = rs->pos[i*2]; j < rs->pos[i*2+1]; ++j) {
+ 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));
goto done;
}
@@ -1939,10 +1705,10 @@ Value* RangeSha1Fn(const char* name, State* state, int argc, Expr* argv[]) {
done:
FreeValue(blockdev_filename);
FreeValue(ranges);
- if (digest == NULL) {
+ if (digest == nullptr) {
return StringValue(strdup(""));
} else {
- return StringValue(PrintSha1(digest));
+ return StringValue(strdup(print_sha1(digest).c_str()));
}
}
diff --git a/updater/install.c b/updater/install.cpp
index 01a5dd24b..422a1bb1e 100644
--- a/updater/install.c
+++ b/updater/install.cpp
@@ -61,6 +61,11 @@ void uiPrint(State* state, char* buffer) {
line = strtok(NULL, "\n");
}
fprintf(ui->cmd_pipe, "ui_print\n");
+
+ // The recovery will only print the contents to screen for pipe command
+ // ui_print. We need to dump the contents to stderr (which has been
+ // redirected to the log file) directly.
+ fprintf(stderr, "%s", buffer);
}
__attribute__((__format__(printf, 2, 3))) __nonnull((2))
@@ -75,9 +80,9 @@ void uiPrintf(State* state, const char* format, ...) {
// Take a sha-1 digest and return it as a newly-allocated hex string.
char* PrintSha1(const uint8_t* digest) {
- char* buffer = malloc(SHA_DIGEST_SIZE*2 + 1);
- int i;
+ char* buffer = reinterpret_cast<char*>(malloc(SHA_DIGEST_SIZE*2 + 1));
const char* alphabet = "0123456789abcdef";
+ size_t i;
for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
buffer[i*2] = alphabet[(digest[i] >> 4) & 0xf];
buffer[i*2+1] = alphabet[digest[i] & 0xf];
@@ -133,18 +138,20 @@ Value* MountFn(const char* name, State* state, int argc, Expr* argv[]) {
goto done;
}
- char *secontext = NULL;
+ {
+ char *secontext = NULL;
- if (sehandle) {
- selabel_lookup(sehandle, &secontext, mount_point, 0755);
- setfscreatecon(secontext);
- }
+ if (sehandle) {
+ selabel_lookup(sehandle, &secontext, mount_point, 0755);
+ setfscreatecon(secontext);
+ }
- mkdir(mount_point, 0755);
+ mkdir(mount_point, 0755);
- if (secontext) {
- freecon(secontext);
- setfscreatecon(NULL);
+ if (secontext) {
+ freecon(secontext);
+ setfscreatecon(NULL);
+ }
}
if (strcmp(partition_type, "MTD") == 0) {
@@ -202,11 +209,13 @@ Value* IsMountedFn(const char* name, State* state, int argc, Expr* argv[]) {
}
scan_mounted_volumes();
- const MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point);
- if (vol == NULL) {
- result = strdup("");
- } else {
- result = mount_point;
+ {
+ const MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point);
+ if (vol == NULL) {
+ result = strdup("");
+ } else {
+ result = mount_point;
+ }
}
done:
@@ -230,17 +239,19 @@ Value* UnmountFn(const char* name, State* state, int argc, Expr* argv[]) {
}
scan_mounted_volumes();
- const MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point);
- if (vol == NULL) {
- uiPrintf(state, "unmount of %s failed; no such volume\n", mount_point);
- result = strdup("");
- } else {
- int ret = unmount_mounted_volume(vol);
- if (ret != 0) {
- uiPrintf(state, "unmount of %s failed (%d): %s\n",
- mount_point, ret, strerror(errno));
+ {
+ const MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point);
+ if (vol == NULL) {
+ uiPrintf(state, "unmount of %s failed; no such volume\n", mount_point);
+ result = strdup("");
+ } else {
+ int ret = unmount_mounted_volume(vol);
+ if (ret != 0) {
+ uiPrintf(state, "unmount of %s failed (%d): %s\n",
+ mount_point, ret, strerror(errno));
+ }
+ result = mount_point;
}
- result = mount_point;
}
done:
@@ -413,9 +424,8 @@ done:
}
Value* DeleteFn(const char* name, State* state, int argc, Expr* argv[]) {
- char** paths = malloc(argc * sizeof(char*));
- int i;
- for (i = 0; i < argc; ++i) {
+ char** paths = reinterpret_cast<char**>(malloc(argc * sizeof(char*)));
+ for (int i = 0; i < argc; ++i) {
paths[i] = Evaluate(state, argv[i]);
if (paths[i] == NULL) {
int j;
@@ -430,7 +440,7 @@ Value* DeleteFn(const char* name, State* state, int argc, Expr* argv[]) {
bool recursive = (strcmp(name, "delete_recursive") == 0);
int success = 0;
- for (i = 0; i < argc; ++i) {
+ for (int i = 0; i < argc; ++i) {
if ((recursive ? dirUnlinkHierarchy(paths[i]) : unlink(paths[i])) == 0)
++success;
free(paths[i]);
@@ -517,8 +527,6 @@ Value* PackageExtractFileFn(const char* name, State* state,
}
bool success = false;
- UpdaterInfo* ui = (UpdaterInfo*)(state->cookie);
-
if (argc == 2) {
// The two-argument version extracts to a file.
@@ -534,14 +542,16 @@ Value* PackageExtractFileFn(const char* name, State* state,
goto done2;
}
- FILE* f = fopen(dest_path, "wb");
- if (f == NULL) {
- printf("%s: can't open %s for write: %s\n",
- name, dest_path, strerror(errno));
- goto done2;
+ {
+ FILE* f = fopen(dest_path, "wb");
+ if (f == NULL) {
+ printf("%s: can't open %s for write: %s\n",
+ name, dest_path, strerror(errno));
+ goto done2;
+ }
+ success = mzExtractZipEntryToFile(za, entry, fileno(f));
+ fclose(f);
}
- success = mzExtractZipEntryToFile(za, entry, fileno(f));
- fclose(f);
done2:
free(zip_path);
@@ -552,7 +562,7 @@ Value* PackageExtractFileFn(const char* name, State* state,
// as the result.
char* zip_path;
- Value* v = malloc(sizeof(Value));
+ Value* v = reinterpret_cast<Value*>(malloc(sizeof(Value)));
v->type = VAL_BLOB;
v->size = -1;
v->data = NULL;
@@ -567,7 +577,7 @@ Value* PackageExtractFileFn(const char* name, State* state,
}
v->size = mzGetZipEntryUncompLen(entry);
- v->data = malloc(v->size);
+ v->data = reinterpret_cast<char*>(malloc(v->size));
if (v->data == NULL) {
printf("%s: failed to allocate %ld bytes for %s\n",
name, (long)v->size, zip_path);
@@ -866,17 +876,14 @@ static int do_SetMetadataRecursive(const char* filename, const struct stat *stat
}
static Value* SetMetadataFn(const char* name, State* state, int argc, Expr* argv[]) {
- int i;
int bad = 0;
- static int nwarnings = 0;
struct stat sb;
Value* result = NULL;
bool recursive = (strcmp(name, "set_metadata_recursive") == 0);
if ((argc % 2) != 1) {
- return ErrorAbort(state, "%s() expects an odd number of arguments, got %d",
- name, argc);
+ return ErrorAbort(state, "%s() expects an odd number of arguments, got %d", name, argc);
}
char** args = ReadVarArgs(state, argc, argv);
@@ -887,20 +894,22 @@ static Value* SetMetadataFn(const char* name, State* state, int argc, Expr* argv
goto done;
}
- struct perm_parsed_args parsed = ParsePermArgs(state, argc, args);
+ {
+ struct perm_parsed_args parsed = ParsePermArgs(state, argc, args);
- if (recursive) {
- recursive_parsed_args = parsed;
- recursive_state = state;
- bad += nftw(args[0], do_SetMetadataRecursive, 30, FTW_CHDIR | FTW_DEPTH | FTW_PHYS);
- memset(&recursive_parsed_args, 0, sizeof(recursive_parsed_args));
- recursive_state = NULL;
- } else {
- bad += ApplyParsedPerms(state, args[0], &sb, parsed);
+ if (recursive) {
+ recursive_parsed_args = parsed;
+ recursive_state = state;
+ bad += nftw(args[0], do_SetMetadataRecursive, 30, FTW_CHDIR | FTW_DEPTH | FTW_PHYS);
+ memset(&recursive_parsed_args, 0, sizeof(recursive_parsed_args));
+ recursive_state = NULL;
+ } else {
+ bad += ApplyParsedPerms(state, args[0], &sb, parsed);
+ }
}
done:
- for (i = 0; i < argc; ++i) {
+ for (int i = 0; i < argc; ++i) {
free(args[i]);
}
free(args);
@@ -920,8 +929,7 @@ Value* GetPropFn(const char* name, State* state, int argc, Expr* argv[]) {
if (argc != 1) {
return ErrorAbort(state, "%s() expects 1 arg, got %d", name, argc);
}
- char* key;
- key = Evaluate(state, argv[0]);
+ char* key = Evaluate(state, argv[0]);
if (key == NULL) return NULL;
char value[PROPERTY_VALUE_MAX];
@@ -948,29 +956,27 @@ Value* FileGetPropFn(const char* name, State* state, int argc, Expr* argv[]) {
struct stat st;
if (stat(filename, &st) < 0) {
- ErrorAbort(state, "%s: failed to stat \"%s\": %s",
- name, filename, strerror(errno));
+ ErrorAbort(state, "%s: failed to stat \"%s\": %s", name, filename, strerror(errno));
goto done;
}
#define MAX_FILE_GETPROP_SIZE 65536
if (st.st_size > MAX_FILE_GETPROP_SIZE) {
- ErrorAbort(state, "%s too large for %s (max %d)",
- filename, name, MAX_FILE_GETPROP_SIZE);
+ ErrorAbort(state, "%s too large for %s (max %d)", filename, name, MAX_FILE_GETPROP_SIZE);
goto done;
}
- buffer = malloc(st.st_size+1);
+ buffer = reinterpret_cast<char*>(malloc(st.st_size+1));
if (buffer == NULL) {
ErrorAbort(state, "%s: failed to alloc %lld bytes", name, (long long)st.st_size+1);
goto done;
}
- FILE* f = fopen(filename, "rb");
+ FILE* f;
+ f = fopen(filename, "rb");
if (f == NULL) {
- ErrorAbort(state, "%s: failed to open %s: %s",
- name, filename, strerror(errno));
+ ErrorAbort(state, "%s: failed to open %s: %s", name, filename, strerror(errno));
goto done;
}
@@ -984,7 +990,8 @@ Value* FileGetPropFn(const char* name, State* state, int argc, Expr* argv[]) {
fclose(f);
- char* line = strtok(buffer, "\n");
+ char* line;
+ line = strtok(buffer, "\n");
do {
// skip whitespace at start of line
while (*line && isspace(*line)) ++line;
@@ -1028,15 +1035,6 @@ Value* FileGetPropFn(const char* name, State* state, int argc, Expr* argv[]) {
return StringValue(result);
}
-
-static bool write_raw_image_cb(const unsigned char* data,
- int data_len, void* ctx) {
- int r = mtd_write_data((MtdWriteContext*)ctx, (const char *)data, data_len);
- if (r == data_len) return true;
- printf("%s\n", strerror(errno));
- return false;
-}
-
// write_raw_image(filename_or_blob, partition)
Value* WriteRawImageFn(const char* name, State* state, int argc, Expr* argv[]) {
char* result = NULL;
@@ -1063,14 +1061,16 @@ Value* WriteRawImageFn(const char* name, State* state, int argc, Expr* argv[]) {
}
mtd_scan_partitions();
- const MtdPartition* mtd = mtd_find_partition_by_name(partition);
+ const MtdPartition* mtd;
+ mtd = mtd_find_partition_by_name(partition);
if (mtd == NULL) {
printf("%s: no mtd partition named \"%s\"\n", name, partition);
result = strdup("");
goto done;
}
- MtdWriteContext* ctx = mtd_write_partition(mtd);
+ MtdWriteContext* ctx;
+ ctx = mtd_write_partition(mtd);
if (ctx == NULL) {
printf("%s: can't write mtd partition \"%s\"\n",
name, partition);
@@ -1085,14 +1085,13 @@ Value* WriteRawImageFn(const char* name, State* state, int argc, Expr* argv[]) {
char* filename = contents->data;
FILE* f = fopen(filename, "rb");
if (f == NULL) {
- printf("%s: can't open %s: %s\n",
- name, filename, strerror(errno));
+ printf("%s: can't open %s: %s\n", name, filename, strerror(errno));
result = strdup("");
goto done;
}
success = true;
- char* buffer = malloc(BUFSIZ);
+ char* buffer = reinterpret_cast<char*>(malloc(BUFSIZ));
int read;
while (success && (read = fread(buffer, 1, BUFSIZ, f)) > 0) {
int wrote = mtd_write_data(ctx, buffer, read);
@@ -1139,8 +1138,7 @@ Value* ApplyPatchSpaceFn(const char* name, State* state,
char* endptr;
size_t bytes = strtol(bytes_str, &endptr, 10);
if (bytes == 0 && endptr == bytes_str) {
- ErrorAbort(state, "%s(): can't parse \"%s\" as byte count\n\n",
- name, bytes_str);
+ ErrorAbort(state, "%s(): can't parse \"%s\" as byte count\n\n", name, bytes_str);
free(bytes_str);
return NULL;
}
@@ -1200,7 +1198,7 @@ Value* ApplyPatchFn(const char* name, State* state, int argc, Expr* argv[]) {
return NULL;
}
- char** patch_sha_str = malloc(patchcount * sizeof(char*));
+ char** patch_sha_str = reinterpret_cast<char**>(malloc(patchcount * sizeof(char*)));
for (i = 0; i < patchcount; ++i) {
patch_sha_str[i] = patches[i*2]->data;
patches[i*2]->data = NULL;
@@ -1259,7 +1257,7 @@ Value* UIPrintFn(const char* name, State* state, int argc, Expr* argv[]) {
for (i = 0; i < argc; ++i) {
size += strlen(args[i]);
}
- char* buffer = malloc(size+1);
+ char* buffer = reinterpret_cast<char*>(malloc(size+1));
size = 0;
for (i = 0; i < argc; ++i) {
strcpy(buffer+size, args[i]);
@@ -1289,7 +1287,7 @@ Value* RunProgramFn(const char* name, State* state, int argc, Expr* argv[]) {
return NULL;
}
- char** args2 = malloc(sizeof(char*) * (argc+1));
+ char** args2 = reinterpret_cast<char**>(malloc(sizeof(char*) * (argc+1)));
memcpy(args2, args, sizeof(char*) * argc);
args2[argc] = NULL;
@@ -1356,7 +1354,7 @@ Value* Sha1CheckFn(const char* name, State* state, int argc, Expr* argv[]) {
}
int i;
- uint8_t* arg_digest = malloc(SHA_DIGEST_SIZE);
+ uint8_t* arg_digest = reinterpret_cast<uint8_t*>(malloc(SHA_DIGEST_SIZE));
for (i = 1; i < argc; ++i) {
if (args[i]->type != VAL_STRING) {
printf("%s(): arg %d is not a string; skipping",
@@ -1392,7 +1390,7 @@ Value* ReadFileFn(const char* name, State* state, int argc, Expr* argv[]) {
char* filename;
if (ReadArgs(state, argv, 1, &filename) < 0) return NULL;
- Value* v = malloc(sizeof(Value));
+ Value* v = reinterpret_cast<Value*>(malloc(sizeof(Value)));
v->type = VAL_BLOB;
FileContents fc;
@@ -1550,15 +1548,14 @@ Value* Tune2FsFn(const char* name, State* state, int argc, Expr* argv[]) {
return ErrorAbort(state, "%s() could not read args", name);
}
- int i;
- char** args2 = malloc(sizeof(char*) * (argc+1));
+ char** args2 = reinterpret_cast<char**>(malloc(sizeof(char*) * (argc+1)));
// Tune2fs expects the program name as its args[0]
args2[0] = strdup(name);
- for (i = 0; i < argc; ++i) {
+ for (int i = 0; i < argc; ++i) {
args2[i + 1] = args[i];
}
int result = tune2fs_main(argc + 1, args2);
- for (i = 0; i < argc; ++i) {
+ for (int i = 0; i < argc; ++i) {
free(args[i]);
}
free(args);
diff --git a/updater/updater.c b/updater/updater.cpp
index 661f69587..0f22e6d04 100644
--- a/updater/updater.c
+++ b/updater/updater.cpp
@@ -89,7 +89,7 @@ int main(int argc, char** argv) {
return 4;
}
- char* script = malloc(script_entry->uncompLen+1);
+ char* script = reinterpret_cast<char*>(malloc(script_entry->uncompLen+1));
if (!mzReadZipEntry(&za, script_entry, script, script_entry->uncompLen)) {
printf("failed to read script from package\n");
return 5;
diff --git a/verifier_test.cpp b/verifier_test.cpp
index 82546edce..21633dc20 100644
--- a/verifier_test.cpp
+++ b/verifier_test.cpp
@@ -141,6 +141,12 @@ class FakeUI : public RecoveryUI {
vfprintf(stderr, fmt, ap);
va_end(ap);
}
+ void PrintOnScreenOnly(const char* fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ }
void ShowFile(const char*) { }
void StartMenu(const char* const * headers, const char* const * items,