qemu-img.c 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793
  1. /*
  2. * QEMU disk image utility
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  5. *
  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. */
  24. #include "qapi-visit.h"
  25. #include "qapi/qmp-output-visitor.h"
  26. #include "qapi/qmp/qjson.h"
  27. #include "qemu-common.h"
  28. #include "qemu/option.h"
  29. #include "qemu/error-report.h"
  30. #include "qemu/osdep.h"
  31. #include "sysemu/sysemu.h"
  32. #include "block/block_int.h"
  33. #include "block/qapi.h"
  34. #include <getopt.h>
  35. typedef struct img_cmd_t {
  36. const char *name;
  37. int (*handler)(int argc, char **argv);
  38. } img_cmd_t;
  39. enum {
  40. OPTION_OUTPUT = 256,
  41. OPTION_BACKING_CHAIN = 257,
  42. };
  43. typedef enum OutputFormat {
  44. OFORMAT_JSON,
  45. OFORMAT_HUMAN,
  46. } OutputFormat;
  47. /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
  48. #define BDRV_O_FLAGS BDRV_O_CACHE_WB
  49. #define BDRV_DEFAULT_CACHE "writeback"
  50. static void format_print(void *opaque, const char *name)
  51. {
  52. printf(" %s", name);
  53. }
  54. /* Please keep in synch with qemu-img.texi */
  55. static void help(void)
  56. {
  57. const char *help_msg =
  58. "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
  59. "usage: qemu-img command [command options]\n"
  60. "QEMU disk image utility\n"
  61. "\n"
  62. "Command syntax:\n"
  63. #define DEF(option, callback, arg_string) \
  64. " " arg_string "\n"
  65. #include "qemu-img-cmds.h"
  66. #undef DEF
  67. #undef GEN_DOCS
  68. "\n"
  69. "Command parameters:\n"
  70. " 'filename' is a disk image filename\n"
  71. " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
  72. " 'cache' is the cache mode used to write the output disk image, the valid\n"
  73. " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
  74. " 'directsync' and 'unsafe' (default for convert)\n"
  75. " 'size' is the disk image size in bytes. Optional suffixes\n"
  76. " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
  77. " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
  78. " supported. 'b' is ignored.\n"
  79. " 'output_filename' is the destination disk image filename\n"
  80. " 'output_fmt' is the destination format\n"
  81. " 'options' is a comma separated list of format specific options in a\n"
  82. " name=value format. Use -o ? for an overview of the options supported by the\n"
  83. " used format\n"
  84. " 'snapshot_param' is param used for internal snapshot, format\n"
  85. " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
  86. " '[ID_OR_NAME]'\n"
  87. " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
  88. " instead\n"
  89. " '-c' indicates that target image must be compressed (qcow format only)\n"
  90. " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
  91. " match exactly. The image doesn't need a working backing file before\n"
  92. " rebasing in this case (useful for renaming the backing file)\n"
  93. " '-h' with or without a command shows this help and lists the supported formats\n"
  94. " '-p' show progress of command (only certain commands)\n"
  95. " '-q' use Quiet mode - do not print any output (except errors)\n"
  96. " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
  97. " contain only zeros for qemu-img to create a sparse image during\n"
  98. " conversion. If the number of bytes is 0, the source will not be scanned for\n"
  99. " unallocated or zero sectors, and the destination image will always be\n"
  100. " fully allocated\n"
  101. " '--output' takes the format in which the output must be done (human or json)\n"
  102. " '-n' skips the target volume creation (useful if the volume is created\n"
  103. " prior to running qemu-img)\n"
  104. "\n"
  105. "Parameters to check subcommand:\n"
  106. " '-r' tries to repair any inconsistencies that are found during the check.\n"
  107. " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
  108. " kinds of errors, with a higher risk of choosing the wrong fix or\n"
  109. " hiding corruption that has already occurred.\n"
  110. "\n"
  111. "Parameters to snapshot subcommand:\n"
  112. " 'snapshot' is the name of the snapshot to create, apply or delete\n"
  113. " '-a' applies a snapshot (revert disk to saved state)\n"
  114. " '-c' creates a snapshot\n"
  115. " '-d' deletes a snapshot\n"
  116. " '-l' lists all snapshots in the given image\n"
  117. "\n"
  118. "Parameters to compare subcommand:\n"
  119. " '-f' first image format\n"
  120. " '-F' second image format\n"
  121. " '-s' run in Strict mode - fail on different image size or sector allocation\n";
  122. printf("%s\nSupported formats:", help_msg);
  123. bdrv_iterate_format(format_print, NULL);
  124. printf("\n");
  125. exit(1);
  126. }
  127. static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
  128. {
  129. int ret = 0;
  130. if (!quiet) {
  131. va_list args;
  132. va_start(args, fmt);
  133. ret = vprintf(fmt, args);
  134. va_end(args);
  135. }
  136. return ret;
  137. }
  138. #if defined(WIN32)
  139. /* XXX: put correct support for win32 */
  140. static int read_password(char *buf, int buf_size)
  141. {
  142. int c, i;
  143. printf("Password: ");
  144. fflush(stdout);
  145. i = 0;
  146. for(;;) {
  147. c = getchar();
  148. if (c == '\n')
  149. break;
  150. if (i < (buf_size - 1))
  151. buf[i++] = c;
  152. }
  153. buf[i] = '\0';
  154. return 0;
  155. }
  156. #else
  157. #include <termios.h>
  158. static struct termios oldtty;
  159. static void term_exit(void)
  160. {
  161. tcsetattr (0, TCSANOW, &oldtty);
  162. }
  163. static void term_init(void)
  164. {
  165. struct termios tty;
  166. tcgetattr (0, &tty);
  167. oldtty = tty;
  168. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  169. |INLCR|IGNCR|ICRNL|IXON);
  170. tty.c_oflag |= OPOST;
  171. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  172. tty.c_cflag &= ~(CSIZE|PARENB);
  173. tty.c_cflag |= CS8;
  174. tty.c_cc[VMIN] = 1;
  175. tty.c_cc[VTIME] = 0;
  176. tcsetattr (0, TCSANOW, &tty);
  177. atexit(term_exit);
  178. }
  179. static int read_password(char *buf, int buf_size)
  180. {
  181. uint8_t ch;
  182. int i, ret;
  183. printf("password: ");
  184. fflush(stdout);
  185. term_init();
  186. i = 0;
  187. for(;;) {
  188. ret = read(0, &ch, 1);
  189. if (ret == -1) {
  190. if (errno == EAGAIN || errno == EINTR) {
  191. continue;
  192. } else {
  193. ret = -1;
  194. break;
  195. }
  196. } else if (ret == 0) {
  197. ret = -1;
  198. break;
  199. } else {
  200. if (ch == '\r') {
  201. ret = 0;
  202. break;
  203. }
  204. if (i < (buf_size - 1))
  205. buf[i++] = ch;
  206. }
  207. }
  208. term_exit();
  209. buf[i] = '\0';
  210. printf("\n");
  211. return ret;
  212. }
  213. #endif
  214. static int print_block_option_help(const char *filename, const char *fmt)
  215. {
  216. BlockDriver *drv, *proto_drv;
  217. QEMUOptionParameter *create_options = NULL;
  218. /* Find driver and parse its options */
  219. drv = bdrv_find_format(fmt);
  220. if (!drv) {
  221. error_report("Unknown file format '%s'", fmt);
  222. return 1;
  223. }
  224. create_options = append_option_parameters(create_options,
  225. drv->create_options);
  226. if (filename) {
  227. proto_drv = bdrv_find_protocol(filename, true);
  228. if (!proto_drv) {
  229. error_report("Unknown protocol '%s'", filename);
  230. return 1;
  231. }
  232. create_options = append_option_parameters(create_options,
  233. proto_drv->create_options);
  234. }
  235. print_option_help(create_options);
  236. free_option_parameters(create_options);
  237. return 0;
  238. }
  239. static BlockDriverState *bdrv_new_open(const char *filename,
  240. const char *fmt,
  241. int flags,
  242. bool require_io,
  243. bool quiet)
  244. {
  245. BlockDriverState *bs;
  246. BlockDriver *drv;
  247. char password[256];
  248. Error *local_err = NULL;
  249. int ret;
  250. bs = bdrv_new("image");
  251. if (fmt) {
  252. drv = bdrv_find_format(fmt);
  253. if (!drv) {
  254. error_report("Unknown file format '%s'", fmt);
  255. goto fail;
  256. }
  257. } else {
  258. drv = NULL;
  259. }
  260. ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);
  261. if (ret < 0) {
  262. error_report("Could not open '%s': %s", filename,
  263. error_get_pretty(local_err));
  264. error_free(local_err);
  265. goto fail;
  266. }
  267. if (bdrv_is_encrypted(bs) && require_io) {
  268. qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
  269. if (read_password(password, sizeof(password)) < 0) {
  270. error_report("No password given");
  271. goto fail;
  272. }
  273. if (bdrv_set_key(bs, password) < 0) {
  274. error_report("invalid password");
  275. goto fail;
  276. }
  277. }
  278. return bs;
  279. fail:
  280. bdrv_unref(bs);
  281. return NULL;
  282. }
  283. static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
  284. const char *base_filename,
  285. const char *base_fmt)
  286. {
  287. if (base_filename) {
  288. if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
  289. error_report("Backing file not supported for file format '%s'",
  290. fmt);
  291. return -1;
  292. }
  293. }
  294. if (base_fmt) {
  295. if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
  296. error_report("Backing file format not supported for file "
  297. "format '%s'", fmt);
  298. return -1;
  299. }
  300. }
  301. return 0;
  302. }
  303. static int img_create(int argc, char **argv)
  304. {
  305. int c;
  306. uint64_t img_size = -1;
  307. const char *fmt = "raw";
  308. const char *base_fmt = NULL;
  309. const char *filename;
  310. const char *base_filename = NULL;
  311. char *options = NULL;
  312. Error *local_err = NULL;
  313. bool quiet = false;
  314. for(;;) {
  315. c = getopt(argc, argv, "F:b:f:he6o:q");
  316. if (c == -1) {
  317. break;
  318. }
  319. switch(c) {
  320. case '?':
  321. case 'h':
  322. help();
  323. break;
  324. case 'F':
  325. base_fmt = optarg;
  326. break;
  327. case 'b':
  328. base_filename = optarg;
  329. break;
  330. case 'f':
  331. fmt = optarg;
  332. break;
  333. case 'e':
  334. error_report("option -e is deprecated, please use \'-o "
  335. "encryption\' instead!");
  336. goto fail;
  337. case '6':
  338. error_report("option -6 is deprecated, please use \'-o "
  339. "compat6\' instead!");
  340. goto fail;
  341. case 'o':
  342. if (!is_valid_option_list(optarg)) {
  343. error_report("Invalid option list: %s", optarg);
  344. goto fail;
  345. }
  346. if (!options) {
  347. options = g_strdup(optarg);
  348. } else {
  349. char *old_options = options;
  350. options = g_strdup_printf("%s,%s", options, optarg);
  351. g_free(old_options);
  352. }
  353. break;
  354. case 'q':
  355. quiet = true;
  356. break;
  357. }
  358. }
  359. /* Get the filename */
  360. filename = (optind < argc) ? argv[optind] : NULL;
  361. if (options && has_help_option(options)) {
  362. g_free(options);
  363. return print_block_option_help(filename, fmt);
  364. }
  365. if (optind >= argc) {
  366. help();
  367. }
  368. optind++;
  369. /* Get image size, if specified */
  370. if (optind < argc) {
  371. int64_t sval;
  372. char *end;
  373. sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
  374. if (sval < 0 || *end) {
  375. if (sval == -ERANGE) {
  376. error_report("Image size must be less than 8 EiB!");
  377. } else {
  378. error_report("Invalid image size specified! You may use k, M, "
  379. "G, T, P or E suffixes for ");
  380. error_report("kilobytes, megabytes, gigabytes, terabytes, "
  381. "petabytes and exabytes.");
  382. }
  383. goto fail;
  384. }
  385. img_size = (uint64_t)sval;
  386. }
  387. if (optind != argc) {
  388. help();
  389. }
  390. bdrv_img_create(filename, fmt, base_filename, base_fmt,
  391. options, img_size, BDRV_O_FLAGS, &local_err, quiet);
  392. if (local_err) {
  393. error_report("%s: %s", filename, error_get_pretty(local_err));
  394. error_free(local_err);
  395. goto fail;
  396. }
  397. g_free(options);
  398. return 0;
  399. fail:
  400. g_free(options);
  401. return 1;
  402. }
  403. static void dump_json_image_check(ImageCheck *check, bool quiet)
  404. {
  405. Error *errp = NULL;
  406. QString *str;
  407. QmpOutputVisitor *ov = qmp_output_visitor_new();
  408. QObject *obj;
  409. visit_type_ImageCheck(qmp_output_get_visitor(ov),
  410. &check, NULL, &errp);
  411. obj = qmp_output_get_qobject(ov);
  412. str = qobject_to_json_pretty(obj);
  413. assert(str != NULL);
  414. qprintf(quiet, "%s\n", qstring_get_str(str));
  415. qobject_decref(obj);
  416. qmp_output_visitor_cleanup(ov);
  417. QDECREF(str);
  418. }
  419. static void dump_human_image_check(ImageCheck *check, bool quiet)
  420. {
  421. if (!(check->corruptions || check->leaks || check->check_errors)) {
  422. qprintf(quiet, "No errors were found on the image.\n");
  423. } else {
  424. if (check->corruptions) {
  425. qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
  426. "Data may be corrupted, or further writes to the image "
  427. "may corrupt it.\n",
  428. check->corruptions);
  429. }
  430. if (check->leaks) {
  431. qprintf(quiet,
  432. "\n%" PRId64 " leaked clusters were found on the image.\n"
  433. "This means waste of disk space, but no harm to data.\n",
  434. check->leaks);
  435. }
  436. if (check->check_errors) {
  437. qprintf(quiet,
  438. "\n%" PRId64
  439. " internal errors have occurred during the check.\n",
  440. check->check_errors);
  441. }
  442. }
  443. if (check->total_clusters != 0 && check->allocated_clusters != 0) {
  444. qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
  445. "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
  446. check->allocated_clusters, check->total_clusters,
  447. check->allocated_clusters * 100.0 / check->total_clusters,
  448. check->fragmented_clusters * 100.0 / check->allocated_clusters,
  449. check->compressed_clusters * 100.0 /
  450. check->allocated_clusters);
  451. }
  452. if (check->image_end_offset) {
  453. qprintf(quiet,
  454. "Image end offset: %" PRId64 "\n", check->image_end_offset);
  455. }
  456. }
  457. static int collect_image_check(BlockDriverState *bs,
  458. ImageCheck *check,
  459. const char *filename,
  460. const char *fmt,
  461. int fix)
  462. {
  463. int ret;
  464. BdrvCheckResult result;
  465. ret = bdrv_check(bs, &result, fix);
  466. if (ret < 0) {
  467. return ret;
  468. }
  469. check->filename = g_strdup(filename);
  470. check->format = g_strdup(bdrv_get_format_name(bs));
  471. check->check_errors = result.check_errors;
  472. check->corruptions = result.corruptions;
  473. check->has_corruptions = result.corruptions != 0;
  474. check->leaks = result.leaks;
  475. check->has_leaks = result.leaks != 0;
  476. check->corruptions_fixed = result.corruptions_fixed;
  477. check->has_corruptions_fixed = result.corruptions != 0;
  478. check->leaks_fixed = result.leaks_fixed;
  479. check->has_leaks_fixed = result.leaks != 0;
  480. check->image_end_offset = result.image_end_offset;
  481. check->has_image_end_offset = result.image_end_offset != 0;
  482. check->total_clusters = result.bfi.total_clusters;
  483. check->has_total_clusters = result.bfi.total_clusters != 0;
  484. check->allocated_clusters = result.bfi.allocated_clusters;
  485. check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
  486. check->fragmented_clusters = result.bfi.fragmented_clusters;
  487. check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
  488. check->compressed_clusters = result.bfi.compressed_clusters;
  489. check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
  490. return 0;
  491. }
  492. /*
  493. * Checks an image for consistency. Exit codes:
  494. *
  495. * 0 - Check completed, image is good
  496. * 1 - Check not completed because of internal errors
  497. * 2 - Check completed, image is corrupted
  498. * 3 - Check completed, image has leaked clusters, but is good otherwise
  499. */
  500. static int img_check(int argc, char **argv)
  501. {
  502. int c, ret;
  503. OutputFormat output_format = OFORMAT_HUMAN;
  504. const char *filename, *fmt, *output;
  505. BlockDriverState *bs;
  506. int fix = 0;
  507. int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
  508. ImageCheck *check;
  509. bool quiet = false;
  510. fmt = NULL;
  511. output = NULL;
  512. for(;;) {
  513. int option_index = 0;
  514. static const struct option long_options[] = {
  515. {"help", no_argument, 0, 'h'},
  516. {"format", required_argument, 0, 'f'},
  517. {"repair", required_argument, 0, 'r'},
  518. {"output", required_argument, 0, OPTION_OUTPUT},
  519. {0, 0, 0, 0}
  520. };
  521. c = getopt_long(argc, argv, "f:hr:q",
  522. long_options, &option_index);
  523. if (c == -1) {
  524. break;
  525. }
  526. switch(c) {
  527. case '?':
  528. case 'h':
  529. help();
  530. break;
  531. case 'f':
  532. fmt = optarg;
  533. break;
  534. case 'r':
  535. flags |= BDRV_O_RDWR;
  536. if (!strcmp(optarg, "leaks")) {
  537. fix = BDRV_FIX_LEAKS;
  538. } else if (!strcmp(optarg, "all")) {
  539. fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
  540. } else {
  541. help();
  542. }
  543. break;
  544. case OPTION_OUTPUT:
  545. output = optarg;
  546. break;
  547. case 'q':
  548. quiet = true;
  549. break;
  550. }
  551. }
  552. if (optind != argc - 1) {
  553. help();
  554. }
  555. filename = argv[optind++];
  556. if (output && !strcmp(output, "json")) {
  557. output_format = OFORMAT_JSON;
  558. } else if (output && !strcmp(output, "human")) {
  559. output_format = OFORMAT_HUMAN;
  560. } else if (output) {
  561. error_report("--output must be used with human or json as argument.");
  562. return 1;
  563. }
  564. bs = bdrv_new_open(filename, fmt, flags, true, quiet);
  565. if (!bs) {
  566. return 1;
  567. }
  568. check = g_new0(ImageCheck, 1);
  569. ret = collect_image_check(bs, check, filename, fmt, fix);
  570. if (ret == -ENOTSUP) {
  571. if (output_format == OFORMAT_HUMAN) {
  572. error_report("This image format does not support checks");
  573. }
  574. ret = 63;
  575. goto fail;
  576. }
  577. if (check->corruptions_fixed || check->leaks_fixed) {
  578. int corruptions_fixed, leaks_fixed;
  579. leaks_fixed = check->leaks_fixed;
  580. corruptions_fixed = check->corruptions_fixed;
  581. if (output_format == OFORMAT_HUMAN) {
  582. qprintf(quiet,
  583. "The following inconsistencies were found and repaired:\n\n"
  584. " %" PRId64 " leaked clusters\n"
  585. " %" PRId64 " corruptions\n\n"
  586. "Double checking the fixed image now...\n",
  587. check->leaks_fixed,
  588. check->corruptions_fixed);
  589. }
  590. ret = collect_image_check(bs, check, filename, fmt, 0);
  591. check->leaks_fixed = leaks_fixed;
  592. check->corruptions_fixed = corruptions_fixed;
  593. }
  594. switch (output_format) {
  595. case OFORMAT_HUMAN:
  596. dump_human_image_check(check, quiet);
  597. break;
  598. case OFORMAT_JSON:
  599. dump_json_image_check(check, quiet);
  600. break;
  601. }
  602. if (ret || check->check_errors) {
  603. ret = 1;
  604. goto fail;
  605. }
  606. if (check->corruptions) {
  607. ret = 2;
  608. } else if (check->leaks) {
  609. ret = 3;
  610. } else {
  611. ret = 0;
  612. }
  613. fail:
  614. qapi_free_ImageCheck(check);
  615. bdrv_unref(bs);
  616. return ret;
  617. }
  618. static int img_commit(int argc, char **argv)
  619. {
  620. int c, ret, flags;
  621. const char *filename, *fmt, *cache;
  622. BlockDriverState *bs;
  623. bool quiet = false;
  624. fmt = NULL;
  625. cache = BDRV_DEFAULT_CACHE;
  626. for(;;) {
  627. c = getopt(argc, argv, "f:ht:q");
  628. if (c == -1) {
  629. break;
  630. }
  631. switch(c) {
  632. case '?':
  633. case 'h':
  634. help();
  635. break;
  636. case 'f':
  637. fmt = optarg;
  638. break;
  639. case 't':
  640. cache = optarg;
  641. break;
  642. case 'q':
  643. quiet = true;
  644. break;
  645. }
  646. }
  647. if (optind != argc - 1) {
  648. help();
  649. }
  650. filename = argv[optind++];
  651. flags = BDRV_O_RDWR;
  652. ret = bdrv_parse_cache_flags(cache, &flags);
  653. if (ret < 0) {
  654. error_report("Invalid cache option: %s", cache);
  655. return -1;
  656. }
  657. bs = bdrv_new_open(filename, fmt, flags, true, quiet);
  658. if (!bs) {
  659. return 1;
  660. }
  661. ret = bdrv_commit(bs);
  662. switch(ret) {
  663. case 0:
  664. qprintf(quiet, "Image committed.\n");
  665. break;
  666. case -ENOENT:
  667. error_report("No disk inserted");
  668. break;
  669. case -EACCES:
  670. error_report("Image is read-only");
  671. break;
  672. case -ENOTSUP:
  673. error_report("Image is already committed");
  674. break;
  675. default:
  676. error_report("Error while committing image");
  677. break;
  678. }
  679. bdrv_unref(bs);
  680. if (ret) {
  681. return 1;
  682. }
  683. return 0;
  684. }
  685. /*
  686. * Returns true iff the first sector pointed to by 'buf' contains at least
  687. * a non-NUL byte.
  688. *
  689. * 'pnum' is set to the number of sectors (including and immediately following
  690. * the first one) that are known to be in the same allocated/unallocated state.
  691. */
  692. static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
  693. {
  694. bool is_zero;
  695. int i;
  696. if (n <= 0) {
  697. *pnum = 0;
  698. return 0;
  699. }
  700. is_zero = buffer_is_zero(buf, 512);
  701. for(i = 1; i < n; i++) {
  702. buf += 512;
  703. if (is_zero != buffer_is_zero(buf, 512)) {
  704. break;
  705. }
  706. }
  707. *pnum = i;
  708. return !is_zero;
  709. }
  710. /*
  711. * Like is_allocated_sectors, but if the buffer starts with a used sector,
  712. * up to 'min' consecutive sectors containing zeros are ignored. This avoids
  713. * breaking up write requests for only small sparse areas.
  714. */
  715. static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
  716. int min)
  717. {
  718. int ret;
  719. int num_checked, num_used;
  720. if (n < min) {
  721. min = n;
  722. }
  723. ret = is_allocated_sectors(buf, n, pnum);
  724. if (!ret) {
  725. return ret;
  726. }
  727. num_used = *pnum;
  728. buf += BDRV_SECTOR_SIZE * *pnum;
  729. n -= *pnum;
  730. num_checked = num_used;
  731. while (n > 0) {
  732. ret = is_allocated_sectors(buf, n, pnum);
  733. buf += BDRV_SECTOR_SIZE * *pnum;
  734. n -= *pnum;
  735. num_checked += *pnum;
  736. if (ret) {
  737. num_used = num_checked;
  738. } else if (*pnum >= min) {
  739. break;
  740. }
  741. }
  742. *pnum = num_used;
  743. return 1;
  744. }
  745. /*
  746. * Compares two buffers sector by sector. Returns 0 if the first sector of both
  747. * buffers matches, non-zero otherwise.
  748. *
  749. * pnum is set to the number of sectors (including and immediately following
  750. * the first one) that are known to have the same comparison result
  751. */
  752. static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
  753. int *pnum)
  754. {
  755. int res, i;
  756. if (n <= 0) {
  757. *pnum = 0;
  758. return 0;
  759. }
  760. res = !!memcmp(buf1, buf2, 512);
  761. for(i = 1; i < n; i++) {
  762. buf1 += 512;
  763. buf2 += 512;
  764. if (!!memcmp(buf1, buf2, 512) != res) {
  765. break;
  766. }
  767. }
  768. *pnum = i;
  769. return res;
  770. }
  771. #define IO_BUF_SIZE (2 * 1024 * 1024)
  772. static int64_t sectors_to_bytes(int64_t sectors)
  773. {
  774. return sectors << BDRV_SECTOR_BITS;
  775. }
  776. static int64_t sectors_to_process(int64_t total, int64_t from)
  777. {
  778. return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
  779. }
  780. /*
  781. * Check if passed sectors are empty (not allocated or contain only 0 bytes)
  782. *
  783. * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
  784. * data and negative value on error.
  785. *
  786. * @param bs: Driver used for accessing file
  787. * @param sect_num: Number of first sector to check
  788. * @param sect_count: Number of sectors to check
  789. * @param filename: Name of disk file we are checking (logging purpose)
  790. * @param buffer: Allocated buffer for storing read data
  791. * @param quiet: Flag for quiet mode
  792. */
  793. static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
  794. int sect_count, const char *filename,
  795. uint8_t *buffer, bool quiet)
  796. {
  797. int pnum, ret = 0;
  798. ret = bdrv_read(bs, sect_num, buffer, sect_count);
  799. if (ret < 0) {
  800. error_report("Error while reading offset %" PRId64 " of %s: %s",
  801. sectors_to_bytes(sect_num), filename, strerror(-ret));
  802. return ret;
  803. }
  804. ret = is_allocated_sectors(buffer, sect_count, &pnum);
  805. if (ret || pnum != sect_count) {
  806. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  807. sectors_to_bytes(ret ? sect_num : sect_num + pnum));
  808. return 1;
  809. }
  810. return 0;
  811. }
  812. /*
  813. * Compares two images. Exit codes:
  814. *
  815. * 0 - Images are identical
  816. * 1 - Images differ
  817. * >1 - Error occurred
  818. */
  819. static int img_compare(int argc, char **argv)
  820. {
  821. const char *fmt1 = NULL, *fmt2 = NULL, *filename1, *filename2;
  822. BlockDriverState *bs1, *bs2;
  823. int64_t total_sectors1, total_sectors2;
  824. uint8_t *buf1 = NULL, *buf2 = NULL;
  825. int pnum1, pnum2;
  826. int allocated1, allocated2;
  827. int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
  828. bool progress = false, quiet = false, strict = false;
  829. int64_t total_sectors;
  830. int64_t sector_num = 0;
  831. int64_t nb_sectors;
  832. int c, pnum;
  833. uint64_t bs_sectors;
  834. uint64_t progress_base;
  835. for (;;) {
  836. c = getopt(argc, argv, "hpf:F:sq");
  837. if (c == -1) {
  838. break;
  839. }
  840. switch (c) {
  841. case '?':
  842. case 'h':
  843. help();
  844. break;
  845. case 'f':
  846. fmt1 = optarg;
  847. break;
  848. case 'F':
  849. fmt2 = optarg;
  850. break;
  851. case 'p':
  852. progress = true;
  853. break;
  854. case 'q':
  855. quiet = true;
  856. break;
  857. case 's':
  858. strict = true;
  859. break;
  860. }
  861. }
  862. /* Progress is not shown in Quiet mode */
  863. if (quiet) {
  864. progress = false;
  865. }
  866. if (optind != argc - 2) {
  867. help();
  868. }
  869. filename1 = argv[optind++];
  870. filename2 = argv[optind++];
  871. /* Initialize before goto out */
  872. qemu_progress_init(progress, 2.0);
  873. bs1 = bdrv_new_open(filename1, fmt1, BDRV_O_FLAGS, true, quiet);
  874. if (!bs1) {
  875. error_report("Can't open file %s", filename1);
  876. ret = 2;
  877. goto out3;
  878. }
  879. bs2 = bdrv_new_open(filename2, fmt2, BDRV_O_FLAGS, true, quiet);
  880. if (!bs2) {
  881. error_report("Can't open file %s", filename2);
  882. ret = 2;
  883. goto out2;
  884. }
  885. buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
  886. buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
  887. bdrv_get_geometry(bs1, &bs_sectors);
  888. total_sectors1 = bs_sectors;
  889. bdrv_get_geometry(bs2, &bs_sectors);
  890. total_sectors2 = bs_sectors;
  891. total_sectors = MIN(total_sectors1, total_sectors2);
  892. progress_base = MAX(total_sectors1, total_sectors2);
  893. qemu_progress_print(0, 100);
  894. if (strict && total_sectors1 != total_sectors2) {
  895. ret = 1;
  896. qprintf(quiet, "Strict mode: Image size mismatch!\n");
  897. goto out;
  898. }
  899. for (;;) {
  900. nb_sectors = sectors_to_process(total_sectors, sector_num);
  901. if (nb_sectors <= 0) {
  902. break;
  903. }
  904. allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
  905. &pnum1);
  906. if (allocated1 < 0) {
  907. ret = 3;
  908. error_report("Sector allocation test failed for %s", filename1);
  909. goto out;
  910. }
  911. allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
  912. &pnum2);
  913. if (allocated2 < 0) {
  914. ret = 3;
  915. error_report("Sector allocation test failed for %s", filename2);
  916. goto out;
  917. }
  918. nb_sectors = MIN(pnum1, pnum2);
  919. if (allocated1 == allocated2) {
  920. if (allocated1) {
  921. ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
  922. if (ret < 0) {
  923. error_report("Error while reading offset %" PRId64 " of %s:"
  924. " %s", sectors_to_bytes(sector_num), filename1,
  925. strerror(-ret));
  926. ret = 4;
  927. goto out;
  928. }
  929. ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
  930. if (ret < 0) {
  931. error_report("Error while reading offset %" PRId64
  932. " of %s: %s", sectors_to_bytes(sector_num),
  933. filename2, strerror(-ret));
  934. ret = 4;
  935. goto out;
  936. }
  937. ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
  938. if (ret || pnum != nb_sectors) {
  939. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  940. sectors_to_bytes(
  941. ret ? sector_num : sector_num + pnum));
  942. ret = 1;
  943. goto out;
  944. }
  945. }
  946. } else {
  947. if (strict) {
  948. ret = 1;
  949. qprintf(quiet, "Strict mode: Offset %" PRId64
  950. " allocation mismatch!\n",
  951. sectors_to_bytes(sector_num));
  952. goto out;
  953. }
  954. if (allocated1) {
  955. ret = check_empty_sectors(bs1, sector_num, nb_sectors,
  956. filename1, buf1, quiet);
  957. } else {
  958. ret = check_empty_sectors(bs2, sector_num, nb_sectors,
  959. filename2, buf1, quiet);
  960. }
  961. if (ret) {
  962. if (ret < 0) {
  963. error_report("Error while reading offset %" PRId64 ": %s",
  964. sectors_to_bytes(sector_num), strerror(-ret));
  965. ret = 4;
  966. }
  967. goto out;
  968. }
  969. }
  970. sector_num += nb_sectors;
  971. qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
  972. }
  973. if (total_sectors1 != total_sectors2) {
  974. BlockDriverState *bs_over;
  975. int64_t total_sectors_over;
  976. const char *filename_over;
  977. qprintf(quiet, "Warning: Image size mismatch!\n");
  978. if (total_sectors1 > total_sectors2) {
  979. total_sectors_over = total_sectors1;
  980. bs_over = bs1;
  981. filename_over = filename1;
  982. } else {
  983. total_sectors_over = total_sectors2;
  984. bs_over = bs2;
  985. filename_over = filename2;
  986. }
  987. for (;;) {
  988. nb_sectors = sectors_to_process(total_sectors_over, sector_num);
  989. if (nb_sectors <= 0) {
  990. break;
  991. }
  992. ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
  993. nb_sectors, &pnum);
  994. if (ret < 0) {
  995. ret = 3;
  996. error_report("Sector allocation test failed for %s",
  997. filename_over);
  998. goto out;
  999. }
  1000. nb_sectors = pnum;
  1001. if (ret) {
  1002. ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
  1003. filename_over, buf1, quiet);
  1004. if (ret) {
  1005. if (ret < 0) {
  1006. error_report("Error while reading offset %" PRId64
  1007. " of %s: %s", sectors_to_bytes(sector_num),
  1008. filename_over, strerror(-ret));
  1009. ret = 4;
  1010. }
  1011. goto out;
  1012. }
  1013. }
  1014. sector_num += nb_sectors;
  1015. qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
  1016. }
  1017. }
  1018. qprintf(quiet, "Images are identical.\n");
  1019. ret = 0;
  1020. out:
  1021. bdrv_unref(bs2);
  1022. qemu_vfree(buf1);
  1023. qemu_vfree(buf2);
  1024. out2:
  1025. bdrv_unref(bs1);
  1026. out3:
  1027. qemu_progress_end();
  1028. return ret;
  1029. }
  1030. static int img_convert(int argc, char **argv)
  1031. {
  1032. int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
  1033. int64_t ret = 0;
  1034. int progress = 0, flags;
  1035. const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
  1036. BlockDriver *drv, *proto_drv;
  1037. BlockDriverState **bs = NULL, *out_bs = NULL;
  1038. int64_t total_sectors, nb_sectors, sector_num, bs_offset;
  1039. uint64_t bs_sectors;
  1040. uint8_t * buf = NULL;
  1041. size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
  1042. const uint8_t *buf1;
  1043. BlockDriverInfo bdi;
  1044. QEMUOptionParameter *param = NULL, *create_options = NULL;
  1045. QEMUOptionParameter *out_baseimg_param;
  1046. char *options = NULL;
  1047. const char *snapshot_name = NULL;
  1048. int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
  1049. bool quiet = false;
  1050. Error *local_err = NULL;
  1051. QemuOpts *sn_opts = NULL;
  1052. fmt = NULL;
  1053. out_fmt = "raw";
  1054. cache = "unsafe";
  1055. out_baseimg = NULL;
  1056. compress = 0;
  1057. skip_create = 0;
  1058. for(;;) {
  1059. c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:qnl:");
  1060. if (c == -1) {
  1061. break;
  1062. }
  1063. switch(c) {
  1064. case '?':
  1065. case 'h':
  1066. help();
  1067. break;
  1068. case 'f':
  1069. fmt = optarg;
  1070. break;
  1071. case 'O':
  1072. out_fmt = optarg;
  1073. break;
  1074. case 'B':
  1075. out_baseimg = optarg;
  1076. break;
  1077. case 'c':
  1078. compress = 1;
  1079. break;
  1080. case 'e':
  1081. error_report("option -e is deprecated, please use \'-o "
  1082. "encryption\' instead!");
  1083. ret = -1;
  1084. goto fail_getopt;
  1085. case '6':
  1086. error_report("option -6 is deprecated, please use \'-o "
  1087. "compat6\' instead!");
  1088. ret = -1;
  1089. goto fail_getopt;
  1090. case 'o':
  1091. if (!is_valid_option_list(optarg)) {
  1092. error_report("Invalid option list: %s", optarg);
  1093. ret = -1;
  1094. goto fail_getopt;
  1095. }
  1096. if (!options) {
  1097. options = g_strdup(optarg);
  1098. } else {
  1099. char *old_options = options;
  1100. options = g_strdup_printf("%s,%s", options, optarg);
  1101. g_free(old_options);
  1102. }
  1103. break;
  1104. case 's':
  1105. snapshot_name = optarg;
  1106. break;
  1107. case 'l':
  1108. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  1109. sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
  1110. if (!sn_opts) {
  1111. error_report("Failed in parsing snapshot param '%s'",
  1112. optarg);
  1113. ret = -1;
  1114. goto fail_getopt;
  1115. }
  1116. } else {
  1117. snapshot_name = optarg;
  1118. }
  1119. break;
  1120. case 'S':
  1121. {
  1122. int64_t sval;
  1123. char *end;
  1124. sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
  1125. if (sval < 0 || *end) {
  1126. error_report("Invalid minimum zero buffer size for sparse output specified");
  1127. ret = -1;
  1128. goto fail_getopt;
  1129. }
  1130. min_sparse = sval / BDRV_SECTOR_SIZE;
  1131. break;
  1132. }
  1133. case 'p':
  1134. progress = 1;
  1135. break;
  1136. case 't':
  1137. cache = optarg;
  1138. break;
  1139. case 'q':
  1140. quiet = true;
  1141. break;
  1142. case 'n':
  1143. skip_create = 1;
  1144. break;
  1145. }
  1146. }
  1147. /* Initialize before goto out */
  1148. if (quiet) {
  1149. progress = 0;
  1150. }
  1151. qemu_progress_init(progress, 1.0);
  1152. bs_n = argc - optind - 1;
  1153. out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
  1154. if (options && has_help_option(options)) {
  1155. ret = print_block_option_help(out_filename, out_fmt);
  1156. goto out;
  1157. }
  1158. if (bs_n < 1) {
  1159. help();
  1160. }
  1161. if (bs_n > 1 && out_baseimg) {
  1162. error_report("-B makes no sense when concatenating multiple input "
  1163. "images");
  1164. ret = -1;
  1165. goto out;
  1166. }
  1167. qemu_progress_print(0, 100);
  1168. bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
  1169. total_sectors = 0;
  1170. for (bs_i = 0; bs_i < bs_n; bs_i++) {
  1171. bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
  1172. quiet);
  1173. if (!bs[bs_i]) {
  1174. error_report("Could not open '%s'", argv[optind + bs_i]);
  1175. ret = -1;
  1176. goto out;
  1177. }
  1178. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  1179. total_sectors += bs_sectors;
  1180. }
  1181. if (sn_opts) {
  1182. ret = bdrv_snapshot_load_tmp(bs[0],
  1183. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  1184. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  1185. &local_err);
  1186. } else if (snapshot_name != NULL) {
  1187. if (bs_n > 1) {
  1188. error_report("No support for concatenating multiple snapshot");
  1189. ret = -1;
  1190. goto out;
  1191. }
  1192. bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
  1193. }
  1194. if (local_err) {
  1195. error_report("Failed to load snapshot: %s",
  1196. error_get_pretty(local_err));
  1197. error_free(local_err);
  1198. ret = -1;
  1199. goto out;
  1200. }
  1201. /* Find driver and parse its options */
  1202. drv = bdrv_find_format(out_fmt);
  1203. if (!drv) {
  1204. error_report("Unknown file format '%s'", out_fmt);
  1205. ret = -1;
  1206. goto out;
  1207. }
  1208. proto_drv = bdrv_find_protocol(out_filename, true);
  1209. if (!proto_drv) {
  1210. error_report("Unknown protocol '%s'", out_filename);
  1211. ret = -1;
  1212. goto out;
  1213. }
  1214. create_options = append_option_parameters(create_options,
  1215. drv->create_options);
  1216. create_options = append_option_parameters(create_options,
  1217. proto_drv->create_options);
  1218. if (options) {
  1219. param = parse_option_parameters(options, create_options, param);
  1220. if (param == NULL) {
  1221. error_report("Invalid options for file format '%s'.", out_fmt);
  1222. ret = -1;
  1223. goto out;
  1224. }
  1225. } else {
  1226. param = parse_option_parameters("", create_options, param);
  1227. }
  1228. set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
  1229. ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
  1230. if (ret < 0) {
  1231. goto out;
  1232. }
  1233. /* Get backing file name if -o backing_file was used */
  1234. out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
  1235. if (out_baseimg_param) {
  1236. out_baseimg = out_baseimg_param->value.s;
  1237. }
  1238. /* Check if compression is supported */
  1239. if (compress) {
  1240. QEMUOptionParameter *encryption =
  1241. get_option_parameter(param, BLOCK_OPT_ENCRYPT);
  1242. QEMUOptionParameter *preallocation =
  1243. get_option_parameter(param, BLOCK_OPT_PREALLOC);
  1244. if (!drv->bdrv_write_compressed) {
  1245. error_report("Compression not supported for this file format");
  1246. ret = -1;
  1247. goto out;
  1248. }
  1249. if (encryption && encryption->value.n) {
  1250. error_report("Compression and encryption not supported at "
  1251. "the same time");
  1252. ret = -1;
  1253. goto out;
  1254. }
  1255. if (preallocation && preallocation->value.s
  1256. && strcmp(preallocation->value.s, "off"))
  1257. {
  1258. error_report("Compression and preallocation not supported at "
  1259. "the same time");
  1260. ret = -1;
  1261. goto out;
  1262. }
  1263. }
  1264. if (!skip_create) {
  1265. /* Create the new image */
  1266. ret = bdrv_create(drv, out_filename, param, &local_err);
  1267. if (ret < 0) {
  1268. error_report("%s: error while converting %s: %s",
  1269. out_filename, out_fmt, error_get_pretty(local_err));
  1270. error_free(local_err);
  1271. goto out;
  1272. }
  1273. }
  1274. flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
  1275. ret = bdrv_parse_cache_flags(cache, &flags);
  1276. if (ret < 0) {
  1277. error_report("Invalid cache option: %s", cache);
  1278. goto out;
  1279. }
  1280. out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
  1281. if (!out_bs) {
  1282. ret = -1;
  1283. goto out;
  1284. }
  1285. bs_i = 0;
  1286. bs_offset = 0;
  1287. bdrv_get_geometry(bs[0], &bs_sectors);
  1288. /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
  1289. * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
  1290. * as maximum. */
  1291. bufsectors = MIN(32768,
  1292. MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
  1293. out_bs->bl.discard_alignment))
  1294. );
  1295. buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
  1296. if (skip_create) {
  1297. int64_t output_length = bdrv_getlength(out_bs);
  1298. if (output_length < 0) {
  1299. error_report("unable to get output image length: %s\n",
  1300. strerror(-output_length));
  1301. ret = -1;
  1302. goto out;
  1303. } else if (output_length < total_sectors << BDRV_SECTOR_BITS) {
  1304. error_report("output file is smaller than input file");
  1305. ret = -1;
  1306. goto out;
  1307. }
  1308. }
  1309. cluster_sectors = 0;
  1310. ret = bdrv_get_info(out_bs, &bdi);
  1311. if (ret < 0) {
  1312. if (compress) {
  1313. error_report("could not get block driver info");
  1314. goto out;
  1315. }
  1316. } else {
  1317. cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
  1318. }
  1319. if (compress) {
  1320. if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
  1321. error_report("invalid cluster size");
  1322. ret = -1;
  1323. goto out;
  1324. }
  1325. sector_num = 0;
  1326. nb_sectors = total_sectors;
  1327. for(;;) {
  1328. int64_t bs_num;
  1329. int remainder;
  1330. uint8_t *buf2;
  1331. nb_sectors = total_sectors - sector_num;
  1332. if (nb_sectors <= 0)
  1333. break;
  1334. if (nb_sectors >= cluster_sectors)
  1335. n = cluster_sectors;
  1336. else
  1337. n = nb_sectors;
  1338. bs_num = sector_num - bs_offset;
  1339. assert (bs_num >= 0);
  1340. remainder = n;
  1341. buf2 = buf;
  1342. while (remainder > 0) {
  1343. int nlow;
  1344. while (bs_num == bs_sectors) {
  1345. bs_i++;
  1346. assert (bs_i < bs_n);
  1347. bs_offset += bs_sectors;
  1348. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  1349. bs_num = 0;
  1350. /* printf("changing part: sector_num=%" PRId64 ", "
  1351. "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
  1352. "\n", sector_num, bs_i, bs_offset, bs_sectors); */
  1353. }
  1354. assert (bs_num < bs_sectors);
  1355. nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
  1356. ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
  1357. if (ret < 0) {
  1358. error_report("error while reading sector %" PRId64 ": %s",
  1359. bs_num, strerror(-ret));
  1360. goto out;
  1361. }
  1362. buf2 += nlow * 512;
  1363. bs_num += nlow;
  1364. remainder -= nlow;
  1365. }
  1366. assert (remainder == 0);
  1367. if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
  1368. ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
  1369. if (ret != 0) {
  1370. error_report("error while compressing sector %" PRId64
  1371. ": %s", sector_num, strerror(-ret));
  1372. goto out;
  1373. }
  1374. }
  1375. sector_num += n;
  1376. qemu_progress_print(100.0 * sector_num / total_sectors, 0);
  1377. }
  1378. /* signal EOF to align */
  1379. bdrv_write_compressed(out_bs, 0, NULL, 0);
  1380. } else {
  1381. int64_t sectors_to_read, sectors_read, sector_num_next_status;
  1382. bool count_allocated_sectors;
  1383. int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
  1384. if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
  1385. ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
  1386. if (ret < 0) {
  1387. goto out;
  1388. }
  1389. has_zero_init = 1;
  1390. }
  1391. sectors_to_read = total_sectors;
  1392. count_allocated_sectors = progress && (out_baseimg || has_zero_init);
  1393. restart:
  1394. sector_num = 0; // total number of sectors converted so far
  1395. sectors_read = 0;
  1396. sector_num_next_status = 0;
  1397. for(;;) {
  1398. nb_sectors = total_sectors - sector_num;
  1399. if (nb_sectors <= 0) {
  1400. if (count_allocated_sectors) {
  1401. sectors_to_read = sectors_read;
  1402. count_allocated_sectors = false;
  1403. goto restart;
  1404. }
  1405. ret = 0;
  1406. break;
  1407. }
  1408. while (sector_num - bs_offset >= bs_sectors) {
  1409. bs_i ++;
  1410. assert (bs_i < bs_n);
  1411. bs_offset += bs_sectors;
  1412. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  1413. /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
  1414. "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
  1415. sector_num, bs_i, bs_offset, bs_sectors); */
  1416. }
  1417. if ((out_baseimg || has_zero_init) &&
  1418. sector_num >= sector_num_next_status) {
  1419. n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
  1420. ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
  1421. n, &n1);
  1422. if (ret < 0) {
  1423. error_report("error while reading block status of sector %"
  1424. PRId64 ": %s", sector_num - bs_offset,
  1425. strerror(-ret));
  1426. goto out;
  1427. }
  1428. /* If the output image is zero initialized, we are not working
  1429. * on a shared base and the input is zero we can skip the next
  1430. * n1 sectors */
  1431. if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
  1432. sector_num += n1;
  1433. continue;
  1434. }
  1435. /* If the output image is being created as a copy on write
  1436. * image, assume that sectors which are unallocated in the
  1437. * input image are present in both the output's and input's
  1438. * base images (no need to copy them). */
  1439. if (out_baseimg) {
  1440. if (!(ret & BDRV_BLOCK_DATA)) {
  1441. sector_num += n1;
  1442. continue;
  1443. }
  1444. /* The next 'n1' sectors are allocated in the input image.
  1445. * Copy only those as they may be followed by unallocated
  1446. * sectors. */
  1447. nb_sectors = n1;
  1448. }
  1449. /* avoid redundant callouts to get_block_status */
  1450. sector_num_next_status = sector_num + n1;
  1451. }
  1452. n = MIN(nb_sectors, bufsectors);
  1453. /* round down request length to an aligned sector, but
  1454. * do not bother doing this on short requests. They happen
  1455. * when we found an all-zero area, and the next sector to
  1456. * write will not be sector_num + n. */
  1457. if (cluster_sectors > 0 && n >= cluster_sectors) {
  1458. int64_t next_aligned_sector = (sector_num + n);
  1459. next_aligned_sector -= next_aligned_sector % cluster_sectors;
  1460. if (sector_num + n > next_aligned_sector) {
  1461. n = next_aligned_sector - sector_num;
  1462. }
  1463. }
  1464. n = MIN(n, bs_sectors - (sector_num - bs_offset));
  1465. sectors_read += n;
  1466. if (count_allocated_sectors) {
  1467. sector_num += n;
  1468. continue;
  1469. }
  1470. n1 = n;
  1471. ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
  1472. if (ret < 0) {
  1473. error_report("error while reading sector %" PRId64 ": %s",
  1474. sector_num - bs_offset, strerror(-ret));
  1475. goto out;
  1476. }
  1477. /* NOTE: at the same time we convert, we do not write zero
  1478. sectors to have a chance to compress the image. Ideally, we
  1479. should add a specific call to have the info to go faster */
  1480. buf1 = buf;
  1481. while (n > 0) {
  1482. if (!has_zero_init ||
  1483. is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
  1484. ret = bdrv_write(out_bs, sector_num, buf1, n1);
  1485. if (ret < 0) {
  1486. error_report("error while writing sector %" PRId64
  1487. ": %s", sector_num, strerror(-ret));
  1488. goto out;
  1489. }
  1490. }
  1491. sector_num += n1;
  1492. n -= n1;
  1493. buf1 += n1 * 512;
  1494. }
  1495. qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
  1496. }
  1497. }
  1498. out:
  1499. if (!ret) {
  1500. qemu_progress_print(100, 0);
  1501. }
  1502. qemu_progress_end();
  1503. free_option_parameters(create_options);
  1504. free_option_parameters(param);
  1505. qemu_vfree(buf);
  1506. if (sn_opts) {
  1507. qemu_opts_del(sn_opts);
  1508. }
  1509. if (out_bs) {
  1510. bdrv_unref(out_bs);
  1511. }
  1512. if (bs) {
  1513. for (bs_i = 0; bs_i < bs_n; bs_i++) {
  1514. if (bs[bs_i]) {
  1515. bdrv_unref(bs[bs_i]);
  1516. }
  1517. }
  1518. g_free(bs);
  1519. }
  1520. fail_getopt:
  1521. g_free(options);
  1522. if (ret) {
  1523. return 1;
  1524. }
  1525. return 0;
  1526. }
  1527. static void dump_snapshots(BlockDriverState *bs)
  1528. {
  1529. QEMUSnapshotInfo *sn_tab, *sn;
  1530. int nb_sns, i;
  1531. nb_sns = bdrv_snapshot_list(bs, &sn_tab);
  1532. if (nb_sns <= 0)
  1533. return;
  1534. printf("Snapshot list:\n");
  1535. bdrv_snapshot_dump(fprintf, stdout, NULL);
  1536. printf("\n");
  1537. for(i = 0; i < nb_sns; i++) {
  1538. sn = &sn_tab[i];
  1539. bdrv_snapshot_dump(fprintf, stdout, sn);
  1540. printf("\n");
  1541. }
  1542. g_free(sn_tab);
  1543. }
  1544. static void dump_json_image_info_list(ImageInfoList *list)
  1545. {
  1546. Error *errp = NULL;
  1547. QString *str;
  1548. QmpOutputVisitor *ov = qmp_output_visitor_new();
  1549. QObject *obj;
  1550. visit_type_ImageInfoList(qmp_output_get_visitor(ov),
  1551. &list, NULL, &errp);
  1552. obj = qmp_output_get_qobject(ov);
  1553. str = qobject_to_json_pretty(obj);
  1554. assert(str != NULL);
  1555. printf("%s\n", qstring_get_str(str));
  1556. qobject_decref(obj);
  1557. qmp_output_visitor_cleanup(ov);
  1558. QDECREF(str);
  1559. }
  1560. static void dump_json_image_info(ImageInfo *info)
  1561. {
  1562. Error *errp = NULL;
  1563. QString *str;
  1564. QmpOutputVisitor *ov = qmp_output_visitor_new();
  1565. QObject *obj;
  1566. visit_type_ImageInfo(qmp_output_get_visitor(ov),
  1567. &info, NULL, &errp);
  1568. obj = qmp_output_get_qobject(ov);
  1569. str = qobject_to_json_pretty(obj);
  1570. assert(str != NULL);
  1571. printf("%s\n", qstring_get_str(str));
  1572. qobject_decref(obj);
  1573. qmp_output_visitor_cleanup(ov);
  1574. QDECREF(str);
  1575. }
  1576. static void dump_human_image_info_list(ImageInfoList *list)
  1577. {
  1578. ImageInfoList *elem;
  1579. bool delim = false;
  1580. for (elem = list; elem; elem = elem->next) {
  1581. if (delim) {
  1582. printf("\n");
  1583. }
  1584. delim = true;
  1585. bdrv_image_info_dump(fprintf, stdout, elem->value);
  1586. }
  1587. }
  1588. static gboolean str_equal_func(gconstpointer a, gconstpointer b)
  1589. {
  1590. return strcmp(a, b) == 0;
  1591. }
  1592. /**
  1593. * Open an image file chain and return an ImageInfoList
  1594. *
  1595. * @filename: topmost image filename
  1596. * @fmt: topmost image format (may be NULL to autodetect)
  1597. * @chain: true - enumerate entire backing file chain
  1598. * false - only topmost image file
  1599. *
  1600. * Returns a list of ImageInfo objects or NULL if there was an error opening an
  1601. * image file. If there was an error a message will have been printed to
  1602. * stderr.
  1603. */
  1604. static ImageInfoList *collect_image_info_list(const char *filename,
  1605. const char *fmt,
  1606. bool chain)
  1607. {
  1608. ImageInfoList *head = NULL;
  1609. ImageInfoList **last = &head;
  1610. GHashTable *filenames;
  1611. Error *err = NULL;
  1612. filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
  1613. while (filename) {
  1614. BlockDriverState *bs;
  1615. ImageInfo *info;
  1616. ImageInfoList *elem;
  1617. if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
  1618. error_report("Backing file '%s' creates an infinite loop.",
  1619. filename);
  1620. goto err;
  1621. }
  1622. g_hash_table_insert(filenames, (gpointer)filename, NULL);
  1623. bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
  1624. false, false);
  1625. if (!bs) {
  1626. goto err;
  1627. }
  1628. bdrv_query_image_info(bs, &info, &err);
  1629. if (err) {
  1630. error_report("%s", error_get_pretty(err));
  1631. error_free(err);
  1632. bdrv_unref(bs);
  1633. goto err;
  1634. }
  1635. elem = g_new0(ImageInfoList, 1);
  1636. elem->value = info;
  1637. *last = elem;
  1638. last = &elem->next;
  1639. bdrv_unref(bs);
  1640. filename = fmt = NULL;
  1641. if (chain) {
  1642. if (info->has_full_backing_filename) {
  1643. filename = info->full_backing_filename;
  1644. } else if (info->has_backing_filename) {
  1645. filename = info->backing_filename;
  1646. }
  1647. if (info->has_backing_filename_format) {
  1648. fmt = info->backing_filename_format;
  1649. }
  1650. }
  1651. }
  1652. g_hash_table_destroy(filenames);
  1653. return head;
  1654. err:
  1655. qapi_free_ImageInfoList(head);
  1656. g_hash_table_destroy(filenames);
  1657. return NULL;
  1658. }
  1659. static int img_info(int argc, char **argv)
  1660. {
  1661. int c;
  1662. OutputFormat output_format = OFORMAT_HUMAN;
  1663. bool chain = false;
  1664. const char *filename, *fmt, *output;
  1665. ImageInfoList *list;
  1666. fmt = NULL;
  1667. output = NULL;
  1668. for(;;) {
  1669. int option_index = 0;
  1670. static const struct option long_options[] = {
  1671. {"help", no_argument, 0, 'h'},
  1672. {"format", required_argument, 0, 'f'},
  1673. {"output", required_argument, 0, OPTION_OUTPUT},
  1674. {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
  1675. {0, 0, 0, 0}
  1676. };
  1677. c = getopt_long(argc, argv, "f:h",
  1678. long_options, &option_index);
  1679. if (c == -1) {
  1680. break;
  1681. }
  1682. switch(c) {
  1683. case '?':
  1684. case 'h':
  1685. help();
  1686. break;
  1687. case 'f':
  1688. fmt = optarg;
  1689. break;
  1690. case OPTION_OUTPUT:
  1691. output = optarg;
  1692. break;
  1693. case OPTION_BACKING_CHAIN:
  1694. chain = true;
  1695. break;
  1696. }
  1697. }
  1698. if (optind != argc - 1) {
  1699. help();
  1700. }
  1701. filename = argv[optind++];
  1702. if (output && !strcmp(output, "json")) {
  1703. output_format = OFORMAT_JSON;
  1704. } else if (output && !strcmp(output, "human")) {
  1705. output_format = OFORMAT_HUMAN;
  1706. } else if (output) {
  1707. error_report("--output must be used with human or json as argument.");
  1708. return 1;
  1709. }
  1710. list = collect_image_info_list(filename, fmt, chain);
  1711. if (!list) {
  1712. return 1;
  1713. }
  1714. switch (output_format) {
  1715. case OFORMAT_HUMAN:
  1716. dump_human_image_info_list(list);
  1717. break;
  1718. case OFORMAT_JSON:
  1719. if (chain) {
  1720. dump_json_image_info_list(list);
  1721. } else {
  1722. dump_json_image_info(list->value);
  1723. }
  1724. break;
  1725. }
  1726. qapi_free_ImageInfoList(list);
  1727. return 0;
  1728. }
  1729. typedef struct MapEntry {
  1730. int flags;
  1731. int depth;
  1732. int64_t start;
  1733. int64_t length;
  1734. int64_t offset;
  1735. BlockDriverState *bs;
  1736. } MapEntry;
  1737. static void dump_map_entry(OutputFormat output_format, MapEntry *e,
  1738. MapEntry *next)
  1739. {
  1740. switch (output_format) {
  1741. case OFORMAT_HUMAN:
  1742. if ((e->flags & BDRV_BLOCK_DATA) &&
  1743. !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
  1744. error_report("File contains external, encrypted or compressed clusters.");
  1745. exit(1);
  1746. }
  1747. if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
  1748. printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
  1749. e->start, e->length, e->offset, e->bs->filename);
  1750. }
  1751. /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
  1752. * Modify the flags here to allow more coalescing.
  1753. */
  1754. if (next &&
  1755. (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
  1756. next->flags &= ~BDRV_BLOCK_DATA;
  1757. next->flags |= BDRV_BLOCK_ZERO;
  1758. }
  1759. break;
  1760. case OFORMAT_JSON:
  1761. printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
  1762. " \"zero\": %s, \"data\": %s",
  1763. (e->start == 0 ? "[" : ",\n"),
  1764. e->start, e->length, e->depth,
  1765. (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
  1766. (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
  1767. if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
  1768. printf(", \"offset\": %"PRId64"", e->offset);
  1769. }
  1770. putchar('}');
  1771. if (!next) {
  1772. printf("]\n");
  1773. }
  1774. break;
  1775. }
  1776. }
  1777. static int get_block_status(BlockDriverState *bs, int64_t sector_num,
  1778. int nb_sectors, MapEntry *e)
  1779. {
  1780. int64_t ret;
  1781. int depth;
  1782. /* As an optimization, we could cache the current range of unallocated
  1783. * clusters in each file of the chain, and avoid querying the same
  1784. * range repeatedly.
  1785. */
  1786. depth = 0;
  1787. for (;;) {
  1788. ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
  1789. if (ret < 0) {
  1790. return ret;
  1791. }
  1792. assert(nb_sectors);
  1793. if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
  1794. break;
  1795. }
  1796. bs = bs->backing_hd;
  1797. if (bs == NULL) {
  1798. ret = 0;
  1799. break;
  1800. }
  1801. depth++;
  1802. }
  1803. e->start = sector_num * BDRV_SECTOR_SIZE;
  1804. e->length = nb_sectors * BDRV_SECTOR_SIZE;
  1805. e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
  1806. e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
  1807. e->depth = depth;
  1808. e->bs = bs;
  1809. return 0;
  1810. }
  1811. static int img_map(int argc, char **argv)
  1812. {
  1813. int c;
  1814. OutputFormat output_format = OFORMAT_HUMAN;
  1815. BlockDriverState *bs;
  1816. const char *filename, *fmt, *output;
  1817. int64_t length;
  1818. MapEntry curr = { .length = 0 }, next;
  1819. int ret = 0;
  1820. fmt = NULL;
  1821. output = NULL;
  1822. for (;;) {
  1823. int option_index = 0;
  1824. static const struct option long_options[] = {
  1825. {"help", no_argument, 0, 'h'},
  1826. {"format", required_argument, 0, 'f'},
  1827. {"output", required_argument, 0, OPTION_OUTPUT},
  1828. {0, 0, 0, 0}
  1829. };
  1830. c = getopt_long(argc, argv, "f:h",
  1831. long_options, &option_index);
  1832. if (c == -1) {
  1833. break;
  1834. }
  1835. switch (c) {
  1836. case '?':
  1837. case 'h':
  1838. help();
  1839. break;
  1840. case 'f':
  1841. fmt = optarg;
  1842. break;
  1843. case OPTION_OUTPUT:
  1844. output = optarg;
  1845. break;
  1846. }
  1847. }
  1848. if (optind >= argc) {
  1849. help();
  1850. }
  1851. filename = argv[optind++];
  1852. if (output && !strcmp(output, "json")) {
  1853. output_format = OFORMAT_JSON;
  1854. } else if (output && !strcmp(output, "human")) {
  1855. output_format = OFORMAT_HUMAN;
  1856. } else if (output) {
  1857. error_report("--output must be used with human or json as argument.");
  1858. return 1;
  1859. }
  1860. bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS, true, false);
  1861. if (!bs) {
  1862. return 1;
  1863. }
  1864. if (output_format == OFORMAT_HUMAN) {
  1865. printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
  1866. }
  1867. length = bdrv_getlength(bs);
  1868. while (curr.start + curr.length < length) {
  1869. int64_t nsectors_left;
  1870. int64_t sector_num;
  1871. int n;
  1872. sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
  1873. /* Probe up to 1 GiB at a time. */
  1874. nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
  1875. n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
  1876. ret = get_block_status(bs, sector_num, n, &next);
  1877. if (ret < 0) {
  1878. error_report("Could not read file metadata: %s", strerror(-ret));
  1879. goto out;
  1880. }
  1881. if (curr.length != 0 && curr.flags == next.flags &&
  1882. curr.depth == next.depth &&
  1883. ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
  1884. curr.offset + curr.length == next.offset)) {
  1885. curr.length += next.length;
  1886. continue;
  1887. }
  1888. if (curr.length > 0) {
  1889. dump_map_entry(output_format, &curr, &next);
  1890. }
  1891. curr = next;
  1892. }
  1893. dump_map_entry(output_format, &curr, NULL);
  1894. out:
  1895. bdrv_unref(bs);
  1896. return ret < 0;
  1897. }
  1898. #define SNAPSHOT_LIST 1
  1899. #define SNAPSHOT_CREATE 2
  1900. #define SNAPSHOT_APPLY 3
  1901. #define SNAPSHOT_DELETE 4
  1902. static int img_snapshot(int argc, char **argv)
  1903. {
  1904. BlockDriverState *bs;
  1905. QEMUSnapshotInfo sn;
  1906. char *filename, *snapshot_name = NULL;
  1907. int c, ret = 0, bdrv_oflags;
  1908. int action = 0;
  1909. qemu_timeval tv;
  1910. bool quiet = false;
  1911. Error *err = NULL;
  1912. bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
  1913. /* Parse commandline parameters */
  1914. for(;;) {
  1915. c = getopt(argc, argv, "la:c:d:hq");
  1916. if (c == -1) {
  1917. break;
  1918. }
  1919. switch(c) {
  1920. case '?':
  1921. case 'h':
  1922. help();
  1923. return 0;
  1924. case 'l':
  1925. if (action) {
  1926. help();
  1927. return 0;
  1928. }
  1929. action = SNAPSHOT_LIST;
  1930. bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
  1931. break;
  1932. case 'a':
  1933. if (action) {
  1934. help();
  1935. return 0;
  1936. }
  1937. action = SNAPSHOT_APPLY;
  1938. snapshot_name = optarg;
  1939. break;
  1940. case 'c':
  1941. if (action) {
  1942. help();
  1943. return 0;
  1944. }
  1945. action = SNAPSHOT_CREATE;
  1946. snapshot_name = optarg;
  1947. break;
  1948. case 'd':
  1949. if (action) {
  1950. help();
  1951. return 0;
  1952. }
  1953. action = SNAPSHOT_DELETE;
  1954. snapshot_name = optarg;
  1955. break;
  1956. case 'q':
  1957. quiet = true;
  1958. break;
  1959. }
  1960. }
  1961. if (optind != argc - 1) {
  1962. help();
  1963. }
  1964. filename = argv[optind++];
  1965. /* Open the image */
  1966. bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
  1967. if (!bs) {
  1968. return 1;
  1969. }
  1970. /* Perform the requested action */
  1971. switch(action) {
  1972. case SNAPSHOT_LIST:
  1973. dump_snapshots(bs);
  1974. break;
  1975. case SNAPSHOT_CREATE:
  1976. memset(&sn, 0, sizeof(sn));
  1977. pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
  1978. qemu_gettimeofday(&tv);
  1979. sn.date_sec = tv.tv_sec;
  1980. sn.date_nsec = tv.tv_usec * 1000;
  1981. ret = bdrv_snapshot_create(bs, &sn);
  1982. if (ret) {
  1983. error_report("Could not create snapshot '%s': %d (%s)",
  1984. snapshot_name, ret, strerror(-ret));
  1985. }
  1986. break;
  1987. case SNAPSHOT_APPLY:
  1988. ret = bdrv_snapshot_goto(bs, snapshot_name);
  1989. if (ret) {
  1990. error_report("Could not apply snapshot '%s': %d (%s)",
  1991. snapshot_name, ret, strerror(-ret));
  1992. }
  1993. break;
  1994. case SNAPSHOT_DELETE:
  1995. bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
  1996. if (err) {
  1997. error_report("Could not delete snapshot '%s': (%s)",
  1998. snapshot_name, error_get_pretty(err));
  1999. error_free(err);
  2000. ret = 1;
  2001. }
  2002. break;
  2003. }
  2004. /* Cleanup */
  2005. bdrv_unref(bs);
  2006. if (ret) {
  2007. return 1;
  2008. }
  2009. return 0;
  2010. }
  2011. static int img_rebase(int argc, char **argv)
  2012. {
  2013. BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
  2014. BlockDriver *old_backing_drv, *new_backing_drv;
  2015. char *filename;
  2016. const char *fmt, *cache, *out_basefmt, *out_baseimg;
  2017. int c, flags, ret;
  2018. int unsafe = 0;
  2019. int progress = 0;
  2020. bool quiet = false;
  2021. Error *local_err = NULL;
  2022. /* Parse commandline parameters */
  2023. fmt = NULL;
  2024. cache = BDRV_DEFAULT_CACHE;
  2025. out_baseimg = NULL;
  2026. out_basefmt = NULL;
  2027. for(;;) {
  2028. c = getopt(argc, argv, "uhf:F:b:pt:q");
  2029. if (c == -1) {
  2030. break;
  2031. }
  2032. switch(c) {
  2033. case '?':
  2034. case 'h':
  2035. help();
  2036. return 0;
  2037. case 'f':
  2038. fmt = optarg;
  2039. break;
  2040. case 'F':
  2041. out_basefmt = optarg;
  2042. break;
  2043. case 'b':
  2044. out_baseimg = optarg;
  2045. break;
  2046. case 'u':
  2047. unsafe = 1;
  2048. break;
  2049. case 'p':
  2050. progress = 1;
  2051. break;
  2052. case 't':
  2053. cache = optarg;
  2054. break;
  2055. case 'q':
  2056. quiet = true;
  2057. break;
  2058. }
  2059. }
  2060. if (quiet) {
  2061. progress = 0;
  2062. }
  2063. if ((optind != argc - 1) || (!unsafe && !out_baseimg)) {
  2064. help();
  2065. }
  2066. filename = argv[optind++];
  2067. qemu_progress_init(progress, 2.0);
  2068. qemu_progress_print(0, 100);
  2069. flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
  2070. ret = bdrv_parse_cache_flags(cache, &flags);
  2071. if (ret < 0) {
  2072. error_report("Invalid cache option: %s", cache);
  2073. return -1;
  2074. }
  2075. /*
  2076. * Open the images.
  2077. *
  2078. * Ignore the old backing file for unsafe rebase in case we want to correct
  2079. * the reference to a renamed or moved backing file.
  2080. */
  2081. bs = bdrv_new_open(filename, fmt, flags, true, quiet);
  2082. if (!bs) {
  2083. return 1;
  2084. }
  2085. /* Find the right drivers for the backing files */
  2086. old_backing_drv = NULL;
  2087. new_backing_drv = NULL;
  2088. if (!unsafe && bs->backing_format[0] != '\0') {
  2089. old_backing_drv = bdrv_find_format(bs->backing_format);
  2090. if (old_backing_drv == NULL) {
  2091. error_report("Invalid format name: '%s'", bs->backing_format);
  2092. ret = -1;
  2093. goto out;
  2094. }
  2095. }
  2096. if (out_basefmt != NULL) {
  2097. new_backing_drv = bdrv_find_format(out_basefmt);
  2098. if (new_backing_drv == NULL) {
  2099. error_report("Invalid format name: '%s'", out_basefmt);
  2100. ret = -1;
  2101. goto out;
  2102. }
  2103. }
  2104. /* For safe rebasing we need to compare old and new backing file */
  2105. if (unsafe) {
  2106. /* Make the compiler happy */
  2107. bs_old_backing = NULL;
  2108. bs_new_backing = NULL;
  2109. } else {
  2110. char backing_name[1024];
  2111. bs_old_backing = bdrv_new("old_backing");
  2112. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  2113. ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, BDRV_O_FLAGS,
  2114. old_backing_drv, &local_err);
  2115. if (ret) {
  2116. error_report("Could not open old backing file '%s': %s",
  2117. backing_name, error_get_pretty(local_err));
  2118. error_free(local_err);
  2119. goto out;
  2120. }
  2121. if (out_baseimg[0]) {
  2122. bs_new_backing = bdrv_new("new_backing");
  2123. ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL,
  2124. BDRV_O_FLAGS, new_backing_drv, &local_err);
  2125. if (ret) {
  2126. error_report("Could not open new backing file '%s': %s",
  2127. out_baseimg, error_get_pretty(local_err));
  2128. error_free(local_err);
  2129. goto out;
  2130. }
  2131. }
  2132. }
  2133. /*
  2134. * Check each unallocated cluster in the COW file. If it is unallocated,
  2135. * accesses go to the backing file. We must therefore compare this cluster
  2136. * in the old and new backing file, and if they differ we need to copy it
  2137. * from the old backing file into the COW file.
  2138. *
  2139. * If qemu-img crashes during this step, no harm is done. The content of
  2140. * the image is the same as the original one at any time.
  2141. */
  2142. if (!unsafe) {
  2143. uint64_t num_sectors;
  2144. uint64_t old_backing_num_sectors;
  2145. uint64_t new_backing_num_sectors = 0;
  2146. uint64_t sector;
  2147. int n;
  2148. uint8_t * buf_old;
  2149. uint8_t * buf_new;
  2150. float local_progress = 0;
  2151. buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
  2152. buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
  2153. bdrv_get_geometry(bs, &num_sectors);
  2154. bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
  2155. if (bs_new_backing) {
  2156. bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
  2157. }
  2158. if (num_sectors != 0) {
  2159. local_progress = (float)100 /
  2160. (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
  2161. }
  2162. for (sector = 0; sector < num_sectors; sector += n) {
  2163. /* How many sectors can we handle with the next read? */
  2164. if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
  2165. n = (IO_BUF_SIZE / 512);
  2166. } else {
  2167. n = num_sectors - sector;
  2168. }
  2169. /* If the cluster is allocated, we don't need to take action */
  2170. ret = bdrv_is_allocated(bs, sector, n, &n);
  2171. if (ret < 0) {
  2172. error_report("error while reading image metadata: %s",
  2173. strerror(-ret));
  2174. goto out;
  2175. }
  2176. if (ret) {
  2177. continue;
  2178. }
  2179. /*
  2180. * Read old and new backing file and take into consideration that
  2181. * backing files may be smaller than the COW image.
  2182. */
  2183. if (sector >= old_backing_num_sectors) {
  2184. memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
  2185. } else {
  2186. if (sector + n > old_backing_num_sectors) {
  2187. n = old_backing_num_sectors - sector;
  2188. }
  2189. ret = bdrv_read(bs_old_backing, sector, buf_old, n);
  2190. if (ret < 0) {
  2191. error_report("error while reading from old backing file");
  2192. goto out;
  2193. }
  2194. }
  2195. if (sector >= new_backing_num_sectors || !bs_new_backing) {
  2196. memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
  2197. } else {
  2198. if (sector + n > new_backing_num_sectors) {
  2199. n = new_backing_num_sectors - sector;
  2200. }
  2201. ret = bdrv_read(bs_new_backing, sector, buf_new, n);
  2202. if (ret < 0) {
  2203. error_report("error while reading from new backing file");
  2204. goto out;
  2205. }
  2206. }
  2207. /* If they differ, we need to write to the COW file */
  2208. uint64_t written = 0;
  2209. while (written < n) {
  2210. int pnum;
  2211. if (compare_sectors(buf_old + written * 512,
  2212. buf_new + written * 512, n - written, &pnum))
  2213. {
  2214. ret = bdrv_write(bs, sector + written,
  2215. buf_old + written * 512, pnum);
  2216. if (ret < 0) {
  2217. error_report("Error while writing to COW image: %s",
  2218. strerror(-ret));
  2219. goto out;
  2220. }
  2221. }
  2222. written += pnum;
  2223. }
  2224. qemu_progress_print(local_progress, 100);
  2225. }
  2226. qemu_vfree(buf_old);
  2227. qemu_vfree(buf_new);
  2228. }
  2229. /*
  2230. * Change the backing file. All clusters that are different from the old
  2231. * backing file are overwritten in the COW file now, so the visible content
  2232. * doesn't change when we switch the backing file.
  2233. */
  2234. if (out_baseimg && *out_baseimg) {
  2235. ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
  2236. } else {
  2237. ret = bdrv_change_backing_file(bs, NULL, NULL);
  2238. }
  2239. if (ret == -ENOSPC) {
  2240. error_report("Could not change the backing file to '%s': No "
  2241. "space left in the file header", out_baseimg);
  2242. } else if (ret < 0) {
  2243. error_report("Could not change the backing file to '%s': %s",
  2244. out_baseimg, strerror(-ret));
  2245. }
  2246. qemu_progress_print(100, 0);
  2247. /*
  2248. * TODO At this point it is possible to check if any clusters that are
  2249. * allocated in the COW file are the same in the backing file. If so, they
  2250. * could be dropped from the COW file. Don't do this before switching the
  2251. * backing file, in case of a crash this would lead to corruption.
  2252. */
  2253. out:
  2254. qemu_progress_end();
  2255. /* Cleanup */
  2256. if (!unsafe) {
  2257. if (bs_old_backing != NULL) {
  2258. bdrv_unref(bs_old_backing);
  2259. }
  2260. if (bs_new_backing != NULL) {
  2261. bdrv_unref(bs_new_backing);
  2262. }
  2263. }
  2264. bdrv_unref(bs);
  2265. if (ret) {
  2266. return 1;
  2267. }
  2268. return 0;
  2269. }
  2270. static int img_resize(int argc, char **argv)
  2271. {
  2272. int c, ret, relative;
  2273. const char *filename, *fmt, *size;
  2274. int64_t n, total_size;
  2275. bool quiet = false;
  2276. BlockDriverState *bs = NULL;
  2277. QemuOpts *param;
  2278. static QemuOptsList resize_options = {
  2279. .name = "resize_options",
  2280. .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
  2281. .desc = {
  2282. {
  2283. .name = BLOCK_OPT_SIZE,
  2284. .type = QEMU_OPT_SIZE,
  2285. .help = "Virtual disk size"
  2286. }, {
  2287. /* end of list */
  2288. }
  2289. },
  2290. };
  2291. /* Remove size from argv manually so that negative numbers are not treated
  2292. * as options by getopt. */
  2293. if (argc < 3) {
  2294. help();
  2295. return 1;
  2296. }
  2297. size = argv[--argc];
  2298. /* Parse getopt arguments */
  2299. fmt = NULL;
  2300. for(;;) {
  2301. c = getopt(argc, argv, "f:hq");
  2302. if (c == -1) {
  2303. break;
  2304. }
  2305. switch(c) {
  2306. case '?':
  2307. case 'h':
  2308. help();
  2309. break;
  2310. case 'f':
  2311. fmt = optarg;
  2312. break;
  2313. case 'q':
  2314. quiet = true;
  2315. break;
  2316. }
  2317. }
  2318. if (optind != argc - 1) {
  2319. help();
  2320. }
  2321. filename = argv[optind++];
  2322. /* Choose grow, shrink, or absolute resize mode */
  2323. switch (size[0]) {
  2324. case '+':
  2325. relative = 1;
  2326. size++;
  2327. break;
  2328. case '-':
  2329. relative = -1;
  2330. size++;
  2331. break;
  2332. default:
  2333. relative = 0;
  2334. break;
  2335. }
  2336. /* Parse size */
  2337. param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
  2338. if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
  2339. /* Error message already printed when size parsing fails */
  2340. ret = -1;
  2341. qemu_opts_del(param);
  2342. goto out;
  2343. }
  2344. n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
  2345. qemu_opts_del(param);
  2346. bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
  2347. if (!bs) {
  2348. ret = -1;
  2349. goto out;
  2350. }
  2351. if (relative) {
  2352. total_size = bdrv_getlength(bs) + n * relative;
  2353. } else {
  2354. total_size = n;
  2355. }
  2356. if (total_size <= 0) {
  2357. error_report("New image size must be positive");
  2358. ret = -1;
  2359. goto out;
  2360. }
  2361. ret = bdrv_truncate(bs, total_size);
  2362. switch (ret) {
  2363. case 0:
  2364. qprintf(quiet, "Image resized.\n");
  2365. break;
  2366. case -ENOTSUP:
  2367. error_report("This image does not support resize");
  2368. break;
  2369. case -EACCES:
  2370. error_report("Image is read-only");
  2371. break;
  2372. default:
  2373. error_report("Error resizing image (%d)", -ret);
  2374. break;
  2375. }
  2376. out:
  2377. if (bs) {
  2378. bdrv_unref(bs);
  2379. }
  2380. if (ret) {
  2381. return 1;
  2382. }
  2383. return 0;
  2384. }
  2385. static int img_amend(int argc, char **argv)
  2386. {
  2387. int c, ret = 0;
  2388. char *options = NULL;
  2389. QEMUOptionParameter *create_options = NULL, *options_param = NULL;
  2390. const char *fmt = NULL, *filename;
  2391. bool quiet = false;
  2392. BlockDriverState *bs = NULL;
  2393. for (;;) {
  2394. c = getopt(argc, argv, "hqf:o:");
  2395. if (c == -1) {
  2396. break;
  2397. }
  2398. switch (c) {
  2399. case 'h':
  2400. case '?':
  2401. help();
  2402. break;
  2403. case 'o':
  2404. if (!is_valid_option_list(optarg)) {
  2405. error_report("Invalid option list: %s", optarg);
  2406. ret = -1;
  2407. goto out;
  2408. }
  2409. if (!options) {
  2410. options = g_strdup(optarg);
  2411. } else {
  2412. char *old_options = options;
  2413. options = g_strdup_printf("%s,%s", options, optarg);
  2414. g_free(old_options);
  2415. }
  2416. break;
  2417. case 'f':
  2418. fmt = optarg;
  2419. break;
  2420. case 'q':
  2421. quiet = true;
  2422. break;
  2423. }
  2424. }
  2425. if (!options) {
  2426. help();
  2427. }
  2428. filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
  2429. if (fmt && has_help_option(options)) {
  2430. /* If a format is explicitly specified (and possibly no filename is
  2431. * given), print option help here */
  2432. ret = print_block_option_help(filename, fmt);
  2433. goto out;
  2434. }
  2435. if (optind != argc - 1) {
  2436. help();
  2437. }
  2438. bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
  2439. if (!bs) {
  2440. error_report("Could not open image '%s'", filename);
  2441. ret = -1;
  2442. goto out;
  2443. }
  2444. fmt = bs->drv->format_name;
  2445. if (has_help_option(options)) {
  2446. /* If the format was auto-detected, print option help here */
  2447. ret = print_block_option_help(filename, fmt);
  2448. goto out;
  2449. }
  2450. create_options = append_option_parameters(create_options,
  2451. bs->drv->create_options);
  2452. options_param = parse_option_parameters(options, create_options,
  2453. options_param);
  2454. if (options_param == NULL) {
  2455. error_report("Invalid options for file format '%s'", fmt);
  2456. ret = -1;
  2457. goto out;
  2458. }
  2459. ret = bdrv_amend_options(bs, options_param);
  2460. if (ret < 0) {
  2461. error_report("Error while amending options: %s", strerror(-ret));
  2462. goto out;
  2463. }
  2464. out:
  2465. if (bs) {
  2466. bdrv_unref(bs);
  2467. }
  2468. free_option_parameters(create_options);
  2469. free_option_parameters(options_param);
  2470. g_free(options);
  2471. if (ret) {
  2472. return 1;
  2473. }
  2474. return 0;
  2475. }
  2476. static const img_cmd_t img_cmds[] = {
  2477. #define DEF(option, callback, arg_string) \
  2478. { option, callback },
  2479. #include "qemu-img-cmds.h"
  2480. #undef DEF
  2481. #undef GEN_DOCS
  2482. { NULL, NULL, },
  2483. };
  2484. int main(int argc, char **argv)
  2485. {
  2486. const img_cmd_t *cmd;
  2487. const char *cmdname;
  2488. #ifdef CONFIG_POSIX
  2489. signal(SIGPIPE, SIG_IGN);
  2490. #endif
  2491. error_set_progname(argv[0]);
  2492. qemu_init_exec_dir(argv[0]);
  2493. qemu_init_main_loop();
  2494. bdrv_init();
  2495. if (argc < 2)
  2496. help();
  2497. cmdname = argv[1];
  2498. argc--; argv++;
  2499. /* find the command */
  2500. for(cmd = img_cmds; cmd->name != NULL; cmd++) {
  2501. if (!strcmp(cmdname, cmd->name)) {
  2502. return cmd->handler(argc, argv);
  2503. }
  2504. }
  2505. /* not found */
  2506. help();
  2507. return 0;
  2508. }