Skip to content
This repository was archived by the owner on Sep 14, 2022. It is now read-only.

Commit f739b71

Browse files
author
Michael P. Starkweather
committed
Code cleanup and change parameter of LoadDLL
1 parent 97aa9a8 commit f739b71

File tree

2 files changed

+141
-130
lines changed

2 files changed

+141
-130
lines changed

BattleTechModLoader/BTModLoader.cs

Lines changed: 128 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,25 @@ namespace BattleTechModLoader
1111
{
1212
public static class BTModLoader
1313
{
14-
public static string LogPath;
15-
public static string ModDirectory;
14+
internal static string modDirectory;
15+
16+
// logging
17+
internal static string logPath;
18+
internal static void Log(string message, params object[] formatObjects)
19+
{
20+
if (logPath != null && logPath != "")
21+
using (var logWriter = File.AppendText(logPath))
22+
logWriter.WriteLine(message, formatObjects);
23+
}
24+
25+
internal static void LogWithDate(string message, params object[] formatObjects)
26+
{
27+
if (logPath != null && logPath != "")
28+
using (var logWriter = File.AppendText(logPath))
29+
logWriter.WriteLine(DateTime.Now.ToLongTimeString() + " - " + message, formatObjects);
30+
}
1631

17-
public static void LoadDLL(string path, StreamWriter logWriter = null, string methodName = "Init", string typeName = null, object[] prms = null, BindingFlags bFlags = BindingFlags.Public | BindingFlags.Static)
32+
public static void LoadDLL(string path, string methodName = "Init", string typeName = null, object[] prms = null, BindingFlags bFlags = BindingFlags.Public | BindingFlags.Static)
1833
{
1934
var fileName = Path.GetFileName(path);
2035

@@ -25,159 +40,157 @@ public static void LoadDLL(string path, StreamWriter logWriter = null, string me
2540

2641
// find the type/s with our entry point/s
2742
if (typeName == null)
28-
{
2943
types.AddRange(assembly.GetTypes().Where(x => x.GetMethod(methodName, bFlags) != null));
30-
}
3144
else
32-
{
3345
types.Add(assembly.GetType(typeName));
46+
47+
// run each entry point
48+
if (types.Count == 0)
49+
{
50+
LogWithDate("{0}: Failed to find specified entry point: {1}.{2}", fileName, typeName ?? "NotSpecified", methodName);
51+
return;
3452
}
3553

36-
if (types.Count > 0)
54+
foreach (var type in types)
3755
{
38-
// run each entry point
39-
foreach (var type in types)
40-
{
41-
var entryMethod = type.GetMethod(methodName, bFlags);
42-
var methodParams = entryMethod.GetParameters();
56+
var entryMethod = type.GetMethod(methodName, bFlags);
57+
var methodParams = entryMethod.GetParameters();
4358

44-
if (methodParams.Length == 0)
45-
{
46-
logWriter?.WriteLine("{0}: Found and called entry point with void param: {1}.{2}", fileName, type.Name, entryMethod.Name);
47-
entryMethod.Invoke(null, null);
48-
}
49-
else
59+
if (methodParams.Length == 0)
60+
{
61+
LogWithDate("{0}: Found and called entry point with void param: {1}.{2}", fileName, type.Name, entryMethod.Name);
62+
entryMethod.Invoke(null, null);
63+
}
64+
else
65+
{
66+
// match up the passed in params with the method's params, if they match, call the method
67+
if (prms != null && methodParams.Length == prms.Length)
5068
{
51-
// match up the passed in params with the method's params, if they match, call the method
52-
if (prms != null && methodParams.Length == prms.Length)
69+
bool paramsMatch = true;
70+
for (int i = 0; i < methodParams.Length; i++)
5371
{
54-
bool paramsMatch = true;
55-
for (int i = 0; i < methodParams.Length; i++)
72+
if (prms[i] != null && prms[i].GetType() != methodParams[i].ParameterType)
5673
{
57-
if (prms[i] != null && prms[i].GetType() != methodParams[i].ParameterType)
58-
{
59-
paramsMatch = false;
60-
}
61-
}
62-
63-
if (paramsMatch)
64-
{
65-
logWriter?.WriteLine("{0}: Found and called entry point with params: {1}.{2}", fileName, type.Name, entryMethod.Name);
66-
entryMethod.Invoke(null, prms);
67-
continue;
68-
}
69-
}
70-
71-
logWriter?.WriteLine("{0}: Provided params don't match {1}.{2}", fileName, type.Name, entryMethod.Name);
72-
logWriter?.WriteLine("\tPassed in Params:");
73-
if (prms != null)
74-
{
75-
foreach (var prm in prms)
76-
{
77-
logWriter?.WriteLine("\t\t{0}", prm.GetType());
74+
paramsMatch = false;
7875
}
7976
}
80-
else
81-
{
82-
logWriter?.WriteLine("\t\tprms is null");
83-
}
84-
if (methodParams != null)
77+
78+
if (paramsMatch)
8579
{
86-
logWriter?.WriteLine("\tMethod Params:");
87-
foreach (var prm in methodParams)
88-
{
89-
logWriter?.WriteLine("\t\t{0}", prm.ParameterType);
90-
}
80+
LogWithDate("{0}: Found and called entry point with params: {1}.{2}", fileName, type.Name, entryMethod.Name);
81+
entryMethod.Invoke(null, prms);
82+
continue;
9183
}
9284
}
85+
86+
// diagnosing problems of this type (haha it's a pun) is pretty hard
87+
LogWithDate("{0}: Provided params don't match {1}.{2}", fileName, type.Name, entryMethod.Name);
88+
Log("\tPassed in Params:");
89+
if (prms != null)
90+
{
91+
foreach (var prm in prms)
92+
Log("\t\t{0}", prm.GetType());
93+
}
94+
else
95+
{
96+
Log("\t\tprms is null");
97+
}
98+
99+
if (methodParams != null)
100+
{
101+
Log("\tMethod Params:");
102+
103+
foreach (var prm in methodParams)
104+
Log("\t\t{0}", prm.ParameterType);
105+
}
93106
}
94107
}
95-
else
96-
{
97-
logWriter?.WriteLine("{0}: Failed to find specified entry point: {1}.{2}", fileName, (typeName == null) ? typeName : "NotSpecified", methodName);
98-
}
99108
}
100109
catch (Exception e)
101110
{
102-
logWriter?.WriteLine("{0}: While loading a dll, an exception occured: {1}", fileName, e.ToString());
111+
LogWithDate("{0}: While loading a dll, an exception occured:\n{1}", fileName, e.ToString());
103112
}
104113
}
105114

106115
public static void Init()
107116
{
108-
ModDirectory = Path.Combine(Path.GetDirectoryName(VersionManifestUtilities.MANIFEST_FILEPATH), @"..\..\..\Mods\");
109-
LogPath = Path.Combine(ModDirectory, "BTModLoader.log");
117+
modDirectory = Path.Combine(Path.GetDirectoryName(VersionManifestUtilities.MANIFEST_FILEPATH), @"..\..\..\Mods\");
118+
logPath = Path.Combine(modDirectory, "BTModLoader.log");
110119

111120
// do some simple benchmarking
112121
Stopwatch sw = new Stopwatch();
113122
sw.Start();
114123

115-
if (!Directory.Exists(ModDirectory))
116-
Directory.CreateDirectory(ModDirectory);
124+
if (!Directory.Exists(modDirectory))
125+
Directory.CreateDirectory(modDirectory);
126+
127+
// create log file, overwritting if it's already there
128+
using (var logWriter = File.CreateText(logPath))
129+
logWriter.WriteLine("BTModLoader -- {0}", DateTime.Now);
117130

118131
var harmony = HarmonyInstance.Create("io.github.mpstark.BTModLoader");
119132

120-
using (var logWriter = File.CreateText(LogPath))
133+
// get all dll paths
134+
var dllPaths = Directory.GetFiles(modDirectory).Where(x => Path.GetExtension(x).ToLower() == ".dll");
135+
136+
if (dllPaths.Count() == 0)
121137
{
122-
logWriter.WriteLine("BTModLoader -- {0}", DateTime.Now.ToString());
138+
Log(@"No .dlls loaded. DLLs must be placed in the root of the folder \BATTLETECH\Mods\.");
139+
return;
140+
}
123141

124-
var dllPaths = new DirectoryInfo(ModDirectory).GetFiles("*.dll", SearchOption.TopDirectoryOnly);
125-
if (dllPaths.Length == 0)
126-
{
127-
logWriter.WriteLine(@"No .dlls loaded. DLLs must be placed in the root of the folder \BATTLETECH\Mods\.");
128-
}
129-
else
130-
{
131-
foreach (var dllFileInfo in dllPaths)
132-
{
133-
logWriter.WriteLine("Found DLL: {0}", dllFileInfo.Name);
134-
LoadDLL(dllFileInfo.ToString(), logWriter);
135-
}
136-
}
137-
138-
// print out harmony summary
139-
logWriter.WriteLine("");
140-
logWriter.WriteLine("Harmony Patched Methods (after mod loader startup):");
141-
var patchedMethods = harmony.GetPatchedMethods();
142-
foreach (var method in patchedMethods)
143-
{
144-
var info = harmony.IsPatched(method);
142+
// load the dlls
143+
foreach (var dllPath in dllPaths)
144+
{
145+
Log("Found DLL: {0}", Path.GetFileName(dllPath));
146+
LoadDLL(dllPath);
147+
}
148+
149+
// do some simple benchmarking
150+
sw.Stop();
151+
Log("");
152+
Log("Took {0} seconds to load mods", sw.Elapsed.TotalSeconds);
145153

146-
if (info != null)
147-
{
148-
logWriter.WriteLine("{0}.{1}.{2}:", method.ReflectedType.Namespace, method.ReflectedType.Name, method.Name);
154+
// print out harmony summary
155+
var patchedMethods = harmony.GetPatchedMethods();
156+
if (patchedMethods.Count() == 0)
157+
{
158+
Log("No Harmony Patches loaded.");
159+
return;
160+
}
149161

150-
// prefixes
151-
if (info.Prefixes.Count != 0)
152-
logWriter.WriteLine("\tPrefixes:");
153-
foreach (var patch in info.Prefixes)
154-
{
155-
logWriter.WriteLine("\t\t{0}", patch.owner);
156-
}
162+
Log("");
163+
Log("Harmony Patched Methods (after mod loader startup):");
157164

158-
// transpilers
159-
if (info.Transpilers.Count != 0)
160-
logWriter.WriteLine("\tTranspilers:");
161-
foreach (var patch in info.Transpilers)
162-
{
163-
logWriter.WriteLine("\t\t{0}", patch.owner);
164-
}
165+
foreach (var method in patchedMethods)
166+
{
167+
var info = harmony.IsPatched(method);
165168

166-
// postfixes
167-
if (info.Postfixes.Count != 0)
168-
logWriter.WriteLine("\tPostfixes:");
169-
foreach (var patch in info.Postfixes)
170-
{
171-
logWriter.WriteLine("\t\t{0}", patch.owner);
172-
}
173-
}
174-
}
169+
if (info != null)
170+
{
171+
Log("{0}.{1}.{2}:", method.ReflectedType.Namespace, method.ReflectedType.Name, method.Name);
175172

176-
// do some simple benchmarking
177-
sw.Stop();
178-
logWriter.WriteLine();
179-
logWriter.WriteLine("Took {0} seconds to load mods", sw.Elapsed.TotalSeconds);
173+
// prefixes
174+
if (info.Prefixes.Count != 0)
175+
Log("\tPrefixes:");
176+
foreach (var patch in info.Prefixes)
177+
Log("\t\t{0}", patch.owner);
178+
179+
// transpilers
180+
if (info.Transpilers.Count != 0)
181+
Log("\tTranspilers:");
182+
foreach (var patch in info.Transpilers)
183+
Log("\t\t{0}", patch.owner);
184+
185+
// postfixes
186+
if (info.Postfixes.Count != 0)
187+
Log("\tPostfixes:");
188+
foreach (var patch in info.Postfixes)
189+
Log("\t\t{0}", patch.owner);
190+
}
180191
}
192+
193+
Log("");
181194
}
182195
}
183196
}

BattleTechModLoaderInjector/BTMLInjector.cs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ static void Main(string[] args)
5050
Console.ReadKey();
5151
}
5252

53-
public static void Backup(string filePath, string backupFilePath)
53+
static void Backup(string filePath, string backupFilePath)
5454
{
5555
if (File.Exists(backupFilePath))
5656
File.Delete(backupFilePath);
@@ -60,30 +60,28 @@ public static void Backup(string filePath, string backupFilePath)
6060
Console.WriteLine("{0} backed up to {1}", Path.GetFileName(filePath), Path.GetFileName(backupFilePath));
6161
}
6262

63-
public static void Inject(string hookFilePath, string hookType, string hookMethod, string injectFilePath, string injectType, string injectMethod)
63+
static void Inject(string hookFilePath, string hookType, string hookMethod, string injectFilePath, string injectType, string injectMethod)
6464
{
6565
Console.WriteLine("Injecting {0} with {1}.{2} at {3}.{4}", Path.GetFileName(hookFilePath), injectType, injectMethod, hookType, hookMethod);
6666

6767
using (var game = ModuleDefinition.ReadModule(hookFilePath, new ReaderParameters { ReadWrite = true }))
68+
using (var injected = ModuleDefinition.ReadModule(injectFilePath))
6869
{
69-
using (var injected = ModuleDefinition.ReadModule(injectFilePath))
70-
{
71-
// get the methods that we're hooking and injecting
72-
var injectedMethod = injected.GetType(injectType).Methods.Single(x => x.Name == injectMethod);
73-
var hookedMethod = game.GetType(hookType).Methods.First(x => x.Name == hookMethod);
70+
// get the methods that we're hooking and injecting
71+
var injectedMethod = injected.GetType(injectType).Methods.Single(x => x.Name == injectMethod);
72+
var hookedMethod = game.GetType(hookType).Methods.First(x => x.Name == hookMethod);
7473

75-
// inject our method into the beginning of the hooks method
76-
hookedMethod.Body.GetILProcessor().InsertBefore(hookedMethod.Body.Instructions[0], Instruction.Create(OpCodes.Call, game.ImportReference(injectedMethod)));
74+
// inject our method into the beginning of the hooks method
75+
hookedMethod.Body.GetILProcessor().InsertBefore(hookedMethod.Body.Instructions[0], Instruction.Create(OpCodes.Call, game.ImportReference(injectedMethod)));
7776

78-
// save the modified assembly
79-
Console.WriteLine("Writing back to {0}...", Path.GetFileName(hookFilePath));
80-
game.Write();
81-
Console.WriteLine("Injection complete!");
82-
}
77+
// save the modified assembly
78+
Console.WriteLine("Writing back to {0}...", Path.GetFileName(hookFilePath));
79+
game.Write();
80+
Console.WriteLine("Injection complete!");
8381
}
8482
}
8583

86-
public static bool IsInjected(string hookFilePath, string hookType, string hookMethod, string injectFilePath, string injectType, string injectMethod)
84+
static bool IsInjected(string hookFilePath, string hookType, string hookMethod, string injectFilePath, string injectType, string injectMethod)
8785
{
8886
using (var game = ModuleDefinition.ReadModule(hookFilePath))
8987
{

0 commit comments

Comments
 (0)