-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDecompiler.cs
288 lines (229 loc) · 6.81 KB
/
Decompiler.cs
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
/**
* Decompiler.cs
*
* Copyright (C) 2024 Elletra
*
* This file is part of the DSO Sharp source code. It may be used under the BSD 3-Clause License.
*
* For full terms, see the LICENSE file or visit https://spdx.org/licenses/BSD-3-Clause.html
*/
using DSO.AST;
using DSO.AST.Nodes;
using DSO.ControlFlow;
using DSO.Disassembler;
using DSO.Loader;
using DSO.Util;
using DSO.Versions;
using static DSO.Constants.Decompiler;
using static DSO.Util.CommandLineOptions;
namespace DSO
{
public class DecompilerException : Exception
{
public DecompilerException() { }
public DecompilerException(string message) : base(message) { }
public DecompilerException(string message, Exception inner) : base(message, inner) { }
}
public class Decompiler
{
private CommandLineOptions _options;
public void Decompile(CommandLineOptions options)
{
if (options.Paths.Count <= 0)
{
return;
}
_options = options;
var startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
foreach (var path in options.Paths)
{
if (Path.HasExtension(path))
{
if (Path.GetExtension(path) != EXTENSION)
{
Logger.LogError($"File \"{path}\" does not have a `{EXTENSION}` extension");
return;
}
if (!File.Exists(path))
{
Logger.LogError($"File \"{path}\" does not exist at the path specified");
return;
}
}
else if (!Directory.Exists(path))
{
Logger.LogError($"Directory \"{path}\" does not exist at the path specified");
return;
}
}
var files = 0;
var failures = 0;
foreach (var path in options.Paths)
{
if (Path.HasExtension(path))
{
files++;
if (!DecompileFile(path))
{
failures++;
}
}
else
{
if (files > 0)
{
Logger.LogMessage("");
}
var result = DecompileDirectory(path);
files += result.Item1;
failures += result.Item2;
}
}
var totalTime = DateTimeOffset.Now.ToUnixTimeMilliseconds() - startTime;
var plural = files != 1;
Logger.LogMessage("");
var verb = _options.OutputDisassembly == DisassemblyOutput.DisassemblyOnly ? "Disassemble" : "Decompile";
if (failures <= 0)
{
Logger.LogSuccess($"{verb}d {files} file{(plural ? "s" : "")} successfully in {totalTime} ms\n");
}
else if (failures < files)
{
Logger.LogWarning($"{verb}d {files - failures} of {files} file{(plural ? "s" : "")} in {totalTime} ms");
}
else
{
Logger.LogError($"Failed to {verb.ToLower()} {(plural ? "all " : "")}{files} file{(plural ? "s" : "")}");
}
}
private Tuple<int, int> DecompileDirectory(string path)
{
Logger.LogMessage($"{(_options.OutputDisassembly == DisassemblyOutput.DisassemblyOnly ? "Disassembling" : "Decompiling")} all files in directory: \"{path}\"");
var files = Directory.GetFiles(path, $"*{EXTENSION}", SearchOption.AllDirectories);
var failures = 0;
foreach (var file in files)
{
if (!DecompileFile(file))
{
failures++;
}
}
return new(files.Length, failures);
}
private bool DecompileFile(string path)
{
if (_options.OutputDisassembly == DisassemblyOutput.DisassemblyOnly)
{
Logger.LogMessage($"Disassembling file: \"{path}\"");
}
else
{
Logger.LogMessage($"Decompiling file: \"{path}\"");
}
if (_options.GameIdentifier != GameIdentifier.Auto)
{
Logger.LogMessage($"\tUsing game settings: \"{GameVersion.GetDisplayName(_options.GameIdentifier)}\"", ConsoleColor.DarkGray);
return DecompileFile(path, _options.GameIdentifier, silentError: false);
}
var version = FileLoader.ReadFileVersion(path);
var identifiers = GameVersion.GetIdentifiersFromVersion(version);
if (identifiers.Length <= 0)
{
Logger.LogError($"Could not automatically identify game from file");
return false;
}
if (identifiers.Length == 1)
{
Logger.LogMessage($"\tGame automatically detected as {GameVersion.GetDisplayName(identifiers[0])}", ConsoleColor.DarkGray);
return DecompileFile(path, identifiers[0], silentError: false);
}
Logger.LogWarning($"Multiple games use file version {version}!");
for (var i = 0; i < identifiers.Length; i++)
{
var ident = identifiers[i];
Logger.LogMessage($"\tAttempting with settings: \"{GameVersion.GetDisplayName(ident)}\"", ConsoleColor.DarkGray);
if (DecompileFile(path, ident, silentError: i < identifiers.Length - 1))
{
return true;
}
}
Logger.LogError("Failed to decompile after multiple attempts");
return false;
}
private bool DecompileFile(string path, GameIdentifier identifier, bool silentError)
{
GameVersion? game = null;
FileData data;
Disassembly disassembly;
List<Node> nodes = [];
var disassemblyOnly = _options.OutputDisassembly == DisassemblyOutput.DisassemblyOnly;
try
{
game = GameVersion.Create(identifier);
data = game?.FileLoader.LoadFile(path);
if (data.Version != game.Version)
{
Logger.LogWarning($"File version {data.Version} differs from expected version {game.Version}");
}
disassembly = new Disassembler.Disassembler().Disassemble(GameVersion.CreateBytecodeReader(identifier, data, game.Ops));
if (!disassemblyOnly)
{
nodes = new Builder().Build(new ControlFlowAnalyzer().Analyze(disassembly), disassembly);
}
}
catch (Exception exception)
{
if (!silentError)
{
Logger.LogError(exception.Message);
}
game.FileLoader?.Close();
return false;
}
if (!disassemblyOnly)
{
var scriptPath = $"{Directory.GetParent(path)}/{Path.GetFileNameWithoutExtension(path)}";
Logger.LogMessage($"Writing output file: \"{scriptPath}\"");
WriteScriptFile(scriptPath, nodes);
}
if (_options.OutputDisassembly != DisassemblyOutput.None)
{
var disassemblyPath = $"{Directory.GetParent(path)}/{Path.GetFileNameWithoutExtension(path)}{DISASM_EXTENSION}";
Logger.LogMessage($"Writing disassembly file: \"{disassemblyPath}\"");
WriteDisassemblyFile(disassemblyPath, game, data, disassembly);
}
return true;
}
private bool WriteScriptFile(string outputPath, List<Node> nodes)
{
var success = false;
try
{
File.WriteAllText(outputPath, string.Join("", new CodeGenerator.CodeGenerator().Generate(nodes)));
success = true;
}
catch (Exception exception)
{
Logger.LogError(exception.Message);
}
return success;
}
private bool WriteDisassemblyFile(string outputPath, GameVersion game, FileData fileData, Disassembly disassembly)
{
var success = false;
try
{
var writer = new DisassemblyWriter();
writer.WriteHeader(game, fileData);
disassembly.Visit(writer);
File.WriteAllText(outputPath, string.Join("", writer.Stream));
success = true;
}
catch (Exception exception)
{
Logger.LogError(exception.Message);
}
return success;
}
}
}