-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkcov-gui.cpp
More file actions
1745 lines (1618 loc) · 62.2 KB
/
Copy pathkcov-gui.cpp
File metadata and controls
1745 lines (1618 loc) · 62.2 KB
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
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kcov-common.h"
#include "basic.h"
#include <capstone/x86.h>
#include <pthread.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <linux/vm_sockets.h>
#include <dwarf.h>
#include <elfutils/libdw.h>
#include <capstone/capstone.h>
#include <algorithm>
#include <atomic>
#include <cstring>
#include <fstream>
#include <map>
#include <memory>
#include <variant>
#include <unordered_map>
#include <unordered_set>
#include "common.h"
// thread code already needs it for glfwPostEmptyEvent()
#define GL_SILENCE_DEPRECATION
#include <GLFW/glfw3.h>
//#include "easy_ipc.h"
struct DIStack {
std::vector<struct kcov_di_stack_elem> thread_distacks[2];
size_t thread_indices[2] = {SIZE_MAX,SIZE_MAX};
void swap() {
if (thread_distacks[1].size() == 0)
return;
std::swap(thread_distacks[0], thread_distacks[1]);
std::swap(thread_indices[0], thread_indices[1]);
}
};
struct DIStacksState {
std::vector<DIStack> distacks;
std::vector<struct ipc_distack> as_ipc_distacks() {
std::vector<struct ipc_distack> res;
unsigned int flagidx = 0;
for (DIStack& dis : distacks) {
if (dis.thread_distacks[0].size() >= 32 || dis.thread_distacks[1].size() >= 32)
errx(1, "distack too big");
if (dis.thread_distacks[1].size() == 0)
continue;
for (int i=0; i<2; i++) {
struct ipc_distack ipc_dis = {
.num_elems = (int)dis.thread_distacks[i].size(),
.type = (i==0) ? DI_STACK_WAKE_POST : DI_STACK_WAIT,
.flagidx = flagidx,
.thread_idx = (unsigned int)dis.thread_indices[i]
};
memcpy(ipc_dis.elems, dis.thread_distacks[i].data(), dis.thread_distacks[i].size() * sizeof(struct kcov_di_stack_elem));
assert(ipc_dis.num_elems < 32);
res.push_back(ipc_dis);
}
flagidx++;
}
return res;
}
void handle_addition(size_t thread_idx, std::vector<struct kcov_di_stack_elem> stack_elems) {
if (distacks.size() == 0 ||
(distacks[distacks.size()-1].thread_distacks[1].size() != 0)) {
distacks.emplace_back();
}
DIStack &dis = distacks[distacks.size()-1];
size_t part = (dis.thread_distacks[0].size() == 0) ? 0 : 1;
if (part == 1 && thread_idx == dis.thread_indices[0])
return;
dis.thread_distacks[part] = stack_elems;
dis.thread_indices[part] = thread_idx;
}
};
static DIStacksState distate;
static int listen_sock;
static std::atomic<int> incoming_state;
static std::atomic<std::shared_ptr<struct KcovTraceSet>> current_trace_set;
static std::atomic<std::shared_ptr<struct DIStacksState>> current_distate = std::make_shared<DIStacksState>();
static void listen_init(void) {
listen_sock = SYSCHK(socket(AF_VSOCK, SOCK_STREAM, 0));
struct sockaddr_vm listen_addr = {
.svm_family = AF_VSOCK,
.svm_port = 0x4b434f56 /* "KCOV" */,
.svm_cid = VMADDR_CID_ANY
};
SYSCHK(bind(listen_sock, (struct sockaddr *)&listen_addr, sizeof(listen_addr)));
SYSCHK(listen(listen_sock, 16));
}
static int recv_full(int sockfd, void *buf, size_t size) {
size_t done = 0;
while (done < size) {
// std::min() hack because vsock recv is fragile and can fail with ENOMEM :/
ssize_t res = recv(sockfd, (char *)buf+done, std::min((size_t)4096,size-done), MSG_WAITALL);
if (res == 0) {
errno = EPROTO;
return -1;
}
if (res < 0)
return res;
done += (size_t)res;
}
return 0;
}
static int send_full(int sockfd, void *buf, size_t size) {
size_t done = 0;
while (done < size) {
// std::min() hack because vsock send is fragile and can fail with ENOMEM :/
ssize_t res = send(sockfd, (char *)buf+done, std::min((size_t)4096,size-done), MSG_WAITALL);
if (res == 0) {
errno = EPROTO;
return -1;
}
if (res < 0)
return res;
done += (size_t)res;
}
return 0;
}
static void *listen_threadfn(void *dummy) {
while (1) {
int sock = SYSCHK(accept(listen_sock, NULL, NULL));
incoming_state = 1;
glfwPostEmptyEvent();
unsigned int num_threads;
continue_reading:
if (recv_full(sock, &num_threads, sizeof(num_threads))) {
perror("receive num of threads");
goto abort;
}
if (num_threads == 0x12345678) {
std::shared_ptr<struct DIStacksState> distate = current_distate;
auto stacks = distate->as_ipc_distacks();
unsigned int num_distacks = stacks.size();
if (send_full(sock, &num_distacks, sizeof(num_distacks))) {
perror("send");
goto abort;
}
if (num_distacks > 0) {
if (send_full(sock, stacks.data(), sizeof(struct ipc_distack) * num_distacks)) {
perror("send2");
goto abort;
}
}
goto continue_reading;
}
if (num_threads == 0) {
perror("received invalid num of threads");
goto abort;
}
{
std::shared_ptr<KcovTraceSet> trace_set(new KcovTraceSet);
for (unsigned int i=0; i<num_threads; i++) {
unsigned long elem_count;
if (recv_full(sock, &elem_count, sizeof(elem_count))) {
perror("receive size");
goto abort;
}
printf("received count: %lu\n", elem_count);
KcovTrace *trace = &trace_set->traces.emplace_back(i);
trace->data.resize(elem_count);
if (recv_full(sock, trace->data.data(), elem_count*sizeof(unsigned long))) {
perror("receive data");
goto abort;
}
}
// commit
current_trace_set = trace_set;
}
abort:
close(sock);
incoming_state = 0;
glfwPostEmptyEvent();
}
}
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
static void glfw_error_callback(int error, const char* description) {
fprintf(stderr, "GLFW Error %d: %s\n", error, description);
}
struct VARangeSet : RangeSet {
void sub_inlines_inside(Dwarf_Die *die) {
Dwarf_Die child;
if (dwarf_child(die, &child) == 0) {
do {
if (dwarf_tag(&child) == DW_TAG_inlined_subroutine) {
VARangeSet child_ranges(&child, false);
sub(child_ranges);
} else {
sub_inlines_inside(&child);
}
} while (dwarf_siblingof(&child, &child) == 0);
}
}
explicit VARangeSet(Dwarf_Die *die, bool exclude_inline) {
ptrdiff_t offset = 0;
Dwarf_Addr base, start, end;
while (true) {
offset = dwarf_ranges(die, offset, &base, &start, &end);
if (offset < 0)
errx(1, "dwarf_ranges() error");
if (offset == 0)
break;
if (start != end)
add(Range(start, end-1));
}
if (exclude_inline)
sub_inlines_inside(die);
}
VARangeSet() {}
};
static struct Dwarf *vmlinux_dwarf;
static int vmlinux_fd;
static unsigned long FUNC__sanitizer_cov_trace_pc, FUNC__sanitizer_cov_trace_pc_entry;
struct LineCoveragePoint {
LineCoveragePoint(int lineno) : lineno(lineno) {}
int lineno;
unsigned long count = 0;
};
class SourceLoc {
public:
SourceLoc(const char *file, int lineno) : file(file), lineno(lineno) {}
SourceLoc(Dwarf_Line* line) {
dwarf_lineno(line, &lineno);
file = dwarf_linesrc(line, NULL, NULL);
}
const char *file;
int lineno;
};
class BasicBlock {
public:
BasicBlock(Range range) : range(range) {}
Range range;
//bool entrypoint = false;
std::vector<BasicBlock*> predecessors;
std::vector<BasicBlock*> targets;
bool direct_coverage = false;
std::unordered_set<unsigned long> kcov_ret_ips;
std::vector<std::pair<Range, SourceLoc>> source_locs;
};
class CFG {
public:
std::set<Range> ranges;
void split_at(unsigned long addr) {
auto range_node = ranges.extract(Range(addr));
if (range_node.empty()) {
// can legitimately happen if addr is at end of function address range
return;
}
Range orig = range_node.value();
if (orig.start == addr) {
ranges.insert(orig);
return;
}
Range part2 = Range(addr, orig.end);
orig.end = addr-1;
ranges.insert(orig);
ranges.insert(part2);
}
std::map<Range, BasicBlock> bbs;
void make_bbs(void) {
for (Range r : ranges)
bbs.emplace(r, BasicBlock(r));
}
};
struct FunctionInfo {
struct FunctionInfo *machine_func;
unsigned long entry_addr;
bool is_inline = false;
struct {
const char *file = nullptr;
Dwarf_Word line = 0;
Dwarf_Word column = 0;
} inline_caller;
VARangeSet ip_ranges;
VARangeSet ip_ranges_own;
Dwarf_Die cudie = {};
Dwarf_Die prog_die = {};
std::vector<struct FunctionInfo> inline_children;
std::map<Range, struct FunctionInfo *> children_by_va;
std::unordered_map<unsigned long, std::vector<LineCoveragePoint>> line_cov_by_va;
struct FunctionInfo *child_by_va(unsigned long va) {
auto it = children_by_va.find(Range(va, va));
if (it == children_by_va.end())
return nullptr;
return it->second;
}
std::string name;
bool has_srcinfo = false;
const char *filename;
int min_line = INT_MAX;
int max_line = 0;
std::optional<std::vector<std::string>> lines;
std::vector<std::vector<size_t>> line_posmaps;
std::vector<std::string>& get_lines() {
if (!lines) {
if (min_line == INT_MAX) {
min_line = 1;
max_line = 1;
}
lines.emplace();
std::string full_filename = filename;
if (full_filename.size() && full_filename[0] != '/') {
Dwarf_Attribute attrmem;
const char *comp_dir = dwarf_formstring(dwarf_attr(&cudie, DW_AT_comp_dir, &attrmem));
if (comp_dir) {
full_filename = std::string(comp_dir) + "/" + full_filename;
}
}
std::ifstream file(full_filename);
if (file.is_open()) {
for (int i=1; i<min_line; i++) {
std::string dummy;
std::getline(file, dummy);
}
for (int i=min_line; i<=max_line; i++) {
std::string line;
std::getline(file, line);
std::string line_expanded;
std::vector<size_t> posmap;
for (size_t i = 0; i < line.size(); i++) {
posmap.push_back(line_expanded.size());
if (line[i] == '\t') {
line_expanded.append(" ");
} else {
line_expanded.push_back(line[i]);
}
}
lines->push_back(line_expanded);
line_posmaps.push_back(posmap);
}
}
}
return *lines;
}
int fixup_column_tabs(int lineno, int column) {
get_lines();
if (lineno < min_line || (size_t)lineno >= min_line + line_posmaps.size())
return 0;
if (column == 0)
return 0;
std::vector<size_t> &posmap = line_posmaps[lineno - min_line];
if ((size_t)column-1 >= posmap.size())
return 0;
return line_posmaps[lineno - min_line][column-1];
}
// per machine function
CFG cfg;
};
static std::unordered_map<unsigned long, struct FunctionInfo> func_by_addr;
struct SourcePoint {
bool valid = false;
const char *file; // irrelevant if valid==true
// following are only initialized if valid
int line;
int column_raw;
int column_fixedwidth;
SourcePoint(struct FunctionInfo *fi, unsigned long ip) {
Dwarf_Line *dl = dwarf_getsrc_die(&fi->cudie, ip);
file = dwarf_linesrc(dl, NULL, NULL);
if (!file || strcmp(file, fi->filename))
return;
dwarf_lineno(dl, &line);
dwarf_linecol(dl, &column_raw);
column_fixedwidth = fi->fixup_column_tabs(line, column_raw);
valid = true;
}
};
static std::optional<Dwarf_Die> funcdie_by_addr(Dwarf_Die *cudie, unsigned long addr) {
Dwarf_Die *scopes;
int num_scopes = dwarf_getscopes(cudie, addr, &scopes);
if (num_scopes < 0)
return std::nullopt;
if (num_scopes == 0)
return std::nullopt;
std::string funcname;
for (int i=num_scopes-1; i>=0; i--) {
int tag = dwarf_tag(scopes+i);
if (tag == DW_TAG_subprogram) {
Dwarf_Die retval = scopes[i];
free(scopes);
return retval;
}
}
free(scopes);
return std::nullopt;
}
static void populate_func_name(struct FunctionInfo *fi) {
Dwarf_Die *scopes;
int num_scopes = dwarf_getscopes_die(&fi->prog_die, &scopes);
if (num_scopes < 0) {
fi->name = "<getting scopes failed>";
return;
}
if (num_scopes == 0) {
fi->name = "<not in any scope>";
return;
}
std::string funcname;
for (int i=num_scopes-1; i>=0; i--) {
int tag = dwarf_tag(scopes+i);
if (tag == DW_TAG_compile_unit)
continue;
const char *name = dwarf_diename(scopes+i);
if (name != nullptr) {
if (funcname.size() != 0)
funcname.append("::");
funcname.append(name);
}
}
free(scopes);
fi->name = funcname;
}
// assumes that fi->inline_children is final
static void populate_children_by_va(struct FunctionInfo *fi) {
for (struct FunctionInfo &child : fi->inline_children) {
for (Range range : child.ip_ranges.ranges) {
assert(!fi->children_by_va.contains(range));
fi->children_by_va[range] = &child;
}
}
}
static void populate_func_with_dwarf(struct FunctionInfo *fi);
static void populate_func_inlines(struct FunctionInfo *fi, Dwarf_Die *die) {
Dwarf_Die child;
if (dwarf_child(die, &child) == 0) {
do {
if (dwarf_tag(&child) == DW_TAG_inlined_subroutine) {
//VARangeSet child_ranges(&child, false);
//sub(child_ranges);
struct FunctionInfo *child_fi = &fi->inline_children.emplace_back();
child_fi->machine_func = fi->machine_func;
child_fi->is_inline = true;
child_fi->cudie = fi->cudie;
child_fi->prog_die = child;
//populate_func_name(child_fi);
child_fi->name = dwarf_diename(&child) ?: "<unknown inline>";
child_fi->filename = dwarf_decl_file(&child) ?: "<?>";
populate_func_with_dwarf(child_fi);
fi->ip_ranges_own.sub(child_fi->ip_ranges);
} else {
populate_func_inlines(fi, &child);
}
} while (dwarf_siblingof(&child, &child) == 0);
}
}
static unsigned char *get_bytes(unsigned long addr, unsigned long num_bytes) {
Elf *elf = dwarf_getelf(vmlinux_dwarf);
for (Elf_Scn *scn = elf_nextscn(elf, nullptr); scn; scn = elf_nextscn(elf, scn)) {
Elf64_Shdr *shdr = elf64_getshdr(scn);
if (!(shdr->sh_flags & SHF_ALLOC))
continue;
if (shdr->sh_addr > addr)
continue;
size_t off_in_section = addr - shdr->sh_addr;
if (off_in_section > shdr->sh_size)
continue;
if (shdr->sh_size - off_in_section < num_bytes)
continue;
unsigned char *data = (unsigned char *)malloc(num_bytes);
if (!data)
err(1, "malloc data");
if (pread(vmlinux_fd, data, num_bytes, off_in_section + shdr->sh_offset) != (ssize_t)num_bytes)
errx(1, "vmlinux read");
return data;
}
errx(1, "unable to find section");
}
static void scan_machine_func_code(struct FunctionInfo *fi) {
if (!fi->filename)
return;
csh handle;
if (cs_open(CS_ARCH_X86, CS_MODE_64, &handle) != CS_ERR_OK)
errx(1, "cs_open");
cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON);
CFG cfg;
for (const Range& range : fi->ip_ranges.ranges)
cfg.ranges.insert(range);
std::vector<std::pair<unsigned long, unsigned long>> edges;
std::vector<unsigned long> kcov_cov_addrs;
for (const Range& range : fi->ip_ranges.ranges) {
unsigned char *insn_bytes = get_bytes(range.start, range.size());
cs_insn *insns;
ssize_t count = cs_disasm(handle, insn_bytes, range.size(), range.start, 0, &insns);
if (count > 0) {
for (ssize_t i = 0; i < count; i++) {
cs_insn *insn = &insns[i];
unsigned long insn_end = insn->address + insn->size;
if (cs_insn_group(handle, insn, X86_GRP_RET))
cfg.split_at(insn_end);
if (cs_insn_group(handle, insn, X86_GRP_BRANCH_RELATIVE) &&
!cs_insn_group(handle, insn, X86_GRP_CALL) &&
insn->detail->x86.op_count >= 1) {
cs_x86_op *op0 = &insn->detail->x86.operands[0];
if (op0->type == X86_OP_IMM) {
cfg.split_at(insn_end);
if (insn->id != X86_INS_JMP)
edges.push_back(std::make_pair((unsigned long)insn->address, insn_end));
unsigned long target = op0->imm;
if (fi->ip_ranges.has(target)) {
cfg.split_at(target);
edges.push_back(std::make_pair((unsigned long)insn->address, target));
//printf("jump 0x%lx -> 0x%lx\n", insn_end, target);
}
}
}
if (cs_insn_group(handle, insn, X86_GRP_CALL) && insn->detail->x86.op_count == 1) {
unsigned long ret_ip = insn->address + insn->size;
cs_x86_op *op = &insn->detail->x86.operands[0];
if (op->type == X86_OP_IMM &&
((unsigned long)op->imm == FUNC__sanitizer_cov_trace_pc ||
(unsigned long)op->imm == FUNC__sanitizer_cov_trace_pc_entry)) {
kcov_cov_addrs.push_back(ret_ip);
/*
Dwarf_Line *dl = dwarf_getsrc_die(&fi->cudie, insn->address);
const char *dl_file = dwarf_linesrc(dl, NULL, NULL);
int lineno;
dwarf_lineno(dl, &lineno);
if (dl_file && lineno != 0 && strcmp(dl_file, fi->filename) == 0)
fi->line_cov_by_va.emplace(ret_ip, lineno);
*/
}
}
}
cs_free(insns, count);
}
free(insn_bytes);
}
cfg.make_bbs();
//cfg.bbs.at(Range(fi->entry_addr)).entrypoint = true;
for (auto& edge: edges) {
//printf("EDGE: 0x%lx -> 0x%lx\n", edge.first, edge.second);
cfg.bbs.at(Range(edge.first)).targets.push_back(&cfg.bbs.at(Range(edge.second)));
}
for (auto &iter : cfg.bbs) {
BasicBlock *bb = &iter.second;
for (BasicBlock *successor : bb->targets) {
successor->predecessors.push_back(bb);
}
}
for (unsigned long addr : kcov_cov_addrs) {
cfg.bbs.at(Range(addr)).direct_coverage = true;
cfg.bbs.at(Range(addr)).kcov_ret_ips.insert(addr);
}
Dwarf_Lines *lines;
size_t nlines;
if (dwarf_getsrclines(&fi->cudie, &lines, &nlines))
return;
for (size_t i=0; i+1 < nlines; i++) {
Dwarf_Line *line = dwarf_onesrcline(lines, i);
Dwarf_Addr line_addr = 0;
dwarf_lineaddr(line, &line_addr);
if (!fi->ip_ranges.has(line_addr))
continue;
Dwarf_Addr next_line_addr;
dwarf_lineaddr(dwarf_onesrcline(lines, i+1), &next_line_addr);
if (line_addr == next_line_addr) {
/*
* This DWARF line record does not correspond to any machine code; this
* can happen, for example, because of barrier() calls.
*/
continue;
}
while (line_addr < next_line_addr) {
if (!fi->ip_ranges.has(line_addr))
break;
BasicBlock *bb = &cfg.bbs.at(Range(line_addr));
bb->source_locs.push_back(std::make_pair(Range(line_addr, std::min(next_line_addr-1, bb->range.end)), SourceLoc(line)));
line_addr = bb->range.end+1;
}
}
fi->cfg = std::move(cfg);
}
static void scan_func_code(struct FunctionInfo *fi) {
for (auto& bb_ : fi->machine_func->cfg.bbs) {
BasicBlock *bb = &bb_.second;
if (!bb->direct_coverage)
continue;
for (auto& locinfo : bb->source_locs) {
if (strcmp(locinfo.second.file, fi->filename))
continue;
if (fi->ip_ranges_own.ranges.count(locinfo.first)) {
for (unsigned long kcov_ret_ip : bb->kcov_ret_ips) {
fi->line_cov_by_va[kcov_ret_ip].push_back(LineCoveragePoint(locinfo.second.lineno));
}
}
}
}
}
static void populate_func_with_dwarf(struct FunctionInfo *fi) {
fi->ip_ranges_own = fi->ip_ranges = VARangeSet(&fi->prog_die, false);
const char *filename = dwarf_decl_file(&fi->prog_die);
if (filename)
fi->filename = filename;
if (fi->is_inline) {
do {
Dwarf_Files *files;
size_t nfiles;
if (dwarf_getsrcfiles(&fi->cudie, &files, &nfiles))
break;
Dwarf_Attribute attr_mem;
if (dwarf_formudata(dwarf_attr(&fi->prog_die, DW_AT_call_line, &attr_mem), &fi->inline_caller.line))
break;
if (dwarf_formudata(dwarf_attr(&fi->prog_die, DW_AT_call_column, &attr_mem), &fi->inline_caller.column))
break;
Dwarf_Word call_file_num;
if (dwarf_formudata(dwarf_attr(&fi->prog_die, DW_AT_call_file, &attr_mem), &call_file_num))
break;
fi->inline_caller.file = dwarf_filesrc(files, call_file_num, NULL, NULL);
} while (0);
}
if (!fi->is_inline)
scan_machine_func_code(fi);
populate_func_inlines(fi, &fi->prog_die);
populate_children_by_va(fi);
scan_func_code(fi);
}
static void ensure_func_srcinfo(struct FunctionInfo *fi) {
if (fi->has_srcinfo)
return;
fi->has_srcinfo = true;
{
int decl_line;
if (dwarf_decl_line(&fi->prog_die, &decl_line) == 0 && decl_line != 0) {
fi->min_line = fi->max_line = decl_line;
}
}
Dwarf_Lines *lines;
size_t nlines;
if (dwarf_getsrclines(&fi->cudie, &lines, &nlines))
return;
for (size_t i=0; i<nlines; i++) {
Dwarf_Line *line = dwarf_onesrcline(lines, i);
Dwarf_Addr line_addr = 0;
dwarf_lineaddr(line, &line_addr);
if (i < nlines+1) {
Dwarf_Addr next_line_addr;
dwarf_lineaddr(dwarf_onesrcline(lines, i+1), &next_line_addr);
if (line_addr == next_line_addr) {
/*
* This DWARF line record does not correspond to any machine code; this
* can happen, for example, because of barrier() calls.
*/
continue;
}
}
// can't use dwarf_linecontext() for checking whether this is an inline
// line, it relies on some weird NVIDIA CUDA extension
if (!fi->ip_ranges_own.has(line_addr))
continue;
// hack
if (strcmp(fi->filename, dwarf_linesrc(line, NULL, NULL))) {
fprintf(stderr, "skipping %s in %s\n", dwarf_linesrc(line, NULL, NULL), fi->name.c_str());
continue;
}
int lineno;
dwarf_lineno(line, &lineno);
/*
* 6.2.2 State Machine Registers:
* "Lines are numbered beginning at 1.
* The compiler may emit the value 0 in cases
* where an instruction cannot be attributed to any
* source line."
*/
if (lineno != 0) {
if (lineno < fi->min_line)
fi->min_line = lineno;
if (lineno > fi->max_line)
fi->max_line = lineno;
}
}
for (FunctionInfo& inline_child_fi : fi->inline_children) {
if (!inline_child_fi.inline_caller.file || strcmp(inline_child_fi.inline_caller.file, fi->filename))
continue;
if ((int)inline_child_fi.inline_caller.line > fi->max_line)
fi->max_line = inline_child_fi.inline_caller.line;
}
}
static struct FunctionInfo *vmlinux_funcinfo_by_entry_addr(unsigned long addr) {
if (func_by_addr.contains(addr))
return &func_by_addr[addr];
struct FunctionInfo *fi = &func_by_addr[addr];
fi->machine_func = fi;
fi->entry_addr = addr;
Dwarf_Die cudie;
if (dwarf_addrdie(vmlinux_dwarf, addr-1, &cudie) == NULL) {
fi->name = "<no CU>";
fprintf(stderr, "no CU for %lx\n", addr);
return fi;
}
fi->cudie = cudie;
printf("has die?\n");
std::optional<Dwarf_Die> funcdie = funcdie_by_addr(&cudie, addr-1);
if (!funcdie) {
printf("no die?\n");
fi->name = "<getting DIE failed>";
return fi;
}
fi->prog_die = *funcdie;
populate_func_name(fi);
printf("has cu?\n");
if (fi->prog_die.cu)
populate_func_with_dwarf(fi);
return fi;
}
static unsigned long get_die_address(Dwarf_Die *die) {
Dwarf_Attribute loc_attr;
if (dwarf_attr_integrate(die, DW_AT_location, &loc_attr) == NULL)
errx(1, "%s: no location attribute", __func__);
Dwarf_Op *loc_expr;
size_t loc_expr_len;
if (dwarf_getlocation(&loc_attr, &loc_expr, &loc_expr_len) != 0)
errx(1, "%s: getlocation failed", __func__);
if (loc_expr_len < 1)
errx(1, "%s: loc_expr_len < 1", __func__);
Dwarf_Attribute var_loc_attr_decoded;
if (dwarf_getlocation_attr(&loc_attr, loc_expr, &var_loc_attr_decoded))
errx(1, "%s: dwarf_getlocation_attr", __func__);
Dwarf_Addr addr;
if (dwarf_formaddr(&var_loc_attr_decoded, &addr))
errx(1, "%s: dwarf_formaddr", __func__);
return addr;
}
static std::optional<Range> vmlinux_get_var_range(const char *name) {
Dwarf_CU *cu = nullptr;
Dwarf_Die cudie;
std::optional<Range> result;
while (dwarf_get_units(vmlinux_dwarf, cu, &cu, NULL, NULL, &cudie, NULL) == 0) {
Dwarf_Die var_die;
if (dwarf_getscopevar(&cudie, 1, name, 0, NULL, 0, 0, &var_die) != 0)
continue;
// get size
Dwarf_Attribute type_attr;
if (dwarf_attr_integrate(&var_die, DW_AT_type, &type_attr) == nullptr)
continue;
Dwarf_Die type_die;
if (dwarf_formref_die(&type_attr, &type_die) == nullptr)
continue;
Dwarf_Word size;
dwarf_aggregate_size(&type_die, &size);
if (result)
errx(1, "duplicate result for '%s'", name);
unsigned long address = get_die_address(&var_die);
result = Range(address, address+size-1);
}
if (result)
printf("'%s' is 0x%lx (size 0x%lx)\n", name, result->start, result->end - result->start + 1);
else
printf("unable to find '%s'\n", name);
return result;
}
static unsigned long vmlinux_get_func_addr(const char *name) {
Dwarf_CU *cu = nullptr;
Dwarf_Die cudie;
std::optional<unsigned long> result;
while (dwarf_get_units(vmlinux_dwarf, cu, &cu, NULL, NULL, &cudie, NULL) == 0) {
Dwarf_Die child;
if (dwarf_child(&cudie, &child) == 0) {
do {
if (dwarf_tag(&child) != DW_TAG_subprogram)
continue;
if (strcmp(dwarf_diename(&child), name) != 0)
continue;
if (result)
errx(1, "duplicate result for '%s'", name);
Dwarf_Addr entry_addr;
if (dwarf_entrypc(&child, &entry_addr))
continue; // probably an extern declaration?
result = entry_addr;
} while (dwarf_siblingof(&child, &child) == 0);
}
}
if (!result)
errx(1, "unable to find '%s'\n", name);
printf("'%s' is 0x%lx\n", name, *result);
return *result;
}
struct FunctionInfoView {
FunctionInfoView(FunctionInfo *backing) : backing(backing) {
if (backing) {
line_cov_by_va = backing->line_cov_by_va;
for (auto& elem : line_cov_by_va) {
for (auto& covpoint : elem.second) {
line_cov_by_line[covpoint.lineno].push_back(&covpoint);
}
}
}
}
struct FunctionInfo *backing;
std::unordered_map<struct FunctionInfo*, struct FunctionInfoView> active_inline_children;
std::unordered_set<struct FunctionInfo*> active_inline_children_set;
std::vector<struct StableGraphPosElem> active_machine_children;
std::map<unsigned long, std::vector<struct memory_access_record*>> mars;
std::unordered_map<int, std::vector<LineCoveragePoint*>> line_cov_by_line;
std::unordered_map<unsigned long, std::vector<LineCoveragePoint>> line_cov_by_va;
struct FunctionInfoView *inline_by_fi(struct FunctionInfo *fi) {
auto [elem, inserted] = active_inline_children.try_emplace(fi, fi);
return &elem->second;
}
struct FunctionInfoView *inline_by_addr(unsigned long addr, bool make_visible) {
if (!backing)
return nullptr;
struct FunctionInfo *child = backing->child_by_va(addr);
if (!child)
return this;
if (make_visible)
active_inline_children_set.insert(child);
return inline_by_fi(child)->inline_by_addr(addr, make_visible);
}
};
struct StableGraphPosElem {
struct FunctionInfo *fi;
uint64_t parent_idx;
size_t thread_idx;
bool is_spooky;
unsigned long caller_ip = 0;
StableGraphPosElem(size_t thread_idx) : fi(nullptr), parent_idx(0), thread_idx(thread_idx), is_spooky(false) {}
StableGraphPosElem(size_t thread_idx, struct FunctionInfo *fi, uint64_t parent_idx, bool is_spooky) :
fi(fi), parent_idx(parent_idx), thread_idx(thread_idx), is_spooky(is_spooky) {}
bool operator==(const StableGraphPosElem &other) const {
return fi == other.fi &&
parent_idx == other.parent_idx &&
thread_idx == other.thread_idx;
}
};
struct StableGraphPos {
std::vector<StableGraphPosElem> elems;
size_t thread_idx = SIZE_MAX;
size_t match_depth, nomatch_depth, nomatch_depth_noinline;
bool ready = true;
void track_reset() {
match_depth = 0;
nomatch_depth = 0;
nomatch_depth_noinline = 0;
}
void track_enter(StableGraphPosElem e) {
if (thread_idx != e.thread_idx)
return;
if (!ready)
return;
if (nomatch_depth || match_depth >= elems.size() || e != elems[match_depth]) {
nomatch_depth++;
if (e.fi && !e.fi->is_inline)
nomatch_depth_noinline++;
} else {
match_depth++;
}
}
void track_exit(StableGraphPosElem e) {
if (thread_idx != e.thread_idx)
return;
if (!ready)
return;
if (nomatch_depth) {
nomatch_depth--;
if (e.fi && !e.fi->is_inline)
nomatch_depth_noinline--;
} else {
assert(match_depth > 0);
match_depth--;
}
}
bool inside_match(size_t cur_thread_idx) { return ready && cur_thread_idx == thread_idx && match_depth == elems.size(); }
bool matching(size_t cur_thread_idx) { return inside_match(cur_thread_idx) && nomatch_depth == 0; }
bool matching_with_inline(size_t cur_thread_idx) { return inside_match(cur_thread_idx) && nomatch_depth_noinline == 0; }
/*
bool matching_fuzzyinline() { return nomatch_depth == 0 && match_depth == elems.size(); }
size_t inline_count = 0;
void calc_inline_len() {
for (size_t i = elems.size()-1; i >= 0 && elems[i].fi && elems[i].fi->is_inline)
inline_count++;
}
*/
};
static StableGraphPos stable_selected;
static bool is_item_clicked_notify(ImGuiMouseButton mouse_button = ImGuiMouseButton_Left) {
bool result = ImGui::IsItemClicked(mouse_button);
if (result)
glfwPostEmptyEvent();
return result;
}
const float STACK_INDENT = 10;
const ImVec4 INLINE_FUNC_COLOR(0, 0.8, 0, 1);
const ImVec4 MEMORY_ACCESS_COLOR(0, 0, 0.8, 1);
const ImVec4 SOURCE_MEMORY_ACCESS_COLOR(1, 0, 0, 1);
const ImVec4 SOURCE_INTERFERENCE_COLOR(1, 0.5, 0, 1);
const ImVec4 SOURCE_CALL_COLOR(0, 0, 1, 1);
struct StackGraphElem : StableGraphPosElem {
std::unordered_map<struct FunctionInfo *, uint64_t> child_counts;
};
struct StackGraphState {
private:
size_t thread_idx;
std::vector<struct StackGraphElem> full_stack = {StackGraphElem(thread_idx)}; // ORDER DEPENDENCY
int depth_emitted = 1;
//int selected_depth = -1;
void invariant_check() {
if (stable_selected.ready && stable_selected.thread_idx == thread_idx) {
assert(full_stack.size() - 1 == stable_selected.match_depth + stable_selected.nomatch_depth);
}
}
void pop_internal(int count) {
for (int i=0; i<count; i++) {
invariant_check();
stable_selected.track_exit(full_stack.back());
full_stack.pop_back();
invariant_check();
}
post_trunc();
}
public:
StableGraphPosElem& last_elem() {
assert(full_stack.size() >= 2);
return full_stack.back();
}
StackGraphState(size_t thread_idx) : thread_idx(thread_idx) {}
std::vector<FunctionInfo*> get_real_func_stack() {