Read a file into memory; optionally (retouch_flag == RETOUCH_DO_MASK) mask the retouched entries back to their original value (such that SHA-1 checks don't fail due to randomization); store the file contents and associated metadata in *file. Return 0 on success.
| 51 | // |
| 52 | // Return 0 on success. |
| 53 | int LoadFileContents(const char* filename, FileContents* file, |
| 54 | int retouch_flag) { |
| 55 | file->data = NULL; |
| 56 | |
| 57 | // A special 'filename' beginning with "MTD:" or "EMMC:" means to |
| 58 | // load the contents of a partition. |
| 59 | if (strncmp(filename, "MTD:", 4) == 0 || |
| 60 | strncmp(filename, "EMMC:", 5) == 0) { |
| 61 | return LoadPartitionContents(filename, file); |
| 62 | } |
| 63 | |
| 64 | if (stat(filename, &file->st) != 0) { |
| 65 | printf("failed to stat \"%s\": %s\n", filename, strerror(errno)); |
| 66 | return (errno == ENOENT ? -ENOENT : -1); |
| 67 | } |
| 68 | |
| 69 | file->size = file->st.st_size; |
| 70 | file->data = malloc(file->size); |
| 71 | |
| 72 | FILE* f = fopen(filename, "rb"); |
| 73 | if (f == NULL) { |
| 74 | printf("failed to open \"%s\": %s\n", filename, strerror(errno)); |
| 75 | free(file->data); |
| 76 | file->data = NULL; |
| 77 | return -1; |
| 78 | } |
| 79 | |
| 80 | ssize_t bytes_read = fread(file->data, 1, file->size, f); |
| 81 | if (bytes_read != file->size) { |
| 82 | printf("short read of \"%s\" (%ld bytes of %ld)\n", |
| 83 | filename, (long)bytes_read, (long)file->size); |
| 84 | free(file->data); |
| 85 | file->data = NULL; |
| 86 | return -1; |
| 87 | } |
| 88 | fclose(f); |
| 89 | |
| 90 | // apply_patch[_check] functions are blind to randomization. Randomization |
| 91 | // is taken care of in [Undo]RetouchBinariesFn. If there is a mismatch |
| 92 | // within a file, this means the file is assumed "corrupt" for simplicity. |
| 93 | if (retouch_flag) { |
| 94 | int32_t desired_offset = 0; |
| 95 | if (retouch_mask_data(file->data, file->size, |
| 96 | &desired_offset, NULL) != RETOUCH_DATA_MATCHED) { |
| 97 | printf("error trying to mask retouch entries\n"); |
| 98 | free(file->data); |
| 99 | file->data = NULL; |
| 100 | return -1; |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | SHA_hash(file->data, file->size, file->sha1); |
| 105 | return 0; |
| 106 | } |
| 107 | |
| 108 | static size_t* size_array; |
| 109 | // comparison function for qsort()ing an int array of indexes into |
no test coverage detected