auto-scrambling-python-opcodes 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: auto-scrambling-python-opcodes
3
+ Version: 0.1.0
4
+ Summary: 一个适用于Python 3.13的自动混淆opcode脚本
5
+ Author-email: ExMC-Github <2545869165@qq.com>
6
+ License: Apache-2.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.13
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Requires-Python: >=3.13
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Dynamic: license-file
14
+
15
+ ### Auto-Scrambling-Python-Opcodes
16
+ ###### Made By ExRFy
17
+ ------
18
+
19
+ <img src="https://img.shields.io/badge/Python-3.13.8-blue">
20
+
21
+ <img src="https://img.shields.io/badge/使用提示-生产环境建议使用git备份-red">
22
+
23
+ ------
24
+
25
+ 目录
26
+ * [介绍](#介绍)
27
+ * [使用](#使用)
28
+
29
+ <p id="介绍"></p>
30
+
31
+ ------
32
+
33
+ # 介绍
34
+
35
+ 这是一款使用python的Python 3.13 opcodes混淆工具
36
+
37
+ 能让opcode的顺序完全重新排列,如
38
+ ```
39
+ Examples (name: old -> new):
40
+ CACHE: 0 -> 208
41
+ NOP: 30 -> 105
42
+ LOAD_CONST: 83 -> 103
43
+ POP_TOP: 32 -> 72
44
+ RESUME: 149 -> 138
45
+ INSTRUMENTED_LINE: 254 -> 27
46
+ JUMP: 256 -> 265
47
+ STORE_FAST_MAYBE_NULL: 267 -> 256
48
+ ```
49
+
50
+ 这种的
51
+
52
+ <p id="使用"></p>
53
+
54
+ ------
55
+
56
+ # 使用
57
+
58
+ 使用方法:
59
+
60
+ 1. 找一个3.13的cpython仓库,download下来
61
+
62
+ 2. 运行脚本,第一个参数填仓库目录
63
+
64
+ 可选择项:
65
+
66
+ --seed 该参数能指定随机数种子,若无该参数则反转opcode
@@ -0,0 +1,8 @@
1
+ auto_scrambling_python_opcodes-0.1.0.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
2
+ scramble_313_opcodes/__init__.py,sha256=q21gi3THKM24Atvi-moP_txfLNAua1fFrOLZihKBZk4,30
3
+ scramble_313_opcodes/scramble_opcodes.py,sha256=O8D2yLoK74lcjMXl0VMFAXIKEn2Q8FEU_Gr3dSzdu48,12116
4
+ auto_scrambling_python_opcodes-0.1.0.dist-info/METADATA,sha256=-x5JsXp30OgmL9leBeriovSe2Zz3NSW4UEsg6gU05vc,1460
5
+ auto_scrambling_python_opcodes-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
+ auto_scrambling_python_opcodes-0.1.0.dist-info/entry_points.txt,sha256=DYgvVKmMxj6nRjQNSNqEzO1xA7zrVqpndLCbJB2mPQc,62
7
+ auto_scrambling_python_opcodes-0.1.0.dist-info/top_level.txt,sha256=l-VIYPJ1UT25UtsxTnmvlNz3aRq7HLzD7LXdP7Qrp5M,21
8
+ auto_scrambling_python_opcodes-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ scramble-opcodes = scramble_opcodes.py:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ scramble_313_opcodes
@@ -0,0 +1 @@
1
+ from scramble_opcodes import *
@@ -0,0 +1,323 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ CPython 3.13 Opcode Scrambling Script
4
+
5
+ Scrambles all opcode values in a CPython 3.13 source tree so that the
6
+ bytecode appears fully randomized (e.g., CACHE is no longer 0).
7
+
8
+ Two scrambling modes:
9
+ 1. Reversal (default): new_value = 254 - old_value (deterministic)
10
+ 2. Random shuffle (--seed N): uses a seeded random permutation
11
+
12
+ Usage:
13
+ python scramble_opcodes.py <cpython_source_root>
14
+ python scramble_opcodes.py <cpython_source_root> --seed 42
15
+ python scramble_opcodes.py <cpython_source_root> --seed 12345
16
+ """
17
+
18
+ import os
19
+ import re
20
+ import sys
21
+ import random
22
+
23
+
24
+ def parse_opcode_ids_h(filepath):
25
+ """Parse Include/opcode_ids.h to extract opcode name -> value mappings."""
26
+ opcodes = {}
27
+ with open(filepath, 'r', encoding='utf-8') as f:
28
+ for line in f:
29
+ m = re.match(r'#define\s+(\w+)\s+(\d+)', line.strip())
30
+ if m:
31
+ name = m.group(1)
32
+ value = int(m.group(2))
33
+ if name in ('HAVE_ARGUMENT', 'MIN_INSTRUMENTED_OPCODE', 'NB_OPARG_LAST'):
34
+ continue
35
+ if name.startswith('NB_'):
36
+ continue
37
+ opcodes[name] = value
38
+ return opcodes
39
+
40
+
41
+ def parse_opcode_metadata_py(filepath):
42
+ """Parse Lib/_opcode_metadata.py to extract opmap and specialized_opmap."""
43
+ namespace = {}
44
+ with open(filepath, 'r', encoding='utf-8') as f:
45
+ content = f.read()
46
+ exec(content, namespace)
47
+ return {
48
+ 'opmap': namespace['opmap'],
49
+ '_specialized_opmap': namespace['_specialized_opmap'],
50
+ '_specializations': namespace['_specializations'],
51
+ 'HAVE_ARGUMENT': namespace['HAVE_ARGUMENT'],
52
+ 'MIN_INSTRUMENTED_OPCODE': namespace['MIN_INSTRUMENTED_OPCODE'],
53
+ }
54
+
55
+
56
+ def compute_reversed_mapping(opcodes):
57
+ """Reversal: real opcodes 0-254 -> 254-0, pseudo 256-267 -> 267-256."""
58
+ MAX_REAL = 254
59
+ PSEUDO_BASE = 256
60
+ PSEUDO_MAX = 267
61
+ new_opcodes = {}
62
+ for name, value in opcodes.items():
63
+ if value <= MAX_REAL:
64
+ new_opcodes[name] = MAX_REAL - value
65
+ elif value >= PSEUDO_BASE:
66
+ new_opcodes[name] = (PSEUDO_BASE + PSEUDO_MAX) - value
67
+ else:
68
+ raise ValueError(f"Unexpected opcode value {value} for {name}")
69
+ return new_opcodes
70
+
71
+
72
+ def compute_random_mapping(opcodes, seed):
73
+ """Random shuffle: permute real opcodes within 0-254, pseudo within 256-267."""
74
+ MAX_REAL = 254
75
+ PSEUDO_BASE = 256
76
+ PSEUDO_MAX = 267
77
+
78
+ rng = random.Random(seed)
79
+
80
+ # Separate real and pseudo opcodes
81
+ real_names = [n for n, v in opcodes.items() if v <= MAX_REAL]
82
+ pseudo_names = [n for n, v in opcodes.items() if v >= PSEUDO_BASE]
83
+
84
+ # Shuffle target values
85
+ real_values = list(range(MAX_REAL + 1))
86
+ rng.shuffle(real_values)
87
+ pseudo_values = list(range(PSEUDO_BASE, PSEUDO_MAX + 1))
88
+ rng.shuffle(pseudo_values)
89
+
90
+ new_opcodes = {}
91
+ for name, value in opcodes.items():
92
+ if value <= MAX_REAL:
93
+ idx = [n for n, v in opcodes.items() if v <= MAX_REAL].index(name)
94
+ new_opcodes[name] = real_values[idx]
95
+ elif value >= PSEUDO_BASE:
96
+ idx = [n for n, v in opcodes.items() if v >= PSEUDO_BASE].index(name)
97
+ new_opcodes[name] = pseudo_values[idx]
98
+ else:
99
+ raise ValueError(f"Unexpected opcode value {value} for {name}")
100
+ return new_opcodes
101
+
102
+
103
+ def write_opcode_ids_h(filepath, new_opcodes):
104
+ """Write updated Include/opcode_ids.h with new opcode values."""
105
+ # Re-parse to get original values for HAVE_ARGUMENT calculation
106
+ original_opcodes = {}
107
+ with open(filepath, 'r', encoding='utf-8') as f:
108
+ for line in f:
109
+ m = re.match(r'#define\s+(\w+)\s+(\d+)', line.strip())
110
+ if m:
111
+ name = m.group(1)
112
+ value = int(m.group(2))
113
+ if name not in ('HAVE_ARGUMENT', 'MIN_INSTRUMENTED_OPCODE',
114
+ 'NB_OPARG_LAST') and not name.startswith('NB_'):
115
+ original_opcodes[name] = value
116
+
117
+ orig_have_argument = 44
118
+ min_has_arg = 255
119
+ for name, orig_val in original_opcodes.items():
120
+ if orig_val >= orig_have_argument:
121
+ new_val = new_opcodes[name]
122
+ if new_val < min_has_arg:
123
+ min_has_arg = new_val
124
+
125
+ min_instrumented = 255
126
+ for name, orig_val in original_opcodes.items():
127
+ if name.startswith('INSTRUMENTED_'):
128
+ new_val = new_opcodes[name]
129
+ if new_val < min_instrumented:
130
+ min_instrumented = new_val
131
+
132
+ new_lines = []
133
+ with open(filepath, 'r', encoding='utf-8') as f:
134
+ for line in f:
135
+ stripped = line.strip()
136
+ m = re.match(r'#define\s+(\w+)\s+(\d+)', stripped)
137
+ if m:
138
+ name = m.group(1)
139
+ if name in ('HAVE_ARGUMENT',):
140
+ new_lines.append(f'#define HAVE_ARGUMENT'
141
+ f'{"".ljust(36)}{min_has_arg}\n')
142
+ continue
143
+ elif name in ('MIN_INSTRUMENTED_OPCODE',):
144
+ new_lines.append(f'#define MIN_INSTRUMENTED_OPCODE'
145
+ f'{"".ljust(24)}{min_instrumented}\n')
146
+ continue
147
+ elif name.startswith('NB_') or name == 'NB_OPARG_LAST':
148
+ new_lines.append(line)
149
+ continue
150
+ elif name in new_opcodes:
151
+ padding = 40 - len(name) - 9
152
+ if padding < 1:
153
+ padding = 1
154
+ new_lines.append(f'#define {name}'
155
+ f'{" " * padding}{new_opcodes[name]}\n')
156
+ continue
157
+ new_lines.append(line)
158
+
159
+ with open(filepath, 'w', encoding='utf-8') as f:
160
+ f.writelines(new_lines)
161
+
162
+
163
+ def write_opcode_metadata_py(filepath, new_opcodes, metadata):
164
+ """Write updated Lib/_opcode_metadata.py with new opcode values."""
165
+ new_opmap = {}
166
+ for name, value in metadata['opmap'].items():
167
+ if name in new_opcodes:
168
+ new_opmap[name] = new_opcodes[name]
169
+ else:
170
+ new_opmap[name] = value
171
+
172
+ new_specialized_opmap = {}
173
+ for name, value in metadata['_specialized_opmap'].items():
174
+ if name in new_opcodes:
175
+ new_specialized_opmap[name] = new_opcodes[name]
176
+ else:
177
+ new_specialized_opmap[name] = value
178
+
179
+ orig_have_argument = metadata['HAVE_ARGUMENT']
180
+ min_has_arg = 255
181
+ for name, orig_val in metadata['opmap'].items():
182
+ if orig_val >= orig_have_argument:
183
+ new_val = new_opcodes.get(name, orig_val)
184
+ if new_val < min_has_arg:
185
+ min_has_arg = new_val
186
+
187
+ min_instrumented = 255
188
+ for name, orig_val in metadata['opmap'].items():
189
+ if name.startswith('INSTRUMENTED_'):
190
+ new_val = new_opcodes.get(name, orig_val)
191
+ if new_val < min_instrumented:
192
+ min_instrumented = new_val
193
+
194
+ lines = []
195
+ lines.append('# This file is generated by Tools/cases_generator/py_metadata_generator.py')
196
+ lines.append('# from:')
197
+ lines.append('# Python/bytecodes.c')
198
+ lines.append('# Do not edit!')
199
+ lines.append('')
200
+
201
+ lines.append('_specializations = {')
202
+ for parent, children in metadata['_specializations'].items():
203
+ lines.append(f' "{parent}": [')
204
+ for child in children:
205
+ lines.append(f' "{child}",')
206
+ lines.append(' ],')
207
+ lines.append('}')
208
+ lines.append('')
209
+
210
+ lines.append('_specialized_opmap = {')
211
+ for name in sorted(new_specialized_opmap.keys(), key=lambda x: new_specialized_opmap[x]):
212
+ lines.append(f" '{name}': {new_specialized_opmap[name]},")
213
+ lines.append('}')
214
+ lines.append('')
215
+
216
+ lines.append('opmap = {')
217
+ for name in sorted(new_opmap.keys(), key=lambda x: new_opmap[x]):
218
+ lines.append(f" '{name}': {new_opmap[name]},")
219
+ lines.append('}')
220
+ lines.append('')
221
+
222
+ lines.append(f'HAVE_ARGUMENT = {min_has_arg}')
223
+ lines.append(f'MIN_INSTRUMENTED_OPCODE = {min_instrumented}')
224
+ lines.append('')
225
+
226
+ with open(filepath, 'w', encoding='utf-8') as f:
227
+ f.write('\n'.join(lines))
228
+
229
+
230
+ def update_extra_cases(filepath, new_opcodes):
231
+ """Update EXTRA_CASES in pycore_opcode_metadata.h with new unused values."""
232
+ used_values = set()
233
+ for name, value in new_opcodes.items():
234
+ if value <= 254:
235
+ used_values.add(value)
236
+
237
+ gaps = []
238
+ for v in range(256):
239
+ if v not in used_values:
240
+ gaps.append(v)
241
+
242
+ with open(filepath, 'r', encoding='utf-8') as f:
243
+ content = f.read()
244
+
245
+ extra_cases_lines = []
246
+ for v in gaps:
247
+ extra_cases_lines.append(f' case {v}: \\')
248
+
249
+ extra_cases_str = '#define EXTRA_CASES \\\n' + '\n'.join(extra_cases_lines)
250
+ if extra_cases_lines:
251
+ extra_cases_str = extra_cases_str.rstrip(' \\')
252
+ extra_cases_str += '\n ;'
253
+
254
+ pattern = r'#define EXTRA_CASES\s*\\[^;]*;'
255
+ content = re.sub(pattern, extra_cases_str, content, flags=re.DOTALL)
256
+
257
+ with open(filepath, 'w', encoding='utf-8') as f:
258
+ f.write(content)
259
+
260
+
261
+ def main():
262
+ import argparse
263
+ parser = argparse.ArgumentParser(
264
+ description="Scramble CPython 3.13 opcode values")
265
+ parser.add_argument("source_root", help="CPython source root directory")
266
+ parser.add_argument("--seed", type=int, default=None,
267
+ help="Random seed for shuffle (omit for deterministic reversal)")
268
+ args = parser.parse_args()
269
+
270
+ source_root = os.path.abspath(args.source_root)
271
+
272
+ opcode_ids_h = os.path.join(source_root, 'Include', 'opcode_ids.h')
273
+ opcode_metadata_py = os.path.join(source_root, 'Lib', '_opcode_metadata.py')
274
+ opcode_metadata_h = os.path.join(source_root, 'Include', 'internal',
275
+ 'pycore_opcode_metadata.h')
276
+
277
+ for f in [opcode_ids_h, opcode_metadata_py, opcode_metadata_h]:
278
+ if not os.path.exists(f):
279
+ print(f"Error: {f} not found. Is this a CPython 3.13 source tree?")
280
+ sys.exit(1)
281
+
282
+ mode = "random shuffle" if args.seed is not None else "reversal"
283
+ print(f"=== CPython 3.13 Opcode Scrambling Script (mode: {mode}) ===\n")
284
+
285
+ print("[1/4] Parsing current opcode definitions...")
286
+ opcodes = parse_opcode_ids_h(opcode_ids_h)
287
+ print(f" Found {len(opcodes)} opcodes")
288
+
289
+ print("[2/4] Computing new opcode mapping...")
290
+ if args.seed is not None:
291
+ new_opcodes = compute_random_mapping(opcodes, args.seed)
292
+ print(f" Using random seed: {args.seed}")
293
+ else:
294
+ new_opcodes = compute_reversed_mapping(opcodes)
295
+ print(" Using reversal (default)")
296
+
297
+ examples = ['CACHE', 'NOP', 'LOAD_CONST', 'POP_TOP', 'RESUME',
298
+ 'INSTRUMENTED_LINE', 'JUMP', 'STORE_FAST_MAYBE_NULL']
299
+ print(" Examples (name: old -> new):")
300
+ for name in examples:
301
+ if name in opcodes:
302
+ print(f" {name}: {opcodes[name]} -> {new_opcodes[name]}")
303
+
304
+ print("[3/4] Updating header and metadata files...")
305
+ write_opcode_ids_h(opcode_ids_h, new_opcodes)
306
+ print(f" Updated {opcode_ids_h}")
307
+
308
+ metadata = parse_opcode_metadata_py(opcode_metadata_py)
309
+ write_opcode_metadata_py(opcode_metadata_py, new_opcodes, metadata)
310
+ print(f" Updated {opcode_metadata_py}")
311
+
312
+ update_extra_cases(opcode_metadata_h, new_opcodes)
313
+ print(f" Updated {opcode_metadata_h}")
314
+
315
+ print("\n=== Done! ===")
316
+ print("Opcode values have been scrambled. The modified Python interpreter")
317
+ print("will use completely different bytecode values, making .pyc files")
318
+ print("incompatible with standard Python 3.13.")
319
+ print("\nYou need to rebuild CPython for changes to take effect.")
320
+
321
+
322
+ if __name__ == '__main__':
323
+ main()