1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define _FILE_OFFSET_BITS 64
18 #define _LARGEFILE64_SOURCE 1
19
20 #include <fcntl.h>
21 #include <stdbool.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28
29 #include <sparse/sparse.h>
30
31 #ifndef O_BINARY
32 #define O_BINARY 0
33 #endif
34
usage()35 void usage() {
36 fprintf(stderr, "Usage: simg2simg <sparse image file> <sparse_image_file> <max_size>\n");
37 }
38
main(int argc,char * argv[])39 int main(int argc, char* argv[]) {
40 int in;
41 int out;
42 int i;
43 int ret;
44 struct sparse_file* s;
45 int64_t max_size;
46 struct sparse_file** out_s;
47 int files;
48 char filename[4096];
49
50 if (argc != 4) {
51 usage();
52 exit(-1);
53 }
54
55 max_size = atoll(argv[3]);
56
57 in = open(argv[1], O_RDONLY | O_BINARY);
58 if (in < 0) {
59 fprintf(stderr, "Cannot open input file %s\n", argv[1]);
60 exit(-1);
61 }
62
63 s = sparse_file_import(in, true, false);
64 if (!s) {
65 fprintf(stderr, "Failed to import sparse file\n");
66 exit(-1);
67 }
68
69 files = sparse_file_resparse(s, max_size, nullptr, 0);
70 if (files < 0) {
71 fprintf(stderr, "Failed to resparse\n");
72 exit(-1);
73 }
74
75 out_s = calloc(sizeof(struct sparse_file*), files);
76 if (!out_s) {
77 fprintf(stderr, "Failed to allocate sparse file array\n");
78 exit(-1);
79 }
80
81 files = sparse_file_resparse(s, max_size, out_s, files);
82 if (files < 0) {
83 fprintf(stderr, "Failed to resparse\n");
84 exit(-1);
85 }
86
87 for (i = 0; i < files; i++) {
88 ret = snprintf(filename, sizeof(filename), "%s.%d", argv[2], i);
89 if (ret >= (int)sizeof(filename)) {
90 fprintf(stderr, "Filename too long\n");
91 exit(-1);
92 }
93
94 out = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0664);
95 if (out < 0) {
96 fprintf(stderr, "Cannot open output file %s\n", argv[2]);
97 exit(-1);
98 }
99
100 ret = sparse_file_write(out_s[i], out, false, true, false);
101 if (ret) {
102 fprintf(stderr, "Failed to write sparse file\n");
103 exit(-1);
104 }
105 close(out);
106 }
107
108 close(in);
109
110 exit(0);
111 }
112