xref: /openbmc/qemu/tests/qemu-iotests/qcow2.py (revision f03868bd5653265e97b253102d77d83ea85efdea)
16e19b3c4SKevin Wolf#!/usr/bin/env python
26e19b3c4SKevin Wolf
3*f03868bdSEduardo Habkostfrom __future__ import print_function
46e19b3c4SKevin Wolfimport sys
56e19b3c4SKevin Wolfimport struct
66e19b3c4SKevin Wolfimport string
76e19b3c4SKevin Wolf
86e19b3c4SKevin Wolfclass QcowHeaderExtension:
96e19b3c4SKevin Wolf
106e19b3c4SKevin Wolf    def __init__(self, magic, length, data):
118884dd1bSKevin Wolf        if length % 8 != 0:
128884dd1bSKevin Wolf            padding = 8 - (length % 8)
138884dd1bSKevin Wolf            data += "\0" * padding
148884dd1bSKevin Wolf
156e19b3c4SKevin Wolf        self.magic  = magic
166e19b3c4SKevin Wolf        self.length = length
176e19b3c4SKevin Wolf        self.data   = data
186e19b3c4SKevin Wolf
196e19b3c4SKevin Wolf    @classmethod
206e19b3c4SKevin Wolf    def create(cls, magic, data):
216e19b3c4SKevin Wolf        return QcowHeaderExtension(magic, len(data), data)
226e19b3c4SKevin Wolf
236e19b3c4SKevin Wolfclass QcowHeader:
246e19b3c4SKevin Wolf
256e19b3c4SKevin Wolf    uint32_t = 'I'
266e19b3c4SKevin Wolf    uint64_t = 'Q'
276e19b3c4SKevin Wolf
286e19b3c4SKevin Wolf    fields = [
296e19b3c4SKevin Wolf        # Version 2 header fields
306e19b3c4SKevin Wolf        [ uint32_t, '%#x',  'magic' ],
316e19b3c4SKevin Wolf        [ uint32_t, '%d',   'version' ],
326e19b3c4SKevin Wolf        [ uint64_t, '%#x',  'backing_file_offset' ],
336e19b3c4SKevin Wolf        [ uint32_t, '%#x',  'backing_file_size' ],
346e19b3c4SKevin Wolf        [ uint32_t, '%d',   'cluster_bits' ],
356e19b3c4SKevin Wolf        [ uint64_t, '%d',   'size' ],
366e19b3c4SKevin Wolf        [ uint32_t, '%d',   'crypt_method' ],
376e19b3c4SKevin Wolf        [ uint32_t, '%d',   'l1_size' ],
386e19b3c4SKevin Wolf        [ uint64_t, '%#x',  'l1_table_offset' ],
396e19b3c4SKevin Wolf        [ uint64_t, '%#x',  'refcount_table_offset' ],
406e19b3c4SKevin Wolf        [ uint32_t, '%d',   'refcount_table_clusters' ],
416e19b3c4SKevin Wolf        [ uint32_t, '%d',   'nb_snapshots' ],
426e19b3c4SKevin Wolf        [ uint64_t, '%#x',  'snapshot_offset' ],
431042ec94SKevin Wolf
441042ec94SKevin Wolf        # Version 3 header fields
451042ec94SKevin Wolf        [ uint64_t, '%#x',  'incompatible_features' ],
461042ec94SKevin Wolf        [ uint64_t, '%#x',  'compatible_features' ],
471042ec94SKevin Wolf        [ uint64_t, '%#x',  'autoclear_features' ],
481042ec94SKevin Wolf        [ uint32_t, '%d',   'refcount_order' ],
491042ec94SKevin Wolf        [ uint32_t, '%d',   'header_length' ],
506e19b3c4SKevin Wolf    ];
516e19b3c4SKevin Wolf
526e19b3c4SKevin Wolf    fmt = '>' + ''.join(field[0] for field in fields)
536e19b3c4SKevin Wolf
546e19b3c4SKevin Wolf    def __init__(self, fd):
556e19b3c4SKevin Wolf
566e19b3c4SKevin Wolf        buf_size = struct.calcsize(QcowHeader.fmt)
576e19b3c4SKevin Wolf
586e19b3c4SKevin Wolf        fd.seek(0)
596e19b3c4SKevin Wolf        buf = fd.read(buf_size)
606e19b3c4SKevin Wolf
616e19b3c4SKevin Wolf        header = struct.unpack(QcowHeader.fmt, buf)
626e19b3c4SKevin Wolf        self.__dict__ = dict((field[2], header[i])
636e19b3c4SKevin Wolf            for i, field in enumerate(QcowHeader.fields))
646e19b3c4SKevin Wolf
651042ec94SKevin Wolf        self.set_defaults()
666e19b3c4SKevin Wolf        self.cluster_size = 1 << self.cluster_bits
676e19b3c4SKevin Wolf
681042ec94SKevin Wolf        fd.seek(self.header_length)
696e19b3c4SKevin Wolf        self.load_extensions(fd)
706e19b3c4SKevin Wolf
716e19b3c4SKevin Wolf        if self.backing_file_offset:
726e19b3c4SKevin Wolf            fd.seek(self.backing_file_offset)
736e19b3c4SKevin Wolf            self.backing_file = fd.read(self.backing_file_size)
746e19b3c4SKevin Wolf        else:
756e19b3c4SKevin Wolf            self.backing_file = None
766e19b3c4SKevin Wolf
771042ec94SKevin Wolf    def set_defaults(self):
786e19b3c4SKevin Wolf        if self.version == 2:
791042ec94SKevin Wolf            self.incompatible_features = 0
801042ec94SKevin Wolf            self.compatible_features = 0
811042ec94SKevin Wolf            self.autoclear_features = 0
821042ec94SKevin Wolf            self.refcount_order = 4
831042ec94SKevin Wolf            self.header_length = 72
846e19b3c4SKevin Wolf
856e19b3c4SKevin Wolf    def load_extensions(self, fd):
866e19b3c4SKevin Wolf        self.extensions = []
876e19b3c4SKevin Wolf
886e19b3c4SKevin Wolf        if self.backing_file_offset != 0:
896e19b3c4SKevin Wolf            end = min(self.cluster_size, self.backing_file_offset)
906e19b3c4SKevin Wolf        else:
916e19b3c4SKevin Wolf            end = self.cluster_size
926e19b3c4SKevin Wolf
936e19b3c4SKevin Wolf        while fd.tell() < end:
946e19b3c4SKevin Wolf            (magic, length) = struct.unpack('>II', fd.read(8))
956e19b3c4SKevin Wolf            if magic == 0:
966e19b3c4SKevin Wolf                break
976e19b3c4SKevin Wolf            else:
986e19b3c4SKevin Wolf                padded = (length + 7) & ~7
996e19b3c4SKevin Wolf                data = fd.read(padded)
1006e19b3c4SKevin Wolf                self.extensions.append(QcowHeaderExtension(magic, length, data))
1016e19b3c4SKevin Wolf
1026e19b3c4SKevin Wolf    def update_extensions(self, fd):
1036e19b3c4SKevin Wolf
1041042ec94SKevin Wolf        fd.seek(self.header_length)
1056e19b3c4SKevin Wolf        extensions = self.extensions
1066e19b3c4SKevin Wolf        extensions.append(QcowHeaderExtension(0, 0, ""))
1076e19b3c4SKevin Wolf        for ex in extensions:
1086e19b3c4SKevin Wolf            buf = struct.pack('>II', ex.magic, ex.length)
1096e19b3c4SKevin Wolf            fd.write(buf)
1106e19b3c4SKevin Wolf            fd.write(ex.data)
1116e19b3c4SKevin Wolf
1126e19b3c4SKevin Wolf        if self.backing_file != None:
1136e19b3c4SKevin Wolf            self.backing_file_offset = fd.tell()
1146e19b3c4SKevin Wolf            fd.write(self.backing_file)
1156e19b3c4SKevin Wolf
1166e19b3c4SKevin Wolf        if fd.tell() > self.cluster_size:
1176e19b3c4SKevin Wolf            raise Exception("I think I just broke the image...")
1186e19b3c4SKevin Wolf
1196e19b3c4SKevin Wolf
1206e19b3c4SKevin Wolf    def update(self, fd):
1211042ec94SKevin Wolf        header_bytes = self.header_length
1226e19b3c4SKevin Wolf
1236e19b3c4SKevin Wolf        self.update_extensions(fd)
1246e19b3c4SKevin Wolf
1256e19b3c4SKevin Wolf        fd.seek(0)
1266e19b3c4SKevin Wolf        header = tuple(self.__dict__[f] for t, p, f in QcowHeader.fields)
1276e19b3c4SKevin Wolf        buf = struct.pack(QcowHeader.fmt, *header)
1286e19b3c4SKevin Wolf        buf = buf[0:header_bytes-1]
1296e19b3c4SKevin Wolf        fd.write(buf)
1306e19b3c4SKevin Wolf
1316e19b3c4SKevin Wolf    def dump(self):
1326e19b3c4SKevin Wolf        for f in QcowHeader.fields:
133*f03868bdSEduardo Habkost            print("%-25s" % f[2], f[1] % self.__dict__[f[2]])
134*f03868bdSEduardo Habkost        print("")
1356e19b3c4SKevin Wolf
1366e19b3c4SKevin Wolf    def dump_extensions(self):
1376e19b3c4SKevin Wolf        for ex in self.extensions:
1386e19b3c4SKevin Wolf
1396e19b3c4SKevin Wolf            data = ex.data[:ex.length]
1406e19b3c4SKevin Wolf            if all(c in string.printable for c in data):
1416e19b3c4SKevin Wolf                data = "'%s'" % data
1426e19b3c4SKevin Wolf            else:
1436e19b3c4SKevin Wolf                data = "<binary>"
1446e19b3c4SKevin Wolf
145*f03868bdSEduardo Habkost            print("Header extension:")
146*f03868bdSEduardo Habkost            print("%-25s %#x" % ("magic", ex.magic))
147*f03868bdSEduardo Habkost            print("%-25s %d" % ("length", ex.length))
148*f03868bdSEduardo Habkost            print("%-25s %s" % ("data", data))
149*f03868bdSEduardo Habkost            print("")
1506e19b3c4SKevin Wolf
1516e19b3c4SKevin Wolf
1526e19b3c4SKevin Wolfdef cmd_dump_header(fd):
1536e19b3c4SKevin Wolf    h = QcowHeader(fd)
1546e19b3c4SKevin Wolf    h.dump()
1556e19b3c4SKevin Wolf    h.dump_extensions()
1566e19b3c4SKevin Wolf
157c93331c9SKevin Wolfdef cmd_set_header(fd, name, value):
158c93331c9SKevin Wolf    try:
159c93331c9SKevin Wolf        value = int(value, 0)
160c93331c9SKevin Wolf    except:
161*f03868bdSEduardo Habkost        print("'%s' is not a valid number" % value)
162c93331c9SKevin Wolf        sys.exit(1)
163c93331c9SKevin Wolf
164c93331c9SKevin Wolf    fields = (field[2] for field in QcowHeader.fields)
165c93331c9SKevin Wolf    if not name in fields:
166*f03868bdSEduardo Habkost        print("'%s' is not a known header field" % name)
167c93331c9SKevin Wolf        sys.exit(1)
168c93331c9SKevin Wolf
169c93331c9SKevin Wolf    h = QcowHeader(fd)
170c93331c9SKevin Wolf    h.__dict__[name] = value
171c93331c9SKevin Wolf    h.update(fd)
172c93331c9SKevin Wolf
1736e19b3c4SKevin Wolfdef cmd_add_header_ext(fd, magic, data):
1746e19b3c4SKevin Wolf    try:
1756e19b3c4SKevin Wolf        magic = int(magic, 0)
1766e19b3c4SKevin Wolf    except:
177*f03868bdSEduardo Habkost        print("'%s' is not a valid magic number" % magic)
1786e19b3c4SKevin Wolf        sys.exit(1)
1796e19b3c4SKevin Wolf
1806e19b3c4SKevin Wolf    h = QcowHeader(fd)
1816e19b3c4SKevin Wolf    h.extensions.append(QcowHeaderExtension.create(magic, data))
1826e19b3c4SKevin Wolf    h.update(fd)
1836e19b3c4SKevin Wolf
18412ac6d3dSKevin Wolfdef cmd_add_header_ext_stdio(fd, magic):
18512ac6d3dSKevin Wolf    data = sys.stdin.read()
18612ac6d3dSKevin Wolf    cmd_add_header_ext(fd, magic, data)
18712ac6d3dSKevin Wolf
1886e19b3c4SKevin Wolfdef cmd_del_header_ext(fd, magic):
1896e19b3c4SKevin Wolf    try:
1906e19b3c4SKevin Wolf        magic = int(magic, 0)
1916e19b3c4SKevin Wolf    except:
192*f03868bdSEduardo Habkost        print("'%s' is not a valid magic number" % magic)
1936e19b3c4SKevin Wolf        sys.exit(1)
1946e19b3c4SKevin Wolf
1956e19b3c4SKevin Wolf    h = QcowHeader(fd)
1966e19b3c4SKevin Wolf    found = False
1976e19b3c4SKevin Wolf
1986e19b3c4SKevin Wolf    for ex in h.extensions:
1996e19b3c4SKevin Wolf        if ex.magic == magic:
2006e19b3c4SKevin Wolf            found = True
2016e19b3c4SKevin Wolf            h.extensions.remove(ex)
2026e19b3c4SKevin Wolf
2036e19b3c4SKevin Wolf    if not found:
204*f03868bdSEduardo Habkost        print("No such header extension")
2056e19b3c4SKevin Wolf        return
2066e19b3c4SKevin Wolf
2076e19b3c4SKevin Wolf    h.update(fd)
2086e19b3c4SKevin Wolf
2091b2eff62SStefan Hajnoczidef cmd_set_feature_bit(fd, group, bit):
2101b2eff62SStefan Hajnoczi    try:
2111b2eff62SStefan Hajnoczi        bit = int(bit, 0)
2121b2eff62SStefan Hajnoczi        if bit < 0 or bit >= 64:
2131b2eff62SStefan Hajnoczi            raise ValueError
2141b2eff62SStefan Hajnoczi    except:
215*f03868bdSEduardo Habkost        print("'%s' is not a valid bit number in range [0, 64)" % bit)
2161b2eff62SStefan Hajnoczi        sys.exit(1)
2171b2eff62SStefan Hajnoczi
2181b2eff62SStefan Hajnoczi    h = QcowHeader(fd)
2191b2eff62SStefan Hajnoczi    if group == 'incompatible':
2201b2eff62SStefan Hajnoczi        h.incompatible_features |= 1 << bit
2211b2eff62SStefan Hajnoczi    elif group == 'compatible':
2221b2eff62SStefan Hajnoczi        h.compatible_features |= 1 << bit
2231b2eff62SStefan Hajnoczi    elif group == 'autoclear':
2241b2eff62SStefan Hajnoczi        h.autoclear_features |= 1 << bit
2251b2eff62SStefan Hajnoczi    else:
226*f03868bdSEduardo Habkost        print("'%s' is not a valid group, try 'incompatible', 'compatible', or 'autoclear'" % group)
2271b2eff62SStefan Hajnoczi        sys.exit(1)
2281b2eff62SStefan Hajnoczi
2291b2eff62SStefan Hajnoczi    h.update(fd)
2301b2eff62SStefan Hajnoczi
2316e19b3c4SKevin Wolfcmds = [
2326e19b3c4SKevin Wolf    [ 'dump-header',          cmd_dump_header,          0, 'Dump image header and header extensions' ],
233c93331c9SKevin Wolf    [ 'set-header',           cmd_set_header,           2, 'Set a field in the header'],
2346e19b3c4SKevin Wolf    [ 'add-header-ext',       cmd_add_header_ext,       2, 'Add a header extension' ],
23512ac6d3dSKevin Wolf    [ 'add-header-ext-stdio', cmd_add_header_ext_stdio, 1, 'Add a header extension, data from stdin' ],
2366e19b3c4SKevin Wolf    [ 'del-header-ext',       cmd_del_header_ext,       1, 'Delete a header extension' ],
2371b2eff62SStefan Hajnoczi    [ 'set-feature-bit',      cmd_set_feature_bit,      2, 'Set a feature bit'],
2386e19b3c4SKevin Wolf]
2396e19b3c4SKevin Wolf
2406e19b3c4SKevin Wolfdef main(filename, cmd, args):
2416e19b3c4SKevin Wolf    fd = open(filename, "r+b")
2426e19b3c4SKevin Wolf    try:
2436e19b3c4SKevin Wolf        for name, handler, num_args, desc in cmds:
2446e19b3c4SKevin Wolf            if name != cmd:
2456e19b3c4SKevin Wolf                continue
2466e19b3c4SKevin Wolf            elif len(args) != num_args:
2476e19b3c4SKevin Wolf                usage()
2486e19b3c4SKevin Wolf                return
2496e19b3c4SKevin Wolf            else:
2506e19b3c4SKevin Wolf                handler(fd, *args)
2516e19b3c4SKevin Wolf                return
252*f03868bdSEduardo Habkost        print("Unknown command '%s'" % cmd)
2536e19b3c4SKevin Wolf    finally:
2546e19b3c4SKevin Wolf        fd.close()
2556e19b3c4SKevin Wolf
2566e19b3c4SKevin Wolfdef usage():
257*f03868bdSEduardo Habkost    print("Usage: %s <file> <cmd> [<arg>, ...]" % sys.argv[0])
258*f03868bdSEduardo Habkost    print("")
259*f03868bdSEduardo Habkost    print("Supported commands:")
2606e19b3c4SKevin Wolf    for name, handler, num_args, desc in cmds:
261*f03868bdSEduardo Habkost        print("    %-20s - %s" % (name, desc))
2626e19b3c4SKevin Wolf
263d2ef210cSKevin Wolfif __name__ == '__main__':
2646e19b3c4SKevin Wolf    if len(sys.argv) < 3:
2656e19b3c4SKevin Wolf        usage()
2666e19b3c4SKevin Wolf        sys.exit(1)
2676e19b3c4SKevin Wolf
2686e19b3c4SKevin Wolf    main(sys.argv[1], sys.argv[2], sys.argv[3:])
269