/
instrumentChan.go
1672 lines (1512 loc) · 38.8 KB
/
instrumentChan.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
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
package instrumenter
/*
Copyright (c) 2023, Erik Kassubek
All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Author: Erik Kassubek <erik-kassubek@t-online.de>
Package: dedego-instrumenter
Project: Dynamic Analysis to detect potential deadlocks in concurrent Go programs
*/
/*
instrumentChan.go
Instrument channels to work with the "github.com/ErikKassubek/deadlockDetectorGo/src/dedego" library
*/
import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
"strconv"
"strings"
"golang.org/x/tools/go/ast/astutil"
)
var selectIdCounter int = 0
var selectCaseCounter int = 0
/*
Type for the select_ops list
@field id int: id of the select statement
@field size int: number of cases (incl. default) of the select
*/
type select_op struct {
id int
size int
}
/*
Tuple to store an index and string
@field index int: index
@field name string: string
*/
type chanRetNil struct {
index int
name string
}
// collect select cases with (id, no of cases)
var select_ops = make([]select_op, 0)
/*
Function to instrument a given ast.File with channels. Channels and operation
of this channels are replaced by there dedego equivalent.
@param f *ast.File: ast file to instrument
@param astSet *token.FileSet: token file set
@param maxTime int: maximum time to wait for the program
@param maxSelectTime int: maximum time to wait for a select operation
@param imports []string: list of imported libraries
@return error: error or nil
*/
func instrument_chan(f *ast.File, astSet *token.FileSet, maxTime int,
maxSelectTime int, imports []string) error {
// ast.Print(astSet, f)
// add the import of the dedego library
add_dedego_import(f)
var main_func *ast.FuncDecl
// first pass-through to instrument main function and function declarations
astutil.Apply(f, nil, func(c *astutil.Cursor) bool {
n := c.Node()
switch n := n.(type) {
case *ast.FuncDecl:
if n.Name.Obj != nil && n.Name.Obj.Name == "main" {
add_dedego_fetch_order(f)
add_run_analyzer(n)
add_init_call(n, maxTime)
main_func = n
} else {
instrument_function_declarations(n, c)
}
case *ast.FuncType:
instrument_function_type(n, c)
}
return true
})
// second pass-through to instrument everything else
astutil.Apply(f, nil, func(c *astutil.Cursor) bool {
n := c.Node()
switch n := n.(type) {
case *ast.GenDecl: // instrument declarations of structs, interfaces, chan.
instrument_gen_decl(n, c, astSet)
case *ast.AssignStmt: // handle assign statements
switch n.Rhs[0].(type) {
case *ast.UnaryExpr: // receive with assign
instrument_receive_with_assign(n, c)
case *ast.CompositeLit: // creation of struct
instrument_assign_struct(n)
case *ast.Ident: // nil
instrument_nil_assign(n, astSet)
}
case *ast.CallExpr: // call expression
instrument_call_expressions(n, c, astSet, imports)
case *ast.SendStmt: // handle send messages
instrument_send_statement(n, c)
case *ast.ExprStmt: // handle receive and close
instrument_expression_statement(n, c)
case *ast.DeferStmt: // handle defer
instrument_defer_statement(n, c)
case *ast.GoStmt: // handle the creation of new go routines
instrument_go_statements(n, c)
case *ast.SelectStmt: // handel select statements
instrument_select_statements(n, c, maxSelectTime, astSet)
case *ast.RangeStmt: // range
instrument_range_stm(n)
case *ast.ReturnStmt: // return <- c
instrument_return(n)
case *ast.IfStmt: // if a == nil {
instrument_if(n, astSet)
}
return true
})
if len(select_ops) > 0 {
add_order_in_main(main_func)
}
return nil
}
/*
Function to add the import of the dedego library
@param n *ast.File: ast file to instrument
*/
func add_dedego_import(n *ast.File) {
import_spec := &ast.ImportSpec{
Path: &ast.BasicLit{
Kind: token.STRING,
Value: "\"github.com/ErikKassubek/deadlockDetectorGo/src/dedego\"",
},
}
if n.Decls == nil {
n.Decls = []ast.Decl{}
}
if len(n.Decls) == 0 {
n.Decls = append([]ast.Decl{&ast.GenDecl{Tok: token.IMPORT}}, n.Decls...)
}
switch n.Decls[0].(type) {
case (*ast.GenDecl):
if n.Decls[0].(*ast.GenDecl).Tok != token.IMPORT {
n.Decls = append([]ast.Decl{&ast.GenDecl{Tok: token.IMPORT}}, n.Decls...)
}
default:
n.Decls = append([]ast.Decl{&ast.GenDecl{Tok: token.IMPORT}}, n.Decls...)
}
switch n.Decls[0].(type) {
case *ast.GenDecl:
default:
n.Decls = append([]ast.Decl{&ast.GenDecl{Tok: token.IMPORT}}, n.Decls...)
}
if n.Decls[0].(*ast.GenDecl).Specs == nil {
n.Decls[0].(*ast.GenDecl).Specs = []ast.Spec{}
}
n.Decls[0].(*ast.GenDecl).Specs = append(n.Decls[0].(*ast.GenDecl).Specs, import_spec)
}
/*
Add var dedegoFetchOrder = make(map[int]int) as global variable
@param n *ast.File: ast file
*/
func add_dedego_fetch_order(n *ast.File) {
n.Decls = append(n.Decls, &ast.GenDecl{
Tok: token.VAR,
Specs: []ast.Spec{
&ast.ValueSpec{
Names: []*ast.Ident{
{
Name: "dedegoFetchOrder = make(map[int]int)",
},
},
},
},
})
}
/*
Function to add call of dedego.Init(), defer time.Sleep(time.Millisecond)
and defer dedego.RunAnalyzer() to the main function. The time.Sleep call is used
to give the go routines a chance to finish there execution.
@param n *ast.FuncDecl: node of the main function declaration of the ast
*/
func add_init_call(n *ast.FuncDecl, maxTime int) {
body := n.Body.List
if body == nil {
return
}
body = append([]ast.Stmt{
&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.Ident{
Name: "dedego.Init",
},
Args: []ast.Expr{
&ast.Ident{
Name: strconv.Itoa(maxTime),
},
},
},
},
}, body...)
n.Body.List = body
}
/*
Function to add order inforcement structure and command line argument receiver
@param n *ast.FuncDecl: main function declaration in ast
@return: nil
*/
func add_order_in_main(n *ast.FuncDecl) {
if n == nil || n.Body == nil {
return
}
body := n.Body.List
if body == nil {
return
}
body = append([]ast.Stmt{
&ast.ExprStmt{
X: &ast.Ident{
Name: "var order string",
},
},
&ast.ExprStmt{
X: &ast.Ident{
Name: "if len(os.Args) > 0 { order = os.Args[1] }",
},
},
&ast.ExprStmt{
X: &ast.Ident{
Name: "order_split := strings.Split(order, \";\")",
},
},
&ast.ExprStmt{
X: &ast.Ident{
Name: "for _, ord := range order_split { " +
"ord_split := strings.Split(ord, \",\"); " +
"id, err1 := strconv.Atoi(ord_split[0]);" +
"c, err2 := strconv.Atoi(ord_split[1]);" +
"if (err1 == nil && err2 == nil) {" +
"dedegoFetchOrder[id] = c}}",
},
},
}, body...)
n.Body.List = body
}
/*
Add a defer statement to run the analyzer
@param n *ast.FuncDecl: ast function declaration
*/
func add_run_analyzer(n *ast.FuncDecl) {
n.Body.List = append([]ast.Stmt{
&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.Ident{
Name: "defer dedego.RunAnalyzer",
},
},
},
&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.Ident{
Name: "defer time.Sleep",
},
Args: []ast.Expr{
&ast.Ident{
Name: "time.Millisecond",
},
},
},
},
},
n.Body.List...)
}
/*
Function to instrument the declarations of channels, structs and interfaces.
@param n *ast.GenDecl: node of the declaration in the ast
@param c *astutil.Cursor: cursor that traverses the ast
*/
func instrument_gen_decl(n *ast.GenDecl, c *astutil.Cursor, astSet *token.FileSet) {
// ast.Print(astSet, n)
for i, s := range n.Specs {
switch s_type := s.(type) {
case *ast.ValueSpec:
switch t_type := s_type.Type.(type) {
case *ast.ChanType:
type_val := get_name(t_type.Value)
if !strings.Contains(type_val, "time.") {
n.Specs[i].(*ast.ValueSpec).Type = &ast.Ident{
Name: "= dedego.NewChan[" + type_val + "](0)",
}
}
}
case *ast.TypeSpec:
switch s_type_type := s_type.Type.(type) {
case *ast.StructType:
for j, t := range s_type_type.Fields.List {
switch t_type := t.Type.(type) {
case *ast.ChanType:
type_val := get_name(t_type.Value)
n.Specs[i].(*ast.TypeSpec).Type.(*ast.StructType).Fields.List[j].Type = &ast.Ident{
Name: "dedego.Chan[" + type_val + "]",
}
case *ast.ArrayType:
switch elt := t_type.Elt.(type) {
case *ast.ChanType:
type_string := get_name(elt.Value)
n.Specs[i].(*ast.TypeSpec).Type.(*ast.StructType).Fields.List[j].Type.(*ast.ArrayType).Elt = &ast.Ident{
Name: "dedego.Chan[" + type_string + "]",
}
}
}
}
case *ast.InterfaceType:
for _, t := range s_type_type.Methods.List {
switch t_type := t.Type.(type) {
case *ast.FuncType:
_ = instrument_function_declaration_return_values(t_type)
instrument_function_declaration_parameter(t_type)
}
}
}
}
}
}
/*
Function to instrument function types outside of function declarations.
@param n *ast.FuncDecl: node of the func declaration in the ast
@param c *astutil.Cursor: cursor that traverses the ast
*/
func instrument_function_type(n *ast.FuncType, c *astutil.Cursor) {
_ = instrument_function_declaration_return_values(n)
instrument_function_declaration_parameter(n)
}
/*
Function to instrument function declarations.
@param n *ast.FuncDecl: node of the func declaration in the ast
@param c *astutil.Cursor: cursor that traverses the ast
*/
func instrument_function_declarations(n *ast.FuncDecl, c *astutil.Cursor) {
val := instrument_function_declaration_return_values(n.Type)
instrument_function_declaration_parameter(n.Type)
// change nil
if len(val) != 0 {
astutil.Apply(n, nil, func(c *astutil.Cursor) bool {
node := c.Node()
switch ret := node.(type) {
case *ast.ReturnStmt:
for _, elem := range val {
switch r := ret.Results[elem.index].(type) {
case *ast.Ident:
if r.Name == "nil" {
node.(*ast.ReturnStmt).Results[elem.index].(*ast.Ident).Name = elem.name + "{}"
}
}
}
}
return true
})
}
}
/*
Function to change the return value of functions if they contain a chan.
@param n *ast.FuncType: node of the func type in the ast
*/
func instrument_function_declaration_return_values(n *ast.FuncType) []chanRetNil {
astResult := n.Results
// do nothing if the functions does not have return values
if astResult == nil {
return []chanRetNil{}
}
r := make([]chanRetNil, 0)
// traverse all return types
for i, res := range n.Results.List {
switch res.Type.(type) {
case *ast.ChanType: // do not call continue if channel
default:
continue // continue if not a channel
}
translated_string := ""
name := get_name(res.Type.(*ast.ChanType).Value)
translated_string = "dedego.Chan[" + name + "]"
r = append(r, chanRetNil{i, translated_string})
// set the translated value
n.Results.List[i] = &ast.Field{
Type: &ast.Ident{
Name: translated_string,
},
}
}
return r
}
/*
Function to instrument the parameter value of functions if they contain a chan.
@param n *ast.FuncType: node of the func type in the ast
*/
func instrument_function_declaration_parameter(n *ast.FuncType) {
astParam := n.Params
// do nothing if the functions does not have return values
if astParam == nil {
return
}
// traverse all parameters
for i, res := range astParam.List {
switch res.Type.(type) {
case *ast.ChanType: // do not call continue if channel
default:
continue // continue if not a channel
}
translated_string := ""
switch v := res.Type.(*ast.ChanType).Value.(type) {
case *ast.Ident: // chan <type>
translated_string = "dedego.Chan[" + v.Name + "]"
case *ast.StructType:
translated_string = "dedego.Chan[struct{}]"
case *ast.ArrayType:
translated_string = "dedego.Chan[[]" + get_name(v.Elt) + "]"
}
// set the translated value
n.Params.List[i] = &ast.Field{
Names: n.Params.List[i].Names,
Type: &ast.Ident{
Name: translated_string,
},
}
}
}
/*
Insturment receive with assign
@param n *ast.AssignStmt: assign statment
@param c *astutil.Cursor: ast cursor
*/
func instrument_receive_with_assign(n *ast.AssignStmt, c *astutil.Cursor) {
if n.Rhs[0].(*ast.UnaryExpr).Op != token.ARROW {
return
}
variable := get_name(n.Lhs[0])
receiveStmt := ".Receive"
if len(n.Lhs) > 1 {
variable += ", " + get_name(n.Lhs[1])
receiveStmt = ".ReceiveOk"
}
channel := get_name(n.Rhs[0].(*ast.UnaryExpr).X)
token := n.Tok
c.Replace(&ast.AssignStmt{
Lhs: []ast.Expr{
&ast.Ident{
Name: variable,
},
},
Tok: token,
Rhs: []ast.Expr{
&ast.CallExpr{
Fun: &ast.Ident{
Name: channel + receiveStmt,
},
},
},
})
}
// instrument creation of struct
func instrument_assign_struct(n *ast.AssignStmt) {
for i, t := range n.Rhs[0].(*ast.CompositeLit).Elts {
switch t.(type) {
case *(ast.KeyValueExpr):
default:
continue
}
switch t.(*ast.KeyValueExpr).Value.(type) {
case *ast.CallExpr:
default:
continue
}
t_type := t.(*ast.KeyValueExpr).Value.(*ast.CallExpr)
if get_name(t_type.Fun) != "make" {
continue
}
switch t_type.Args[0].(type) {
case *ast.ChanType:
default:
continue
}
name := get_name(t_type.Args[0].(*ast.ChanType).Value)
size := "0"
if len(t_type.Args) > 1 {
size = get_name(t_type.Args[1])
}
n.Rhs[0].(*ast.CompositeLit).Elts[i].(*ast.KeyValueExpr).Value.(*ast.CallExpr).Fun = &ast.Ident{Name: "dedego.NewChan[" + name + "]"}
n.Rhs[0].(*ast.CompositeLit).Elts[i].(*ast.KeyValueExpr).Value.(*ast.CallExpr).Args = []ast.Expr{&ast.Ident{Name: size}}
}
}
// instrument range over channel
func instrument_range_stm(n *ast.RangeStmt) {
// switch n.Rhs[0].Body.List
get_info_string := "_.GetInfo()"
varName := get_name(n.Key)
if strings.Contains(varName, ",") {
get_info_string = "_.GetInfoOk()"
}
if n.Key.(*ast.Ident).Obj == nil {
return
}
switch n.Key.(*ast.Ident).Obj.Decl.(type) {
case *ast.AssignStmt:
default:
return
}
l := n.Key.(*ast.Ident).Obj.Decl.(*ast.AssignStmt).Lhs
if len(l) != 1 {
return
}
r := n.Key.(*ast.Ident).Obj.Decl.(*ast.AssignStmt).Rhs[0]
switch r.(type) {
case *ast.UnaryExpr:
default:
return
}
chanName := get_name(r.(*ast.UnaryExpr).X)
switch x := n.X.(type) {
case *ast.Ident:
switch d := x.Obj.Decl.(type) {
case *ast.AssignStmt:
switch r := d.Rhs[0].(type) {
case *ast.CallExpr:
switch f := r.Fun.(type) {
case *ast.IndexExpr:
switch x1 := f.X.(type) {
case *ast.SelectorExpr:
switch x2 := x1.X.(type) {
case *ast.Ident:
if x2.Name == "dedego" {
n.Key.(*ast.Ident).Name = varName + "_"
n.X = &ast.Ident{Name: chanName + ".GetChan()"}
n.Body.List = append([]ast.Stmt{
&ast.ExprStmt{
X: &ast.Ident{Name: chanName + ".Post(false, " + varName + "_)"},
},
&ast.ExprStmt{
X: &ast.Ident{Name: varName + " := " + varName + get_info_string},
},
},
n.Body.List...)
}
}
}
case *ast.Ident:
if strings.HasPrefix(f.Name, "dedego.NewChan") {
n.Key.(*ast.Ident).Name = varName + "_"
n.X = &ast.Ident{Name: chanName + ".GetChan()"}
n.Body.List = append([]ast.Stmt{
&ast.ExprStmt{
X: &ast.Ident{Name: chanName + ".Post(false, " + varName + "_)"},
},
&ast.ExprStmt{
X: &ast.Ident{Name: varName + " := " + varName + get_info_string},
},
},
n.Body.List...)
}
}
}
}
}
}
func instrument_nil_assign(n *ast.AssignStmt, astSet *token.FileSet) {
switch n.Rhs[0].(type) {
case *ast.Ident:
default:
return
}
if get_name(n.Rhs[0]) != "nil" {
return
}
buf := new(bytes.Buffer)
name := ""
for _, line := range strings.Split(buf.String(), "\n") {
if strings.Contains(line, "dedego.Chan") {
name_split := strings.Split(line, "\"")
if len(name_split) > 1 {
name = name_split[1]
break
}
}
}
if name != "" {
n.Rhs[0].(*ast.Ident).Name = name + "{}"
}
}
/*
instrument the call expression. This contains instrumentation of make and
library function calls
@params callExp: the call expression to instrument
@params c: the cursor
@params astSet: the ast file set
@params imports: list of imported libraries
*/
func instrument_call_expressions(callExp *ast.CallExpr, c *astutil.Cursor,
astSet *token.FileSet, imports []string) {
switch callExp.Fun.(type) {
case *ast.Ident:
instrument_make(callExp)
case *ast.SelectorExpr:
instrument_library_function_call(callExp, c, astSet, imports)
}
}
/*
instrument the make of a channel
@params callExp: the call expression to instrument
*/
func instrument_make(callExp *ast.CallExpr) {
// don't change call expression of non-make function
if get_name(callExp.Fun) == "make" {
switch callExp.Args[0].(type) {
// make creates a channel
case *ast.ChanType:
callExpVal := callExp.Args[0].(*ast.ChanType).Value
chanType := get_name(callExpVal)
// set size of channel
chanSize := "0"
if len(callExp.Args) >= 2 {
switch args_type := callExp.Args[1].(type) {
case *ast.BasicLit:
chanSize = args_type.Value
case *ast.Ident:
chanSize = args_type.Name
}
}
// set function name to dedego.NewChan[<chanType>]
callExp.Fun.(*ast.Ident).Name = "dedego.NewChan[" + chanType + "]"
// remove second argument if size was given in make
if len(callExp.Args) >= 1 {
callExp.Args = callExp.Args[:1]
}
// set function argument to channel size
callExp.Args[0] = &ast.BasicLit{Kind: token.INT, Value: "int(" + chanSize + ")"}
}
}
}
/*
instrument a function call of a library function
@params n: the call expression to instrument
@params c: the cursor
@params astSet: the ast file set
@params imports: list of imported libraries
*/
func instrument_library_function_call(n *ast.CallExpr, c *astutil.Cursor,
astSet *token.FileSet, imports []string) {
// check if function call has selector
switch n.Fun.(type) {
case *ast.SelectorExpr:
default:
return
}
sel := n.Fun.(*ast.SelectorExpr)
// check if selector is in imports
name := get_name(sel.X)
// check if selector is in imports
for _, imp := range imports {
if name != imp {
continue
}
if n.Args == nil {
return
}
// check find args with type chan
var channels []string
var types []string
var sizes []string
for i, arg := range n.Args {
switch arg_type := arg.(type) {
case *ast.Ident:
if arg_type.Obj == nil || arg_type.Obj.Decl == nil {
continue
}
decl := arg_type.Obj.Decl
switch decl_type := decl.(type) {
case *ast.AssignStmt:
decl_name := get_name(decl_type.Rhs[0])
if len(decl_name) >= 14 && decl_name[:14] == "dedego.NewChan" {
chanName := get_name(decl_type.Lhs[0])
chanType := strings.Split(decl_name[15:], "]")[0]
decl_val := decl_type.Rhs[0].(*ast.CallExpr).Args[0].(*ast.BasicLit).Value
chanSize := decl_val[4 : len(decl_val)-1]
channels = append(channels, chanName)
types = append(types, chanType)
sizes = append(sizes, chanSize)
n.Args[i] = &ast.Ident{Name: chanName + "_dedego"}
}
case *ast.UnaryExpr:
panic("TODO: Implement unary expression") // TODO: Implement unary expression
default:
continue
}
}
}
if len(channels) == 0 {
continue
}
// get string representation of function
buf := new(bytes.Buffer)
printer.Fprint(buf, astSet, n)
replacement_string := "{\n"
for i, channel := range channels {
replacement_string += channel + "_dedego := make(chan " +
types[i] + ", " + sizes[i] + ")\n"
replacement_string += "go func() {\n"
replacement_string += "for {\n"
replacement_string += "select {\n"
replacement_string += "case " + "dedego_case := <- " + channel +
"_dedego:\n" + channel + ".Send(dedego_case)\n"
replacement_string += "case dedego_case := <-" + channel +
".GetChan():\n" + channel + ".Post(true, dedego_case)\n" +
channel + "_dedego <- dedego_case.GetInfo()\n"
replacement_string += "}\n"
replacement_string += "if " + channel + ".IsClosed(){\nbreak\n}}}()\n"
}
replacement_string += buf.String() + "\n"
replacement_string += "}"
c.Replace(&ast.Ident{
Name: replacement_string,
})
}
}
// instrument a send statement
func instrument_send_statement(n *ast.SendStmt, c *astutil.Cursor) {
// get the channel name
channel := get_name(n.Chan)
value := ""
// get what is send through the channel
v := n.Value
// fmt.Printf("%T\n", v)
call_expr := false
func_lit := false
switch lit := v.(type) {
case (*ast.BasicLit):
value = lit.Value
case (*ast.Ident):
value = lit.Name
case (*ast.CallExpr):
call_expr = true
case *ast.ParenExpr:
value = n.Chan.(*ast.Ident).Obj.Decl.(*ast.Field).Type.(*ast.ChanType).Value.(*ast.Ident).Name
case *ast.CompositeLit:
switch lit_type := lit.Type.(type) {
case *ast.StructType:
value = "struct{}{}"
case *ast.ArrayType:
value = "[]" + get_name(lit_type.Elt) + "{" + get_name(lit.Elts[0]) + "}"
case *ast.Ident:
value = get_name(lit_type) + "{}"
}
case *ast.SelectorExpr:
value = get_selector_expression_name(lit)
case *ast.UnaryExpr:
arg_string := ""
switch x := lit.X.(type) {
case *ast.CompositeLit:
for _, a := range x.Elts {
arg_string += get_name(a) + ","
}
switch t_type := x.Type.(type) {
case *ast.Ident:
value = lit.Op.String() + t_type.Name + "{" + arg_string + "}"
case *ast.SelectorExpr:
value = lit.Op.String() + get_selector_expression_name(t_type) + "{" + arg_string + "}"
}
}
case *ast.FuncLit:
func_lit = true
case *ast.IndexExpr:
value = get_name(lit.X) + "[" + get_name(lit.Index)
default:
errString := fmt.Sprintf("Unknown type %T in instrument_send_statement2", v)
panic(errString)
}
// replace with function call
if call_expr {
c.Replace(&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: &ast.Ident{
Name: channel,
},
Sel: &ast.Ident{
Name: "Send",
},
},
Lparen: token.NoPos,
Args: []ast.Expr{
v.(*ast.CallExpr),
},
},
})
} else if func_lit {
c.Replace(&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: &ast.Ident{
Name: channel,
},
Sel: &ast.Ident{
Name: "Send",
},
},
Lparen: token.NoPos,
Args: []ast.Expr{
v.(*ast.FuncLit),
},
},
})
} else {
c.Replace(&ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: &ast.Ident{
Name: channel,
},
Sel: &ast.Ident{
Name: "Send",
},
},
Lparen: token.NoPos,
Args: []ast.Expr{
&ast.Ident{
Name: value,
},
},
},
})
}
}
// instrument receive and call statements
func instrument_expression_statement(n *ast.ExprStmt, c *astutil.Cursor) {
x_part := n.X
switch x_part.(type) {
case *ast.UnaryExpr:
instrument_receive_statement(n, c)
case *ast.CallExpr:
instrument_close_statement(n, c)
case *ast.TypeAssertExpr, *ast.Ident:
default:
errString := fmt.Sprintf("Unknown type %T in instrument_expression_statement", x_part)
panic(errString)
}
}
// instrument defer state,emt
func instrument_defer_statement(n *ast.DeferStmt, c *astutil.Cursor) {
x_call := n.Call.Fun
switch fun_type := x_call.(type) {
case *ast.Ident:
if fun_type.Name == "close" && len(n.Call.Args) > 0 {
name := get_name(n.Call.Args[0])
c.Replace(&ast.DeferStmt{
Call: &ast.CallExpr{
Fun: &ast.Ident{
Name: name + ".Close",
},
},
})
}
}
}
// instrument receive statements
func instrument_receive_statement(n *ast.ExprStmt, c *astutil.Cursor) {
x_part := n.X.(*ast.UnaryExpr)
// check if correct operation
if x_part.Op != token.ARROW {
return
}
if is_time_element(x_part) {
return
}
// get channel name
var channel string
switch x_part_x := x_part.X.(type) {
case *ast.Ident:
channel = x_part_x.Name
case *ast.CallExpr:
channel = get_name(x_part_x)
case *ast.SelectorExpr:
channel = get_selector_expression_name(x_part_x)
default:
errString := fmt.Sprintf("Unknown type %T in instrument_receive_statement", x_part)
panic(errString)
}
if !(len(channel) > 11 && channel[:11] == "time.After(") {