-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSurku.js
executable file
·339 lines (320 loc) · 10.4 KB
/
Surku.js
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
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const Surku = function (user_config) {
this.m = require("./mersenne-twister.js");
const mutators = require("./mutators.js");
this.mutators = mutators;
const self = this;
// eslint-disable-next-line no-control-regex
const stringCheckRegExp = /[\u0000-\u0005]+/;
// eslint-disable-next-line no-control-regex
const isNonNullRegExp = /[^\u0000-\u0005]+/;
const config = {
maxMutations: 20,
minMutations: 1,
chunkSize: 3000,
useOnly: undefined,
seed: undefined,
verbose: undefined,
};
this.config = config;
if (user_config !== undefined) {
for (const key in user_config) this.config[key] = user_config[key];
}
if (
this.config.useOnly !== undefined &&
this.config.useOnly instanceof Array
) {
mutators.useOnlyMutators(this.config.useOnly);
}
this.ra = function (array) {
if (Array.isArray(array)) return array[this.rint(array.length)];
console.error("ra: called with non-array");
console.error(array);
return false;
};
this.rint = function (max) {
if (max || max === 0) {
const rintOutput = Math.floor(this.r.genrand_real1() * max);
if (Number.isNaN(rintOutput))
console.error(
`rint: called with non-number ${max} results to ${rintOutput}`
);
return rintOutput;
}
console.error(`rint: called with ${max}`);
return false;
};
this.wrint = function (max) {
if (max === undefined) max = 2000;
const num = this.r.genrand_real1() * 3;
const div = this.r.genrand_real1() + Number.MIN_VALUE; // Avoid divide by zero.
return (Math.floor(num / div) ? Math.floor(num / div) : 1) % max;
};
const seedBase = this.m.newMersenneTwister(self.config.seed);
this.seedBase = seedBase;
this.generateTestCase = function (input) {
this.config = self.config;
this.storage = self.storage;
this.debugPrint = function (message, level) {
if (
self.config.hasOwnProperty("verbose") &&
self.config.verbose >= level
) {
process.stderr.write(message);
}
};
this.ra = self.ra;
this.rint = self.rint;
this.r = self.m.newMersenneTwister(seedBase.genrand_int31());
return mutate.call(this, input);
};
//
// Hold kind of linked list of stored data
//
/*
storage:{
where:[
[key1,key2],
[[key1value1,key1value2],[key2value2]]
]
}
*/
this.storage = {
lastChunks: [],
maxKeys: 100,
maxValues: 30,
maxChunks: 10,
valueStorages: {},
storeKeyValuePair(keyValueArray, where) {
// Check if valueStorage name was provided
const key = keyValueArray[0];
const value = keyValueArray[1];
let storageObject;
// if(process.memoryUsage().heapUsed<700*1024*1024){
if (where === undefined) where = "defaultStorage";
// If valueStorage named with value of where exists use it, else create empty one.
if (this.valueStorages.hasOwnProperty(where))
storageObject = this.valueStorages[where];
else {
this.valueStorages[where] = [[], []];
storageObject = this.valueStorages[where];
}
// Check that keyValueArray is an Array with length 2 so that storage will stay in sync.
if (keyValueArray instanceof Array && keyValueArray.length == 2) {
// Look from valueStorage[where] if key exists, if it does save into keys index on values array.
// Check that size of storage is not exceeded from unshift return value.
const index = storageObject[0].indexOf(key);
if (index !== -1) {
if (storageObject[1][index].unshift(value) > this.maxValues) {
storageObject[1][index].pop();
}
} else {
if (storageObject[0].unshift(key) > this.maxKeys) {
storageObject[0].pop();
storageObject[1].pop();
}
storageObject[1].unshift([value]);
}
} else {
console.log(
`Invalid input to storeKeyValue. Must be Array [key,value] got ${keyValueArray}`
);
}
/* }else{
console.log('Memory consumption high. Skipping saves to storage.')
} */
},
getValueForKey(key, where) {
let storageObject;
if (where === undefined) where = "defaultStorage";
if (this.valueStorages.hasOwnProperty(where))
storageObject = this.valueStorages[where];
else return false;
const index = storageObject[0].indexOf(key);
if (index !== -1) return self.ra(storageObject[1][index]);
return false;
},
pushNewChunk(chunk) {
if (this.lastChunks.unshift({ data: chunk }) > this.maxChunks) {
this.lastChunks.pop();
}
},
getChunk() {
return self.ra(this.lastChunks);
},
};
function splitToChunks(input) {
if (input.length > config.chunkSize) {
const inputLength = input.length;
let index = 0;
let count = 0;
const tmp = [];
for (; index < inputLength - config.chunkSize; count++)
tmp[count] = input.slice(
index,
(index += Math.floor(Math.random() * 1000) + 1)
);
tmp[count] = input.slice(index, inputLength);
return tmp;
}
return [input];
}
//
// mutate(input)
// input: Data to be mutated
//
// Selects amount of mutations to be done based on config.maxMutations and config.minMutations
// Takes data chunk size of config.chunkSize from random location inside the input data and applies mutators.
//
function mutate(input) {
let string = true;
if (input instanceof Buffer) {
string = false;
input = input.toString("binary");
} else if (!(input instanceof String || typeof input === "string")) {
console.log("Wrong input format. Must be String or Buffer!");
return input;
}
input = splitToChunks(input);
// console.log('Chunks: '+input.length)
if (input.length !== 0) {
let mutations;
if (this.config.maxMutations === this.config.minMutations)
mutations = this.config.maxMutations;
else if (this.config.maxMutations !== undefined)
mutations =
this.wrint(this.config.maxMutations - this.config.minMutations) -
1 +
this.config.minMutations;
else
mutations = this.config.minMutations
? this.config.minMutations + this.wrint(100)
: this.wrint(100);
let index;
let mutator;
let chunk;
let isString;
let result = false;
this.debugPrint(`Start: ${process.memoryUsage().heapUsed}\n`, 1);
while (mutations--) {
this.debugPrint(`Round: ${process.memoryUsage().heapUsed}\n`, 1);
index = 0;
chunk = "";
if (input.length > 1) {
let tries = 10;
while (tries--) {
index = this.rint(input.length);
if (isNonNullRegExp.test(input[index])) break;
}
let length = 0;
let chunks = 0;
while (length < config.chunkSize) {
length += input[index + chunks].length;
chunks++;
if (index + chunks >= input.length) {
break;
}
}
chunk = input.splice(index, chunks).join("");
} else {
chunk = input.splice(0, 1).join("");
}
isString = !stringCheckRegExp.test(chunk);
let tryCount = 10;
result = false;
if (chunk.length > 0) {
if (this.storage.lastChunks.length === 0 || !this.rint(5))
this.storage.pushNewChunk(chunk);
while (tryCount--) {
mutator = this.ra(mutators.mutators);
this.debugPrint(`Mutator: ${mutator.mutatorFunction.name} - `, 1);
if (
!mutator.stringOnly ||
(mutator.stringOnly && isString) ||
!this.rint(3)
) {
result = mutator.mutatorFunction.call(this, chunk, isString);
if (result === false) this.debugPrint("Fail\n", 1);
} else {
this.debugPrint("Fail\n", 1);
result = false;
}
if (result !== false) break;
}
} else if (input.length === 0 || input[0].length === 0) {
break;
}
if (result !== false) {
this.debugPrint("Success\n", 1);
Array.prototype.splice.apply(
input,
[index, 0].concat(splitToChunks(result))
);
}
}
this.debugPrint(`End: ${process.memoryUsage().heapUsed}\n`, 1);
input = input.join("");
if (string) return input;
return Buffer.from(input, "binary");
}
this.debugPrint("Mutate Error: Zero-sized input.");
return input;
}
return this;
};
//
// Commandline interface wrapper.
//
// TODO: Investigate if file could be read as a Stream and mutated with just a single chunk in memory.
if (require.main === module) {
const config = require("./cmd.js");
let samples;
const debugPrint = function (message, level) {
if (config.hasOwnProperty("verbose") && config.verbose >= level) {
process.stderr.write(message);
}
};
debugPrint("Initializing Surku with config:\n", 5);
if (config.verbose >= 5) console.log(config);
const S = new Surku(config);
if (config.inputPath) samples = fs.readdirSync(config.inputPath);
else if (config.inputFile) {
config.inputPath = "";
samples = config.inputFile;
}
const sampleSelectorRandom = S.m.newMersenneTwister(
S.seedBase.genrand_int31()
);
let output = {};
let fileName = "";
if (config.outputName !== undefined) {
fileName = config.outputName.split("%n");
}
for (let x = 0; x < config.count; x++) {
const random = sampleSelectorRandom.genrand_real1();
const index = Math.floor(random * samples.length);
let sample = samples[index];
if (config.inputPath) sample = path.join(config.inputPath, sample);
debugPrint(`Input file: ${sample}\n`, 5);
if (fs.statSync(sample).isDirectory()) {
x--;
samples.splice(index, 1);
if (samples.length === 0) {
console.log("Input folder doesn't contain any files");
process.exit(2);
}
} else {
output = S.generateTestCase(fs.readFileSync(sample));
if (fileName === "") console.log(output.toString());
else {
debugPrint(`Output file: ${fileName.join(x)}\n`);
debugPrint(`Output file size: ${output.length}\n`);
fs.writeFileSync(fileName.join(x), output);
}
}
}
} else {
module.exports = Surku;
}