-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasses.py
More file actions
1686 lines (1418 loc) · 62.3 KB
/
passes.py
File metadata and controls
1686 lines (1418 loc) · 62.3 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
import ast
from model import ThreadTarget, Scope
from collections import defaultdict
class PCNodeVisitor(ast.NodeVisitor):
'''
Custom NodeVisitor that enables parent tracking for upwards recursion
'''
def generic_visit(self, node):
for child in ast.iter_child_nodes(node):
child.parent = node
self.visit(child)
class ImportDetection(ast.NodeVisitor):
'''
This pass of the AST is meant to detect
whether a file contains the threading import
'''
def __init__(self):
self.uses_threading = False
# checks normal "import ...,x,..." where x is a multithreading module
def visit_Import(self, node):
for alias in node.names:
if alias.name in {"threading",
"_thread",
"concurrent.futures",
"multiprocessing.pool"}:
self.uses_threading = True
return
self.generic_visit(node)
# checks "from x import ..." where x is a multithreading module
def visit_ImportFrom(self, node):
if node.module in {"threading",
"_thread",
"concurrent",
"concurrent.futures",
"multiprocessing.pool"}:
self.uses_threading = True
return
# Just in case
for alias in node.names:
if alias.name in {"Thread",
"start_new_thread",
"ThreadPoolExecutor",
"ThreadPool"}:
self.uses_threading = True
return
self.generic_visit(node)
class SymbolPass(PCNodeVisitor):
'''
This pass of the AST is meant to gather the names and locations
of global, nonlocal variables and function definitions to later
use as potential pieces of interest in threads, as well as
gathering info about class definitions for later resolution of method calls;
we also capture rudimentary data about various ways threads are instantiated
'''
def __init__(self, model, src=None):
self.model = model
self.current_function = None
self.current_class = None
with open(src, "r") as f:
self.model.total_lines = len(f.read().splitlines())
# Simply used to update the live class we're visiting
def visit_ClassDef(self, node):
previous_class = self.current_class
self.current_class = node.name
for base in node.bases:
if self._is_thread_base(base):
self.model.thread_subclasses.add(node.name)
break
self.generic_visit(node)
self.current_class = previous_class
# Functions are saved with their qualified name
# which helps to resolve thread accesses that
# use class data instead of simple module-level data
def visit_FunctionDef(self, node):
if self.current_class:
qualified_name = f"{self.current_class}.{node.name}"
else:
qualified_name = node.name
self.current_function = qualified_name
self.model.functions[qualified_name] = node
# If a function is defined within a class,
# we want to save the qualified name as well for later reference
if self.current_class:
self.model.method_to_class[qualified_name] = self.current_class
self.model.class_methods \
.setdefault(self.current_class, set()) \
.add(qualified_name)
previous = self.current_function
self.current_function = node.name
self.generic_visit(node)
self.current_function = previous
# Interestingly enough, asynch func defs are
# completely different nodes but they are treated the same
visit_AsyncFunctionDef = visit_FunctionDef
# add globals to model
def visit_Global(self, node):
for name in node.names:
self.model.globals[name] = node
# if we're in a function,
# tie that global to the function
if self.current_function:
self.model.function_globals \
.setdefault(self.current_function, set()) \
.add(name)
# add nonlocals to model
def visit_Nonlocal(self, node):
for name in node.names:
self.model.nonlocals[name] = node
if self.current_function:
self.model.function_nonlocals \
.setdefault(self.current_function, set()) \
.add(name)
def visit_Assign(self, node):
# Module-level variables are special in that
# threads can access them without needing a global declaration,
# so we want to track them, especially since we need to
# verify any thread targets access them after their initial assignment
if self.current_function is None:
for target in node.targets:
for name in self._extract_names(target):
self.model.module_vars[name] = node
# Here we capture any instantiations from function calls
# that either alias to known threading constructs or are used as thread targets
if isinstance(node.value, ast.Call):
func = node.value.func
is_executor = (
isinstance(func, ast.Name) and func.id in ("ThreadPoolExecutor", "ThreadPool")
) or (
isinstance(func, ast.Attribute) and func.attr in ("ThreadPoolExecutor", "ThreadPool")
)
# Greedily add assignments as executors
if is_executor:
for target in node.targets:
for name in self._extract_names(target):
self.model.executors \
.setdefault(name, set()) \
.add(node.value)
is_thread = (
isinstance(func, ast.Name) and func.id == "Thread"
) or (
isinstance(func, ast.Attribute) and func.attr == "Thread"
) or (
isinstance(func, ast.Name) and func.id in self.model.thread_subclasses
) or (
isinstance(func, ast.Attribute) and func.attr in self.model.thread_subclasses
)
if is_thread:
for target in node.targets:
for name in self._extract_names(target):
self.model.thread_vars.add(name)
# We also capture Queue instantiations since they are thread-safe
is_queue = (
isinstance(func, ast.Name) and func.id in {"Queue", "SimpleQueue", "PriorityQueue"}
) or (
isinstance(func, ast.Attribute) and func.attr in {"Queue", "SimpleQueue", "PriorityQueue"}
)
if is_queue:
type_name = func.id if isinstance(func, ast.Name) else func.attr
for target in node.targets:
for name in self._extract_names(target):
self.model.var_types[name] = type_name
# Also capture info about class attribute instantiations
if self.current_class and self.current_function:
for target in node.targets:
if (isinstance(target, ast.Attribute)
and isinstance(target.value, ast.Name)
and target.value.id == "self"):
qualified = f"{self.current_class}.{target.attr}"
self.model.class_attrs[qualified] = node
self.generic_visit(node)
# Threading constructs often use context managers, so we visit these as well
def visit_With(self, node):
for with_item in node.items:
context_expr = with_item.context_expr
if isinstance(context_expr, ast.Call):
func = context_expr.func
is_executor = (
isinstance(func, ast.Name) and func.id in ("ThreadPoolExecutor", "ThreadPool")
) or (
isinstance(func, ast.Attribute) and func.attr in ("ThreadPoolExecutor", "ThreadPool")
)
if is_executor:
alias = with_item.optional_vars
if isinstance(alias, ast.Name):
name = alias.id
self.model.executors \
.setdefault(name, set())\
.add(context_expr)
self.generic_visit(node)
def _extract_names(self, node):
if isinstance(node, ast.Name):
return [node.id]
elif isinstance(node, (ast.Tuple, ast.List)):
names = []
for elt in node.elts:
names.extend(self._extract_names(elt))
return names
return []
# Helper to check if a class inherits from threading.Thread
def _is_thread_base(self, node):
if isinstance(node, ast.Name) and node.id == "Thread":
return True
elif isinstance(node, ast.Attribute) and node.attr == "Thread":
return True
# Assumes the parent class is defined first, and in the same file
elif isinstance(node, ast.Name) and node.id in self.model.thread_subclasses:
return True
else:
return False
COLLECTION_CONSTRUCTORS = {"list", "dict", "set", "defaultdict", "OrderedDict", "Counter"}
QUEUE_TYPES = {"Queue", "SimpleQueue", "PriorityQueue"}
class TypeInferencePass(PCNodeVisitor):
'''
This pass of the AST is meant to gather types of
variables (namely default data structures) created in the
program so we can filter out the mutations to Python's
naturally unsafe default collections like lists, sets, and dicts
'''
def __init__(self, model) -> None:
self.model = model
self.current_function = None
self.current_class = None
# Standard scoping rules
def visit_ClassDef(self, node) -> None:
prev = self.current_class
self.current_class = node.name
self.generic_visit(node)
self.current_class = prev
def visit_FunctionDef(self, node) -> None:
prev = self.current_function
self.current_function = node.name
self.generic_visit(node)
self.current_function = prev
visit_AsyncFunctionDef = visit_FunctionDef
# Visit variable assignments, and populate var_types
# If we're looking at class attributes, qualify their full name
def visit_Assign(self, node) -> None:
inferred = self._infer(node.value)
if inferred:
for target in node.targets:
for name in self._extract_names(target):
self.model.var_types[name] = inferred
# Handle self.x = [] / self.x = {} / self.x = set()
if (isinstance(target, ast.Attribute)
and isinstance(target.value, ast.Name)
and target.value.id == "self"
and self.current_class):
qualified = f"{self.current_class}.{target.attr}"
self.model.var_types[qualified] = inferred
self.model.var_types[target.attr] = inferred
self.generic_visit(node)
# Properly annotated variables are different nodes,
# but are inferred more straightforwardly
def visit_AnnAssign(self, node) -> None:
inferred = self._infer(node.value) if node.value else self._infer_annotation(node.annotation)
if inferred:
if isinstance(node.target, ast.Name):
self.model.var_types[node.target.id] = inferred
# Also store qualified name if we're in a class
if self.current_class:
qualified = f"{self.current_class}.{node.target.id}"
self.model.var_types[qualified] = inferred
elif (isinstance(node.target, ast.Attribute)
and isinstance(node.target.value, ast.Name)
and node.target.value.id == "self"
and self.current_class):
qualified = f"{self.current_class}.{node.target.attr}"
self.model.var_types[qualified] = inferred
self.model.var_types[node.target.attr] = inferred
self.generic_visit(node)
# Helper that takes a node and looks at the type
def _infer(self, node) -> str | None:
if node is None:
return None
if isinstance(node, (ast.List, ast.ListComp)):
return "list"
if isinstance(node, (ast.Dict, ast.DictComp)):
return "dict"
if isinstance(node, (ast.Set, ast.SetComp)):
return "set"
# Constructor calls: list(), dict(), set(), defaultdict(list), etc.
if isinstance(node, ast.Call):
return self._infer_call(node)
if isinstance(node, ast.Subscript):
if isinstance(node.slice, ast.Slice):
return self._infer(node.value)
# For operations like x = [] + [] or x = set() | set()
if isinstance(node, ast.BinOp):
if isinstance(node.op, ast.Add):
left = self._infer(node.left)
if left: return left
return self._infer(node.right)
if isinstance(node.op, ast.BitOr):
return self._infer(node.left) or self._infer(node.right)
return None
def _infer_call(self, node):
if isinstance(node.func, ast.Name):
name = node.func.id
if name in COLLECTION_CONSTRUCTORS:
# Normalize defaultdict/OrderedDict()
return {"defaultdict": "dict", "OrderedDict": "dict",
"Counter": "dict"}.get(name, name)
if name in QUEUE_TYPES:
return name
elif isinstance(node.func, ast.Attribute):
# Normalize collections.defaultdict(...)
if node.func.attr in COLLECTION_CONSTRUCTORS:
return {"defaultdict": "dict", "OrderedDict": "dict",
"Counter": "dict"}.get(node.func.attr, node.func.attr)
if node.func.attr in QUEUE_TYPES:
return node.func.attr
return None
def _infer_annotation(self, node):
# Handles bare annotations like x: list
if isinstance(node, ast.Name) and node.id in {"list", "dict", "set"}:
return node.id
# Handles subscript annotations like x: list[int]
if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name):
if node.value.id in {"List", "Dict", "Set", "list", "dict", "set"}:
return node.value.id.lower()
if node.value.id == "Optional":
return self._infer_annotation(node.slice)
# Handles union annotations like x: list | None
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
left = self._infer_annotation(node.left)
if left: return left
return self._infer_annotation(node.right)
return None
def _extract_names(self, node):
if isinstance(node, ast.Name):
return [node.id]
elif isinstance(node, (ast.Tuple, ast.List)):
names = []
for elt in node.elts:
names.extend(self._extract_names(elt))
return names
return []
class ScopePass(PCNodeVisitor):
'''
This pass of the AST is meant to go over the function
definitions, variable writes in each function/scope
and define the stack scope for each one
'''
def __init__(self, model):
self.model = model
self.scope_stack: list[Scope] = []
self.current_class = None
def current_scope(self):
return self.scope_stack[-1] if self.scope_stack else None
def visit_ClassDef(self, node):
previous = self.current_class
self.current_class = node.name
self.generic_visit(node)
self.current_class = previous
'''
Whenever we enter a function definition, we create a new scope
and add the parameters as local variables (this is somewhat pessimistic,
as it can be a copy of a variable or a reference). When we exit,
we pop the scope and save it in the program model for later use.
'''
def visit_FunctionDef(self, node):
if self.current_class:
qualified_name = f"{self.current_class}.{node.name}"
else:
qualified_name = node.name
scope = Scope(parent=self.current_scope())
self.scope_stack.append(scope)
# parameters are locals
for arg in node.args.args:
scope.locals.add(arg.arg)
self.generic_visit(node)
self.model.function_scopes[qualified_name] = scope
self.scope_stack.pop()
visit_AsyncFunctionDef = visit_FunctionDef
def visit_Name(self, node):
scope = self.current_scope()
if scope and isinstance(node.ctx, ast.Store):
if node.id not in scope.globals and node.id not in scope.nonlocals:
scope.locals.add(node.id)
def visit_Global(self, node):
scope = self.current_scope()
if scope:
scope.globals.update(node.names)
def visit_Nonlocal(self, node):
scope = self.current_scope()
if scope:
scope.nonlocals.update(node.names)
def visit_For(self, node):
scope = self.current_scope()
if scope:
for name in self._extract_names(node.target):
scope.locals.add(name)
self.generic_visit(node)
def visit_With(self, node):
scope = self.current_scope()
if scope:
for item in node.items:
if item.optional_vars:
for name in self._extract_names(item.optional_vars):
scope.locals.add(name)
self.generic_visit(node)
def visit_ExceptHandler(self, node):
scope = self.current_scope()
if scope and node.name:
scope.locals.add(node.name)
self.generic_visit(node)
# Comprehensions create their own scope in Python 3,
# so we don't want their variables leaking into the enclosing scope
def visit_ListComp(self, node):
self._visit_comprehension(node)
def visit_SetComp(self, node):
self._visit_comprehension(node)
def visit_DictComp(self, node):
self._visit_comprehension(node)
def visit_GeneratorExp(self, node):
self._visit_comprehension(node)
def _extract_names(self, node):
if isinstance(node, ast.Name):
return [node.id]
elif isinstance(node, (ast.Tuple, ast.List)):
names = []
for elt in node.elts:
names.extend(self._extract_names(elt))
return names
return []
# As long as we create a new scope for the comprehension
# and don't add any of its variables to the enclosing scope,
# we can just visit it normally without worrying about the details
def _visit_comprehension(self, node):
comp_scope = Scope(parent=self.current_scope())
self.scope_stack.append(comp_scope)
for generator in node.generators:
for name in self._extract_names(generator.target):
comp_scope.locals.add(name)
self.generic_visit(node)
self.scope_stack.pop()
class ThreadPass(PCNodeVisitor):
'''
This pass of the AST is meant to gather
info about which functions are designated
as Thread targets and saves their nodes
and other relevant information for later use
'''
def __init__(self, model):
self.model = model
self.current_class = None
def visit_ClassDef(self, node):
previous = self.current_class
self.current_class = node.name
self.generic_visit(node)
self.current_class = previous
# We look for both explicit Thread(target=...) cases
# and classes that inherit from Thread and define run()
def visit_FunctionDef(self, node):
if (self.current_class
and self.current_class in self.model.thread_subclasses
and node.name == "run"):
qualified_name = f"{self.current_class}.run"
if qualified_name not in self.model.seen_targets \
and qualified_name in self.model.functions:
target = ThreadTarget(name=qualified_name,
class_name=self.current_class,
node=node,
parent_target=None,
root_target=qualified_name)
self.model.thread_targets.append(target)
self.model.seen_targets.add(qualified_name)
self.generic_visit(node)
visit_AsyncFunctionDef = visit_FunctionDef
def _check_threading(self, node, kw):
if kw.arg == "target":
name = self._qualify(kw.value)
# Only targets known as defined functions are added
if name and name not in self.model.seen_targets \
and name in self.model.functions.keys():
target = ThreadTarget(name=name,
class_name=self.current_class,
node=node,
parent_target=None,
root_target=name)
self.model.thread_targets.append(target)
self.model.seen_targets.add(name)
def _check_thread(self, arg):
# The first argument to start_new_thread() is the target function
name = self._qualify(arg)
if name and name not in self.model.seen_targets \
and name in self.model.functions.keys():
target = ThreadTarget(name=name,
class_name=self.current_class,
node=arg,
parent_target=None,
root_target=name)
self.model.thread_targets.append(target)
self.model.seen_targets.add(name)
def _check_executor(self, arg, executor_node=None):
name = self._qualify(arg)
if name and name not in self.model.seen_targets \
and name in self.model.functions.keys():
# Check if the call is on a known executor
executor_name = self._qualify(executor_node) if executor_node else None
if executor_name and executor_name in self.model.executors:
target = ThreadTarget(name=name,
class_name=self.current_class,
node=arg,
parent_target=None,
root_target=name)
self.model.thread_targets.append(target)
self.model.seen_targets.add(name)
def visit_Call(self, node):
# Look for calls to Thread(target=...)
if isinstance(node.func, ast.Name):
if node.func.id == "Thread":
for kw in node.keywords:
self._check_threading(node, kw)
# Most cases, we are calling attribute methods
elif isinstance(node.func, ast.Attribute):
if node.func.attr == "Thread":
for kw in node.keywords:
self._check_threading(node, kw)
# or for _threading.start_new_thread(...) cases
elif node.func.attr == "start_new_thread":
if node.args:
self._check_thread(node.args[0])
# or for executor.submit/map(...) cases
elif node.func.attr in ("submit", "map",
"imap", "imap_unordered", "starmap", "apply_async"):
if node.args:
self._check_executor(node.args[0], node.func.value)
elif node.func.attr == "start":
receiver = node.func.value
if isinstance(receiver, ast.Name):
if receiver.id in self.model.thread_vars:
self.model.thread_start_lines.append(node.lineno)
self.generic_visit(node)
def _qualify(self, node):
if isinstance(node, ast.Attribute):
method = node.attr
# Resolve self.method -> "ClassName.method"
if isinstance(node.value, ast.Name) and node.value.id == "self":
if self.current_class:
qualified = f"{self.current_class}.{method}"
if qualified in self.model.functions:
return qualified
for _class, methods in self.model.class_methods.items():
if method in methods:
return f"{self.current_class}.{method}" if self.current_class else method
return method
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Lambda):
body = node.body
if isinstance(body, ast.Call):
return self._qualify(body.func)
return None
class CallGraphPass(PCNodeVisitor):
'''
This pass of the AST is meant to
build a call graph so we can
find "transitive ThreadTargets"
'''
def __init__(self, model):
self.model = model
self.current_function = None
self.current_class = None
def visit_ClassDef(self, node):
prev = self.current_class
self.current_class = node.name
self.generic_visit(node)
self.current_class = prev
def visit_FunctionDef(self, node):
if self.current_class:
fname = f"{self.current_class}.{node.name}"
else:
fname = node.name
self.model.call_graph.setdefault(fname, set())
prev = self.current_function
self.current_function = fname
self.generic_visit(node)
self.current_function = prev
visit_AsyncFunctionDef = visit_FunctionDef
# Find any function calls that exist
# within functions and add them to the call graph
def visit_Call(self, node):
if not self.current_function:
return
callee = None
if isinstance(node.func, ast.Name):
callee = node.func.id
elif isinstance(node.func, ast.Attribute):
bare = node.func.attr
if self.current_class:
qualified = f"{self.current_class}.{bare}"
callee = qualified if qualified in self.model.functions else bare
else:
callee = bare
if callee and callee in self.model.functions:
self.model.call_graph[self.current_function].add(callee)
self.generic_visit(node)
class ThreadExpansion:
'''
This class is meant to update the
program model so that we include
the indirect thread targets
'''
def __init__(self, model):
self.model = model
def expand(self):
worklist = [t.name for t in self.model.thread_targets]
visited = set(worklist)
while worklist:
current = worklist.pop()
for callee in self.model.call_graph.get(current, []):
# Only consider known functions
if callee in self.model.functions and callee not in visited:
visited.add(callee)
worklist.append(callee)
# Add as synthetic thread target
class_name = self.model.method_to_class.get(callee)
root_target = current.root_target if current in self.model.thread_targets else current
self.model.thread_targets.append(
ThreadTarget(name=callee,
class_name=class_name,
node=self.model.functions[callee],
parent_target=current,
root_target=root_target)
)
# We only care about list, set, and dict mutations
MUTATING_METHODS = {
"append", "extend", "insert", "remove", "pop", "clear", "sort", "reverse",
"add", "discard", "pop", "clear", "update", "intersection_update", "difference_update", "symmetric_difference_update",
"clear", "pop", "popitem", "setdefault", "update",
}
class TargetPass(PCNodeVisitor):
'''
This pass of the AST is meant to target specifically the
functions designated as ThreadTargets and gather information
about the variable reads, writes, function calls with
potential side effects, and subscript/attribute accesses
'''
def __init__(self,
model = None,
scope: Scope = None,
class_name: str = None,
var_types = None):
self.model = model
self.scope = scope
self.class_name = class_name
self.var_types = var_types
self.reads = defaultdict(list)
self.writes = defaultdict(list)
self.calls = defaultdict(list)
# For attribute accesses, we need to
# extract the entire chain: class.list.append()
def get_full_attr_name(self, node):
parts = []
current = node
while isinstance(current, ast.Attribute):
parts.append(current.attr)
current = current.value
if isinstance(current, ast.Name):
parts.append(current.id)
return ".".join(reversed(parts))
return None
# For reads/writes within thread targets
def visit_Name(self, node):
parent = getattr(node, "parent", None)
# If this Name is part of ANY attribute chain, ignore it
if isinstance(parent, ast.Attribute) and parent.value is node:
return
# If this Name is part of a call (foo()), ignore it
if isinstance(parent, ast.Call) and parent.func is node:
return
if node.id in self.scope.locals:
# If this is a local variable, we can ignore it for cross-thread sharing purposes
self.generic_visit(node)
return
# Otherwise only standalone variables count
if isinstance(node.ctx, ast.Load):
self.reads[node.id].append(node)
elif isinstance(node.ctx, ast.Store):
self.writes[node.id].append(node)
# For shorthand exprs like x += 1
def visit_AugAssign(self, node):
target = node.target
if isinstance(target, ast.Name):
self.reads[target.id].append(node)
self.writes[target.id].append(node)
elif isinstance(target, ast.Attribute):
full_name = self.get_full_attr_name(target)
if full_name and full_name.startswith("self.") and self.class_name:
full_name = f"{self.class_name}.{full_name[5:]}"
if full_name:
self.reads[full_name].append(node)
self.writes[full_name].append(node)
elif isinstance(target, ast.Subscript):
if isinstance(target.value, ast.Name):
self.reads[target.value.id].append(node)
self.writes[target.value.id].append(node)
elif isinstance(target.value, ast.Attribute):
full_name = self.get_full_attr_name(target.value)
if full_name and full_name.startswith("self.") and self.class_name:
full_name = f"{self.class_name}.{full_name[5:]}"
if full_name:
self.reads[full_name].append(node)
self.writes[full_name].append(node)
# Don't call generic_visit, we'll double count
# self.generic_visit(node)
self.visit(node.value)
# For attribute accesses like class.x
def visit_Attribute(self, node):
full_name = self.get_full_attr_name(node)
if full_name and full_name.startswith("self.") and self.class_name:
full_name = f"{self.class_name}.{full_name[5:]}"
if full_name:
# If this attribute is part of a Call, classify ONLY as call, not read
if isinstance(node.parent, ast.Call) and node.parent.func is node:
return
root = full_name.split(".")[0]
if self.scope and root in self.scope.locals and root not in {"self", "cls"}:
# If the root of this attribute is a local variable,
# we can ignore it for cross-thread sharing purposes
self.generic_visit(node)
return
if isinstance(node.ctx, ast.Load):
self.reads[full_name].append(node)
elif isinstance(node.ctx, ast.Store):
self.writes[full_name].append(node)
self.generic_visit(node)
# For method calls that may be
# mutating a shared data structure
def visit_Call(self, node):
func_name = None
if isinstance(node.func, ast.Name):
func_name = node.func.id
if func_name in MUTATING_METHODS:
self.calls[func_name].append(node)
elif isinstance(node.func, ast.Attribute):
func_name = self.get_full_attr_name(node.func)
if func_name and func_name.startswith("self.") and self.class_name:
func_name = f"{self.class_name}.{func_name[5:]}"
method = node.func.attr
obj = node.func.value
# Record method calls that mutate,
# but filter out mutations to known
# thread-safe queue types and collections
# that are locally defined within the function
if method in MUTATING_METHODS:
if isinstance(obj, ast.Name):
obj_type = self.var_types.get(obj.id)
if obj_type not in QUEUE_TYPES and (obj_type in {"list", "set", "dict"} or obj_type is None):
self.calls[func_name].append(node)
if self.scope and obj.id not in self.scope.locals:
self.writes[obj.id].append(node)
elif isinstance(obj, ast.Attribute):
full_obj = self.get_full_attr_name(obj)
if full_obj and full_obj.startswith("self.") and self.class_name:
full_obj = f"{self.class_name}.{full_obj[5:]}"
if full_obj:
# Check if any prefix resolves to a queue type, e.g. "_HandlerThread._queue.queue"
# should be suppressed because "_HandlerThread._queue" is a Queue
obj_root = ".".join(full_obj.split(".")[:2])
if (self.var_types.get(full_obj) in QUEUE_TYPES
or self.var_types.get(obj_root) in QUEUE_TYPES):
pass
else:
self.calls[full_obj + "." + method].append(node)
self.writes[full_obj].append(node)
self.generic_visit(node)
# For subscript reads/writes
def visit_Subscript(self, node):
if isinstance(node.ctx, ast.Store):
if isinstance(node.value, ast.Name):
self.writes[node.value.id].append(node)
elif isinstance(node.value, ast.Attribute):
full_name = self.get_full_attr_name(node.value)
if full_name and full_name.startswith("self.") and self.class_name:
full_name = f"{self.class_name}.{full_name[5:]}"
if full_name:
self.writes[full_name].append(node)
elif isinstance(node.ctx, ast.Load):
if isinstance(node.value, ast.Name):
self.reads[node.value.id].append(node)
elif isinstance(node.value, ast.Attribute):
full_name = self.get_full_attr_name(node.value)
if full_name and full_name.startswith("self.") and self.class_name:
full_name = f"{self.class_name}.{full_name[5:]}"
if full_name:
self.reads[full_name].append(node)
# for del list[x] or del list[:]
def visit_Delete(self, node):
for target in node.targets:
if isinstance(target, ast.Subscript):
if isinstance(target.value, ast.Name):
self.writes[target.value.id].append(node)
elif isinstance(target.value, ast.Attribute):
full_name = self.get_full_attr_name(target.value)
if full_name and full_name.startswith("self.") and self.class_name:
full_name = f"{self.class_name}.{full_name[5:]}"
if full_name:
self.writes[full_name].append(node)
# del list (the variable itself)
elif isinstance(target, ast.Name):
self.writes[target.id].append(node)
self.generic_visit(node)
def visit_ListComp(self, node):
self._visit_comprehension(node)
def visit_SetComp(self, node):
self._visit_comprehension(node)
def visit_DictComp(self, node):
self._visit_comprehension(node)
def visit_GeneratorExp(self, node):
self._visit_comprehension(node)
def _visit_comprehension(self, node):
saved = set(self.scope.locals)
for generator in node.generators:
for name in self._extract_names(generator.target):
self.scope.locals.add(name)
self.generic_visit(node)
self.scope.locals = saved
def _extract_names(self, node):
if isinstance(node, ast.Name):
return [node.id]
elif isinstance(node, (ast.Tuple, ast.List)):
names = []
for elt in node.elts:
names.extend(self._extract_names(elt))
return names
return []
class TargetUpdate:
'''
This class is meant to update the program model
with the relevant data collected from the thread pass
'''
def __init__(self, model):
self.model = model
def update_thread_accesses(self):
# if not self.model.thread_targets:
# print("No thread targets found...")
for target in self.model.thread_targets:
target_node = self.model.functions[target.name]
target_scope = self.model.function_scopes.get(target.name)
target_class = target.class_name
parser = TargetPass(model = self.model,
scope = target_scope,
class_name = target_class,
var_types = self.model.var_types)
parser.visit(target_node)
target.reads = parser.reads
target.writes = parser.writes
target.calls = parser.calls
class ClassResolutionPass(PCNodeVisitor):
'''
This pass of the AST is meant to check
targets belonging to a class and capture
info about instance attributes, as thread
detection for thread targets within classes
is handled slightly differently than in the ThreadPass
'''
def __init__(self, model):
self.model = model
# A method is reachable from another thread if it's called by the target