-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
926 lines (796 loc) · 24.7 KB
/
main.go
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
package main
import (
// "github.com/cs-au-dk/goat/solver"
"fmt"
"log"
"math"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/cs-au-dk/goat/analysis/upfront/chreflect"
"github.com/cs-au-dk/goat/analysis/upfront/loopinline"
dotg "github.com/cs-au-dk/goat/graph"
"github.com/cs-au-dk/goat/pkgutil"
tu "github.com/cs-au-dk/goat/testutil"
"github.com/cs-au-dk/goat/utils"
"github.com/cs-au-dk/goat/utils/dot"
"github.com/cs-au-dk/goat/utils/graph"
"github.com/cs-au-dk/goat/utils/hmap"
ai "github.com/cs-au-dk/goat/analysis/absint"
"github.com/cs-au-dk/goat/analysis/cfg"
"github.com/cs-au-dk/goat/analysis/defs"
"github.com/cs-au-dk/goat/analysis/gotopo"
u "github.com/cs-au-dk/goat/analysis/upfront"
"github.com/fatih/color"
"golang.org/x/tools/go/callgraph/rta"
"golang.org/x/tools/go/pointer"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/go/ssa/ssautil"
"net/http"
_ "net/http/pprof"
)
var (
opts = utils.Opts()
task = opts.Task()
)
func main() {
utils.ParseArgs()
path := utils.MakePath()
if opts.HttpDebug() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
}
pkgs, err := pkgutil.LoadPackages(pkgutil.LoadConfig{
GoPath: opts.GoPath(),
ModulePath: opts.ModulePath(),
IncludeTests: opts.IncludeTests(),
}, path)
if err != nil {
log.Printf("Failed pkgutil.LoadPackages(GoPath=\"%s\", ModulePath=\"%s\", IncludeTests=%v)\n", opts.GoPath(), opts.ModulePath(), opts.IncludeTests())
log.Println(err)
os.Exit(1)
}
// pkgs = u.UnrollLoops(pkgs)
err = loopinline.InlineLoops(pkgs)
if err != nil {
log.Fatalln("Loop inlining failed?", err)
}
if opts.Task().IsCanBuild() {
return
}
prog, _ := ssautil.AllPackages(pkgs, ssa.InstantiateGenerics)
prog.Build()
mains := ssautil.MainPackages(prog.AllPackages())
if len(mains) == 0 {
log.Println("No main packages detected")
return
}
allPackages := pkgutil.AllPackages(prog)
pkgutil.GetLocalPackages(mains, allPackages)
if !opts.SkipChanNames() {
u.CollectNames(pkgs)
}
// Assemble pre-analysis preanalysisPipeline
preanalysisPipeline := func(includes u.IncludeType) (*pointer.Result, *cfg.Cfg) {
fmt.Println()
log.Println("Performing points-to analysis...")
ptaResult := u.Andersen(prog, mains, includes)
log.Println("Points-to analysis done")
fmt.Println()
log.Println("Extending CFG...")
progCfg := cfg.GetCFG(prog, mains, ptaResult)
log.Println("CFG extensions done")
fmt.Println()
opts.OnVerbose(func() {
for val, ptr := range ptaResult.Queries {
fmt.Printf("Points to information for \"%s\" at %d (%s):\n",
val, val.Pos(), prog.Fset.Position(val.Pos()))
for _, label := range ptr.PointsTo().Labels() {
fmt.Printf("%s : %d (%s), ", label, (*label).Pos(), prog.Fset.Position((*label).Pos()))
}
fmt.Print("\n\n")
}
})
return ptaResult, progCfg
}
fullPreanalysisPipeline := func(includes u.IncludeType) (
*pointer.Result,
*cfg.Cfg,
u.GoTopology,
) {
ptaResult, progCfg := preanalysisPipeline(includes)
log.Println("Constructing Goroutine topology...")
goros := u.CollectGoros(ptaResult)
log.Println("Goroutine topology done")
opts.OnVerbose(func() {
fmt.Println("Found the following goroutines:")
for _, goro := range goros {
fmt.Println(goro.String())
fmt.Println()
}
fmt.Println()
})
return ptaResult, progCfg, goros
}
// States queries for which types to include the Andersen points-to analysis
standardPTAnalysisQueries := u.IncludeType{
Chan: true,
Function: true,
Interface: true,
}
aiConfig := ai.AIConfig{
Metrics: opts.Metrics(),
Log: opts.LogAI(),
}
switch {
case task.IsStaticMetrics():
pt, cfg := preanalysisPipeline(u.IncludeType{All: true})
cs, callees := cfg.MaxCallees()
prec2 := func(n float64) float64 {
return math.Floor(n*100) / 100
}
order := func(count map[int]int) (ordered []struct{ count, nodes int }, total int) {
for c, nodes := range count {
ordered = append(ordered, struct {
count, nodes int
}{c, nodes})
total += nodes
}
sort.Slice(ordered, func(i, j int) bool {
return ordered[i].count < ordered[j].count
})
return
}
fmt.Println("================ Results =====================")
fmt.Println("Maximum callees for a call-site:", color.BlueString(cs.String()), color.GreenString(strconv.Itoa(callees)))
orderedCallsites, callsiteTotal := order(cfg.CalleeCount())
orderedExitnodes, exitsTotal := order(cfg.CallerCount())
orderedChanops, chOpsTotal := order(cfg.ChanOpsPointsToSets(pt))
orderedChanImprecision, chTotal := order(cfg.CheckImpreciseChanOps(pt))
type printConfig = struct {
source string
drain string
total int
}
print := func(conf printConfig, orderedSites []struct{ count, nodes int }) {
for _, o := range orderedSites {
c, nodes := o.count, o.nodes
percent := prec2(float64(nodes) / float64(conf.total) * 100)
var colorize func(string, ...interface{}) string
switch {
case c <= 1:
colorize = color.BlueString
case c == 2:
colorize = color.GreenString
case 3 <= c && c <= 5:
colorize = color.YellowString
default:
colorize = color.HiRedString
}
fmt.Println(colorize("%v", c), " "+conf.drain+" found at", percent, "% ("+color.HiCyanString("%v", nodes)+") of", conf.source)
}
}
fmt.Println("\nOutgoing degree for function call/method invocation sites")
print(printConfig{
source: "call sites",
drain: "callees",
total: callsiteTotal,
}, orderedCallsites)
fmt.Println("\nOutgoing degree for function exit nodes")
print(printConfig{
source: "function exit nodes",
drain: "callers",
total: exitsTotal,
}, orderedExitnodes)
fmt.Println("\nPoints-to set cardinality for channel operands of channel operations")
print(printConfig{
source: "channel operations",
drain: "channel operands in points-to set",
total: chOpsTotal,
}, orderedChanops)
fmt.Println("\nChannel primitive imprecision")
print(printConfig{
source: "channels",
drain: "maximum channels which may alias at the same operation",
total: chTotal,
}, orderedChanImprecision)
case task.IsGoroTopology():
ptaResult, _, goros := fullPreanalysisPipeline(standardPTAnalysisQueries)
log.Println("Constructing topology graph...")
image_path := dotg.BuildGraph(prog, ptaResult, goros)
fmt.Println(image_path)
case task.IsCycleCheck():
_, _, goros := fullPreanalysisPipeline(standardPTAnalysisQueries)
log.Println("Logging cycles in the goroutine topology graph...")
goros.LogCycles()
case task.IsPointsTo():
pt, _ := preanalysisPipeline(u.IncludeType{All: true})
if len(pt.Warnings) > 0 {
fmt.Println("Warnings:")
for _, w := range pt.Warnings {
fmt.Println(w)
}
}
fmt.Println()
log.Println("Points-to analysis results:")
fmt.Println("Direct queries:")
for v, ptset := range pt.Queries {
if opts.LocalPackages() && !pkgutil.IsLocal(v) {
continue
}
fmt.Println("SSA Value", utils.SSAValString(v))
fmt.Println("Points to: {")
str := ""
for _, l := range ptset.PointsTo().Labels() {
lv := l.Value()
str += "\t" + utils.SSAValString(lv) + ",\n"
}
str += "}"
fmt.Println(str)
}
fmt.Println("")
fmt.Println("Indirect queries:")
for v, ptset := range pt.IndirectQueries {
if opts.LocalPackages() && !pkgutil.IsLocal(v) {
continue
}
fmt.Println("SSA Value", utils.SSAValString(v))
fmt.Println("Indirectly points to: {")
str := ""
for _, l := range ptset.PointsTo().Labels() {
lv := l.Value()
str += "\t" + utils.SSAValString(lv) + ",\n"
}
str += "}"
fmt.Println(str)
}
case task.IsCheckPsets():
pt, cfg := preanalysisPipeline(u.IncludeType{All: true})
G := graph.FromCallGraph(pt.CallGraph, true)
psets := gotopo.GetInterprocPsets(cfg, pt, G)
log.Println(psets)
case task.IsWrittenFieldsAnalysis():
pt, _ := preanalysisPipeline(u.IncludeType{All: true})
cg := pt.CallGraph
callDAG := graph.FromCallGraph(cg, true).SCC([]*ssa.Function{cg.Root.Func})
wf := u.ComputeWrittenFields(pt, callDAG)
log.Println(wf)
case task.IsCollectPrimitives():
if !opts.Metrics() {
log.Fatalln("Run with -metrics")
}
entries := pkgutil.TestFunctions(prog)
for _, main := range ssautil.MainPackages(allPackages) {
entries = append(entries, main.Func("main"))
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].String() < entries[j].String()
})
if len(entries) == 0 {
log.Println("Skipping benchmark since it has no entries")
return
} else {
// This is a cheap check to see if we can avoid processing the package altogether.
// If there is no reachable local channel allocation in the RTA call graph,
// there is no need to do expensive (pointer) pre-analyses.
log.Println("Building initial RTA callgraph")
rtaCG := rta.Analyze(entries, true).CallGraph
rtaG := graph.FromCallGraph(rtaCG, false)
log.Printf("RTA callgraph constructed with %d nodes", len(rtaCG.Nodes))
// Check if an entry can reach a local channel allocation in the RTA call graph
if !rtaG.BFSV(func(fun *ssa.Function) bool {
if pkgutil.IsLocal(fun) {
for _, block := range fun.Blocks {
for _, insn := range block.Instrs {
if _, isMakeChan := insn.(*ssa.MakeChan); isMakeChan {
//log.Println(insn, prog.Fset.Position(insn.Pos()))
return true
}
}
}
}
return false
}, entries...) {
log.Println("Skipping benchmark since it has no local channel allocations")
return
}
}
skips, aborts, completes := 0, 0, 0
pt, pcfg := preanalysisPipeline(u.IncludeType{All: true})
cfgFunctions := pcfg.Functions()
soundG := graph.FromCallGraph(pt.CallGraph, false)
G := graph.FromCallGraph(pt.CallGraph, true)
wf := u.ComputeWrittenFields(pt, G.SCC(entries))
// Perform deduplication of fragments over all entry points.
// This breaks joined use of flags -fun and -pset since the number
// of psets for a function depends on analysis of previous functions.
// (At least it's a little bit less obvious how to use them)
allSeenFragments := map[*ssa.Function]*hmap.Map[utils.SSAValueSet, bool]{}
for idx, entry := range entries {
if !opts.IsWholeProgramAnalysis() && !(strings.HasSuffix(entry.Name(), opts.Function()) ||
strings.HasSuffix(entry.String(), opts.Function())) {
continue
}
log.Printf("Entry %d of %d: %v", idx+1, len(entries), entry)
/*
var spkg *ssa.Package
if entry.Name() == "main" {
spkg = entry.Package()
} else {
spkg = pkgutil.CreateFakeTestMainPackage(entry)
}
mains = []*ssa.Package{spkg}
*/
callDAG := G.SCC([]*ssa.Function{entry})
computeDominator := G.DominatorTree(entry)
ps, primsToUses := gotopo.GetPrimitives(entry, pt, G)
psets := func() (psets gotopo.PSets) {
switch {
case opts.PSets().SameFunc():
return gotopo.GetSameFuncPsets(ps)
case opts.PSets().GCatch():
return gotopo.GetGCatchPSets(
pcfg, entry, pt, G,
computeDominator, callDAG, ps) // GCatch Psets
case opts.PSets().Total():
return gotopo.GetTotalPset(ps) // Singular whole program p-set
case opts.PSets().Singleton():
fallthrough
default:
return gotopo.GetSingletonPsets(ps) // Singleton sets
}
}()
// Remove channels from PSets where the channel flows into the reflection library
if reflectedChans := chreflect.GetReflectedChannels(prog, pt); !reflectedChans.Empty() {
log.Printf("%s:\n%v",
color.YellowString("Pruning channels from PSets that flow into the reflection library"),
reflectedChans)
// Since pruning may introduce duplicate PSets, we use hashing
// to ensure they are not present in the output.
newPsets := make(gotopo.PSets, 0, len(psets))
seen := hmap.NewMap[bool](utils.SSAValueSetHasher)
for _, pset := range psets {
reflectedChans.ForEach(func(rCh ssa.Value) {
pset.Map = pset.Delete(rCh)
})
if !pset.Empty() && !seen.Get(pset) {
seen.Set(pset, true)
newPsets = append(newPsets, pset)
}
}
psets = newPsets
}
//log.Printf("%s", psets)
if len(psets) == 0 {
log.Printf("%d primitives outside GOROOT reachable from %s", len(psets), entry)
continue
}
// Ensure consistent ordering
sort.Slice(psets, func(i, j int) bool {
return psets[i].String() < psets[j].String()
})
type fragment struct {
entry *ssa.Function
pset utils.SSAValueSet
}
fragments := []fragment{}
for _, pset := range psets {
// TODO: Protect dominator computation with flag?
funs := []*ssa.Function{}
pset.ForEach(func(v ssa.Value) {
if v.Parent() != nil {
// Include allocation site in dominator computation
funs = append(funs, v.Parent())
}
for fun := range primsToUses[v] {
funs = append(funs, fun)
}
})
loweredEntry := computeDominator(funs...)
if _, found := cfgFunctions[loweredEntry]; !found {
log.Println(color.YellowString("CFG does not contain the entry function."))
continue
}
seenFragments, ok := allSeenFragments[loweredEntry]
if !ok {
mp := hmap.NewMap[bool](utils.SSAValueSetHasher)
allSeenFragments[loweredEntry] = mp
seenFragments = mp
}
if !seenFragments.Get(pset) {
seenFragments.Set(pset, true)
fragments = append(fragments, fragment{loweredEntry, pset})
}
}
log.Printf("%d primitives outside GOROOT reachable from %s", len(fragments), entry)
loadRes := tu.LoadResult{
Prog: prog,
Mains: mains,
Cfg: pcfg,
Pointer: pt,
CallDAG: soundG.SCC([]*ssa.Function{entry}),
PrunedCallDAG: callDAG,
CtrLocPriorities: u.GetCtrLocPriorities(cfgFunctions, callDAG),
WrittenFields: wf,
}
for i, fragment := range fragments {
if !opts.IsPickedPset(i + 1) {
continue
}
loweredEntry, pset := fragment.entry, fragment.pset
fmt.Println()
log.Println(color.CyanString("Found PSet"), i+1, color.CyanString("of"), len(fragments), color.CyanString(":"))
fmt.Println(pset)
fmt.Println()
log.Println("Using", loweredEntry, "as entrypoint")
C := ai.ConfigAI(aiConfig).Function(loweredEntry)(loadRes)
C.FragmentPredicateFromPrimitives(pset.Entries(), primsToUses)
done := make(chan bool, 1)
timeout := 60 * time.Second
go func() {
select {
case <-time.After(timeout):
log.Println("Skipping")
C.Metrics.Skip()
case <-done:
}
}()
C.Metrics.TimerStart()
ts, analysis := ai.StaticAnalysis(C)
done <- true
log.Println("Superlocation graph size:", ts.Size())
switch C.Metrics.Outcome {
case ai.OUTCOME_SKIP:
log.Println(color.RedString("Skipped!"))
skips++
case ai.OUTCOME_PANIC:
log.Println(color.RedString("Aborted!"))
log.Println(C.Metrics.Error())
aborts++
default:
C.Metrics.Done()
log.Println(color.GreenString("SA completed in %s", C.Metrics.Performance()))
completes++
blocks := ai.BlockAnalysisFiltered(C, ts, analysis, true)
if len(blocks) == 0 {
log.Println(color.GreenString("No blocking bugs detected"))
} else {
blocks.Log()
if opts.Visualize() {
blocks.PrintPath(ts, analysis, G)
ts.Visualize(blocks)
}
}
}
/*
allocSiteExpansions := 0
pset.ForEach(func(prim ssa.Value) {
allocSiteExpansions += C.Metrics.Functions()[prim.Parent()]
})
syncConfsWithPrimitive := 0
ts.ForEach(func(conf *ai.AbsConfiguration) {
state := analysis.GetUnsafe(conf.Superlocation())
if !conf.IsPanicked() && conf.IsSynchronizing(C, state) {
mem := state.Memory()
_, _, found := conf.Threads().Find(func(g defs.Goro, cl defs.CtrLoc) bool {
for _, prim := range cfg.CommunicationPrimitivesOf(cl.Node()) {
if av := ai.EvaluateSSA(g, mem, prim); av.IsPointer() {
for _, ptr := range av.PointerValue().Entries() {
site, _ := ptr.GetSite()
if C.IsPrimitiveFocused(site) {
return true
}
}
}
}
return false
})
if found {
syncConfsWithPrimitive++
}
}
})
log.Printf("allocSiteExpansions: %d, synchronizing configurations with primitive: %d",
allocSiteExpansions, syncConfsWithPrimitive)
*/
}
}
log.Printf("Completed runs: %d, skipped runs: %d, aborted runs: %d", completes, skips, aborts)
case task.IsChannelAliasingCheck():
fullPreanalysisPipeline(standardPTAnalysisQueries)
fmt.Printf("%d -- %s\n", u.ChAliasingInfo.MaxChanPtsToSetSize, u.ChAliasingInfo.Location)
case task.IsCfgToDot():
ptaResult, cfg := preanalysisPipeline(standardPTAnalysisQueries)
log.Println("Preparing to visualize CFG:")
if opts.IsWholeProgramAnalysis() {
cfg.Visualize(ptaResult)
} else {
cfg.VisualizeFunc(opts.Function())
}
case task.IsCallGraphToDot():
ptaResult, cfg := preanalysisPipeline(standardPTAnalysisQueries)
log.Println("Preparing to visualize callgraph:")
cg := graph.FromCallGraph(ptaResult.CallGraph, false)
root := ptaResult.CallGraph.Root.Func
if opts.Function() != "main" {
root = cfg.FunctionByName(opts.Function())
}
scc := cg.SCC([]*ssa.Function{root})
allNodes := []*ssa.Function{}
allComps := []int{}
for i, comp := range scc.Components {
anyLocal := false
for _, node := range comp {
if pkgutil.IsLocal(node) {
anyLocal = true
break
}
}
if anyLocal || !opts.LocalPackages() {
allNodes = append(allNodes, comp...)
allComps = append(allComps, i)
}
}
scc.Convolution().ToDotGraph(allComps, &graph.VisualizationConfig[int]{
NodeAttrs: func(node int) (string, dot.DotAttrs) {
return fmt.Sprint(node), dot.DotAttrs{"label": fmt.Sprint(scc.Components[node][0])}
},
}).ShowDot()
cg.ToDotGraph(allNodes, &graph.VisualizationConfig[*ssa.Function]{
ClusterKey: func(node *ssa.Function) any { return scc.ComponentOf(node) },
}).ShowDot()
case task.IsAbstractInterpretation():
ptQueries := u.IncludeType{All: true}
if !task.IsWholeProgramAnalysis() {
ptQueries = u.IncludeType{All: true}
}
results := make(map[*ssa.Function]*ai.Metrics)
ptaResult, prog_cfg := preanalysisPipeline(ptQueries)
cg := ptaResult.CallGraph
entries := []*ssa.Function{cg.Root.Func}
loadRes := tu.LoadResult{
Prog: prog,
Mains: mains,
Cfg: prog_cfg,
Pointer: ptaResult,
CallDAG: graph.FromCallGraph(cg, false).SCC(entries),
}
loadRes.PrunedCallDAG = graph.FromCallGraph(cg, true).SCC(entries)
loadRes.CtrLocPriorities = u.GetCtrLocPriorities(prog_cfg.Functions(), loadRes.PrunedCallDAG)
loadRes.WrittenFields = u.ComputeWrittenFields(ptaResult, loadRes.PrunedCallDAG)
// Analysis context
Cs := ai.ConfigAI(aiConfig).Executable(loadRes)
timeout := 120000 * time.Millisecond
for f, C := range Cs {
if !C.Metrics.Enabled() {
log.Println("Abstractly interpreting:")
fmt.Println(f)
fmt.Println("Found at", prog.Fset.Position(f.Pos()))
fmt.Println()
}
if !opts.AnalyzeAllFuncs() {
var blocks ai.Blocks
G, A := ai.StaticAnalysis(C)
log.Println("Done")
fmt.Println()
log.Println("Analysis result:\n", A.ProjectMemory())
// if G.Size() > 3 {
// }
// Log all the found blocking bugs.
blocks = ai.BlockAnalysis(C, G, A)
blocks.ForEach(func(sl defs.Superloc, gs map[defs.Goro]struct{}) {
fmt.Printf("%s ↦ %s\n", sl, A.GetUnsafe(sl).Memory())
})
blocks.Log()
if opts.Visualize() {
G.Visualize(blocks)
}
continue
}
done := make(chan bool)
closed := make(chan bool)
mu := &sync.Mutex{}
// Allocate space for spawned goroutines
go func(f *ssa.Function, C ai.AnalysisCtxt) {
var blocks ai.Blocks
C.Metrics.TimerStart()
defer func() {
if C.Metrics.HasConcurrency() {
// ops := C.ConcurrencyOps
// fs := C.ExpandedFunctions
mu.Lock()
C.Metrics.Done()
results[f] = C.Metrics
mu.Unlock()
}
}()
defer func() {
if err := recover(); err != nil {
mu.Lock()
if _, ok := results[f]; !ok {
C.Metrics.Panic(err)
results[f] = C.Metrics
}
mu.Unlock()
close(done)
return
}
mu.Lock()
if _, ok := results[f]; !ok {
C.Metrics.Done()
results[f] = C.Metrics
}
mu.Unlock()
close(done)
}()
G, result := ai.StaticAnalysis(C)
if !C.Metrics.Enabled() {
log.Println("Done")
fmt.Println()
}
blocks = ai.BlockAnalysis(C, G, result)
// log.Println("Analysis result:\n", A)
if C.Metrics.IsRelevant() {
C.Metrics.SetBlocks(blocks)
}
if !C.Metrics.Enabled() {
blocks.Log()
if opts.Visualize() {
G.Visualize(blocks)
}
}
}(f, C)
go func(f *ssa.Function, C ai.AnalysisCtxt) {
select {
case <-done:
case <-time.After(timeout):
if !C.Metrics.Enabled() {
fmt.Println("Function", f, "takes too long to analyze. Skip?")
utils.Prompt()
fmt.Println("Function", f, "skipped")
}
close(closed)
mu.Lock()
if _, ok := results[f]; !ok {
C.Metrics.Skip()
results[f] = C.Metrics
}
mu.Unlock()
}
}(f, C)
select {
case <-done:
case <-closed:
}
}
GatherMetrics(loadRes, results)
case task.IsPosition():
for _, pkg := range prog.AllPackages() {
for _, member := range pkg.Members {
switch f := member.(type) {
case *ssa.Function:
utils.PrintSSAFunWithPos(prog.Fset, f)
}
}
}
}
}
func GatherMetrics(loadRes tu.LoadResult, results map[*ssa.Function]*ai.Metrics) {
if !opts.Metrics() || len(results) == 0 {
return
}
prog := loadRes.Prog
coveredConcOp := make(map[ssa.Instruction]struct{})
coveredChans := make(map[ssa.Instruction]struct{})
coveredGos := make(map[ssa.Instruction]struct{})
msg := "================ Results =====================\n\n"
for f, r := range results {
msg += "Function: " + f.String() + "\n"
msg += "Outcome: " + r.Outcome + "\n"
if r.Outcome == ai.OUTCOME_SKIP {
msg += "Function finished\n\n"
continue
}
if r.Outcome == ai.OUTCOME_PANIC {
msg += r.Error() + "\nFunction finished\n\n"
continue
}
msg += "Time: " + r.Performance() + "\n\n"
files := make(map[string]struct{})
if len(r.Functions()) > 0 {
msg += "Expanded functions: " + fmt.Sprintf("%d", len(r.Functions())) + " {\n"
for f, times := range r.Functions() {
fn := prog.Fset.Position(f.Pos()).Filename
if _, ok := files[fn]; !ok {
files[prog.Fset.Position(f.Pos()).Filename] = struct{}{}
}
msg += " " + f.String() + " -- " + fmt.Sprintf("%d", times) + "\n"
}
msg += "}\n"
}
if len(r.Blocks()) > 0 {
msg += "Blocks:"
msg += r.Blocks().String()
msg += "\n"
}
fs := make([]string, 0, len(files))
for f := range files {
fs = append(fs, f)
}
if len(fs) > 0 {
cloc := exec.Command("cloc", fs...)
out, err := cloc.Output()
if err == nil {
msg += string(out) + "\n"
}
}
for i := range r.ConcurrencyOps() {
coveredConcOp[i] = struct{}{}
}
for i := range r.Gos() {
coveredGos[i] = struct{}{}
}
for i := range r.Chans() {
coveredChans[i] = struct{}{}
}
msg += "Function finished\n\n"
}
allConcOps := loadRes.Cfg.GetAllConcurrencyOps()
msg += "Concurrency operations covered: " + fmt.Sprint(len(coveredConcOp)) + "/" + fmt.Sprint(len(allConcOps)) + " {\n"
if len(allConcOps) > 0 {
notCovered := make(map[ssa.Instruction]struct{})
for op := range allConcOps {
if _, ok := coveredConcOp[op]; !ok {
notCovered[op] = struct{}{}
}
}
if len(notCovered) > 0 {
msg += "Not covered: {\n"
for op := range notCovered {
msg += " " + op.String() + ":" + prog.Fset.Position(op.Pos()).String() + "\n"
}
msg += "}\n"
}
}
allChans := loadRes.Cfg.GetAllChans()
msg += "Channel sites covered: " + fmt.Sprint(len(coveredChans)) + "/" + fmt.Sprint(len(allChans)) + "\n"
if len(allChans) > 0 {
notCovered := make(map[ssa.Instruction]struct{})
for ch := range allChans {
if _, ok := coveredChans[ch]; !ok {
notCovered[ch] = struct{}{}
}
}
if len(notCovered) > 0 {
msg += "Not covered: {\n"
for ch := range notCovered {
msg += " " + ch.String() + ":" + prog.Fset.Position(ch.Pos()).String() + "\n"
}
msg += "}\n"
}
}
allGos := loadRes.Cfg.GetAllGos()
msg += "Goroutine sites covered: " + fmt.Sprint(len(coveredGos)) + "/" + fmt.Sprint(len(allGos)) + "\n"
if len(allGos) > 0 {
notCovered := make(map[ssa.Instruction]struct{})
for g := range allGos {
if _, ok := coveredGos[g]; !ok {
notCovered[g] = struct{}{}
}
}
if len(notCovered) > 0 {
msg += "Not covered: {\n"
for g := range notCovered {
msg += " " + g.String() + ":" + prog.Fset.Position(g.Pos()).String() + "\n"
}
msg += "}\n"
}
}
msg += "================ Results ====================="
fmt.Println(msg)
}