-
Notifications
You must be signed in to change notification settings - Fork 1
/
qcheck.c
1883 lines (1642 loc) · 56.7 KB
/
qcheck.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdint.h>
#include <inttypes.h>
#include <endian.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/param.h>
#include <assert.h>
#include <getopt.h>
#include <time.h>
#include "range.h"
#ifndef ROUND_UP
#define ROUND_UP(n,d) (((n) + (d) - 1) & -(d))
#endif
#ifndef DIV_ROUND_UP
#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
#endif
typedef enum message_type {
M_RANGE_BEGIN,
M_ERROR = M_RANGE_BEGIN, /* Fatal error messages */
M_WARN, /* Nonfatal warnings, distinct from analysis problems */
M_SUMMARY, /* Analysis summaries */
M_HELLO, /* Bootup logging message(s) */
M_HEADERS, /* Headers, Progress */
M_INFO, /* Misc. output */
M_PROBLEMS, /* All problems found, one-by-one */
M_POSITIVE, /* Positive confirmation of successful tests */
M_DEBUG, /* Debugging messages */
/* Tables */
M_HEADER_DATA, /* Dump Header block */
M_L1_TABLE, /* Dump entire L1 table, even if uninteresting */
M_L2_TABLE, /* Dump entire L2 table, even if uninteresting */
M_REFTABLE, /* Dump entire Refcount table, even if uninteresting */
M_REFBLOCK_2, /* Dump refblock entries at 2+ */
M_REFBLOCK_1, /* Dump refblock entries at 1 */
M_REFBLOCK_0, /* Dump refblock entries of 0 */
/* Ranges */
M_METADATA, /* Dump metadata ranges */
M_DATA, /* Dump data ranges */
M_VACANT, /* Dump vacant ranges */
M_LEAKED, /* Dump leaked ranges */
M_ALLOCATED, /* Dump allocated (metadata + data) ranges, squashed */
M_UNALLOCATED, /* Dump unallocated (vacant + leaked) ranges, squashed */
M_RANGE_ALL, /* Dump all ranges, unsquashed */
M_RANGE_END
} message_type;
struct {
const char *h;
char c;
} message_filters[M_RANGE_END] = {
[M_ERROR] = { "Fatal errors", 'f' },
[M_WARN] = { "Nonfatal errors", 'w' },
[M_SUMMARY] = { "Analysis summaries", 's' },
[M_HELLO] = { "Bootup log message", 'e' },
[M_HEADERS] = { "Section headers", 'h' },
[M_INFO] = { "Info / misc.", 'i' },
[M_PROBLEMS] = { "Detailed problems reports", 'p' },
[M_POSITIVE] = { "Successful test messages (Confirmation)", 'c' },
[M_DEBUG] = { "Debugging messages", 'd' },
[M_HEADER_DATA] = { "qcow2 header information", 'H' },
[M_L1_TABLE] = { "L1 table", 'L' },
[M_L2_TABLE] = { "L2 tables", 'l' },
[M_REFTABLE] = { "Refcount Table", 'R' },
[M_REFBLOCK_2] = { "Refcount Block entries (if 2+)", '2' },
[M_REFBLOCK_1] = { "Refcount Block entries (if 1)", '1' },
[M_REFBLOCK_0] = { "Refcount Block entries (if 0)", '0' },
[M_METADATA] = { "Dump metadata rangeset", 'M' },
[M_DATA] = { "Dump guest data rangeset", 'D' },
[M_VACANT] = { "Dump vacant rangeset", 'V' },
[M_LEAKED] = { "Dump leaked ([F]orgotten) rangeset", 'F' },
[M_ALLOCATED] = { "Dump allocated rangeset", 'A' },
[M_UNALLOCATED] = { "Dump unallocated rangeset", 'U' },
[M_RANGE_ALL] = { "Dump entire rangeset", 'E' }
};
#define LMASK(mtype) (1 << (mtype))
#define SMASK (LMASK(M_ERROR) | LMASK(M_WARN) | LMASK(M_DEBUG))
#define MSTREAM(mtype) ((LMASK(mtype) & mtype_stderr) ? stderr : stdout)
#define LOG_SILENT (0)
#define LOG_QUIET (LMASK(M_ERROR) | LMASK(M_WARN))
#define LOG_BASIC (LOG_QUIET | LMASK(M_SUMMARY) | LMASK(M_HEADERS) | \
LMASK(M_INFO) | LMASK(M_HEADER_DATA) | LMASK(M_L1_TABLE) | \
LMASK(M_REFTABLE) | LMASK(M_HELLO))
#define LOG_VERBOSE (LOG_BASIC | LMASK(M_PROBLEMS) | LMASK(M_POSITIVE))
#define LOG_DELUGE (-1UL & ~LMASK(M_DEBUG))
/**
* mtype_stderr: which messages get logged to stderr?
* mtype_stdout: which get logged to stdout?
* mlevel: which messages actually get printed at all?
*/
unsigned long mtype_stderr = SMASK;
unsigned long mtype_stdout = -1UL & ~SMASK;
unsigned long mlevel = LOG_BASIC;
#define STREAM_ON(mtype) ((LMASK(mtype) & mlevel) == LMASK(mtype))
#define STREAM_OFF(mtype) ((LMASK(mtype) & mlevel) == 0)
void mvprintf(enum message_type mtype, const char *fmt, va_list va)
{
if (STREAM_ON(mtype)) {
vfprintf(MSTREAM(mtype), fmt, va);
}
}
static __attribute__((format(printf, 2, 3)))
void mprintf(enum message_type mtype, const char *fmt, ...)
{
va_list va;
va_start(va, fmt);
mvprintf(mtype, fmt, va);
va_end(va);
}
static __attribute__((format(printf, 2, 3)))
void lprintf(enum message_type mtype, const char *fmt, ...)
{
va_list va;
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char ts[20];
strftime(ts, sizeof(ts), "%F %T", tm);
mprintf(mtype, "[%s] ", ts);
va_start(va, fmt);
mvprintf(mtype, fmt, va);
va_end(va);
}
char perror_buff[256];
static __attribute__((format(printf, 1, 2)))
void perrorf(const char *fmt, ...)
{
va_list va;
strerror_r(errno, perror_buff, sizeof(perror_buff));
va_start(va, fmt);
mvprintf(M_ERROR, fmt, va);
va_end(va);
mprintf(M_ERROR, ": %s\n", perror_buff);
}
#define msg_error(FMT, ...) mprintf(M_ERROR, FMT, ##__VA_ARGS__)
#define msg_warn(FMT, ...) mprintf(M_WARN, FMT, ##__VA_ARGS__)
#define msg_problem(FMT, ...) mprintf(M_PROBLEMS, FMT, ##__VA_ARGS__)
#define msg_ok(FMT, ...) mprintf(M_POSITIVE, FMT, ##__VA_ARGS__)
#define msg_info(FMT, ...) mprintf(M_INFO, FMT, ##__VA_ARGS__)
void do_summary(const char *section, int rc, int problems)
{
mprintf(M_SUMMARY, "%s: ", section);
if (rc) {
mprintf(M_SUMMARY, "Could not complete analysis, ");
}
if (!rc && !problems) {
mprintf(M_SUMMARY, "OK, 0 problems");
} else {
mprintf(M_SUMMARY, "%d %s found",
problems,
problems == 1 ? "problem" : "problems");
}
mprintf(M_SUMMARY, "\n");
}
void h1(const char *section)
{
mprintf(M_HEADERS, "\n\n== %s ==\n\n", section);
}
static __attribute__((format(printf, 1, 2)))
void h2(const char *section, ...)
{
mprintf(M_HEADERS, "== ");
va_list va;
va_start(va, section);
mvprintf(M_HEADERS, section, va);
va_end(va);
mprintf(M_HEADERS, " ==\n");
}
typedef enum rtype {
RANGE_TYPE_BEGIN = 0,
RANGE_TYPE_METADATA = RANGE_TYPE_BEGIN,
RANGE_TYPE_DATA,
RANGE_TYPE_LEAKED,
RANGE_TYPE_VACANT,
RANGE_TYPE_MAX
} rtype;
const char *rtype_lookup[RANGE_TYPE_MAX] = {
[RANGE_TYPE_METADATA] = "Metadata",
[RANGE_TYPE_DATA] = "Data",
[RANGE_TYPE_LEAKED] = "Leaked",
[RANGE_TYPE_VACANT] = "Vacant"
};
struct qheader {
unsigned char magic[4];
uint32_t version;
uint64_t backing_file_offset;
uint32_t backing_file_size;
uint32_t cluster_bits;
uint64_t size;
uint32_t crypt_method;
uint32_t l1_size;
uint64_t l1_table_offset;
uint64_t refcount_table_offset;
uint32_t refcount_table_clusters;
uint32_t nb_snapshots;
uint64_t snapshots_offset;
} __attribute__((__packed__));
struct qheader3 {
struct qheader common;
uint64_t incompatible_features; /* bit 0, 1 */
uint64_t compatible_features; /* bit 0 */
uint64_t autoclear_features; /* bit 0 */
uint32_t refcount_order;
uint32_t header_length;
} __attribute__((__packed__));
typedef struct l1_entry {
union {
uint64_t val;
struct {
#if BITS_BIG_ENDIAN
uint64_t cow:1;
uint64_t reserved:7;
uint64_t offset:47;
uint64_t align:9;
#else
uint64_t align:9;
uint64_t offset:47;
uint64_t reserved:7;
uint64_t cow:1;
#endif
};
};
} l1_entry;
typedef uint64_t l2_entry;
typedef struct qfile {
rangeset *all; /* cluster range data */
/* File Info */
FILE *fh; /* File stream */
uint64_t cluster_size; /* Size of clusters in bytes */
uint64_t file_size; /* Size of file in bytes */
uint64_t host_clusters; /* Size of file in clusters */
/* References */
uint16_t *ref_calc; /* Calculated Refcounts */
uint16_t *ref_file; /* Refcounts according to image */
uint64_t *refcount_table; /* Refcount table */
uint64_t refcount_bits; /* refcount width */
uint64_t refcount_table_size; /* actual length of refcount table */
uint64_t refcount_table_entries; /* total number of refblock pointers */
uint64_t refcount_block_entries; /* refcounts per block */
/***************/
struct qheader *header;
l1_entry *l1_table;
uint64_t num_l2_entries; /* Number of L2 entries per L2 cluster */
} qfile;
/**
* destroy_qfile: close the qcow2 and clean up all resources.
*/
void destroy_qfile(qfile *qf)
{
free(qf->l1_table);
free(qf->refcount_table);
free(qf->ref_calc);
free(qf->ref_file);
delete_rangeset(qf->all);
free(qf->header);
if (qf->fh) {
fclose(qf->fh);
}
free(qf);
}
/**
* new_qfile: Create a new qcow2 file object.
* @filename: qcow2 object to open and analyze.
* @return: NULL on error, a valid qfile object otherwise.
*/
qfile *new_qfile(const char *filename)
{
struct qfile *qf;
struct stat finfo;
int rc;
qf = (struct qfile *)calloc(1, sizeof(qfile));
if (!qf) {
perrorf("Failed to allocate storage for qfile object");
return NULL;
}
qf->all = new_rangeset(1024);
if (!qf->all) {
goto error;
}
qf->fh = fopen(filename, "r");
if (!qf->fh) {
perrorf("Couldn't open file");
goto error;
}
rc = fstat(fileno(qf->fh), &finfo);
if (rc) {
perrorf("Couldn't stat file");
goto error;
}
qf->file_size = finfo.st_size;
return qf;
error:
destroy_qfile(qf);
return NULL;
}
/**
* overlap: Check if the specified range overlaps existing ranges in a set.
* @qf: qcow2 file whose rangeset we will operate against
* @offset: Byte offset into file
* @len: Length of the range
* @return: 0 if there is no overlap, 1 otherwise.
*/
int overlap(qfile *qf, uint64_t offset, uint64_t len)
{
return range_overlap(qf->all, offset, len, NULL);
}
/**
* overlap_cluster: Check if the specified cluster overlaps
* existing ranges in a set.
* @qf: qcow2 file whose rangeset to check against
* @offset: Offset in bytes of the cluster
* @return: 0 if there is no overlap, 1 otherwise.
*/
int overlap_cluster(qfile *qf, uint64_t offset)
{
return overlap(qf, offset, qf->cluster_size);
}
/**
* add_host_range: define a new range in the host qcow2 file.
* @qf: The qcow2 file object to define a new range within.
* @offset: The host offset in the qcow2 file that starts the range, in bytes.
* @len: The length of the range, in bytes.
* @rtype: The 'type' of the range. See @rtype
* @r: Return parameter for the conflicting range, if any.
* @return: 0 if the range was added successfully.
* 1 if the range could not be added due to overlap; see @r.
* -ERRNO if there was an unrecoverable error.
*/
int add_host_range(qfile *qf, uint64_t offset, uint64_t len, rtype type,
const range **r)
{
int rc;
if (!qf) {
return -EINVAL;
}
rc = add_range(qf->all, offset, len, (1 << type), r);
if (rc > 0) {
msg_error("Unable to add range [0x%"PRIx64", 0x%"PRIx64"): "
"Collision against typemask %x\n",
offset, offset + len, rc);
/* "one" error */
return 1;
}
return rc; /* 0 or -errno */
}
/**
* add_host_cluster: Syntactic sugar for @add_host_range.
*/
int add_host_cluster(qfile *qf, uint64_t offset, rtype type,
const range **r)
{
if (!qf) {
return -EINVAL;
}
return add_host_range(qf, offset, qf->cluster_size, type, r);
}
struct filter {
qfile *qf;
int typemask;
int squash;
int showtypes;
uint64_t clusters;
range tmp;
int squashtypes;
enum message_type msg_type;
};
/**
* print_range: print a given range [r]
* Used as a callback by @print_rangset
* @r: The range to print
* @opaque: Callback information; a pointer to `struct filter` in this case.
* @return: 0.
*/
int print_range(const range *r, void *opaque)
{
struct filter *cfg = (struct filter *)opaque;
int i;
uint64_t clusters = r->length / cfg->qf->cluster_size;
mask_t typemask = r->typemask;
if (!(r->typemask & cfg->typemask)) {
return 0;
}
if (cfg->squash) {
if (cfg->tmp.end == r->offset) {
cfg->tmp.end = r->end;
cfg->tmp.length += r->length;
cfg->squashtypes |= r->typemask;
return 0;
}
}
mprintf(cfg->msg_type, "0x%09"PRIx64" - 0x%09"PRIx64" ",
r->offset,
r->end - 1);
if (cfg->showtypes) {
for (i = RANGE_TYPE_BEGIN; i < RANGE_TYPE_MAX && typemask; i++) {
if (typemask & (1 << i)) {
mprintf(cfg->msg_type, "[%s] ", rtype_lookup[i]);
typemask &= ~(1 << i);
}
}
}
if (clusters > 1) {
mprintf(cfg->msg_type, "(%"PRId64" clusters)\n", clusters);
} else {
mprintf(cfg->msg_type, "\n");
}
cfg->clusters += clusters;
return 0;
}
/* TODO: make 'squash' work as a setting */
/**
* print_rangeset: print the ranges of the file occupied by a specified
* type or types of data.
* @qf: The (analyzed) file to print the ranges for.
* @title: The title to print for this section.
* @typemask: The type mask that selects which ranges to print.
* E.g. RANGE_TYPE_METADATA.
* @showtypes: Boolean: display the type of each range next to it?
* @squash: Boolean: "merge" adjacent ranges? If more than one type
* is selected, the "type display" will show only e.g.
* which types are present in this squashed range.
* @msg_type: Which logging stream should this rangeset be printed to?
* Headers and summaries go to M_HEADERS and M_SUMMARY,
* but the rangeset itself will be printed to this stream.
*/
void print_rangeset(qfile *qf, const char *title, int typemask,
int showtypes, int squash, enum message_type msg_type)
{
struct filter *cfg;
if (!qf || !qf->all || STREAM_OFF(msg_type)) {
return;
}
cfg = (struct filter *)malloc(sizeof(struct filter));
cfg->qf = qf;
cfg->typemask = typemask;
cfg->squash = squash;
cfg->showtypes = showtypes;
cfg->clusters = 0;
cfg->msg_type = msg_type;
h1(title);
range_traversal(qf->all, T_INORDER, print_range, cfg);
h2("%s stats", title);
mprintf(msg_type, "%"PRId64" clusters\n\n", cfg->clusters);
free(cfg);
}
/**
* qref_bump: increment reference count of cluster at given offset
* @qf: qfile object to increment the refcount within
* @offset: offset in bytes of the cluster to increment the refcount of
* @return: 0 if we incremented the refcount, -ERRNO on failure.
*/
int qref_bump(qfile *qf, uint64_t offset)
{
uint64_t cluster_no;
if (!qf || !qf->ref_calc) {
return -EINVAL;
}
if (offset % qf->cluster_size) {
msg_error("Offset Misaligned, cannot bump refcount\n");
return -EINVAL;
}
cluster_no = offset / qf->cluster_size;
if (cluster_no >= qf->host_clusters) {
msg_error("BEYOND EOF, cannot bump refcount\n");
return -EINVAL;
}
qf->ref_calc[cluster_no] += 1;
return 0;
}
/**
* qref_dump: dump all calculated refcounts to M_DEBUG/stdout
* @qf: pre-analyzed file to dump refcounts for
*/
__attribute__((__unused__))
void qref_dump(qfile *qf)
{
int i;
for (i = 0; i < qf->host_clusters; i++) {
if (qf->ref_calc[i]) {
mprintf(M_DEBUG, "%d: %d\n", i, qf->ref_calc[i]);
}
}
}
/* Generally, functions return -ERRNO on error,
* and +rc on some analysis failure. */
#define CHECK_RC(rc, ret, jlabel) do { \
if ((rc) < 0) { \
goto jlabel; \
} else { \
(ret) += (rc); \
} \
} while(0)
/* sigh */
size_t fread_errno(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t rc = fread(ptr, size, nmemb, stream);
if (rc != nmemb) {
/* Treat EOF as an error; we can't get the data we want. */
errno = EIO;
}
clearerr(stream);
return rc;
}
/******************************************************************************/
/* Header Parsing & Analysis */
/******************************************************************************/
/**
* parse_header_v3: parse the v3 header if present.
* @qf: the qcow2 object to parse.
* @return: -errno on failure, 0 on success.
*/
int parse_header_v3(qfile *qf)
{
int rc;
struct qheader3 *buff;
if (!qf || !qf->header || qf->header->version != 3) {
return -EINVAL;
}
buff = (struct qheader3 *)qf->header;
rc = fseek(qf->fh, sizeof(struct qheader), SEEK_SET);
if (rc) {
rc = -errno;
perrorf("fseek to qcow2 v3 header failed");
return rc;
}
rc = fread_errno(&buff->incompatible_features,
sizeof(struct qheader3) - sizeof(struct qheader),
1, qf->fh);
if (rc != 1) {
rc = -errno;
perrorf("Couldn't read qcow2v3 header");
return rc;
}
*buff = (struct qheader3) {
.common = buff->common,
.incompatible_features = be64toh(buff->incompatible_features),
.compatible_features = be64toh(buff->compatible_features),
.autoclear_features = be64toh(buff->autoclear_features),
.refcount_order = be32toh(buff->refcount_order),
.header_length = be32toh(buff->header_length),
};
qf->refcount_bits = (1 << buff->refcount_order);
return 0;
}
/**
* parse_header: read and cache important global details of the qcow2.
* @qf: qfile object to analyze
* @return: 0 on success, -errno on failure.
* Does not perform any soft analysis or report recoverable errors.
*/
int parse_header(qfile *qf)
{
int rc;
struct qheader *header;
if (!qf) {
return -EINVAL;
}
qf->header = (struct qheader *)malloc(sizeof(struct qheader3));
if (!qf->header) {
rc = -errno;
perrorf("Could not allocate buffer for QCOW2 header block");
goto out;
}
rc = fread_errno(qf->header, sizeof(struct qheader), 1, qf->fh);
if (rc != 1) {
rc = -errno;
perrorf("Could not read QCOW2 header block");
goto error;
}
header = qf->header;
*qf->header = (struct qheader) {
.magic = { header->magic[0], header->magic[1],
header->magic[2], header->magic[3] },
.version = be32toh(header->version),
.backing_file_offset = be64toh(header->backing_file_offset),
.backing_file_size = be32toh(header->backing_file_size),
.cluster_bits = be32toh(header->cluster_bits),
.size = be64toh(header->size),
.crypt_method = be32toh(header->crypt_method),
.l1_size = be32toh(header->l1_size),
.l1_table_offset = be64toh(header->l1_table_offset),
.refcount_table_offset = be64toh(header->refcount_table_offset),
.refcount_table_clusters = be32toh(header->refcount_table_clusters),
.nb_snapshots = be32toh(header->nb_snapshots),
.snapshots_offset = be64toh(header->snapshots_offset),
};
if (header->version >= 3) {
rc = parse_header_v3(qf);
if (rc) {
goto error;
}
} else {
qf->refcount_bits = 16;
}
/* Derivative Data */
qf->cluster_size = 1 << header->cluster_bits;
qf->host_clusters = DIV_ROUND_UP(qf->file_size, qf->cluster_size);
qf->refcount_block_entries = (qf->cluster_size * 8) / qf->refcount_bits;
qf->num_l2_entries = qf->cluster_size / sizeof(l2_entry);
/* Refcount Tables -- Calculated and Read */
qf->ref_calc = (uint16_t *)calloc(qf->host_clusters, sizeof(*qf->ref_calc));
if (!qf->ref_calc) {
rc = -errno;
perrorf("Couldn't allocate reference count table");
goto error;
}
return 0;
error:
free(qf->header);
qf->header = NULL;
out:
return rc;
}
/**
* print_header: Print the header info to a stream in a readable format.
* @qf: qcow2 file object with a parsed header to print.
* @stream: Where to print.
*/
void print_header(qfile *qf)
{
struct qheader *header;
if (!qf || !qf->header) {
return;
}
header = qf->header;
h1("Header");
mprintf(M_HEADER_DATA,
"magic: 0x%x%x%x%x\n"
"version: %d\n"
"backing_file_offset: 0x%"PRIx64"\n"
"backing_file_size: 0x%x (filename length, bytes)\n"
"cluster_bits: %d (cluster size: %"PRId64" bytes)\n"
"size: 0x%"PRIx64" / %"PRId64" (bytes)\n"
"crypt_method: 0x%08x (%s)\n"
"l1_size: (num entries) 0x%x (Clusters: %"PRIx64")\n"
"l1_table_offset: 0x%"PRIx64" (Cluster Index 0x%"PRIx64")\n"
"refcount_table_offset: 0x%"PRIx64" (Cluster Index 0x%"PRIx64")\n"
"refcount_table_clusters: 0x%x\n"
"nb_snapshots: %d\n"
"snapshots_offset: 0x%"PRIx64"\n",
header->magic[0], header->magic[1],
header->magic[2], header->magic[3],
header->version,
header->backing_file_offset,
header->backing_file_size,
header->cluster_bits,
qf->cluster_size,
header->size,
header->size,
header->crypt_method,
(header->crypt_method == 0) ? "None" : "AES",
header->l1_size,
DIV_ROUND_UP(sizeof(uint64_t) * header->l1_size, qf->cluster_size),
header->l1_table_offset,
header->l1_table_offset / qf->cluster_size,
header->refcount_table_offset,
header->refcount_table_offset / qf->cluster_size,
header->refcount_table_clusters,
header->nb_snapshots,
header->snapshots_offset);
h2("Derivative Data");
mprintf(M_HEADER_DATA, "Host Clusters: %"PRId64"\n", qf->host_clusters);
mprintf(M_HEADER_DATA, "File Size: 0x%016"PRIx64"\n", qf->file_size);
}
/**
* analyze_header: check header metadata for issues,
* including metadata range bookkeeping steps.
* @qf: qcow2 file with parsed header to analyze.
* @return: -EINVAL if the qfile is absent or the header was not parsed.
* 0 if there are no issues found.
* The number of issues found otherwise.
*/
int analyze_header(qfile *qf)
{
int rc, ret = 0;
struct qheader *header;
if (!qf || !qf->header) {
return -EINVAL;
}
header = qf->header;
h1("Header Analysis");
/* Reference counting calculation */
rc = qref_bump(qf, 0);
CHECK_RC(rc, ret, error);
rc = qref_bump(qf, header->l1_table_offset);
CHECK_RC(rc, ret, error);
rc = qref_bump(qf, header->refcount_table_offset);
CHECK_RC(rc, ret, error);
/* Metadata range bookkeeping */
rc = add_host_cluster(qf, 0, RANGE_TYPE_METADATA, NULL);
CHECK_RC(rc, ret, error);
rc = add_host_range(qf, header->l1_table_offset,
DIV_ROUND_UP(sizeof(l1_entry) * header->l1_size,
qf->cluster_size) * qf->cluster_size,
RANGE_TYPE_METADATA, NULL);
CHECK_RC(rc, ret, error);
rc = add_host_range(qf, header->refcount_table_offset,
header->refcount_table_clusters * qf->cluster_size,
RANGE_TYPE_METADATA, NULL);
CHECK_RC(rc, ret, error);
if (header->snapshots_offset) {
rc = qref_bump(qf, header->snapshots_offset);
CHECK_RC(rc, ret, error);
/* FIXME: How many clusters for snapshots table? */
rc = add_host_cluster(qf, header->snapshots_offset,
RANGE_TYPE_METADATA, NULL);
CHECK_RC(rc, ret, error);
}
/* Misc Checks */
if (memcmp(&header->magic, "QFI\xfb", 4) == 0) {
msg_ok("Magic OK\n");
} else {
msg_problem("Bad header Magic\n");
ret++;
}
if (qf->cluster_size < 512) {
msg_problem("Bad cluster size, too small.\n");
ret++;
} else if (qf->cluster_size > (2 * 1024 * 1024)) {
msg_problem("Warning, cluster size is too big for QEMU.\n");
ret++;
} else {
msg_ok("Cluster size OK.\n");
}
if (header->l1_table_offset % qf->cluster_size) {
msg_problem("L1 table misalinged\n");
ret++;
} else {
msg_ok("L1 table OK\n");
}
if (header->refcount_table_offset % qf->cluster_size) {
msg_problem("Refcount table misaligned\n");
ret++;
} else {
msg_ok("Refcount table OK\n");
}
if (header->nb_snapshots) {
if (header->snapshots_offset % qf->cluster_size) {
msg_problem("Snapshots table misaligned\n");
ret++;
} else {
msg_ok("Snapshots table OK, cluster index %"PRId64"\n",
header->snapshots_offset);
}
} else {
msg_info("No snapshots or snapshots table.\n");
}
error:
do_summary("Header", rc, ret);
return rc ? rc : ret;
}
/**
* print_header_v3: Print the header info to a stream in a readable format.
* @qf: qcow2 file object with a parsed header to print.
* @stream: Where to print.
*/
void print_header_v3(qfile *qf)
{
struct qheader3 *buff;
if (!qf || !qf->header || qf->header->version != 3) {
return;
}
buff = (struct qheader3 *)qf->header;
h1("Header (v3)");
mprintf(M_HEADER_DATA,
"incompatible_features: 0x%"PRIx64"\n"
"compatible_features: 0x%"PRIx64"\n"
"autoclear_features: 0x%"PRIx64"\n"
"refcount_order: %d\n"
"header_length: %d\n",
buff->incompatible_features,
buff->compatible_features,
buff->autoclear_features,
buff->refcount_order,
buff->header_length);
}
/**
* analyze_header_v3: check header metadata for issues.
* @qf: qcow2 file with parsed header to analyze.
* @return: -EINVAL if the qfile is absent, header was not parsed,
* or if the header version was not 3.
* -ENOTSUP if the refcount width is not 4.
* 0 if there are no issues found,
* The number of issues found otherwise.
*/
int analyze_header_v3(qfile *qf)
{
int ret = 0;
struct qheader3 *header;
if (!qf || !qf->header || (qf->header->version != 3)) {
return -EINVAL;
}
header = (struct qheader3 *)qf->header;
if (header->refcount_order != 4) {
msg_error("refcnt tool can't cope with refcount_bits != 4\n");
return -ENOTSUP;
}
if (header->header_length != sizeof(struct qheader3)) {
msg_problem("header_length (%d) is not what we think it is (%zu)\n",
header->header_length,
sizeof(struct qheader3));
ret++;
}
do_summary("Header (v3)", 0, ret);
return ret;
}
/******************************************************************************/
/* Refcount Parsing & Analysis */
/******************************************************************************/
/**
* parse_refcount_table: Read the reference count table into memory.
* @qf: The qcow2 file to obtain the refcount table of.
* @return: 0 on success, -ERRNO on critical failure.
* Does not perform soft analysis.
*/
int parse_refcount_table(qfile *qf)
{
int rc, i;
struct qheader *header;
if (!qf || !qf->header) {
return -EINVAL;
}
header = qf->header;
/* refcount_table_size is the total number of refcount block pointers we can
* store in the reference count table.
* refcount_table_entries is the total number of refcount block pointers we
* expect to see given the length of the host file.
*/
qf->refcount_table_size = (header->refcount_table_clusters * \
qf->cluster_size) / sizeof(uint64_t);
qf->refcount_table_entries = DIV_ROUND_UP(qf->host_clusters,
qf->refcount_block_entries);
rc = fseek(qf->fh, header->refcount_table_offset, SEEK_SET);
if (rc) {
rc = -errno;
perrorf("Couldn't seek to refcount table");
return rc;
}
qf->refcount_table = (uint64_t *)malloc(sizeof(*qf->refcount_table) *
MAX(qf->refcount_table_size,
qf->refcount_table_entries));
if (!qf->refcount_table) {
rc = -errno;
perrorf("Couldn't allocate space for reference count table");
return rc;
}
rc = fread_errno(qf->refcount_table, sizeof(*qf->refcount_table),
qf->refcount_table_size, qf->fh);
if (rc != qf->refcount_table_size) {
rc = -errno;
perrorf("Couldn't read refcount table");
free(qf->refcount_table);
qf->refcount_table = NULL;
return rc;
}
for (i = 0; i < qf->refcount_table_size; i++) {
if (qf->refcount_table[i]) {
qf->refcount_table[i] = be64toh(qf->refcount_table[i]);
}
}
return 0;
}
enum reftable_errors {
R_BEGIN,
R_MISALIGNED = R_BEGIN,
R_OUT_OF_BOUNDS,
R_BEYOND_EOF,
R_MAX
};
/* Refblock pointer %s */
const char *reftable_errors[R_MAX] = {
[R_MISALIGNED] = "is not aligned to a cluster boundary",
[R_OUT_OF_BOUNDS] = "is beyond EOF or overruns EOF",
[R_BEYOND_EOF] = "implies reference counts for clusters beyond EOF",
};
/**
* analyze_refcount_table: Investigate a parsed refcount table for potential
* issues, including pointer alignment, range overlap and refcount analysis.
* @qf: the qcow2 file whose refcount table to analyze