-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy pathparser.js
More file actions
621 lines (583 loc) · 28.4 KB
/
parser.js
File metadata and controls
621 lines (583 loc) · 28.4 KB
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
const Parser = require("@babel/parser");
const protobuf = require("protobufjs");
const fs = require('fs');
if (process.argv.length < 5) {
console.error(`Usage: node ${process.argv[1]} path/to/ast.proto path/to/code.js path/to/output.ast.proto`);
process.exit(0);
}
let astProtobufDefinitionPath = process.argv[2];
let inputFilePath = process.argv[3];
let outputFilePath = process.argv[4];
function assert(cond, msg) {
if (!cond) {
if (typeof msg !== 'undefined') {
throw "Assertion failed: " + msg;
} else {
throw "Assertion failed";
}
}
}
function tryReadFile(path) {
let content;
try {
content = fs.readFileSync(path, 'utf8').toString();
} catch(err) {
console.error(`Couldn't read ${path}: ${err}`);
process.exit(-1);
}
return content;
}
// Parse the given JavaScript script and return an AST compatible with Fuzzilli's protobuf-based AST format.
function parse(script, proto) {
let ast = Parser.parse(script, { plugins: ["v8intrinsic"] });
function assertNoError(err) {
if (err) throw err;
}
function dump(node) {
console.log(JSON.stringify(node, null, 2));
}
function visitProgram(node) {
const AST = proto.lookupType('compiler.protobuf.AST');
let program = {statements: []};
for (let child of node.body) {
program.statements.push(visitStatement(child));
}
assertNoError(AST.verify(program));
return AST.create(program);
}
// Helper function to turn misc. object into their corresponding protobuf message.
function make(name, obj) {
let Proto = proto.lookupType('compiler.protobuf.' + name);
assertNoError(Proto.verify(obj));
return Proto.create(obj);
}
// Helper function to turn object nodes into their corresponding protobuf message.
const Statement = proto.lookupType('compiler.protobuf.Statement');
function makeStatement(name, node) {
let Proto = proto.lookupType('compiler.protobuf.' + name);
let fieldName = name.charAt(0).toLowerCase() + name.slice(1);
assertNoError(Proto.verify(node));
let statement = {[fieldName]: Proto.create(node)};
assertNoError(Statement.verify(statement));
return Statement.create(statement);
}
function visitParameter(param) {
assert(param.type == 'Identifier');
return make('Parameter', { name: param.name });
}
function visitVariableDeclaration(node) {
let kind;
if (node.kind === "var") {
kind = 0;
} else if (node.kind === "let") {
kind = 1;
} else if (node.kind === "const") {
kind = 2;
} else {
throw "Unknown variable declaration kind: " + node.kind;
}
let declarations = [];
for (let decl of node.declarations) {
assert(decl.type === 'VariableDeclarator', "Expected variable declarator nodes inside variable declaration, found " + decl.type);
let outDecl = {name: decl.id.name};
if (decl.init !== null) {
outDecl.value = visitExpression(decl.init);
}
declarations.push(make('VariableDeclarator', outDecl));
}
return { kind, declarations };
}
function visitStatement(node) {
switch (node.type) {
case 'EmptyStatement': {
return makeStatement('EmptyStatement', {});
}
case 'BlockStatement': {
let body = [];
for (let stmt of node.body) {
body.push(visitStatement(stmt));
}
return makeStatement('BlockStatement', {body});
}
case 'ExpressionStatement': {
let expr = visitExpression(node.expression);
return makeStatement('ExpressionStatement', {expression: expr});
}
case 'VariableDeclaration': {
return makeStatement('VariableDeclaration', visitVariableDeclaration(node));
}
case 'FunctionDeclaration': {
assert(node.id.type === 'Identifier', "Expected an identifier as function declaration name");
let name = node.id.name;
let type = 0; //"PLAIN";
if (node.generator && node.async) {
type = 3; //"ASYNC_GENERATOR";
} else if (node.generator) {
type = 1; //"GENERATOR";
} else if (node.async) {
type = 2; //"ASYNC";
}
let parameters = node.params.map(visitParameter);
assert(node.body.type === 'BlockStatement', "Expected block statement as function declaration body, found " + node.body.type);
let body = node.body.body.map(visitStatement);
return makeStatement('FunctionDeclaration', { name, type, parameters, body });
}
case 'ClassDeclaration': {
let cls = {};
cls.name = node.id.name;
if (node.superClass !== null) {
cls.superClass = visitExpression(node.superClass);
}
cls.fields = [];
for (let field of node.body.body) {
if (field.type === 'ClassProperty') {
let property = {};
property.isStatic = field.static;
if (field.value !== null) {
property.value = visitExpression(field.value);
}
if (field.computed) {
property.expression = visitExpression(field.key);
} else {
if (field.key.type === 'Identifier') {
property.name = field.key.name;
} else if (field.key.type === 'NumericLiteral') {
property.index = field.key.value;
} else {
throw "Unknown property key type: " + field.key.type + " in class declaration";
}
}
cls.fields.push(make('ClassField', { property: make('ClassProperty', property) }));
} else if (field.type === 'ClassMethod') {
assert(!field.shorthand);
assert(!field.computed);
assert(!field.generator);
assert(!field.async);
assert(field.key.type === 'Identifier');
let method = field;
field = {};
let name = method.key.name;
let isStatic = method.static;
if (method.kind === 'constructor') {
assert(method.body.type === 'BlockStatement');
assert(name === 'constructor');
assert(!isStatic);
let parameters = method.params.map(visitParameter);
let body = method.body.body.map(visitStatement);
field.ctor = make('ClassConstructor', { parameters, body });
} else if (method.kind === 'method') {
assert(method.body.type === 'BlockStatement');
let parameters = method.params.map(visitParameter);
let body = method.body.body.map(visitStatement);
field.method = make('ClassMethod', { name, isStatic, parameters, body });
} else if (method.kind === 'get') {
assert(method.params.length === 0);
assert(!method.generator && !method.async);
assert(method.body.type === 'BlockStatement');
let body = method.body.body.map(visitStatement);
field.getter = make('ClassGetter', { name, isStatic, body });
} else if (method.kind === 'set') {
assert(method.params.length === 1);
assert(!method.generator && !method.async);
assert(method.body.type === 'BlockStatement');
let parameter = visitParameter(method.params[0]);
let body = method.body.body.map(visitStatement);
field.setter = make('ClassSetter', { name, isStatic, parameter, body });
} else {
throw "Unknown method kind: " + method.kind;
}
cls.fields.push(make('ClassField', field));
} else if (field.type === 'StaticBlock') {
let body = field.body.map(visitStatement);
let staticInitializer = make('ClassStaticInitializer', { body });
cls.fields.push(make('ClassField', { staticInitializer }));
} else {
throw "Unsupported class declaration field: " + field.type;
}
}
return makeStatement('ClassDeclaration', cls);
}
case 'ReturnStatement': {
if (node.argument !== null) {
return makeStatement('ReturnStatement', { argument: visitExpression(node.argument) });
} else {
return makeStatement('ReturnStatement', {});
}
}
case 'IfStatement': {
let ifStmt = {};
ifStmt.test = visitExpression(node.test);
ifStmt.ifBody = visitStatement(node.consequent);
if (node.alternate !== null) {
ifStmt.elseBody = visitStatement(node.alternate);
}
return makeStatement('IfStatement', ifStmt);
}
case 'WhileStatement': {
let whileLoop = {};
whileLoop.test = visitExpression(node.test);
whileLoop.body = visitStatement(node.body);
return makeStatement('WhileLoop', whileLoop);
}
case 'DoWhileStatement': {
let doWhileLoop = {};
doWhileLoop.test = visitExpression(node.test);
doWhileLoop.body = visitStatement(node.body);
return makeStatement('DoWhileLoop', doWhileLoop);
}
case 'ForStatement': {
let forLoop = {};
if (node.init !== null) {
if (node.init.type === 'VariableDeclaration') {
forLoop.declaration = make('VariableDeclaration', visitVariableDeclaration(node.init));
} else {
forLoop.expression = visitExpression(node.init);
}
}
if (node.test !== null) {
forLoop.condition = visitExpression(node.test);
}
if (node.update !== null) {
forLoop.afterthought = visitExpression(node.update);
}
forLoop.body = visitStatement(node.body);
return makeStatement('ForLoop', forLoop);
}
case 'ForInStatement': {
assert(node.left.type === 'VariableDeclaration', "Expected variable declaration as init part of a for-in loop, found " + node.left.type);
assert(node.left.declarations.length === 1, "Expected exactly one variable declaration in the init part of a for-in loop");
let decl = node.left.declarations[0];
let forInLoop = {};
let initDecl = { name: decl.id.name };
assert(decl.init == null, "Expected no initial value for the variable declared as part of a for-in loop")
forInLoop.left = make('VariableDeclarator', initDecl);
forInLoop.right = visitExpression(node.right);
forInLoop.body = visitStatement(node.body);
return makeStatement('ForInLoop', forInLoop);
}
case 'ForOfStatement': {
assert(node.left.type === 'VariableDeclaration', "Expected variable declaration as init part of a for-in loop, found " + node.left.type);
assert(node.left.declarations.length === 1, "Expected exactly one variable declaration in the init part of a for-in loop");
let decl = node.left.declarations[0];
let forOfLoop = {};
let initDecl = { name: decl.id.name };
assert(decl.init == null, "Expected no initial value for the variable declared as part of a for-in loop")
forOfLoop.left = make('VariableDeclarator', initDecl);
forOfLoop.right = visitExpression(node.right);
forOfLoop.body = visitStatement(node.body);
return makeStatement('ForOfLoop', forOfLoop);
}
case 'BreakStatement': {
let breakStatementProto = {};
if (node.label) {
breakStatementProto.label = node.label.name; // Extract the label if present
}
return makeStatement('BreakStatement', breakStatementProto);
}
case 'ContinueStatement': {
let continueStatementProto = {};
if (node.label) {
continueStatementProto.label = node.label.name; // Extract the label if present
}
return makeStatement('ContinueStatement', continueStatementProto);
}
case 'TryStatement': {
assert(node.block.type === 'BlockStatement', "Expected block statement as body of a try block");
let tryStatement = {}
tryStatement.body = node.block.body.map(visitStatement);
assert(node.handler !== null || node.finalizer !== null, "TryStatements require either a handler or a finalizer (or both)")
if (node.handler !== null) {
assert(node.handler.type === 'CatchClause', "Expected catch clause as try handler");
assert(node.handler.body.type === 'BlockStatement', "Expected block statement as body of a catch block");
let catchClause = {};
if (node.handler.param !== null) {
catchClause.parameter = visitParameter(node.handler.param);
}
catchClause.body = node.handler.body.body.map(visitStatement);
tryStatement.catch = make('CatchClause', catchClause);
}
if (node.finalizer !== null) {
assert(node.finalizer.type === 'BlockStatement', "Expected block statement as body of finally block");
let finallyClause = {};
finallyClause.body = node.finalizer.body.map(visitStatement);
tryStatement.finally = make('FinallyClause', finallyClause);
}
return makeStatement('TryStatement', tryStatement);
}
case 'ThrowStatement': {
return makeStatement('ThrowStatement', { argument: visitExpression(node.argument) });
}
case 'WithStatement': {
let withStatement = {};
withStatement.object = visitExpression(node.object);
withStatement.body = visitStatement(node.body);
return makeStatement('WithStatement', withStatement);
}
case 'SwitchStatement': {
let switchStatement = {};
switchStatement.discriminant = visitExpression(node.discriminant);
switchStatement.cases = node.cases.map(visitStatement);
return makeStatement('SwitchStatement', switchStatement);
}
case "LabeledStatement": {
let labeledStatementProto = {
label: node.label.name, // Store the label
statement: visitStatement(node.body)
};
return { labeledStatement: labeledStatementProto };
}
case 'SwitchCase': {
let switchCase = {};
if (node.test) {switchCase.test = visitExpression(node.test)}
switchCase.consequent = node.consequent.map(visitStatement);
return switchCase;
}
default: {
throw "Unhandled node type " + node.type;
}
}
}
// Helper function to turn object nodes into their corresponding protobuf message.
const Expression = proto.lookupType('compiler.protobuf.Expression');
function makeExpression(name, node) {
let Proto = proto.lookupType('compiler.protobuf.' + name);
let fieldName = name.charAt(0).toLowerCase() + name.slice(1);
assertNoError(Proto.verify(node));
let expression = { [fieldName]: Proto.create(node) };
assertNoError(Expression.verify(expression));
return Expression.create(expression);
}
function visitExpression(node) {
const Expression = proto.lookupType('compiler.protobuf.Expression');
switch (node.type) {
case 'Identifier': {
return makeExpression('Identifier', { name: node.name });
}
case 'NumericLiteral': {
return makeExpression('NumberLiteral', { value: node.value });
}
case 'BigIntLiteral': {
return makeExpression('BigIntLiteral', { value: node.value });
}
case 'StringLiteral': {
return makeExpression('StringLiteral', { value: node.value });
}
case 'TemplateLiteral': {
let expressions = node.expressions.map(visitExpression);
let parts = node.quasis.map((part) => part.value.raw);
return makeExpression('TemplateLiteral', { parts, expressions });
}
case 'RegExpLiteral': {
return makeExpression('RegExpLiteral', { pattern: node.pattern, flags: node.flags });
}
case 'BooleanLiteral': {
return makeExpression('BooleanLiteral', { value: node.value });
}
case 'NullLiteral': {
return makeExpression('NullLiteral', {});
}
case 'ThisExpression': {
return makeExpression('ThisExpression', {});
}
case 'AssignmentExpression': {
let operator = node.operator;
let lhs = visitExpression(node.left);
let rhs = visitExpression(node.right);
return makeExpression('AssignmentExpression', { operator, lhs, rhs });
}
case 'ObjectExpression': {
let fields = [];
for (let field of node.properties) {
if (field.type === 'ObjectProperty') {
assert(!field.method);
let property = {};
property.value = visitExpression(field.value);
if (field.computed) {
property.expression = visitExpression(field.key);
} else {
if (field.key.type === 'Identifier') {
property.name = field.key.name;
} else if (field.key.type === 'NumericLiteral') {
property.index = field.key.value;
} else {
throw "Unknown property key type: " + field.key.type;
}
}
fields.push(make('ObjectField', { property: make('ObjectProperty', property) }));
} else {
assert(field.type === 'ObjectMethod');
assert(!field.shorthand);
let method = field;
let out = {};
if (method.computed) {
out.expression = visitExpression(method.key);
} else {
assert(method.key.type === 'Identifier')
out.name = method.key.name;
}
field = {};
if (method.kind === 'method') {
assert(method.body.type === 'BlockStatement');
let type = 0; //"PLAIN";
if (method.generator && method.async) {
out.type = 3; //"ASYNC_GENERATOR";
} else if (method.generator) {
out.type = 1; //"GENERATOR";
} else if (method.async) {
out.type = 2; //"ASYNC";
}
out.parameters = method.params.map(visitParameter);
out.body = method.body.body.map(visitStatement);
field.method = make('ObjectMethod', out);
} else if (method.kind === 'get') {
assert(method.params.length === 0);
assert(!method.generator && !method.async);
assert(method.body.type === 'BlockStatement');
out.body = method.body.body.map(visitStatement);
field.getter = make('ObjectGetter', out);
} else if (method.kind === 'set') {
assert(method.params.length === 1);
assert(!method.generator && !method.async);
assert(method.body.type === 'BlockStatement');
out.parameter = visitParameter(method.params[0]);
out.body = method.body.body.map(visitStatement);
field.setter = make('ObjectSetter', out);
} else {
throw "Unknown method kind: " + method.kind;
}
fields.push(make('ObjectField', field));
}
}
return makeExpression('ObjectExpression', { fields });
}
case 'ArrayExpression': {
let elements = [];
for (let elem of node.elements) {
if (elem == null) {
// Empty expressions indicate holes.
elements.push(Expression.create({}));
} else {
elements.push(visitExpression(elem));
}
}
return makeExpression('ArrayExpression', { elements });
}
case 'FunctionExpression': {
let type = 0; //"PLAIN";
if (node.generator && node.async) {
type = 3; //"ASYNC_GENERATOR";
} else if (node.generator) {
type = 1; //"GENERATOR";
} else if (node.async) {
type = 2; //"ASYNC";
}
let parameters = node.params.map(visitParameter);
assert(node.body.type === 'BlockStatement', "Expected block statement as function expression body, found " + node.body.type);
let body = node.body.body.map(visitStatement);
return makeExpression('FunctionExpression', { type, parameters, body });
}
case 'ArrowFunctionExpression': {
assert(node.id == null);
assert(node.generator == false);
let type = 0; //"PLAIN";
if (node.async) {
type = 2; //"ASYNC";
}
let parameters = node.params.map(visitParameter);
let out = { type, parameters };
if (node.body.type === 'BlockStatement') {
out.block = visitStatement(node.body);
} else {
out.expression = visitExpression(node.body);
}
return makeExpression('ArrowFunctionExpression', out);
}
case 'CallExpression':
case 'OptionalCallExpression': {
let callee = visitExpression(node.callee);
let arguments = node.arguments.map(visitExpression);
let isOptional = node.type === 'OptionalCallExpression';
return makeExpression('CallExpression', { callee, arguments, isOptional });
}
case 'NewExpression': {
let callee = visitExpression(node.callee);
let arguments = node.arguments.map(visitExpression);
return makeExpression('NewExpression', { callee, arguments });
}
case 'MemberExpression':
case 'OptionalMemberExpression': {
let object = visitExpression(node.object);
let out = { object };
if (node.computed) {
out.expression = visitExpression(node.property);
} else {
assert(node.property.type === 'Identifier');
out.name = node.property.name;
}
out.isOptional = node.type === 'OptionalMemberExpression';
return makeExpression('MemberExpression', out);
}
case 'UnaryExpression': {
assert(node.prefix);
let operator = node.operator;
let argument = visitExpression(node.argument);
return makeExpression('UnaryExpression', { operator, argument });
}
case 'ConditionalExpression': {
let condition = visitExpression(node.test);
let consequent = visitExpression(node.consequent);
let alternate = visitExpression(node.alternate);
return makeExpression('TernaryExpression', { condition, consequent, alternate });
}
case 'BinaryExpression':
case 'LogicalExpression': {
let operator = node.operator;
let lhs = visitExpression(node.left);
let rhs = visitExpression(node.right);
return makeExpression('BinaryExpression', { operator, lhs, rhs });
}
case 'UpdateExpression': {
let operator = node.operator;
let isPrefix = node.prefix;
let argument = visitExpression(node.argument);
return makeExpression('UpdateExpression', { operator, isPrefix, argument });
}
case 'YieldExpression': {
assert(node.delegate == false);
if (node.argument !== null) {
let argument = visitExpression(node.argument);
return makeExpression('YieldExpression', { argument });
} else {
return makeExpression('YieldExpression', {});
}
}
case 'SpreadElement': {
let argument = visitExpression(node.argument);
return makeExpression('SpreadElement', { argument });
}
case 'SequenceExpression': {
let expressions = node.expressions.map(visitExpression);
return makeExpression('SequenceExpression', { expressions });
}
case 'V8IntrinsicIdentifier': {
return makeExpression('V8IntrinsicIdentifier', { name: node.name });
}
default: {
throw "Unhandled node type " + node.type;
}
}
}
return visitProgram(ast.program);
}
let script = tryReadFile(inputFilePath);
protobuf.load(astProtobufDefinitionPath, function(err, root) {
if (err)
throw err;
let ast = parse(script, root);
// Uncomment this to print the AST to stdout (will be very verbose).
//console.log(JSON.stringify(ast, null, 2));
const AST = root.lookupType('compiler.protobuf.AST');
let buffer = AST.encode(ast).finish();
fs.writeFileSync(outputFilePath, buffer);
console.log("All done, output file @ " + outputFilePath);
});