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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
34 run_alloc (const char *cmd, size_t 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 run_sparse (const char *cmd, size_t 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 /* This is the underlying allocation function. It's called from
62 * a few other places in guestfish.
65 alloc_disk (const char *filename, const char *size_str, int add, int sparse)
71 if (parse_size (size_str, &size) == -1)
74 if (!guestfs_is_config (g)) {
75 fprintf (stderr, _("can't allocate or add disks after launching\n"));
79 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_TRUNC, 0666);
85 if (!sparse) { /* Not sparse */
86 #ifdef HAVE_POSIX_FALLOCATE
87 int err = posix_fallocate (fd, 0, size);
96 /* Slow emulation of posix_fallocate on platforms which don't have it. */
98 memset (buffer, 0, sizeof buffer);
100 size_t remaining = size;
101 while (remaining > 0) {
102 size_t n = remaining > sizeof buffer ? sizeof buffer : remaining;
103 ssize_t r = write (fd, buffer, n);
113 } else { /* Sparse */
114 if (lseek (fd, size-1, SEEK_SET) == (off_t) -1) {
121 if (write (fd, &c, 1) != 1) {
129 if (close (fd) == -1) {
136 if (guestfs_add_drive_opts (g, filename,
137 GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw",
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 "parse_size", "xstrtoull", xerr);
161 /* XXX 32 bit file offsets, if anyone uses them? GCC should give
162 * a warning here anyhow.