blob: 6f02f4fccb455a40295ddfceafdf66f1222fcd82 [file] [log] [blame]
Colin Crossbdc6d392012-05-02 15:18:22 -07001/*
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
Colin Crossbdc6d392012-05-02 15:18:22 -070019
20#include <fcntl.h>
21#include <stdbool.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <sys/types.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <unistd.h>
29
30#include <sparse/sparse.h>
31
32#ifndef O_BINARY
33#define O_BINARY 0
34#endif
35
36void usage()
37{
38 fprintf(stderr, "Usage: simg2simg <sparse image file> <sparse_image_file> <max_size>\n");
39}
40
41int main(int argc, char *argv[])
42{
43 int in;
44 int out;
45 int i;
46 int ret;
47 struct sparse_file *s;
48 int64_t max_size;
49 struct sparse_file **out_s;
50 int files;
51 char filename[4096];
52
53 if (argc != 4) {
54 usage();
55 exit(-1);
56 }
57
58 max_size = atoll(argv[3]);
59
60 in = open(argv[1], O_RDONLY | O_BINARY);
61 if (in < 0) {
62 fprintf(stderr, "Cannot open input file %s\n", argv[1]);
63 exit(-1);
64 }
65
66 s = sparse_file_import(in, true, false);
67 if (!s) {
68 fprintf(stderr, "Failed to import sparse file\n");
69 exit(-1);
70 }
71
72 files = sparse_file_resparse(s, max_size, NULL, 0);
73 if (files < 0) {
74 fprintf(stderr, "Failed to resparse\n");
75 exit(-1);
76 }
77
78 out_s = calloc(sizeof(struct sparse_file *), files);
79 if (!out_s) {
80 fprintf(stderr, "Failed to allocate sparse file array\n");
81 exit(-1);
82 }
83
84 files = sparse_file_resparse(s, max_size, out_s, files);
85 if (files < 0) {
86 fprintf(stderr, "Failed to resparse\n");
87 exit(-1);
88 }
89
90 for (i = 0; i < files; i++) {
91 ret = snprintf(filename, sizeof(filename), "%s.%d", argv[2], i);
92 if (ret >= (int)sizeof(filename)) {
93 fprintf(stderr, "Filename too long\n");
94 exit(-1);
95 }
96
97 out = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0664);
98 if (out < 0) {
99 fprintf(stderr, "Cannot open output file %s\n", argv[2]);
100 exit(-1);
101 }
102
103 ret = sparse_file_write(out_s[i], out, false, true, false);
104 if (ret) {
105 fprintf(stderr, "Failed to write sparse file\n");
106 exit(-1);
107 }
108 close(out);
109 }
110
111 close(in);
112
113 exit(0);
114}