forked from go-gremlins/gremlins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenmutator.go
327 lines (272 loc) · 7.82 KB
/
tokenmutator.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
/*
* Copyright 2022 The Gremlins Authors
*
* 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
*
* http://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.
*/
package engine
import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
"os"
"os/exec"
"path/filepath"
"sync"
"syscall"
"github.com/singhnishant94/gremlins/internal/mutator"
)
// TokenMutator is a mutator.Mutator of a token.Token.
//
// Since the AST is shared among mutants, it is important to avoid that more
// than one mutation is applied to the same file before writing it. For this
// reason, TokenMutator contains a cache of locks, one for each file.
// Every time a mutation is about to being applied, a lock is acquired for
// the file it is operating on. Once the file is written and the token is
// rolled back, the lock is released.
// Keeping a lock per file instead of a lock per TokenMutator allows to apply
// mutations on different files in parallel.
type TokenMutator struct {
pkg string
fs *token.FileSet
file *ast.File
tokenNode *NodeToken
workDir string
origFile []byte
status mutator.Status
mutantType mutator.Type
actualToken token.Token
diff string
testExecErr error
}
// NewTokenMutant initialises a TokenMutator.
func NewTokenMutant(pkg string, set *token.FileSet, file *ast.File, node *NodeToken) *TokenMutator {
return &TokenMutator{
pkg: pkg,
fs: set,
file: file,
tokenNode: node,
}
}
// Type returns the mutator.Type of the mutant.Mutator.
func (m *TokenMutator) Type() mutator.Type {
return m.mutantType
}
// SetType sets the mutator.Type of the mutant.Mutator.
func (m *TokenMutator) SetType(mt mutator.Type) {
m.mutantType = mt
}
// Status returns the mutator.Status of the mutant.Mutator.
func (m *TokenMutator) Status() mutator.Status {
return m.status
}
// SetStatus sets the mutator.Status of the mutant.Mutator.
func (m *TokenMutator) SetStatus(s mutator.Status) {
m.status = s
}
// Position returns the token.Position where the TokenMutator resides.
func (m *TokenMutator) Position() token.Position {
return m.fs.Position(m.tokenNode.TokPos)
}
// Pos returns the token.Pos where the TokenMutator resides.
func (m *TokenMutator) Pos() token.Pos {
return m.tokenNode.TokPos
}
// Diff returns the diff between the original and the mutation.
func (m *TokenMutator) Diff() string {
return m.diff
}
// SetDiff sets the diff between the original and the mutation.
func (m *TokenMutator) SetDiff(d string) {
m.diff = d
}
// Pkg returns the package name to which the mutant belongs.
func (m *TokenMutator) Pkg() string {
return m.pkg
}
// Apply saves the original token.Token of the mutator.Mutator and sets the
// current token from the tokenMutations table.
// Apply overwrites the source code file with the mutated one. It also
// stores the original file in the TokenMutator in order to allow
// Rollback to put it back later.
//
// Apply also puts back the original Token after the mutated file write.
// This is done in order to facilitate the atomicity of the operation,
// avoiding locking in a method and unlocking in another.
func (m *TokenMutator) Apply() error {
fileLock(m.Position().Filename).Lock()
defer fileLock(m.Position().Filename).Unlock()
filename := filepath.Join(m.workDir, m.Position().Filename)
var err error
m.origFile, err = os.ReadFile(filename)
if err != nil {
return err
}
// Create a copy of the original file to calculate the diff later.
copyOrigFileName := filepath.Join(m.workDir, m.Position().Filename+".copy.orig")
if err = m.writeMutatedFile(copyOrigFileName); err != nil {
return err
}
var oldX ast.Expr
var oldY ast.Expr
switch m.Type() {
case mutator.RemoveBinaryExpressionLeft:
n, ok := (*m.tokenNode.node).(*ast.BinaryExpr)
if !ok {
return nil
}
if n.Op != token.LAND && n.Op != token.LOR {
return nil
}
var r *ast.Ident
switch n.Op {
case token.LAND:
r = ast.NewIdent("true")
case token.LOR:
r = ast.NewIdent("false")
}
oldX = n.X
n.X = r
case mutator.RemoveBinaryExpressionRight:
n, ok := (*m.tokenNode.node).(*ast.BinaryExpr)
if !ok {
return nil
}
if n.Op != token.LAND && n.Op != token.LOR {
return nil
}
var r *ast.Ident
switch n.Op {
case token.LAND:
r = ast.NewIdent("true")
case token.LOR:
r = ast.NewIdent("false")
}
oldY = n.Y
n.Y = r
default:
m.actualToken = m.tokenNode.Tok()
m.tokenNode.SetTok(tokenMutations[m.Type()][m.tokenNode.Tok()])
}
if err = m.writeMutatedFile(filename); err != nil {
return err
}
// Rollback here to facilitate the atomicity of the operation.
switch m.Type() {
case mutator.RemoveBinaryExpressionLeft:
n, ok := (*m.tokenNode.node).(*ast.BinaryExpr)
if !ok {
return nil
}
if n.Op != token.LAND && n.Op != token.LOR {
return nil
}
n.X = oldX
case mutator.RemoveBinaryExpressionRight:
n, ok := (*m.tokenNode.node).(*ast.BinaryExpr)
if !ok {
return nil
}
if n.Op != token.LAND && n.Op != token.LOR {
return nil
}
n.Y = oldY
default:
m.tokenNode.SetTok(m.actualToken)
}
m.SetDiff(m.calcDiff(copyOrigFileName, filename))
// Remove the copy of the original file.
os.Remove(copyOrigFileName)
return nil
}
func (m *TokenMutator) writeMutatedFile(filename string) error {
w := &bytes.Buffer{}
err := printer.Fprint(w, m.fs, m.file)
if err != nil {
return err
}
err = os.WriteFile(filename, w.Bytes(), 0600)
if err != nil {
return err
}
return nil
}
func (m *TokenMutator) calcDiff(origFile, mutationFile string) string {
diff, err := exec.Command("diff", "--label=Original", "--label=New", "-u", origFile, mutationFile).CombinedOutput()
var execExitCode int
if err == nil {
execExitCode = 0
} else if e, ok := err.(*exec.ExitError); ok {
execExitCode = e.Sys().(syscall.WaitStatus).ExitStatus()
} else {
panic(err)
}
if execExitCode != 0 && execExitCode != 1 {
fmt.Printf("%s\n", diff)
panic("Could not execute diff on mutation file")
}
return string(diff)
}
var locks = make(map[string]*sync.Mutex)
var mutex sync.RWMutex
func fileLock(filename string) *sync.Mutex {
lock, ok := cachedLock(filename)
if !ok {
mutex.Lock()
defer mutex.Unlock()
lock, ok = locks[filename]
if !ok {
lock = &sync.Mutex{}
locks[filename] = lock
return lock
}
return lock
}
return lock
}
func cachedLock(filename string) (*sync.Mutex, bool) {
mutex.RLock()
defer mutex.RUnlock()
lock, ok := locks[filename]
return lock, ok
}
// Rollback puts back the original file after the test and cleans up the
// TokenMutator to free memory.
func (m *TokenMutator) Rollback() error {
defer m.resetOrigFile()
filename := filepath.Join(m.workDir, m.Position().Filename)
return os.WriteFile(filename, m.origFile, 0600)
}
func (m *TokenMutator) SetTestExecutionError(err error) {
m.testExecErr = err
}
func (m *TokenMutator) TestExecutionError() error {
return m.testExecErr
}
// SetWorkdir sets the base path on which to Apply and Rollback operations.
//
// By default, TokenMutator will operate on the same source on which the analysis
// was performed. Changing the workdir will prevent the modifications of the
// original files.
func (m *TokenMutator) SetWorkdir(path string) {
m.workDir = path
}
// Workdir returns the current working dir in which the Mutator will apply its mutations.
func (m *TokenMutator) Workdir() string {
return m.workDir
}
func (m *TokenMutator) resetOrigFile() {
var zeroByte []byte
m.origFile = zeroByte
}