-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_errors.py
More file actions
330 lines (296 loc) · 11.7 KB
/
Copy pathfix_errors.py
File metadata and controls
330 lines (296 loc) · 11.7 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
#!/usr/bin/env python3
"""
Semantics-preserving compile fixer for the deobfuscated Tenacity sources.
Reads javac error output, patches the flagged source lines in place.
Fix classes handled (all preserve exact bytecode semantics):
1. "boolean cannot be converted to byte" on `byte v = <boolExpr>;`
-> byte v = (byte)((<boolExpr>) ? 1 : 0);
Multi-line RHS is gathered first (statement ends at `;` with balanced parens).
2. "byte cannot be converted to boolean" on lines containing `(boolean)X`
-> (X != 0)
3. "cannot assign a value to final variable N"
-> drop `final` from that field's declaration
Usage: python fix_errors.py <javac-output.txt>
"""
import re
import sys
import collections
from pathlib import Path
ERR_PAT = re.compile(r'^(.*?\.java):(\d+): error: (.*)$')
def parse_errors(path):
errs = collections.defaultdict(list)
lines = Path(path).read_text(encoding='utf-8', errors='replace').splitlines()
i = 0
while i < len(lines):
m = ERR_PAT.match(lines[i])
if m:
src = lines[i + 1] if i + 1 < len(lines) else ''
errs[m.group(1)].append((int(m.group(2)), m.group(3), src))
i += 1
return errs
def statement_end(lines, start_idx):
"""Return (end_idx, end_col) of the `;` closing the statement beginning at
lines[start_idx], tracking paren depth and skipping string/char literals."""
depth = 0
in_str = in_chr = in_line_comment = in_block_comment = False
for i in range(start_idx, min(start_idx + 200, len(lines))):
line = lines[i]
j = 0
while j < len(line):
c = line[j]
nxt = line[j + 1] if j + 1 < len(line) else ''
if in_line_comment:
break
if in_block_comment:
if c == '*' and nxt == '/':
in_block_comment = False
j += 2
continue
j += 1
continue
if in_str:
if c == '\\':
j += 2
continue
if c == '"':
in_str = False
j += 1
continue
if in_chr:
if c == '\\':
j += 2
continue
if c == "'":
in_chr = False
j += 1
continue
if c == '/' and nxt == '/':
in_line_comment = True
break
if c == '/' and nxt == '*':
in_block_comment = True
j += 2
continue
if c == '"':
in_str = True
elif c == "'":
in_chr = True
elif c == '(' or c == '[':
depth += 1
elif c == ')' or c == ']':
depth -= 1
elif c == ';' and depth <= 0:
return i, j
j += 1
in_line_comment = False
return start_idx, -1
DECL_PAT = re.compile(r'^(\s*)byte\s+(\w+)\s*=\s*(.*)$')
def replace_boolean_casts(text):
"""Replace every `(boolean)<operand>` with `(<operand> != 0)` in text."""
out = []
i = 0
n = len(text)
while True:
j = text.find('(boolean)', i)
if j < 0:
out.append(text[i:])
break
out.append(text[i:j])
k = j + len('(boolean)')
while k < n and text[k] == ' ':
k += 1
if k < n and text[k] == '(':
depth = 0
e = k
while e < n:
if text[e] == '(':
depth += 1
elif text[e] == ')':
depth -= 1
if depth == 0:
break
e += 1
if depth != 0:
out.append(text[j:])
break
operand = text[k:e + 1]
i = e + 1
else:
m2 = re.match(r'[\w.$\[\]]+', text[k:])
if not m2:
out.append(text[j:])
break
operand = m2.group(0)
i = k + len(operand)
out.append(f'({operand} != 0)')
return ''.join(out)
ASSIGN_PAT = re.compile(r'^(\s*)(.*?)\s*=\s*([^;]+);(\s*(//.*)?)$')
RETURN_PAT = re.compile(r'^(\s*)return\s+([^;]+);(\s*(//.*)?)$')
def fix_byte_to_bool_line(line):
m = RETURN_PAT.match(line)
if m:
indent, expr, tail = m.group(1), m.group(2), m.group(3)
return f'{indent}return ({expr}) != 0;{tail}'
m = ASSIGN_PAT.match(line)
if m:
indent, lhs, rhs, tail = m.group(1), m.group(2), m.group(3), m.group(4)
return f'{indent}{lhs} = ({rhs}) != 0;{tail}'
return None
FINAL_ERR_PAT = re.compile(r'cannot assign a value to final variable (\S+)')
FIELD_PAT = re.compile(
r'^\s*(?:private|public|protected)?\s*(?:static\s+)?final\s+'
r'[\w.$<>\[\], ?]+\s+(\w+)\s*(?:=[^;]*)?;')
def collect_final_fields(roots):
decls = collections.defaultdict(list)
for root in roots:
rootp = Path(root)
if not rootp.exists():
continue
for p in rootp.rglob('*.java'):
try:
text_lines = p.read_text(encoding='utf-8', errors='replace').splitlines()
except OSError:
continue
for idx, ln in enumerate(text_lines):
fm = FIELD_PAT.match(ln)
if fm:
decls[fm.group(1)].append((p, idx, ln))
return decls
def main():
if len(sys.argv) != 2:
print(__doc__)
sys.exit(1)
errs = parse_errors(sys.argv[1])
stats = collections.Counter()
unhandled = []
for f, recs in errs.items():
p = Path(f)
if not p.exists():
continue
by_line = collections.defaultdict(list)
for ln, msg, src in recs:
by_line[ln].append(msg)
text_lines = p.read_text(encoding='utf-8', errors='replace').splitlines()
changed = False
consumed = set()
# Process descending; blank out consumed continuation lines (no deletion)
# so line numbers of other pending errors stay valid.
for ln in sorted(by_line, reverse=True):
if ln in consumed:
continue
msgs = by_line[ln]
if ln < 1 or ln > len(text_lines):
continue
line = text_lines[ln - 1]
if any('boolean cannot be converted to byte' in m for m in msgs):
m = DECL_PAT.match(line)
if not m:
unhandled.append((f, ln, 'bool->byte', line.strip()[:100]))
continue
indent, name = m.group(1), m.group(2)
ei, ec = statement_end(text_lines, ln - 1)
if ec < 0:
unhandled.append((f, ln, 'bool->byte no-semi', line.strip()[:100]))
continue
# Full statement text (single or multi line), up to but not
# including the closing `;`.
if ei == ln - 1:
stmt = line[:ec]
else:
middle = '\n'.join(text_lines[k] for k in range(ln, ei))
stmt = line + ('\n' + middle if middle else '') + '\n' + text_lines[ei][:ec]
# RHS = statement text after the `byte name = ` prefix
prefix = f'{indent}byte {name} = '
rhs = stmt[len(prefix):].strip()
rhs = replace_boolean_casts(rhs)
new_stmt = f'{indent}byte {name} = (byte)(({rhs}) ? 1 : 0);'
if ei == ln - 1:
text_lines[ln - 1] = new_stmt + line[ec + 1:]
else:
text_lines[ln - 1] = new_stmt + text_lines[ei][ec + 1:]
for k in range(ln, ei + 1):
text_lines[k] = ''
consumed.add(k + 1) # 1-based pending-error line numbers
changed = True
stats['bool->byte decl'] += 1
continue
if any('does not override or implement a method from a supertype' in m for m in msgs):
# Event dispatch in this codebase is reflective (EventManager),
# so @Override on handlers is decorative; drop it.
if line.strip() == '@Override':
text_lines[ln - 1] = ''
changed = True
stats['@Override removed'] += 1
else:
unhandled.append((f, ln, 'override', line.strip()[:100]))
continue
if any('byte cannot be converted to boolean' in m for m in msgs):
if '(boolean)' in line:
# gather multi-line span until parens balance, then replace
span = [line]
si = ln - 1
depth = 0
for probe in range(si, min(si + 40, len(text_lines))):
depth += text_lines[probe].count('(') - text_lines[probe].count(')')
if probe > si and depth <= 0:
break
if probe == si and depth <= 0:
break
if probe == si and depth > 0:
continue
# find actual end: first line >= si where running depth <= 0
depth = 0
end_i = si
for probe in range(si, min(si + 40, len(text_lines))):
depth += text_lines[probe].count('(') - text_lines[probe].count(')')
end_i = probe
if depth <= 0:
break
span_text = '\n'.join(text_lines[si:end_i + 1])
replaced = replace_boolean_casts(span_text)
if '(boolean)' not in replaced:
text_lines[si] = replaced
for k in range(si + 1, end_i + 1):
text_lines[k] = ''
changed = True
stats['(boolean) cast -> != 0'] += 1
else:
unhandled.append((f, ln, 'multi-line (boolean)', line.strip()[:80]))
else:
r = fix_byte_to_bool_line(line)
if r is None:
unhandled.append((f, ln, 'byte->bool', line.strip()[:100]))
else:
text_lines[ln - 1] = r
changed = True
stats['byte->bool expr'] += 1
if changed:
p.write_text('\n'.join(text_lines) + ('\n' if text_lines else ''), encoding='utf-8')
# ---- final-field fixes ----
finals_needed = set()
for f, recs in errs.items():
for ln, msg, src in recs:
m = FINAL_ERR_PAT.search(msg)
if m:
finals_needed.add(m.group(1))
if finals_needed:
decls = collect_final_fields(
['dev', 'de', 'net', 'novoline', 'unobf/src/java/org', 'thpirxhcgbnlbfjy', 'viamcp', 'myau'])
for name in finals_needed:
hits = decls.get(name, [])
for p, idx, ln in hits:
new = ln.replace(' final ', ' ', 1)
if new != ln:
tl = p.read_text(encoding='utf-8', errors='replace').splitlines()
tl[idx] = new
p.write_text('\n'.join(tl) + '\n', encoding='utf-8')
stats['final removed'] += 1
if not hits:
unhandled.append(('-', 0, f'final variable {name}', 'no decl found'))
print('stats:', dict(stats))
if unhandled:
print(f'unhandled: {len(unhandled)}')
for u in unhandled[:25]:
print(' ', u)
if __name__ == '__main__':
main()