forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNodes.qll
More file actions
1751 lines (1566 loc) · 54.2 KB
/
Nodes.qll
File metadata and controls
1751 lines (1566 loc) · 54.2 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
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
/**
* Provides classes representing particular kinds of data flow nodes, such
* as nodes corresponding to function definitions or nodes corresponding to
* parameters.
*/
private import javascript
private import semmle.javascript.dependencies.Dependencies
private import internal.CallGraphs
private import semmle.javascript.internal.CachedStages
private import semmle.javascript.dataflow.internal.PreCallGraphStep
/**
* A data flow node corresponding to an expression.
*
* Examples:
* ```js
* x + y
* Math.abs(x)
* ```
*/
class ExprNode extends DataFlow::ValueNode {
override Expr astNode;
pragma[nomagic]
ExprNode() { any() }
}
/**
* A data flow node corresponding to a parameter.
*
* For example, `x` is a parameter of `function f(x) {}`.
*
* When a parameter is a destructuring pattern, such as `{x, y}`, there is one
* parameter node representing the entire parameter, and separate `PropRead` nodes
* for the individual property patterns (`x` and `y`).
*/
class ParameterNode extends DataFlow::SourceNode {
Parameter p;
ParameterNode() { DataFlow::parameterNode(this, p) }
/** Gets the parameter to which this data flow node corresponds. */
Parameter getParameter() { result = p }
/** Gets the name of this parameter. */
string getName() { result = p.getName() }
/** Holds if this parameter is a rest parameter. */
predicate isRestParameter() { p.isRestParameter() }
/** Gets the data flow node for an expression that is applied to this decorator. */
DataFlow::Node getADecorator() {
result = this.getParameter().getADecorator().getExpression().flow()
}
}
/**
* A data flow node corresponding to a function invocation (with or without `new`).
*
* Examples:
* ```js
* Math.abs(x)
* new Array(16)
* ```
*/
class InvokeNode extends DataFlow::SourceNode instanceof DataFlow::Impl::InvokeNodeDef {
/** Gets the syntactic invoke expression underlying this function invocation. */
InvokeExpr getInvokeExpr() { result = super.getInvokeExpr() }
/** Gets the name of the function or method being invoked, if it can be determined. */
string getCalleeName() { result = super.getCalleeName() }
/** Gets the data flow node specifying the function to be called. */
DataFlow::Node getCalleeNode() { result = super.getCalleeNode() }
/**
* Gets the data flow node corresponding to the `i`th argument of this invocation.
*
* For direct calls, this is the `i`th argument to the call itself: for instance,
* for a call `f(x, y)`, the 0th argument node is `x` and the first argument node is `y`.
*
* For reflective calls using `call`, the 0th argument to the call denotes the
* receiver, so argument positions are shifted by one: for instance, for a call
* `f.call(x, y, z)`, the 0th argument node is `y` and the first argument node is `z`,
* while `x` is not an argument node at all.
*
* For reflective calls using `apply` we cannot, in general, tell which argument
* occurs at which position, so this predicate is not defined for such calls.
*
* Note that this predicate is not defined for arguments following a spread
* argument: for instance, for a call `f(x, ...y, z)`, the 0th argument node is `x`,
* but the position of `z` cannot be determined, hence there are no first and second
* argument nodes.
*/
cached
DataFlow::Node getArgument(int i) {
result = super.getArgument(i) and Stages::DataFlowStage::ref()
}
/** Gets the data flow node corresponding to an argument of this invocation. */
cached
DataFlow::Node getAnArgument() { result = super.getAnArgument() and Stages::DataFlowStage::ref() }
/** Gets the data flow node corresponding to the last argument of this invocation. */
cached
DataFlow::Node getLastArgument() {
result = this.getArgument(this.getNumArgument() - 1) and Stages::DataFlowStage::ref()
}
/**
* Gets a data flow node corresponding to an array of values being passed as
* individual arguments to this invocation.
*
* Examples:
* ```
* x.push(...args); // 'args' is a spread argument
* x.push(x, ...args, y, ...more); // 'args' and 'more' are a spread arguments
* Array.prototype.push.apply(x, args); // 'args' is a spread argument
* ```
* .
*/
DataFlow::Node getASpreadArgument() { result = super.getASpreadArgument() }
/** Gets the number of arguments of this invocation, if it can be determined. */
int getNumArgument() { result = super.getNumArgument() }
Function getEnclosingFunction() { result = this.getBasicBlock().getContainer() }
/**
* Gets a function passed as the `i`th argument of this invocation.
*
* This predicate only performs local data flow tracking.
* Consider using `getABoundCallbackParameter` to handle interprocedural flow of callback functions.
*/
FunctionNode getCallback(int i) { result.flowsTo(this.getArgument(i)) }
/**
* Gets a parameter of a callback passed into this call.
*
* `callback` indicates which argument the callback passed into, and `param`
* is the index of the parameter in the callback function.
*
* For example, for the call below, `getABoundCallbackParameter(1, 0)` refers
* to the parameter `e` (the first parameter of the second callback argument):
* ```js
* addEventHandler("click", e => { ... })
* ```
*
* This predicate takes interprocedural data flow into account, as well as
* partial function applications such as `.bind`.
*
* For example, for the call below `getABoundCallbackParameter(1, 0)` returns the parameter `e`,
* (the first parameter of the second callback argument), since the first parameter of `foo`
* has been bound by the `bind` call:
* ```js
* function foo(x, e) { }
* addEventHandler("click", foo.bind(this, "value of x"))
* ```
*/
ParameterNode getABoundCallbackParameter(int callback, int param) {
exists(int boundArgs |
result =
this.getArgument(callback).getABoundFunctionValue(boundArgs).getParameter(param + boundArgs)
)
}
/**
* Holds if the `i`th argument of this invocation is an object literal whose property
* `name` is set to `result`.
*/
pragma[nomagic]
DataFlow::ValueNode getOptionArgument(int i, string name) {
this.getOptionsArgument(i).hasPropertyWrite(name, result)
}
pragma[noinline]
private ObjectLiteralNode getOptionsArgument(int i) { result.flowsTo(this.getArgument(i)) }
/** Gets an abstract value representing possible callees of this call site. */
final AbstractValue getACalleeValue() {
exists(DataFlow::Node callee, DataFlow::AnalyzedNode analyzed |
pragma[only_bind_into](callee) = this.getCalleeNode() and
pragma[only_bind_into](analyzed) = callee.analyze() and
pragma[only_bind_into](result) = analyzed.getAValue()
)
}
/**
* Gets a potential callee of this call site.
*
* To alter the call graph as seen by the interprocedural data flow libraries, override
* the `getACallee(int imprecision)` predicate instead.
*/
final Function getACallee() { result = this.getACallee(0) }
/**
* Gets a callee of this call site where `imprecision` is a heuristic measure of how
* likely it is that `callee` is only suggested as a potential callee due to
* imprecise analysis of global variables and is not, in fact, a viable callee at all.
*
* Callees with imprecision zero, in particular, have either been derived without
* considering global variables, or are calls to a global variable within the same file,
* or a global variable that has unique definition within the project.
*
* This predicate can be overridden to alter the call graph used by the interprocedural
* data flow libraries.
*/
Function getACallee(int imprecision) {
result = CallGraph::getACallee(this, imprecision).getFunction()
}
/**
* Holds if the approximation of possible callees for this call site is
* affected by the given analysis incompleteness `cause`.
*/
predicate isIndefinite(DataFlow::Incompleteness cause) {
this.getACalleeValue().isIndefinite(cause)
}
/**
* Holds if our approximation of possible callees for this call site is
* likely to be imprecise.
*
* We currently track one specific source of imprecision: call
* resolution relies on flow through global variables, and the flow
* analysis finds possible callees that are not functions.
* This usually means that a global variable is used in multiple
* independent contexts, so tracking flow through it leads to
* imprecision.
*/
predicate isImprecise() {
this.isIndefinite("global") and
exists(DefiniteAbstractValue v | v = this.getACalleeValue() | not v instanceof AbstractCallable)
}
/**
* Holds if our approximation of possible callees for this call site is
* likely to be incomplete.
*/
predicate isIncomplete() {
// the flow analysis identifies a source of incompleteness other than
// global flow (which usually leads to imprecision rather than incompleteness)
any(DataFlow::Incompleteness cause | this.isIndefinite(cause)) != "global"
}
/**
* Holds if our approximation of possible callees for this call site is
* likely to be imprecise or incomplete.
*/
predicate isUncertain() { this.isImprecise() or this.isIncomplete() }
/**
* Gets the data flow node representing an exception thrown from this invocation.
*/
DataFlow::ExceptionalInvocationReturnNode getExceptionalReturn() {
DataFlow::exceptionalInvocationReturnNode(result, this.asExpr())
}
}
/**
* A data flow node corresponding to a function call without `new`.
*
* Examples:
* ```js
* Math.abs(x)
* ```
*/
class CallNode extends InvokeNode instanceof DataFlow::Impl::CallNodeDef {
/**
* Gets the data flow node corresponding to the receiver expression of this method call.
*
* For example, the receiver of `x.m()` is `x`.
*/
DataFlow::Node getReceiver() { result = super.getReceiver() }
}
/**
* A data flow node corresponding to a method call, that is,
* a call of form `x.m(...)`.
*
* Examples:
* ```js
* obj.foo()
* Math.abs(x)
* ```
*/
class MethodCallNode extends CallNode instanceof DataFlow::Impl::MethodCallNodeDef {
/** Gets the name of the invoked method, if it can be determined. */
string getMethodName() { result = super.getMethodName() }
/**
* Holds if this data flow node calls method `methodName` on receiver node `receiver`.
*/
predicate calls(DataFlow::Node receiver, string methodName) {
receiver = this.getReceiver() and
methodName = this.getMethodName()
}
}
/**
* A data flow node corresponding to a `new` expression.
*
* Examples:
* ```js
* new Array(16)
* ```
*/
class NewNode extends InvokeNode instanceof DataFlow::Impl::NewNodeDef { }
/**
* A data flow node corresponding to the `this` parameter in a function or `this` at the top-level.
*
* Each function only has one `this` node, even if it references `this` multiple times.
*/
class ThisNode extends DataFlow::Node, DataFlow::SourceNode {
ThisNode() { DataFlow::thisNode(this, _) }
/**
* Gets the function whose `this` binding this expression refers to,
* which is the nearest enclosing non-arrow function.
*/
FunctionNode getBinder() {
exists(Function binder |
DataFlow::thisNode(this, binder) and
result = DataFlow::valueNode(binder)
)
}
/**
* Gets the function or top-level whose `this` binding this expression refers to,
* which is the nearest enclosing non-arrow function or top-level.
*/
StmtContainer getBindingContainer() { DataFlow::thisNode(this, result) }
}
/**
* A data flow node corresponding to a global variable access through a simple identifier.
*
* For example, this includes `document` but not `window.document`.
* To recognize global variable access more generally, instead use `DataFlow::globalVarRef`
* or the member predicate `accessesGlobal`.
*
* Examples:
* ```js
* document
* Math
* NaN
* undefined
* ```
*/
class GlobalVarRefNode extends DataFlow::ValueNode, DataFlow::SourceNode {
override GlobalVarAccess astNode;
/** Gets the name of the global variable. */
string getName() { result = astNode.getName() }
}
/**
* Gets a data flow node corresponding to an access to the global object, including
* `this` expressions outside functions, references to global variables `window`
* and `global`, and uses of the `global` npm package.
*
* Examples:
* ```js
* window
* window.window
* global
* globalThis
* this
* self
* require('global/window')
* ```
*/
DataFlow::SourceNode globalObjectRef() {
// top-level `this`
exists(StmtContainer sc |
sc = result.(ThisNode).getBindingContainer() and
not sc instanceof Function and
not sc instanceof Templating::TemplateTopLevel
)
or
// DOM
result = globalVariable("window")
or
// DOM alias via `document.defaultView`
result = globalVariable("document").getAPropertyRead("defaultView")
or
// Node.js
result = globalVariable("global")
or
// DOM and service workers
result = globalVariable("self")
or
// ECMAScript 2020
result = globalVariable("globalThis")
or
// `require("global")`
result = moduleImport("global")
or
// Closure library - based on AST to avoid recursion with Closure library model
result = globalVariable("goog").getAPropertyRead("global")
}
/**
* Gets a reference to a global variable `name`.
* For example, if `name` is "foo":
* ```js
* foo
* require('global/foo')
* ```
*/
private DataFlow::SourceNode globalVariable(string name) {
result.(GlobalVarRefNode).getName() = name
or
// `require("global/document")` or `require("global/window")`
(name = "document" or name = "window") and
result = moduleImport("global/" + name)
}
/**
* Gets a data flow node corresponding to an access to global variable `name`,
* either directly, through `window` or `global`, or through the `global` npm package.
*
* Examples:
* ```js
* document
* Math
* window.document
* window.Math
* require('global/document')
* ```
*/
pragma[nomagic]
DataFlow::SourceNode globalVarRef(string name) {
result = globalVariable(name)
or
result = globalObjectRef().getAPropertyReference(name)
}
/**
* A data flow node corresponding to a function definition.
*
* Examples:
*
* ```
* function greet() { // function declaration
* console.log("Hi");
* }
*
* var greet =
* function() { // function expression
* console.log("Hi");
* };
*
* var greet2 =
* () => console.log("Hi") // arrow function expression
*
* var o = {
* m() { // function expression in a method definition in an object literal
* return 0;
* },
* get x() { // function expression in a getter method definition in an object literal
* return 1
* }
* };
*
* class C {
* m() { // function expression in a method definition in a class
* return 0;
* }
* }
* ```
*/
class FunctionNode extends DataFlow::ValueNode, DataFlow::SourceNode {
override Function astNode;
/** Gets the `i`th parameter of this function. */
ParameterNode getParameter(int i) { result = DataFlow::parameterNode(astNode.getParameter(i)) }
/** Gets a parameter of this function. */
ParameterNode getAParameter() { result = this.getParameter(_) }
/** Gets the parameter named `name` of this function, if any. */
DataFlow::ParameterNode getParameterByName(string name) {
result = this.getAParameter() and
result.getName() = name
}
/** Gets the number of parameters declared on this function. */
int getNumParameter() { result = count(astNode.getAParameter()) }
/** Gets the last parameter of this function. */
ParameterNode getLastParameter() { result = this.getParameter(this.getNumParameter() - 1) }
/** Holds if the last parameter of this function is a rest parameter. */
predicate hasRestParameter() { astNode.hasRestParameter() }
/** Gets the unqualified name of this function, if it has one or one can be determined from the context. */
string getName() { result = astNode.getName() }
/** Gets a data flow node corresponding to a return value of this function. */
DataFlow::Node getAReturn() { result = astNode.getAReturnedExpr().flow() }
/**
* Gets the function this node corresponds to.
*/
Function getFunction() { result = astNode }
/**
* Gets the function whose `this` binding a `this` expression in this function refers to,
* which is the nearest enclosing non-arrow function.
*/
FunctionNode getThisBinder() { result.getFunction() = this.getFunction().getThisBinder() }
/**
* Gets the dataflow node holding the value of the receiver passed to the given function.
*
* Has no result for arrow functions, as they ignore the receiver argument.
*
* To get the data flow node for `this` in an arrow function, consider using `getThisBinder().getReceiver()`.
*/
ThisNode getReceiver() { result.getBinder() = this }
/**
* Gets the data flow node representing an exception thrown from this function.
*/
DataFlow::ExceptionalFunctionReturnNode getExceptionalReturn() {
DataFlow::exceptionalFunctionReturnNode(result, astNode)
}
/**
* Gets the data flow node representing the value returned from this function.
*
* Note that this differs from `getAReturn()`, in that every function has exactly
* one canonical return node, but may have multiple (or zero) returned expressions.
* The result of `getAReturn()` is always a predecessor of `getReturnNode()`
* in the data-flow graph.
*/
DataFlow::FunctionReturnNode getReturnNode() { DataFlow::functionReturnNode(result, astNode) }
}
/**
* A data flow node corresponding to an object literal expression.
*
* Example:
* ```js
* var p = { // object literal containing five property definitions
* x: 1,
* y: 1,
* diag: function() { return this.x - this.y; },
* get area() { return this.x * this.y; },
* set area(a) { this.x = Math.sqrt(a); this.y = Math.sqrt(a); }
* };
* ```
*/
class ObjectLiteralNode extends DataFlow::ValueNode, DataFlow::SourceNode {
override ObjectExpr astNode;
/** Gets the value of a spread property of this object literal, such as `x` in `{...x}` */
DataFlow::Node getASpreadProperty() {
result = astNode.getAProperty().(SpreadProperty).getInit().(SpreadElement).getOperand().flow()
}
/** Gets the property getter of the given name, installed on this object literal. */
DataFlow::FunctionNode getPropertyGetter(string name) {
result = astNode.getPropertyByName(name).(PropertyGetter).getInit().flow()
}
/** Gets the property setter of the given name, installed on this object literal. */
DataFlow::FunctionNode getPropertySetter(string name) {
result = astNode.getPropertyByName(name).(PropertySetter).getInit().flow()
}
/** Gets the value of a computed property name of this object literal, such as `x` in `{[x]: 1}` */
DataFlow::Node getAComputedPropertyName() {
exists(Property prop | prop = astNode.getAProperty() |
prop.isComputed() and
result = prop.getNameExpr().flow()
)
}
}
/**
* A data flow node corresponding to an array literal expression.
*
* Example:
* ```
* [ 1, , [ 3, 4 ] ]
* ```
*/
class ArrayLiteralNode extends DataFlow::ValueNode, DataFlow::SourceNode {
override ArrayExpr astNode;
/** Gets the `i`th element of this array literal. */
DataFlow::ValueNode getElement(int i) { result = DataFlow::valueNode(astNode.getElement(i)) }
/** Gets an element of this array literal. */
DataFlow::ValueNode getAnElement() { result = DataFlow::valueNode(astNode.getAnElement()) }
/** Gets the initial size of this array. */
int getSize() { result = astNode.getSize() }
}
/**
* A data-flow node corresponding to a regular-expression literal.
*
* Examples:
* ```js
* /https?/i
* ```
*/
class RegExpLiteralNode extends DataFlow::ValueNode, DataFlow::SourceNode {
override RegExpLiteral astNode;
/** Holds if this regular expression has a `g` flag. */
predicate isGlobal() { astNode.isGlobal() }
/** Gets the root term of this regular expression. */
RegExpTerm getRoot() { result = astNode.getRoot() }
/** Gets the flags of this regular expression literal. */
string getFlags() { result = astNode.getFlags() }
}
/**
* A data flow node corresponding to a `new Array()` or `Array()` invocation.
*
* Examples:
* ```js
* Array('apple', 'orange') // two initial elements
* new Array('apple', 'orange')
* Array(16) // size 16 but no initial elements
* new Array(16)
* ```
*/
class ArrayConstructorInvokeNode extends DataFlow::InvokeNode {
ArrayConstructorInvokeNode() { this.getCalleeNode() = DataFlow::globalVarRef("Array") }
/** Gets the `i`th initial element of this array, if one is provided. */
DataFlow::ValueNode getElement(int i) {
this.getNumArgument() > 1 and // A single-argument invocation specifies the array length, not an element.
result = this.getArgument(i)
}
/** Gets an initial element of this array, if one is provided. */
DataFlow::ValueNode getAnElement() {
this.getNumArgument() > 1 and
result = this.getAnArgument()
}
/** Gets the initial size of the created array, if it can be determined. */
int getSize() {
if this.getNumArgument() = 1
then result = this.getArgument(0).getIntValue()
else result = count(this.getAnElement())
}
}
/**
* A data flow node corresponding to the creation or a new array, either through an array literal,
* an invocation of the `Array` constructor, or the `Array.from` method.
*
*
* Examples:
* ```js
* ['apple', 'orange'];
* Array('apple', 'orange')
* new Array('apple', 'orange')
* Array(16)
* new Array(16)
* ```
*/
class ArrayCreationNode extends DataFlow::ValueNode, DataFlow::SourceNode {
ArrayCreationNode() {
this instanceof ArrayLiteralNode or
this instanceof ArrayConstructorInvokeNode
}
/** Gets the `i`th initial element of this array, if one is provided. */
DataFlow::ValueNode getElement(int i) {
result = this.(ArrayLiteralNode).getElement(i) or
result = this.(ArrayConstructorInvokeNode).getElement(i)
}
/** Gets an initial element of this array, if one if provided. */
DataFlow::ValueNode getAnElement() { result = this.getElement(_) }
/** Gets the initial size of the created array, if it can be determined. */
int getSize() {
result = this.(ArrayLiteralNode).getSize() or
result = this.(ArrayConstructorInvokeNode).getSize()
}
/**
* Gets a data flow node corresponding to an array of values being passed as
* individual arguments to this array creation.
*/
DataFlow::Node getASpreadArgument() {
exists(SpreadElement arg | arg = this.getAnElement().getEnclosingExpr() |
result = DataFlow::valueNode(arg.getOperand())
)
}
}
/**
* A data flow node representing an import of a module, either through
* an `import` declaration, a call to `require`, or an AMD dependency parameter.
*
* For compatibility with old transpilers, we treat both `import * as x from '...'` and
* `import x from '...'` as module import nodes.
*
* Additional import nodes can be added by subclassing `ModuleImportNode::Range`.
*
* Examples:
* ```js
* require('fs');
* import * as fs from 'fs';
* import fs from 'fs';
* import { readDir } from 'fs'; // Note: 'readDir' is a PropRead with a ModuleImportNode as base
* define(["fs"], function(fs) { ... }); // AMD module
* ```
*/
class ModuleImportNode extends DataFlow::SourceNode instanceof ModuleImportNode::Range {
/** Gets the path of the imported module. */
string getPath() { result = super.getPath() }
}
module ModuleImportNode {
/**
* A data flow node that refers to an imported module.
*/
abstract class Range extends DataFlow::SourceNode {
/** Gets the path of the imported module. */
abstract string getPath();
}
private class DefaultRange extends Range {
string path;
DefaultRange() {
exists(Import i |
this = i.getImportedModuleNode() and
i.getImportedPathString() = path
)
or
// AMD require
exists(AmdModuleDefinition amd, CallExpr req |
req = amd.getARequireCall() and
this = DataFlow::valueNode(req) and
path = req.getArgument(0).getStringValue()
)
}
/** Gets the path of the imported module. */
override string getPath() { result = path }
}
}
/**
* Gets a (default) import of the module with the given path, such as `require("fs")`
* or `import * as fs from "fs"`.
*
* This predicate can be extended by subclassing `ModuleImportNode::Range`.
*/
cached
ModuleImportNode moduleImport(string path) {
// NB. internal modules may be imported with a "node:" prefix
Stages::Imports::ref() and result.getPath() = ["node:" + path, path]
}
/**
* Gets a (default) import of the given dependency `dep`, such as
* `require("lodash")` in a context where a package.json file includes
* `"lodash"` as a dependency.
*/
ModuleImportNode dependencyModuleImport(Dependency dep) {
result = dep.getAUse("import").(Import).getImportedModuleNode()
}
/**
* Gets a data flow node that either imports `m` from the module with
* the given `path`, or accesses `m` as a member on a default or
* namespace import from `path`.
*/
DataFlow::SourceNode moduleMember(string path, string m) {
result = moduleImport(path).getAPropertyRead(m)
}
/**
* The string `method`, `getter`, or `setter`, representing the kind of a function member
* in a class.
*
* Can can be used with `ClassNode.getInstanceMember` to obtain members of a specific kind.
*/
class MemberKind extends string {
MemberKind() { this = "method" or this = "getter" or this = "setter" }
/** Holds if this is the `method` kind. */
predicate isMethod() { this = MemberKind::method() }
/** Holds if this is the `getter` kind. */
predicate isGetter() { this = MemberKind::getter() }
/** Holds if this is the `setter` kind. */
predicate isSetter() { this = MemberKind::setter() }
/** Holds if this is the `getter` or `setter` kind. */
predicate isAccessor() { this = MemberKind::accessor() }
}
private import internal.StepSummary
module MemberKind {
/** Gets the kind of a method, such as `m() {}` */
MemberKind method() { result = "method" }
/** Gets the kind of a getter accessor, such as `get f() {}`. */
MemberKind getter() { result = "getter" }
/** Gets the kind of a setter accessor, such as `set f() {}`. */
MemberKind setter() { result = "setter" }
/** Gets the `getter` and `setter` kinds. */
MemberKind accessor() { result = getter() or result = setter() }
/**
* Gets the member kind of a given syntactic member declaration in a class.
*/
MemberKind of(MemberDeclaration decl) {
decl instanceof GetterMethodDeclaration and result = getter()
or
decl instanceof SetterMethodDeclaration and result = setter()
or
decl instanceof MethodDeclaration and
not decl instanceof AccessorMethodDeclaration and
not decl instanceof ConstructorDeclaration and
result = method()
}
}
/**
* A data flow node corresponding to a class definition or a function definition
* acting as a class.
*
* The following patterns are recognized as classes and methods:
* ```
* class C {
* method()
* }
*
* function F() {}
*
* F.prototype.method = function() {}
*
* F.prototype = {
* method: function() {}
* }
*
* extend(F.prototype, {
* method: function() {}
* });
* ```
*
* Additional patterns can be recognized as class nodes, by extending `DataFlow::ClassNode::Range`.
*/
class ClassNode extends DataFlow::ValueNode, DataFlow::SourceNode {
override AST::ValueNode astNode;
AbstractCallable function;
ClassNode() {
// ES6 class case
astNode instanceof ClassDefinition and
function.(AbstractClass).getClass() = astNode
or
// Function-style class case
astNode instanceof Function and
not astNode = any(ClassDefinition cls).getConstructor().getBody() and
function.getFunction() = astNode and
(
exists(getAFunctionValueWithPrototype(function))
or
function = any(NewNode new).getCalleeNode().analyze().getAValue()
or
exists(string name | this = AccessPath::getAnAssignmentTo(name) |
exists(getAPrototypeReferenceInFile(name, this.getFile()))
or
exists(getAnInstantiationInFile(name, this.getFile()))
)
)
}
/**
* Gets the unqualified name of the class, if it has one or one can be determined from the context.
*/
string getName() {
astNode instanceof ClassDefinition and result = astNode.(ClassDefinition).getName()
or
astNode instanceof Function and result = astNode.(Function).getName()
}
/**
* Gets a description of the class.
*/
string describe() {
astNode instanceof ClassDefinition and result = astNode.(ClassDefinition).describe()
or
astNode instanceof Function and result = astNode.(Function).describe()
}
/**
* Gets the constructor function of this class.
*/
FunctionNode getConstructor() {
// For ES6 classes
astNode instanceof ClassDefinition and
result = astNode.(ClassDefinition).getConstructor().getBody().flow()
or
// For function-style classes
astNode instanceof Function and result = this
}
/**
* Gets an instance method declared in this class, with the given name, if any.
*
* Does not include methods from superclasses.
*/
FunctionNode getInstanceMethod(string name) {
result = this.getInstanceMember(name, MemberKind::method())
}
/**
* Gets an instance method declared in this class.
*
* The constructor is not considered an instance method.
*
* Does not include methods from superclasses.
*/
FunctionNode getAnInstanceMethod() { result = this.getAnInstanceMember(MemberKind::method()) }
/**
* Gets the instance method, getter, or setter with the given name and kind.
*
* Does not include members from superclasses.
*/
FunctionNode getInstanceMember(string name, MemberKind kind) {
// ES6 class methods
exists(MethodDeclaration method |
astNode instanceof ClassDefinition and
method = astNode.(ClassDefinition).getMethod(name) and
not method.isStatic() and
kind = MemberKind::of(method) and
result = method.getBody().flow()
)
or
// Function-style class accessors
astNode instanceof Function and
exists(PropertyAccessor accessor |
accessor = this.getAnAccessor(kind) and
accessor.getName() = name and
result = accessor.getInit().flow()
)
or
kind = MemberKind::method() and
result =
[
this.getConstructor().getReceiver().getAPropertySource(name),
this.getAPrototypeReference().getAPropertySource(name)
]
}
/**
* Gets an instance method, getter, or setter with the given kind.
*
* Does not include members from superclasses.
*/
FunctionNode getAnInstanceMember(MemberKind kind) {
// ES6 class methods
exists(MethodDeclaration method |
astNode instanceof ClassDefinition and
method = astNode.(ClassDefinition).getAMethod() and
not method.isStatic() and
kind = MemberKind::of(method) and
result = method.getBody().flow()
)
or
// Function-style class accessors
astNode instanceof Function and
exists(PropertyAccessor accessor |
accessor = this.getAnAccessor(kind) and
result = accessor.getInit().flow()
)
or
kind = MemberKind::method() and
result =
[
this.getConstructor().getReceiver().getAPropertySource(),
this.getAPrototypeReference().getAPropertySource()
]
}