-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathpython-analyzer.ts
More file actions
1497 lines (1389 loc) · 48.9 KB
/
python-analyzer.ts
File metadata and controls
1497 lines (1389 loc) · 48.9 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
const SymAddress = require('../../common/sym-address')
const { Analyzer } = require('../../common')
const CheckerManager = require('../../common/checker-manager')
const BasicRuleHandler = require('../../../../checker/common/rules-basic-handler')
const PythonParser = require('../../../parser/python/python-ast-builder')
const {
ValueUtil: { ObjectValue, Scoped, PrimitiveValue, UndefinedValue, UnionValue, SymbolValue, PackageValue },
} = require('../../../util/value-util')
const logger = require('../../../../util/logger')(__filename)
const Config = require('../../../../config')
const { ErrorCode, Errors } = require('../../../../util/error-code')
const { assembleFullPath } = require('../../../../util/file-util')
const path = require('path')
const SourceLine = require('../../common/source-line')
const Uuid = require('node-uuid')
const Scope = require('../../common/scope')
const { unionAllValues } = require('../../common/memStateBVT')
const AstUtil = require('../../../../util/ast-util')
const { floor } = require('lodash')
const Stat = require('../../../../util/statistics')
const constValue = require('../../../../util/constant')
const entryPointConfig = require('../../common/current-entrypoint')
const FileUtil = require('../../../../util/file-util')
const globby = require('fast-glob')
const _ = require('lodash')
const { getSourceNameList } = require('./entrypoint-collector/python-entrypoint')
const { handleException } = require('../../common/exception-handler')
const { resolveImportPath } = require('./python-import-resolver')
/**
*
*/
class PythonAnalyzer extends (Analyzer as any) {
/**
*
* @param options
*/
constructor(options: any) {
const checkerManager = new CheckerManager(
options,
options.checkerIds,
options.checkerPackIds,
options.printers,
BasicRuleHandler
)
super(checkerManager, options)
this.fileList = []
this.astManager = {}
// 搜索路径列表(类似 Python 的 sys.path)
// 用于解析绝对导入,按优先级排序
this.searchPaths = []
}
/**
* 预处理阶段:扫描模块并解析代码
*
* @param dir - 项目目录
*/
async preProcess(dir: any) {
try {
;(this as any).thisIterationTime = 0
;(this as any).prevIterationTime = new Date().getTime()
this.scanModules(dir)
this.astManager = {}
} catch (e) {
handleException(
e,
`Error in PythonAnalyzer:preProcess \n${this.traceNodeInfo((this as any).lastProcessedNode)}`,
`Error in PythonAnalyzer:preProcess \n${this.traceNodeInfo((this as any).lastProcessedNode)}`
)
}
}
/**
*
* @param source
* @param fileName
*/
preProcess4SingleFile(source: any, fileName: any) {
;(this as any).thisIterationTime = 0
;(this as any).prevIterationTime = new Date().getTime()
this.fileList = [fileName]
const { options } = this
const ast = PythonParser.parseSingleFile(fileName, options)
this.astManager[fileName] = ast
this.addASTInfo(ast, source, fileName, false as any)
if (ast) {
this.processModule(ast, fileName, false as any)
}
SourceLine.storeCode(fileName, source)
}
/**
*
*/
symbolInterpret() {
const { entryPoints } = this as any
const state = this.initState(this.topScope)
if (_.isEmpty(entryPoints)) {
logger.info('[symbolInterpret]:EntryPoints are not found')
return true
}
const hasAnalysised: any[] = []
for (const entryPoint of entryPoints) {
if (entryPoint.type === constValue.ENGIN_START_FUNCALL) {
if (
hasAnalysised.includes(
`${entryPoint.filePath}.${entryPoint.functionName}/${entryPoint?.entryPointSymVal?._qid}#${entryPoint.entryPointSymVal.ast.parameters}.${entryPoint.attribute}`
)
) {
continue
}
hasAnalysised.push(
`${entryPoint.filePath}.${entryPoint.functionName}/${entryPoint?.entryPointSymVal?._qid}#${entryPoint.entryPointSymVal.ast.parameters}.${entryPoint.attribute}`
)
entryPointConfig.setCurrentEntryPoint(entryPoint)
logger.info(
'EntryPoint [%s.%s] is executing',
entryPoint.filePath?.substring(0, entryPoint.filePath?.lastIndexOf('.')),
entryPoint.functionName ||
`<anonymousFunc_${entryPoint.entryPointSymVal?.ast.loc.start.line}_$${
entryPoint.entryPointSymVal?.ast.loc.end.line
}>`
)
const fileFullPath = assembleFullPath(entryPoint.filePath, Config.maindir)
const sourceNameList = getSourceNameList()
this.refreshCtx(this.moduleManager.field[fileFullPath]?.field, sourceNameList)
this.refreshCtx(this.fileManager[fileFullPath]?.field, sourceNameList)
this.refreshCtx(this.packageManager.field[fileFullPath], sourceNameList)
this.checkerManager.checkAtSymbolInterpretOfEntryPointBefore(this, null, null, null, null)
const argValues: any[] = []
try {
for (const key in entryPoint.entryPointSymVal?.ast?.parameters) {
argValues.push(
this.processInstruction(
entryPoint.entryPointSymVal,
entryPoint.entryPointSymVal?.ast?.parameters[key]?.id,
state
)
)
}
} catch (e) {
handleException(
e,
'Error occurred in PythonAnalyzer.symbolInterpret: process argValue err',
'Error occurred in PythonAnalyzer.symbolInterpret: process argValue err'
)
}
if (
entryPoint?.entryPointSymVal?.parent?.vtype === 'class' &&
entryPoint?.entryPointSymVal?.parent?.field._CTOR_
) {
this.executeCall(
entryPoint.entryPointSymVal?.parent?.field?._CTOR_?.ast,
entryPoint.entryPointSymVal?.parent?.field?._CTOR_,
[],
state,
entryPoint.entryPointSymVal?.parent?.field?._CTOR_?.ast?.parent
)
}
try {
this.executeCall(
entryPoint.entryPointSymVal?.ast,
entryPoint.entryPointSymVal,
argValues,
state,
entryPoint.entryPointSymVal?.parent
)
} catch (e) {
handleException(
e,
`[${entryPoint.entryPointSymVal?.ast?.id?.name} symbolInterpret failed. Exception message saved in error log file`,
`[${entryPoint.entryPointSymVal?.ast?.id?.name} symbolInterpret failed. Exception message saved in error log file`
)
}
this.checkerManager.checkAtSymbolInterpretOfEntryPointAfter(this, null, null, null, null)
} else if (entryPoint.type === constValue.ENGIN_START_FILE_BEGIN) {
if (hasAnalysised.includes(`fileBegin:${entryPoint.filePath}.${entryPoint.attribute}`)) {
continue
}
hasAnalysised.push(`fileBegin:${entryPoint.filePath}.${entryPoint.attribute}`)
entryPointConfig.setCurrentEntryPoint(entryPoint)
logger.info('EntryPoint [%s] is executing ', entryPoint.filePath)
const fileFullPath = assembleFullPath(entryPoint.filePath, Config.maindir)
const sourceNameList = getSourceNameList()
this.refreshCtx(this.moduleManager.field[fileFullPath]?.field, sourceNameList)
this.refreshCtx(this.fileManager[fileFullPath]?.field, sourceNameList)
this.refreshCtx(this.packageManager.field[fileFullPath], sourceNameList)
const { filePath } = entryPoint
const scope = this.moduleManager.field[filePath]
if (scope) {
try {
this.checkerManager.checkAtSymbolInterpretOfEntryPointBefore(this, null, null, null, null)
this.processCompileUnit(scope, entryPoint.entryPointSymVal?.ast, state)
this.checkerManager.checkAtSymbolInterpretOfEntryPointAfter(this, null, null, null, null)
} catch (e) {
handleException(
e,
`[${entryPoint.entryPointSymVal?.ast?.loc?.sourcefile} symbolInterpret failed. Exception message saved in error log file`,
`[${entryPoint.entryPointSymVal?.ast?.loc?.sourcefile} symbolInterpret failed. Exception message saved in error log file`
)
}
}
}
}
return true
}
/**
*
* @param scope
* @param node
* @param state
*/
processBinaryExpression(scope: any, node: any, state: any) {
const new_node: any = _.clone(node)
new_node.ast = node
const new_left = (new_node.left = this.processInstruction(scope, node.left, state))
const new_right = (new_node.right = this.processInstruction(scope, node.right, state))
if (node.operator === 'push') {
this.processOperator(new_left.parent ? new_left.parent : new_left, node.left, new_right, node.operator, state)
}
if (node.operator === 'instanceof') {
new_node._meta.type = node.right
}
const has_tag = (new_left && new_left.hasTagRec) || (new_right && new_right.hasTagRec)
if (has_tag) {
new_node.hasTagRec = has_tag
}
if (this.checkerManager && (this.checkerManager as any).checkAtBinaryOperation)
this.checkerManager.checkAtBinaryOperation(this, scope, node, state, { newNode: new_node })
return SymbolValue(new_node)
}
/**
*
* @param scope
* @param node
* @param state
*/
processCallExpression(scope: any, node: any, state: any) {
if (this.checkerManager && (this.checkerManager as any).checkAtFuncCallSyntax)
this.checkerManager.checkAtFuncCallSyntax(this, scope, node, state, {
pcond: state.pcond,
einfo: state.einfo,
})
let fclos = this.processInstruction(scope, node.callee, state)
const callFallback = this.tryResolveMemberCallFallback(scope, node, state, fclos)
if (callFallback) {
fclos = callFallback
}
if (node?.callee?.type === 'MemberAccess' && fclos.fdef && node.callee?.object?.type !== 'SuperExpression') {
fclos._this = this.processInstruction(scope, node.callee.object, state)
}
if (!fclos) return UndefinedValue()
const argvalues: any[] = []
/**
*
* @param paramAST
* @param positionalArgs
* @param keywordArgs
* @param len
*/
function collectArgsFromArray(
paramAST: any[],
positionalArgs: any[],
keywordArgs: Record<string, any>,
len: number
) {
const paramNames = paramAST.map((n: any) => n.id.name)
const collectedArgs = new Array(len).fill(undefined)
positionalArgs.forEach((arg, index) => {
if (index < collectedArgs.length) collectedArgs[index] = arg
})
for (const [key, value] of Object.entries(keywordArgs)) {
const paramIndex = paramNames.indexOf(key)
if (paramIndex !== -1) collectedArgs[paramIndex] = value
}
return collectedArgs
}
const positionalArgs: any[] = []
const keywordArgs: Record<string, any> = {}
for (const arg of node.arguments) {
if (arg.type === 'VariableDeclaration') {
keywordArgs[arg.id.name] = arg
} else {
positionalArgs.push(arg)
}
}
let collectedArgs: any[]
if (fclos.fdef && fclos.fdef.type === 'FunctionDefinition') {
collectedArgs = collectArgsFromArray(fclos.ast.parameters, positionalArgs, keywordArgs, node.arguments.length)
} else {
collectedArgs = node.arguments
}
for (const arg of collectedArgs) {
const argv = this.processInstruction(scope, arg, state)
if ((logger as any).isTraceEnabled()) logger.trace(`arg: ${this.formatScope(argv)}`)
if (Array.isArray(argv)) argvalues.push(...argv)
else argvalues.push(argv)
}
if (argvalues && this.checkerManager) {
this.checkerManager.checkAtFunctionCallBefore(this, scope, node, state, {
argvalues,
fclos,
pcond: state.pcond,
entry_fclos: this.entry_fclos,
einfo: state.einfo,
state,
analyzer: this,
ainfo: this.ainfo,
})
}
if (fclos.vtype === 'class') {
return this.propagateNewObject(scope, node, state, fclos, argvalues)
}
// todo 待迁移到库函数建模中
if (node.callee.type === 'MemberAccess' && node.callee.property.name === 'append' && fclos?.object?.parent) {
this.saveVarInCurrentScope(fclos.object.parent, fclos.object, argvalues[0], state)
return
}
const res = this.executeCall(node, fclos, argvalues, state, scope)
this.propagateTaintFromMemberReceiver(node, fclos, res)
if (fclos.vtype !== 'fclos' && Config.invokeCallbackOnUnknownFunction) {
this.executeFunctionInArguments(scope, fclos, node, argvalues, state)
}
if (res && (this.checkerManager as any)?.checkAtFunctionCallAfter) {
this.checkerManager.checkAtFunctionCallAfter(this, scope, node, state, {
fclos,
ret: res,
argvalues,
pcond: state.pcond,
einfo: state.einfo,
callstack: state.callstack,
})
}
return res
}
/**
* Fallback for member calls unresolved as symbol/undefine.
* It binds the method by name from loaded class definitions to current receiver.
*/
tryResolveMemberCallFallback(scope: any, node: any, state: any, currentFclos: any) {
if (!node || node?.callee?.type !== 'MemberAccess') {
return undefined
}
if (!currentFclos || !['symbol', 'undefine', 'uninitialized'].includes(currentFclos.vtype)) {
return undefined
}
const prop = node.callee.property
if (!prop || prop.type !== 'Identifier' || !prop.name) {
return undefined
}
const receiver = this.processInstruction(scope, node.callee.object, state)
if (!receiver) {
return undefined
}
const preferredClassNames: string[] = []
const receiverName = `${receiver?.id || ''}.${receiver?.sid || ''}.${receiver?.qid || ''}`
if (receiverName.includes('SelectAction')) {
preferredClassNames.push('SelectAction')
}
if (receiverName.includes('QueryAction')) {
preferredClassNames.push('QueryAction')
}
for (const className of preferredClassNames) {
const cls = this.findClassInModules(className)
const method = cls?.value?.[prop.name]
if (method?.vtype === 'fclos') {
const methodCopy = _.clone(method)
methodCopy._this = receiver
methodCopy.parent = receiver
methodCopy.object = receiver
methodCopy._qid = `${receiver?.qid || receiver?.sid || className}.${prop.name}`
return methodCopy
}
}
const modules = this.moduleManager?.field || {}
for (const modKey of Object.keys(modules)) {
const modScope = modules[modKey]
for (const key of Object.keys(modScope?.value || {})) {
const cls = modScope.value[key]
if (cls?.vtype !== 'class') continue
const method = cls?.value?.[prop.name]
if (method?.vtype === 'fclos') {
const methodCopy = _.clone(method)
methodCopy._this = receiver
methodCopy.parent = receiver
methodCopy.object = receiver
methodCopy._qid = `${receiver?.qid || receiver?.sid || key}.${prop.name}`
return methodCopy
}
}
}
return undefined
}
/**
* Preserve taint on return value for member calls when receiver already carries taint.
* This helps Python dynamic method chains like str.split(...)->list[index] keep dataflow.
*/
propagateTaintFromMemberReceiver(node: any, fclos: any, ret: any) {
if (!ret || !node || node?.callee?.type !== 'MemberAccess') {
return
}
const receiver = fclos?.getThis ? fclos.getThis() : fclos?._this
if (!receiver || !(receiver.hasTagRec || AstUtil.hasTag(receiver, ''))) {
return
}
ret.hasTagRec = true
if (!ret._tags && receiver._tags) {
ret._tags = _.clone(receiver._tags)
}
if (!ret.trace && receiver.trace) {
ret.trace = _.clone(receiver.trace)
}
}
/**
*
* @param scope
* @param node
* @param state
* @param fclos
* @param argvalues
*/
propagateNewObject(scope: any, node: any, state: any, fclos: any, argvalues: any) {
if (fclos.field && Object.prototype.hasOwnProperty.call(fclos.field, '_CTOR_')) {
const res = this.buildNewObject(fclos.cdef, argvalues, fclos, state, node, scope)
if (res && (this.checkerManager as any)?.checkAtFunctionCallAfter) {
this.checkerManager.checkAtFunctionCallAfter(this, scope, node, state, {
fclos,
ret: res,
argvalues,
pcond: state.pcond,
einfo: state.einfo,
callstack: state.callstack,
})
}
return res
}
const res = this.processLibArgToRet(node, fclos, argvalues, scope, state)
if (res && (this.checkerManager as any)?.checkAtFunctionCallAfter) {
this.checkerManager.checkAtFunctionCallAfter(this, scope, node, state, {
fclos,
ret: res,
argvalues,
pcond: state.pcond,
einfo: state.einfo,
callstack: state.callstack,
})
}
return res
}
/**
*
* @param scope
* @param node
* @param state
*/
processIdentifier(scope: any, node: any, state: any) {
const res = super.processIdentifier(scope, node, state)
this.checkerManager.checkAtIdentifier(this, scope, node, state, { res })
return res
}
/**
* 处理 Python import 语句
*
* @param scope
* @param node
* @param state
*/
processImportDirect(scope: any, node: any, state: any) {
let { from, imported } = node
let sourcefile
while (imported) {
sourcefile = imported.loc.sourcefile
if (sourcefile) break
imported = from?.parent
}
if (!sourcefile) {
handleException(
null,
'Error occurred in PythonAnalyzer.processImportDirect: failed to sourcefile in ast',
'Error occurred in PythonAnalyzer.processImportDirect: failed to sourcefile in ast'
)
return UndefinedValue()
}
const sourceFileAbs = path.resolve(sourcefile.toString())
const projectRoot = Config.maindir?.replace(/\/$/, '') || path.dirname(sourceFileAbs)
let importPath: string | null = null
let modulePath: string | null = null
if (!from) {
// 处理 "import module" 形式的导入
const importName = imported.value || imported.name
if (importName) {
importPath = resolveImportPath(importName, sourceFileAbs, this.fileList, projectRoot)
}
} else {
// 处理 "from module import ..." 形式的导入
const fromValue = from.value
if (fromValue) {
if (fromValue.startsWith('.')) {
// 相对导入,需要区分两种情况:
// 1. "from .. import moduleName" - 导入整个模块,fromValue 只有点号(如 "..")
// 2. "from ..moduleName import fieldName" - 从模块中导入字段,fromValue 包含点号和模块名(如 "..moduleName")
const onlyDots = /^\.+$/.test(fromValue)
if (onlyDots) {
const moduleName = imported?.name && imported.name !== '*' ? imported.name : null
const { resolveRelativeImport } = require('./python-import-resolver')
importPath = resolveRelativeImport(fromValue, sourceFileAbs, this.fileList, moduleName || undefined)
// 不设置 modulePath,因为这是导入整个模块,应该返回整个模块对象
} else {
importPath = resolveImportPath(fromValue, sourceFileAbs, this.fileList, projectRoot)
if (imported && imported.name && imported.name !== '*') {
modulePath = imported.name
}
}
} else {
// 绝对导入
importPath = resolveImportPath(fromValue, sourceFileAbs, this.fileList, projectRoot)
if (imported && imported.name && imported.name !== '*') {
modulePath = imported.name
}
}
}
}
// 如果 resolver 找到了路径,加载模块
if (importPath) {
const normalizedPath = path.normalize(importPath)
let targetPath = normalizedPath
if (!targetPath.endsWith('.py')) {
// 可能是包目录,检查是否有 __init__.py
const initFile = path.join(targetPath, '__init__.py')
if (this.fileList.some((f: string) => path.normalize(f) === path.normalize(initFile))) {
targetPath = initFile
} else {
// 尝试添加 .py 扩展名
const pyFile = `${targetPath}.py`
if (this.fileList.some((f: string) => path.normalize(f) === path.normalize(pyFile))) {
targetPath = pyFile
}
}
}
const cachedModule = this.moduleManager.field[targetPath]
if (cachedModule) {
if (modulePath) {
const field = cachedModule.field?.[modulePath]
if (field) return field
}
return cachedModule
}
// 加载并处理模块
// 检查是否已经在处理中,防止循环导入导致的无限递归
const processingKey = `processing_${targetPath}`
if ((this as any)[processingKey]) {
logger.warn(`Circular import detected for: ${targetPath}`)
return UndefinedValue()
}
try {
;(this as any)[processingKey] = true
const ast = this.astManager[targetPath]
if (ast) {
const module = this.processModule(ast, targetPath, false as any)
if (module) {
if (modulePath) {
const field = module.field?.[modulePath]
if (field) {
delete (this as any)[processingKey]
return field
}
}
delete (this as any)[processingKey]
return module
}
}
delete (this as any)[processingKey]
} catch (e) {
delete (this as any)[processingKey]
handleException(
e,
`Error: PythonAnalyzer.processImportDirect: failed to loading: ${targetPath}`,
`Error: PythonAnalyzer.processImportDirect: failed to loading: ${targetPath}`
)
}
}
// 如果找不到,尝试作为三方库处理
const importName = from?.value || imported?.value || imported?.name
if (importName) {
return this.loadPredefinedModule(scope, imported?.name || importName, from?.value || 'syslib_from')
}
return UndefinedValue()
}
/**
*
* @param scope
* @param node
* @param state
*/
processMemberAccess(scope: any, node: any, state: any) {
const defscope = this.processInstruction(scope, node.object, state)
const prop = node.property
let resolved_prop = prop
if (node.computed) {
resolved_prop = this.processInstruction(scope, prop, state)
} else if (prop.type !== 'Identifier' && prop.type !== 'Literal') {
resolved_prop = this.processInstruction(scope, prop, state)
}
if (prop.type === 'Identifier' && prop.name === '__init__' && prop.parent?.parent?.type === 'CallExpression') {
resolved_prop.name = '_CTOR_'
}
if (!resolved_prop) return defscope
let res = this.getMemberValue(defscope, resolved_prop, state)
const taintedIndexFallback = this.tryResolveTaintedIndexFallback(node, defscope, resolved_prop, res)
if (taintedIndexFallback) {
res = taintedIndexFallback
}
const fallbackObject = this.tryResolveObjectsManagerFallback(defscope, resolved_prop, res)
if (fallbackObject) {
res = fallbackObject
}
if (this.checkerManager && (this.checkerManager as any).checkAtMemberAccess) {
this.checkerManager.checkAtMemberAccess(this, defscope, node, state, { res })
}
return res
}
/**
* Python negative-index / computed-index fallback:
* when member lookup fails on a tainted sequence-like value, preserve taint on indexed result.
* This keeps flows like `parts = s.split('__'); parts[-1]` alive even when list elements are not concretely modeled.
*/
tryResolveTaintedIndexFallback(node: any, defscope: any, resolvedProp: any, currentRes: any) {
const unresolved = !currentRes || ['symbol', 'undefine', 'uninitialized'].includes(currentRes.vtype)
if (!unresolved || !defscope) {
return undefined
}
const isComputed = !!node?.computed
const propType = resolvedProp?.type || resolvedProp?.ast?.type
const isIndexLikeProp =
isComputed || propType === 'UnaryExpression' || propType === 'Literal' || propType === 'primitive'
if (!isIndexLikeProp) {
return undefined
}
if (!(defscope.hasTagRec || AstUtil.hasTag(defscope, ''))) {
return undefined
}
const fallback = SymbolValue({
type: 'MemberAccess',
object: defscope,
property: resolvedProp,
ast: node,
sid: `${defscope?.sid || defscope?.id || 'obj'}[idx]`,
qid: `${defscope?.qid || defscope?.sid || defscope?.id || 'obj'}[idx]`,
})
fallback.hasTagRec = true
if (!fallback._tags && defscope._tags) {
fallback._tags = _.clone(defscope._tags)
}
if (!fallback.trace && defscope.trace) {
fallback.trace = _.clone(defscope.trace)
}
return fallback
}
/**
* Try resolving dynamic ORM-style "<Model>.objects" to QuerySet-like object when direct member lookup fails.
*/
tryResolveObjectsManagerFallback(defscope: any, resolved_prop: any, currentRes: any) {
if (!resolved_prop || resolved_prop.type !== 'Identifier' || resolved_prop.name !== 'objects') {
return undefined
}
if (!defscope || defscope.vtype !== 'class') {
return undefined
}
const unresolved = !currentRes || ['symbol', 'undefine', 'uninitialized'].includes(currentRes.vtype)
if (!unresolved) {
return undefined
}
const querySetClass = this.findClassInModules('QuerySet')
if (!querySetClass || querySetClass.vtype !== 'class') {
return undefined
}
return this.cloneClassMethodsAsObject(querySetClass, `${defscope?.id || 'Model'}_objects`)
}
/**
* Find a class symbol by name from processed python modules.
*/
findClassInModules(className: string) {
const modules = this.moduleManager?.field || {}
for (const modKey of Object.keys(modules)) {
const modScope = modules[modKey]
const candidate = modScope?.value?.[className]
if (candidate?.vtype === 'class') {
return candidate
}
}
return undefined
}
/**
* Create a lightweight object view from class methods to model descriptor-returned manager objects.
*/
cloneClassMethodsAsObject(classClos: any, objectName: string) {
const obj = ObjectValue({
id: objectName,
sid: objectName,
qid: objectName,
parent: classClos?.parent || this.topScope,
ast: classClos?.ast,
})
obj._this = obj
obj.vtype = 'object'
for (const fieldName in classClos?.value || {}) {
const v = classClos.value[fieldName]
if (!v) continue
const vCopy = _.clone(v)
vCopy._this = obj
vCopy.parent = obj
obj.value[fieldName] = vCopy
}
return obj
}
/**
*
* @param ast
* @param filename
* @param isReScan
*/
processModule(ast: any, filename: any, isReScan: any) {
if (!ast) {
process.exitCode = ErrorCode.fail_to_parse
const sourceFile = filename
Stat.fileIssues[sourceFile] = 'Parsing Error'
handleException(
null,
`Error occurred in JsAnalyzer.processModule: ${sourceFile} parse error`,
`Error occurred in JsAnalyzer.processModule: ${sourceFile} parse error`
)
return
}
this.preloadFileToPackage(ast, filename)
let m = this.moduleManager.field[filename]
if (m && !isReScan) return m
let relateFileName = 'file'
if (ast.loc?.sourcefile) {
relateFileName = ast.loc?.sourcefile?.startsWith(Config.maindirPrefix)
? ast.loc.sourcefile?.substring(Config.maindirPrefix.length).split('.')[0]
: ast.loc.sourcefile.split('.')[0]
}
const modClos = Scoped({ sid: relateFileName, parent: this.topScope, decls: {}, fdef: ast, ast })
this.moduleManager.field[filename] = modClos
this.fileManager[filename] = modClos
m = this.processModuleDirect(ast, filename, modClos)
;(m as any).ast = ast
return m
}
/**
*
* @param node
* @param filename
* @param modClos
*/
processModuleDirect(node: any, filename: any, modClos: any) {
if (!node || node.type !== 'CompileUnit') {
handleException(
null,
`node type should be CompileUnit, but ${node.type}`,
`node type should be CompileUnit, but ${node.type}`
)
return undefined
}
this.entry_fclos = modClos
this.thisFClos = modClos
const state = this.initState(modClos)
this.processInstruction(modClos, node, state)
return modClos
}
/**
*
* @param scope
* @param node
* @param state
*/
processNewObject(scope: any, node: any, state: any) {
const call = node
let fclos = this.processInstruction(scope, node.callee, state)
if (!fclos) return
if (fclos.vtype === 'union') {
fclos = fclos.value[0]
}
let argvalues: any[] = []
if (call.arguments) {
let same_args = true
for (const arg of call.arguments) {
const argv = this.processInstruction(scope, arg, state)
if (argv !== arg) same_args = false
argvalues.push(argv)
}
if (same_args) argvalues = call.arguments
}
const { fdef } = fclos
const obj = this.buildNewObject(fdef, argvalues, fclos, state, node, scope)
if ((logger as any).isTraceEnabled()) logger.trace(`new expression: ${this.formatScope(obj)}`)
if (obj && (this.checkerManager as any)?.checkAtNewExprAfter) {
this.checkerManager.checkAtNewExprAfter(this, scope, node, state, {
argvalues,
fclos,
ret: obj,
pcond: state.pcond,
einfo: state.einfo,
callstack: state.callstack,
})
}
return obj
}
/**
*
* @param scope
* @param node
* @param argvalues
* @param operator
* @param state
*/
processOperator(scope: any, node: any, argvalues: any, operator: any, state: any) {
switch (operator) {
case 'push': {
// Python list-comprehension in UAST lowers to temp-list + push operations.
// We need append semantics here instead of overwriting temp variable each time.
let container = this.getMemberValueNoCreate(scope, node, state)
if (!container || ['undefine', 'uninitialized', 'symbol'].includes(container.vtype)) {
const sid = node?.name || node?.sid || '__tmp__'
container = ObjectValue({
id: sid,
sid,
qid: scope?.qid ? `${scope.qid}.${sid}` : sid,
parent: scope,
})
container.vtype = 'object'
container._this = container
}
if (!container.value || typeof container.value !== 'object') {
container.value = {}
}
const numericIndices = Object.keys(container.value)
.filter((k) => /^\d+$/.test(k))
.map((k) => Number(k))
const nextIndex = numericIndices.length > 0 ? Math.max(...numericIndices) + 1 : 0
container.value[String(nextIndex)] = argvalues
this.saveVarInCurrentScope(scope, node, container, state)
const has_tag = (scope && scope.hasTagRec) || (argvalues && argvalues.hasTagRec) || container?.hasTagRec
if (has_tag) {
container.hasTagRec = has_tag
scope.hasTagRec = has_tag
}
}
}
}
/**
*
* @param scope
* @param node
* @param state
*/
processReturnStatement(scope: any, node: any, state: any) {
if (node.argument) {
const return_value = this.processInstruction(scope, node.argument, state)
if (!node.isYield) {
if (!(this as any).lastReturnValue) {
;(this as any).lastReturnValue = return_value
} else if ((this as any).lastReturnValue.vtype === 'union') {
;(this as any).lastReturnValue.appendValue(return_value)
} else {
const tmp = UnionValue()
tmp.appendValue((this as any).lastReturnValue)
tmp.appendValue(return_value)
;(this as any).lastReturnValue = tmp
}
if (!(node.argument.type === 'Identifier' && node.argument.name === 'self')) {
if (node.loc && (this as any).lastReturnValue)
(this as any).lastReturnValue = SourceLine.addSrcLineInfo(
(this as any).lastReturnValue,
node,
node.loc.sourcefile,
'Return Value: ',
'[return value]'
)
}
}
return return_value
}
return PrimitiveValue({ type: 'Literal', value: null, loc: node.loc })
}
/**
*
* @param scope
* @param node
* @param state
*/
processScopedStatement(scope: any, node: any, state: any) {
if (node.parent?.type === 'TryStatement') {
node.body
.filter((n: any) => needCompileFirst(n.type))
.forEach((s: any) => this.processInstruction(scope, s, state))
node.body
.filter((n: any) => !needCompileFirst(n.type))
.forEach((s: any) => this.processInstruction(scope, s, state))
} else {
const { loc } = node
let scopeName
if (loc) {
scopeName = `<block_${loc.start?.line}_${loc.start?.column}_${loc.end?.line}_${loc.end?.column}>`
} else {
scopeName = `<block_${Uuid.v4()}>`
}
let block_scope = scope
if (node.parent?.type === 'FunctionDefinition') {
// 只对函数体内的块语句创建子作用域,python的其他块语句不创建子作用域
block_scope = Scope.createSubScope(scopeName, scope, 'scope')
}
node.body
.filter((n: any) => needCompileFirst(n.type))
.forEach((s: any) => this.processInstruction(block_scope, s, state))
node.body
.filter((n: any) => !needCompileFirst(n.type))
.forEach((s: any) => this.processInstruction(block_scope, s, state))
}
if (this.checkerManager && (this.checkerManager as any).checkAtEndOfBlock) {
this.checkerManager.checkAtEndOfBlock(this, scope, node, state, {})
}
}
/**
*
* @param scope
* @param node
* @param state
*/
processVariableDeclaration(scope: any, node: any, state: any) {
const initialNode = node.init