]> git.proxmox.com Git - qemu.git/blame - qemu-img.c
qcow2: Fix some more qemu_malloc fallout
[qemu.git] / qemu-img.c
CommitLineData
ea2384d3 1/*
fb43f4dd 2 * QEMU disk image utility
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
5fafdf24 5 *
ea2384d3
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
faf07963 24#include "qemu-common.h"
9ea2ea71 25#include "qemu-option.h"
f7b4a940 26#include "osdep.h"
ec36ba14 27#include "block_int.h"
9230eaf6 28#include <stdio.h>
ea2384d3 29
e8445331
FB
30#ifdef _WIN32
31#include <windows.h>
32#endif
33
c227f099 34typedef struct img_cmd_t {
153859be
SB
35 const char *name;
36 int (*handler)(int argc, char **argv);
c227f099 37} img_cmd_t;
153859be 38
137519ce
AJ
39/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
40#define BRDV_O_FLAGS BDRV_O_CACHE_WB
41
a5e50b26 42static void QEMU_NORETURN error(const char *fmt, ...)
ea2384d3
FB
43{
44 va_list ap;
45 va_start(ap, fmt);
57d1a2b6 46 fprintf(stderr, "qemu-img: ");
ea2384d3
FB
47 vfprintf(stderr, fmt, ap);
48 fprintf(stderr, "\n");
49 exit(1);
50 va_end(ap);
51}
52
53static void format_print(void *opaque, const char *name)
54{
55 printf(" %s", name);
56}
57
d2c639d6 58/* Please keep in synch with qemu-img.texi */
3f379ab1 59static void help(void)
ea2384d3 60{
68d0f70e 61 printf("qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
57d1a2b6 62 "usage: qemu-img command [command options]\n"
ea2384d3
FB
63 "QEMU disk image utility\n"
64 "\n"
65 "Command syntax:\n"
153859be
SB
66#define DEF(option, callback, arg_string) \
67 " " arg_string "\n"
68#include "qemu-img-cmds.h"
69#undef DEF
70#undef GEN_DOCS
ea2384d3
FB
71 "\n"
72 "Command parameters:\n"
73 " 'filename' is a disk image filename\n"
ea2384d3 74 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
d2c639d6 75 " 'size' is the disk image size in kilobytes. Optional suffixes\n"
2fbc4095
AJ
76 " 'M' (megabyte, 1024 * 1024) and 'G' (gigabyte, 1024 * 1024 * 1024) are\n"
77 " supported any 'k' or 'K' is ignored\n"
ea2384d3
FB
78 " 'output_filename' is the destination disk image filename\n"
79 " 'output_fmt' is the destination format\n"
eff44266
KW
80 " 'options' is a comma separated list of format specific options in a\n"
81 " name=value format. Use -o ? for an overview of the options supported by the\n"
82 " used format\n"
ea2384d3 83 " '-c' indicates that target image must be compressed (qcow format only)\n"
d2c639d6 84 " '-h' with or without a command shows this help and lists the supported formats\n"
f7b4a940 85 "\n"
d2c639d6
BS
86 "Parameters to snapshot subcommand:\n"
87 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
88 " '-a' applies a snapshot (revert disk to saved state)\n"
89 " '-c' creates a snapshot\n"
90 " '-d' deletes a snapshot\n"
91 " '-l' lists all snapshots in the given image\n"
ea2384d3 92 );
d2c639d6 93 printf("\nSupported formats:");
ea2384d3
FB
94 bdrv_iterate_format(format_print, NULL);
95 printf("\n");
96 exit(1);
97}
98
ea2384d3
FB
99#if defined(WIN32)
100/* XXX: put correct support for win32 */
101static int read_password(char *buf, int buf_size)
102{
103 int c, i;
104 printf("Password: ");
105 fflush(stdout);
106 i = 0;
107 for(;;) {
108 c = getchar();
109 if (c == '\n')
110 break;
111 if (i < (buf_size - 1))
112 buf[i++] = c;
113 }
114 buf[i] = '\0';
115 return 0;
116}
117
118#else
119
120#include <termios.h>
121
122static struct termios oldtty;
123
124static void term_exit(void)
125{
126 tcsetattr (0, TCSANOW, &oldtty);
127}
128
129static void term_init(void)
130{
131 struct termios tty;
132
133 tcgetattr (0, &tty);
134 oldtty = tty;
135
136 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
137 |INLCR|IGNCR|ICRNL|IXON);
138 tty.c_oflag |= OPOST;
139 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
140 tty.c_cflag &= ~(CSIZE|PARENB);
141 tty.c_cflag |= CS8;
142 tty.c_cc[VMIN] = 1;
143 tty.c_cc[VTIME] = 0;
3b46e624 144
ea2384d3
FB
145 tcsetattr (0, TCSANOW, &tty);
146
147 atexit(term_exit);
148}
149
3f379ab1 150static int read_password(char *buf, int buf_size)
ea2384d3
FB
151{
152 uint8_t ch;
153 int i, ret;
154
155 printf("password: ");
156 fflush(stdout);
157 term_init();
158 i = 0;
159 for(;;) {
160 ret = read(0, &ch, 1);
161 if (ret == -1) {
162 if (errno == EAGAIN || errno == EINTR) {
163 continue;
164 } else {
165 ret = -1;
166 break;
167 }
168 } else if (ret == 0) {
169 ret = -1;
170 break;
171 } else {
172 if (ch == '\r') {
173 ret = 0;
174 break;
175 }
176 if (i < (buf_size - 1))
177 buf[i++] = ch;
178 }
179 }
180 term_exit();
181 buf[i] = '\0';
182 printf("\n");
183 return ret;
184}
185#endif
186
75c23805
FB
187static BlockDriverState *bdrv_new_open(const char *filename,
188 const char *fmt)
189{
190 BlockDriverState *bs;
191 BlockDriver *drv;
192 char password[256];
193
194 bs = bdrv_new("");
195 if (!bs)
196 error("Not enough memory");
197 if (fmt) {
198 drv = bdrv_find_format(fmt);
199 if (!drv)
200 error("Unknown file format '%s'", fmt);
201 } else {
202 drv = NULL;
203 }
137519ce 204 if (bdrv_open2(bs, filename, BRDV_O_FLAGS, drv) < 0) {
75c23805
FB
205 error("Could not open '%s'", filename);
206 }
207 if (bdrv_is_encrypted(bs)) {
208 printf("Disk image '%s' is encrypted.\n", filename);
209 if (read_password(password, sizeof(password)) < 0)
210 error("No password given");
211 if (bdrv_set_key(bs, password) < 0)
212 error("invalid password");
213 }
214 return bs;
215}
216
efa84d43
KW
217static void add_old_style_options(const char *fmt, QEMUOptionParameter *list,
218 int flags, const char *base_filename, const char *base_fmt)
219{
220 if (flags & BLOCK_FLAG_ENCRYPT) {
221 if (set_option_parameter(list, BLOCK_OPT_ENCRYPT, "on")) {
222 error("Encryption not supported for file format '%s'", fmt);
223 }
224 }
225 if (flags & BLOCK_FLAG_COMPAT6) {
226 if (set_option_parameter(list, BLOCK_OPT_COMPAT6, "on")) {
227 error("VMDK version 6 not supported for file format '%s'", fmt);
228 }
229 }
230
231 if (base_filename) {
232 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
233 error("Backing file not supported for file format '%s'", fmt);
234 }
235 }
236 if (base_fmt) {
237 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
238 error("Backing file format not supported for file format '%s'", fmt);
239 }
240 }
241}
242
ea2384d3
FB
243static int img_create(int argc, char **argv)
244{
ec36ba14 245 int c, ret, flags;
ea2384d3 246 const char *fmt = "raw";
9230eaf6 247 const char *base_fmt = NULL;
ea2384d3
FB
248 const char *filename;
249 const char *base_filename = NULL;
ea2384d3 250 BlockDriver *drv;
9ea2ea71
KW
251 QEMUOptionParameter *param = NULL;
252 char *options = NULL;
3b46e624 253
ec36ba14 254 flags = 0;
ea2384d3 255 for(;;) {
9ea2ea71 256 c = getopt(argc, argv, "F:b:f:he6o:");
ea2384d3
FB
257 if (c == -1)
258 break;
259 switch(c) {
260 case 'h':
261 help();
262 break;
9230eaf6
AL
263 case 'F':
264 base_fmt = optarg;
265 break;
ea2384d3
FB
266 case 'b':
267 base_filename = optarg;
268 break;
269 case 'f':
270 fmt = optarg;
271 break;
272 case 'e':
ec36ba14 273 flags |= BLOCK_FLAG_ENCRYPT;
ea2384d3 274 break;
d8871c5a 275 case '6':
ec36ba14 276 flags |= BLOCK_FLAG_COMPAT6;
d8871c5a 277 break;
9ea2ea71
KW
278 case 'o':
279 options = optarg;
280 break;
ea2384d3
FB
281 }
282 }
9230eaf6 283
9ea2ea71
KW
284 /* Find driver and parse its options */
285 drv = bdrv_find_format(fmt);
286 if (!drv)
287 error("Unknown file format '%s'", fmt);
9230eaf6 288
db08adf5
KW
289 if (options && !strcmp(options, "?")) {
290 print_option_help(drv->create_options);
291 return 0;
292 }
293
9f56640c
KW
294 /* Create parameter list with default values */
295 param = parse_option_parameters("", drv->create_options, param);
296 set_option_parameter_int(param, BLOCK_OPT_SIZE, -1);
297
298 /* Parse -o options */
9ea2ea71
KW
299 if (options) {
300 param = parse_option_parameters(options, drv->create_options, param);
301 if (param == NULL) {
302 error("Invalid options for file format '%s'.", fmt);
303 }
9ea2ea71
KW
304 }
305
db08adf5
KW
306 /* Get the filename */
307 if (optind >= argc)
308 help();
309 filename = argv[optind++];
310
9ea2ea71
KW
311 /* Add size to parameters */
312 if (optind < argc) {
313 set_option_parameter(param, BLOCK_OPT_SIZE, argv[optind++]);
314 }
315
316 /* Add old-style options to parameters */
efa84d43 317 add_old_style_options(fmt, param, flags, base_filename, base_fmt);
9ea2ea71
KW
318
319 // The size for the image must always be specified, with one exception:
320 // If we are using a backing file, we can obtain the size from there
9f56640c 321 if (get_option_parameter(param, BLOCK_OPT_SIZE)->value.n == -1) {
9ea2ea71
KW
322
323 QEMUOptionParameter *backing_file =
324 get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
325 QEMUOptionParameter *backing_fmt =
326 get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
327
328 if (backing_file && backing_file->value.s) {
329 BlockDriverState *bs;
330 uint64_t size;
331 const char *fmt = NULL;
332 char buf[32];
333
334 if (backing_fmt && backing_fmt->value.s) {
335 if (bdrv_find_format(backing_fmt->value.s)) {
336 fmt = backing_fmt->value.s;
337 } else {
338 error("Unknown backing file format '%s'",
339 backing_fmt->value.s);
340 }
341 }
342
343 bs = bdrv_new_open(backing_file->value.s, fmt);
344 bdrv_get_geometry(bs, &size);
345 size *= 512;
346 bdrv_delete(bs);
347
348 snprintf(buf, sizeof(buf), "%" PRId64, size);
349 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
350 } else {
351 error("Image creation needs a size parameter");
352 }
75c23805 353 }
9ea2ea71
KW
354
355 printf("Formatting '%s', fmt=%s ", filename, fmt);
356 print_option_parameters(param);
357 puts("");
358
359 ret = bdrv_create(drv, filename, param);
360 free_option_parameters(param);
361
ea2384d3
FB
362 if (ret < 0) {
363 if (ret == -ENOTSUP) {
3c56521b 364 error("Formatting or formatting option not supported for file format '%s'", fmt);
6e9ea0c0
AJ
365 } else if (ret == -EFBIG) {
366 error("The image size is too large for file format '%s'", fmt);
ea2384d3
FB
367 } else {
368 error("Error while formatting");
369 }
370 }
371 return 0;
372}
373
1585969c
AL
374static int img_check(int argc, char **argv)
375{
376 int c, ret;
377 const char *filename, *fmt;
378 BlockDriver *drv;
379 BlockDriverState *bs;
380
381 fmt = NULL;
382 for(;;) {
383 c = getopt(argc, argv, "f:h");
384 if (c == -1)
385 break;
386 switch(c) {
387 case 'h':
388 help();
389 break;
390 case 'f':
391 fmt = optarg;
392 break;
393 }
394 }
395 if (optind >= argc)
396 help();
397 filename = argv[optind++];
398
399 bs = bdrv_new("");
400 if (!bs)
401 error("Not enough memory");
402 if (fmt) {
403 drv = bdrv_find_format(fmt);
404 if (!drv)
405 error("Unknown file format '%s'", fmt);
406 } else {
407 drv = NULL;
408 }
409 if (bdrv_open2(bs, filename, BRDV_O_FLAGS, drv) < 0) {
410 error("Could not open '%s'", filename);
411 }
412 ret = bdrv_check(bs);
413 switch(ret) {
414 case 0:
415 printf("No errors were found on the image.\n");
416 break;
417 case -ENOTSUP:
418 error("This image format does not support checks");
419 break;
420 default:
421 if (ret < 0) {
422 error("An error occurred during the check");
423 } else {
424 printf("%d errors were found on the image.\n", ret);
425 }
426 break;
427 }
428
429 bdrv_delete(bs);
430 return 0;
431}
432
ea2384d3
FB
433static int img_commit(int argc, char **argv)
434{
435 int c, ret;
436 const char *filename, *fmt;
437 BlockDriver *drv;
438 BlockDriverState *bs;
439
440 fmt = NULL;
441 for(;;) {
442 c = getopt(argc, argv, "f:h");
443 if (c == -1)
444 break;
445 switch(c) {
446 case 'h':
447 help();
448 break;
449 case 'f':
450 fmt = optarg;
451 break;
452 }
453 }
5fafdf24 454 if (optind >= argc)
ea2384d3
FB
455 help();
456 filename = argv[optind++];
457
458 bs = bdrv_new("");
459 if (!bs)
460 error("Not enough memory");
461 if (fmt) {
462 drv = bdrv_find_format(fmt);
463 if (!drv)
464 error("Unknown file format '%s'", fmt);
465 } else {
466 drv = NULL;
467 }
137519ce 468 if (bdrv_open2(bs, filename, BRDV_O_FLAGS, drv) < 0) {
ea2384d3
FB
469 error("Could not open '%s'", filename);
470 }
471 ret = bdrv_commit(bs);
472 switch(ret) {
473 case 0:
474 printf("Image committed.\n");
475 break;
476 case -ENOENT:
477 error("No disk inserted");
478 break;
479 case -EACCES:
480 error("Image is read-only");
481 break;
482 case -ENOTSUP:
483 error("Image is already committed");
484 break;
485 default:
486 error("Error while committing image");
487 break;
488 }
489
490 bdrv_delete(bs);
491 return 0;
492}
493
494static int is_not_zero(const uint8_t *sector, int len)
495{
496 int i;
497 len >>= 2;
498 for(i = 0;i < len; i++) {
499 if (((uint32_t *)sector)[i] != 0)
500 return 1;
501 }
502 return 0;
503}
504
f58c7b35
TS
505/*
506 * Returns true iff the first sector pointed to by 'buf' contains at least
507 * a non-NUL byte.
508 *
509 * 'pnum' is set to the number of sectors (including and immediately following
510 * the first one) that are known to be in the same allocated/unallocated state.
511 */
ea2384d3
FB
512static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
513{
514 int v, i;
515
516 if (n <= 0) {
517 *pnum = 0;
518 return 0;
519 }
520 v = is_not_zero(buf, 512);
521 for(i = 1; i < n; i++) {
522 buf += 512;
523 if (v != is_not_zero(buf, 512))
524 break;
525 }
526 *pnum = i;
527 return v;
528}
529
80ee15a6 530#define IO_BUF_SIZE (2 * 1024 * 1024)
ea2384d3
FB
531
532static int img_convert(int argc, char **argv)
533{
926c2d23 534 int c, ret, n, n1, bs_n, bs_i, flags, cluster_size, cluster_sectors;
f58c7b35 535 const char *fmt, *out_fmt, *out_baseimg, *out_filename;
ea2384d3 536 BlockDriver *drv;
926c2d23 537 BlockDriverState **bs, *out_bs;
96b8f136
TS
538 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
539 uint64_t bs_sectors;
ea2384d3
FB
540 uint8_t buf[IO_BUF_SIZE];
541 const uint8_t *buf1;
faea38e7 542 BlockDriverInfo bdi;
efa84d43
KW
543 QEMUOptionParameter *param = NULL;
544 char *options = NULL;
ea2384d3
FB
545
546 fmt = NULL;
547 out_fmt = "raw";
f58c7b35 548 out_baseimg = NULL;
ec36ba14 549 flags = 0;
ea2384d3 550 for(;;) {
efa84d43 551 c = getopt(argc, argv, "f:O:B:hce6o:");
ea2384d3
FB
552 if (c == -1)
553 break;
554 switch(c) {
555 case 'h':
556 help();
557 break;
558 case 'f':
559 fmt = optarg;
560 break;
561 case 'O':
562 out_fmt = optarg;
563 break;
f58c7b35
TS
564 case 'B':
565 out_baseimg = optarg;
566 break;
ea2384d3 567 case 'c':
ec36ba14 568 flags |= BLOCK_FLAG_COMPRESS;
ea2384d3
FB
569 break;
570 case 'e':
ec36ba14
TS
571 flags |= BLOCK_FLAG_ENCRYPT;
572 break;
573 case '6':
574 flags |= BLOCK_FLAG_COMPAT6;
ea2384d3 575 break;
efa84d43
KW
576 case 'o':
577 options = optarg;
578 break;
ea2384d3
FB
579 }
580 }
3b46e624 581
926c2d23
AZ
582 bs_n = argc - optind - 1;
583 if (bs_n < 1) help();
584
585 out_filename = argv[argc - 1];
f58c7b35
TS
586
587 if (bs_n > 1 && out_baseimg)
588 error("-B makes no sense when concatenating multiple input images");
926c2d23
AZ
589
590 bs = calloc(bs_n, sizeof(BlockDriverState *));
591 if (!bs)
592 error("Out of memory");
593
594 total_sectors = 0;
595 for (bs_i = 0; bs_i < bs_n; bs_i++) {
596 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt);
597 if (!bs[bs_i])
598 error("Could not open '%s'", argv[optind + bs_i]);
599 bdrv_get_geometry(bs[bs_i], &bs_sectors);
600 total_sectors += bs_sectors;
601 }
ea2384d3 602
efa84d43 603 /* Find driver and parse its options */
ea2384d3
FB
604 drv = bdrv_find_format(out_fmt);
605 if (!drv)
d34dda5e 606 error("Unknown file format '%s'", out_fmt);
efa84d43 607
db08adf5
KW
608 if (options && !strcmp(options, "?")) {
609 print_option_help(drv->create_options);
610 return 0;
611 }
612
efa84d43
KW
613 if (options) {
614 param = parse_option_parameters(options, drv->create_options, param);
615 if (param == NULL) {
616 error("Invalid options for file format '%s'.", out_fmt);
617 }
618 } else {
619 param = parse_option_parameters("", drv->create_options, param);
620 }
621
622 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
623 add_old_style_options(out_fmt, param, flags, out_baseimg, NULL);
624
625 /* Check if compression is supported */
626 if (flags & BLOCK_FLAG_COMPRESS) {
627 QEMUOptionParameter *encryption =
628 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
629
630 if (!drv->bdrv_write_compressed) {
631 error("Compression not supported for this file format");
632 }
633
634 if (encryption && encryption->value.n) {
635 error("Compression and encryption not supported at the same time");
636 }
637 }
638
639 /* Create the new image */
640 ret = bdrv_create(drv, out_filename, param);
641 free_option_parameters(param);
642
ea2384d3
FB
643 if (ret < 0) {
644 if (ret == -ENOTSUP) {
93c65b47 645 error("Formatting not supported for file format '%s'", out_fmt);
6e9ea0c0
AJ
646 } else if (ret == -EFBIG) {
647 error("The image size is too large for file format '%s'", out_fmt);
ea2384d3
FB
648 } else {
649 error("Error while formatting '%s'", out_filename);
650 }
651 }
3b46e624 652
ea2384d3
FB
653 out_bs = bdrv_new_open(out_filename, out_fmt);
654
926c2d23
AZ
655 bs_i = 0;
656 bs_offset = 0;
657 bdrv_get_geometry(bs[0], &bs_sectors);
658
659 if (flags & BLOCK_FLAG_COMPRESS) {
faea38e7
FB
660 if (bdrv_get_info(out_bs, &bdi) < 0)
661 error("could not get block driver info");
662 cluster_size = bdi.cluster_size;
ea2384d3
FB
663 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE)
664 error("invalid cluster size");
665 cluster_sectors = cluster_size >> 9;
666 sector_num = 0;
667 for(;;) {
926c2d23
AZ
668 int64_t bs_num;
669 int remainder;
670 uint8_t *buf2;
671
ea2384d3
FB
672 nb_sectors = total_sectors - sector_num;
673 if (nb_sectors <= 0)
674 break;
675 if (nb_sectors >= cluster_sectors)
676 n = cluster_sectors;
677 else
678 n = nb_sectors;
926c2d23
AZ
679
680 bs_num = sector_num - bs_offset;
681 assert (bs_num >= 0);
682 remainder = n;
683 buf2 = buf;
684 while (remainder > 0) {
685 int nlow;
686 while (bs_num == bs_sectors) {
687 bs_i++;
688 assert (bs_i < bs_n);
689 bs_offset += bs_sectors;
690 bdrv_get_geometry(bs[bs_i], &bs_sectors);
691 bs_num = 0;
692 /* printf("changing part: sector_num=%lld, "
693 "bs_i=%d, bs_offset=%lld, bs_sectors=%lld\n",
694 sector_num, bs_i, bs_offset, bs_sectors); */
695 }
696 assert (bs_num < bs_sectors);
697
698 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
699
700 if (bdrv_read(bs[bs_i], bs_num, buf2, nlow) < 0)
701 error("error while reading");
702
703 buf2 += nlow * 512;
704 bs_num += nlow;
705
706 remainder -= nlow;
707 }
708 assert (remainder == 0);
709
ea2384d3
FB
710 if (n < cluster_sectors)
711 memset(buf + n * 512, 0, cluster_size - n * 512);
712 if (is_not_zero(buf, cluster_size)) {
5fafdf24 713 if (bdrv_write_compressed(out_bs, sector_num, buf,
faea38e7 714 cluster_sectors) != 0)
ec3757de
FB
715 error("error while compressing sector %" PRId64,
716 sector_num);
ea2384d3
FB
717 }
718 sector_num += n;
719 }
faea38e7
FB
720 /* signal EOF to align */
721 bdrv_write_compressed(out_bs, 0, NULL, 0);
ea2384d3 722 } else {
f58c7b35 723 sector_num = 0; // total number of sectors converted so far
ea2384d3
FB
724 for(;;) {
725 nb_sectors = total_sectors - sector_num;
726 if (nb_sectors <= 0)
727 break;
728 if (nb_sectors >= (IO_BUF_SIZE / 512))
729 n = (IO_BUF_SIZE / 512);
730 else
731 n = nb_sectors;
926c2d23
AZ
732
733 while (sector_num - bs_offset >= bs_sectors) {
734 bs_i ++;
735 assert (bs_i < bs_n);
736 bs_offset += bs_sectors;
737 bdrv_get_geometry(bs[bs_i], &bs_sectors);
738 /* printf("changing part: sector_num=%lld, bs_i=%d, "
739 "bs_offset=%lld, bs_sectors=%lld\n",
740 sector_num, bs_i, bs_offset, bs_sectors); */
741 }
742
743 if (n > bs_offset + bs_sectors - sector_num)
744 n = bs_offset + bs_sectors - sector_num;
745
5efa9d5a 746 if (strcmp(drv->format_name, "host_device")) {
d032044f
AS
747 /* If the output image is being created as a copy on write image,
748 assume that sectors which are unallocated in the input image
749 are present in both the output's and input's base images (no
750 need to copy them). */
751 if (out_baseimg) {
752 if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
753 n, &n1)) {
754 sector_num += n1;
755 continue;
756 }
757 /* The next 'n1' sectors are allocated in the input image. Copy
758 only those as they may be followed by unallocated sectors. */
759 n = n1;
93c65b47 760 }
93c65b47
AL
761 } else {
762 n1 = n;
f58c7b35
TS
763 }
764
926c2d23 765 if (bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n) < 0)
ea2384d3
FB
766 error("error while reading");
767 /* NOTE: at the same time we convert, we do not write zero
768 sectors to have a chance to compress the image. Ideally, we
769 should add a specific call to have the info to go faster */
770 buf1 = buf;
771 while (n > 0) {
f58c7b35
TS
772 /* If the output image is being created as a copy on write image,
773 copy all sectors even the ones containing only NUL bytes,
93c65b47
AL
774 because they may differ from the sectors in the base image.
775
776 If the output is to a host device, we also write out
777 sectors that are entirely 0, since whatever data was
778 already there is garbage, not 0s. */
5efa9d5a 779 if (strcmp(drv->format_name, "host_device") == 0 || out_baseimg ||
93c65b47 780 is_allocated_sectors(buf1, n, &n1)) {
5fafdf24 781 if (bdrv_write(out_bs, sector_num, buf1, n1) < 0)
ea2384d3
FB
782 error("error while writing");
783 }
784 sector_num += n1;
785 n -= n1;
786 buf1 += n1 * 512;
787 }
788 }
789 }
790 bdrv_delete(out_bs);
926c2d23
AZ
791 for (bs_i = 0; bs_i < bs_n; bs_i++)
792 bdrv_delete(bs[bs_i]);
793 free(bs);
ea2384d3
FB
794 return 0;
795}
796
57d1a2b6
FB
797#ifdef _WIN32
798static int64_t get_allocated_file_size(const char *filename)
799{
e8445331
FB
800 typedef DWORD (WINAPI * get_compressed_t)(const char *filename, DWORD *high);
801 get_compressed_t get_compressed;
57d1a2b6 802 struct _stati64 st;
e8445331
FB
803
804 /* WinNT support GetCompressedFileSize to determine allocate size */
805 get_compressed = (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"), "GetCompressedFileSizeA");
806 if (get_compressed) {
807 DWORD high, low;
808 low = get_compressed(filename, &high);
809 if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR)
810 return (((int64_t) high) << 32) + low;
811 }
812
5fafdf24 813 if (_stati64(filename, &st) < 0)
57d1a2b6
FB
814 return -1;
815 return st.st_size;
816}
817#else
818static int64_t get_allocated_file_size(const char *filename)
819{
820 struct stat st;
5fafdf24 821 if (stat(filename, &st) < 0)
57d1a2b6
FB
822 return -1;
823 return (int64_t)st.st_blocks * 512;
824}
825#endif
826
faea38e7
FB
827static void dump_snapshots(BlockDriverState *bs)
828{
829 QEMUSnapshotInfo *sn_tab, *sn;
830 int nb_sns, i;
831 char buf[256];
832
833 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
834 if (nb_sns <= 0)
835 return;
836 printf("Snapshot list:\n");
837 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
838 for(i = 0; i < nb_sns; i++) {
839 sn = &sn_tab[i];
840 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
841 }
842 qemu_free(sn_tab);
843}
844
ea2384d3
FB
845static int img_info(int argc, char **argv)
846{
847 int c;
848 const char *filename, *fmt;
849 BlockDriver *drv;
850 BlockDriverState *bs;
851 char fmt_name[128], size_buf[128], dsize_buf[128];
96b8f136
TS
852 uint64_t total_sectors;
853 int64_t allocated_size;
93b6b2a3
FB
854 char backing_filename[1024];
855 char backing_filename2[1024];
faea38e7 856 BlockDriverInfo bdi;
ea2384d3
FB
857
858 fmt = NULL;
859 for(;;) {
860 c = getopt(argc, argv, "f:h");
861 if (c == -1)
862 break;
863 switch(c) {
864 case 'h':
865 help();
866 break;
867 case 'f':
868 fmt = optarg;
869 break;
870 }
871 }
5fafdf24 872 if (optind >= argc)
ea2384d3
FB
873 help();
874 filename = argv[optind++];
875
876 bs = bdrv_new("");
877 if (!bs)
878 error("Not enough memory");
879 if (fmt) {
880 drv = bdrv_find_format(fmt);
881 if (!drv)
882 error("Unknown file format '%s'", fmt);
883 } else {
884 drv = NULL;
885 }
137519ce 886 if (bdrv_open2(bs, filename, BRDV_O_FLAGS, drv) < 0) {
ea2384d3
FB
887 error("Could not open '%s'", filename);
888 }
889 bdrv_get_format(bs, fmt_name, sizeof(fmt_name));
890 bdrv_get_geometry(bs, &total_sectors);
891 get_human_readable_size(size_buf, sizeof(size_buf), total_sectors * 512);
57d1a2b6
FB
892 allocated_size = get_allocated_file_size(filename);
893 if (allocated_size < 0)
a10ea30b 894 snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
de167e41 895 else
5fafdf24 896 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
de167e41 897 allocated_size);
ea2384d3
FB
898 printf("image: %s\n"
899 "file format: %s\n"
ec3757de 900 "virtual size: %s (%" PRId64 " bytes)\n"
ea2384d3 901 "disk size: %s\n",
5fafdf24 902 filename, fmt_name, size_buf,
ec3757de 903 (total_sectors * 512),
ea2384d3
FB
904 dsize_buf);
905 if (bdrv_is_encrypted(bs))
906 printf("encrypted: yes\n");
faea38e7 907 if (bdrv_get_info(bs, &bdi) >= 0) {
5fafdf24 908 if (bdi.cluster_size != 0)
faea38e7
FB
909 printf("cluster_size: %d\n", bdi.cluster_size);
910 }
93b6b2a3 911 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
faea38e7 912 if (backing_filename[0] != '\0') {
93b6b2a3
FB
913 path_combine(backing_filename2, sizeof(backing_filename2),
914 filename, backing_filename);
5fafdf24 915 printf("backing file: %s (actual path: %s)\n",
93b6b2a3
FB
916 backing_filename,
917 backing_filename2);
faea38e7
FB
918 }
919 dump_snapshots(bs);
ea2384d3
FB
920 bdrv_delete(bs);
921 return 0;
922}
923
f7b4a940
AL
924#define SNAPSHOT_LIST 1
925#define SNAPSHOT_CREATE 2
926#define SNAPSHOT_APPLY 3
927#define SNAPSHOT_DELETE 4
928
153859be 929static int img_snapshot(int argc, char **argv)
f7b4a940
AL
930{
931 BlockDriverState *bs;
932 QEMUSnapshotInfo sn;
933 char *filename, *snapshot_name = NULL;
40a4539e 934 int c, ret;
f7b4a940
AL
935 int action = 0;
936 qemu_timeval tv;
937
938 /* Parse commandline parameters */
939 for(;;) {
940 c = getopt(argc, argv, "la:c:d:h");
941 if (c == -1)
942 break;
943 switch(c) {
944 case 'h':
945 help();
153859be 946 return 0;
f7b4a940
AL
947 case 'l':
948 if (action) {
949 help();
153859be 950 return 0;
f7b4a940
AL
951 }
952 action = SNAPSHOT_LIST;
953 break;
954 case 'a':
955 if (action) {
956 help();
153859be 957 return 0;
f7b4a940
AL
958 }
959 action = SNAPSHOT_APPLY;
960 snapshot_name = optarg;
961 break;
962 case 'c':
963 if (action) {
964 help();
153859be 965 return 0;
f7b4a940
AL
966 }
967 action = SNAPSHOT_CREATE;
968 snapshot_name = optarg;
969 break;
970 case 'd':
971 if (action) {
972 help();
153859be 973 return 0;
f7b4a940
AL
974 }
975 action = SNAPSHOT_DELETE;
976 snapshot_name = optarg;
977 break;
978 }
979 }
980
981 if (optind >= argc)
982 help();
983 filename = argv[optind++];
984
985 /* Open the image */
986 bs = bdrv_new("");
987 if (!bs)
988 error("Not enough memory");
989
990 if (bdrv_open2(bs, filename, 0, NULL) < 0) {
991 error("Could not open '%s'", filename);
992 }
993
994 /* Perform the requested action */
995 switch(action) {
996 case SNAPSHOT_LIST:
997 dump_snapshots(bs);
998 break;
999
1000 case SNAPSHOT_CREATE:
1001 memset(&sn, 0, sizeof(sn));
1002 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
1003
1004 qemu_gettimeofday(&tv);
1005 sn.date_sec = tv.tv_sec;
1006 sn.date_nsec = tv.tv_usec * 1000;
1007
1008 ret = bdrv_snapshot_create(bs, &sn);
1009 if (ret)
1010 error("Could not create snapshot '%s': %d (%s)",
1011 snapshot_name, ret, strerror(-ret));
1012 break;
1013
1014 case SNAPSHOT_APPLY:
1015 ret = bdrv_snapshot_goto(bs, snapshot_name);
1016 if (ret)
1017 error("Could not apply snapshot '%s': %d (%s)",
1018 snapshot_name, ret, strerror(-ret));
1019 break;
1020
1021 case SNAPSHOT_DELETE:
1022 ret = bdrv_snapshot_delete(bs, snapshot_name);
1023 if (ret)
1024 error("Could not delete snapshot '%s': %d (%s)",
1025 snapshot_name, ret, strerror(-ret));
1026 break;
1027 }
1028
1029 /* Cleanup */
1030 bdrv_delete(bs);
153859be
SB
1031
1032 return 0;
f7b4a940
AL
1033}
1034
c227f099 1035static const img_cmd_t img_cmds[] = {
153859be
SB
1036#define DEF(option, callback, arg_string) \
1037 { option, callback },
1038#include "qemu-img-cmds.h"
1039#undef DEF
1040#undef GEN_DOCS
1041 { NULL, NULL, },
1042};
1043
ea2384d3
FB
1044int main(int argc, char **argv)
1045{
c227f099 1046 const img_cmd_t *cmd;
153859be 1047 const char *cmdname;
ea2384d3
FB
1048
1049 bdrv_init();
1050 if (argc < 2)
1051 help();
153859be 1052 cmdname = argv[1];
8f9b157e 1053 argc--; argv++;
153859be
SB
1054
1055 /* find the command */
1056 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
1057 if (!strcmp(cmdname, cmd->name)) {
1058 return cmd->handler(argc, argv);
1059 }
ea2384d3 1060 }
153859be
SB
1061
1062 /* not found */
1063 help();
ea2384d3
FB
1064 return 0;
1065}