-
Notifications
You must be signed in to change notification settings - Fork 10
/
deadcode.go
85 lines (72 loc) · 1.72 KB
/
deadcode.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
package main
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"math/rand"
log "github.com/sirupsen/logrus"
"golang.org/x/tools/go/ast/astutil"
)
func generateDeadCode() ([]ast.Stmt, error) {
xMin := 1
xMax := 10
zXXXinit := rand.Intn(xMax-xMin+1) + xMin
sXXXinit := rand.Intn(xMax-xMin+1) + xMin
iXXXinit := rand.Intn(xMax-xMin+1) + xMin
// BUG : need to have it in anonymous function otherwwise
// loop-obfuscator fails
src := fmt.Sprintf(`
package main
func SOMEDEADCODE() {
(func() {
zXXX := int64(%d)
sXXX := float64(%d)
for iXXX := %d; iXXX < 15; iXXX++ {
for jXXX := iXXX; jXXX < 15; jXXX++ {
for zXXX := jXXX; zXXX < 15; zXXX++ {
sXXX = (float64(iXXX+ jXXX) * float64(zXXX)) / float64(iXXX);
}
}
}
if sXXX == float64(zXXX) {
;
}
})()
}`, zXXXinit, sXXXinit, iXXXinit)
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, 0)
if err != nil {
return nil, err
}
// Extract function from Decls
funcDecl, ok := f.Decls[0].(*ast.FuncDecl)
if !ok {
return nil, errors.New("failed to cast funcDecl")
}
return funcDecl.Body.List, nil
}
func injectDeadcode(fset *token.FileSet, pkgs map[string]*ast.Package) error {
deadcodeAST, err := generateDeadCode()
if err != nil {
return err
}
for _, pkg := range pkgs {
for _, fileast := range pkg.Files {
astutil.Apply(fileast, func(cr *astutil.Cursor) bool {
cn, ok := cr.Node().(*ast.FuncDecl)
if !ok {
return true
}
if *verbose {
log.Printf("Adding deadcode to %s", cn.Name.Name)
}
cn.Body.List = append(deadcodeAST, cn.Body.List...)
return true
}, nil)
}
}
return nil
}