Coverage Report

Created: 2026-11-20 08:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qemu/block/dmg.c
Line
Count
Source
1
/*
2
 * QEMU Block driver for DMG images
3
 *
4
 * Copyright (c) 2004 Johannes E. Schindelin
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "qemu/osdep.h"
25
#include "qapi/error.h"
26
#include "block/block-io.h"
27
#include "block/block_int.h"
28
#include "qemu/bswap.h"
29
#include "qemu/error-report.h"
30
#include "qemu/module.h"
31
#include "qemu/memalign.h"
32
#include "dmg.h"
33
34
BdrvDmgUncompressFunc *dmg_uncompress_bz2;
35
BdrvDmgUncompressFunc *dmg_uncompress_lzfse;
36
37
enum {
38
    /* Limit chunk sizes to prevent unreasonable amounts of memory being used
39
     * or truncating when converting to 32-bit types
40
     */
41
    DMG_LENGTHS_MAX = 64 * 1024 * 1024, /* 64 MB */
42
    DMG_SECTORCOUNTS_MAX = DMG_LENGTHS_MAX / 512,
43
};
44
45
enum {
46
    /* DMG Block Type */
47
    UDZE = 0, /* Zeroes */
48
    UDRW,     /* RAW type */
49
    UDIG,     /* Ignore */
50
    UDCO = 0x80000004,
51
    UDZO,
52
    UDBZ,
53
    ULFO,
54
    UDCM = 0x7ffffffe, /* Comments */
55
    UDLE = 0xffffffff  /* Last Entry */
56
};
57
58
static int dmg_probe(const uint8_t *buf, int buf_size, const char *filename)
59
0
{
60
0
    int len;
61
62
0
    if (!filename) {
63
0
        return 0;
64
0
    }
65
66
0
    len = strlen(filename);
67
0
    if (len > 4 && !strcmp(filename + len - 4, ".dmg")) {
68
0
        return 2;
69
0
    }
70
0
    return 0;
71
0
}
72
73
static int GRAPH_RDLOCK
74
read_uint64(BlockDriverState *bs, int64_t offset, uint64_t *result)
75
0
{
76
0
    uint64_t buffer;
77
0
    int ret;
78
79
0
    ret = bdrv_pread(bs->file, offset, 8, &buffer, 0);
80
0
    if (ret < 0) {
81
0
        return ret;
82
0
    }
83
84
0
    *result = be64_to_cpu(buffer);
85
0
    return 0;
86
0
}
87
88
static int GRAPH_RDLOCK
89
read_uint32(BlockDriverState *bs, int64_t offset, uint32_t *result)
90
0
{
91
0
    uint32_t buffer;
92
0
    int ret;
93
94
0
    ret = bdrv_pread(bs->file, offset, 4, &buffer, 0);
95
0
    if (ret < 0) {
96
0
        return ret;
97
0
    }
98
99
0
    *result = be32_to_cpu(buffer);
100
0
    return 0;
101
0
}
102
103
static inline uint64_t buff_read_uint64(const uint8_t *buffer, int64_t offset)
104
0
{
105
0
    return be64_to_cpu(*(uint64_t *)&buffer[offset]);
106
0
}
107
108
static inline uint32_t buff_read_uint32(const uint8_t *buffer, int64_t offset)
109
0
{
110
0
    return be32_to_cpu(*(uint32_t *)&buffer[offset]);
111
0
}
112
113
/* Increase max chunk sizes, if necessary.  This function is used to calculate
114
 * the buffer sizes needed for compressed/uncompressed chunk I/O.
115
 */
116
static void update_max_chunk_size(BDRVDMGState *s, uint32_t chunk,
117
                                  uint32_t *max_compressed_size,
118
                                  uint32_t *max_sectors_per_chunk)
119
0
{
120
0
    uint32_t compressed_size = 0;
121
0
    uint32_t uncompressed_sectors = 0;
122
123
0
    switch (s->types[chunk]) {
124
0
    case UDZO: /* zlib compressed */
125
0
    case UDBZ: /* bzip2 compressed */
126
0
    case ULFO: /* lzfse compressed */
127
0
        compressed_size = s->lengths[chunk];
128
0
        uncompressed_sectors = s->sectorcounts[chunk];
129
0
        break;
130
0
    case UDRW: /* copy */
131
0
        uncompressed_sectors = DIV_ROUND_UP(s->lengths[chunk], 512);
132
0
        break;
133
0
    case UDZE: /* zero */
134
0
    case UDIG: /* ignore */
135
        /* as the all-zeroes block may be large, it is treated specially: the
136
         * sector is not copied from a large buffer, a simple memset is used
137
         * instead. Therefore uncompressed_sectors does not need to be set. */
138
0
        break;
139
0
    }
140
141
0
    if (compressed_size > *max_compressed_size) {
142
0
        *max_compressed_size = compressed_size;
143
0
    }
144
0
    if (uncompressed_sectors > *max_sectors_per_chunk) {
145
0
        *max_sectors_per_chunk = uncompressed_sectors;
146
0
    }
147
0
}
148
149
static int64_t dmg_find_koly_offset(BdrvChild *file, Error **errp)
150
0
{
151
0
    BlockDriverState *file_bs = file->bs;
152
0
    int64_t length;
153
0
    int64_t offset = 0;
154
0
    uint8_t buffer[515];
155
0
    int i, ret;
156
157
    /* bdrv_getlength returns a multiple of block size (512), rounded up. Since
158
     * dmg images can have odd sizes, try to look for the "koly" magic which
159
     * marks the begin of the UDIF trailer (512 bytes). This magic can be found
160
     * in the last 511 bytes of the second-last sector or the first 4 bytes of
161
     * the last sector (search space: 515 bytes) */
162
0
    length = bdrv_getlength(file_bs);
163
0
    if (length < 0) {
164
0
        error_setg_errno(errp, -length,
165
0
            "Failed to get file size while reading UDIF trailer");
166
0
        return length;
167
0
    } else if (length < 512) {
168
0
        error_setg(errp, "dmg file must be at least 512 bytes long");
169
0
        return -EINVAL;
170
0
    }
171
0
    if (length > 511 + 512) {
172
0
        offset = length - 511 - 512;
173
0
    }
174
0
    length = length < 515 ? length : 515;
175
0
    ret = bdrv_pread(file, offset, length, buffer, 0);
176
0
    if (ret < 0) {
177
0
        error_setg_errno(errp, -ret, "Failed while reading UDIF trailer");
178
0
        return ret;
179
0
    }
180
0
    for (i = 0; i < length - 3; i++) {
181
0
        if (buffer[i] == 'k' && buffer[i+1] == 'o' &&
182
0
            buffer[i+2] == 'l' && buffer[i+3] == 'y') {
183
0
            return offset + i;
184
0
        }
185
0
    }
186
0
    error_setg(errp, "Could not locate UDIF trailer in dmg file");
187
0
    return -EINVAL;
188
0
}
189
190
/* used when building the sector table */
191
typedef struct DmgHeaderState {
192
    /* used internally by dmg_read_mish_block to remember offsets of blocks
193
     * across calls */
194
    uint64_t data_fork_offset;
195
    /* exported for dmg_open */
196
    uint32_t max_compressed_size;
197
    uint32_t max_sectors_per_chunk;
198
} DmgHeaderState;
199
200
static bool dmg_is_known_block_type(uint32_t entry_type)
201
0
{
202
0
    switch (entry_type) {
203
0
    case UDZE:    /* zeros */
204
0
    case UDRW:    /* uncompressed */
205
0
    case UDIG:    /* ignore */
206
0
    case UDZO:    /* zlib */
207
0
        return true;
208
0
    case UDBZ:    /* bzip2 */
209
0
        return !!dmg_uncompress_bz2;
210
0
    case ULFO:    /* lzfse */
211
0
        return !!dmg_uncompress_lzfse;
212
0
    default:
213
0
        return false;
214
0
    }
215
0
}
216
217
static int dmg_read_mish_block(BDRVDMGState *s, DmgHeaderState *ds,
218
                               uint8_t *buffer, uint32_t count)
219
0
{
220
0
    uint32_t type, i;
221
0
    int ret;
222
0
    size_t new_size;
223
0
    uint32_t chunk_count;
224
0
    int64_t offset = 0;
225
0
    uint64_t data_offset;
226
0
    uint64_t in_offset = ds->data_fork_offset;
227
0
    uint64_t out_offset;
228
229
0
    if (count < 244) {
230
0
        return 0; /* too small, skip silently */
231
0
    }
232
233
0
    type = buff_read_uint32(buffer, offset);
234
    /* skip data that is not a valid MISH block (invalid magic) */
235
0
    if (type != 0x6d697368) {
236
        /* assume success for now */
237
0
        return 0;
238
0
    }
239
240
    /* chunk offsets are relative to this sector number */
241
0
    out_offset = buff_read_uint64(buffer, offset + 8);
242
243
    /* location in data fork for (compressed) blob (in bytes) */
244
0
    data_offset = buff_read_uint64(buffer, offset + 0x18);
245
0
    in_offset += data_offset;
246
247
    /* move to begin of chunk entries */
248
0
    offset += 204;
249
250
0
    chunk_count = (count - 204) / 40;
251
0
    new_size = sizeof(uint64_t) * (s->n_chunks + chunk_count);
252
0
    s->types = g_realloc(s->types, new_size / 2);
253
0
    s->offsets = g_realloc(s->offsets, new_size);
254
0
    s->lengths = g_realloc(s->lengths, new_size);
255
0
    s->sectors = g_realloc(s->sectors, new_size);
256
0
    s->sectorcounts = g_realloc(s->sectorcounts, new_size);
257
258
0
    for (i = s->n_chunks; i < s->n_chunks + chunk_count; i++) {
259
0
        s->types[i] = buff_read_uint32(buffer, offset);
260
0
        if (!dmg_is_known_block_type(s->types[i])) {
261
0
            switch (s->types[i]) {
262
0
            case UDBZ:
263
0
                warn_report_once("dmg-bzip2 module is missing, accessing bzip2 "
264
0
                                 "compressed blocks will result in I/O errors");
265
0
                break;
266
0
            case ULFO:
267
0
                warn_report_once("dmg-lzfse module is missing, accessing lzfse "
268
0
                                 "compressed blocks will result in I/O errors");
269
0
                break;
270
0
            case UDCM:
271
0
            case UDLE:
272
                /* Comments and last entry can be ignored without problems */
273
0
                break;
274
0
            default:
275
0
                warn_report_once("Image contains chunks of unknown type %x, "
276
0
                                 "accessing them will result in I/O errors",
277
0
                                 s->types[i]);
278
0
                break;
279
0
            }
280
0
            chunk_count--;
281
0
            i--;
282
0
            offset += 40;
283
0
            continue;
284
0
        }
285
286
        /* sector number */
287
0
        s->sectors[i] = buff_read_uint64(buffer, offset + 8);
288
0
        s->sectors[i] += out_offset;
289
290
        /* sector count */
291
0
        s->sectorcounts[i] = buff_read_uint64(buffer, offset + 0x10);
292
293
        /* all-zeroes sector (type UDZE and UDIG) does not need to be
294
         * "uncompressed" and can therefore be unbounded. */
295
0
        if (s->types[i] != UDZE && s->types[i] != UDIG
296
0
            && s->sectorcounts[i] > DMG_SECTORCOUNTS_MAX) {
297
0
            error_report("sector count %" PRIu64 " for chunk %" PRIu32
298
0
                         " is larger than max (%u)",
299
0
                         s->sectorcounts[i], i, DMG_SECTORCOUNTS_MAX);
300
0
            ret = -EINVAL;
301
0
            goto fail;
302
0
        }
303
304
        /* offset in (compressed) data fork */
305
0
        s->offsets[i] = buff_read_uint64(buffer, offset + 0x18);
306
0
        s->offsets[i] += in_offset;
307
308
        /* length in (compressed) data fork */
309
0
        s->lengths[i] = buff_read_uint64(buffer, offset + 0x20);
310
311
0
        if (s->lengths[i] > DMG_LENGTHS_MAX) {
312
0
            error_report("length %" PRIu64 " for chunk %" PRIu32
313
0
                         " is larger than max (%u)",
314
0
                         s->lengths[i], i, DMG_LENGTHS_MAX);
315
0
            ret = -EINVAL;
316
0
            goto fail;
317
0
        }
318
319
        /*
320
         * Uncompressed chunk length must match sector count. Compressed chunks
321
         * are validated during dmg_read_chunk() since the uncompressed size is
322
         * not known ahead of time.
323
         */
324
0
        if (s->types[i] == UDRW) {
325
0
            if (s->sectorcounts[i] != DIV_ROUND_UP(s->lengths[i], 512)) {
326
0
                error_report("length %" PRIu64 " for chunk %" PRIu32
327
0
                             " is inconsistent with sector count %" PRIu64,
328
0
                             s->lengths[i], i, s->sectorcounts[i]);
329
0
                ret = -EINVAL;
330
0
                goto fail;
331
0
            }
332
0
        }
333
334
0
        update_max_chunk_size(s, i, &ds->max_compressed_size,
335
0
                              &ds->max_sectors_per_chunk);
336
0
        offset += 40;
337
0
    }
338
0
    s->n_chunks += chunk_count;
339
0
    return 0;
340
341
0
fail:
342
0
    return ret;
343
0
}
344
345
static int GRAPH_RDLOCK
346
dmg_read_resource_fork(BlockDriverState *bs, DmgHeaderState *ds,
347
                       uint64_t info_begin, uint64_t info_length)
348
0
{
349
0
    BDRVDMGState *s = bs->opaque;
350
0
    int ret;
351
0
    uint32_t count, rsrc_data_offset;
352
0
    uint8_t *buffer = NULL;
353
0
    uint64_t info_end;
354
0
    uint64_t offset;
355
356
    /* read offset from begin of resource fork (info_begin) to resource data */
357
0
    ret = read_uint32(bs, info_begin, &rsrc_data_offset);
358
0
    if (ret < 0) {
359
0
        goto fail;
360
0
    } else if (rsrc_data_offset > info_length) {
361
0
        ret = -EINVAL;
362
0
        goto fail;
363
0
    }
364
365
    /* read length of resource data */
366
0
    ret = read_uint32(bs, info_begin + 8, &count);
367
0
    if (ret < 0) {
368
0
        goto fail;
369
0
    } else if (count == 0 || rsrc_data_offset + count > info_length) {
370
0
        ret = -EINVAL;
371
0
        goto fail;
372
0
    }
373
374
    /* begin of resource data (consisting of one or more resources) */
375
0
    offset = info_begin + rsrc_data_offset;
376
377
    /* end of resource data (there is possibly a following resource map
378
     * which will be ignored). */
379
0
    info_end = offset + count;
380
381
    /* read offsets (mish blocks) from one or more resources in resource data */
382
0
    while (offset < info_end) {
383
        /* size of following resource */
384
0
        ret = read_uint32(bs, offset, &count);
385
0
        if (ret < 0) {
386
0
            goto fail;
387
0
        } else if (count == 0 || count > info_end - offset) {
388
0
            ret = -EINVAL;
389
0
            goto fail;
390
0
        }
391
0
        offset += 4;
392
393
0
        buffer = g_realloc(buffer, count);
394
0
        ret = bdrv_pread(bs->file, offset, count, buffer, 0);
395
0
        if (ret < 0) {
396
0
            goto fail;
397
0
        }
398
399
0
        ret = dmg_read_mish_block(s, ds, buffer, count);
400
0
        if (ret < 0) {
401
0
            goto fail;
402
0
        }
403
        /* advance offset by size of resource */
404
0
        offset += count;
405
0
    }
406
0
    ret = 0;
407
408
0
fail:
409
0
    g_free(buffer);
410
0
    return ret;
411
0
}
412
413
static int GRAPH_RDLOCK
414
dmg_read_plist_xml(BlockDriverState *bs, DmgHeaderState *ds,
415
                   uint64_t info_begin, uint64_t info_length)
416
0
{
417
0
    BDRVDMGState *s = bs->opaque;
418
0
    int ret;
419
0
    uint8_t *buffer = NULL;
420
0
    char *data_begin, *data_end;
421
422
    /* Have at least some length to avoid NULL for g_malloc. Attempt to set a
423
     * safe upper cap on the data length. A test sample had a XML length of
424
     * about 1 MiB. */
425
0
    if (info_length == 0 || info_length > 16 * 1024 * 1024) {
426
0
        ret = -EINVAL;
427
0
        goto fail;
428
0
    }
429
430
0
    buffer = g_malloc(info_length + 1);
431
0
    buffer[info_length] = '\0';
432
0
    ret = bdrv_pread(bs->file, info_begin, info_length, buffer, 0);
433
0
    if (ret < 0) {
434
0
        ret = -EINVAL;
435
0
        goto fail;
436
0
    }
437
438
    /* look for <data>...</data>. The data is 284 (0x11c) bytes after base64
439
     * decode. The actual data element has 431 (0x1af) bytes which includes tabs
440
     * and line feeds. */
441
0
    data_end = (char *)buffer;
442
0
    while ((data_begin = strstr(data_end, "<data>")) != NULL) {
443
0
        guchar *mish;
444
0
        gsize out_len = 0;
445
446
0
        data_begin += 6;
447
0
        data_end = strstr(data_begin, "</data>");
448
        /* malformed XML? */
449
0
        if (data_end == NULL) {
450
0
            ret = -EINVAL;
451
0
            goto fail;
452
0
        }
453
0
        *data_end++ = '\0';
454
0
        mish = g_base64_decode(data_begin, &out_len);
455
0
        ret = dmg_read_mish_block(s, ds, mish, (uint32_t)out_len);
456
0
        g_free(mish);
457
0
        if (ret < 0) {
458
0
            goto fail;
459
0
        }
460
0
    }
461
0
    ret = 0;
462
463
0
fail:
464
0
    g_free(buffer);
465
0
    return ret;
466
0
}
467
468
static int dmg_open(BlockDriverState *bs, QDict *options, int flags,
469
                    Error **errp)
470
0
{
471
0
    BDRVDMGState *s = bs->opaque;
472
0
    DmgHeaderState ds;
473
0
    uint64_t rsrc_fork_offset, rsrc_fork_length;
474
0
    uint64_t plist_xml_offset, plist_xml_length;
475
0
    int64_t offset;
476
0
    int ret;
477
478
0
    GLOBAL_STATE_CODE();
479
480
0
    bdrv_graph_rdlock_main_loop();
481
0
    ret = bdrv_apply_auto_read_only(bs, NULL, errp);
482
0
    bdrv_graph_rdunlock_main_loop();
483
0
    if (ret < 0) {
484
0
        return ret;
485
0
    }
486
487
0
    ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
488
0
    if (ret < 0) {
489
0
        return ret;
490
0
    }
491
492
0
    GRAPH_RDLOCK_GUARD_MAINLOOP();
493
494
    /*
495
     * NB: if uncompress submodules are absent,
496
     * ie block_module_load return value == 0, the function pointers
497
     * dmg_uncompress_bz2 and dmg_uncompress_lzfse will be NULL.
498
     */
499
0
    if (block_module_load("dmg-bz2", errp) < 0) {
500
0
        return -EINVAL;
501
0
    }
502
0
    if (block_module_load("dmg-lzfse", errp) < 0) {
503
0
        return -EINVAL;
504
0
    }
505
506
0
    s->n_chunks = 0;
507
0
    s->offsets = s->lengths = s->sectors = s->sectorcounts = NULL;
508
    /* used by dmg_read_mish_block to keep track of the current I/O position */
509
0
    ds.data_fork_offset = 0;
510
0
    ds.max_compressed_size = 1;
511
0
    ds.max_sectors_per_chunk = 1;
512
513
    /* locate the UDIF trailer */
514
0
    offset = dmg_find_koly_offset(bs->file, errp);
515
0
    if (offset < 0) {
516
0
        ret = offset;
517
0
        goto fail;
518
0
    }
519
520
    /* offset of data fork (DataForkOffset) */
521
0
    ret = read_uint64(bs, offset + 0x18, &ds.data_fork_offset);
522
0
    if (ret < 0) {
523
0
        goto fail;
524
0
    } else if (ds.data_fork_offset > offset) {
525
0
        ret = -EINVAL;
526
0
        goto fail;
527
0
    }
528
529
    /* offset of resource fork (RsrcForkOffset) */
530
0
    ret = read_uint64(bs, offset + 0x28, &rsrc_fork_offset);
531
0
    if (ret < 0) {
532
0
        goto fail;
533
0
    }
534
0
    ret = read_uint64(bs, offset + 0x30, &rsrc_fork_length);
535
0
    if (ret < 0) {
536
0
        goto fail;
537
0
    }
538
0
    if (rsrc_fork_offset >= offset ||
539
0
        rsrc_fork_length > offset - rsrc_fork_offset) {
540
0
        ret = -EINVAL;
541
0
        goto fail;
542
0
    }
543
    /* offset of property list (XMLOffset) */
544
0
    ret = read_uint64(bs, offset + 0xd8, &plist_xml_offset);
545
0
    if (ret < 0) {
546
0
        goto fail;
547
0
    }
548
0
    ret = read_uint64(bs, offset + 0xe0, &plist_xml_length);
549
0
    if (ret < 0) {
550
0
        goto fail;
551
0
    }
552
0
    if (plist_xml_offset >= offset ||
553
0
        plist_xml_length > offset - plist_xml_offset) {
554
0
        ret = -EINVAL;
555
0
        goto fail;
556
0
    }
557
0
    ret = read_uint64(bs, offset + 0x1ec, (uint64_t *)&bs->total_sectors);
558
0
    if (ret < 0) {
559
0
        goto fail;
560
0
    }
561
0
    if (bs->total_sectors < 0) {
562
0
        ret = -EINVAL;
563
0
        goto fail;
564
0
    }
565
0
    if (rsrc_fork_length != 0) {
566
0
        ret = dmg_read_resource_fork(bs, &ds,
567
0
                                     rsrc_fork_offset, rsrc_fork_length);
568
0
        if (ret < 0) {
569
0
            goto fail;
570
0
        }
571
0
    } else if (plist_xml_length != 0) {
572
0
        ret = dmg_read_plist_xml(bs, &ds, plist_xml_offset, plist_xml_length);
573
0
        if (ret < 0) {
574
0
            goto fail;
575
0
        }
576
0
    } else {
577
0
        ret = -EINVAL;
578
0
        goto fail;
579
0
    }
580
581
    /* There must be at least one chunk */
582
0
    if (s->n_chunks == 0) {
583
0
        ret = -EINVAL;
584
0
        goto fail;
585
0
    }
586
587
    /* initialize zlib engine */
588
0
    s->compressed_chunk = qemu_try_blockalign(bs->file->bs,
589
0
                                              ds.max_compressed_size + 1);
590
0
    s->uncompressed_chunk = qemu_try_blockalign(bs->file->bs,
591
0
                                                512 * ds.max_sectors_per_chunk);
592
0
    if (s->compressed_chunk == NULL || s->uncompressed_chunk == NULL) {
593
0
        ret = -ENOMEM;
594
0
        goto fail;
595
0
    }
596
597
0
    if (inflateInit(&s->zstream) != Z_OK) {
598
0
        ret = -EINVAL;
599
0
        goto fail;
600
0
    }
601
602
0
    s->current_chunk = s->n_chunks;
603
604
0
    qemu_co_mutex_init(&s->lock);
605
0
    return 0;
606
607
0
fail:
608
0
    g_free(s->types);
609
0
    g_free(s->offsets);
610
0
    g_free(s->lengths);
611
0
    g_free(s->sectors);
612
0
    g_free(s->sectorcounts);
613
0
    qemu_vfree(s->compressed_chunk);
614
0
    qemu_vfree(s->uncompressed_chunk);
615
0
    return ret;
616
0
}
617
618
static void dmg_refresh_limits(BlockDriverState *bs, Error **errp)
619
0
{
620
0
    bs->bl.request_alignment = BDRV_SECTOR_SIZE; /* No sub-sector I/O */
621
0
}
622
623
static inline int is_sector_in_chunk(BDRVDMGState *s,
624
                uint32_t chunk_num, uint64_t sector_num)
625
0
{
626
0
    if (chunk_num >= s->n_chunks || s->sectors[chunk_num] > sector_num ||
627
0
            s->sectors[chunk_num] + s->sectorcounts[chunk_num] <= sector_num) {
628
0
        return 0;
629
0
    } else {
630
0
        return -1;
631
0
    }
632
0
}
633
634
static inline uint32_t search_chunk(BDRVDMGState *s, uint64_t sector_num)
635
0
{
636
    /* binary search */
637
0
    uint32_t chunk1 = 0, chunk2 = s->n_chunks - 1, chunk3;
638
0
    if (s->n_chunks == 0) {
639
0
        goto err; /* should never happen */
640
0
    }
641
0
    while (chunk1 <= chunk2) {
642
0
        chunk3 = (chunk1 + chunk2) / 2;
643
0
        if (s->sectors[chunk3] > sector_num) {
644
0
            if (chunk3 == 0) {
645
0
                goto err;
646
0
            }
647
0
            chunk2 = chunk3 - 1;
648
0
        } else if (s->sectors[chunk3] + s->sectorcounts[chunk3] > sector_num) {
649
0
            return chunk3;
650
0
        } else {
651
0
            chunk1 = chunk3 + 1;
652
0
        }
653
0
    }
654
0
err:
655
0
    return s->n_chunks; /* error */
656
0
}
657
658
static int coroutine_fn GRAPH_RDLOCK
659
dmg_read_chunk(BlockDriverState *bs, uint64_t sector_num)
660
0
{
661
0
    BDRVDMGState *s = bs->opaque;
662
663
0
    if (!is_sector_in_chunk(s, s->current_chunk, sector_num)) {
664
0
        int ret;
665
0
        uint32_t chunk = search_chunk(s, sector_num);
666
667
0
        if (chunk >= s->n_chunks) {
668
0
            return -1;
669
0
        }
670
671
0
        s->current_chunk = s->n_chunks;
672
0
        switch (s->types[chunk]) { /* block entry type */
673
0
        case UDZO: { /* zlib compressed */
674
            /* we need to buffer, because only the chunk as whole can be
675
             * inflated. */
676
0
            ret = bdrv_co_pread(bs->file, s->offsets[chunk], s->lengths[chunk],
677
0
                                s->compressed_chunk, 0);
678
0
            if (ret < 0) {
679
0
                return -1;
680
0
            }
681
682
0
            s->zstream.next_in = s->compressed_chunk;
683
0
            s->zstream.avail_in = s->lengths[chunk];
684
0
            s->zstream.next_out = s->uncompressed_chunk;
685
0
            s->zstream.avail_out = 512 * s->sectorcounts[chunk];
686
0
            ret = inflateReset(&s->zstream);
687
0
            if (ret != Z_OK) {
688
0
                return -1;
689
0
            }
690
0
            ret = inflate(&s->zstream, Z_FINISH);
691
0
            if (ret != Z_STREAM_END ||
692
0
                s->zstream.total_out != 512 * s->sectorcounts[chunk]) {
693
0
                return -1;
694
0
            }
695
0
            break; }
696
0
        case UDBZ: /* bzip2 compressed */
697
0
            if (!dmg_uncompress_bz2) {
698
0
                break;
699
0
            }
700
            /* we need to buffer, because only the chunk as whole can be
701
             * inflated. */
702
0
            ret = bdrv_co_pread(bs->file, s->offsets[chunk], s->lengths[chunk],
703
0
                                s->compressed_chunk, 0);
704
0
            if (ret < 0) {
705
0
                return -1;
706
0
            }
707
708
0
            ret = dmg_uncompress_bz2((char *)s->compressed_chunk,
709
0
                                     (unsigned int) s->lengths[chunk],
710
0
                                     (char *)s->uncompressed_chunk,
711
0
                                     (unsigned int)
712
0
                                         (512 * s->sectorcounts[chunk]));
713
0
            if (ret < 0) {
714
0
                return ret;
715
0
            }
716
0
            break;
717
0
        case ULFO:
718
0
            if (!dmg_uncompress_lzfse) {
719
0
                break;
720
0
            }
721
            /* we need to buffer, because only the chunk as whole can be
722
             * inflated. */
723
0
            ret = bdrv_co_pread(bs->file, s->offsets[chunk], s->lengths[chunk],
724
0
                                s->compressed_chunk, 0);
725
0
            if (ret < 0) {
726
0
                return -1;
727
0
            }
728
729
0
            ret = dmg_uncompress_lzfse((char *)s->compressed_chunk,
730
0
                                       (unsigned int) s->lengths[chunk],
731
0
                                       (char *)s->uncompressed_chunk,
732
0
                                       (unsigned int)
733
0
                                           (512 * s->sectorcounts[chunk]));
734
0
            if (ret < 0) {
735
0
                return ret;
736
0
            }
737
0
            break;
738
0
        case UDRW: /* copy */
739
0
            ret = bdrv_co_pread(bs->file, s->offsets[chunk], s->lengths[chunk],
740
0
                                s->uncompressed_chunk, 0);
741
0
            if (ret < 0) {
742
0
                return -1;
743
0
            }
744
745
            /*
746
             * Zero the unread part of the last sector when chunk length is
747
             * unaligned to avoid exposing uninitialized memory. Valid image
748
             * files may never hit this case, but cover it to be safe.
749
             */
750
0
            if (s->lengths[chunk] & 511) {
751
0
                size_t trailing_bytes = 512 - (s->lengths[chunk] & 511);
752
0
                memset(s->uncompressed_chunk + s->lengths[chunk], 0, trailing_bytes);
753
0
            }
754
0
            break;
755
0
        case UDZE: /* zeros */
756
0
        case UDIG: /* ignore */
757
            /* see dmg_read, it is treated specially. No buffer needs to be
758
             * pre-filled, the zeroes can be set directly. */
759
0
            break;
760
0
        }
761
0
        s->current_chunk = chunk;
762
0
    }
763
0
    return 0;
764
0
}
765
766
static int coroutine_fn GRAPH_RDLOCK
767
dmg_co_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
768
              QEMUIOVector *qiov, BdrvRequestFlags flags)
769
0
{
770
0
    BDRVDMGState *s = bs->opaque;
771
0
    uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
772
0
    int nb_sectors = bytes >> BDRV_SECTOR_BITS;
773
0
    int ret, i;
774
775
0
    assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
776
0
    assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
777
778
0
    qemu_co_mutex_lock(&s->lock);
779
780
0
    for (i = 0; i < nb_sectors; i++) {
781
0
        uint32_t sector_offset_in_chunk;
782
0
        void *data;
783
784
0
        if (dmg_read_chunk(bs, sector_num + i) != 0) {
785
0
            ret = -EIO;
786
0
            goto fail;
787
0
        }
788
        /* Special case: current chunk is all zeroes. Do not perform a memcpy as
789
         * s->uncompressed_chunk may be too small to cover the large all-zeroes
790
         * section. dmg_read_chunk is called to find s->current_chunk */
791
0
        if (s->types[s->current_chunk] == UDZE
792
0
            || s->types[s->current_chunk] == UDIG) { /* all zeroes block entry */
793
0
            qemu_iovec_memset(qiov, i * 512, 0, 512);
794
0
            continue;
795
0
        }
796
0
        sector_offset_in_chunk = sector_num + i - s->sectors[s->current_chunk];
797
0
        data = s->uncompressed_chunk + sector_offset_in_chunk * 512;
798
0
        qemu_iovec_from_buf(qiov, i * 512, data, 512);
799
0
    }
800
801
0
    ret = 0;
802
0
fail:
803
0
    qemu_co_mutex_unlock(&s->lock);
804
0
    return ret;
805
0
}
806
807
static void dmg_close(BlockDriverState *bs)
808
0
{
809
0
    BDRVDMGState *s = bs->opaque;
810
811
0
    g_free(s->types);
812
0
    g_free(s->offsets);
813
0
    g_free(s->lengths);
814
0
    g_free(s->sectors);
815
0
    g_free(s->sectorcounts);
816
0
    qemu_vfree(s->compressed_chunk);
817
0
    qemu_vfree(s->uncompressed_chunk);
818
819
0
    inflateEnd(&s->zstream);
820
0
}
821
822
static BlockDriver bdrv_dmg = {
823
    .format_name    = "dmg",
824
    .instance_size  = sizeof(BDRVDMGState),
825
    .bdrv_probe     = dmg_probe,
826
    .bdrv_open      = dmg_open,
827
    .bdrv_refresh_limits = dmg_refresh_limits,
828
    .bdrv_child_perm     = bdrv_default_perms,
829
    .bdrv_co_preadv = dmg_co_preadv,
830
    .bdrv_close     = dmg_close,
831
    .is_format      = true,
832
};
833
834
static void bdrv_dmg_init(void)
835
63
{
836
63
    bdrv_register(&bdrv_dmg);
837
63
}
838
839
block_init(bdrv_dmg_init);