diff --git a/usr.bin/mkimg/mkimg.1 b/usr.bin/mkimg/mkimg.1 index f6b151d2d5c7..ae48904eb16c 100644 --- a/usr.bin/mkimg/mkimg.1 +++ b/usr.bin/mkimg/mkimg.1 @@ -1,418 +1,418 @@ .\" Copyright (c) 2013, 2014 Juniper Networks, Inc. .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES .\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. .\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, .\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT .\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, .\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY .\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. .\" .Dd June 25, 2025 .Dt MKIMG 1 .Os .Sh NAME .Nm mkimg .Nd "utility to make disk images" .Sh SYNOPSIS .Nm .Op Fl H Ar heads .Op Fl P Ar blksz .Op Fl S Ar secsz .Op Fl T Ar tracksz .Op Fl b Ar bootcode .Op Fl c Ar min_capacity .Op Fl C Ar max_capacity .Op Fl -capacity Ar capacity .Op Fl f Ar format .Op Fl o Ar outfile .Op Fl a Ar active -.Op Fl R +.Op Fl t Ar timestamp .Op Fl v .Op Fl y .Op Fl s Ar scheme Op Fl p Ar partition ... .Nm .Fl -formats | Fl -schemes | Fl -version .Sh DESCRIPTION The .Nm utility creates a disk image from the raw partition contents specified with the .Ar partition argument(s) and using the partitioning scheme specified with the .Ar scheme argument. The disk image is written to .Ar stdout by default or the file specified with the .Ar outfile argument. The image file is a raw disk image by default, but the format of the image file can be specified with the .Ar format argument. Most formats require seekable output, except of raw disk image. .Pp The disk image can be made bootable by specifying the scheme-specific boot block contents with the .Ar bootcode argument and, depending on the scheme, with a boot partition. The contents of such a boot partition is provided like any other partition and the .Nm utility does not treat it any differently from other partitions. .Pp Some partitioning schemes need a disk geometry and for those the .Nm utility accepts the .Ar tracksz and .Ar heads arguments, specifying the number of sectors per track and the number of heads per cylinder (resp.) .Pp Both the logical and physical sector size can be specified and for that the .Nm utility accepts the .Ar secsz and .Ar blksz arguments. The .Ar secsz argument is used to specify the logical sector size. This is the sector size reported by a disk when queried for its capacity. Modern disks use a larger sector size internally, referred to as block size by the .Nm utility and this can be specified by the .Ar blksz argument. The .Nm utility will use the (physical) block size to determine the start of partitions and to round the size of the disk image. .Pp The .Fl c option can be used to specify a minimal capacity for the disk image. Use this option without the .Fl s and .Fl p options to create an empty disk image with the given (virtual) size. An empty partition table can be written to the disk when specifying a partitioning scheme with the .Fl s option, but without specifying any partitions. When the size required for all the partitions is larger than the given capacity, then the disk image will be larger than the capacity given. .Pp The .Fl C option specifies a maximum capacity for the disk image. If the combined sizes of the given partitions exceed the size given with .Fl C , image creation fails. .Pp The .Fl -capacity option is a shorthand to specify the minimum and maximum capacity at the same time. .Pp The -.Fl R -option enables reproducible mode: any timestamps or random identifiers will -be fixed so as to ensure consistent output. +.Fl t +option causes any timestamps embedded in the output file to be set to the +given time, specified in seconds since the epoch. .Pp The .Fl v option increases the level of output that the .Nm utility prints. .Pp The .Fl y option is used for testing purposes only and is not to be used in production. When present, the .Nm utility will generate predictable values for Universally Unique Identifiers (UUIDs) and time stamps so that consecutive runs of the .Nm utility will create images that are identical. .Pp The .Ar active option marks a partition as active, if the partitioning scheme supports it. Currently, only the .Ar mbr scheme supports this concept. By default, .Nm will only mark the first partition as active when boot code is specified. Use the .Ar active option to override the active partition. The number specified corresponds to the number after the 's' in the partition's .Xr geom 8 name. No partitions are marked active when the value is 0. .Pp A set of long options exist to query about the .Nm utility itself. Options in this set should be given by themselves because the .Nm utility exits immediately after providing the requested information. The version of the .Nm utility is printed when the .Fl -version option is given. The list of supported output formats is printed when the .Fl -formats option is given and the list of supported partitioning schemes is printed when the .Fl -schemes option is given. Both the format and scheme lists a space-separated lists for easy handling in scripts. .Pp For a more descriptive list of supported partitioning schemes or supported output format, or for a detailed description of how to specify partitions, run the .Nm utility without any arguments. This will print a usage message with all the necessary details. .Sh DISK FORMATS The .Nm utility supports a number of output file formats. A short description of these is given below. .Ss QCOW and QCOW2 QCOW stands for "QEMU Copy On Write". It's a sparse file format akin to VHD and VMDK and QCOW represents the first version. QCOW2 represents version 2 of the file format. Version 2 is not backward compatible with version 1 and adds support for snapshots among other things. The QCOW file formats are natively supported by QEMU and Xen. To write QCOW, specify .Fl f Ar qcow on the command line. To write version 2 QCOW, specify .Fl f Ar qcow2 on the command line. The preferred file extension is ".qcow" and ".qcow2" for QCOW and QCOW2 (resp.), but ".qcow" is sometimes used for version 2 files as well. .Ss RAW file format This file format is a sector by sector representation of an actual disk. There is no extra information that describes or relates to the format itself. The size of the file is the size of the (virtual) disk. This file format is suitable for being copied onto a disk with utilities like .Nm dd . To write a raw disk file, either omit the .Fl f option, or specify .Fl f Ar raw on the command line. The preferred file extension is one of ".img" or ".raw", but there's no real convention for it. .Ss Dynamic VHD and Fixed VHD Microsoft's "Virtual Hard Disk" file formats. The dynamic format is a sparse format akin to QCOW and VMDK. The fixed format is effectively a raw format with a footer appended to the file and as such it's often indistinguishable from the raw format. The fixed file format has been added to support Microsoft's Azure platform and due to inconsistencies in interpretation of the footer is not compatible with utilities like .Nm qemu when it is specifically instructed to interpreted the file as a VHD file. By default .Nm qemu will treat the file as a raw disk file, which mostly works fine. To have .Nm create a dynamic VHD file, specify .Fl f Ar vhd on the command line. To create a fixed VHD file for use by Azure, specify .Fl f Ar vhdf on the command line. The preferred file extension is ".vhd". .Ss Dynamic VHDX Microsoft's "Virtual Hard Disk v2" file formats, the successor to VHD. VHDX is the required format for the 2nd generation Hyper-V VMs. To have .Nm create a dynamic VHDX file, specify .Fl f Ar vhdx on the command line. The preferred file extension is ".vhdx". .Ss VMDK VMware's "Virtual Machine Disk" file format. It's a sparse file format akin to QCOW and VHD and supported by many virtualization solutions. To create a VMDK file, specify .Fl f Ar vmdk on the command line. The preferred file extension is ".vmdk". .Pp Not all virtualization solutions support all file formats, but often those virtualization environments have utilities to convert from one format to another. Note however that conversion may require that the virtual disk size is changed to match the constraints of the output format and this may invalidate the contents of the disk image. For example, the GUID Partition Table (GPT) scheme has a header in the last sector on the disk. When changing the disk size, the GPT must be changed so that the last header is moved accordingly. This is typically not part of the conversion process. If possible, use an output format specifically for the environment in which the file is intended to be used. .Sh PARTITION SPECIFICATION An option .Fl p may be used multiple times to specify a list of created partition entries. A specification that is a single dash indicates an unused partition entry. Otherwise, a partition specification has the following format: .Bd -literal -offset indent ':' .Ed .Bl -tag -width indent .It Cm type the partition type alias (f.e.: freebsd-swap) that may be optionally followed by a '/' separator and a label for partitioning schemes that feature partition labels (see the .Sx EXAMPLES Section below) .It Cm kind the interpretation of the contents specification: .Bl -tag -width indent .It Cm ':' contents holds the size of an empty partition, a number that may be suffixed with one of K, M, G, T, P or E (either upper or lower case) following the SI power of two convention (see also .Xr expand_number 3 ) .It Cm '=' contents holds the name of a file to read .It Cm '-' contents holds a command to run; the output of which is the contents of the partition. Multi-word strings should be quoted according to the shell rules. .El .It Cm contents the specification of a partition's contents .El .Sh ENVIRONMENT .Bl -tag -width "TMPDIR" -compact .It Ev TMPDIR Directory to put temporary files in; default is .Pa /tmp . .El .Sh EXAMPLES To create a bootable disk image that is partitioned using the GPT scheme and containing a root file system that was previously created using .Xr makefs 8 and also containing a swap partition, run the .Nm utility as follows: .Dl % mkimg -s gpt -b /boot/pmbr -p freebsd-boot:=/boot/gptboot \ -p freebsd-ufs:=root-file-system.ufs -p freebsd-swap::1G \ -o gpt.img .Pp The command line given above results in a raw image file. This is because no output format was given. To create a VMDK image for example, add the .Fl f Ar vmdk argument to the .Nm utility and name the output file accordingly. .Pp A nested partitioning scheme is created by running the .Nm utility twice. The output of the first will be fed as the contents of a partition to the second. This can be done using a temporary file, like so: .Dl % mkimg -s bsd -b /boot/boot -p freebsd-ufs:=root-file-system.ufs \ -p freebsd-swap::1G -o /tmp/bsd.img .Dl % mkimg -s mbr -b /boot/mbr -p freebsd:=/tmp/bsd.img -o mbr-bsd.img .Pp Alternatively, the .Nm utility can be run in a cascaded fashion, whereby the output of the first is fed directly into the second. To do this, run the .Nm utility as follows: .Dl % mkimg -s mbr -b /boot/mbr -p freebsd:-'mkimg -s bsd -b /boot/boot \ -p freebsd-ufs:=root-file-system.ufs -p freebsd-swap::1G' -o mbr-bsd.img .Pp To accommodate the need to have partitions named or numbered in a certain way, the .Nm utility allows for the specification of empty partitions. For example, to create an image that is compatible with partition layouts found in .Pa /etc/disktab , the 'd' partition often needs to be skipped. This is accomplished by inserting an unused partition after the first 2 partition specifications. It is worth noting at this time that the BSD scheme will automatically skip the 'c' partition by virtue of it referring to the entire disk. To create an image that is compatible with the qp120at disk, use the .Nm utility as follows: .Dl % mkimg -s bsd -b /boot/boot -p freebsd-ufs:=root-file-system.ufs \ -p freebsd-swap::20M -p- -p- -p- -p- -p freebsd-ufs:=usr-file-system.ufs \ -o bsd.img .Pp For partitioning schemes that feature partition labels, the .Nm utility supports assigning labels to the partitions specified. In the following example the file system partition is labeled as 'backup': .Dl % mkimg -s gpt -p freebsd-ufs/backup:=file-system.ufs -o gpt.img .Sh SEE ALSO .Xr dd 1 , .Xr expand_number 3 , .Xr gpart 8 , .Xr makefs 8 , .Xr mdconfig 8 , .Xr newfs 8 .Sh HISTORY The .Nm utility first appeared in .Fx 10.1 . .Sh AUTHORS The .Nm utility and manpage were written by .An Marcel Moolenaar Aq Mt marcel@FreeBSD.org . diff --git a/usr.bin/mkimg/mkimg.c b/usr.bin/mkimg/mkimg.c index 58bf90fd5ad4..80c79777575e 100644 --- a/usr.bin/mkimg/mkimg.c +++ b/usr.bin/mkimg/mkimg.c @@ -1,753 +1,761 @@ /*- * Copyright (c) 2013,2014 Juniper Networks, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "image.h" #include "format.h" #include "mkimg.h" #include "scheme.h" #define LONGOPT_FORMATS 0x01000001 #define LONGOPT_SCHEMES 0x01000002 #define LONGOPT_VERSION 0x01000003 #define LONGOPT_CAPACITY 0x01000004 static struct option longopts[] = { { "formats", no_argument, NULL, LONGOPT_FORMATS }, { "schemes", no_argument, NULL, LONGOPT_SCHEMES }, { "version", no_argument, NULL, LONGOPT_VERSION }, { "capacity", required_argument, NULL, LONGOPT_CAPACITY }, { NULL, 0, NULL, 0 } }; static uint64_t min_capacity = 0; static uint64_t max_capacity = 0; -bool reproducible = false; +/* Fixed timestamp for reproducible builds. */ +time_t timestamp = (time_t)-1; struct partlisthead partlist = TAILQ_HEAD_INITIALIZER(partlist); u_int nparts = 0; u_int unit_testing; u_int verbose; u_int ncyls = 0; u_int nheads = 1; u_int nsecs = 1; u_int secsz = 512; u_int blksz = 0; uint32_t active_partition = 0; static void print_formats(int usage) { struct mkimg_format *f; const char *sep; if (usage) { fprintf(stderr, " formats:\n"); f = NULL; while ((f = format_iterate(f)) != NULL) { fprintf(stderr, "\t%s\t- %s\n", f->name, f->description); } } else { sep = ""; f = NULL; while ((f = format_iterate(f)) != NULL) { printf("%s%s", sep, f->name); sep = " "; } putchar('\n'); } } static void print_schemes(int usage) { struct mkimg_scheme *s; const char *sep; if (usage) { fprintf(stderr, " schemes:\n"); s = NULL; while ((s = scheme_iterate(s)) != NULL) { fprintf(stderr, "\t%s\t- %s\n", s->name, s->description); } } else { sep = ""; s = NULL; while ((s = scheme_iterate(s)) != NULL) { printf("%s%s", sep, s->name); sep = " "; } putchar('\n'); } } static void print_version(void) { u_int width; #ifdef __LP64__ width = 64; #else width = 32; #endif printf("mkimg %u (%u-bit)\n", MKIMG_VERSION, width); } static void usage(const char *why) { warnx("error: %s", why); fputc('\n', stderr); fprintf(stderr, "usage: %s \n", getprogname()); fprintf(stderr, " options:\n"); fprintf(stderr, "\t--formats\t- list image formats\n"); fprintf(stderr, "\t--schemes\t- list partition schemes\n"); fprintf(stderr, "\t--version\t- show version information\n"); fputc('\n', stderr); fprintf(stderr, "\t-a \t- mark num'th partition as active\n"); fprintf(stderr, "\t-b \t- file containing boot code\n"); fprintf(stderr, "\t-c \t- minimum capacity (in bytes) of the disk\n"); fprintf(stderr, "\t-C \t- maximum capacity (in bytes) of the disk\n"); fprintf(stderr, "\t-f \n"); fprintf(stderr, "\t-o \t- file to write image into\n"); fprintf(stderr, "\t-p \n"); fprintf(stderr, "\t-s \n"); fprintf(stderr, "\t-v\t\t- increase verbosity\n"); fprintf(stderr, "\t-y\t\t- [developers] enable unit test\n"); fprintf(stderr, "\t-H \t- number of heads to simulate\n"); fprintf(stderr, "\t-P \t- physical sector size\n"); fprintf(stderr, "\t-S \t- logical sector size\n"); fprintf(stderr, "\t-T \t- number of tracks to simulate\n"); fputc('\n', stderr); print_formats(1); fputc('\n', stderr); print_schemes(1); fputc('\n', stderr); fprintf(stderr, " partition specification:\n"); fprintf(stderr, "\t[/]::[:[+]]\t- " "empty partition of given size and\n\t\t\t\t\t" " optional relative or absolute offset\n"); fprintf(stderr, "\t[/]:=[:[+]offset]\t- partition " "content and size are\n\t\t\t\t\t" " determined by the named file and\n" "\t\t\t\t\t optional relative or absolute offset\n"); fprintf(stderr, "\t[/]:-\t\t- partition content and size " "are taken\n\t\t\t\t\t from the output of the command to run\n"); fprintf(stderr, "\t-\t\t\t\t- unused partition entry\n"); fprintf(stderr, "\t where:\n"); fprintf(stderr, "\t\t\t- scheme neutral partition type\n"); fprintf(stderr, "\t\t\t- optional scheme-dependent partition " "label\n"); exit(EX_USAGE); } static int parse_uint32(uint32_t *valp, uint32_t min, uint32_t max, const char *arg) { uint64_t val; if (expand_number(arg, &val) == -1) return (errno); if (val > UINT_MAX || val < (uint64_t)min || val > (uint64_t)max) return (EINVAL); *valp = (uint32_t)val; return (0); } static int parse_uint64(uint64_t *valp, uint64_t min, uint64_t max, const char *arg) { uint64_t val; if (expand_number(arg, &val) == -1) return (errno); if (val < min || val > max) return (EINVAL); *valp = val; return (0); } static int pwr_of_two(u_int nr) { return (((nr & (nr - 1)) == 0) ? 1 : 0); } /* * A partition specification has the following format: * ':' * where: * type the partition type alias * kind the interpretation of the contents specification * ':' contents holds the size of an empty partition * '=' contents holds the name of a file to read * '-' contents holds a command to run; the output of * which is the contents of the partition. * contents the specification of a partition's contents * * A specification that is a single dash indicates an unused partition * entry. */ static int parse_part(const char *spec) { struct part *part; char *sep; size_t len; int error; if (strcmp(spec, "-") == 0) { nparts++; return (0); } part = calloc(1, sizeof(struct part)); if (part == NULL) return (ENOMEM); sep = strchr(spec, ':'); if (sep == NULL) { error = EINVAL; goto errout; } len = sep - spec + 1; if (len < 2) { error = EINVAL; goto errout; } part->alias = malloc(len); if (part->alias == NULL) { error = ENOMEM; goto errout; } strlcpy(part->alias, spec, len); spec = sep + 1; switch (*spec) { case ':': part->kind = PART_KIND_SIZE; break; case '=': part->kind = PART_KIND_FILE; break; case '-': part->kind = PART_KIND_PIPE; break; default: error = EINVAL; goto errout; } spec++; part->contents = strdup(spec); if (part->contents == NULL) { error = ENOMEM; goto errout; } spec = part->alias; sep = strchr(spec, '/'); if (sep != NULL) { *sep++ = '\0'; if (strlen(part->alias) == 0 || strlen(sep) == 0) { error = EINVAL; goto errout; } part->label = strdup(sep); if (part->label == NULL) { error = ENOMEM; goto errout; } } part->index = nparts; TAILQ_INSERT_TAIL(&partlist, part, link); nparts++; return (0); errout: if (part->alias != NULL) free(part->alias); free(part); return (error); } #if defined(SPARSE_WRITE) ssize_t sparse_write(int fd, const void *ptr, size_t sz) { const char *buf, *p; off_t ofs; size_t len; ssize_t wr, wrsz; buf = ptr; wrsz = 0; p = memchr(buf, 0, sz); while (sz > 0) { len = (p != NULL) ? (size_t)(p - buf) : sz; if (len > 0) { len = (len + secsz - 1) & ~(secsz - 1); if (len > sz) len = sz; wr = write(fd, buf, len); if (wr < 0) return (-1); } else { while (len < sz && *p++ == '\0') len++; if (len < sz) len &= ~(secsz - 1); if (len == 0) continue; ofs = lseek(fd, len, SEEK_CUR); if (ofs < 0) return (-1); wr = len; } buf += wr; sz -= wr; wrsz += wr; p = memchr(buf, 0, sz); } return (wrsz); } #endif /* SPARSE_WRITE */ void mkimg_chs(lba_t lba, u_int maxcyl, u_int *cylp, u_int *hdp, u_int *secp) { u_int hd, sec; *cylp = *hdp = *secp = ~0U; if (nsecs == 1 || nheads == 1) return; sec = lba % nsecs + 1; lba /= nsecs; hd = lba % nheads; lba /= nheads; if (lba > maxcyl) return; *cylp = lba; *hdp = hd; *secp = sec; } static int capacity_resize(lba_t end) { lba_t min_capsz, max_capsz; min_capsz = (min_capacity + secsz - 1) / secsz; max_capsz = (max_capacity + secsz - 1) / secsz; if (max_capsz != 0 && end > max_capsz) return (ENOSPC); if (end >= min_capsz) return (0); return (image_set_size(min_capsz)); } static void mkimg_validate(void) { struct part *part, *part2; lba_t start, end, start2, end2; int i, j; i = 0; TAILQ_FOREACH(part, &partlist, link) { start = part->block; end = part->block + part->size; j = i + 1; part2 = TAILQ_NEXT(part, link); if (part2 == NULL) break; TAILQ_FOREACH_FROM(part2, &partlist, link) { start2 = part2->block; end2 = part2->block + part2->size; if ((start >= start2 && start < end2) || (end > start2 && end <= end2)) { errx(1, "partition %d overlaps partition %d", i, j); } j++; } i++; } } static void mkimg(void) { FILE *fp; struct part *part; lba_t block, blkoffset; uint64_t bytesize, byteoffset; char *size, *offset; bool abs_offset; int error, fd; /* First check partition information */ TAILQ_FOREACH(part, &partlist, link) { error = scheme_check_part(part); if (error) errc(EX_DATAERR, error, "partition %d", part->index+1); } block = scheme_metadata(SCHEME_META_IMG_START, 0); abs_offset = false; TAILQ_FOREACH(part, &partlist, link) { byteoffset = blkoffset = 0; abs_offset = false; /* Look for an offset. Set size too if we can. */ switch (part->kind) { case PART_KIND_SIZE: case PART_KIND_FILE: offset = part->contents; size = strsep(&offset, ":"); if (part->kind == PART_KIND_SIZE && expand_number(size, &bytesize) == -1) error = errno; if (offset != NULL) { if (*offset != '+') abs_offset = true; else offset++; if (expand_number(offset, &byteoffset) == -1) error = errno; } break; } /* Work out exactly where the partition starts. */ blkoffset = (byteoffset + secsz - 1) / secsz; if (abs_offset) block = scheme_metadata(SCHEME_META_PART_ABSOLUTE, blkoffset); else block = scheme_metadata(SCHEME_META_PART_BEFORE, block + blkoffset); part->block = block; if (verbose) fprintf(stderr, "partition %d: starting block %llu " "... ", part->index + 1, (long long)part->block); /* Pull in partition contents, set size if we haven't yet. */ switch (part->kind) { case PART_KIND_FILE: fd = open(part->contents, O_RDONLY, 0); if (fd != -1) { error = image_copyin(block, fd, &bytesize); close(fd); } else error = errno; break; case PART_KIND_PIPE: fp = popen(part->contents, "r"); if (fp != NULL) { fd = fileno(fp); error = image_copyin(block, fd, &bytesize); pclose(fp); } else error = errno; break; } if (error) errc(EX_IOERR, error, "partition %d", part->index + 1); part->size = (bytesize + secsz - 1) / secsz; if (verbose) { bytesize = part->size * secsz; fprintf(stderr, "size %llu bytes (%llu blocks)\n", (long long)bytesize, (long long)part->size); if (abs_offset) { fprintf(stderr, " location %llu bytes (%llu blocks)\n", (long long)byteoffset, (long long)blkoffset); } else if (blkoffset > 0) { fprintf(stderr, " offset %llu bytes (%llu blocks)\n", (long long)byteoffset, (long long)blkoffset); } } block = scheme_metadata(SCHEME_META_PART_AFTER, part->block + part->size); } mkimg_validate(); block = scheme_metadata(SCHEME_META_IMG_END, block); error = image_set_size(block); if (!error) { error = capacity_resize(block); block = image_get_size(); } if (!error) { error = format_resize(block); block = image_get_size(); } if (error) errc(EX_IOERR, error, "image sizing"); ncyls = block / (nsecs * nheads); error = scheme_write(block); if (error) errc(EX_IOERR, error, "writing metadata"); } int main(int argc, char *argv[]) { const char *format_name; int bcfd, outfd; int c, error; bcfd = -1; outfd = 1; /* Write to stdout by default */ - while ((c = getopt_long(argc, argv, "a:b:c:C:f:o:p:s:vyH:P:RS:T:", + while ((c = getopt_long(argc, argv, "a:b:c:C:f:o:p:s:t:vyH:P:S:T:", longopts, NULL)) != -1) { switch (c) { case 'a': /* ACTIVE PARTITION, if supported */ error = parse_uint32(&active_partition, 1, 100, optarg); if (error) errc(EX_DATAERR, error, "Partition ordinal"); break; case 'b': /* BOOT CODE */ if (bcfd != -1) usage("multiple bootcode given"); bcfd = open(optarg, O_RDONLY, 0); if (bcfd == -1) err(EX_UNAVAILABLE, "%s", optarg); break; case 'c': /* MINIMUM CAPACITY */ error = parse_uint64(&min_capacity, 1, INT64_MAX, optarg); if (error) errc(EX_DATAERR, error, "minimum capacity in bytes"); break; case 'C': /* MAXIMUM CAPACITY */ error = parse_uint64(&max_capacity, 1, INT64_MAX, optarg); if (error) errc(EX_DATAERR, error, "maximum capacity in bytes"); break; case 'f': /* OUTPUT FORMAT */ if (format_selected() != NULL) usage("multiple formats given"); error = format_select(optarg); if (error) errc(EX_DATAERR, error, "format"); break; case 'o': /* OUTPUT FILE */ if (outfd != 1) usage("multiple output files given"); outfd = open(optarg, O_WRONLY | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH); if (outfd == -1) err(EX_CANTCREAT, "%s", optarg); break; case 'p': /* PARTITION */ error = parse_part(optarg); if (error) errc(EX_DATAERR, error, "partition"); break; - case 'R': - reproducible = true; - break; case 's': /* SCHEME */ if (scheme_selected() != NULL) usage("multiple schemes given"); error = scheme_select(optarg); if (error) errc(EX_DATAERR, error, "scheme"); break; + case 't': { + char *ep; + long long val; + + errno = 0; + val = strtoll(optarg, &ep, 0); + if (ep == optarg || *ep != '\0') + errno = EINVAL; + if (errno != 0) + errc(EX_DATAERR, errno, "timestamp"); + timestamp = (time_t)val; + break; + } case 'y': unit_testing++; break; case 'v': verbose++; break; case 'H': /* GEOMETRY: HEADS */ error = parse_uint32(&nheads, 1, 255, optarg); if (error) errc(EX_DATAERR, error, "number of heads"); break; case 'P': /* GEOMETRY: PHYSICAL SECTOR SIZE */ error = parse_uint32(&blksz, 512, INT_MAX+1U, optarg); if (error == 0 && !pwr_of_two(blksz)) error = EINVAL; if (error) errc(EX_DATAERR, error, "physical sector size"); break; case 'S': /* GEOMETRY: LOGICAL SECTOR SIZE */ error = parse_uint32(&secsz, 512, INT_MAX+1U, optarg); if (error == 0 && !pwr_of_two(secsz)) error = EINVAL; if (error) errc(EX_DATAERR, error, "logical sector size"); break; case 'T': /* GEOMETRY: TRACK SIZE */ error = parse_uint32(&nsecs, 1, 63, optarg); if (error) errc(EX_DATAERR, error, "track size"); break; case LONGOPT_FORMATS: print_formats(0); exit(EX_OK); /*NOTREACHED*/ case LONGOPT_SCHEMES: print_schemes(0); exit(EX_OK); /*NOTREACHED*/ case LONGOPT_VERSION: print_version(); exit(EX_OK); /*NOTREACHED*/ case LONGOPT_CAPACITY: error = parse_uint64(&min_capacity, 1, INT64_MAX, optarg); if (error) errc(EX_DATAERR, error, "capacity in bytes"); max_capacity = min_capacity; break; default: usage("unknown option"); } } if (argc > optind) usage("trailing arguments"); if (scheme_selected() == NULL && nparts > 0) usage("no scheme"); if (nparts == 0 && min_capacity == 0) usage("no partitions"); if (max_capacity != 0 && min_capacity > max_capacity) usage("minimum capacity cannot be larger than the maximum one"); - if (reproducible) - srandom(42); - if (secsz > blksz) { if (blksz != 0) errx(EX_DATAERR, "the physical block size cannot " "be smaller than the sector size"); blksz = secsz; } if (secsz > scheme_max_secsz()) errx(EX_DATAERR, "maximum sector size supported is %u; " "size specified is %u", scheme_max_secsz(), secsz); if (nparts > scheme_max_parts()) errx(EX_DATAERR, "%d partitions supported; %d given", scheme_max_parts(), nparts); if (format_selected() == NULL) format_select("raw"); if (bcfd != -1) { error = scheme_bootcode(bcfd); close(bcfd); if (error) errc(EX_DATAERR, error, "boot code"); } format_name = format_selected()->name; if (verbose) { fprintf(stderr, "Logical sector size: %u\n", secsz); fprintf(stderr, "Physical block size: %u\n", blksz); fprintf(stderr, "Sectors per track: %u\n", nsecs); fprintf(stderr, "Number of heads: %u\n", nheads); fputc('\n', stderr); if (scheme_selected()) fprintf(stderr, "Partitioning scheme: %s\n", scheme_selected()->name); fprintf(stderr, "Output file format: %s\n", format_name); fputc('\n', stderr); } #if defined(SPARSE_WRITE) /* * sparse_write() fails if output is not seekable so fail early * not wasting some load unless output format is raw */ if (strcmp("raw", format_name) && lseek(outfd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE) errx(EX_USAGE, "%s: output must be seekable", format_name); #endif error = image_init(); if (error) errc(EX_OSERR, error, "cannot initialize"); mkimg(); if (verbose) { fputc('\n', stderr); fprintf(stderr, "Number of cylinders: %u\n", ncyls); } error = format_write(outfd); if (error) errc(EX_IOERR, error, "writing image"); return (0); } diff --git a/usr.bin/mkimg/mkimg.h b/usr.bin/mkimg/mkimg.h index 608de458e83c..aa0ec2a8d944 100644 --- a/usr.bin/mkimg/mkimg.h +++ b/usr.bin/mkimg/mkimg.h @@ -1,114 +1,114 @@ /*- * Copyright (c) 2014 Juniper Networks, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _MKIMG_MKIMG_H_ #define _MKIMG_MKIMG_H_ #include #include -#include +#include -extern bool reproducible; /* Generate reproducible output. */ +extern time_t timestamp; struct part { TAILQ_ENTRY(part) link; char *alias; /* Partition type alias. */ char *contents; /* Contents/size specification. */ u_int kind; /* Content kind. */ #define PART_UNDEF 0 #define PART_KIND_FILE 1 #define PART_KIND_PIPE 2 #define PART_KIND_SIZE 3 u_int index; /* Partition index (0-based). */ uintptr_t type; /* Scheme-specific partition type. */ lba_t block; /* Block-offset of partition in image. */ lba_t size; /* Size in blocks of partition. */ char *label; /* Partition label. */ }; extern TAILQ_HEAD(partlisthead, part) partlist; extern u_int nparts; extern u_int unit_testing; extern u_int verbose; extern u_int ncyls; extern u_int nheads; extern u_int nsecs; extern u_int secsz; /* Logical block size. */ extern u_int blksz; /* Physical block size. */ extern uint32_t active_partition; static inline lba_t round_block(lba_t n) { lba_t b = blksz / secsz; return ((n + b - 1) & ~(b - 1)); } static inline lba_t round_cylinder(lba_t n) { u_int cyl = nsecs * nheads; u_int r = n % cyl; return ((r == 0) ? n : n + cyl - r); } static inline lba_t round_track(lba_t n) { u_int r = n % nsecs; return ((r == 0) ? n : n + nsecs - r); } #if !defined(SPARSE_WRITE) #define sparse_write write #else ssize_t sparse_write(int, const void *, size_t); #endif void mkimg_chs(lba_t, u_int, u_int *, u_int *, u_int *); struct mkimg_uuid { uint32_t time_low; uint16_t time_mid; uint16_t time_hi_and_version; uint8_t clock_seq_hi_and_reserved; uint8_t clock_seq_low; uint8_t node[6]; }; typedef struct mkimg_uuid mkimg_uuid_t; void mkimg_uuid(mkimg_uuid_t *); void mkimg_uuid_enc(void *, const mkimg_uuid_t *); #ifdef __linux__ # if !defined(__unused) # define __unused __attribute__ ((__unused__)) # endif #endif #endif /* _MKIMG_MKIMG_H_ */ diff --git a/usr.bin/mkimg/uuid.c b/usr.bin/mkimg/uuid.c index f3415a8c1111..885a6c36b522 100644 --- a/usr.bin/mkimg/uuid.c +++ b/usr.bin/mkimg/uuid.c @@ -1,113 +1,114 @@ /*- * Copyright (c) 2016 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include "endian.h" #include "image.h" #include "mkimg.h" static void osdep_uuidgen(mkimg_uuid_t *); #ifdef __APPLE__ #include static void osdep_uuidgen(mkimg_uuid_t *uuid) { uuid_generate_time((void *)uuid); } #endif /* __APPLE__ */ #if defined(__linux__) || defined(__FreeBSD__) #include #include static void osdep_uuidgen(mkimg_uuid_t *uuid) { struct timeval tv; uint64_t time = 0x01B21DD213814000LL; u_int i; uint16_t seq; - if (reproducible) - memset(&tv, 0, sizeof(tv)); - else if (gettimeofday(&tv, NULL) == -1) + if (timestamp != (time_t)-1) { + tv.tv_sec = timestamp; + tv.tv_usec = 0; + } else if (gettimeofday(&tv, NULL) == -1) abort(); time += (uint64_t)tv.tv_sec * 10000000LL; time += tv.tv_usec * 10; uuid->time_low = (uint32_t)time; uuid->time_mid = (uint16_t)(time >> 32); uuid->time_hi_and_version = (uint16_t)(time >> 48) & 0xfff; uuid->time_hi_and_version |= 1 << 12; seq = random(); uuid->clock_seq_hi_and_reserved = (uint8_t)(seq >> 8) & 0x3f; uuid->clock_seq_low = (uint8_t)seq; for (i = 0; i < 6; i++) uuid->node[i] = (uint8_t)random(); uuid->node[0] |= 0x01; } #endif /* __linux__ */ void mkimg_uuid(mkimg_uuid_t *uuid) { static uint8_t gen[sizeof(mkimg_uuid_t)]; u_int i; if (!unit_testing) { osdep_uuidgen(uuid); return; } for (i = 0; i < sizeof(gen); i++) gen[i]++; memcpy(uuid, gen, sizeof(*uuid)); } void mkimg_uuid_enc(void *buf, const mkimg_uuid_t *uuid) { uint8_t *p = buf; u_int i; le32enc(p, uuid->time_low); le16enc(p + 4, uuid->time_mid); le16enc(p + 6, uuid->time_hi_and_version); p[8] = uuid->clock_seq_hi_and_reserved; p[9] = uuid->clock_seq_low; for (i = 0; i < 6; i++) p[10 + i] = uuid->node[i]; } diff --git a/usr.bin/mkimg/vhd.c b/usr.bin/mkimg/vhd.c index 1e1f1e7f3c3e..c0fe45ab416e 100644 --- a/usr.bin/mkimg/vhd.c +++ b/usr.bin/mkimg/vhd.c @@ -1,412 +1,412 @@ /*- * Copyright (c) 2014, 2015 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include "endian.h" #include "image.h" #include "format.h" #include "mkimg.h" #ifndef __has_extension #define __has_extension(x) 0 #endif /* * General notes: * o File is in network byte order. * o The timestamp is seconds since 1/1/2000 12:00:00 AM UTC * * This file is divided in 3 parts: * 1. Common definitions * 2. Dynamic VHD support * 3. Fixed VHD support */ /* * PART 1: Common definitions */ #define VHD_SECTOR_SIZE 512 #define VHD_BLOCK_SIZE (4096 * VHD_SECTOR_SIZE) /* 2MB blocks */ struct vhd_geom { uint16_t cylinders; uint8_t heads; uint8_t sectors; }; struct vhd_footer { uint64_t cookie; #define VHD_FOOTER_COOKIE 0x636f6e6563746978ULL uint32_t features; #define VHD_FEATURES_TEMPORARY 0x01 #define VHD_FEATURES_RESERVED 0x02 uint32_t version; #define VHD_VERSION 0x00010000 uint64_t data_offset; uint32_t timestamp; uint32_t creator_tool; #define VHD_CREATOR_TOOL 0x2a696d67 /* FreeBSD mkimg */ uint32_t creator_version; #define VHD_CREATOR_VERSION 0x00020000 uint32_t creator_os; #define VHD_CREATOR_OS 0x5769326b /* Wi2k */ uint64_t original_size; uint64_t current_size; struct vhd_geom geometry; uint32_t disk_type; #define VHD_DISK_TYPE_FIXED 2 #define VHD_DISK_TYPE_DYNAMIC 3 #define VHD_DISK_TYPE_DIFF 4 uint32_t checksum; mkimg_uuid_t id; uint8_t saved_state; uint8_t _reserved[427]; }; #if __has_extension(c_static_assert) _Static_assert(sizeof(struct vhd_footer) == VHD_SECTOR_SIZE, "Wrong size for footer"); #endif static uint32_t vhd_checksum(void *buf, size_t sz) { uint8_t *p = buf; uint32_t sum; size_t ofs; sum = 0; for (ofs = 0; ofs < sz; ofs++) sum += p[ofs]; return (~sum); } static void vhd_geometry(uint64_t image_size, struct vhd_geom *geom) { lba_t imgsz; long cth; imgsz = image_size / VHD_SECTOR_SIZE; /* Respect command line options if possible. */ if (nheads > 1 && nheads < 256 && nsecs > 1 && nsecs < 256 && ncyls < 65536) { geom->cylinders = (ncyls != 0) ? ncyls : imgsz / (nheads * nsecs); geom->heads = nheads; geom->sectors = nsecs; return; } if (imgsz > 65536 * 16 * 255) imgsz = 65536 * 16 * 255; if (imgsz >= 65535 * 16 * 63) { geom->cylinders = imgsz / (16 * 255); geom->heads = 16; geom->sectors = 255; return; } geom->sectors = 17; cth = imgsz / 17; geom->heads = (cth + 1023) / 1024; if (geom->heads < 4) geom->heads = 4; if (cth >= (geom->heads * 1024) || geom->heads > 16) { geom->heads = 16; geom->sectors = 31; cth = imgsz / 31; } if (cth >= (geom->heads * 1024)) { geom->heads = 16; geom->sectors = 63; cth = imgsz / 63; } geom->cylinders = cth / geom->heads; } static uint64_t vhd_resize(uint64_t origsz) { struct vhd_geom geom; uint64_t newsz; /* * Round the image size to the pre-determined geometry that * matches the image size. This circular dependency implies * that we need to loop to handle boundary conditions. * The first time, newsz equals origsz and the geometry will * typically yield a new size that's smaller. We keep adding * cylinder's worth of sectors to the new size until its * larger or equal or origsz. But during those iterations, * the geometry can change, so we need to account for that. */ newsz = origsz; while (1) { vhd_geometry(newsz, &geom); newsz = (int64_t)geom.cylinders * geom.heads * geom.sectors * VHD_SECTOR_SIZE; if (newsz >= origsz) break; newsz += geom.heads * geom.sectors * VHD_SECTOR_SIZE; } return (newsz); } static uint32_t vhd_timestamp(void) { time_t t; if (!unit_testing) { - t = time(NULL); + t = timestamp != (time_t)-1 ? timestamp : time(NULL); return (t - 0x386d4380); } return (0x01234567); } static void vhd_make_footer(struct vhd_footer *footer, uint64_t image_size, uint32_t disk_type, uint64_t data_offset) { mkimg_uuid_t id; memset(footer, 0, sizeof(*footer)); be64enc(&footer->cookie, VHD_FOOTER_COOKIE); be32enc(&footer->features, VHD_FEATURES_RESERVED); be32enc(&footer->version, VHD_VERSION); be64enc(&footer->data_offset, data_offset); be32enc(&footer->timestamp, vhd_timestamp()); be32enc(&footer->creator_tool, VHD_CREATOR_TOOL); be32enc(&footer->creator_version, VHD_CREATOR_VERSION); be32enc(&footer->creator_os, VHD_CREATOR_OS); be64enc(&footer->original_size, image_size); be64enc(&footer->current_size, image_size); vhd_geometry(image_size, &footer->geometry); be16enc(&footer->geometry.cylinders, footer->geometry.cylinders); be32enc(&footer->disk_type, disk_type); mkimg_uuid(&id); mkimg_uuid_enc(&footer->id, &id); be32enc(&footer->checksum, vhd_checksum(footer, sizeof(*footer))); } /* * PART 2: Dynamic VHD support * * Notes: * o File layout: * copy of disk footer * dynamic disk header * block allocation table (BAT) * data blocks * disk footer */ struct vhd_dyn_header { uint64_t cookie; #define VHD_HEADER_COOKIE 0x6378737061727365ULL uint64_t data_offset; uint64_t table_offset; uint32_t version; uint32_t max_entries; uint32_t block_size; uint32_t checksum; mkimg_uuid_t parent_id; uint32_t parent_timestamp; char _reserved1[4]; uint16_t parent_name[256]; /* UTF-16 */ struct { uint32_t code; uint32_t data_space; uint32_t data_length; uint32_t _reserved; uint64_t data_offset; } parent_locator[8]; char _reserved2[256]; }; #if __has_extension(c_static_assert) _Static_assert(sizeof(struct vhd_dyn_header) == VHD_SECTOR_SIZE * 2, "Wrong size for header"); #endif static int vhd_dyn_resize(lba_t imgsz) { uint64_t imagesz; imagesz = vhd_resize(imgsz * secsz); return (image_set_size(imagesz / secsz)); } static int vhd_dyn_write(int fd) { struct vhd_footer footer; struct vhd_dyn_header header; uint64_t imgsz, rawsz; lba_t blk, blkcnt, nblks; uint32_t *bat; void *bitmap; size_t batsz; uint32_t sector; int bat_entries, error, entry; rawsz = image_get_size() * secsz; imgsz = (rawsz + VHD_BLOCK_SIZE - 1) & ~(VHD_BLOCK_SIZE - 1); vhd_make_footer(&footer, rawsz, VHD_DISK_TYPE_DYNAMIC, sizeof(footer)); if (sparse_write(fd, &footer, sizeof(footer)) < 0) return (errno); bat_entries = imgsz / VHD_BLOCK_SIZE; memset(&header, 0, sizeof(header)); be64enc(&header.cookie, VHD_HEADER_COOKIE); be64enc(&header.data_offset, ~0ULL); be64enc(&header.table_offset, sizeof(footer) + sizeof(header)); be32enc(&header.version, VHD_VERSION); be32enc(&header.max_entries, bat_entries); be32enc(&header.block_size, VHD_BLOCK_SIZE); be32enc(&header.checksum, vhd_checksum(&header, sizeof(header))); if (sparse_write(fd, &header, sizeof(header)) < 0) return (errno); batsz = bat_entries * sizeof(uint32_t); batsz = (batsz + VHD_SECTOR_SIZE - 1) & ~(VHD_SECTOR_SIZE - 1); bat = malloc(batsz); if (bat == NULL) return (errno); memset(bat, 0xff, batsz); blkcnt = VHD_BLOCK_SIZE / secsz; sector = (sizeof(footer) + sizeof(header) + batsz) / VHD_SECTOR_SIZE; for (entry = 0; entry < bat_entries; entry++) { blk = entry * blkcnt; if (image_data(blk, blkcnt)) { be32enc(&bat[entry], sector); sector += (VHD_BLOCK_SIZE / VHD_SECTOR_SIZE) + 1; } } if (sparse_write(fd, bat, batsz) < 0) { free(bat); return (errno); } free(bat); bitmap = malloc(VHD_SECTOR_SIZE); if (bitmap == NULL) return (errno); memset(bitmap, 0xff, VHD_SECTOR_SIZE); blk = 0; blkcnt = VHD_BLOCK_SIZE / secsz; error = 0; nblks = rawsz / secsz; while (blk < nblks) { if (!image_data(blk, blkcnt)) { blk += blkcnt; continue; } if (sparse_write(fd, bitmap, VHD_SECTOR_SIZE) < 0) { error = errno; break; } /* Handle partial last block */ if (blk + blkcnt > nblks) blkcnt = nblks - blk; error = image_copyout_region(fd, blk, blkcnt); if (error) break; blk += blkcnt; } free(bitmap); if (error) return (error); error = image_copyout_zeroes(fd, imgsz - rawsz); if (error) return (error); if (sparse_write(fd, &footer, sizeof(footer)) < 0) return (errno); return (0); } static struct mkimg_format vhd_dyn_format = { .name = "vhd", .description = "Virtual Hard Disk", .resize = vhd_dyn_resize, .write = vhd_dyn_write, }; FORMAT_DEFINE(vhd_dyn_format); /* * PART 3: Fixed VHD */ static int vhd_fix_resize(lba_t imgsz) { uint64_t imagesz; imagesz = vhd_resize(imgsz * secsz); /* * Azure demands that images are a whole number of megabytes. */ imagesz = (imagesz + 0xfffffULL) & ~0xfffffULL; return (image_set_size(imagesz / secsz)); } static int vhd_fix_write(int fd) { struct vhd_footer footer; uint64_t imagesz; int error; error = image_copyout(fd); if (error) return (error); imagesz = image_get_size() * secsz; vhd_make_footer(&footer, imagesz, VHD_DISK_TYPE_FIXED, ~0ULL); error = (sparse_write(fd, &footer, sizeof(footer)) < 0) ? errno : 0; return (error); } static struct mkimg_format vhd_fix_format = { .name = "vhdf", .description = "Fixed Virtual Hard Disk", .resize = vhd_fix_resize, .write = vhd_fix_write, }; FORMAT_DEFINE(vhd_fix_format);