DO NOT MERGE recovery: Switch applypatch/ and updater/ to cpp.

Mostly trivial changes to make cpp compiler happy.

Change-Id: I69bd1d96fcccf506007f6144faf37e11cfba1270
(cherry picked from commit ba9a42aa7e)
This commit is contained in:
Tao Bao
2015-06-23 23:23:33 -07:00
committed by Rom Lemarchand
parent 806f72f9e6
commit 818fa781d1
15 changed files with 304 additions and 300 deletions
+4 -4
View File
@@ -17,7 +17,7 @@ LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_CLANG := true LOCAL_CLANG := true
LOCAL_SRC_FILES := applypatch.c bspatch.c freecache.c imgpatch.c utils.c LOCAL_SRC_FILES := applypatch.cpp bspatch.cpp freecache.cpp imgpatch.cpp utils.cpp
LOCAL_MODULE := libapplypatch LOCAL_MODULE := libapplypatch
LOCAL_MODULE_TAGS := eng LOCAL_MODULE_TAGS := eng
LOCAL_C_INCLUDES += external/bzip2 external/zlib bootable/recovery LOCAL_C_INCLUDES += external/bzip2 external/zlib bootable/recovery
@@ -28,7 +28,7 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_CLANG := true LOCAL_CLANG := true
LOCAL_SRC_FILES := main.c LOCAL_SRC_FILES := main.cpp
LOCAL_MODULE := applypatch LOCAL_MODULE := applypatch
LOCAL_C_INCLUDES += bootable/recovery LOCAL_C_INCLUDES += bootable/recovery
LOCAL_STATIC_LIBRARIES += libapplypatch libmtdutils libmincrypt libbz LOCAL_STATIC_LIBRARIES += libapplypatch libmtdutils libmincrypt libbz
@@ -39,7 +39,7 @@ include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_CLANG := true LOCAL_CLANG := true
LOCAL_SRC_FILES := main.c LOCAL_SRC_FILES := main.cpp
LOCAL_MODULE := applypatch_static LOCAL_MODULE := applypatch_static
LOCAL_FORCE_STATIC_EXECUTABLE := true LOCAL_FORCE_STATIC_EXECUTABLE := true
LOCAL_MODULE_TAGS := eng LOCAL_MODULE_TAGS := eng
@@ -52,7 +52,7 @@ include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_CLANG := true LOCAL_CLANG := true
LOCAL_SRC_FILES := imgdiff.c utils.c bsdiff.c LOCAL_SRC_FILES := imgdiff.cpp utils.cpp bsdiff.cpp
LOCAL_MODULE := imgdiff LOCAL_MODULE := imgdiff
LOCAL_FORCE_STATIC_EXECUTABLE := true LOCAL_FORCE_STATIC_EXECUTABLE := true
LOCAL_C_INCLUDES += external/zlib external/bzip2 LOCAL_C_INCLUDES += external/zlib external/bzip2
@@ -15,6 +15,7 @@
*/ */
#include <errno.h> #include <errno.h>
#include <fcntl.h>
#include <libgen.h> #include <libgen.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@@ -22,9 +23,7 @@
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/statfs.h> #include <sys/statfs.h>
#include <sys/types.h> #include <sys/types.h>
#include <fcntl.h>
#include <unistd.h> #include <unistd.h>
#include <stdbool.h>
#include "mincrypt/sha.h" #include "mincrypt/sha.h"
#include "applypatch.h" #include "applypatch.h"
@@ -65,7 +64,7 @@ int LoadFileContents(const char* filename, FileContents* file) {
} }
file->size = file->st.st_size; 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"); FILE* f = fopen(filename, "rb");
if (f == NULL) { if (f == NULL) {
@@ -75,10 +74,9 @@ int LoadFileContents(const char* filename, FileContents* file) {
return -1; return -1;
} }
ssize_t bytes_read = fread(file->data, 1, file->size, f); size_t bytes_read = fread(file->data, 1, file->size, f);
if (bytes_read != file->size) { if (bytes_read != static_cast<size_t>(file->size)) {
printf("short read of \"%s\" (%ld bytes of %ld)\n", printf("short read of \"%s\" (%zu bytes of %zd)\n", filename, bytes_read, file->size);
filename, (long)bytes_read, (long)file->size);
free(file->data); free(file->data);
file->data = NULL; file->data = NULL;
return -1; return -1;
@@ -93,8 +91,8 @@ static size_t* size_array;
// comparison function for qsort()ing an int array of indexes into // comparison function for qsort()ing an int array of indexes into
// size_array[]. // size_array[].
static int compare_size_indices(const void* a, const void* b) { static int compare_size_indices(const void* a, const void* b) {
int aa = *(int*)a; const int aa = *reinterpret_cast<const int*>(a);
int bb = *(int*)b; const int bb = *reinterpret_cast<const int*>(b);
if (size_array[aa] < size_array[bb]) { if (size_array[aa] < size_array[bb]) {
return -1; return -1;
} else if (size_array[aa] > size_array[bb]) { } else if (size_array[aa] > size_array[bb]) {
@@ -132,8 +130,7 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
} else if (strcmp(magic, "EMMC") == 0) { } else if (strcmp(magic, "EMMC") == 0) {
type = EMMC; type = EMMC;
} else { } else {
printf("LoadPartitionContents called with bad filename (%s)\n", printf("LoadPartitionContents called with bad filename (%s)\n", filename);
filename);
return -1; return -1;
} }
const char* partition = strtok(NULL, ":"); const char* partition = strtok(NULL, ":");
@@ -151,9 +148,9 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
} }
int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
int* index = malloc(pairs * sizeof(int)); int* index = reinterpret_cast<int*>(malloc(pairs * sizeof(int)));
size_t* size = malloc(pairs * sizeof(size_t)); size_t* size = reinterpret_cast<size_t*>(malloc(pairs * sizeof(size_t)));
char** sha1sum = malloc(pairs * sizeof(char*)); char** sha1sum = reinterpret_cast<char**>(malloc(pairs * sizeof(char*)));
for (i = 0; i < pairs; ++i) { for (i = 0; i < pairs; ++i) {
const char* size_str = strtok(NULL, ":"); const char* size_str = strtok(NULL, ":");
@@ -175,7 +172,7 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
FILE* dev = NULL; FILE* dev = NULL;
switch (type) { switch (type) {
case MTD: case MTD: {
if (!mtd_partitions_scanned) { if (!mtd_partitions_scanned) {
mtd_scan_partitions(); mtd_scan_partitions();
mtd_partitions_scanned = 1; mtd_partitions_scanned = 1;
@@ -195,6 +192,7 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
return -1; return -1;
} }
break; break;
}
case EMMC: case EMMC:
dev = fopen(partition, "rb"); dev = fopen(partition, "rb");
@@ -210,7 +208,7 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
uint8_t parsed_sha[SHA_DIGEST_SIZE]; uint8_t parsed_sha[SHA_DIGEST_SIZE];
// allocate enough memory to hold the largest size. // allocate enough memory to hold the largest size.
file->data = malloc(size[index[pairs-1]]); file->data = reinterpret_cast<unsigned char*>(malloc(size[index[pairs-1]]));
char* p = (char*)file->data; char* p = (char*)file->data;
file->size = 0; // # bytes read so far file->size = 0; // # bytes read so far
@@ -248,8 +246,7 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
const uint8_t* sha_so_far = SHA_final(&temp_ctx); const uint8_t* sha_so_far = SHA_final(&temp_ctx);
if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) { if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
printf("failed to parse sha1 %s in %s\n", printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]], filename);
sha1sum[index[i]], filename);
free(file->data); free(file->data);
file->data = NULL; file->data = NULL;
return -1; return -1;
@@ -280,15 +277,14 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
if (i == pairs) { if (i == pairs) {
// Ran off the end of the list of (size,sha1) pairs without // Ran off the end of the list of (size,sha1) pairs without
// finding a match. // finding a match.
printf("contents of partition \"%s\" didn't match %s\n", printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
partition, filename);
free(file->data); free(file->data);
file->data = NULL; file->data = NULL;
return -1; return -1;
} }
const uint8_t* sha_final = SHA_final(&sha_ctx); 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]; file->sha1[i] = sha_final[i];
} }
@@ -311,16 +307,14 @@ static int LoadPartitionContents(const char* filename, FileContents* file) {
int SaveFileContents(const char* filename, const 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); int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
if (fd < 0) { if (fd < 0) {
printf("failed to open \"%s\" for write: %s\n", printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
filename, strerror(errno));
return -1; return -1;
} }
ssize_t bytes_written = FileSink(file->data, file->size, &fd); ssize_t bytes_written = FileSink(file->data, file->size, &fd);
if (bytes_written != file->size) { if (bytes_written != file->size) {
printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n", printf("short write of \"%s\" (%zd bytes of %zd) (%s)\n",
filename, (long)bytes_written, (long)file->size, filename, bytes_written, file->size, strerror(errno));
strerror(errno));
close(fd); close(fd);
return -1; return -1;
} }
@@ -348,8 +342,7 @@ int SaveFileContents(const char* filename, const FileContents* file) {
// Write a memory buffer to 'target' partition, a string of the form // Write a memory buffer to 'target' partition, a string of the form
// "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on // "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on
// success. // success.
int WriteToPartition(unsigned char* data, size_t len, int WriteToPartition(unsigned char* data, size_t len, const char* target) {
const char* target) {
char* copy = strdup(target); char* copy = strdup(target);
const char* magic = strtok(copy, ":"); const char* magic = strtok(copy, ":");
@@ -370,7 +363,7 @@ int WriteToPartition(unsigned char* data, size_t len,
} }
switch (type) { switch (type) {
case MTD: case MTD: {
if (!mtd_partitions_scanned) { if (!mtd_partitions_scanned) {
mtd_scan_partitions(); mtd_scan_partitions();
mtd_partitions_scanned = 1; mtd_partitions_scanned = 1;
@@ -378,22 +371,19 @@ int WriteToPartition(unsigned char* data, size_t len,
const MtdPartition* mtd = mtd_find_partition_by_name(partition); const MtdPartition* mtd = mtd_find_partition_by_name(partition);
if (mtd == NULL) { if (mtd == NULL) {
printf("mtd partition \"%s\" not found for writing\n", printf("mtd partition \"%s\" not found for writing\n", partition);
partition);
return -1; return -1;
} }
MtdWriteContext* ctx = mtd_write_partition(mtd); MtdWriteContext* ctx = mtd_write_partition(mtd);
if (ctx == NULL) { if (ctx == NULL) {
printf("failed to init mtd partition \"%s\" for writing\n", printf("failed to init mtd partition \"%s\" for writing\n", partition);
partition);
return -1; 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) { if (written != len) {
printf("only wrote %zu of %zu bytes to MTD %s\n", printf("only wrote %zu of %zu bytes to MTD %s\n", written, len, partition);
written, len, partition);
mtd_write_close(ctx); mtd_write_close(ctx);
return -1; return -1;
} }
@@ -409,22 +399,20 @@ int WriteToPartition(unsigned char* data, size_t len,
return -1; return -1;
} }
break; break;
}
case EMMC: case EMMC: {
{
size_t start = 0; size_t start = 0;
int success = 0; bool success = false;
int fd = open(partition, O_RDWR | O_SYNC); int fd = open(partition, O_RDWR | O_SYNC);
if (fd < 0) { if (fd < 0) {
printf("failed to open %s: %s\n", partition, strerror(errno)); printf("failed to open %s: %s\n", partition, strerror(errno));
return -1; return -1;
} }
int attempt;
for (attempt = 0; attempt < 2; ++attempt) { for (int attempt = 0; attempt < 2; ++attempt) {
if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) { if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
printf("failed seek on %s: %s\n", printf("failed seek on %s: %s\n", partition, strerror(errno));
partition, strerror(errno));
return -1; return -1;
} }
while (start < len) { while (start < len) {
@@ -439,23 +427,20 @@ int WriteToPartition(unsigned char* data, size_t len,
start += written; start += written;
} }
if (fsync(fd) != 0) { if (fsync(fd) != 0) {
printf("failed to sync to %s (%s)\n", printf("failed to sync to %s (%s)\n", partition, strerror(errno));
partition, strerror(errno));
return -1; return -1;
} }
if (close(fd) != 0) { if (close(fd) != 0) {
printf("failed to close %s (%s)\n", printf("failed to close %s (%s)\n", partition, strerror(errno));
partition, strerror(errno));
return -1; return -1;
} }
fd = open(partition, O_RDONLY); fd = open(partition, O_RDONLY);
if (fd < 0) { if (fd < 0) {
printf("failed to reopen %s for verify (%s)\n", printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
partition, strerror(errno));
return -1; return -1;
} }
// drop caches so our subsequent verification read // Drop caches so our subsequent verification read
// won't just be reading the cache. // won't just be reading the cache.
sync(); sync();
int dc = open("/proc/sys/vm/drop_caches", O_WRONLY); int dc = open("/proc/sys/vm/drop_caches", O_WRONLY);
@@ -475,10 +460,11 @@ int WriteToPartition(unsigned char* data, size_t len,
} }
unsigned char buffer[4096]; unsigned char buffer[4096];
start = len; start = len;
size_t p; for (size_t p = 0; p < len; p += sizeof(buffer)) {
for (p = 0; p < len; p += sizeof(buffer)) {
size_t to_read = len - p; 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; size_t so_far = 0;
while (so_far < to_read) { while (so_far < to_read) {
@@ -489,14 +475,14 @@ int WriteToPartition(unsigned char* data, size_t len,
partition, p, strerror(errno)); partition, p, strerror(errno));
return -1; 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", printf("short verify read %s at %zu: %zd %zu %s\n",
partition, p, read_count, to_read, strerror(errno)); partition, p, read_count, to_read, strerror(errno));
} }
so_far += read_count; 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); printf("verification failed starting at %zu\n", p);
start = p; start = p;
break; break;
@@ -534,10 +520,9 @@ int WriteToPartition(unsigned char* data, size_t len,
// the form "<digest>:<anything>". Return 0 on success, -1 on any // the form "<digest>:<anything>". Return 0 on success, -1 on any
// error. // error.
int ParseSha1(const char* str, uint8_t* digest) { int ParseSha1(const char* str, uint8_t* digest) {
int i;
const char* ps = str; const char* ps = str;
uint8_t* pd = digest; 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; int digit;
if (*ps >= '0' && *ps <= '9') { if (*ps >= '0' && *ps <= '9') {
digit = *ps - '0'; digit = *ps - '0';
@@ -564,9 +549,8 @@ int ParseSha1(const char* str, uint8_t* digest) {
// found. // found.
int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str, int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
int num_patches) { int num_patches) {
int i;
uint8_t patch_sha1[SHA_DIGEST_SIZE]; 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 && if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) { memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
return i; return i;
@@ -578,8 +562,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 // 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 // match any of the sha1's on the command line (argv[3:]). Returns
// nonzero otherwise. // nonzero otherwise.
int applypatch_check(const char* filename, int applypatch_check(const char* filename, int num_patches,
int num_patches, char** const patch_sha1_str) { char** const patch_sha1_str) {
FileContents file; FileContents file;
file.data = NULL; file.data = NULL;
@@ -624,13 +608,13 @@ int ShowLicenses() {
} }
ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) { 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 done = 0;
ssize_t wrote; ssize_t wrote;
while (done < (ssize_t) len) { while (done < len) {
wrote = TEMP_FAILURE_RETRY(write(fd, data+done, len-done)); wrote = TEMP_FAILURE_RETRY(write(fd, data+done, len-done));
if (wrote == -1) { 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; return done;
} }
done += wrote; done += wrote;
@@ -645,7 +629,7 @@ typedef struct {
} MemorySinkInfo; } MemorySinkInfo;
ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) { 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) { if (msi->size - msi->pos < len) {
return -1; return -1;
} }
@@ -675,9 +659,8 @@ int CacheSizeCheck(size_t bytes) {
} }
static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) { static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
int i;
const char* hex = "0123456789abcdef"; const char* hex = "0123456789abcdef";
for (i = 0; i < 4; ++i) { for (size_t i = 0; i < 4; ++i) {
putchar(hex[(sha1[i]>>4) & 0xf]); putchar(hex[(sha1[i]>>4) & 0xf]);
putchar(hex[sha1[i] & 0xf]); putchar(hex[sha1[i] & 0xf]);
} }
@@ -719,8 +702,7 @@ int applypatch(const char* source_filename,
Value* bonus_data) { Value* bonus_data) {
printf("patch %s: ", source_filename); printf("patch %s: ", source_filename);
if (target_filename[0] == '-' && if (target_filename[0] == '-' && target_filename[1] == '\0') {
target_filename[1] == '\0') {
target_filename = source_filename; target_filename = source_filename;
} }
@@ -761,8 +743,7 @@ int applypatch(const char* source_filename,
} }
if (source_file.data != NULL) { if (source_file.data != NULL) {
int to_use = FindMatchingPatch(source_file.sha1, int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str, num_patches);
patch_sha1_str, num_patches);
if (to_use >= 0) { if (to_use >= 0) {
source_patch_value = patch_data[to_use]; source_patch_value = patch_data[to_use];
} }
@@ -779,8 +760,7 @@ int applypatch(const char* source_filename,
return 1; return 1;
} }
int to_use = FindMatchingPatch(copy_file.sha1, int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str, num_patches);
patch_sha1_str, num_patches);
if (to_use >= 0) { if (to_use >= 0) {
copy_patch_value = patch_data[to_use]; copy_patch_value = patch_data[to_use];
} }
@@ -865,8 +845,8 @@ static int GenerateTarget(FileContents* source_file,
(free_space > (256 << 10)) && // 256k (two-block) minimum (free_space > (256 << 10)) && // 256k (two-block) minimum
(free_space > (target_size * 3 / 2)); // 50% margin of error (free_space > (target_size * 3 / 2)); // 50% margin of error
if (!enough_space) { if (!enough_space) {
printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n", printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
(long)target_size, (long)free_space, retry, enough_space); target_size, free_space, retry, enough_space);
} }
} }
@@ -884,8 +864,7 @@ static int GenerateTarget(FileContents* source_file,
// It's impossible to free space on the target filesystem by // It's impossible to free space on the target filesystem by
// deleting the source if the source is a partition. If // deleting the source if the source is a partition. If
// we're ever in a state where we need to do this, fail. // we're ever in a state where we need to do this, fail.
printf("not enough free space for target but source " printf("not enough free space for target but source is partition\n");
"is partition\n");
return 1; return 1;
} }
@@ -902,7 +881,7 @@ static int GenerateTarget(FileContents* source_file,
unlink(source_filename); unlink(source_filename);
size_t free_space = FreeSpaceForFile(target_fs); 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 +906,9 @@ static int GenerateTarget(FileContents* source_file,
if (strncmp(target_filename, "MTD:", 4) == 0 || if (strncmp(target_filename, "MTD:", 4) == 0 ||
strncmp(target_filename, "EMMC:", 5) == 0) { strncmp(target_filename, "EMMC:", 5) == 0) {
// We store the decoded output in memory. // 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) { if (msi.buffer == NULL) {
printf("failed to alloc %ld bytes for output\n", printf("failed to alloc %zu bytes for output\n", target_size);
(long)target_size);
return 1; return 1;
} }
msi.pos = 0; msi.pos = 0;
@@ -939,12 +917,11 @@ static int GenerateTarget(FileContents* source_file,
token = &msi; token = &msi;
} else { } else {
// We write the decoded output to "<tgt-file>.patch". // 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); strcpy(outname, target_filename);
strcat(outname, ".patch"); strcat(outname, ".patch");
output = open(outname, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, output = open(outname, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
S_IRUSR | S_IWUSR);
if (output < 0) { if (output < 0) {
printf("failed to open output file %s: %s\n", printf("failed to open output file %s: %s\n",
outname, strerror(errno)); outname, strerror(errno));
@@ -1025,23 +1002,23 @@ static int GenerateTarget(FileContents* source_file,
printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno)); printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
return 1; return 1;
} }
if (chown(outname, source_to_use->st.st_uid, if (chown(outname, source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
source_to_use->st.st_gid) != 0) {
printf("chown of \"%s\" failed: %s\n", outname, strerror(errno)); printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
return 1; return 1;
} }
// Finally, rename the .patch file to replace the target file. // Finally, rename the .patch file to replace the target file.
if (rename(outname, target_filename) != 0) { if (rename(outname, target_filename) != 0) {
printf("rename of .patch to \"%s\" failed: %s\n", printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
target_filename, strerror(errno));
return 1; return 1;
} }
} }
// If this run of applypatch created the copy, and we're here, we // If this run of applypatch created the copy, and we're here, we
// can delete it. // can delete it.
if (made_copy) unlink(CACHE_TEMP_SOURCE); if (made_copy) {
unlink(CACHE_TEMP_SOURCE);
}
// Success! // Success!
return 0; return 0;
+24 -24
View File
@@ -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; 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; off_t i;
for(i=0;(i<oldsize)&&(i<newsize);i++) for(i=0;(i<oldsize)&&(i<newsize);i++)
if(old[i]!=new[i]) break; if(olddata[i]!=newdata[i]) break;
return i; return i;
} }
static off_t search(off_t *I,u_char *old,off_t oldsize, 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; off_t x,y;
if(en-st<2) { if(en-st<2) {
x=matchlen(old+I[st],oldsize-I[st],new,newsize); x=matchlen(old+I[st],oldsize-I[st],newdata,newsize);
y=matchlen(old+I[en],oldsize-I[en],new,newsize); y=matchlen(old+I[en],oldsize-I[en],newdata,newsize);
if(x>y) { if(x>y) {
*pos=I[st]; *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; x=st+(en-st)/2;
if(memcmp(old+I[x],new,MIN(oldsize-I[x],newsize))<0) { if(memcmp(old+I[x],newdata,MIN(oldsize-I[x],newsize))<0) {
return search(I,old,oldsize,new,newsize,x,en,pos); return search(I,old,oldsize,newdata,newsize,x,en,pos);
} else { } 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: // This is main() from bsdiff.c, with the following changes:
// //
// - old, oldsize, new, newsize are arguments; we don't load this // - old, oldsize, newdata, newsize are arguments; we don't load this
// data from files. old and new are owned by the caller; we // data from files. old and newdata are owned by the caller; we
// don't free them at the end. // don't free them at the end.
// //
// - the "I" block of memory is owned by the caller, who passes a // - 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 // bsdiff() multiple times with the same 'old' data, we only do
// the qsufsort() step the first time. // 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) const char* patch_filename)
{ {
int fd; 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) { if (*IP == NULL) {
off_t* V; off_t* V;
*IP = malloc((oldsize+1) * sizeof(off_t)); *IP = reinterpret_cast<off_t*>(malloc((oldsize+1) * sizeof(off_t)));
V = malloc((oldsize+1) * sizeof(off_t)); V = reinterpret_cast<off_t*>(malloc((oldsize+1) * sizeof(off_t)));
qsufsort(*IP, V, old, oldsize); qsufsort(*IP, V, old, oldsize);
free(V); free(V);
} }
I = *IP; I = *IP;
if(((db=malloc(newsize+1))==NULL) || if(((db=reinterpret_cast<u_char*>(malloc(newsize+1)))==NULL) ||
((eb=malloc(newsize+1))==NULL)) err(1,NULL); ((eb=reinterpret_cast<u_char*>(malloc(newsize+1)))==NULL)) err(1,NULL);
dblen=0; dblen=0;
eblen=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; oldscore=0;
for(scsc=scan+=len;scan<newsize;scan++) { 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); 0,oldsize,&pos);
for(;scsc<scan+len;scsc++) for(;scsc<scan+len;scsc++)
if((scsc+lastoffset<oldsize) && if((scsc+lastoffset<oldsize) &&
(old[scsc+lastoffset] == new[scsc])) (old[scsc+lastoffset] == newdata[scsc]))
oldscore++; oldscore++;
if(((len==oldscore) && (len!=0)) || if(((len==oldscore) && (len!=0)) ||
(len>oldscore+8)) break; (len>oldscore+8)) break;
if((scan+lastoffset<oldsize) && if((scan+lastoffset<oldsize) &&
(old[scan+lastoffset] == new[scan])) (old[scan+lastoffset] == newdata[scan]))
oldscore--; oldscore--;
}; };
if((len!=oldscore) || (scan==newsize)) { if((len!=oldscore) || (scan==newsize)) {
s=0;Sf=0;lenf=0; s=0;Sf=0;lenf=0;
for(i=0;(lastscan+i<scan)&&(lastpos+i<oldsize);) { 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++; i++;
if(s*2-i>Sf*2-lenf) { Sf=s; lenf=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) { if(scan<newsize) {
s=0;Sb=0; s=0;Sb=0;
for(i=1;(scan>=lastscan+i)&&(pos>=i);i++) { 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; }; 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); overlap=(lastscan+lenf)-(scan-lenb);
s=0;Ss=0;lens=0; s=0;Ss=0;lens=0;
for(i=0;i<overlap;i++) { for(i=0;i<overlap;i++) {
if(new[lastscan+lenf-overlap+i]== if(newdata[lastscan+lenf-overlap+i]==
old[lastpos+lenf-overlap+i]) s++; old[lastpos+lenf-overlap+i]) s++;
if(new[scan-lenb+i]== if(newdata[scan-lenb+i]==
old[pos-lenb+i]) s--; old[pos-lenb+i]) s--;
if(s>Ss) { Ss=s; lens=i+1; }; 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++) 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++) 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; dblen+=lenf;
eblen+=(scan-lenb)-(lastscan+lenf); eblen+=(scan-lenb)-(lastscan+lenf);
@@ -182,10 +182,9 @@ int ApplyBSDiffPatchMem(const unsigned char* old_data, ssize_t old_size,
printf("failed to bzinit extra stream (%d)\n", bzerr); 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) { if (*new_data == NULL) {
printf("failed to allocate %ld bytes of memory for output file\n", printf("failed to allocate %zd bytes of memory for output file\n", *new_size);
(long)*new_size);
return 1; return 1;
} }
@@ -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 <errno.h>
#include <libgen.h> #include <libgen.h>
#include <stdio.h> #include <stdio.h>
@@ -76,7 +92,7 @@ int FindExpendableFiles(char*** names, int* entries) {
struct dirent* de; struct dirent* de;
int size = 32; int size = 32;
*entries = 0; *entries = 0;
*names = malloc(size * sizeof(char*)); *names = reinterpret_cast<char**>(malloc(size * sizeof(char*)));
char path[FILENAME_MAX]; char path[FILENAME_MAX];
@@ -84,8 +100,7 @@ int FindExpendableFiles(char*** names, int* entries) {
// directories. // directories.
const char* dirs[2] = {"/cache", "/cache/recovery/otatest"}; const char* dirs[2] = {"/cache", "/cache/recovery/otatest"};
unsigned int i; for (size_t i = 0; i < sizeof(dirs)/sizeof(dirs[0]); ++i) {
for (i = 0; i < sizeof(dirs)/sizeof(dirs[0]); ++i) {
d = opendir(dirs[i]); d = opendir(dirs[i]);
if (d == NULL) { if (d == NULL) {
printf("error opening %s: %s\n", dirs[i], strerror(errno)); 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 (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
if (*entries >= size) { if (*entries >= size) {
size *= 2; size *= 2;
*names = realloc(*names, size * sizeof(char*)); *names = reinterpret_cast<char**>(realloc(*names, size * sizeof(char*)));
} }
(*names)[(*entries)++] = strdup(path); (*names)[(*entries)++] = strdup(path);
} }
@@ -127,8 +142,7 @@ int FindExpendableFiles(char*** names, int* entries) {
int MakeFreeSpaceOnCache(size_t bytes_needed) { int MakeFreeSpaceOnCache(size_t bytes_needed) {
size_t free_now = FreeSpaceForFile("/cache"); size_t free_now = FreeSpaceForFile("/cache");
printf("%ld bytes free on /cache (%ld needed)\n", printf("%zu bytes free on /cache (%zu needed)\n", free_now, bytes_needed);
(long)free_now, (long)bytes_needed);
if (free_now >= bytes_needed) { if (free_now >= bytes_needed) {
return 0; return 0;
@@ -158,7 +172,7 @@ int MakeFreeSpaceOnCache(size_t bytes_needed) {
if (names[i]) { if (names[i]) {
unlink(names[i]); unlink(names[i]);
free_now = FreeSpaceForFile("/cache"); 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]); free(names[i]);
} }
} }
+46 -38
View File
@@ -122,6 +122,7 @@
*/ */
#include <errno.h> #include <errno.h>
#include <inttypes.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@@ -179,7 +180,7 @@ static int fileentry_compare(const void* a, const void* b) {
} }
// from bsdiff.c // 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); const char* patch_filename);
unsigned char* ReadZip(const char* filename, unsigned char* ReadZip(const char* filename,
@@ -191,9 +192,10 @@ unsigned char* ReadZip(const char* filename,
return NULL; 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"); 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)); printf("failed to read \"%s\" %s\n", filename, strerror(errno));
fclose(f); fclose(f);
return NULL; return NULL;
@@ -218,7 +220,8 @@ unsigned char* ReadZip(const char* filename,
int cdcount = Read2(img+i+8); int cdcount = Read2(img+i+8);
int cdoffset = Read4(img+i+16); 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; int entrycount = 0;
unsigned char* cd = img+cdoffset; unsigned char* cd = img+cdoffset;
@@ -235,7 +238,7 @@ unsigned char* ReadZip(const char* filename,
int mlen = Read2(cd+32); // file comment len int mlen = Read2(cd+32); // file comment len
int hoffset = Read4(cd+42); // local header offset 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); memcpy(filename, cd+46, nlen);
filename[nlen] = '\0'; filename[nlen] = '\0';
@@ -284,7 +287,7 @@ unsigned char* ReadZip(const char* filename,
#endif #endif
*num_chunks = 0; *num_chunks = 0;
*chunks = malloc((entrycount*2+2) * sizeof(ImageChunk)); *chunks = reinterpret_cast<ImageChunk*>(malloc((entrycount*2+2) * sizeof(ImageChunk)));
ImageChunk* curr = *chunks; ImageChunk* curr = *chunks;
if (include_pseudo_chunk) { if (include_pseudo_chunk) {
@@ -311,7 +314,7 @@ unsigned char* ReadZip(const char* filename,
curr->I = NULL; curr->I = NULL;
curr->len = temp_entries[nextentry].uncomp_len; curr->len = temp_entries[nextentry].uncomp_len;
curr->data = malloc(curr->len); curr->data = reinterpret_cast<unsigned char*>(malloc(curr->len));
z_stream strm; z_stream strm;
strm.zalloc = Z_NULL; strm.zalloc = Z_NULL;
@@ -381,9 +384,10 @@ unsigned char* ReadImage(const char* filename,
return NULL; 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"); 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)); printf("failed to read \"%s\" %s\n", filename, strerror(errno));
fclose(f); fclose(f);
return NULL; 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 // 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 // four-byte string 1f8b0800 starting at any point in the actual
// file data, without special-casing the end of the data. // 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; size_t pos = 0;
*num_chunks = 0; *num_chunks = 0;
*chunks = NULL; *chunks = NULL;
while (pos < st.st_size) { while (pos < sz) {
unsigned char* p = img+pos; unsigned char* p = img+pos;
if (st.st_size - pos >= 4 && if (sz - pos >= 4 &&
p[0] == 0x1f && p[1] == 0x8b && p[0] == 0x1f && p[1] == 0x8b &&
p[2] == 0x08 && // deflate compression p[2] == 0x08 && // deflate compression
p[3] == 0x00) { // no header flags p[3] == 0x00) { // no header flags
@@ -411,7 +415,8 @@ unsigned char* ReadImage(const char* filename,
size_t chunk_offset = pos; size_t chunk_offset = pos;
*num_chunks += 3; *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); ImageChunk* curr = *chunks + (*num_chunks-3);
// create a normal chunk for the header. // create a normal chunk for the header.
@@ -435,7 +440,7 @@ unsigned char* ReadImage(const char* filename,
size_t allocated = 32768; size_t allocated = 32768;
curr->len = 0; curr->len = 0;
curr->data = malloc(allocated); curr->data = reinterpret_cast<unsigned char*>(malloc(allocated));
curr->start = pos; curr->start = pos;
curr->deflate_data = p; curr->deflate_data = p;
@@ -443,7 +448,7 @@ unsigned char* ReadImage(const char* filename,
strm.zalloc = Z_NULL; strm.zalloc = Z_NULL;
strm.zfree = Z_NULL; strm.zfree = Z_NULL;
strm.opaque = Z_NULL; strm.opaque = Z_NULL;
strm.avail_in = st.st_size - pos; strm.avail_in = sz - pos;
strm.next_in = p; strm.next_in = p;
// -15 means we are decoding a 'raw' deflate stream; zlib will // -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; curr->len = allocated - strm.avail_out;
if (strm.avail_out == 0) { if (strm.avail_out == 0) {
allocated *= 2; allocated *= 2;
curr->data = realloc(curr->data, allocated); curr->data = reinterpret_cast<unsigned char*>(realloc(curr->data, allocated));
} }
} while (ret != Z_STREAM_END); } 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); inflateEnd(&strm);
pos += curr->deflate_len; pos += curr->deflate_len;
p += curr->deflate_len; p += curr->deflate_len;
@@ -493,8 +498,8 @@ unsigned char* ReadImage(const char* filename,
// the decompression. // the decompression.
size_t footer_size = Read4(p-4); size_t footer_size = Read4(p-4);
if (footer_size != curr[-2].len) { if (footer_size != curr[-2].len) {
printf("Error: footer size %d != decompressed size %d\n", printf("Error: footer size %zu != decompressed size %zu\n",
footer_size, curr[-2].len); footer_size, curr[-2].len);
free(img); free(img);
return NULL; return NULL;
} }
@@ -502,7 +507,7 @@ unsigned char* ReadImage(const char* filename,
// Reallocate the list for every chunk; we expect the number of // Reallocate the list for every chunk; we expect the number of
// chunks to be small (5 for typical boot and recovery images). // chunks to be small (5 for typical boot and recovery images).
++*num_chunks; ++*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); ImageChunk* curr = *chunks + (*num_chunks-1);
curr->start = pos; curr->start = pos;
curr->I = NULL; curr->I = NULL;
@@ -512,7 +517,7 @@ unsigned char* ReadImage(const char* filename,
curr->type = CHUNK_NORMAL; curr->type = CHUNK_NORMAL;
curr->data = p; 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 && if (p[curr->len] == 0x1f &&
p[curr->len+1] == 0x8b && p[curr->len+1] == 0x8b &&
p[curr->len+2] == 0x08 && p[curr->len+2] == 0x08 &&
@@ -587,7 +592,7 @@ int ReconstructDeflateChunk(ImageChunk* chunk) {
} }
size_t p = 0; 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 // We only check two combinations of encoder parameters: level 6
// (the default) and level 9 (the maximum). // (the default) and level 9 (the maximum).
@@ -638,9 +643,11 @@ unsigned char* MakePatch(ImageChunk* src, ImageChunk* tgt, size_t* size) {
return NULL; 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); unlink(ptemp);
tgt->type = CHUNK_RAW; tgt->type = CHUNK_RAW;
@@ -648,14 +655,14 @@ unsigned char* MakePatch(ImageChunk* src, ImageChunk* tgt, size_t* size) {
return tgt->data; return tgt->data;
} }
*size = st.st_size; *size = sz;
FILE* f = fopen(ptemp, "rb"); FILE* f = fopen(ptemp, "rb");
if (f == NULL) { if (f == NULL) {
printf("failed to open patch %s: %s\n", ptemp, strerror(errno)); printf("failed to open patch %s: %s\n", ptemp, strerror(errno));
return NULL; 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)); printf("failed to read patch %s: %s\n", ptemp, strerror(errno));
return NULL; return NULL;
} }
@@ -781,9 +788,8 @@ ImageChunk* FindChunkByName(const char* name,
} }
void DumpChunks(ImageChunk* chunks, int num_chunks) { void DumpChunks(ImageChunk* chunks, int num_chunks) {
int i; for (int i = 0; i < num_chunks; ++i) {
for (i = 0; i < num_chunks; ++i) { printf("chunk %d: type %d start %zu len %zu\n",
printf("chunk %d: type %d start %d len %d\n",
i, chunks[i].type, chunks[i].start, chunks[i].len); i, chunks[i].type, chunks[i].start, chunks[i].len);
} }
} }
@@ -806,7 +812,7 @@ int main(int argc, char** argv) {
return 1; return 1;
} }
bonus_size = st.st_size; 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"); FILE* f = fopen(argv[2], "rb");
if (f == NULL) { if (f == NULL) {
printf("failed to open bonus file %s: %s\n", argv[2], strerror(errno)); 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); DumpChunks(src_chunks, num_src_chunks);
printf("Construct patches for %d chunks...\n", num_tgt_chunks); printf("Construct patches for %d chunks...\n", num_tgt_chunks);
unsigned char** patch_data = malloc(num_tgt_chunks * sizeof(unsigned char*)); unsigned char** patch_data = reinterpret_cast<unsigned char**>(malloc(
size_t* patch_size = malloc(num_tgt_chunks * sizeof(size_t)); 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) { for (i = 0; i < num_tgt_chunks; ++i) {
if (zip_mode) { if (zip_mode) {
ImageChunk* src; ImageChunk* src;
@@ -967,15 +974,16 @@ int main(int argc, char** argv) {
} }
} else { } else {
if (i == 1 && bonus_data) { if (i == 1 && bonus_data) {
printf(" using %d bytes of bonus data for chunk %d\n", bonus_size, i); printf(" using %zu 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); 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); memcpy(src_chunks[i].data+src_chunks[i].len, bonus_data, bonus_size);
src_chunks[i].len += bonus_size; src_chunks[i].len += bonus_size;
} }
patch_data[i] = MakePatch(src_chunks+i, tgt_chunks+i, patch_size+i); 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); i, patch_size[i], tgt_chunks[i].source_len);
} }
@@ -1012,7 +1020,7 @@ int main(int argc, char** argv) {
switch (tgt_chunks[i].type) { switch (tgt_chunks[i].type) {
case CHUNK_NORMAL: 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]); tgt_chunks[i].start, tgt_chunks[i].len, patch_size[i]);
Write8(tgt_chunks[i].source_start, f); Write8(tgt_chunks[i].source_start, f);
Write8(tgt_chunks[i].source_len, f); Write8(tgt_chunks[i].source_len, f);
@@ -1021,7 +1029,7 @@ int main(int argc, char** argv) {
break; break;
case CHUNK_DEFLATE: 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].start, tgt_chunks[i].deflate_len, patch_size[i],
tgt_chunks[i].filename); tgt_chunks[i].filename);
Write8(tgt_chunks[i].source_start, f); Write8(tgt_chunks[i].source_start, f);
@@ -1038,7 +1046,7 @@ int main(int argc, char** argv) {
break; break;
case CHUNK_RAW: 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); tgt_chunks[i].start, tgt_chunks[i].len);
Write4(patch_size[i], f); Write4(patch_size[i], f);
fwrite(patch_data[i], 1, patch_size[i], f); fwrite(patch_data[i], 1, patch_size[i], f);
@@ -132,7 +132,7 @@ int ApplyImagePatch(const unsigned char* old_data, ssize_t old_size __unused,
// must be appended from the bonus_data value. // must be appended from the bonus_data value.
size_t bonus_size = (i == 1 && bonus_data != NULL) ? bonus_data->size : 0; 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) { if (expanded_source == NULL) {
printf("failed to allocate %zu bytes for expanded_source\n", printf("failed to allocate %zu bytes for expanded_source\n",
expanded_len); 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 // ... unless the buffer is too small, in which case we'll
// allocate a fresh one. // allocate a fresh one.
free(temp_data); free(temp_data);
temp_data = malloc(32768); temp_data = reinterpret_cast<unsigned char*>(malloc(32768));
temp_size = 32768; temp_size = 32768;
} }
+15 -16
View File
@@ -23,14 +23,14 @@
#include "edify/expr.h" #include "edify/expr.h"
#include "mincrypt/sha.h" #include "mincrypt/sha.h"
int CheckMode(int argc, char** argv) { static int CheckMode(int argc, char** argv) {
if (argc < 3) { if (argc < 3) {
return 2; return 2;
} }
return applypatch_check(argv[2], argc-3, argv+3); 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) { if (argc != 3) {
return 2; return 2;
} }
@@ -45,19 +45,18 @@ int SpaceMode(int argc, char** argv) {
// Parse arguments (which should be of the form "<sha1>" or // Parse arguments (which should be of the form "<sha1>" or
// "<sha1>:<filename>" into the new parallel arrays *sha1s and // "<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. // success.
static int ParsePatchArgs(int argc, char** argv, static bool ParsePatchArgs(int argc, char** argv,
char*** sha1s, Value*** patches, int* num_patches) { char*** sha1s, Value*** patches, int* num_patches) {
*num_patches = argc; *num_patches = argc;
*sha1s = malloc(*num_patches * sizeof(char*)); *sha1s = reinterpret_cast<char**>(malloc(*num_patches * sizeof(char*)));
*patches = malloc(*num_patches * sizeof(Value*)); *patches = reinterpret_cast<Value**>(malloc(*num_patches * sizeof(Value*)));
memset(*patches, 0, *num_patches * sizeof(Value*)); memset(*patches, 0, *num_patches * sizeof(Value*));
uint8_t digest[SHA_DIGEST_SIZE]; uint8_t digest[SHA_DIGEST_SIZE];
int i; for (int i = 0; i < *num_patches; ++i) {
for (i = 0; i < *num_patches; ++i) {
char* colon = strchr(argv[i], ':'); char* colon = strchr(argv[i], ':');
if (colon != NULL) { if (colon != NULL) {
*colon = '\0'; *colon = '\0';
@@ -66,7 +65,7 @@ static int ParsePatchArgs(int argc, char** argv,
if (ParseSha1(argv[i], digest) != 0) { if (ParseSha1(argv[i], digest) != 0) {
printf("failed to parse sha1 \"%s\"\n", argv[i]); printf("failed to parse sha1 \"%s\"\n", argv[i]);
return -1; return false;
} }
(*sha1s)[i] = argv[i]; (*sha1s)[i] = argv[i];
@@ -77,17 +76,17 @@ static int ParsePatchArgs(int argc, char** argv,
if (LoadFileContents(colon, &fc) != 0) { if (LoadFileContents(colon, &fc) != 0) {
goto abort; goto abort;
} }
(*patches)[i] = malloc(sizeof(Value)); (*patches)[i] = reinterpret_cast<Value*>(malloc(sizeof(Value)));
(*patches)[i]->type = VAL_BLOB; (*patches)[i]->type = VAL_BLOB;
(*patches)[i]->size = fc.size; (*patches)[i]->size = fc.size;
(*patches)[i]->data = (char*)fc.data; (*patches)[i]->data = reinterpret_cast<char*>(fc.data);
} }
} }
return 0; return true;
abort: abort:
for (i = 0; i < *num_patches; ++i) { for (int i = 0; i < *num_patches; ++i) {
Value* p = (*patches)[i]; Value* p = (*patches)[i];
if (p != NULL) { if (p != NULL) {
free(p->data); free(p->data);
@@ -96,7 +95,7 @@ static int ParsePatchArgs(int argc, char** argv,
} }
free(*sha1s); free(*sha1s);
free(*patches); free(*patches);
return -1; return false;
} }
int PatchMode(int argc, char** argv) { int PatchMode(int argc, char** argv) {
@@ -107,7 +106,7 @@ int PatchMode(int argc, char** argv) {
printf("failed to load bonus file %s\n", argv[2]); printf("failed to load bonus file %s\n", argv[2]);
return 1; return 1;
} }
bonus = malloc(sizeof(Value)); bonus = reinterpret_cast<Value*>(malloc(sizeof(Value)));
bonus->type = VAL_BLOB; bonus->type = VAL_BLOB;
bonus->size = fc.size; bonus->size = fc.size;
bonus->data = (char*)fc.data; bonus->data = (char*)fc.data;
@@ -129,7 +128,7 @@ int PatchMode(int argc, char** argv) {
char** sha1s; char** sha1s;
Value** patches; Value** patches;
int num_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"); printf("failed to parse patch args\n");
return 1; return 1;
} }
+3 -3
View File
@@ -39,13 +39,13 @@ void Write8(long long value, FILE* f) {
} }
int Read2(void* pv) { int Read2(void* pv) {
unsigned char* p = pv; unsigned char* p = reinterpret_cast<unsigned char*>(pv);
return (int)(((unsigned int)p[1] << 8) | return (int)(((unsigned int)p[1] << 8) |
(unsigned int)p[0]); (unsigned int)p[0]);
} }
int Read4(void* pv) { int Read4(void* pv) {
unsigned char* p = pv; unsigned char* p = reinterpret_cast<unsigned char*>(pv);
return (int)(((unsigned int)p[3] << 24) | return (int)(((unsigned int)p[3] << 24) |
((unsigned int)p[2] << 16) | ((unsigned int)p[2] << 16) |
((unsigned int)p[1] << 8) | ((unsigned int)p[1] << 8) |
@@ -53,7 +53,7 @@ int Read4(void* pv) {
} }
long long Read8(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) | return (long long)(((unsigned long long)p[7] << 56) |
((unsigned long long)p[6] << 48) | ((unsigned long long)p[6] << 48) |
((unsigned long long)p[5] << 40) | ((unsigned long long)p[5] << 40) |
+8
View File
@@ -15,6 +15,10 @@
#include <stdbool.h> #include <stdbool.h>
#include <assert.h> #include <assert.h>
#ifdef __cplusplus
extern "C" {
#endif
/* compute the hash of an item with a specific type */ /* compute the hash of an item with a specific type */
typedef unsigned int (*HashCompute)(const void* item); typedef unsigned int (*HashCompute)(const void* item);
@@ -183,4 +187,8 @@ typedef unsigned int (*HashCalcFunc)(const void* item);
void mzHashTableProbeCount(HashTable* pHashTable, HashCalcFunc calcFunc, void mzHashTableProbeCount(HashTable* pHashTable, HashCalcFunc calcFunc,
HashCompareFunc cmpFunc); HashCompareFunc cmpFunc);
#ifdef __cplusplus
}
#endif
#endif /*_MINZIP_HASH*/ #endif /*_MINZIP_HASH*/
-2
View File
@@ -30,10 +30,8 @@
#include "roots.h" #include "roots.h"
#include "common.h" #include "common.h"
#include "make_ext4fs.h" #include "make_ext4fs.h"
extern "C" {
#include "wipe.h" #include "wipe.h"
#include "cryptfs.h" #include "cryptfs.h"
}
static struct fstab *fstab = NULL; static struct fstab *fstab = NULL;
+15 -3
View File
@@ -1,11 +1,23 @@
# Copyright 2009 The Android Open Source Project # 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) LOCAL_PATH := $(call my-dir)
updater_src_files := \ updater_src_files := \
install.c \ install.cpp \
blockimg.c \ blockimg.cpp \
updater.c updater.cpp
# #
# Build a statically-linked binary to include in OTA packages # Build a statically-linked binary to include in OTA packages
+14 -17
View File
@@ -20,6 +20,7 @@
#include <fcntl.h> #include <fcntl.h>
#include <inttypes.h> #include <inttypes.h>
#include <libgen.h> #include <libgen.h>
#include <linux/fs.h>
#include <pthread.h> #include <pthread.h>
#include <stdarg.h> #include <stdarg.h>
#include <stdio.h> #include <stdio.h>
@@ -45,10 +46,6 @@
// erase to mean fill the region with zeroes. // erase to mean fill the region with zeroes.
#define DEBUG_ERASE 0 #define DEBUG_ERASE 0
#ifndef BLKDISCARD
#define BLKDISCARD _IO(0x12,119)
#endif
#define STASH_DIRECTORY_BASE "/cache/recovery" #define STASH_DIRECTORY_BASE "/cache/recovery"
#define STASH_DIRECTORY_MODE 0700 #define STASH_DIRECTORY_MODE 0700
#define STASH_FILE_MODE 0600 #define STASH_FILE_MODE 0600
@@ -67,7 +64,7 @@ typedef struct {
static RangeSet* parse_range(char* text) { static RangeSet* parse_range(char* text) {
char* save; char* save;
char* token; char* token;
int i, num; int num;
long int val; long int val;
RangeSet* out = NULL; RangeSet* out = NULL;
size_t bufsize; size_t bufsize;
@@ -93,7 +90,7 @@ static RangeSet* parse_range(char* text) {
num = (int) val; num = (int) val;
bufsize = sizeof(RangeSet) + num * sizeof(int); bufsize = sizeof(RangeSet) + num * sizeof(int);
out = malloc(bufsize); out = reinterpret_cast<RangeSet*>(malloc(bufsize));
if (!out) { if (!out) {
fprintf(stderr, "failed to allocate range of %zu bytes\n", bufsize); fprintf(stderr, "failed to allocate range of %zu bytes\n", bufsize);
@@ -103,7 +100,7 @@ static RangeSet* parse_range(char* text) {
out->count = num / 2; out->count = num / 2;
out->size = 0; out->size = 0;
for (i = 0; i < num; ++i) { for (int i = 0; i < num; ++i) {
token = strtok_r(NULL, ",", &save); token = strtok_r(NULL, ",", &save);
if (!token) { if (!token) {
@@ -478,7 +475,7 @@ static char* GetStashFileName(const char* base, const char* id, const char* post
} }
len = strlen(STASH_DIRECTORY_BASE) + 1 + strlen(base) + 1 + strlen(id) + strlen(postfix) + 1; len = strlen(STASH_DIRECTORY_BASE) + 1 + strlen(base) + 1 + strlen(id) + strlen(postfix) + 1;
fn = malloc(len); fn = reinterpret_cast<char*>(malloc(len));
if (fn == NULL) { if (fn == NULL) {
fprintf(stderr, "failed to malloc %d bytes for fn\n", len); fprintf(stderr, "failed to malloc %d bytes for fn\n", len);
@@ -529,7 +526,7 @@ static void EnumerateStash(const char* dirname, StashCallback callback, void* da
} }
len = strlen(dirname) + 1 + strlen(item->d_name) + 1; len = strlen(dirname) + 1 + strlen(item->d_name) + 1;
fn = malloc(len); fn = reinterpret_cast<char*>(malloc(len));
if (fn == NULL) { if (fn == NULL) {
fprintf(stderr, "failed to malloc %d bytes for fn\n", len); fprintf(stderr, "failed to malloc %d bytes for fn\n", len);
@@ -649,7 +646,8 @@ static int LoadStash(const char* base, const char* id, int verify, int* blocks,
fprintf(stderr, " loading %s\n", fn); fprintf(stderr, " loading %s\n", fn);
if ((st.st_size % BLOCKSIZE) != 0) { if ((st.st_size % BLOCKSIZE) != 0) {
fprintf(stderr, "%s size %zd not multiple of block size %d", fn, st.st_size, BLOCKSIZE); fprintf(stderr, "%s size %" PRId64 " not multiple of block size %d",
fn, static_cast<int64_t>(st.st_size), BLOCKSIZE);
goto lsout; goto lsout;
} }
@@ -876,7 +874,6 @@ csout:
static int SaveStash(const char* base, char** wordsave, uint8_t** buffer, size_t* buffer_alloc, static int SaveStash(const char* base, char** wordsave, uint8_t** buffer, size_t* buffer_alloc,
int fd, int usehash, int* isunresumable) { int fd, int usehash, int* isunresumable) {
char *id = NULL; char *id = NULL;
int res = -1;
int blocks = 0; int blocks = 0;
if (!wordsave || !buffer || !buffer_alloc || !isunresumable) { if (!wordsave || !buffer || !buffer_alloc || !isunresumable) {
@@ -972,7 +969,6 @@ static int LoadSrcTgtVersion2(char** wordsave, RangeSet** tgt, int* src_blocks,
char* word; char* word;
char* colonsave; char* colonsave;
char* colon; char* colon;
int id;
int res; int res;
RangeSet* locs; RangeSet* locs;
size_t stashalloc = 0; size_t stashalloc = 0;
@@ -1088,7 +1084,6 @@ static int LoadSrcTgtVersion3(CommandParameters* params, RangeSet** tgt, int* sr
char* srchash = NULL; char* srchash = NULL;
char* tgthash = NULL; char* tgthash = NULL;
int stash_exists = 0; int stash_exists = 0;
int overlap_blocks = 0;
int rc = -1; int rc = -1;
uint8_t* tgtbuffer = NULL; uint8_t* tgtbuffer = NULL;
@@ -1511,7 +1506,7 @@ static int PerformCommandErase(CommandParameters* params) {
range = strtok_r(NULL, " ", &params->cpos); range = strtok_r(NULL, " ", &params->cpos);
if (range == NULL) { if (range == NULL) {
fprintf(stderr, "missing target blocks for zero\n"); fprintf(stderr, "missing target blocks for erase\n");
goto pceout; goto pceout;
} }
@@ -1686,7 +1681,7 @@ static Value* PerformBlockImageUpdate(const char* name, State* state, int argc,
// The data in transfer_list_value is not necessarily null-terminated, so we need // 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. // 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 == NULL) {
fprintf(stderr, "failed to allocate %zd bytes for transfer list\n", fprintf(stderr, "failed to allocate %zd bytes for transfer list\n",
@@ -1964,13 +1959,15 @@ Value* RangeSha1Fn(const char* name, State* state, int argc, Expr* argv[]) {
goto done; goto done;
} }
int fd = open(blockdev_filename->data, O_RDWR); int fd;
fd = open(blockdev_filename->data, O_RDWR);
if (fd < 0) { if (fd < 0) {
ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno)); ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno));
goto done; goto done;
} }
RangeSet* rs = parse_range(ranges->data); RangeSet* rs;
rs = parse_range(ranges->data);
uint8_t buffer[BLOCKSIZE]; uint8_t buffer[BLOCKSIZE];
SHA_CTX ctx; SHA_CTX ctx;
+83 -91
View File
@@ -75,9 +75,9 @@ void uiPrintf(State* state, const char* format, ...) {
// Take a sha-1 digest and return it as a newly-allocated hex string. // Take a sha-1 digest and return it as a newly-allocated hex string.
char* PrintSha1(const uint8_t* digest) { char* PrintSha1(const uint8_t* digest) {
char* buffer = malloc(SHA_DIGEST_SIZE*2 + 1); char* buffer = reinterpret_cast<char*>(malloc(SHA_DIGEST_SIZE*2 + 1));
int i;
const char* alphabet = "0123456789abcdef"; const char* alphabet = "0123456789abcdef";
size_t i;
for (i = 0; i < SHA_DIGEST_SIZE; ++i) { for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
buffer[i*2] = alphabet[(digest[i] >> 4) & 0xf]; buffer[i*2] = alphabet[(digest[i] >> 4) & 0xf];
buffer[i*2+1] = alphabet[digest[i] & 0xf]; buffer[i*2+1] = alphabet[digest[i] & 0xf];
@@ -133,18 +133,20 @@ Value* MountFn(const char* name, State* state, int argc, Expr* argv[]) {
goto done; goto done;
} }
char *secontext = NULL; {
char *secontext = NULL;
if (sehandle) { if (sehandle) {
selabel_lookup(sehandle, &secontext, mount_point, 0755); selabel_lookup(sehandle, &secontext, mount_point, 0755);
setfscreatecon(secontext); setfscreatecon(secontext);
} }
mkdir(mount_point, 0755); mkdir(mount_point, 0755);
if (secontext) { if (secontext) {
freecon(secontext); freecon(secontext);
setfscreatecon(NULL); setfscreatecon(NULL);
}
} }
if (strcmp(partition_type, "MTD") == 0) { if (strcmp(partition_type, "MTD") == 0) {
@@ -202,11 +204,13 @@ Value* IsMountedFn(const char* name, State* state, int argc, Expr* argv[]) {
} }
scan_mounted_volumes(); scan_mounted_volumes();
const MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point); {
if (vol == NULL) { const MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point);
result = strdup(""); if (vol == NULL) {
} else { result = strdup("");
result = mount_point; } else {
result = mount_point;
}
} }
done: done:
@@ -230,17 +234,19 @@ Value* UnmountFn(const char* name, State* state, int argc, Expr* argv[]) {
} }
scan_mounted_volumes(); scan_mounted_volumes();
const MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point); {
if (vol == NULL) { const MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point);
uiPrintf(state, "unmount of %s failed; no such volume\n", mount_point); if (vol == NULL) {
result = strdup(""); uiPrintf(state, "unmount of %s failed; no such volume\n", mount_point);
} else { result = strdup("");
int ret = unmount_mounted_volume(vol); } else {
if (ret != 0) { int ret = unmount_mounted_volume(vol);
uiPrintf(state, "unmount of %s failed (%d): %s\n", if (ret != 0) {
mount_point, ret, strerror(errno)); uiPrintf(state, "unmount of %s failed (%d): %s\n",
mount_point, ret, strerror(errno));
}
result = mount_point;
} }
result = mount_point;
} }
done: done:
@@ -413,9 +419,8 @@ done:
} }
Value* DeleteFn(const char* name, State* state, int argc, Expr* argv[]) { Value* DeleteFn(const char* name, State* state, int argc, Expr* argv[]) {
char** paths = malloc(argc * sizeof(char*)); char** paths = reinterpret_cast<char**>(malloc(argc * sizeof(char*)));
int i; for (int i = 0; i < argc; ++i) {
for (i = 0; i < argc; ++i) {
paths[i] = Evaluate(state, argv[i]); paths[i] = Evaluate(state, argv[i]);
if (paths[i] == NULL) { if (paths[i] == NULL) {
int j; int j;
@@ -430,7 +435,7 @@ Value* DeleteFn(const char* name, State* state, int argc, Expr* argv[]) {
bool recursive = (strcmp(name, "delete_recursive") == 0); bool recursive = (strcmp(name, "delete_recursive") == 0);
int success = 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) if ((recursive ? dirUnlinkHierarchy(paths[i]) : unlink(paths[i])) == 0)
++success; ++success;
free(paths[i]); free(paths[i]);
@@ -517,8 +522,6 @@ Value* PackageExtractFileFn(const char* name, State* state,
} }
bool success = false; bool success = false;
UpdaterInfo* ui = (UpdaterInfo*)(state->cookie);
if (argc == 2) { if (argc == 2) {
// The two-argument version extracts to a file. // The two-argument version extracts to a file.
@@ -534,14 +537,16 @@ Value* PackageExtractFileFn(const char* name, State* state,
goto done2; goto done2;
} }
FILE* f = fopen(dest_path, "wb"); {
if (f == NULL) { FILE* f = fopen(dest_path, "wb");
printf("%s: can't open %s for write: %s\n", if (f == NULL) {
name, dest_path, strerror(errno)); printf("%s: can't open %s for write: %s\n",
goto done2; name, dest_path, strerror(errno));
goto done2;
}
success = mzExtractZipEntryToFile(za, entry, fileno(f));
fclose(f);
} }
success = mzExtractZipEntryToFile(za, entry, fileno(f));
fclose(f);
done2: done2:
free(zip_path); free(zip_path);
@@ -552,7 +557,7 @@ Value* PackageExtractFileFn(const char* name, State* state,
// as the result. // as the result.
char* zip_path; char* zip_path;
Value* v = malloc(sizeof(Value)); Value* v = reinterpret_cast<Value*>(malloc(sizeof(Value)));
v->type = VAL_BLOB; v->type = VAL_BLOB;
v->size = -1; v->size = -1;
v->data = NULL; v->data = NULL;
@@ -567,7 +572,7 @@ Value* PackageExtractFileFn(const char* name, State* state,
} }
v->size = mzGetZipEntryUncompLen(entry); v->size = mzGetZipEntryUncompLen(entry);
v->data = malloc(v->size); v->data = reinterpret_cast<char*>(malloc(v->size));
if (v->data == NULL) { if (v->data == NULL) {
printf("%s: failed to allocate %ld bytes for %s\n", printf("%s: failed to allocate %ld bytes for %s\n",
name, (long)v->size, zip_path); name, (long)v->size, zip_path);
@@ -866,17 +871,14 @@ static int do_SetMetadataRecursive(const char* filename, const struct stat *stat
} }
static Value* SetMetadataFn(const char* name, State* state, int argc, Expr* argv[]) { static Value* SetMetadataFn(const char* name, State* state, int argc, Expr* argv[]) {
int i;
int bad = 0; int bad = 0;
static int nwarnings = 0;
struct stat sb; struct stat sb;
Value* result = NULL; Value* result = NULL;
bool recursive = (strcmp(name, "set_metadata_recursive") == 0); bool recursive = (strcmp(name, "set_metadata_recursive") == 0);
if ((argc % 2) != 1) { if ((argc % 2) != 1) {
return ErrorAbort(state, "%s() expects an odd number of arguments, got %d", return ErrorAbort(state, "%s() expects an odd number of arguments, got %d", name, argc);
name, argc);
} }
char** args = ReadVarArgs(state, argc, argv); char** args = ReadVarArgs(state, argc, argv);
@@ -887,20 +889,22 @@ static Value* SetMetadataFn(const char* name, State* state, int argc, Expr* argv
goto done; goto done;
} }
struct perm_parsed_args parsed = ParsePermArgs(state, argc, args); {
struct perm_parsed_args parsed = ParsePermArgs(state, argc, args);
if (recursive) { if (recursive) {
recursive_parsed_args = parsed; recursive_parsed_args = parsed;
recursive_state = state; recursive_state = state;
bad += nftw(args[0], do_SetMetadataRecursive, 30, FTW_CHDIR | FTW_DEPTH | FTW_PHYS); bad += nftw(args[0], do_SetMetadataRecursive, 30, FTW_CHDIR | FTW_DEPTH | FTW_PHYS);
memset(&recursive_parsed_args, 0, sizeof(recursive_parsed_args)); memset(&recursive_parsed_args, 0, sizeof(recursive_parsed_args));
recursive_state = NULL; recursive_state = NULL;
} else { } else {
bad += ApplyParsedPerms(state, args[0], &sb, parsed); bad += ApplyParsedPerms(state, args[0], &sb, parsed);
}
} }
done: done:
for (i = 0; i < argc; ++i) { for (int i = 0; i < argc; ++i) {
free(args[i]); free(args[i]);
} }
free(args); free(args);
@@ -920,8 +924,7 @@ Value* GetPropFn(const char* name, State* state, int argc, Expr* argv[]) {
if (argc != 1) { if (argc != 1) {
return ErrorAbort(state, "%s() expects 1 arg, got %d", name, argc); return ErrorAbort(state, "%s() expects 1 arg, got %d", name, argc);
} }
char* key; char* key = Evaluate(state, argv[0]);
key = Evaluate(state, argv[0]);
if (key == NULL) return NULL; if (key == NULL) return NULL;
char value[PROPERTY_VALUE_MAX]; char value[PROPERTY_VALUE_MAX];
@@ -948,29 +951,27 @@ Value* FileGetPropFn(const char* name, State* state, int argc, Expr* argv[]) {
struct stat st; struct stat st;
if (stat(filename, &st) < 0) { if (stat(filename, &st) < 0) {
ErrorAbort(state, "%s: failed to stat \"%s\": %s", ErrorAbort(state, "%s: failed to stat \"%s\": %s", name, filename, strerror(errno));
name, filename, strerror(errno));
goto done; goto done;
} }
#define MAX_FILE_GETPROP_SIZE 65536 #define MAX_FILE_GETPROP_SIZE 65536
if (st.st_size > MAX_FILE_GETPROP_SIZE) { if (st.st_size > MAX_FILE_GETPROP_SIZE) {
ErrorAbort(state, "%s too large for %s (max %d)", ErrorAbort(state, "%s too large for %s (max %d)", filename, name, MAX_FILE_GETPROP_SIZE);
filename, name, MAX_FILE_GETPROP_SIZE);
goto done; goto done;
} }
buffer = malloc(st.st_size+1); buffer = reinterpret_cast<char*>(malloc(st.st_size+1));
if (buffer == NULL) { if (buffer == NULL) {
ErrorAbort(state, "%s: failed to alloc %lld bytes", name, (long long)st.st_size+1); ErrorAbort(state, "%s: failed to alloc %lld bytes", name, (long long)st.st_size+1);
goto done; goto done;
} }
FILE* f = fopen(filename, "rb"); FILE* f;
f = fopen(filename, "rb");
if (f == NULL) { if (f == NULL) {
ErrorAbort(state, "%s: failed to open %s: %s", ErrorAbort(state, "%s: failed to open %s: %s", name, filename, strerror(errno));
name, filename, strerror(errno));
goto done; goto done;
} }
@@ -984,7 +985,8 @@ Value* FileGetPropFn(const char* name, State* state, int argc, Expr* argv[]) {
fclose(f); fclose(f);
char* line = strtok(buffer, "\n"); char* line;
line = strtok(buffer, "\n");
do { do {
// skip whitespace at start of line // skip whitespace at start of line
while (*line && isspace(*line)) ++line; while (*line && isspace(*line)) ++line;
@@ -1028,15 +1030,6 @@ Value* FileGetPropFn(const char* name, State* state, int argc, Expr* argv[]) {
return StringValue(result); 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) // write_raw_image(filename_or_blob, partition)
Value* WriteRawImageFn(const char* name, State* state, int argc, Expr* argv[]) { Value* WriteRawImageFn(const char* name, State* state, int argc, Expr* argv[]) {
char* result = NULL; char* result = NULL;
@@ -1063,14 +1056,16 @@ Value* WriteRawImageFn(const char* name, State* state, int argc, Expr* argv[]) {
} }
mtd_scan_partitions(); 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) { if (mtd == NULL) {
printf("%s: no mtd partition named \"%s\"\n", name, partition); printf("%s: no mtd partition named \"%s\"\n", name, partition);
result = strdup(""); result = strdup("");
goto done; goto done;
} }
MtdWriteContext* ctx = mtd_write_partition(mtd); MtdWriteContext* ctx;
ctx = mtd_write_partition(mtd);
if (ctx == NULL) { if (ctx == NULL) {
printf("%s: can't write mtd partition \"%s\"\n", printf("%s: can't write mtd partition \"%s\"\n",
name, partition); name, partition);
@@ -1085,14 +1080,13 @@ Value* WriteRawImageFn(const char* name, State* state, int argc, Expr* argv[]) {
char* filename = contents->data; char* filename = contents->data;
FILE* f = fopen(filename, "rb"); FILE* f = fopen(filename, "rb");
if (f == NULL) { if (f == NULL) {
printf("%s: can't open %s: %s\n", printf("%s: can't open %s: %s\n", name, filename, strerror(errno));
name, filename, strerror(errno));
result = strdup(""); result = strdup("");
goto done; goto done;
} }
success = true; success = true;
char* buffer = malloc(BUFSIZ); char* buffer = reinterpret_cast<char*>(malloc(BUFSIZ));
int read; int read;
while (success && (read = fread(buffer, 1, BUFSIZ, f)) > 0) { while (success && (read = fread(buffer, 1, BUFSIZ, f)) > 0) {
int wrote = mtd_write_data(ctx, buffer, read); int wrote = mtd_write_data(ctx, buffer, read);
@@ -1139,8 +1133,7 @@ Value* ApplyPatchSpaceFn(const char* name, State* state,
char* endptr; char* endptr;
size_t bytes = strtol(bytes_str, &endptr, 10); size_t bytes = strtol(bytes_str, &endptr, 10);
if (bytes == 0 && endptr == bytes_str) { if (bytes == 0 && endptr == bytes_str) {
ErrorAbort(state, "%s(): can't parse \"%s\" as byte count\n\n", ErrorAbort(state, "%s(): can't parse \"%s\" as byte count\n\n", name, bytes_str);
name, bytes_str);
free(bytes_str); free(bytes_str);
return NULL; return NULL;
} }
@@ -1200,7 +1193,7 @@ Value* ApplyPatchFn(const char* name, State* state, int argc, Expr* argv[]) {
return NULL; 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) { for (i = 0; i < patchcount; ++i) {
patch_sha_str[i] = patches[i*2]->data; patch_sha_str[i] = patches[i*2]->data;
patches[i*2]->data = NULL; patches[i*2]->data = NULL;
@@ -1259,7 +1252,7 @@ Value* UIPrintFn(const char* name, State* state, int argc, Expr* argv[]) {
for (i = 0; i < argc; ++i) { for (i = 0; i < argc; ++i) {
size += strlen(args[i]); size += strlen(args[i]);
} }
char* buffer = malloc(size+1); char* buffer = reinterpret_cast<char*>(malloc(size+1));
size = 0; size = 0;
for (i = 0; i < argc; ++i) { for (i = 0; i < argc; ++i) {
strcpy(buffer+size, args[i]); strcpy(buffer+size, args[i]);
@@ -1289,7 +1282,7 @@ Value* RunProgramFn(const char* name, State* state, int argc, Expr* argv[]) {
return NULL; 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); memcpy(args2, args, sizeof(char*) * argc);
args2[argc] = NULL; args2[argc] = NULL;
@@ -1356,7 +1349,7 @@ Value* Sha1CheckFn(const char* name, State* state, int argc, Expr* argv[]) {
} }
int i; 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) { for (i = 1; i < argc; ++i) {
if (args[i]->type != VAL_STRING) { if (args[i]->type != VAL_STRING) {
printf("%s(): arg %d is not a string; skipping", printf("%s(): arg %d is not a string; skipping",
@@ -1392,7 +1385,7 @@ Value* ReadFileFn(const char* name, State* state, int argc, Expr* argv[]) {
char* filename; char* filename;
if (ReadArgs(state, argv, 1, &filename) < 0) return NULL; 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; v->type = VAL_BLOB;
FileContents fc; FileContents fc;
@@ -1550,15 +1543,14 @@ Value* Tune2FsFn(const char* name, State* state, int argc, Expr* argv[]) {
return ErrorAbort(state, "%s() could not read args", name); return ErrorAbort(state, "%s() could not read args", name);
} }
int i; char** args2 = reinterpret_cast<char**>(malloc(sizeof(char*) * (argc+1)));
char** args2 = malloc(sizeof(char*) * (argc+1));
// Tune2fs expects the program name as its args[0] // Tune2fs expects the program name as its args[0]
args2[0] = strdup(name); args2[0] = strdup(name);
for (i = 0; i < argc; ++i) { for (int i = 0; i < argc; ++i) {
args2[i + 1] = args[i]; args2[i + 1] = args[i];
} }
int result = tune2fs_main(argc + 1, args2); 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[i]);
} }
free(args); free(args);
+1 -1
View File
@@ -89,7 +89,7 @@ int main(int argc, char** argv) {
return 4; 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)) { if (!mzReadZipEntry(&za, script_entry, script, script_entry->uncompLen)) {
printf("failed to read script from package\n"); printf("failed to read script from package\n");
return 5; return 5;