forked from Xkein/YRDynamicPatcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatcher.cs
More file actions
335 lines (288 loc) · 12.2 KB
/
Patcher.cs
File metadata and controls
335 lines (288 loc) · 12.2 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
331
332
333
334
335
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DynamicPatcher
{
/// <summary>Provides data for the DynamicPatcher.Patcher.AssemblyRefresh event.</summary>
public class AssemblyRefreshEventArgs : EventArgs
{
/// <summary>Initializes a new instance of the DynamicPatcher.AssemblyRefreshEventArgs class.</summary>
public AssemblyRefreshEventArgs(string fileName, Assembly refreshedAssembly)
{
FileName = fileName;
RefreshedAssembly = refreshedAssembly;
}
/// <summary>Gets string that represents the currently file name.</summary>
public string FileName { get; private set; }
/// <summary>Gets an System.Reflection.Assembly that represents the currently refreshed assembly.</summary>
public Assembly RefreshedAssembly { get; private set; }
}
/// <summary>Represents the method that handles the DynamicPatcher.Patcher.AssemblyRefresh event of an DynamicPatcher.Patcher.</summary>
public delegate void AssemblyRefreshEventHandler(object sender, AssemblyRefreshEventArgs args);
/// <summary>Run class constructor before hook.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class RunClassConstructorFirstAttribute : Attribute
{
}
/// <summary>The class of DynamicPatcher.</summary>
public class Patcher
{
private CompilationManager CompilationManager { get; set; }
/// <summary>The map of 'filename -> assembly'.</summary>
public Dictionary<string, Assembly> FileAssembly { get; } = new Dictionary<string, Assembly>();
/// <summary>Occurs when DynamicPatcher.Patcher.RefreshAssembly.</summary>
public event AssemblyRefreshEventHandler AssemblyRefresh;
HookManager hookManager;
CodeWatcher codeWatcher;
internal Patcher()
{
Logger.WriteLine += ConsoleWriteLine;
}
[DllImport("kernel32.dll")]
private static extern bool AllocConsole();
[DllImport("kernel32", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern bool FreeConsole();
void ConsoleWriteLine(string str) => Console.WriteLine(str);
/// <summary>Occurs when an exception is not caught.</summary>
public event UnhandledExceptionEventHandler ExceptionHandler;
internal void Init(string workDir)
{
FileStream logFileStream = new FileStream(Path.Combine(workDir, "patcher.log"), FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
var logFileWriter = new StreamWriter(logFileStream);
logFileWriter.AutoFlush = true;
Logger.WriteLine += (string str) =>
{
logFileWriter.WriteLine(str);
};
ExceptionHandler += (object sender, UnhandledExceptionEventArgs args) =>
{
if(args != null)
{
Logger.PrintException(args.ExceptionObject as Exception);
}
};
ExceptionHandler += (object sender, UnhandledExceptionEventArgs args) =>
{
string dir = Path.Combine(workDir, "ErrorLogs");
Directory.CreateDirectory(dir);
DateTime date = DateTime.Now;
File.Copy(logFileStream.Name,
Path.Combine(dir, string.Format("ErrorLog_{0}_{1}_{2}_{3}_{4}.log",
date.Year, date.Month, date.Day, date.Hour, date.Minute)), true);
System.Windows.Forms.MessageBox.Show("ErrorLog Created", "Dynamic Patcher");
};
try
{
Logo.ShowLogo();
using StreamReader file = File.OpenText(Path.Combine(workDir, "dynamicpatcher.config.json"));
using JsonTextReader reader = new JsonTextReader(file);
var json = JObject.Load(reader);
if (json["hide_console"].ToObject<bool>())
{
FreeConsole();
Logger.WriteLine -= ConsoleWriteLine;
}
if (json["show_attach_window"].ToObject<bool>())
{
System.Windows.Forms.MessageBox.Show("Attach Me", "Dynamic Patcher");
}
if (json["try_catch_callable"].ToObject<bool>())
{
HookInfo.TryCatchCallable = true;
}
Logger.Log("try-catch callable: " + HookInfo.TryCatchCallable);
if (json["force_gc_collect"].ToObject<bool>())
{
Task.Run(() =>
{
Action showGCInfo = () =>
{
var curProc = Process.GetCurrentProcess();
Logger.Log("Total Memory: {0} MB", curProc.PrivateMemorySize64 / 1024 / 1024);
Logger.Log("Managed Memory: {0} MB", GC.GetTotalMemory(true) / 1024 / 1024);
for (int g = 0; g <= GC.MaxGeneration; g++)
{
Logger.Log("{0} Generation Count: {1}", g, GC.CollectionCount(g));
}
};
while (true)
{
Logger.Log("Sleep 10s.");
Thread.Sleep(TimeSpan.FromSeconds(10));
Logger.Log("----------------------");
Logger.Log("GC collecting...");
showGCInfo();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.WaitForFullGCComplete();
Logger.Log("GC collect finish.");
showGCInfo();
}
});
}
CompilationManager = new CompilationManager(workDir);
hookManager = new HookManager();
codeWatcher = new CodeWatcher(workDir);
codeWatcher.FirstAction += FirstCompile;
codeWatcher.OnCodeChanged += OnCodeChanged;
}
catch (Exception e)
{
Logger.PrintException(e);
}
}
internal Task Start()
{
return codeWatcher.StartWatchPath();
}
private bool TryCompile(string path, out Assembly assembly)
{
assembly = null;
try
{
assembly = CompilationManager.Compile(path);
}
catch (Exception e)
{
Logger.LogError("compile error!");
Logger.PrintException(e);
}
return assembly != null;
}
private void OnCodeChanged(object sender, FileSystemEventArgs e)
{
string path = e.FullPath;
Logger.Log("");
Logger.Log("detected file {0}: {1}", e.ChangeType, path);
switch (e.ChangeType)
{
case WatcherChangeTypes.Changed:
case WatcherChangeTypes.Created:
break;
case WatcherChangeTypes.Deleted:
Logger.Log("remove assembly '{0}' hooks.", FileAssembly[path].FullName);
hookManager.RemoveAssemblyHook(FileAssembly[path]);
return;
case WatcherChangeTypes.Renamed:
string oldPath = (e as RenamedEventArgs).OldFullPath;
if (FileAssembly.ContainsKey(oldPath))
{
Logger.Log("remove assembly '{0}' hooks.", FileAssembly[oldPath].FullName);
hookManager.RemoveAssemblyHook(FileAssembly[oldPath]);
}
break;
}
// wait for editor releasing
var time = TimeSpan.FromSeconds(1.0);
Logger.Log("sleep: {0}s", time.TotalSeconds);
Thread.Sleep(time);
Logger.Log("");
if (TryCompile(path, out var assembly))
{
RefreshAssembly(path, assembly);
}
else
{
Logger.LogError("file compile error: " + path);
}
}
void FirstCompile(string path)
{
try
{
Logger.Log("first compile: " + path);
var dir = new DirectoryInfo(path);
var list = dir.GetFiles("*.cs", SearchOption.AllDirectories).ToList();
List<Tuple<string, Assembly>> assemblies = new();
foreach (var file in list)
{
string filePath = file.FullName;
var project = CompilationManager.GetProjectFromFile(filePath);
// skip because already compiled
if (project == null)
{
if (TryCompile(filePath, out var assembly))
{
assemblies.Add(new Tuple<string, Assembly>(filePath, assembly));
//RefreshAssembly(filePath, assembly);
}
else
{
Logger.Log("first compile error: " + file.FullName);
Logger.Log("");
}
}
}
assemblies.ForEach((tuple) => RefreshAssembly(tuple.Item1, tuple.Item2));
}
catch (Exception ex)
{
Logger.PrintException(ex);
throw ex;
}
}
void RefreshAssembly(string path, Assembly assembly)
{
if (FileAssembly.ContainsKey(path))
{
Logger.Log("replace assembly '{0}' with '{1}'", FileAssembly[path].FullName, assembly.FullName);
hookManager.RemoveAssemblyHook(FileAssembly[path]);
FileAssembly[path] = assembly;
}
else
{
foreach (var pair in FileAssembly.Where(pair => Path.GetFileNameWithoutExtension(pair.Key) == Path.GetFileNameWithoutExtension(path)))
{
Logger.LogWarning("{0} has same Assembly name with {1}", pair.Key, path);
}
FileAssembly.Add(path, assembly);
}
try
{
ApplyAssembly(assembly);
AssemblyRefresh?.Invoke(this, new AssemblyRefreshEventArgs(Path.GetFileNameWithoutExtension(path), assembly));
}
catch (Exception e)
{
Logger.LogError("apply error!");
Logger.PrintException(e);
}
}
void ApplyAssembly(Assembly assembly)
{
Logger.Log("appling: " + assembly.FullName);
Logger.Log("-----------------------------------");
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
Logger.Log("in class {0}: ", type.FullName);
if (type.IsDefined(typeof(RunClassConstructorFirstAttribute), false))
{
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
}
MemberInfo[] members = type.GetMembers();
foreach (MemberInfo member in members)
{
if (member.IsDefined(typeof(HookAttribute), false))
{
Logger.Log("");
hookManager.ApplyHook(member);
}
}
}
Logger.Log("-----------------------------------");
Logger.Log("");
}
}
}