Repository navigation
Expand file tree
/
Copy pathview8_util.py
More file actions
265 lines (228 loc) · 8.6 KB
/
Copy pathview8_util.py
File metadata and controls
265 lines (228 loc) · 8.6 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
#!/usr/bin/env python3
import os
import re
from Parser.shared_function_info import SharedFunctionInfo, save_functions_to_file
def is_root(sfi):
if sfi is None:
return False
if sfi.declarer is None:
return True
return False
def get_start_function(functions):
if not functions:
return None
for curr_func in functions:
sfi = functions.get(curr_func)
if is_root(sfi):
return curr_func
if (sfi is None) or (sfi.declarer is None):
break
curr_func = sfi.declarer
return None
def get_declared_children(functions, curr_func):
children_list = []
for func_name, sfi in functions.items():
declarer = sfi.declarer
if declarer == curr_func:
children_list.append(func_name)
return children_list
def next_visible_line(func, indx, is_backward=False):
"""
Next non-empty, visible line
Returns Index
"""
if is_backward:
step = (-1)
else:
step = 1
indx += step
while (indx >= 0 and indx < len(func.code)):
if ((not func.code[indx].visible) or (not func.code[indx].decompiled) or (func.code[indx].decompiled.strip() == "")):
indx += step
continue
return indx
return None
###
def _rename_functions(
functions: dict[str, SharedFunctionInfo],
renamed_dict: dict[str, str],
) -> int:
renamed_count = 0
new_functions: dict[str, SharedFunctionInfo] = {}
for name, func in functions.items():
if func.declarer in renamed_dict:
func.declarer = renamed_dict[func.declarer]
if name in renamed_dict:
new_name = renamed_dict[name]
func.name = new_name
new_functions[new_name] = func
renamed_count += 1
else:
new_functions[name] = func
# mutate the original dict in place (if callers hold a reference)
functions.clear()
functions.update(new_functions)
return renamed_count
def rename_functions_in_code(
functions: dict[str, SharedFunctionInfo],
renamed_dict: dict[str, str],
verbosity: int
) -> int:
renamed = _rename_functions(functions, renamed_dict)
if verbosity:
print(f"Renamed functions: {renamed}")
func_pattern = r'\b(func_[a-zA-Z0-9_$]+_0x[0-9a-fA-F]+)\b'
regex = re.compile(func_pattern)
for func in functions.values():
for indx in range(len(func.code)):
if (not func.code[indx].visible) or (not func.code[indx].decompiled):
continue
line = func.code[indx].decompiled
# Replace only if the found name is in renamed_dict
def repl(m):
name = m.group(1)
return renamed_dict.get(name, name)
new_line = regex.sub(repl, line)
if new_line != line:
func.code[indx].decompiled = new_line
if verbosity:
print(f"REPL: {line.strip()} -> {new_line.strip()}")
return renamed
###
def print_func(func_name, func, show_hidden=False, show_line_num=True, show_const=False, show_line_meta=False):
print("###")
print(f"# {func_name}")
print(f"# Declarer: {func.declarer}")
if func.metadata:
print(f"Metadata: {func.metadata}")
if show_const:
print(f"# Const Pool")
print(func.const_pool)
print(f"# Arguments: {func.argument_count}")
print(f"# Registers: {func.register_count}")
print(f"# Code")
indx = 0
i = 0
for i in range(len(func.code)):
line_obj = func.code[i]
if not line_obj.decompiled:
continue
if not show_hidden and not line_obj.visible:
continue
indx += 1
line = line_obj.decompiled
meta = ""
if show_line_meta:
if line_obj.metadata:
meta = f" # {line_obj.metadata}"
if show_line_num:
if indx != i:
print(f"{indx}|{i}|{line}{meta}")
else:
print(f"{indx}|{line}{meta}")
else:
print(f"{line}")
#
def print_funcs(functions, show_hidden=False, show_line_num=True, show_const=False, show_line_meta=False):
for func_name, func in functions.items():
print_func(func_name, func, show_hidden, show_line_num, show_const, show_line_meta)
def find_functions_by_name(all_func, name):
funcs = dict()
if name in all_func:
funcs[name] = all_func[name]
return funcs
sub_name = "_" + name + "_"
for key in all_func:
if sub_name in key:
funcs[key] = all_func[key]
return funcs
###
def build_declaration_map(functions):
declared_by = {}
for func_name, sfi in functions.items():
declarer = sfi.declarer
if declarer:
if declarer not in declared_by:
declared_by[declarer] = []
declared_by[declarer].append(func_name)
return declared_by
def remove_exclude_functions(all_functions, exclude_list):
declaration_table = build_declaration_map(all_functions)
number_of_function = len(exclude_list)
while exclude_list:
current_function = exclude_list.pop()
all_functions.pop(current_function, None)
next_level = declaration_table.get(current_function, [])
number_of_function += len(next_level)
exclude_list += next_level
print(f"Removed {number_of_function} functions")
def get_included_functions(all_functions, include_list):
declaration_table = build_declaration_map(all_functions)
number_of_function = len(include_list)
new_all_func = {}
while include_list:
current_function = include_list.pop()
new_all_func[current_function] = all_functions[current_function]
next_level = declaration_table.get(current_function, [])
number_of_function += len(next_level)
include_list += next_level
return new_all_func
###
def _export_to_file(out_name, all_functions, format_list, included_list=None, excluded_list=None):
with open(out_name, "w", encoding="utf-8") as f:
print(f"Exporting to file {out_name}")
for function_name in list(all_functions)[::-1]:
include = True
if (excluded_list is not None and len(excluded_list)) and (function_name in excluded_list):
include = False
if (included_list is not None and len(included_list)) and (function_name not in included_list):
include = False
if not all_functions[function_name].visible:
include = False
if not include:
continue
f.write(all_functions[function_name].export(export_v8code="v8_opcode" in format_list, export_translated="translated" in format_list, export_decompiled="decompiled" in format_list))
def _get_extension(filename):
ext = None
if '.' in filename:
ext = '.' + filename.rsplit('.', 1)[-1]
return ext
def _add_or_replace_extension(filename, new_ext):
if not new_ext.startswith('.'):
new_ext = '.' + new_ext
base = filename.rsplit('.', 1)[0] if '.' in filename else filename
return base + new_ext
def export_to_file(out_name, all_functions, format_list, included_list=None, excluded_list=None):
"""
Saves the decompiled functions into a file of a given format.
:param out_name: Name of the output file (the extension may be autoadjusted to the output format)
:param all_functions: Decompiled functions to be exported
:param format_list: A list defining the format/s that will be used to export the content.
:param included_list: If defined: only functions to be included in the output (param ignored in `serialized` format)
:param excluded_list: If defined: functions to be excluded from the output (param ignored in `serialized` format)
"""
serialize_only = False
serialized_ext = ".pkl"
text_ext = ".txt"
if ('serialized' in format_list):
if len(format_list) == 1:
serialize_only = True
serialized_name = _add_or_replace_extension(out_name, serialized_ext)
print(f"Serializing to file: {serialized_name}")
save_functions_to_file(all_functions, serialized_name)
if serialize_only:
return
if _get_extension(out_name) == serialized_ext:
out_name = _add_or_replace_extension(out_name, text_ext)
_export_to_file(out_name, all_functions, format_list, included_list, excluded_list)
###
def create_dirs(nested_directory):
is_ok = False
try:
os.makedirs(nested_directory)
is_ok = True
except FileExistsError:
is_ok = True
except Exception as e:
print(f"An error occurred: {e}")
return is_ok