1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
34 do_alloc (const char *cmd, int argc, char *argv[])
37 fprintf (stderr, _("use 'alloc file size' to create an image\n"));
41 if (alloc_disk (argv[0], argv[1], 1, 0) == -1)
48 do_sparse (const char *cmd, int argc, char *argv[])
51 fprintf (stderr, _("use 'sparse file size' to create a sparse image\n"));
55 if (alloc_disk (argv[0], argv[1], 1, 1) == -1)
61 static int parse_size (const char *str, off_t *size_rtn);
63 /* This is the underlying allocation function. It's called from
64 * a few other places in guestfish.
67 alloc_disk (const char *filename, const char *size_str, int add, int sparse)
73 if (parse_size (size_str, &size) == -1)
76 if (!guestfs_is_config (g)) {
77 fprintf (stderr, _("can't allocate or add disks after launching\n"));
81 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_TRUNC, 0666);
87 if (!sparse) { /* Not sparse */
88 #ifdef HAVE_POSIX_FALLOCATE
89 int err = posix_fallocate (fd, 0, size);
98 /* Slow emulation of posix_fallocate on platforms which don't have it. */
100 memset (buffer, 0, sizeof buffer);
102 size_t remaining = size;
103 while (remaining > 0) {
104 size_t n = remaining > sizeof buffer ? sizeof buffer : remaining;
105 ssize_t r = write (fd, buffer, n);
115 } else { /* Sparse */
116 if (lseek (fd, size-1, SEEK_SET) == (off_t) -1) {
123 if (write (fd, &c, 1) != 1) {
131 if (close (fd) == -1) {
138 if (guestfs_add_drive (g, filename) == -1) {
148 parse_size (const char *str, off_t *size_rtn)
150 unsigned long long size;
153 xerr = xstrtoull (str, NULL, 0, &size, "0kKMGTPEZY");
154 if (xerr != LONGINT_OK) {
156 _("%s: invalid integer parameter (%s returned %d)\n"),
157 "alloc_disk", "xstrtoull", xerr);
161 /* XXX 32 bit file offsets, if anyone uses them? GCC should give
162 * a warning here anyhow.