-
Notifications
You must be signed in to change notification settings - Fork 55.4k
/
Copy pathveristat.c
2464 lines (2147 loc) · 61.3 KB
/
veristat.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
// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
/* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
#define _GNU_SOURCE
#include <argp.h>
#include <libgen.h>
#include <string.h>
#include <stdlib.h>
#include <sched.h>
#include <pthread.h>
#include <dirent.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/sysinfo.h>
#include <sys/stat.h>
#include <bpf/libbpf.h>
#include <bpf/btf.h>
#include <bpf/bpf.h>
#include <libelf.h>
#include <gelf.h>
#include <float.h>
#include <math.h>
#include <limits.h>
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
#endif
#ifndef max
#define max(a, b) ((a) > (b) ? (a) : (b))
#endif
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
enum stat_id {
VERDICT,
DURATION,
TOTAL_INSNS,
TOTAL_STATES,
PEAK_STATES,
MAX_STATES_PER_INSN,
MARK_READ_MAX_LEN,
SIZE,
JITED_SIZE,
STACK,
PROG_TYPE,
ATTACH_TYPE,
FILE_NAME,
PROG_NAME,
ALL_STATS_CNT,
NUM_STATS_CNT = FILE_NAME - VERDICT,
};
/* In comparison mode each stat can specify up to four different values:
* - A side value;
* - B side value;
* - absolute diff value;
* - relative (percentage) diff value.
*
* When specifying stat specs in comparison mode, user can use one of the
* following variant suffixes to specify which exact variant should be used for
* ordering or filtering:
* - `_a` for A side value;
* - `_b` for B side value;
* - `_diff` for absolute diff value;
* - `_pct` for relative (percentage) diff value.
*
* If no variant suffix is provided, then `_b` (control data) is assumed.
*
* As an example, let's say instructions stat has the following output:
*
* Insns (A) Insns (B) Insns (DIFF)
* --------- --------- --------------
* 21547 20920 -627 (-2.91%)
*
* Then:
* - 21547 is A side value (insns_a);
* - 20920 is B side value (insns_b);
* - -627 is absolute diff value (insns_diff);
* - -2.91% is relative diff value (insns_pct).
*
* For verdict there is no verdict_pct variant.
* For file and program name, _a and _b variants are equivalent and there are
* no _diff or _pct variants.
*/
enum stat_variant {
VARIANT_A,
VARIANT_B,
VARIANT_DIFF,
VARIANT_PCT,
};
struct verif_stats {
char *file_name;
char *prog_name;
long stats[NUM_STATS_CNT];
};
/* joined comparison mode stats */
struct verif_stats_join {
char *file_name;
char *prog_name;
const struct verif_stats *stats_a;
const struct verif_stats *stats_b;
};
struct stat_specs {
int spec_cnt;
enum stat_id ids[ALL_STATS_CNT];
enum stat_variant variants[ALL_STATS_CNT];
bool asc[ALL_STATS_CNT];
bool abs[ALL_STATS_CNT];
int lens[ALL_STATS_CNT * 3]; /* 3x for comparison mode */
};
enum resfmt {
RESFMT_TABLE,
RESFMT_TABLE_CALCLEN, /* fake format to pre-calculate table's column widths */
RESFMT_CSV,
};
enum filter_kind {
FILTER_NAME,
FILTER_STAT,
};
enum operator_kind {
OP_EQ, /* == or = */
OP_NEQ, /* != or <> */
OP_LT, /* < */
OP_LE, /* <= */
OP_GT, /* > */
OP_GE, /* >= */
};
struct filter {
enum filter_kind kind;
/* FILTER_NAME */
char *any_glob;
char *file_glob;
char *prog_glob;
/* FILTER_STAT */
enum operator_kind op;
int stat_id;
enum stat_variant stat_var;
long value;
bool abs;
};
static struct env {
char **filenames;
int filename_cnt;
bool verbose;
bool debug;
bool quiet;
bool force_checkpoints;
bool force_reg_invariants;
enum resfmt out_fmt;
bool show_version;
bool comparison_mode;
bool replay_mode;
int top_n;
int log_level;
int log_size;
bool log_fixed;
struct verif_stats *prog_stats;
int prog_stat_cnt;
/* baseline_stats is allocated and used only in comparison mode */
struct verif_stats *baseline_stats;
int baseline_stat_cnt;
struct verif_stats_join *join_stats;
int join_stat_cnt;
struct stat_specs output_spec;
struct stat_specs sort_spec;
struct filter *allow_filters;
struct filter *deny_filters;
int allow_filter_cnt;
int deny_filter_cnt;
int files_processed;
int files_skipped;
int progs_processed;
int progs_skipped;
int top_src_lines;
} env;
static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
{
if (!env.verbose)
return 0;
if (level == LIBBPF_DEBUG && !env.debug)
return 0;
return vfprintf(stderr, format, args);
}
#ifndef VERISTAT_VERSION
#define VERISTAT_VERSION "<kernel>"
#endif
const char *argp_program_version = "veristat v" VERISTAT_VERSION;
const char *argp_program_bug_address = "<bpf@vger.kernel.org>";
const char argp_program_doc[] =
"veristat BPF verifier stats collection and comparison tool.\n"
"\n"
"USAGE: veristat <obj-file> [<obj-file>...]\n"
" OR: veristat -C <baseline.csv> <comparison.csv>\n"
" OR: veristat -R <results.csv>\n"
" OR: veristat -vl2 <to_analyze.bpf.o>\n";
enum {
OPT_LOG_FIXED = 1000,
OPT_LOG_SIZE = 1001,
};
static const struct argp_option opts[] = {
{ NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
{ "version", 'V', NULL, 0, "Print version" },
{ "verbose", 'v', NULL, 0, "Verbose mode" },
{ "debug", 'd', NULL, 0, "Debug mode (turns on libbpf debug logging)" },
{ "log-level", 'l', "LEVEL", 0, "Verifier log level (default 0 for normal mode, 1 for verbose mode, 2 for full verification log)" },
{ "log-fixed", OPT_LOG_FIXED, NULL, 0, "Disable verifier log rotation" },
{ "log-size", OPT_LOG_SIZE, "BYTES", 0, "Customize verifier log size (default to 16MB)" },
{ "top-n", 'n', "N", 0, "Emit only up to first N results." },
{ "quiet", 'q', NULL, 0, "Quiet mode" },
{ "emit", 'e', "SPEC", 0, "Specify stats to be emitted" },
{ "sort", 's', "SPEC", 0, "Specify sort order" },
{ "output-format", 'o', "FMT", 0, "Result output format (table, csv), default is table." },
{ "compare", 'C', NULL, 0, "Comparison mode" },
{ "replay", 'R', NULL, 0, "Replay mode" },
{ "filter", 'f', "FILTER", 0, "Filter expressions (or @filename for file with expressions)." },
{ "test-states", 't', NULL, 0,
"Force frequent BPF verifier state checkpointing (set BPF_F_TEST_STATE_FREQ program flag)" },
{ "test-reg-invariants", 'r', NULL, 0,
"Force BPF verifier failure on register invariant violation (BPF_F_TEST_REG_INVARIANTS program flag)" },
{ "top-src-lines", 'S', "N", 0, "Emit N most frequent source code lines" },
{},
};
static int parse_stats(const char *stats_str, struct stat_specs *specs);
static int append_filter(struct filter **filters, int *cnt, const char *str);
static int append_filter_file(const char *path);
static error_t parse_arg(int key, char *arg, struct argp_state *state)
{
void *tmp;
int err;
switch (key) {
case 'h':
argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
break;
case 'V':
env.show_version = true;
break;
case 'v':
env.verbose = true;
break;
case 'd':
env.debug = true;
env.verbose = true;
break;
case 'q':
env.quiet = true;
break;
case 'e':
err = parse_stats(arg, &env.output_spec);
if (err)
return err;
break;
case 's':
err = parse_stats(arg, &env.sort_spec);
if (err)
return err;
break;
case 'o':
if (strcmp(arg, "table") == 0) {
env.out_fmt = RESFMT_TABLE;
} else if (strcmp(arg, "csv") == 0) {
env.out_fmt = RESFMT_CSV;
} else {
fprintf(stderr, "Unrecognized output format '%s'\n", arg);
return -EINVAL;
}
break;
case 'l':
errno = 0;
env.log_level = strtol(arg, NULL, 10);
if (errno) {
fprintf(stderr, "invalid log level: %s\n", arg);
argp_usage(state);
}
break;
case OPT_LOG_FIXED:
env.log_fixed = true;
break;
case OPT_LOG_SIZE:
errno = 0;
env.log_size = strtol(arg, NULL, 10);
if (errno) {
fprintf(stderr, "invalid log size: %s\n", arg);
argp_usage(state);
}
break;
case 't':
env.force_checkpoints = true;
break;
case 'r':
env.force_reg_invariants = true;
break;
case 'n':
errno = 0;
env.top_n = strtol(arg, NULL, 10);
if (errno) {
fprintf(stderr, "invalid top N specifier: %s\n", arg);
argp_usage(state);
}
case 'C':
env.comparison_mode = true;
break;
case 'R':
env.replay_mode = true;
break;
case 'f':
if (arg[0] == '@')
err = append_filter_file(arg + 1);
else if (arg[0] == '!')
err = append_filter(&env.deny_filters, &env.deny_filter_cnt, arg + 1);
else
err = append_filter(&env.allow_filters, &env.allow_filter_cnt, arg);
if (err) {
fprintf(stderr, "Failed to collect program filter expressions: %d\n", err);
return err;
}
break;
case 'S':
errno = 0;
env.top_src_lines = strtol(arg, NULL, 10);
if (errno) {
fprintf(stderr, "invalid top lines N specifier: %s\n", arg);
argp_usage(state);
}
break;
case ARGP_KEY_ARG:
tmp = realloc(env.filenames, (env.filename_cnt + 1) * sizeof(*env.filenames));
if (!tmp)
return -ENOMEM;
env.filenames = tmp;
env.filenames[env.filename_cnt] = strdup(arg);
if (!env.filenames[env.filename_cnt])
return -ENOMEM;
env.filename_cnt++;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static const struct argp argp = {
.options = opts,
.parser = parse_arg,
.doc = argp_program_doc,
};
/* Adapted from perf/util/string.c */
static bool glob_matches(const char *str, const char *pat)
{
while (*str && *pat && *pat != '*') {
if (*str != *pat)
return false;
str++;
pat++;
}
/* Check wild card */
if (*pat == '*') {
while (*pat == '*')
pat++;
if (!*pat) /* Tail wild card matches all */
return true;
while (*str)
if (glob_matches(str++, pat))
return true;
}
return !*str && !*pat;
}
static bool is_bpf_obj_file(const char *path) {
Elf64_Ehdr *ehdr;
int fd, err = -EINVAL;
Elf *elf = NULL;
fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return true; /* we'll fail later and propagate error */
/* ensure libelf is initialized */
(void)elf_version(EV_CURRENT);
elf = elf_begin(fd, ELF_C_READ, NULL);
if (!elf)
goto cleanup;
if (elf_kind(elf) != ELF_K_ELF || gelf_getclass(elf) != ELFCLASS64)
goto cleanup;
ehdr = elf64_getehdr(elf);
/* Old LLVM set e_machine to EM_NONE */
if (!ehdr || ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF))
goto cleanup;
err = 0;
cleanup:
if (elf)
elf_end(elf);
close(fd);
return err == 0;
}
static bool should_process_file_prog(const char *filename, const char *prog_name)
{
struct filter *f;
int i, allow_cnt = 0;
for (i = 0; i < env.deny_filter_cnt; i++) {
f = &env.deny_filters[i];
if (f->kind != FILTER_NAME)
continue;
if (f->any_glob && glob_matches(filename, f->any_glob))
return false;
if (f->any_glob && prog_name && glob_matches(prog_name, f->any_glob))
return false;
if (f->file_glob && glob_matches(filename, f->file_glob))
return false;
if (f->prog_glob && prog_name && glob_matches(prog_name, f->prog_glob))
return false;
}
for (i = 0; i < env.allow_filter_cnt; i++) {
f = &env.allow_filters[i];
if (f->kind != FILTER_NAME)
continue;
allow_cnt++;
if (f->any_glob) {
if (glob_matches(filename, f->any_glob))
return true;
/* If we don't know program name yet, any_glob filter
* has to assume that current BPF object file might be
* relevant; we'll check again later on after opening
* BPF object file, at which point program name will
* be known finally.
*/
if (!prog_name || glob_matches(prog_name, f->any_glob))
return true;
} else {
if (f->file_glob && !glob_matches(filename, f->file_glob))
continue;
if (f->prog_glob && prog_name && !glob_matches(prog_name, f->prog_glob))
continue;
return true;
}
}
/* if there are no file/prog name allow filters, allow all progs,
* unless they are denied earlier explicitly
*/
return allow_cnt == 0;
}
static struct {
enum operator_kind op_kind;
const char *op_str;
} operators[] = {
/* Order of these definitions matter to avoid situations like '<'
* matching part of what is actually a '<>' operator. That is,
* substrings should go last.
*/
{ OP_EQ, "==" },
{ OP_NEQ, "!=" },
{ OP_NEQ, "<>" },
{ OP_LE, "<=" },
{ OP_LT, "<" },
{ OP_GE, ">=" },
{ OP_GT, ">" },
{ OP_EQ, "=" },
};
static bool parse_stat_id_var(const char *name, size_t len, int *id,
enum stat_variant *var, bool *is_abs);
static int append_filter(struct filter **filters, int *cnt, const char *str)
{
struct filter *f;
void *tmp;
const char *p;
int i;
tmp = realloc(*filters, (*cnt + 1) * sizeof(**filters));
if (!tmp)
return -ENOMEM;
*filters = tmp;
f = &(*filters)[*cnt];
memset(f, 0, sizeof(*f));
/* First, let's check if it's a stats filter of the following form:
* <stat><op><value, where:
* - <stat> is one of supported numerical stats (verdict is also
* considered numerical, failure == 0, success == 1);
* - <op> is comparison operator (see `operators` definitions);
* - <value> is an integer (or failure/success, or false/true as
* special aliases for 0 and 1, respectively).
* If the form doesn't match what user provided, we assume file/prog
* glob filter.
*/
for (i = 0; i < ARRAY_SIZE(operators); i++) {
enum stat_variant var;
int id;
long val;
const char *end = str;
const char *op_str;
bool is_abs;
op_str = operators[i].op_str;
p = strstr(str, op_str);
if (!p)
continue;
if (!parse_stat_id_var(str, p - str, &id, &var, &is_abs)) {
fprintf(stderr, "Unrecognized stat name in '%s'!\n", str);
return -EINVAL;
}
if (id >= FILE_NAME) {
fprintf(stderr, "Non-integer stat is specified in '%s'!\n", str);
return -EINVAL;
}
p += strlen(op_str);
if (strcasecmp(p, "true") == 0 ||
strcasecmp(p, "t") == 0 ||
strcasecmp(p, "success") == 0 ||
strcasecmp(p, "succ") == 0 ||
strcasecmp(p, "s") == 0 ||
strcasecmp(p, "match") == 0 ||
strcasecmp(p, "m") == 0) {
val = 1;
} else if (strcasecmp(p, "false") == 0 ||
strcasecmp(p, "f") == 0 ||
strcasecmp(p, "failure") == 0 ||
strcasecmp(p, "fail") == 0 ||
strcasecmp(p, "mismatch") == 0 ||
strcasecmp(p, "mis") == 0) {
val = 0;
} else {
errno = 0;
val = strtol(p, (char **)&end, 10);
if (errno || end == p || *end != '\0' ) {
fprintf(stderr, "Invalid integer value in '%s'!\n", str);
return -EINVAL;
}
}
f->kind = FILTER_STAT;
f->stat_id = id;
f->stat_var = var;
f->op = operators[i].op_kind;
f->abs = true;
f->value = val;
*cnt += 1;
return 0;
}
/* File/prog filter can be specified either as '<glob>' or
* '<file-glob>/<prog-glob>'. In the former case <glob> is applied to
* both file and program names. This seems to be way more useful in
* practice. If user needs full control, they can use '/<prog-glob>'
* form to glob just program name, or '<file-glob>/' to glob only file
* name. But usually common <glob> seems to be the most useful and
* ergonomic way.
*/
f->kind = FILTER_NAME;
p = strchr(str, '/');
if (!p) {
f->any_glob = strdup(str);
if (!f->any_glob)
return -ENOMEM;
} else {
if (str != p) {
/* non-empty file glob */
f->file_glob = strndup(str, p - str);
if (!f->file_glob)
return -ENOMEM;
}
if (strlen(p + 1) > 0) {
/* non-empty prog glob */
f->prog_glob = strdup(p + 1);
if (!f->prog_glob) {
free(f->file_glob);
f->file_glob = NULL;
return -ENOMEM;
}
}
}
*cnt += 1;
return 0;
}
static int append_filter_file(const char *path)
{
char buf[1024];
FILE *f;
int err = 0;
f = fopen(path, "r");
if (!f) {
err = -errno;
fprintf(stderr, "Failed to open filters in '%s': %d\n", path, err);
return err;
}
while (fscanf(f, " %1023[^\n]\n", buf) == 1) {
/* lines starting with # are comments, skip them */
if (buf[0] == '\0' || buf[0] == '#')
continue;
/* lines starting with ! are negative match filters */
if (buf[0] == '!')
err = append_filter(&env.deny_filters, &env.deny_filter_cnt, buf + 1);
else
err = append_filter(&env.allow_filters, &env.allow_filter_cnt, buf);
if (err)
goto cleanup;
}
cleanup:
fclose(f);
return err;
}
static const struct stat_specs default_output_spec = {
.spec_cnt = 8,
.ids = {
FILE_NAME, PROG_NAME, VERDICT, DURATION,
TOTAL_INSNS, TOTAL_STATES, SIZE, JITED_SIZE
},
};
static const struct stat_specs default_csv_output_spec = {
.spec_cnt = 14,
.ids = {
FILE_NAME, PROG_NAME, VERDICT, DURATION,
TOTAL_INSNS, TOTAL_STATES, PEAK_STATES,
MAX_STATES_PER_INSN, MARK_READ_MAX_LEN,
SIZE, JITED_SIZE, PROG_TYPE, ATTACH_TYPE,
STACK,
},
};
static const struct stat_specs default_sort_spec = {
.spec_cnt = 2,
.ids = {
FILE_NAME, PROG_NAME,
},
.asc = { true, true, },
};
/* sorting for comparison mode to join two data sets */
static const struct stat_specs join_sort_spec = {
.spec_cnt = 2,
.ids = {
FILE_NAME, PROG_NAME,
},
.asc = { true, true, },
};
static struct stat_def {
const char *header;
const char *names[4];
bool asc_by_default;
bool left_aligned;
} stat_defs[] = {
[FILE_NAME] = { "File", {"file_name", "filename", "file"}, true /* asc */, true /* left */ },
[PROG_NAME] = { "Program", {"prog_name", "progname", "prog"}, true /* asc */, true /* left */ },
[VERDICT] = { "Verdict", {"verdict"}, true /* asc: failure, success */, true /* left */ },
[DURATION] = { "Duration (us)", {"duration", "dur"}, },
[TOTAL_INSNS] = { "Insns", {"total_insns", "insns"}, },
[TOTAL_STATES] = { "States", {"total_states", "states"}, },
[PEAK_STATES] = { "Peak states", {"peak_states"}, },
[MAX_STATES_PER_INSN] = { "Max states per insn", {"max_states_per_insn"}, },
[MARK_READ_MAX_LEN] = { "Max mark read length", {"max_mark_read_len", "mark_read"}, },
[SIZE] = { "Program size", {"prog_size"}, },
[JITED_SIZE] = { "Jited size", {"prog_size_jited"}, },
[STACK] = {"Stack depth", {"stack_depth", "stack"}, },
[PROG_TYPE] = { "Program type", {"prog_type"}, },
[ATTACH_TYPE] = { "Attach type", {"attach_type", }, },
};
static bool parse_stat_id_var(const char *name, size_t len, int *id,
enum stat_variant *var, bool *is_abs)
{
static const char *var_sfxs[] = {
[VARIANT_A] = "_a",
[VARIANT_B] = "_b",
[VARIANT_DIFF] = "_diff",
[VARIANT_PCT] = "_pct",
};
int i, j, k;
/* |<stat>| means we take absolute value of given stat */
*is_abs = false;
if (len > 2 && name[0] == '|' && name[len - 1] == '|') {
*is_abs = true;
name += 1;
len -= 2;
}
for (i = 0; i < ARRAY_SIZE(stat_defs); i++) {
struct stat_def *def = &stat_defs[i];
size_t alias_len, sfx_len;
const char *alias;
for (j = 0; j < ARRAY_SIZE(stat_defs[i].names); j++) {
alias = def->names[j];
if (!alias)
continue;
alias_len = strlen(alias);
if (strncmp(name, alias, alias_len) != 0)
continue;
if (alias_len == len) {
/* If no variant suffix is specified, we
* assume control group (just in case we are
* in comparison mode. Variant is ignored in
* non-comparison mode.
*/
*var = VARIANT_B;
*id = i;
return true;
}
for (k = 0; k < ARRAY_SIZE(var_sfxs); k++) {
sfx_len = strlen(var_sfxs[k]);
if (alias_len + sfx_len != len)
continue;
if (strncmp(name + alias_len, var_sfxs[k], sfx_len) == 0) {
*var = (enum stat_variant)k;
*id = i;
return true;
}
}
}
}
return false;
}
static bool is_asc_sym(char c)
{
return c == '^';
}
static bool is_desc_sym(char c)
{
return c == 'v' || c == 'V' || c == '.' || c == '!' || c == '_';
}
static int parse_stat(const char *stat_name, struct stat_specs *specs)
{
int id;
bool has_order = false, is_asc = false, is_abs = false;
size_t len = strlen(stat_name);
enum stat_variant var;
if (specs->spec_cnt >= ARRAY_SIZE(specs->ids)) {
fprintf(stderr, "Can't specify more than %zd stats\n", ARRAY_SIZE(specs->ids));
return -E2BIG;
}
if (len > 1 && (is_asc_sym(stat_name[len - 1]) || is_desc_sym(stat_name[len - 1]))) {
has_order = true;
is_asc = is_asc_sym(stat_name[len - 1]);
len -= 1;
}
if (!parse_stat_id_var(stat_name, len, &id, &var, &is_abs)) {
fprintf(stderr, "Unrecognized stat name '%s'\n", stat_name);
return -ESRCH;
}
specs->ids[specs->spec_cnt] = id;
specs->variants[specs->spec_cnt] = var;
specs->asc[specs->spec_cnt] = has_order ? is_asc : stat_defs[id].asc_by_default;
specs->abs[specs->spec_cnt] = is_abs;
specs->spec_cnt++;
return 0;
}
static int parse_stats(const char *stats_str, struct stat_specs *specs)
{
char *input, *state = NULL, *next;
int err, cnt = 0;
input = strdup(stats_str);
if (!input)
return -ENOMEM;
while ((next = strtok_r(cnt++ ? NULL : input, ",", &state))) {
err = parse_stat(next, specs);
if (err) {
free(input);
return err;
}
}
free(input);
return 0;
}
static void free_verif_stats(struct verif_stats *stats, size_t stat_cnt)
{
int i;
if (!stats)
return;
for (i = 0; i < stat_cnt; i++) {
free(stats[i].file_name);
free(stats[i].prog_name);
}
free(stats);
}
static char verif_log_buf[64 * 1024];
#define MAX_PARSED_LOG_LINES 100
static int parse_verif_log(char * const buf, size_t buf_sz, struct verif_stats *s)
{
const char *cur;
int pos, lines, sub_stack, cnt = 0;
char *state = NULL, *token, stack[512];
buf[buf_sz - 1] = '\0';
for (pos = strlen(buf) - 1, lines = 0; pos >= 0 && lines < MAX_PARSED_LOG_LINES; lines++) {
/* find previous endline or otherwise take the start of log buf */
for (cur = &buf[pos]; cur > buf && cur[0] != '\n'; cur--, pos--) {
}
/* next time start from end of previous line (or pos goes to <0) */
pos--;
/* if we found endline, point right after endline symbol;
* otherwise, stay at the beginning of log buf
*/
if (cur[0] == '\n')
cur++;
if (1 == sscanf(cur, "verification time %ld usec\n", &s->stats[DURATION]))
continue;
if (5 == sscanf(cur, "processed %ld insns (limit %*d) max_states_per_insn %ld total_states %ld peak_states %ld mark_read %ld",
&s->stats[TOTAL_INSNS],
&s->stats[MAX_STATES_PER_INSN],
&s->stats[TOTAL_STATES],
&s->stats[PEAK_STATES],
&s->stats[MARK_READ_MAX_LEN]))
continue;
if (1 == sscanf(cur, "stack depth %511s", stack))
continue;
}
while ((token = strtok_r(cnt++ ? NULL : stack, "+", &state))) {
if (sscanf(token, "%d", &sub_stack) == 0)
break;
s->stats[STACK] += sub_stack;
}
return 0;
}
struct line_cnt {
char *line;
int cnt;
};
static int str_cmp(const void *a, const void *b)
{
const char **str1 = (const char **)a;
const char **str2 = (const char **)b;
return strcmp(*str1, *str2);
}
static int line_cnt_cmp(const void *a, const void *b)
{
const struct line_cnt *a_cnt = (const struct line_cnt *)a;
const struct line_cnt *b_cnt = (const struct line_cnt *)b;
if (a_cnt->cnt != b_cnt->cnt)
return a_cnt->cnt > b_cnt->cnt ? -1 : 1;
return strcmp(a_cnt->line, b_cnt->line);
}
static int print_top_src_lines(char * const buf, size_t buf_sz, const char *prog_name)
{
int lines_cap = 0;
int lines_size = 0;
char **lines = NULL;
char *line = NULL;
char *state;
struct line_cnt *freq = NULL;
struct line_cnt *cur;
int unique_lines;
int err = 0;
int i;
while ((line = strtok_r(line ? NULL : buf, "\n", &state))) {
if (strncmp(line, "; ", 2) != 0)
continue;
line += 2;
if (lines_size == lines_cap) {
char **tmp;
lines_cap = max(16, lines_cap * 2);
tmp = realloc(lines, lines_cap * sizeof(*tmp));
if (!tmp) {
err = -ENOMEM;
goto cleanup;
}
lines = tmp;
}
lines[lines_size] = line;
lines_size++;
}
if (lines_size == 0)
goto cleanup;
qsort(lines, lines_size, sizeof(*lines), str_cmp);
freq = calloc(lines_size, sizeof(*freq));
if (!freq) {
err = -ENOMEM;
goto cleanup;
}
cur = freq;
cur->line = lines[0];
cur->cnt = 1;
for (i = 1; i < lines_size; ++i) {
if (strcmp(lines[i], cur->line) != 0) {
cur++;
cur->line = lines[i];
cur->cnt = 0;
}
cur->cnt++;
}
unique_lines = cur - freq + 1;
qsort(freq, unique_lines, sizeof(struct line_cnt), line_cnt_cmp);
printf("Top source lines (%s):\n", prog_name);
for (i = 0; i < min(unique_lines, env.top_src_lines); ++i) {
const char *src_code = freq[i].line;
const char *src_line = NULL;
char *split = strrchr(freq[i].line, '@');
if (split) {
src_line = split + 1;
while (*src_line && isspace(*src_line))
src_line++;
while (split > src_code && isspace(*split))
split--;
*split = '\0';
}
if (src_line)
printf("%5d: (%s)\t%s\n", freq[i].cnt, src_line, src_code);
else
printf("%5d: %s\n", freq[i].cnt, src_code);