-
Notifications
You must be signed in to change notification settings - Fork 1
/
ACGParseUtils.ts
247 lines (202 loc) · 9.09 KB
/
ACGParseUtils.ts
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
import * as fs from 'fs';
import * as babel from '@babel/types';
import {parse} from '@babel/parser';
import { default as generate } from '@babel/generator';
/*
Get an appropriate name from the UID. Appropriate for both variable
and file names.
*/
export function buildHappyName(sad : string) {
let happyName = "";
/* sanitize sad */
sad = sad.replace(/\./g, 'dot').replace(/-/g, 'dash');
/* take: acorn/src/location.js:<12,11>--<18,1>
make: acorn_src_location_12_11_18_1
*/
let split : string[] = sad.split(/.js:<|.ts:</);
if (split.length < 2) {
return sad;
}
// Do first part: acorn_src_location_
happyName += split[0].replace(/\//g, '_') + '_';
// Do row cols: 12_11_18_1
happyName += split[1].substring(0, split[1].length - 1).replace(/,/g, '_').replace('>dashdash<', '_');
return happyName;
}
/* Adjust the LOC (from the ACG, from QL) to match Babel.
Code documented by example, see below. */
function adjustLOC(locAsString : string) : string {
/* Fun(/opt/src/acorn/src/location.js:<12,12>--<18,1>)
want
acorn/src/location.js:<12,11>--<18,1>
note the -1 on the first column
*/
/* get /opt/src/acorn/src/location.js:<12,12>--<18,1> */
let adjustedLOC = locAsString.substring(4, locAsString.length - 1);
/* trim up to package root (by removing /opt/src/)
get acorn/src/location.js:<12,12>--<18,1> */
// adjustedLOC = adjustedLOC.substring("/opt/src/".length, adjustedLOC.length);
/* adjust column number
get acorn/src/location.js:<12,11>--<18,1> */
let firstIndex = adjustedLOC.indexOf(":<") + ":<".length;
let secondIndex = adjustedLOC.indexOf(">--<");
let firstRowCol : string[] = adjustedLOC.substring(firstIndex, secondIndex).split(',');
firstRowCol[1] = String(Number(firstRowCol[1]) - 1);
adjustedLOC = adjustedLOC.substring(0, firstIndex) + firstRowCol[0] + ',' + firstRowCol[1] +
adjustedLOC.substring(secondIndex);
return adjustedLOC;
}
/*
Parse an Approximate Call Graph (ACG) .csv file, and produce a string[] with
file and source information for calls which the ACG picked up on.
Note: You may want to cross-reference this list with a list of callable functions, probably.
*/
export function getTargetsFromACG(filepath : string) : string[] {
let unprocessedCG : string[] = fs.readFileSync(filepath, 'utf-8').split('\n');
/* remove header */
unprocessedCG.shift();
let targets : string[] = unprocessedCG.map((line : string) => {
line = line.substr(1, line.length - 2);
let target = line.split('\",\"')[1];
if (!target || target.substr(0, 3) != 'Fun') {
return "";
}
return adjustLOC(target);
})
let partialRet : string[] = targets.filter((line : string) => {
return line != "";
});
/*
let mapObj = {};
// construct return map
partialRet.forEach(s => {
mapObj[s] = "";
});
return new Map(Object.entries(mapObj));
*/
return partialRet;
}
function getUncoveredFunctions(pathToCoverageReport : string) : string[] {
const coverage = require(pathToCoverageReport);
const calledFunctions = [];
const uncalledFunctions = [];
Object.keys(coverage).forEach((fileName) => {
Object.keys(coverage[fileName].fnMap).forEach((key) => {
if(coverage[fileName].f[key] > 0) {
const loc = coverage[fileName].fnMap[key].loc;
calledFunctions.push(
`${fileName}:<${loc.start.line},${loc.start.column}>--<${loc.end.line},${loc.end.column}>`
)
} else {
const loc = coverage[fileName].fnMap[key].loc;
uncalledFunctions.push(
`${fileName}:<${loc.start.line},${loc.start.column}>--<${loc.end.line},${loc.end.column}>`
)
}
});
});
// console.log(calledFunctions);
// console.log(uncalledFunctions);
return calledFunctions;
}
/*
[
'Fun(/Users/Alexi/Documents/Projects/JSTransformationBenchmarks/razorpay-node/distrazorpay.js:<16,11>--<19,5>)',
...
]
*/
export function getTargetsFromCoverageReport(filepath : string) : string[] {
let uncoveredFunctions : string[] = getUncoveredFunctions(filepath);
return uncoveredFunctions;
}
export function getFileName(target: string): string {
return target.split(":")[0];
}
export function buildEvalCheck( callExpNode: babel.CallExpression, inAsyncFct: boolean, filename: string): babel.CallExpression {
// if ( callee === eval ) { console.warn("BTW dangerous call"); }
// "let dangerousFunctions = [eval, process.exec];"
// ( () => let tempExp__uniqID = callee; if( tempExp__uniqID === eval) { console.warn("uh oh"); } return tempExp__uniqID; )()
let tempVarID: babel.Identifier = babel.identifier("tempExp__uniqID");
let tempVarDecl: babel.VariableDeclaration = babel.variableDeclaration("let", [babel.variableDeclarator(tempVarID, <any>callExpNode.callee)]);
let tempVarDecls : babel.Statement[] = [tempVarDecl];
if (callExpNode.callee.type == "MemberExpression" && ( callExpNode.callee.property.type == "Identifier" || callExpNode.callee.property.type == "PrivateName")) {
// If it's a memberExpression, we want to save the receiver.
let tempReceiverID: babel.Identifier = babel.identifier("tempEXP__rec__uniqID");
let tempReceiver = babel.variableDeclaration("let", [babel.variableDeclarator(tempReceiverID, callExpNode.callee.object)]);
// callee.bind(callee.object)
let tempBindCall: babel.CallExpression = babel.callExpression( babel.memberExpression(babel.memberExpression(tempReceiverID, callExpNode.callee.property, callExpNode.callee.computed),
babel.identifier("bind")),
[tempReceiverID]);
(<any>tempBindCall).isNewCallExp = true;
tempVarDecl = babel.variableDeclaration("let", [babel.variableDeclarator(tempVarID, tempBindCall)]);
tempVarDecls = [tempReceiver, tempVarDecl];
}
let intermCallExp: babel.CallExpression = babel.callExpression(
babel.memberExpression(
babel.identifier("dangerousFunctions"),
babel.identifier("indexOf")
),
[ tempVarID]
);
(<any>intermCallExp).isNewCallExp = true;
let test = babel.binaryExpression( ">",
intermCallExp,
babel.numericLiteral(-1)
);
let consequent: babel.Statement = babel.expressionStatement( babel.callExpression(
babel.memberExpression(
babel.identifier("console"),
babel.identifier("warn")
),
[ babel.stringLiteral("[STUBBIFIER METRICS] WARNING: Dangerous call in expanded stub, in file: " + filename)]
));
(<any>consequent.expression).isNewCallExp = true;
let ifCheckStmt: babel.IfStatement = babel.ifStatement( test, consequent);
let retCallExp: babel.CallExpression = babel.callExpression(<any>callExpNode.callee/*tempVarID*/, callExpNode.arguments);
(<any> retCallExp).isNewCallExp = true;
let returnStmt: babel.ReturnStatement = babel.returnStatement( retCallExp);
let arrowFunc: babel.ArrowFunctionExpression = babel.arrowFunctionExpression( [], // params
babel.blockStatement(tempVarDecls.concat([ifCheckStmt, returnStmt])),
inAsyncFct) // whether or not it should be async
return babel.callExpression( arrowFunc, []);
}
// generate rollup.stubbifier.config.js in the directory specified
export function generateBundlerConfig( dirname): void {
/*
export default {
input: 'name of the main file in package.json',
output: {
dir: 'output',
format: 'cjs'
},
context: 'null',
moduleContext: 'null',
plugins: [nodeResolve({ moduleDirectories: ['node_modules'] }), commonjs(), babel()]
};
*/
let mainPath= undefined;
try {
let json = JSON.parse(fs.readFileSync(dirname + "/package.json", 'utf-8'));
mainPath = json.main;
} catch(e) {} // if there's an error, then we're not using esm
if( ! mainPath) {
mainPath = "index.js"
}
let configBody =
`import nodeResolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
export default {
input: '${mainPath}',
output: {
file: 'stubbifyBundle.js',
format: 'cjs'
},
context: 'null',
moduleContext: 'null',
plugins: [nodeResolve({ moduleDirectories: ['node_modules'] }), commonjs(), babel(), json()]
};`;
configBody = generate( parse(configBody, {sourceType: "unambiguous"}).program).code;
fs.writeFileSync( dirname + "/rollup.stubbifier.config.js", configBody);
}