-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCode.js
2115 lines (1929 loc) · 70.4 KB
/
Code.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
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
var path = require('path');
var fs = require('fs');
var child_process = require('child_process');
var EventEmitter = require('events').EventEmitter;
var esprima = require('esprima');
var escodegen = require('escodegen');
var pidusage = require('pidusage');
var yaml = require('js-yaml');
var jsBeautify = require('js-beautify').js_beautify;
var chalk = require('chalk');
var Pubsub = require('./Pubsub.js');
var helpers = require('../helpers.js');
var DEBUG = (process.env.DEBUG === 'true');
var WARNING = false;
var HUMAN_FRIENDLY = false;
// These greek letter prefixes are used to prevent conflicting names with user code.
// var LIB_ALIAS = 'λ';
var SCOPE_PREFIX = 'Σ'; // prefix for Scope identifiers
var PROPERTY_PREFIX = 'τ'; // prefix for injected properties
var ANONYMOUS_PREFIX = 'α'; // prefix for anonymous functions
var PROGRAM_MONITOR_NAMESPACE = 'program-monitor'; // Pubsub topic for code status
var NodeProcessId = helpers.randKey(8);
/* TODO:
* - require statements (instrumenting dependencies)
* - async callbacks in the event loop other than timers (I/O proxy)
* - Object creation scope - when serializing/restoring we need to restore the exact same object.
* - Timer optimization
* - IPC optimization
*/
var NATIVE_OBJECTS = new Map();
NATIVE_OBJECTS.set(global, 'global');
NATIVE_OBJECTS.set(Array, 'Array');
function getAllPrototypeProperties(proto){
var sup = Object.getPrototypeOf(proto);
if (sup) return getAllPrototypeProperties(sup).concat(Object.keys(proto));
else return Object.keys(proto);
}
/* Static Scope object used during instrumentation.
* It is used to keep track of lexical scope of various AST nodes
*/
function StaticScope(func_name, parent){
this.func_name = func_name;
this.parent = parent || null;
this.children = {};
if (this.parent){
// this.parent.children[this.uid] = this;
this.id = func_name;
// if (HUMAN_FRIENDLY) this.id = func_name;
// else this.id = (Object.keys(this.parent.children).length).toString();
this.parent.children[this.id] = this;
}
else {
this.id = SCOPE_PREFIX;
}
this.params = [];
this.hoisted = {};
this.declared = {};
// this.funcs = {};
// this.props = {};
this.refs = {}; // refs maps identifiers to params, vars, or funcs. We do this to emulate the lexical context of JS.
this.protects = parent || null;
// For debug
this.level = parent ? parent.level+1 : 0;
}
StaticScope.prototype.identifier = function(){
if (this.parent === null) return this.id;
else return this.parent.identifier()+'_'+this.id;
}
StaticScope.prototype.initRefs = function(node){
// First scan the body to find variable and function declarations.
// JavaScript lexical scoping behaviour if variable, function, param has the same name is thus:
// 0. if there is a reference in the parent scope, it refers to that.
// 1. if there is a parameter, the reference first refers to the parameter
// 2. if there are variable declarations (var foo), the reference refers to the variable
// 3. if there are hoisted functions, this overwrites the reference
// --- upto 3. the references are updated prior to execution. 4. is applied sequentially during runtime
// 4. if the declared identifier is assigned a value, from that line onwards the reference refers to the variable
var self = this, body;
if (node.type === 'Program'){
body = node.body;
}
else if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression'){
body = node.body.body;
node.params.forEach(function(param){
// self.params[param.name] = param;
self.params.push(param.name);
self.refs[param.name] = param;
});
}
else return;
body.forEach(function(node, index, body){
if (node.type === 'VariableDeclaration'){
node.declarations.forEach(function(declaration){
self.declared[declaration.id.name] = declaration;
self.refs[declaration.id.name] = declaration.id.name;
})
}
else if (node.type === 'FunctionDeclaration'){
self.hoisted[node.id.name] = node; // node will be replaced with protected ancestor scope during top-down pass
self.refs[node.id.name] = node.id.name;
}
else if (node.type === 'ExpressionStatement'
&& node.expression.type === 'AssignmentExpression'){
if (node.expression.left.type === 'MemberExpression'
&& node.expression.left.object.type === 'ThisExpression'){
self.hasInstanceProps = true;
}
}
});
}
StaticScope.prototype.findRef = function(raw_name){
// if (raw_name in this.refs) return this.identifier()+'.refs.'+raw_name;
if (raw_name in this.refs) return { scope: this, identifier: this.identifier()+'.refs.'+raw_name };
if (raw_name === this.func_name) return { scope: null, identifier: raw_name+'.'+PROPERTY_PREFIX+'wrapped' }; // If the enclosing function is named, the identifier refers to the function
if (this.parent !== null) return this.parent.findRef(raw_name);
else {
(WARNING && console.log(chalk.red('[WARNING] Could not find scope for ')+raw_name));
return { scope: null, identifier: raw_name };
}
}
StaticScope.prototype.hasLocals = function(){
return Object.keys(this.declared).length > 0 || Object.keys(this.hoisted).length > 0;
}
StaticScope.prototype.protectAncestor = function(ancestor){
if (ancestor.level < this.level){
if (!(this.protects) || (this.protects.level < ancestor.level)) this.protects = ancestor;
}
}
/* Object that wraps a node in the AST produced by esprima used for instrumenting the code
* @param {StaticScope} scope - The lexical scope that the node belongs to (this is passed on to inner statements by default)
* @param {object} node - An AST node
* @param {object} parsing_context - An arbitrary object that can be passed to child nodes (this is only passed explicitly)
*/
function AstHook(scope, node, parsing_context){
this.scope = scope;
this.node = node;
this.parsing_context = parsing_context;
(DEBUG && this.debug(chalk.green('top-down')));
if (this.node.type in AstHook.onEnter){
this.result = AstHook.onEnter[this.node.type](this, parsing_context);
}
else {
(DEBUG && console.log(chalk.yellow('[INFO] '+this.node.type+' remains the same')));
}
(DEBUG && this.debug(chalk.red('bottom-up')));
}
AstHook.lastId = 0;
AstHook.prototype.debug = function(message){
var label;
switch(this.node.type){
case 'ExpressionStatement':
label = '('+this.node.expression.type+')';
break;
case 'Identifier':
label = '('+this.node.name+')';
break;
case 'MemberExpression':
label = '('+escodegen.generate(this.node)+')';
break;
case 'VariableDeclarator':
label = '('+this.node.id.name+')';
break;
default:
label = '';
break;
}
console.log(helpers.indent(this.scope.level*4)
+ chalk.blue(this.scope.id+':'+this.scope.func_name)
+ ' '+chalk.yellow(this.node.type)+' '
+ label
+ ' '+(message || ''));
}
// Using dictionary for performance
AstHook.NATIVE_KEYWORDS = {
'Object': null,
'Function': null,
'Array': null,
'String': null,
'Number': null,
'Boolean': null,
'Date': null,
'Math': null,
'JSON': null,
'RegExp': null,
'Error': null,
'undefined': null,
'eval': null,
'arguments': null,
'process': null,
'global': null,
'parseInt': null,
'parseFloat': null
}
function _getMemberExpressionObject(node){
if (node.type !== 'MemberExpression') return node;
return _getMemberExpressionObject(node.object);
}
function isNative(node){
return ( !node
|| ((node.type === 'Identifier') && (node.name in AstHook.NATIVE_KEYWORDS))
|| ((node.type === 'MemberExpression') && isNative(_getMemberExpressionObject(node.object)) ) )
}
AstHook.onEnter = {
Program: function(self, context){
self.scope.initRefs(self.node);
// self.hooks = [];
self.node.body.forEach(function(node, index, body){
var hook = new AstHook(self.scope, node);
body[index] = hook.node; // hook may have replaced the node
// self.hooks.push(hook);
})
// After processing the body
var injections = [];
var refs = '{'+Object.keys(self.scope.declared).map(function(name){ return name+':'+name }).join(',')+'}';
var hoisted = Object.keys(self.scope.hoisted).map(function(key){ return '.hoist('+key+','+self.scope.hoisted[key]+')' }).join('');
injections.push(`${SCOPE_PREFIX}.setExtractor(function(){ return [{},${refs}]; })
${hoisted}`);
var inject = esprima.parse(injections.join(';')).body;
self.node.body.unshift.apply(self.node.body, inject);
},
FunctionDeclaration: function(self, context){
var func_scope = new StaticScope(self.node.id.name, self.scope);
func_scope.initRefs(self.node);
self.scope.refs[self.node.id.name] = self.node;
// self.scope.funcs[self.node.id.name] = self.node;
self.node.body.body.forEach(function(node, index, body){
body[index] = new AstHook(func_scope, node).node;
})
// After processing the body
var injections = [];
var params = '{'+func_scope.params.map(function(param){ return param+':'+param }).join(',')+'}';
var refs = '{'+Object.keys(func_scope.declared).map(function(name){ return name+':'+name }).join(',')+'}'
var hoisted = Object.keys(func_scope.hoisted).map(function(key){ return '.hoist('+key+','+func_scope.hoisted[key]+')' }).join('');
// If the function is stateless, don't bother injecting a Scope (Optimization)
/*if (Object.keys(func_scope.refs).length > 0
|| func_scope.hasInstanceProps)*/
if (func_scope.hasLocals())
{
injections.push(`var ${func_scope.identifier()} = new ${SCOPE_PREFIX}.Scope(this, ${func_scope.parent.identifier()}, ${self.node.id.name}, function(){ return [${params}, ${refs}] })${hoisted}`);
}
var inject = esprima.parse(injections.join(';')).body;
self.node.body.body.unshift.apply(self.node.body.body, inject);
// func_scope.protects is available now
if (context != "is_expression"){
// If func_scope.func_name is not in self.scope.hoisted, it implies function was declared inside an if block or for block
if (func_scope.func_name in self.scope.hoisted){
self.scope.hoisted[func_scope.func_name] = func_scope.protects.identifier();
}
}
return { scope_created: func_scope };
},
FunctionExpression: function(self, context){
// Similar to FunctionDeclaration, but here the function can be anonymous.
// If function is anonymous, assign some name. We need the name for migration
if (self.node.id === null){
//self.node.id = esprima.parse(ANONYMOUS_PREFIX + helpers.randKey(4)).body[0].expression;
self.node.id = esprima.parse(ANONYMOUS_PREFIX + (AstHook.lastId++)).body[0].expression;
}
// Using (FunctionDeclaration)
var result = AstHook.onEnter.FunctionDeclaration(self, "is_expression");
// FunctionExpression should be wrapped with addFunction call
// if the enclosing scope keeps locals
if (self.scope.hasLocals())
//if (self.scope.hasLocals() && context != "assign_rhs" && context != "member_rhs" )
{
var replace = esprima.parse(self.scope.identifier()+'.addFunction()').body[0].expression;
replace.arguments.push(self.node);
if (result.scope_created.protects){
replace.arguments.push(esprima.parse(result.scope_created.protects.identifier()).body[0].expression)
}
self.node = replace;
}
},
CallExpression: function(self, context){
// Intercept console.log calls
if (self.node.callee.type === 'MemberExpression'){
if (self.node.callee.object.name === 'console'
&& self.node.callee.property.name === 'log'){
var replace = esprima.parse(SCOPE_PREFIX+'.console').body[0].expression;
self.node.callee.object = replace;
// self.node.callee.object.name = SCOPE_PREFIX;
}
else if (self.node.callee.object.name
&& self.node.callee.object.name in AstHook.NATIVE_KEYWORDS){
// Do nothing
}
else {
var hook = new AstHook(self.scope, self.node.callee);
self.node.callee = hook.node;
}
}
else if (self.node.callee.type === 'Identifier'){
if (['setImmediate', 'setTimeout', 'setInterval',
'clearImmediate', 'clearTimeout', 'clearInterval',
'require'].indexOf(self.node.callee.name) > -1){
var replace = esprima.parse(SCOPE_PREFIX+'.'+self.node.callee.name).body[0].expression;
self.node.callee = replace;
}
else if (self.node.callee.name in AstHook.NATIVE_KEYWORDS){
// Do nothing
}
else {
var hook = new AstHook(self.scope, self.node.callee);
self.node.callee = hook.node;
}
}
else if (self.node.callee.type === 'FunctionExpression'){
self.node.callee = new AstHook(self.scope, self.node.callee).node;
}
else if (self.node.callee.type === 'CallExpression'){
var hook = new AstHook(self.scope, self.node.callee);
}
// handle arguments - replace variable references, etc.
self.node.arguments.forEach(function(node, index, body){
if (!isNative(node)){
body[index] = new AstHook(self.scope, node).node;
}
});
},
AssignmentExpression: function(self, context){
var memberAssignment = false;
if (self.node.left.type === 'MemberExpression'
&& self.node.left.object.type === 'ThisExpression'){
memberAssignment = true;
}
// self.node.left = new AstHook(self.scope, self.node.left).node;
self.node.right = new AstHook(self.scope, self.node.right, "assign_rhs").node;
},
UpdateExpression: function(self, context){
if (self.node.argument.type === 'Identifier'){
var hook = new AstHook(self.scope, self.node.argument);
self.node.argument = hook.node;
}
else if (self.node.argument.type === 'MemberExpression'){
var hook = new AstHook(self.scope, self.node.argument);
self.node.argument = hook.node;
}
},
SequenceExpression: function(self, context){
// self.hooks = [];
self.node.expressions.forEach(function(node, index, body){
var hook = new AstHook(self.scope, node);
body[index] = hook.node; // hook may have replaced the node
// self.hooks.push(hook);
})
},
ExpressionStatement: function(self, context){
// return AstHook.onEnter[self.node.expression.type](self);
self.node.expression = new AstHook(self.scope, self.node.expression).node;
},
VariableDeclaration: function(self, context){
var replacements = [];
// self.node.declarations.forEach(function(declaration){
// // Store information about variable in StaticScope
// var var_name = declaration.id.name;
// self.scope.refs[var_name] = declaration.init;
// if (!isNative(declaration.init)){
// declaration.init = new AstHook(self.scope, declaration.init).node;
// }
// });
self.node.declarations.forEach(function(node, index, body){
var hook = new AstHook(self.scope, node);
body[index] = hook.node;
});
},
VariableDeclarator: function(self, context){
// Store information about variable in StaticScope
var var_name = self.node.id.name;
self.scope.refs[var_name] = self.node.init;
//self.scope.declared[var_name] = self.node; // a small hack because initRef does not cover nested cases like IfStatement or WhileStatement
if (!isNative(self.node.init)){
self.node.init = new AstHook(self.scope, self.node.init).node;
}
},
WhileStatement: function(self, context){
if (self.node.body.type !== "BlockStatement"){
var block = esprima.parse("{}").body[0];
block.body.push(self.node.body);
self.node.body = block;
}
self.node.test = new AstHook(self.scope, self.node.test).node;
var block_hoisted = [];
self.node.body.body.forEach(function(node, index, body){
var hook = new AstHook(self.scope, node);
body[index] = hook.node; // hook may have replaced the node
if (node.type === 'FunctionDeclaration'){
// block_hoisted[node.id.name] = hook.result.protects;
var inject = esprima.parse(self.scope.identifier()+'.addFunction('+node.id.name+', '+hook.result.scope_created.protects.identifier()+', "'+node.id.name+'")').body[0];
block_hoisted.push(inject);
}
});
self.node.body.body.unshift.apply(self.node.body.body, block_hoisted);
},
DoWhileStatement: function(self, context){
return AstHook.onEnter['WhileStatement'](self);
},
ForStatement: function(self, context){
if (self.node.init){
self.node.init = new AstHook(self.scope, self.node.init).node;
if (self.node.init.type === 'ExpressionStatement') self.node.init = self.node.init.expression;
}
if (self.node.test){
self.node.test = new AstHook(self.scope, self.node.test).node;
if (self.node.test.type === 'ExpressionStatement') self.node.test = self.node.test.expression;
}
if (self.node.update){
self.node.update = new AstHook(self.scope, self.node.update).node;
if (self.node.update.type === 'ExpressionStatement') self.node.update = self.node.update.expression;
}
if (self.node.body.type !== "BlockStatement"){
var block = esprima.parse("{}").body[0];
block.body.push(self.node.body);
self.node.body = block;
}
var block_hoisted = [];
self.node.body.body.forEach(function(node, index, body){
var hook = new AstHook(self.scope, node);
body[index] = hook.node; // hook may have replaced the node
if (node.type === 'FunctionDeclaration'){
// block_hoisted[node.id.name] = hook.result.protects;
var inject = esprima.parse(self.scope.identifier()+'.addFunction('+node.id.name+', '+hook.result.scope_created.protects.identifier()+', "'+node.id.name+'")').body[0];
block_hoisted.push(inject);
}
})
self.node.body.body.unshift.apply(self.node.body.body, block_hoisted);
// return AstHook.onEnter['WhileStatement'](self);
},
ForInStatement: function(self, context){
// ATTN: Hacky here... variable declarator in a for...in loop should be handled better.
self.node.left = new AstHook(self.scope, self.node.left).node;
if (self.node.left.type === 'ExpressionStatement'){
self.node.left = self.node.left.expression;
if (self.node.left.right && self.node.left.right.type === 'Identifier' && self.node.left.right.name === 'undefined'){
self.node.left = self.node.left.left;
}
}
self.node.right = new AstHook(self.scope, self.node.right).node;
if (self.node.right.type === 'ExpressionStatement') self.node.right = self.node.right.expression;
if (self.node.body.type !== "BlockStatement"){
var block = esprima.parse("{}").body[0];
block.body.push(self.node.body);
self.node.body = block;
}
var block_hoisted = [];
self.node.body.body.forEach(function(node, index, body){
var hook = new AstHook(self.scope, node);
body[index] = hook.node; // hook may have replaced the node
// body[index] = new AstHook(self.scope, node).node; // hook may have replaced the node
if (node.type === 'FunctionDeclaration'){
// block_hoisted[node.id.name] = hook.result.protects;
var inject = esprima.parse(self.scope.identifier()+'.addFunction('+node.id.name+', '+hook.result.scope_created.protects.identifier()+', "'+node.id.name+'")').body[0];
block_hoisted.push(inject);
}
});
self.node.body.body.unshift.apply(self.node.body.body, block_hoisted);
},
IfStatement: function(self, context){
if (self.node.consequent.type !== "BlockStatement"){
var block = esprima.parse("{}").body[0];
block.body.push(self.node.consequent);
self.node.consequent = block;
}
self.node.test = new AstHook(self.scope, self.node.test).node;
// var block_hoisted = [];
self.node.consequent.body.forEach(function(node, index, body){
var hook = new AstHook(self.scope, node);
body[index] = hook.node; // hook may have replaced the node
// TODO: hoisting within a conditional body
// if (node.type === 'FunctionDeclaration'){
// // block_hoisted[node.id.name] = hook.result.protects;
// var inject = esprima.parse(self.scope.identifier()+'.refs.'+node.id.name+' = '+self.scope.identifier()+'.addFunction('+node.id.name+', '+hook.result.scope_created.protects.identifier()+', "'+node.id.name+'")').body[0];
// block_hoisted.push(inject);
// }
})
// self.node.consequent.body.unshift.apply(self.node.consequent.body, block_hoisted);
if (self.node.alternate){
if (self.node.alternate.type === 'IfStatement'){
// var elif = new AstHook(self.scope, self.node.alternate);
// self.node.alternate = elif.node;
self.node.alternate = new AstHook(self.scope, self.node.alternate).node;
}
else {
if (self.node.alternate.type !== 'BlockStatement'){
var block = esprima.parse("{}").body[0];
block.body.push(self.node.alternate);
self.node.alternate = block;
}
// var block_hoisted = [];
self.node.alternate.body.forEach(function(node, index, body){
// var hook = new AstHook(self.scope, node);
// body[index] = hook.node; // hook may have replaced the node
body[index] = new AstHook(self.scope, node).node; // hook may have replaced the node
// self.hooks.push(hook);
// body[index] = new AstHook(self.scope, node).node;
// if (node.type === 'FunctionDeclaration'){
// // block_hoisted[node.id.name] = hook.result.protects;
// var inject = esprima.parse(self.scope.identifier()+'.addFunction('+node.id.name+', '+hook.result.scope_created.protects.identifier()+', "'+node.id.name+'")').body[0];
// block_hoisted.push(inject);
// }
});
// self.node.alternate.body.unshift.apply(self.node.alternate.body, block_hoisted);
}
}
},
ReturnStatement: function(self, context){
if (!isNative(self.node.argument)) self.node.argument = new AstHook(self.scope, self.node.argument).node;
},
ThrowStatement: function(self, context){
self.node.argument = new AstHook(self.scope, self.node.argument).node;
},
BlockStatement: function(self, context){
self.node.body.forEach(function(node, index, body){
body[index] = new AstHook(self.scope, node).node;
});
},
NewExpression: function(self, context){
// NewExpression has same signature as CallExpression
return AstHook.onEnter.CallExpression(self);
},
ObjectExpression: function(self, context){
self.node.properties.forEach(function(node, index, body){
node.value = new AstHook(self.scope, node.value, "member_rhs").node;
});
// ObjectExpression should be wrapped with addObject call
// var replace = esprima.parse(self.scope.identifier()+'.addObject()').body[0].expression;
// replace.arguments.push(self.node);
// self.node = replace;
},
ArrayExpression: function(self, context){
self.node.elements.forEach(function(node, index, body){
body[index] = new AstHook(self.scope, node).node;
});
// ArrayExpression should be wrapped with addObject call
// var replace = esprima.parse(self.scope.identifier()+'.addObject()').body[0].expression;
// replace.arguments.push(self.node);
// self.node = replace;
},
ConditionalExpression: function(self, context){
self.node.test = new AstHook(self.scope, self.node.test).node;
self.node.consequent = new AstHook(self.scope, self.node.consequent).node;
self.node.alternate = new AstHook(self.scope, self.node.alternate).node;
},
LogicalExpression: function(self, context){
var l_hook = new AstHook(self.scope, self.node.left);
var r_hook = new AstHook(self.scope, self.node.right);
self.node.left = l_hook.node;
self.node.right = r_hook.node;
},
BinaryExpression: function(self, context){
if (!isNative(self.node.left)) self.node.left = new AstHook(self.scope, self.node.left).node;
if (!isNative(self.node.right)) self.node.right = new AstHook(self.scope, self.node.right).node;
},
UnaryExpression: function(self, context){
self.node.argument = new AstHook(self.scope, self.node.argument).node;
},
MemberExpression: function(self, context){
if (!(self.node.object.type === 'Identifier' && self.node.object.name in AstHook.NATIVE_KEYWORDS)){
self.node.object = new AstHook(self.scope, self.node.object).node;
}
if (self.node.computed === true) self.node.property = new AstHook(self.scope, self.node.property).node;
},
Identifier: function(self, context){
var reference = self.scope.findRef(self.node.name);
(reference.scope && self.scope.protectAncestor(reference.scope));
// var replace = esprima.parse(reference.identifier).body[0].expression;
// self.node = replace;
},
}
/** The Code object provides API for processing raw JavaScript code.
* @constructor
* @param {Pubsub} pubsub - Pubsub interface the code should use
* @param {string} name - Name of the code (e.g. file name)
* @param {string} raw_code - String content of the code
*/
function Code(pubsub, name, raw_code){
if (!(this instanceof Code)) return new Code(pubsub, name, raw_code);
EventEmitter.call(this);
this.pubsub = pubsub;
this.name = name;
// this.uid = name+'/'+helpers.randKey(4);
this.source_raw = raw_code || null;
this.source = Code.instrument(pubsub, name, raw_code);
this.processes = {};
this.history = []; // relevant only when Code is a restored program
}
Code.prototype = new EventEmitter();
Code.prototype.constructor = Code;
/** Save the instrumented code as a file
* @param {string} file_path - the path to write to
* @return {Promise} - On successful write, the Promise resolves to `file_path`.
*/
Code.prototype.save = function(file_path){
var self = this;
return new Promise(function(resolve, reject){
fs.writeFile(file_path, self.source, function(err){
if (err) reject(err);
else resolve(file_path);
});
});
}
/**
* Execute a new process as a forked child process.
* @param {object} options - Options object used for initializing the Process object.
* @return {Promise} - On successful execution, the Promise is resolved with a Process object.
*/
Code.prototype.run = function(options){
var self = this;
return new Promise(function(resolve, reject){
var proc = new Process(self, options, self.history.slice());
proc.on('started', function(id){
self.processes[id] = proc;
resolve(proc);
});
});
}
// Code.prototype.getStats = function(instance_id){
// var self = this;
// return this.ipcSend(instance_id, 'STATS')
// }
/* Pause the user code through IPC. This will work only if the user code was executed through Code.run.
* If the user code was executed as a standalone Node process (e.g. node user_code.js),
* it can only be paused through Pubsub.
*/
Code.prototype.kill = function(kill_pubsub){
var self = this;
return Promise.all(Object.values(this.processes).map(function(proc){
return proc.kill();
})).then(function(){
return kill_pubsub ? self.pubsub.kill() : true;
});
}
Code._extractMeta = function(comments){
var meta = {};
for (var i=0; i < comments.length; i++){
if (comments[i].type === 'Block' && comments[i].value.indexOf('things.meta') === 0){
var body = comments[i].value.split('\n').slice(1,-1).join('\n');
meta = yaml.safeLoad(body);
break;
}
}
return meta;
}
/**
* Standalone static function for reading ThingsJS metadata from raw code
* @param {string} raw_code - Raw user code in UTF-8 string
* @return {object} - Object representing the YAML metadata from the code
*/
Code.readMetadata = function(raw_code){
return Code._extractMeta(esprima.parse(raw_code, { comment: true }).comments)
}
/**
* Instrument raw JavaScript code and return a live-migratable version
* @param {Pubsub} pubsub - The Pubsub instance to bind to the program instance
* @param {string} code_name - The name to assign to the program instance
* @param {string} raw_code - Raw user code in UTF-8 string
* @return {string} - Instrumented (live-migratable) user code in UTF-8 string
*/
Code.instrument = function(pubsub, code_name, raw_code){
// var started = Date.now();
var ast = esprima.parse(raw_code, { comment: true }); // Comment may contain meta info
var root_scope = new StaticScope('root'); // Create root scope (static scope)
var hook = new AstHook(root_scope, ast); // Process the AST
// Process metadata about the program
var meta = JSON.stringify(Code._extractMeta(ast.comments));
// Prepare the things-js template
var template_str = `require('things-js/lib/core/Code').bootstrap(module, function(${SCOPE_PREFIX}){}, '${pubsub.url}', '${code_name}', ${meta});`;
var template = esprima.parse(template_str);
// WARNING: the following depends on esprima output, and might break if esprima changes its format
template.body[0].expression.arguments[1].body.body = ast.body;
var result = escodegen.generate(template);
// var ended = Date.now();
// (DEBUG && console.log(chalk.green('Instrumented in '+(ended - started)+'ms')));
// console.log(result);
return result;
}
/* Create a dummy Code object without initializing the properties.
* This function is used when restoring code from a snapshot.
*/
Code._createEmpty = function(){
var code = Object.create(Code.prototype);
code.pubsub = null;
code.name = null;
code.source_raw = null;
code.source = null;
code.processes = {};
code.snapshots = [];
code.history = []; // relevant only when Code is a restored program
return code;
}
/**
* Create a new Code object from raw JavaScript code provided as a utf-8 string
* @param {Pubsub} pubsub Pubsub object to use for instrumentation - this determines which Pubsub service a Process connects to
* @param {string} code_name - Name to assign the code (e.g. factorial.js)
* @param {string} raw_code - JavaScript code string
* @return {Code} Returns a new Code instance
*/
Code.fromString = function(pubsub, code_name, raw_code){
return new Code(pubsub, code_name, raw_code);
}
/**
* Create a new Code object from file path
* @param {string} file_path - the path to the raw JS file
*/
Code.fromFile = function(pubsub, file_path){
return new Code(pubsub, path.basename(file_path), fs.readFileSync(file_path).toString());
}
/**
* Create a new Code object from given Snapshot object
* @param {object} snapshot - The Snapshot object produced when Process.snapshot() is called
* @return {Code} Returns a new Code instance
*/
Code.fromSnapshot = function(snapshot, dummy_pubsub){
var code = Code._createEmpty();
code.pubsub = dummy_pubsub ? new Pubsub.Dummy(snapshot.meta.pubsub) : new Pubsub(snapshot.meta.pubsub);
// code.pubsub = new Pubsub(snapshot.meta.pubsub);
code.name = snapshot.meta.code_name;
// code.uid = snapshot.meta.uid;
// var watch = helpers.StopWatch().start();
var content = Scope.generateCode(snapshot.tree);
// watch.stop();
Object.keys(snapshot.timers).forEach(function(id){
content += Timer.generateCode(snapshot.timers[id]);
});
var meta = JSON.stringify(snapshot.meta.extra);
code.source = `require('things-js/lib/core/Code').bootstrap(module, function(${SCOPE_PREFIX}){ ${content} }, '${code.pubsub.url}', '${snapshot.meta.code_name}/${snapshot.meta.instance_id}', ${meta});`;
// console.log(jsBeautify(code.source));
// code.source = jsBeautify(code.source);
// code.pubsub.publish(PROGRAM_MONITOR_NAMESPACE, {
// code_name: code.name,
// source: code.source
// });
return code;
}
/**
* Create a new Code object from given Snapshot file. This static method calls Code.fromSnapshot after reading from file.
* @param {string} snapshot_path - The path to the snapshot file
* @return {Code} Returns a new Code instance
*/
Code.fromSnapshotFile = function(snapshot_path, dummy_pubsub){
var snapshot = JSON.parse(fs.readFileSync(snapshot_path).toString());
return Code.fromSnapshot(snapshot, dummy_pubsub);
}
/* Pre-processor before serializing Scope Tree; this is needed to serialize more complex objects.
*/
var NATIVE_TRANSFORMERS = {
'Object': {
makeSerializable: function(item, scope, exclude){
var safe = {
type: 'Object',
value: {}
};
Object.keys(item).forEach(function(key){
safe.value[key] = makeSerializable(item[key], scope, exclude);
});
return safe;
},
makeCode: function(item){
// var obj_id = item.obj_id.split('.')[1];
return SCOPE_PREFIX+'.addObject({ '+Object.keys(item.value).map(function(key){ return '"'+key+'" : '+makeCode(item.value[key]); }).join(',')+'}, "'+ item.obj_id +'")';
}
},
'Date': {
makeSerializable: function(item){
return {
type: 'Date',
value: item.toISOString()
}
}
},
'Function': {
makeCode: function(item){
// return SCOPE_PREFIX+'.getFunction("'+(item.value.split('/').slice(1).join('/'))+'")';
return SCOPE_PREFIX+'.getFunction("'+item.value+'")';
}
},
'Buffer': {
makeSerializable: function(item){
return {
type: 'Buffer',
value: item.toString('base64')
}
},
makeCode: function(item){
return 'Buffer.from("'+item.value+'", "base64")';
}
},
'Scope': {
makeSerializable: function(item, scope, exclude){
return {
type: 'Scope',
value: item.uri()
}
},
makeCode: function(item){
return SCOPE_PREFIX+'.getScope("'+(item.value.split('/').slice(1).join('/'))+'")';
}
},
'Pubsub': {
makeSerializable: function(item){
var safe = {
type: 'Pubsub',
value: {
id: item.id,
url: item.url,
handlers: {}
}
}
Object.keys(item.handlers).forEach(function(topic){
safe.value.handlers[topic] = makeSerializable(item.handlers[topic]);
});
return safe;
},
makeCode: function(item){
var handlers = '{'+Object.keys(item.value.handlers).map(function(topic){
return '"'+topic+'":'+makeCode(item.value.handlers[topic])
}).join(',')+'}';
return 'new '+SCOPE_PREFIX+'.Pubsub("'+item.value.url+'", { handlers: '+handlers+' })';
}
},
// 'things-js.reference': {
// makeCode: function(item){
// return item.uri;
// }
// },
'things-js.object': {
makeCode: function(item){
return SCOPE_PREFIX+'.createPointer("'+item.value+'")';
// return SCOPE_PREFIX+'.getObject("'+item.value+'")';
}
},
'things-js.import': {
makeCode: function(item){
return SCOPE_PREFIX+'.require("'+item.value+'")';
}
},
'things-js.verbatim': {
makeCode: function(item){
return item.value;
}
},
'undefined': {
makeCode: function(item){ return 'undefined' }
}
}
var LastObjectId = 0;
function makeSerializable(item, scope, exclude){
return makeSerializable[typeof item](item, scope, exclude);
}
makeSerializable['boolean'] = function(item){
return item;
}
makeSerializable['number'] = function(item){
return item;
}
makeSerializable['string'] = function(item){
return item;
}
makeSerializable['undefined'] = function(item){
return { type: 'undefined' }
}
makeSerializable['object'] = function(item, scope, exclude){
if (!item) return item;
else if (NATIVE_OBJECTS.has(item)) return { type: 'things-js.verbatim', value: NATIVE_OBJECTS.get(item) };
if (!exclude){
exclude = new Map();
}
if (exclude.has(item)) {
return { type: 'things-js.object', value: exclude.get(item) }
}
//let obj_id = scope.uri() + '.' + helpers.randKey();
let obj_id = scope.uri() + '.o' + (LastObjectId++);
exclude.set(item, obj_id);
// console.log(item);
if (item instanceof Array) return item.map(function(item){ return makeSerializable(item, scope, exclude) });
// For now, if it's a "require"d object, require it on the target node instead of migrating object.
if ((PROPERTY_PREFIX+'import') in item){
return {
type: 'things-js.import',
value: item[PROPERTY_PREFIX+'import']
}
};
if (item.constructor && item.constructor.name in NATIVE_TRANSFORMERS)
return Object.assign({ obj_id: obj_id }, NATIVE_TRANSFORMERS[item.constructor.name].makeSerializable(item, scope, exclude));
// If item.constructor is undefined, then object might have been created with Object.create(null). In this case, proceed normally as it's a native JS object.
var safe = {};
Object.keys(item).forEach(function(key){
// if (key === PROPERTY_PREFIX+'scope'){
// // console.log(item);
// item[key].frozen = true;
// }
if (key[0] !== PROPERTY_PREFIX) safe[key] = makeSerializable(item[key], scope, exclude);
})
// console.log(item.constructor.name);
return {
obj_id: obj_id,
type: item.constructor.name,
proto_uri: item.constructor[PROPERTY_PREFIX+'uri'],
scope_uri: item[PROPERTY_PREFIX+'scope'] ? item[PROPERTY_PREFIX+'scope'].uri() : null,
value: safe
}
}
makeSerializable['function'] = function(item, scope, exclude){
// For now, if it's a "require"d object, require it on the target node instead of migrating object.
if ((PROPERTY_PREFIX+'import') in item){
return {
type: 'things-js.import',
value: item[PROPERTY_PREFIX+'import']
}
};
return {