qemu-io: add support for --object command line arg
[sdk/emulator/qemu.git] / qemu-io.c
1 /*
2  * Command line utility to exercise the QEMU I/O path.
3  *
4  * Copyright (C) 2009 Red Hat, Inc.
5  * Copyright (c) 2003-2005 Silicon Graphics, Inc.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or later.
8  * See the COPYING file in the top-level directory.
9  */
10 #include "qemu/osdep.h"
11 #include <getopt.h>
12 #include <libgen.h>
13
14 #include "qemu-io.h"
15 #include "qemu/error-report.h"
16 #include "qemu/main-loop.h"
17 #include "qemu/option.h"
18 #include "qemu/config-file.h"
19 #include "qemu/readline.h"
20 #include "qapi/qmp/qstring.h"
21 #include "qom/object_interfaces.h"
22 #include "sysemu/block-backend.h"
23 #include "block/block_int.h"
24 #include "trace/control.h"
25
26 #define CMD_NOFILE_OK   0x01
27
28 static char *progname;
29
30 static BlockBackend *qemuio_blk;
31
32 /* qemu-io commands passed using -c */
33 static int ncmdline;
34 static char **cmdline;
35
36 static ReadLineState *readline_state;
37
38 static int close_f(BlockBackend *blk, int argc, char **argv)
39 {
40     blk_unref(qemuio_blk);
41     qemuio_blk = NULL;
42     return 0;
43 }
44
45 static const cmdinfo_t close_cmd = {
46     .name       = "close",
47     .altname    = "c",
48     .cfunc      = close_f,
49     .oneline    = "close the current open file",
50 };
51
52 static int openfile(char *name, int flags, QDict *opts)
53 {
54     Error *local_err = NULL;
55     BlockDriverState *bs;
56
57     if (qemuio_blk) {
58         error_report("file open already, try 'help close'");
59         QDECREF(opts);
60         return 1;
61     }
62
63     qemuio_blk = blk_new_open("hda", name, NULL, opts, flags, &local_err);
64     if (!qemuio_blk) {
65         error_reportf_err(local_err, "can't open%s%s: ",
66                           name ? " device " : "", name ?: "");
67         return 1;
68     }
69
70     bs = blk_bs(qemuio_blk);
71     if (bdrv_is_encrypted(bs)) {
72         char password[256];
73         printf("Disk image '%s' is encrypted.\n", name);
74         if (qemu_read_password(password, sizeof(password)) < 0) {
75             error_report("No password given");
76             goto error;
77         }
78         if (bdrv_set_key(bs, password) < 0) {
79             error_report("invalid password");
80             goto error;
81         }
82     }
83
84
85     return 0;
86
87  error:
88     blk_unref(qemuio_blk);
89     qemuio_blk = NULL;
90     return 1;
91 }
92
93 static void open_help(void)
94 {
95     printf(
96 "\n"
97 " opens a new file in the requested mode\n"
98 "\n"
99 " Example:\n"
100 " 'open -Cn /tmp/data' - creates/opens data file read-write and uncached\n"
101 "\n"
102 " Opens a file for subsequent use by all of the other qemu-io commands.\n"
103 " -r, -- open file read-only\n"
104 " -s, -- use snapshot file\n"
105 " -n, -- disable host cache\n"
106 " -o, -- options to be given to the block driver"
107 "\n");
108 }
109
110 static int open_f(BlockBackend *blk, int argc, char **argv);
111
112 static const cmdinfo_t open_cmd = {
113     .name       = "open",
114     .altname    = "o",
115     .cfunc      = open_f,
116     .argmin     = 1,
117     .argmax     = -1,
118     .flags      = CMD_NOFILE_OK,
119     .args       = "[-Crsn] [-o options] [path]",
120     .oneline    = "open the file specified by path",
121     .help       = open_help,
122 };
123
124 static QemuOptsList empty_opts = {
125     .name = "drive",
126     .merge_lists = true,
127     .head = QTAILQ_HEAD_INITIALIZER(empty_opts.head),
128     .desc = {
129         /* no elements => accept any params */
130         { /* end of list */ }
131     },
132 };
133
134 static int open_f(BlockBackend *blk, int argc, char **argv)
135 {
136     int flags = 0;
137     int readonly = 0;
138     int c;
139     QemuOpts *qopts;
140     QDict *opts;
141
142     while ((c = getopt(argc, argv, "snrgo:")) != -1) {
143         switch (c) {
144         case 's':
145             flags |= BDRV_O_SNAPSHOT;
146             break;
147         case 'n':
148             flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
149             break;
150         case 'r':
151             readonly = 1;
152             break;
153         case 'o':
154             if (!qemu_opts_parse_noisily(&empty_opts, optarg, false)) {
155                 qemu_opts_reset(&empty_opts);
156                 return 0;
157             }
158             break;
159         default:
160             qemu_opts_reset(&empty_opts);
161             return qemuio_command_usage(&open_cmd);
162         }
163     }
164
165     if (!readonly) {
166         flags |= BDRV_O_RDWR;
167     }
168
169     qopts = qemu_opts_find(&empty_opts, NULL);
170     opts = qopts ? qemu_opts_to_qdict(qopts, NULL) : NULL;
171     qemu_opts_reset(&empty_opts);
172
173     if (optind == argc - 1) {
174         return openfile(argv[optind], flags, opts);
175     } else if (optind == argc) {
176         return openfile(NULL, flags, opts);
177     } else {
178         QDECREF(opts);
179         return qemuio_command_usage(&open_cmd);
180     }
181 }
182
183 static int quit_f(BlockBackend *blk, int argc, char **argv)
184 {
185     return 1;
186 }
187
188 static const cmdinfo_t quit_cmd = {
189     .name       = "quit",
190     .altname    = "q",
191     .cfunc      = quit_f,
192     .argmin     = -1,
193     .argmax     = -1,
194     .flags      = CMD_FLAG_GLOBAL,
195     .oneline    = "exit the program",
196 };
197
198 static void usage(const char *name)
199 {
200     printf(
201 "Usage: %s [-h] [-V] [-rsnm] [-f FMT] [-c STRING] ... [file]\n"
202 "QEMU Disk exerciser\n"
203 "\n"
204 "  --object OBJECTDEF   define an object such as 'secret' for\n"
205 "                       passwords and/or encryption keys\n"
206 "  -c, --cmd STRING     execute command with its arguments\n"
207 "                       from the given string\n"
208 "  -f, --format FMT     specifies the block driver to use\n"
209 "  -r, --read-only      export read-only\n"
210 "  -s, --snapshot       use snapshot file\n"
211 "  -n, --nocache        disable host cache\n"
212 "  -m, --misalign       misalign allocations for O_DIRECT\n"
213 "  -k, --native-aio     use kernel AIO implementation (on Linux only)\n"
214 "  -t, --cache=MODE     use the given cache mode for the image\n"
215 "  -T, --trace FILE     enable trace events listed in the given file\n"
216 "  -h, --help           display this help and exit\n"
217 "  -V, --version        output version information and exit\n"
218 "\n"
219 "See '%s -c help' for information on available commands."
220 "\n",
221     name, name);
222 }
223
224 static char *get_prompt(void)
225 {
226     static char prompt[FILENAME_MAX + 2 /*"> "*/ + 1 /*"\0"*/ ];
227
228     if (!prompt[0]) {
229         snprintf(prompt, sizeof(prompt), "%s> ", progname);
230     }
231
232     return prompt;
233 }
234
235 static void GCC_FMT_ATTR(2, 3) readline_printf_func(void *opaque,
236                                                     const char *fmt, ...)
237 {
238     va_list ap;
239     va_start(ap, fmt);
240     vprintf(fmt, ap);
241     va_end(ap);
242 }
243
244 static void readline_flush_func(void *opaque)
245 {
246     fflush(stdout);
247 }
248
249 static void readline_func(void *opaque, const char *str, void *readline_opaque)
250 {
251     char **line = readline_opaque;
252     *line = g_strdup(str);
253 }
254
255 static void completion_match(const char *cmd, void *opaque)
256 {
257     readline_add_completion(readline_state, cmd);
258 }
259
260 static void readline_completion_func(void *opaque, const char *str)
261 {
262     readline_set_completion_index(readline_state, strlen(str));
263     qemuio_complete_command(str, completion_match, NULL);
264 }
265
266 static char *fetchline_readline(void)
267 {
268     char *line = NULL;
269
270     readline_start(readline_state, get_prompt(), 0, readline_func, &line);
271     while (!line) {
272         int ch = getchar();
273         if (ch == EOF) {
274             break;
275         }
276         readline_handle_byte(readline_state, ch);
277     }
278     return line;
279 }
280
281 #define MAXREADLINESZ 1024
282 static char *fetchline_fgets(void)
283 {
284     char *p, *line = g_malloc(MAXREADLINESZ);
285
286     if (!fgets(line, MAXREADLINESZ, stdin)) {
287         g_free(line);
288         return NULL;
289     }
290
291     p = line + strlen(line);
292     if (p != line && p[-1] == '\n') {
293         p[-1] = '\0';
294     }
295
296     return line;
297 }
298
299 static char *fetchline(void)
300 {
301     if (readline_state) {
302         return fetchline_readline();
303     } else {
304         return fetchline_fgets();
305     }
306 }
307
308 static void prep_fetchline(void *opaque)
309 {
310     int *fetchable = opaque;
311
312     qemu_set_fd_handler(STDIN_FILENO, NULL, NULL, NULL);
313     *fetchable= 1;
314 }
315
316 static void command_loop(void)
317 {
318     int i, done = 0, fetchable = 0, prompted = 0;
319     char *input;
320
321     for (i = 0; !done && i < ncmdline; i++) {
322         done = qemuio_command(qemuio_blk, cmdline[i]);
323     }
324     if (cmdline) {
325         g_free(cmdline);
326         return;
327     }
328
329     while (!done) {
330         if (!prompted) {
331             printf("%s", get_prompt());
332             fflush(stdout);
333             qemu_set_fd_handler(STDIN_FILENO, prep_fetchline, NULL, &fetchable);
334             prompted = 1;
335         }
336
337         main_loop_wait(false);
338
339         if (!fetchable) {
340             continue;
341         }
342
343         input = fetchline();
344         if (input == NULL) {
345             break;
346         }
347         done = qemuio_command(qemuio_blk, input);
348         g_free(input);
349
350         prompted = 0;
351         fetchable = 0;
352     }
353     qemu_set_fd_handler(STDIN_FILENO, NULL, NULL, NULL);
354 }
355
356 static void add_user_command(char *optarg)
357 {
358     cmdline = g_renew(char *, cmdline, ++ncmdline);
359     cmdline[ncmdline-1] = optarg;
360 }
361
362 static void reenable_tty_echo(void)
363 {
364     qemu_set_tty_echo(STDIN_FILENO, true);
365 }
366
367 enum {
368     OPTION_OBJECT = 256,
369 };
370
371 static QemuOptsList qemu_object_opts = {
372     .name = "object",
373     .implied_opt_name = "qom-type",
374     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
375     .desc = {
376         { }
377     },
378 };
379
380
381 int main(int argc, char **argv)
382 {
383     int readonly = 0;
384     const char *sopt = "hVc:d:f:rsnmgkt:T:";
385     const struct option lopt[] = {
386         { "help", 0, NULL, 'h' },
387         { "version", 0, NULL, 'V' },
388         { "offset", 1, NULL, 'o' },
389         { "cmd", 1, NULL, 'c' },
390         { "format", 1, NULL, 'f' },
391         { "read-only", 0, NULL, 'r' },
392         { "snapshot", 0, NULL, 's' },
393         { "nocache", 0, NULL, 'n' },
394         { "misalign", 0, NULL, 'm' },
395         { "native-aio", 0, NULL, 'k' },
396         { "discard", 1, NULL, 'd' },
397         { "cache", 1, NULL, 't' },
398         { "trace", 1, NULL, 'T' },
399         { "object", 1, NULL, OPTION_OBJECT },
400         { NULL, 0, NULL, 0 }
401     };
402     int c;
403     int opt_index = 0;
404     int flags = BDRV_O_UNMAP;
405     Error *local_error = NULL;
406     QDict *opts = NULL;
407
408 #ifdef CONFIG_POSIX
409     signal(SIGPIPE, SIG_IGN);
410 #endif
411
412     progname = basename(argv[0]);
413     qemu_init_exec_dir(argv[0]);
414
415     module_call_init(MODULE_INIT_QOM);
416     qemu_add_opts(&qemu_object_opts);
417     bdrv_init();
418
419     while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
420         switch (c) {
421         case 's':
422             flags |= BDRV_O_SNAPSHOT;
423             break;
424         case 'n':
425             flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
426             break;
427         case 'd':
428             if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
429                 error_report("Invalid discard option: %s", optarg);
430                 exit(1);
431             }
432             break;
433         case 'f':
434             if (!opts) {
435                 opts = qdict_new();
436             }
437             qdict_put(opts, "driver", qstring_from_str(optarg));
438             break;
439         case 'c':
440             add_user_command(optarg);
441             break;
442         case 'r':
443             readonly = 1;
444             break;
445         case 'm':
446             qemuio_misalign = true;
447             break;
448         case 'k':
449             flags |= BDRV_O_NATIVE_AIO;
450             break;
451         case 't':
452             if (bdrv_parse_cache_flags(optarg, &flags) < 0) {
453                 error_report("Invalid cache option: %s", optarg);
454                 exit(1);
455             }
456             break;
457         case 'T':
458             if (!trace_init_backends()) {
459                 exit(1); /* error message will have been printed */
460             }
461             break;
462         case 'V':
463             printf("%s version %s\n", progname, QEMU_VERSION);
464             exit(0);
465         case 'h':
466             usage(progname);
467             exit(0);
468         case OPTION_OBJECT: {
469             QemuOpts *qopts = NULL;
470             qopts = qemu_opts_parse_noisily(&qemu_object_opts,
471                                             optarg, true);
472             if (!qopts) {
473                 exit(1);
474             }
475         }   break;
476         default:
477             usage(progname);
478             exit(1);
479         }
480     }
481
482     if ((argc - optind) > 1) {
483         usage(progname);
484         exit(1);
485     }
486
487     if (qemu_init_main_loop(&local_error)) {
488         error_report_err(local_error);
489         exit(1);
490     }
491
492     if (qemu_opts_foreach(&qemu_object_opts,
493                           user_creatable_add_opts_foreach,
494                           NULL, &local_error)) {
495         error_report_err(local_error);
496         exit(1);
497     }
498
499     /* initialize commands */
500     qemuio_add_command(&quit_cmd);
501     qemuio_add_command(&open_cmd);
502     qemuio_add_command(&close_cmd);
503
504     if (isatty(STDIN_FILENO)) {
505         readline_state = readline_init(readline_printf_func,
506                                        readline_flush_func,
507                                        NULL,
508                                        readline_completion_func);
509         qemu_set_tty_echo(STDIN_FILENO, false);
510         atexit(reenable_tty_echo);
511     }
512
513     /* open the device */
514     if (!readonly) {
515         flags |= BDRV_O_RDWR;
516     }
517
518     if ((argc - optind) == 1) {
519         openfile(argv[optind], flags, opts);
520     }
521     command_loop();
522
523     /*
524      * Make sure all outstanding requests complete before the program exits.
525      */
526     bdrv_drain_all();
527
528     blk_unref(qemuio_blk);
529     g_free(readline_state);
530     return 0;
531 }