qemu-img.c 83 KB

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