AutoCython-zhang 2.3.10__tar.gz → 2.3.11__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython/_version.py +1 -1
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython/compile.py +154 -12
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython/obfuscate.py +438 -76
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython/run_tasks.py +13 -7
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython/tools.py +1 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/PKG-INFO +2 -2
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/PKG-INFO +2 -2
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/README.md +1 -1
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython/AutoCython.py +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython/__init__.py +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/SOURCES.txt +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/dependency_links.txt +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/entry_points.txt +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/requires.txt +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/top_level.txt +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/LICENSE +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/MANIFEST.in +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/pyproject.toml +0 -0
- {autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/setup.cfg +0 -0
|
@@ -227,9 +227,15 @@ def _find_pydantic_model_classes(tree):
|
|
|
227
227
|
elif match_mapping_type is not None and isinstance(node, match_mapping_type) and node.rest:
|
|
228
228
|
shadow({node.rest})
|
|
229
229
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
230
|
+
if isinstance(scope_node, ast.ClassDef):
|
|
231
|
+
# Python 的 class 命名空间不构成内部方法或嵌套类体的外层词法作用域。
|
|
232
|
+
child_bases = tuple(inherited_bases)
|
|
233
|
+
child_models = tuple(inherited_models)
|
|
234
|
+
child_modules = tuple(inherited_modules)
|
|
235
|
+
else:
|
|
236
|
+
child_bases = tuple(base_names)
|
|
237
|
+
child_models = tuple(known_models)
|
|
238
|
+
child_modules = tuple(module_prefixes)
|
|
233
239
|
for node in nodes:
|
|
234
240
|
if isinstance(node, _SCOPE_TYPES) and node is not scope_node:
|
|
235
241
|
visit_scope(node, child_bases, child_models, child_modules)
|
|
@@ -322,6 +328,45 @@ def _build_pydantic_shim_source(node, forbidden_names):
|
|
|
322
328
|
)
|
|
323
329
|
|
|
324
330
|
|
|
331
|
+
def _is_computed_field_decorator(dec) -> bool:
|
|
332
|
+
target = dec.func if isinstance(dec, ast.Call) else dec
|
|
333
|
+
dotted = _dotted_name(target)
|
|
334
|
+
return bool(dotted and (dotted == "computed_field" or dotted.endswith(".computed_field")))
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _has_property_decorator(decorator_list) -> bool:
|
|
338
|
+
for dec in decorator_list:
|
|
339
|
+
dotted = _dotted_name(dec)
|
|
340
|
+
if dotted in {"property", "builtins.property", "cached_property", "functools.cached_property"}:
|
|
341
|
+
return True
|
|
342
|
+
return False
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _class_has_cython_callable(node: ast.ClassDef) -> bool:
|
|
346
|
+
return any(
|
|
347
|
+
isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda))
|
|
348
|
+
for item in _walk_scope_nodes(node.body)
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _collect_all_bound_names(tree: ast.AST):
|
|
353
|
+
bound = set()
|
|
354
|
+
for child in ast.walk(tree):
|
|
355
|
+
if isinstance(child, ast.Name) and isinstance(child.ctx, (ast.Store, ast.Del)):
|
|
356
|
+
bound.add(child.id)
|
|
357
|
+
elif isinstance(child, ast.arg):
|
|
358
|
+
bound.add(child.arg)
|
|
359
|
+
elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
360
|
+
bound.add(child.name)
|
|
361
|
+
elif isinstance(child, ast.ExceptHandler) and child.name:
|
|
362
|
+
bound.add(child.name)
|
|
363
|
+
elif isinstance(child, (ast.Import, ast.ImportFrom)):
|
|
364
|
+
for alias in child.names:
|
|
365
|
+
if alias.name != "*":
|
|
366
|
+
bound.add(alias.asname or alias.name.split(".", 1)[0])
|
|
367
|
+
return bound
|
|
368
|
+
|
|
369
|
+
|
|
325
370
|
def _add_pydantic_ignored_types(source_code: str) -> str:
|
|
326
371
|
"""Make Pydantic v2 models tolerate Cython's bound method type.
|
|
327
372
|
|
|
@@ -338,23 +383,98 @@ def _add_pydantic_ignored_types(source_code: str) -> str:
|
|
|
338
383
|
|
|
339
384
|
class_nodes = [
|
|
340
385
|
node for node in _find_pydantic_model_classes(tree)
|
|
341
|
-
if
|
|
386
|
+
if _class_has_cython_callable(node)
|
|
342
387
|
]
|
|
343
388
|
|
|
344
389
|
if not class_nodes:
|
|
345
390
|
return source_code
|
|
346
391
|
|
|
347
|
-
# Inject only at the
|
|
392
|
+
# Inject only at the affected class/decorator lines. Re-unparsing the
|
|
348
393
|
# entire module would discard comments/formatting and can change unrelated
|
|
349
394
|
# plain source even though only one model needs the compatibility shim.
|
|
350
395
|
lines = source_code.splitlines(keepends=True)
|
|
351
396
|
newline = "\r\n" if "\r\n" in source_code else "\n"
|
|
352
397
|
forbidden_names = _collect_identifier_names(tree)
|
|
398
|
+
all_bound_names = _collect_all_bound_names(tree)
|
|
399
|
+
has_future_annotations = any(
|
|
400
|
+
isinstance(stmt, ast.ImportFrom)
|
|
401
|
+
and stmt.module == "__future__"
|
|
402
|
+
and any(alias.name == "annotations" for alias in stmt.names)
|
|
403
|
+
for stmt in tree.body
|
|
404
|
+
)
|
|
405
|
+
prop_decorator = (
|
|
406
|
+
'@property'
|
|
407
|
+
if 'property' not in all_bound_names
|
|
408
|
+
else '@(__builtins__["property"] if isinstance(__builtins__, dict) else __builtins__.property)'
|
|
409
|
+
)
|
|
353
410
|
insertions = []
|
|
411
|
+
inline_modified = False
|
|
354
412
|
for node in class_nodes:
|
|
355
|
-
if not node.body
|
|
413
|
+
if not node.body:
|
|
356
414
|
continue
|
|
357
415
|
config_source = _build_pydantic_shim_source(node, forbidden_names)
|
|
416
|
+
if node.lineno == node.end_lineno:
|
|
417
|
+
if "\n" not in config_source:
|
|
418
|
+
last_stmt = node.body[-1]
|
|
419
|
+
end_col = getattr(last_stmt, "end_col_offset", None)
|
|
420
|
+
if isinstance(end_col, int):
|
|
421
|
+
raw_line = lines[node.lineno - 1].encode("utf-8")
|
|
422
|
+
lines[node.lineno - 1] = (
|
|
423
|
+
raw_line[:end_col]
|
|
424
|
+
+ f"; {config_source}".encode("utf-8")
|
|
425
|
+
+ raw_line[end_col:]
|
|
426
|
+
).decode("utf-8")
|
|
427
|
+
inline_modified = True
|
|
428
|
+
continue
|
|
429
|
+
|
|
430
|
+
for item in _walk_scope_nodes(node.body):
|
|
431
|
+
if not isinstance(item, ast.FunctionDef):
|
|
432
|
+
continue
|
|
433
|
+
cf_decorators = [d for d in item.decorator_list if _is_computed_field_decorator(d)]
|
|
434
|
+
if not cf_decorators:
|
|
435
|
+
continue
|
|
436
|
+
if item.returns is not None:
|
|
437
|
+
ret_unparsed = ast.unparse(item.returns)
|
|
438
|
+
ret_expr = repr(ret_unparsed) if has_future_annotations else ret_unparsed
|
|
439
|
+
for dec in cf_decorators:
|
|
440
|
+
if isinstance(dec, ast.Call) and any(
|
|
441
|
+
kw.arg == "return_type" for kw in dec.keywords
|
|
442
|
+
):
|
|
443
|
+
continue
|
|
444
|
+
dec_end_line = getattr(dec, "end_lineno", None)
|
|
445
|
+
dec_end_col = getattr(dec, "end_col_offset", None)
|
|
446
|
+
if not isinstance(dec_end_line, int) or not isinstance(dec_end_col, int):
|
|
447
|
+
continue
|
|
448
|
+
raw_dec_line = lines[dec_end_line - 1].encode("utf-8")
|
|
449
|
+
if isinstance(dec, ast.Call):
|
|
450
|
+
if dec_end_col > 0 and raw_dec_line[dec_end_col - 1 : dec_end_col] == b")":
|
|
451
|
+
prefix = raw_dec_line[: dec_end_col - 1]
|
|
452
|
+
if not (dec.args or dec.keywords):
|
|
453
|
+
patch_bytes = f"return_type={ret_expr}".encode("utf-8")
|
|
454
|
+
elif prefix.rstrip().endswith(b","):
|
|
455
|
+
patch_bytes = f" return_type={ret_expr}".encode("utf-8")
|
|
456
|
+
else:
|
|
457
|
+
patch_bytes = f", return_type={ret_expr}".encode("utf-8")
|
|
458
|
+
lines[dec_end_line - 1] = (
|
|
459
|
+
prefix + patch_bytes + raw_dec_line[dec_end_col - 1 :]
|
|
460
|
+
).decode("utf-8")
|
|
461
|
+
inline_modified = True
|
|
462
|
+
else:
|
|
463
|
+
lines[dec_end_line - 1] = (
|
|
464
|
+
raw_dec_line[:dec_end_col]
|
|
465
|
+
+ f"(return_type={ret_expr})".encode("utf-8")
|
|
466
|
+
+ raw_dec_line[dec_end_col:]
|
|
467
|
+
).decode("utf-8")
|
|
468
|
+
inline_modified = True
|
|
469
|
+
|
|
470
|
+
if not _has_property_decorator(item.decorator_list):
|
|
471
|
+
outermost_cf = cf_decorators[-1]
|
|
472
|
+
cf_line = lines[outermost_cf.lineno - 1]
|
|
473
|
+
prop_indent = cf_line[: len(cf_line) - len(cf_line.lstrip())]
|
|
474
|
+
insertions.append(
|
|
475
|
+
(outermost_cf.end_lineno, 0, f"{prop_indent}{prop_decorator}{newline}")
|
|
476
|
+
)
|
|
477
|
+
|
|
358
478
|
class_line = lines[node.lineno - 1]
|
|
359
479
|
class_indent = class_line[: len(class_line) - len(class_line.lstrip())]
|
|
360
480
|
body_stmt = next(
|
|
@@ -370,17 +490,17 @@ def _add_pydantic_ignored_types(source_code: str) -> str:
|
|
|
370
490
|
indented_config = newline.join(
|
|
371
491
|
body_indent + line for line in config_source.splitlines()
|
|
372
492
|
) + newline
|
|
373
|
-
insertions.append((insert_at, len(body_indent), indented_config))
|
|
493
|
+
insertions.append((insert_at, -len(body_indent), indented_config))
|
|
374
494
|
|
|
375
|
-
if not insertions:
|
|
495
|
+
if not insertions and not inline_modified:
|
|
376
496
|
return source_code
|
|
377
497
|
|
|
378
|
-
if lines and not lines[-1].endswith(("\n", "\r")):
|
|
498
|
+
if insertions and lines and not lines[-1].endswith(("\n", "\r")):
|
|
379
499
|
lines[-1] = lines[-1] + newline
|
|
380
500
|
|
|
381
501
|
for line_number, _, text in sorted(
|
|
382
502
|
insertions,
|
|
383
|
-
key=lambda item: (item[0],
|
|
503
|
+
key=lambda item: (item[0], item[1]),
|
|
384
504
|
reverse=True,
|
|
385
505
|
):
|
|
386
506
|
offset = min(line_number, len(lines))
|
|
@@ -413,7 +533,10 @@ def _strip_binary(path):
|
|
|
413
533
|
after_header = binary_file.read(4)
|
|
414
534
|
binary_file.seek(0, os.SEEK_END)
|
|
415
535
|
after_size = binary_file.tell()
|
|
416
|
-
|
|
536
|
+
# DWARF5 debug sections often exceed 75% of an unstripped shared
|
|
537
|
+
# object's size; use a conservative floor that rejects truncated headers
|
|
538
|
+
# without silently rolling back legitimate strip output.
|
|
539
|
+
minimum_size = max(64, before_size // 32) if before_size is not None else 0
|
|
417
540
|
return (
|
|
418
541
|
bool(after_header)
|
|
419
542
|
and after_header == before_header
|
|
@@ -665,6 +788,14 @@ def check_output_collisions(file_paths) -> None:
|
|
|
665
788
|
f"Output module name collision ({safe_stem!r}) between "
|
|
666
789
|
f"{abs_path} and existing {existing_peer}"
|
|
667
790
|
)
|
|
791
|
+
existing_pkg_init = os.path.abspath(
|
|
792
|
+
os.path.join(source_dir, safe_stem, "__init__.py")
|
|
793
|
+
)
|
|
794
|
+
if os.path.isfile(existing_pkg_init):
|
|
795
|
+
raise ValueError(
|
|
796
|
+
f"Output module name collision ({safe_stem!r}) between "
|
|
797
|
+
f"{abs_path} and existing package {os.path.dirname(existing_pkg_init)}"
|
|
798
|
+
)
|
|
668
799
|
seen[key] = abs_path
|
|
669
800
|
|
|
670
801
|
|
|
@@ -693,6 +824,8 @@ def compile_to_binary(file_path: str, del_source=False, obfuscate=True, obfuscat
|
|
|
693
824
|
if ext != '.py':
|
|
694
825
|
raise ValueError(f"ValueError: The file {file_path} is not a valid Python file (.py)!")
|
|
695
826
|
|
|
827
|
+
check_output_collisions([abs_file_path])
|
|
828
|
+
|
|
696
829
|
module_layout = _resolve_module_layout(abs_file_path)
|
|
697
830
|
safe_module_name = module_layout['safe_module_name']
|
|
698
831
|
target_ext = get_platform_extension()
|
|
@@ -737,9 +870,15 @@ def compile_to_binary(file_path: str, del_source=False, obfuscate=True, obfuscat
|
|
|
737
870
|
_write_source(temp_file_path, transformed_source, source_encoding)
|
|
738
871
|
|
|
739
872
|
setup_code = f"""
|
|
873
|
+
import os
|
|
740
874
|
from setuptools import setup
|
|
741
875
|
from setuptools import Extension
|
|
742
876
|
from Cython.Build import cythonize
|
|
877
|
+
from Cython.Compiler import Options as _cython_options
|
|
878
|
+
|
|
879
|
+
# Match standard Python semantics: reading a local in an untaken branch before
|
|
880
|
+
# its assignment raises UnboundLocalError at runtime instead of failing build.
|
|
881
|
+
_cython_options.error_on_uninitialized = False
|
|
743
882
|
|
|
744
883
|
compiler_directives = {{
|
|
745
884
|
'language_level': '3',
|
|
@@ -748,6 +887,7 @@ compiler_directives = {{
|
|
|
748
887
|
'binding': True,
|
|
749
888
|
'embedsignature': False,
|
|
750
889
|
}}
|
|
890
|
+
extra_compile_args = ['-g0', '-fvisibility=hidden'] if os.name != 'nt' else []
|
|
751
891
|
|
|
752
892
|
setup(
|
|
753
893
|
ext_modules=cythonize(
|
|
@@ -755,9 +895,11 @@ setup(
|
|
|
755
895
|
Extension(
|
|
756
896
|
{repr(module_layout['qualified_module_name'])},
|
|
757
897
|
[{repr(rel_temp_file_path)}],
|
|
898
|
+
extra_compile_args=extra_compile_args,
|
|
758
899
|
)
|
|
759
900
|
],
|
|
760
901
|
compiler_directives=compiler_directives,
|
|
902
|
+
c_line_in_traceback=False,
|
|
761
903
|
force=True
|
|
762
904
|
)
|
|
763
905
|
)
|
|
@@ -766,7 +908,7 @@ setup(
|
|
|
766
908
|
with open(setup_path, 'w', encoding='utf-8') as f:
|
|
767
909
|
f.write(setup_code)
|
|
768
910
|
|
|
769
|
-
command = [sys.executable, 'setup.py', 'build_ext']
|
|
911
|
+
command = [sys.executable, 'setup.py', '--no-user-cfg', 'build_ext']
|
|
770
912
|
try:
|
|
771
913
|
result = subprocess.run(
|
|
772
914
|
command,
|
|
@@ -78,6 +78,82 @@ class _EscapedStringLiteral(str):
|
|
|
78
78
|
return "'" + ''.join(escaped) + "'"
|
|
79
79
|
|
|
80
80
|
|
|
81
|
+
def _has_unsafe_dir_usage(nodes):
|
|
82
|
+
"""检测零参 ``dir()`` 或将 ``dir`` 作为一等函数值引用的动态局部作用域访问。"""
|
|
83
|
+
node_list = list(nodes)
|
|
84
|
+
safe_dir_func_ids = set()
|
|
85
|
+
for child in node_list:
|
|
86
|
+
if (
|
|
87
|
+
isinstance(child, ast.Call)
|
|
88
|
+
and isinstance(child.func, ast.Name)
|
|
89
|
+
and child.func.id == 'dir'
|
|
90
|
+
and (child.args or child.keywords)
|
|
91
|
+
):
|
|
92
|
+
safe_dir_func_ids.add(id(child.func))
|
|
93
|
+
elif (
|
|
94
|
+
isinstance(child, ast.Call)
|
|
95
|
+
and isinstance(child.func, ast.Attribute)
|
|
96
|
+
and child.func.attr == 'dir'
|
|
97
|
+
and not child.args
|
|
98
|
+
and not child.keywords
|
|
99
|
+
and isinstance(child.func.value, ast.Name)
|
|
100
|
+
and child.func.value.id in {'builtins', '__builtins__'}
|
|
101
|
+
):
|
|
102
|
+
return True
|
|
103
|
+
for child in node_list:
|
|
104
|
+
if (
|
|
105
|
+
isinstance(child, ast.Name)
|
|
106
|
+
and isinstance(child.ctx, ast.Load)
|
|
107
|
+
and child.id == 'dir'
|
|
108
|
+
and id(child) not in safe_dir_func_ids
|
|
109
|
+
):
|
|
110
|
+
return True
|
|
111
|
+
return False
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _has_indirect_unsafe_lookup(nodes):
|
|
115
|
+
"""检测同一作用域内通过 ``getattr(builtins, "locals")`` 或 ``__builtins__["eval"]`` 等间接读取。"""
|
|
116
|
+
unsafe_attr_names = _UNSAFE_CALLS | {'dir'}
|
|
117
|
+
for child in nodes:
|
|
118
|
+
if isinstance(child, ast.Call) and len(child.args) >= 2:
|
|
119
|
+
is_getattr_call = (
|
|
120
|
+
(isinstance(child.func, ast.Name) and child.func.id == 'getattr')
|
|
121
|
+
or (isinstance(child.func, ast.Attribute) and child.func.attr == 'getattr')
|
|
122
|
+
)
|
|
123
|
+
if is_getattr_call:
|
|
124
|
+
target_name = child.args[1]
|
|
125
|
+
if isinstance(target_name, ast.Constant) and target_name.value in unsafe_attr_names:
|
|
126
|
+
return True
|
|
127
|
+
elif (
|
|
128
|
+
isinstance(child, ast.Subscript)
|
|
129
|
+
and isinstance(child.value, ast.Name)
|
|
130
|
+
and child.value.id in {'builtins', '__builtins__'}
|
|
131
|
+
and isinstance(child.slice, ast.Constant)
|
|
132
|
+
and child.slice.value in unsafe_attr_names
|
|
133
|
+
):
|
|
134
|
+
return True
|
|
135
|
+
return False
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _scope_has_direct_unsafe_call(body):
|
|
139
|
+
"""仅检查一组语句直接所属词法作用域(含内联推导式)是否含动态命名空间访问。"""
|
|
140
|
+
runtime_nodes = list(_walk_scope_runtime_nodes(body))
|
|
141
|
+
for child in runtime_nodes:
|
|
142
|
+
if (isinstance(child, ast.Name) and isinstance(child.ctx, ast.Load)
|
|
143
|
+
and child.id in _UNSAFE_CALLS):
|
|
144
|
+
return True
|
|
145
|
+
if (isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute)
|
|
146
|
+
and child.func.attr in _UNSAFE_CALLS
|
|
147
|
+
and isinstance(child.func.value, ast.Name)
|
|
148
|
+
and child.func.value.id in {'builtins', '__builtins__'}):
|
|
149
|
+
return True
|
|
150
|
+
if _has_unsafe_dir_usage(runtime_nodes):
|
|
151
|
+
return True
|
|
152
|
+
if _has_indirect_unsafe_lookup(runtime_nodes):
|
|
153
|
+
return True
|
|
154
|
+
return False
|
|
155
|
+
|
|
156
|
+
|
|
81
157
|
def _has_unsafe_call(node):
|
|
82
158
|
"""检查当前词法作用域是否使用动态命名空间/代码执行能力。
|
|
83
159
|
|
|
@@ -86,17 +162,22 @@ def _has_unsafe_call(node):
|
|
|
86
162
|
以覆盖 ``snapshot = locals; snapshot()`` 这类间接调用。
|
|
87
163
|
"""
|
|
88
164
|
if hasattr(node, 'body') and isinstance(node.body, list):
|
|
89
|
-
|
|
165
|
+
if _scope_has_direct_unsafe_call(node.body):
|
|
166
|
+
return True
|
|
90
167
|
else:
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
168
|
+
walked = list(ast.walk(node))
|
|
169
|
+
for child in walked:
|
|
170
|
+
if (isinstance(child, ast.Name) and isinstance(child.ctx, ast.Load)
|
|
171
|
+
and child.id in _UNSAFE_CALLS):
|
|
172
|
+
return True
|
|
173
|
+
if (isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute)
|
|
174
|
+
and child.func.attr in _UNSAFE_CALLS
|
|
175
|
+
and isinstance(child.func.value, ast.Name)
|
|
176
|
+
and child.func.value.id in {'builtins', '__builtins__'}):
|
|
177
|
+
return True
|
|
178
|
+
if _has_unsafe_dir_usage(walked):
|
|
95
179
|
return True
|
|
96
|
-
if (
|
|
97
|
-
and child.func.attr in _UNSAFE_CALLS
|
|
98
|
-
and isinstance(child.func.value, ast.Name)
|
|
99
|
-
and child.func.value.id in {'builtins', '__builtins__'}):
|
|
180
|
+
if _has_indirect_unsafe_lookup(walked):
|
|
100
181
|
return True
|
|
101
182
|
|
|
102
183
|
aliases = _collect_reflection_aliases(node)
|
|
@@ -169,12 +250,9 @@ def _walk_scope_runtime_nodes(body):
|
|
|
169
250
|
outer_nodes.extend(node.bases)
|
|
170
251
|
outer_nodes.extend(keyword.value for keyword in node.keywords)
|
|
171
252
|
outer_nodes.extend(getattr(node, 'type_params', ()))
|
|
172
|
-
elif isinstance(node, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)):
|
|
173
|
-
# Python 3 在 enclosing scope 中求值最外层 iterable;其余部分属于
|
|
174
|
-
# comprehension 的隐式函数作用域。
|
|
175
|
-
if node.generators:
|
|
176
|
-
outer_nodes.append(node.generators[0].iter)
|
|
177
253
|
else:
|
|
254
|
+
# Python 3.12+ (PEP 709) 将推导式内联至外层函数帧执行,推导式体内的
|
|
255
|
+
# eval/locals/vars/dir() 会直接观测外层函数局部变量,必须纳入检查。
|
|
178
256
|
outer_nodes.extend(ast.iter_child_nodes(node))
|
|
179
257
|
if outer_nodes:
|
|
180
258
|
yield from _walk_scope_runtime_nodes(outer_nodes)
|
|
@@ -311,20 +389,32 @@ def _collect_nonlocal_global_names(body):
|
|
|
311
389
|
return nonlocal_names, global_names
|
|
312
390
|
|
|
313
391
|
|
|
392
|
+
def _collect_comp_walrus_store_names(nodes):
|
|
393
|
+
"""收集当前作用域(穿透推导式,但不穿透函数/lambda/类)中 ``:=`` 绑定的目标名。"""
|
|
394
|
+
names = set()
|
|
395
|
+
for node in nodes:
|
|
396
|
+
if isinstance(node, _HARD_SCOPE_NODES):
|
|
397
|
+
continue
|
|
398
|
+
if isinstance(node, ast.NamedExpr) and isinstance(node.target, ast.Name):
|
|
399
|
+
names.add(node.target.id)
|
|
400
|
+
for child in ast.iter_child_nodes(node):
|
|
401
|
+
names.update(_collect_comp_walrus_store_names([child]))
|
|
402
|
+
return names
|
|
403
|
+
|
|
404
|
+
|
|
314
405
|
def _collect_direct_bound_names(body):
|
|
315
|
-
"""
|
|
406
|
+
"""收集当前作用域直接绑定的名称,不穿透嵌套硬作用域(含推导式内 := 绑定)。"""
|
|
316
407
|
bound = _collect_names(body, (ast.Store, ast.Del))
|
|
408
|
+
bound.update(_collect_comp_walrus_store_names(body))
|
|
317
409
|
bound.update(_collect_string_bound_names(body))
|
|
318
410
|
return bound
|
|
319
411
|
|
|
320
412
|
|
|
321
|
-
def
|
|
322
|
-
"""
|
|
413
|
+
def _collect_non_renamable_string_binders(body):
|
|
414
|
+
"""收集不可仅通过 Name/ExceptHandler 同步改名的字符串字段 binder。"""
|
|
323
415
|
bound = set()
|
|
324
416
|
for child in _walk_no_nested_scope(body):
|
|
325
|
-
if isinstance(child, ast.
|
|
326
|
-
bound.add(child.name)
|
|
327
|
-
elif isinstance(child, (ast.Import, ast.ImportFrom)):
|
|
417
|
+
if isinstance(child, (ast.Import, ast.ImportFrom)):
|
|
328
418
|
for alias in child.names:
|
|
329
419
|
if alias.name != '*':
|
|
330
420
|
bound.add(alias.asname or alias.name.split('.', 1)[0])
|
|
@@ -337,6 +427,15 @@ def _collect_string_bound_names(body):
|
|
|
337
427
|
return bound
|
|
338
428
|
|
|
339
429
|
|
|
430
|
+
def _collect_string_bound_names(body):
|
|
431
|
+
"""收集 AST 以字符串字段保存、无法通过 Name(Store) 发现的 binder。"""
|
|
432
|
+
bound = _collect_non_renamable_string_binders(body)
|
|
433
|
+
for child in _walk_no_nested_scope(body):
|
|
434
|
+
if isinstance(child, ast.ExceptHandler) and child.name:
|
|
435
|
+
bound.add(child.name)
|
|
436
|
+
return bound
|
|
437
|
+
|
|
438
|
+
|
|
340
439
|
def _collect_identifier_names(node):
|
|
341
440
|
"""收集整棵子树中所有可能参与 lexical name resolution 的名称。
|
|
342
441
|
|
|
@@ -379,9 +478,36 @@ def _fresh_name(base, forbidden):
|
|
|
379
478
|
return candidate
|
|
380
479
|
|
|
381
480
|
|
|
481
|
+
def _collect_scope_load_names(nodes, shadowed=frozenset()):
|
|
482
|
+
"""收集当前词法作用域(安全穿透推导式并扣除其迭代变量遮蔽)中的 Load 名称。"""
|
|
483
|
+
loads = set()
|
|
484
|
+
for node in nodes:
|
|
485
|
+
if isinstance(node, _HARD_SCOPE_NODES):
|
|
486
|
+
continue
|
|
487
|
+
if isinstance(node, _COMP_SCOPE_NODES):
|
|
488
|
+
if node.generators:
|
|
489
|
+
loads.update(_collect_scope_load_names([node.generators[0].iter], shadowed))
|
|
490
|
+
inner_shadowed = shadowed | _collect_comp_target_names(node)
|
|
491
|
+
if isinstance(node, ast.DictComp):
|
|
492
|
+
loads.update(_collect_scope_load_names([node.key, node.value], inner_shadowed))
|
|
493
|
+
else:
|
|
494
|
+
loads.update(_collect_scope_load_names([node.elt], inner_shadowed))
|
|
495
|
+
for idx, gen in enumerate(node.generators):
|
|
496
|
+
loads.update(_collect_scope_load_names([gen.target], inner_shadowed))
|
|
497
|
+
if idx > 0:
|
|
498
|
+
loads.update(_collect_scope_load_names([gen.iter], inner_shadowed))
|
|
499
|
+
loads.update(_collect_scope_load_names(gen.ifs, inner_shadowed))
|
|
500
|
+
continue
|
|
501
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and node.id not in shadowed:
|
|
502
|
+
loads.add(node.id)
|
|
503
|
+
for child in ast.iter_child_nodes(node):
|
|
504
|
+
loads.update(_collect_scope_load_names([child], shadowed))
|
|
505
|
+
return loads
|
|
506
|
+
|
|
507
|
+
|
|
382
508
|
def _collect_load_names_no_nested(nodes):
|
|
383
|
-
"""收集 Load
|
|
384
|
-
return
|
|
509
|
+
"""收集 Load 名称,不穿透嵌套硬作用域,但正确穿透推导式。"""
|
|
510
|
+
return _collect_scope_load_names(nodes)
|
|
385
511
|
|
|
386
512
|
|
|
387
513
|
def _collect_nested_scope_nodes(body):
|
|
@@ -507,6 +633,8 @@ def _apply_rename_in_function_scope(nodes, active_map):
|
|
|
507
633
|
_apply_rename_in_function_scope([gen.iter], inner_map)
|
|
508
634
|
_apply_rename_in_function_scope(gen.ifs, inner_map)
|
|
509
635
|
continue
|
|
636
|
+
if isinstance(node, ast.ExceptHandler) and node.name in active_map:
|
|
637
|
+
node.name = active_map[node.name]
|
|
510
638
|
if isinstance(node, ast.Name) and node.id in active_map:
|
|
511
639
|
node.id = active_map[node.id]
|
|
512
640
|
for child in ast.iter_child_nodes(node):
|
|
@@ -520,43 +648,151 @@ def _hash_name(name, salt):
|
|
|
520
648
|
|
|
521
649
|
|
|
522
650
|
class _LocalVarRenamer(ast.NodeTransformer):
|
|
523
|
-
"""
|
|
651
|
+
"""函数与推导式作用域内的局部变量重命名为 hash-based 短标识符"""
|
|
652
|
+
|
|
653
|
+
def __init__(self):
|
|
654
|
+
self._unsafe_scope_stack = [False]
|
|
655
|
+
self._scope_salt_stack = ['']
|
|
656
|
+
|
|
657
|
+
def visit_Module(self, node):
|
|
658
|
+
self._unsafe_scope_stack.append(_scope_has_direct_unsafe_call(node.body))
|
|
659
|
+
self._scope_salt_stack.append('$mod')
|
|
660
|
+
try:
|
|
661
|
+
self.generic_visit(node)
|
|
662
|
+
finally:
|
|
663
|
+
self._scope_salt_stack.pop()
|
|
664
|
+
self._unsafe_scope_stack.pop()
|
|
665
|
+
return node
|
|
666
|
+
|
|
667
|
+
def visit_ClassDef(self, node):
|
|
668
|
+
for idx, dec in enumerate(node.decorator_list):
|
|
669
|
+
node.decorator_list[idx] = self.visit(dec)
|
|
670
|
+
for idx, base in enumerate(node.bases):
|
|
671
|
+
node.bases[idx] = self.visit(base)
|
|
672
|
+
for kw in node.keywords:
|
|
673
|
+
kw.value = self.visit(kw.value)
|
|
674
|
+
self._unsafe_scope_stack.append(_scope_has_direct_unsafe_call(node.body))
|
|
675
|
+
self._scope_salt_stack.append(node.name)
|
|
676
|
+
try:
|
|
677
|
+
for idx, stmt in enumerate(node.body):
|
|
678
|
+
node.body[idx] = self.visit(stmt)
|
|
679
|
+
finally:
|
|
680
|
+
self._scope_salt_stack.pop()
|
|
681
|
+
self._unsafe_scope_stack.pop()
|
|
682
|
+
return node
|
|
683
|
+
|
|
684
|
+
def visit_Lambda(self, node):
|
|
685
|
+
for idx, default in enumerate(node.args.defaults):
|
|
686
|
+
node.args.defaults[idx] = self.visit(default)
|
|
687
|
+
for idx, default in enumerate(node.args.kw_defaults):
|
|
688
|
+
if default is not None:
|
|
689
|
+
node.args.kw_defaults[idx] = self.visit(default)
|
|
690
|
+
is_unsafe = self._unsafe_scope_stack[-1] or _has_unsafe_call(node)
|
|
691
|
+
self._unsafe_scope_stack.append(is_unsafe)
|
|
692
|
+
self._scope_salt_stack.append(f'{self._scope_salt_stack[-1]}:$lambda')
|
|
693
|
+
try:
|
|
694
|
+
node.body = self.visit(node.body)
|
|
695
|
+
finally:
|
|
696
|
+
self._scope_salt_stack.pop()
|
|
697
|
+
self._unsafe_scope_stack.pop()
|
|
698
|
+
return node
|
|
699
|
+
|
|
700
|
+
def _rename_comprehension(self, node):
|
|
701
|
+
if self._unsafe_scope_stack[-1] or _has_unsafe_call(node):
|
|
702
|
+
self.generic_visit(node)
|
|
703
|
+
return node
|
|
704
|
+
|
|
705
|
+
targets = {
|
|
706
|
+
name for name in _collect_comp_target_names(node)
|
|
707
|
+
if name != '_' and not name.startswith('__')
|
|
708
|
+
}
|
|
709
|
+
if targets:
|
|
710
|
+
inner_exprs = (
|
|
711
|
+
[node.key, node.value]
|
|
712
|
+
if isinstance(node, ast.DictComp)
|
|
713
|
+
else [node.elt]
|
|
714
|
+
)
|
|
715
|
+
for idx, gen in enumerate(node.generators):
|
|
716
|
+
inner_exprs.append(gen.target)
|
|
717
|
+
if idx > 0:
|
|
718
|
+
inner_exprs.append(gen.iter)
|
|
719
|
+
inner_exprs.extend(gen.ifs)
|
|
720
|
+
|
|
721
|
+
targets -= _collect_nested_free_refs(inner_exprs, targets)
|
|
722
|
+
if targets:
|
|
723
|
+
forbidden = _collect_identifier_names(node)
|
|
724
|
+
salt = f'{self._scope_salt_stack[-1]}:$comp'
|
|
725
|
+
comp_map = {
|
|
726
|
+
name: _fresh_name(_hash_name(name, salt), forbidden)
|
|
727
|
+
for name in sorted(targets)
|
|
728
|
+
}
|
|
729
|
+
_apply_rename_in_function_scope(inner_exprs, comp_map)
|
|
730
|
+
|
|
731
|
+
self.generic_visit(node)
|
|
732
|
+
return node
|
|
733
|
+
|
|
734
|
+
visit_ListComp = _rename_comprehension
|
|
735
|
+
visit_SetComp = _rename_comprehension
|
|
736
|
+
visit_DictComp = _rename_comprehension
|
|
737
|
+
visit_GeneratorExp = _rename_comprehension
|
|
738
|
+
|
|
739
|
+
def _visit_function_children(self, node, *, is_unsafe: bool):
|
|
740
|
+
for idx, dec in enumerate(node.decorator_list):
|
|
741
|
+
node.decorator_list[idx] = self.visit(dec)
|
|
742
|
+
for idx, default in enumerate(node.args.defaults):
|
|
743
|
+
node.args.defaults[idx] = self.visit(default)
|
|
744
|
+
for idx, default in enumerate(node.args.kw_defaults):
|
|
745
|
+
if default is not None:
|
|
746
|
+
node.args.kw_defaults[idx] = self.visit(default)
|
|
747
|
+
self._unsafe_scope_stack.append(is_unsafe)
|
|
748
|
+
self._scope_salt_stack.append(getattr(node, 'name', ''))
|
|
749
|
+
try:
|
|
750
|
+
for idx, stmt in enumerate(node.body):
|
|
751
|
+
node.body[idx] = self.visit(stmt)
|
|
752
|
+
finally:
|
|
753
|
+
self._scope_salt_stack.pop()
|
|
754
|
+
self._unsafe_scope_stack.pop()
|
|
524
755
|
|
|
525
756
|
def _rename_function(self, node):
|
|
526
757
|
if _has_unsafe_call(node):
|
|
527
|
-
self.
|
|
758
|
+
self._visit_function_children(node, is_unsafe=True)
|
|
528
759
|
return node
|
|
529
760
|
|
|
530
761
|
# 收集参数名(不重命名)
|
|
531
762
|
param_names = set()
|
|
532
763
|
param_names.update(_collect_argument_names(node.args))
|
|
533
764
|
|
|
534
|
-
#
|
|
765
|
+
# 收集局部赋值目标与异常捕获变量(含推导式内 := 绑定,不穿透嵌套硬作用域)
|
|
535
766
|
local_names = set()
|
|
536
767
|
# 排除 nonlocal/global 声明的变量
|
|
537
768
|
nonlocal_names, global_names = _collect_nonlocal_global_names(node.body)
|
|
538
769
|
excluded_scope_names = nonlocal_names | global_names
|
|
770
|
+
candidate_names = set(_collect_comp_walrus_store_names(node.body))
|
|
539
771
|
for child in _walk_no_nested_scope(node.body):
|
|
540
772
|
if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store):
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
773
|
+
candidate_names.add(child.id)
|
|
774
|
+
elif isinstance(child, ast.ExceptHandler) and child.name:
|
|
775
|
+
candidate_names.add(child.name)
|
|
776
|
+
|
|
777
|
+
for name in candidate_names:
|
|
778
|
+
if (name not in param_names and name not in excluded_scope_names
|
|
779
|
+
and name != 'self' and name != 'cls'
|
|
780
|
+
and not name.startswith('__')):
|
|
781
|
+
local_names.add(name)
|
|
546
782
|
|
|
547
783
|
if not local_names:
|
|
548
|
-
self.
|
|
784
|
+
self._visit_function_children(node, is_unsafe=False)
|
|
549
785
|
return node
|
|
550
786
|
|
|
551
787
|
# 排除被嵌套函数引用的闭包变量(重命名会破坏语义)
|
|
552
788
|
closure_refs = _collect_nested_free_refs(node.body, local_names)
|
|
553
789
|
local_names -= closure_refs
|
|
554
|
-
# 同一名称可能同时由 assignment 与 import/
|
|
555
|
-
# binder 绑定;只改 Name
|
|
556
|
-
local_names -=
|
|
790
|
+
# 同一名称可能同时由 assignment 与 import/match/def 等字符串
|
|
791
|
+
# binder 绑定;只改 Name/ExceptHandler 会形成 partial rename,故保守排除。
|
|
792
|
+
local_names -= _collect_non_renamable_string_binders(node.body)
|
|
557
793
|
|
|
558
794
|
if not local_names:
|
|
559
|
-
self.
|
|
795
|
+
self._visit_function_children(node, is_unsafe=False)
|
|
560
796
|
return node
|
|
561
797
|
|
|
562
798
|
# 构建重命名映射(hash-based,用函数名做 salt 防跨函数碰撞)
|
|
@@ -572,8 +808,8 @@ class _LocalVarRenamer(ast.NodeTransformer):
|
|
|
572
808
|
# 应用重命名(不穿透嵌套函数/lambda/类作用域,但精确穿透推导式并处理迭代目标遮蔽与 := 绑定)
|
|
573
809
|
_apply_rename_in_function_scope(node.body, rename_map)
|
|
574
810
|
|
|
575
|
-
#
|
|
576
|
-
self.
|
|
811
|
+
# 递归处理嵌套函数/类/推导式(它们有自己的作用域)
|
|
812
|
+
self._visit_function_children(node, is_unsafe=False)
|
|
577
813
|
return node
|
|
578
814
|
|
|
579
815
|
def visit_FunctionDef(self, node):
|
|
@@ -668,28 +904,76 @@ class _ConstantFoldingObfuscator(ast.NodeTransformer):
|
|
|
668
904
|
right=ast.Constant(value=n - a),
|
|
669
905
|
)
|
|
670
906
|
|
|
671
|
-
def
|
|
672
|
-
|
|
673
|
-
|
|
907
|
+
def _build_masked_expr(self, n):
|
|
908
|
+
idx = self._rng.randint(0, 1)
|
|
909
|
+
mask = self._rng.randint(16384, 32767)
|
|
910
|
+
decoy = self._rng.randint(16384, 32767)
|
|
911
|
+
masked = n ^ mask
|
|
912
|
+
elts = (
|
|
913
|
+
[ast.Constant(value=masked), ast.Constant(value=decoy)]
|
|
914
|
+
if idx == 0
|
|
915
|
+
else [ast.Constant(value=decoy), ast.Constant(value=masked)]
|
|
916
|
+
)
|
|
917
|
+
# 使用零引号、零反斜杠、零内置名的容器 .__len__() 选择下标:
|
|
918
|
+
# 既兼容 Python 3.9-3.11 的 f-string 表达式限制,又阻止 Cython/GCC 编译期折叠。
|
|
919
|
+
if idx == 0:
|
|
920
|
+
index_containers = (
|
|
921
|
+
lambda: ast.Tuple(elts=[], ctx=ast.Load()),
|
|
922
|
+
lambda: ast.List(elts=[], ctx=ast.Load()),
|
|
923
|
+
lambda: ast.Dict(keys=[], values=[]),
|
|
924
|
+
)
|
|
925
|
+
else:
|
|
926
|
+
index_containers = (
|
|
927
|
+
lambda: ast.Tuple(elts=[ast.Tuple(elts=[], ctx=ast.Load())], ctx=ast.Load()),
|
|
928
|
+
lambda: ast.List(elts=[ast.Tuple(elts=[], ctx=ast.Load())], ctx=ast.Load()),
|
|
929
|
+
lambda: ast.Dict(keys=[ast.Constant(value=0)], values=[ast.Constant(value=0)]),
|
|
930
|
+
)
|
|
931
|
+
index_container = self._rng.choice(index_containers)()
|
|
932
|
+
index_expr = ast.Call(
|
|
933
|
+
func=ast.Attribute(value=index_container, attr='__len__', ctx=ast.Load()),
|
|
934
|
+
args=[],
|
|
935
|
+
keywords=[],
|
|
936
|
+
)
|
|
674
937
|
return ast.BinOp(
|
|
675
|
-
left=
|
|
676
|
-
|
|
677
|
-
|
|
938
|
+
left=ast.Subscript(
|
|
939
|
+
value=ast.Tuple(elts=elts, ctx=ast.Load()),
|
|
940
|
+
slice=index_expr,
|
|
941
|
+
ctx=ast.Load(),
|
|
942
|
+
),
|
|
943
|
+
op=ast.BitXor(),
|
|
944
|
+
right=self._decompose_1layer(mask),
|
|
678
945
|
)
|
|
679
946
|
|
|
947
|
+
def _decompose_2layer(self, n):
|
|
948
|
+
target_str = str(n)
|
|
949
|
+
expr = None
|
|
950
|
+
for _ in range(32):
|
|
951
|
+
expr = self._build_masked_expr(n)
|
|
952
|
+
if target_str not in ast.unparse(expr):
|
|
953
|
+
return expr
|
|
954
|
+
return expr
|
|
955
|
+
|
|
680
956
|
|
|
681
957
|
class _ControlFlowFlattener(ast.NodeTransformer):
|
|
682
958
|
"""将函数体转换为 while True + 状态机调度"""
|
|
683
959
|
|
|
684
|
-
def __init__(self, rng=None):
|
|
960
|
+
def __init__(self, rng=None, *, randomize_var=False):
|
|
685
961
|
self._rng = rng or random
|
|
962
|
+
self._randomize_var = randomize_var
|
|
686
963
|
|
|
687
964
|
def visit_FunctionDef(self, node):
|
|
688
965
|
self.generic_visit(node) # 先递归处理嵌套
|
|
689
966
|
if self._should_skip(node):
|
|
690
967
|
return node
|
|
691
968
|
forbidden = _collect_identifier_names(node)
|
|
692
|
-
|
|
969
|
+
if self._randomize_var:
|
|
970
|
+
state_base = _hash_name(
|
|
971
|
+
f'state:{getattr(node, "name", "")}',
|
|
972
|
+
str(self._rng.randrange(1 << 30)),
|
|
973
|
+
)
|
|
974
|
+
else:
|
|
975
|
+
state_base = '_s'
|
|
976
|
+
state_var = _fresh_name(state_base, forbidden)
|
|
693
977
|
node.body = self._flatten_body(node.body, state_var=state_var)
|
|
694
978
|
return node
|
|
695
979
|
|
|
@@ -779,47 +1063,108 @@ class _ControlFlowFlattener(ast.NodeTransformer):
|
|
|
779
1063
|
|
|
780
1064
|
|
|
781
1065
|
class _OpaquePredicateInserter(ast.NodeTransformer):
|
|
782
|
-
"""
|
|
1066
|
+
"""在函数体中插入抗编译期静态消除的永真/永假虚假分支(零内置名依赖)。"""
|
|
1067
|
+
|
|
1068
|
+
_TERMINAL_STMTS = (ast.Return, ast.Raise, ast.Break, ast.Continue)
|
|
783
1069
|
|
|
784
1070
|
_PREDICATES_TRUE = [
|
|
785
|
-
#
|
|
1071
|
+
# ().__sizeof__() >= 0
|
|
1072
|
+
lambda: ast.Compare(
|
|
1073
|
+
left=ast.Call(
|
|
1074
|
+
func=ast.Attribute(
|
|
1075
|
+
value=ast.Tuple(elts=[], ctx=ast.Load()),
|
|
1076
|
+
attr='__sizeof__',
|
|
1077
|
+
ctx=ast.Load(),
|
|
1078
|
+
),
|
|
1079
|
+
args=[],
|
|
1080
|
+
keywords=[],
|
|
1081
|
+
),
|
|
1082
|
+
ops=[ast.GtE()],
|
|
1083
|
+
comparators=[ast.Constant(value=0)],
|
|
1084
|
+
),
|
|
1085
|
+
# "".__sizeof__() >= 0
|
|
786
1086
|
lambda: ast.Compare(
|
|
787
|
-
left=ast.
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
1087
|
+
left=ast.Call(
|
|
1088
|
+
func=ast.Attribute(
|
|
1089
|
+
value=ast.Constant(value=''),
|
|
1090
|
+
attr='__sizeof__',
|
|
1091
|
+
ctx=ast.Load(),
|
|
1092
|
+
),
|
|
1093
|
+
args=[],
|
|
1094
|
+
keywords=[],
|
|
791
1095
|
),
|
|
792
1096
|
ops=[ast.GtE()],
|
|
793
1097
|
comparators=[ast.Constant(value=0)],
|
|
794
1098
|
),
|
|
795
|
-
# (
|
|
1099
|
+
# b"".__sizeof__() >= 0
|
|
796
1100
|
lambda: ast.Compare(
|
|
797
|
-
left=ast.
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
1101
|
+
left=ast.Call(
|
|
1102
|
+
func=ast.Attribute(
|
|
1103
|
+
value=ast.Constant(value=b''),
|
|
1104
|
+
attr='__sizeof__',
|
|
1105
|
+
ctx=ast.Load(),
|
|
1106
|
+
),
|
|
1107
|
+
args=[],
|
|
1108
|
+
keywords=[],
|
|
801
1109
|
),
|
|
802
|
-
ops=[ast.
|
|
803
|
-
comparators=[ast.Constant(value=
|
|
1110
|
+
ops=[ast.GtE()],
|
|
1111
|
+
comparators=[ast.Constant(value=0)],
|
|
804
1112
|
),
|
|
805
|
-
#
|
|
1113
|
+
# [].__sizeof__() >= 0
|
|
806
1114
|
lambda: ast.Compare(
|
|
807
|
-
left=ast.
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
1115
|
+
left=ast.Call(
|
|
1116
|
+
func=ast.Attribute(
|
|
1117
|
+
value=ast.List(elts=[], ctx=ast.Load()),
|
|
1118
|
+
attr='__sizeof__',
|
|
1119
|
+
ctx=ast.Load(),
|
|
1120
|
+
),
|
|
1121
|
+
args=[],
|
|
1122
|
+
keywords=[],
|
|
811
1123
|
),
|
|
812
|
-
ops=[ast.
|
|
813
|
-
comparators=[ast.Constant(value=
|
|
1124
|
+
ops=[ast.GtE()],
|
|
1125
|
+
comparators=[ast.Constant(value=0)],
|
|
1126
|
+
),
|
|
1127
|
+
# {}.__sizeof__() >= 0
|
|
1128
|
+
lambda: ast.Compare(
|
|
1129
|
+
left=ast.Call(
|
|
1130
|
+
func=ast.Attribute(
|
|
1131
|
+
value=ast.Dict(keys=[], values=[]),
|
|
1132
|
+
attr='__sizeof__',
|
|
1133
|
+
ctx=ast.Load(),
|
|
1134
|
+
),
|
|
1135
|
+
args=[],
|
|
1136
|
+
keywords=[],
|
|
1137
|
+
),
|
|
1138
|
+
ops=[ast.GtE()],
|
|
1139
|
+
comparators=[ast.Constant(value=0)],
|
|
814
1140
|
),
|
|
815
1141
|
]
|
|
816
1142
|
|
|
817
1143
|
_DEAD_CODE = [
|
|
818
1144
|
lambda name: ast.Assign(
|
|
819
1145
|
targets=[ast.Name(id=name, ctx=ast.Store())],
|
|
820
|
-
value=ast.
|
|
1146
|
+
value=ast.Call(
|
|
1147
|
+
func=ast.Attribute(
|
|
1148
|
+
value=ast.Tuple(elts=[], ctx=ast.Load()),
|
|
1149
|
+
attr='__sizeof__',
|
|
1150
|
+
ctx=ast.Load(),
|
|
1151
|
+
),
|
|
1152
|
+
args=[],
|
|
1153
|
+
keywords=[],
|
|
1154
|
+
),
|
|
1155
|
+
),
|
|
1156
|
+
lambda name: ast.Assign(
|
|
1157
|
+
targets=[ast.Name(id=name, ctx=ast.Store())],
|
|
1158
|
+
value=ast.Call(
|
|
1159
|
+
func=ast.Attribute(
|
|
1160
|
+
value=ast.Constant(value=''),
|
|
1161
|
+
attr='__sizeof__',
|
|
1162
|
+
ctx=ast.Load(),
|
|
1163
|
+
),
|
|
1164
|
+
args=[],
|
|
1165
|
+
keywords=[],
|
|
1166
|
+
),
|
|
821
1167
|
),
|
|
822
|
-
lambda name: ast.Pass(),
|
|
823
1168
|
]
|
|
824
1169
|
|
|
825
1170
|
def __init__(self, rng=None):
|
|
@@ -830,7 +1175,11 @@ class _OpaquePredicateInserter(ast.NodeTransformer):
|
|
|
830
1175
|
if _has_unsafe_call(node):
|
|
831
1176
|
return node
|
|
832
1177
|
forbidden = _collect_identifier_names(node)
|
|
833
|
-
|
|
1178
|
+
dead_base = _hash_name(
|
|
1179
|
+
f'dead:{getattr(node, "name", "")}',
|
|
1180
|
+
str(self._rng.randrange(1 << 30)),
|
|
1181
|
+
)
|
|
1182
|
+
dead_var = _fresh_name(dead_base, forbidden)
|
|
834
1183
|
node.body = self._insert_predicates(node.body, dead_var=dead_var)
|
|
835
1184
|
return node
|
|
836
1185
|
|
|
@@ -839,25 +1188,32 @@ class _OpaquePredicateInserter(ast.NodeTransformer):
|
|
|
839
1188
|
def _insert_predicates(self, stmts, dead_var='_dead'):
|
|
840
1189
|
result = []
|
|
841
1190
|
for stmt in stmts:
|
|
842
|
-
|
|
1191
|
+
fake_branch = None
|
|
843
1192
|
if self._rng.random() < 0.3:
|
|
844
1193
|
pred = self._rng.choice(self._PREDICATES_TRUE)()
|
|
845
1194
|
dead = self._rng.choice(self._DEAD_CODE)(dead_var)
|
|
846
1195
|
if self._rng.random() < 0.5:
|
|
847
|
-
|
|
848
|
-
result.append(ast.If(test=pred, body=[ast.Pass()], orelse=[dead]))
|
|
1196
|
+
fake_branch = ast.If(test=pred, body=[ast.Pass()], orelse=[dead])
|
|
849
1197
|
else:
|
|
850
|
-
|
|
851
|
-
result.append(ast.If(
|
|
1198
|
+
fake_branch = ast.If(
|
|
852
1199
|
test=ast.UnaryOp(op=ast.Not(), operand=pred),
|
|
853
1200
|
body=[dead],
|
|
854
1201
|
orelse=[],
|
|
855
|
-
)
|
|
1202
|
+
)
|
|
1203
|
+
if fake_branch is not None and isinstance(stmt, self._TERMINAL_STMTS):
|
|
1204
|
+
result.append(fake_branch)
|
|
1205
|
+
result.append(stmt)
|
|
1206
|
+
else:
|
|
1207
|
+
result.append(stmt)
|
|
1208
|
+
if fake_branch is not None:
|
|
1209
|
+
result.append(fake_branch)
|
|
856
1210
|
return result
|
|
857
1211
|
|
|
858
1212
|
|
|
859
1213
|
def _extract_header_directives(source_code: str):
|
|
860
1214
|
"""仅从文件首部实质代码前的真实注释 token 中提取解释器/Cython/distutils 指令。"""
|
|
1215
|
+
if source_code.startswith('\ufeff'):
|
|
1216
|
+
source_code = source_code[1:]
|
|
861
1217
|
directives = []
|
|
862
1218
|
source_lines = source_code.splitlines()
|
|
863
1219
|
seen_lines = set()
|
|
@@ -895,6 +1251,8 @@ def obfuscate_source(source_code: str, seed=None) -> str:
|
|
|
895
1251
|
|
|
896
1252
|
:param seed: 随机种子;传入后可复现混淆结果
|
|
897
1253
|
"""
|
|
1254
|
+
if source_code.startswith('\ufeff'):
|
|
1255
|
+
source_code = source_code[1:]
|
|
898
1256
|
if not source_code.strip():
|
|
899
1257
|
return source_code
|
|
900
1258
|
rng = random.Random(seed) if seed is not None else random
|
|
@@ -907,7 +1265,7 @@ def obfuscate_source(source_code: str, seed=None) -> str:
|
|
|
907
1265
|
tree = ast.parse(source_code)
|
|
908
1266
|
tree = _DocstringRemover().visit(tree)
|
|
909
1267
|
tree = _LocalVarRenamer().visit(tree)
|
|
910
|
-
tree = _ControlFlowFlattener(rng=rng).visit(tree)
|
|
1268
|
+
tree = _ControlFlowFlattener(rng=rng, randomize_var=True).visit(tree)
|
|
911
1269
|
tree = _OpaquePredicateInserter(rng=rng).visit(tree)
|
|
912
1270
|
tree = _mark_annotation_constants(tree)
|
|
913
1271
|
tree = _StringEncryptor(rng=rng).visit(tree)
|
|
@@ -917,7 +1275,11 @@ def obfuscate_source(source_code: str, seed=None) -> str:
|
|
|
917
1275
|
isinstance(op, (ast.Is, ast.IsNot)) for op in compare.ops
|
|
918
1276
|
):
|
|
919
1277
|
for child in ast.walk(compare):
|
|
920
|
-
if
|
|
1278
|
+
if (
|
|
1279
|
+
isinstance(child, ast.Constant)
|
|
1280
|
+
and isinstance(child.value, int)
|
|
1281
|
+
and not isinstance(child.value, bool)
|
|
1282
|
+
):
|
|
921
1283
|
identity_values.add(child.value)
|
|
922
1284
|
tree = _ConstantFoldingObfuscator(rng=rng, skip_values=identity_values).visit(tree)
|
|
923
1285
|
ast.fix_missing_locations(tree)
|
|
@@ -156,16 +156,22 @@ def run_tasks(task_list, max_workers=2, language=None, raise_on_failure=False):
|
|
|
156
156
|
with task["lock"]:
|
|
157
157
|
task["status"] = "failed"
|
|
158
158
|
task["error"] = str(e)
|
|
159
|
+
except BaseException as e:
|
|
160
|
+
with task["lock"]:
|
|
161
|
+
task["status"] = "failed"
|
|
162
|
+
task["error"] = f"{type(e).__name__}: {e}" if str(e) else type(e).__name__
|
|
163
|
+
raise
|
|
159
164
|
finally:
|
|
160
165
|
with task["lock"]:
|
|
166
|
+
if task["status"] == "running":
|
|
167
|
+
task["status"] = "failed"
|
|
168
|
+
task["error"] = task["error"] or "Task terminated unexpectedly"
|
|
161
169
|
task["end"] = time.time()
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
progress.update(overall_task, advance=1)
|
|
168
|
-
refresh_event.set() # 触发刷新
|
|
170
|
+
nonlocal completed
|
|
171
|
+
with completed_lock:
|
|
172
|
+
completed += 1
|
|
173
|
+
progress.update(overall_task, advance=1)
|
|
174
|
+
refresh_event.set() # 触发刷新
|
|
169
175
|
return task
|
|
170
176
|
|
|
171
177
|
def generate_display():
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: AutoCython-zhang
|
|
3
|
-
Version: 2.3.
|
|
3
|
+
Version: 2.3.11
|
|
4
4
|
Summary: 自动Cython,使用Cython批量编译.py文件为.pyd文件!
|
|
5
5
|
Author-email: zhang_gavin <qq814608@163.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -64,7 +64,7 @@ pip install AutoCython-zhang
|
|
|
64
64
|
|
|
65
65
|
兼容性补充:Pydantic 兼容 shim 只对词法作用域内可识别的 `pydantic.BaseModel` 子类生效,且仅补充 Cython 所需的 `ignored_types`;Pydantic v2 的 `model_config`(包括条件、`try`、带注解和继承场景)及 legacy `class Config` 均保留,`pydantic.v1` 不会被误判。字符串混淆采用编译期 ASCII escaped literal,不生成 runtime decoder、缓存或 `sys.intern` 副作用;运行时得到的仍是普通 Python `str`。编译产物先写入目标目录的 staging 文件,校验成功后才原子替换旧产物,截断或失败的中间文件不会覆盖已有结果。
|
|
66
66
|
|
|
67
|
-
> v2.3.
|
|
67
|
+
> v2.3.11 加固了反逆向全链路与实战兼容性:POSIX 默认启用 `-g0 -fvisibility=hidden` 并修正 `strip` 完好性阈值彻底清理 DWARF/.symtab 符号;常量掩码拆分与 `__sizeof__()` 不透明谓词抗编译期静态折叠且兼容 Python 3.9–3.11 f-string;同步混淆推导式迭代变量、`except as` 变量与随机化状态机/死变量指纹;完善嵌套推导式闭包、PEP 709 动态作用域与 `dir()`/`getattr(builtins, ...)` 检测、Pydantic `@computed_field`/条件/lambda/单行模型、`error_on_uninitialized=False` 及 `run_tasks()` 防死锁。
|
|
68
68
|
|
|
69
69
|
### 依赖
|
|
70
70
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: AutoCython-zhang
|
|
3
|
-
Version: 2.3.
|
|
3
|
+
Version: 2.3.11
|
|
4
4
|
Summary: 自动Cython,使用Cython批量编译.py文件为.pyd文件!
|
|
5
5
|
Author-email: zhang_gavin <qq814608@163.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -64,7 +64,7 @@ pip install AutoCython-zhang
|
|
|
64
64
|
|
|
65
65
|
兼容性补充:Pydantic 兼容 shim 只对词法作用域内可识别的 `pydantic.BaseModel` 子类生效,且仅补充 Cython 所需的 `ignored_types`;Pydantic v2 的 `model_config`(包括条件、`try`、带注解和继承场景)及 legacy `class Config` 均保留,`pydantic.v1` 不会被误判。字符串混淆采用编译期 ASCII escaped literal,不生成 runtime decoder、缓存或 `sys.intern` 副作用;运行时得到的仍是普通 Python `str`。编译产物先写入目标目录的 staging 文件,校验成功后才原子替换旧产物,截断或失败的中间文件不会覆盖已有结果。
|
|
66
66
|
|
|
67
|
-
> v2.3.
|
|
67
|
+
> v2.3.11 加固了反逆向全链路与实战兼容性:POSIX 默认启用 `-g0 -fvisibility=hidden` 并修正 `strip` 完好性阈值彻底清理 DWARF/.symtab 符号;常量掩码拆分与 `__sizeof__()` 不透明谓词抗编译期静态折叠且兼容 Python 3.9–3.11 f-string;同步混淆推导式迭代变量、`except as` 变量与随机化状态机/死变量指纹;完善嵌套推导式闭包、PEP 709 动态作用域与 `dir()`/`getattr(builtins, ...)` 检测、Pydantic `@computed_field`/条件/lambda/单行模型、`error_on_uninitialized=False` 及 `run_tasks()` 防死锁。
|
|
68
68
|
|
|
69
69
|
### 依赖
|
|
70
70
|
|
|
@@ -44,7 +44,7 @@ pip install AutoCython-zhang
|
|
|
44
44
|
|
|
45
45
|
兼容性补充:Pydantic 兼容 shim 只对词法作用域内可识别的 `pydantic.BaseModel` 子类生效,且仅补充 Cython 所需的 `ignored_types`;Pydantic v2 的 `model_config`(包括条件、`try`、带注解和继承场景)及 legacy `class Config` 均保留,`pydantic.v1` 不会被误判。字符串混淆采用编译期 ASCII escaped literal,不生成 runtime decoder、缓存或 `sys.intern` 副作用;运行时得到的仍是普通 Python `str`。编译产物先写入目标目录的 staging 文件,校验成功后才原子替换旧产物,截断或失败的中间文件不会覆盖已有结果。
|
|
46
46
|
|
|
47
|
-
> v2.3.
|
|
47
|
+
> v2.3.11 加固了反逆向全链路与实战兼容性:POSIX 默认启用 `-g0 -fvisibility=hidden` 并修正 `strip` 完好性阈值彻底清理 DWARF/.symtab 符号;常量掩码拆分与 `__sizeof__()` 不透明谓词抗编译期静态折叠且兼容 Python 3.9–3.11 f-string;同步混淆推导式迭代变量、`except as` 变量与随机化状态机/死变量指纹;完善嵌套推导式闭包、PEP 709 动态作用域与 `dir()`/`getattr(builtins, ...)` 检测、Pydantic `@computed_field`/条件/lambda/单行模型、`error_on_uninitialized=False` 及 `run_tasks()` 防死锁。
|
|
48
48
|
|
|
49
49
|
### 依赖
|
|
50
50
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{autocython_zhang-2.3.10 → autocython_zhang-2.3.11}/AutoCython_zhang.egg-info/entry_points.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|