-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathUtils.cs
More file actions
431 lines (385 loc) · 15.1 KB
/
Copy pathUtils.cs
File metadata and controls
431 lines (385 loc) · 15.1 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
namespace MiscUtils
{
public class Utils
{
public static void debugWrite(string str)
{
Trace.WriteLine(str);
}
public static int compVers(string a, string b)
{
try
{
return new Version(a).CompareTo(new Version(b));
}
catch (Exception ex)
{
debugWrite(ex.ToString());
return -100;
}
}
public static string doHTTPReq(string url, string userAgent)
{
string ret = null;
try
{
var request = WebRequest.Create(url);
((HttpWebRequest)request).UserAgent = userAgent;
var response = request.GetResponse();
debugWrite($"StatusCode: {((HttpWebResponse)response).StatusCode}");
var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
ret = reader.ReadToEnd();
reader.Close(); //closes the stream and the response
}
catch (Exception ex)
{
debugWrite(ex.ToString());
}
return ret;
}
public static int checkVerAgainstURL(string url, string userAgent, string appVer)
{
//appVer -> Application.ProductVersion
//URL should have a version number followed by a newline. later lines are ignored.
//1 -> newer ver available.
//0 -> current.
//-1 -> this version is newer.
//-100 -> error
var vInfo = doHTTPReq(url, userAgent);
if (string.IsNullOrEmpty(vInfo)) { return -100; }
debugWrite(vInfo);
try
{
var r = new StringReader(vInfo);
var ver = r.ReadLine();
if (ver != null) { return compVers(ver, appVer); }
}
catch (Exception ex)
{
debugWrite(ex.ToString());
}
return -100;
}
public static string getFnameInAppdata(string fname, string appName, bool localAppData = false)
{//will create dir if needed, otherwise return a full filename.
var appData = Environment.GetFolderPath(localAppData ? Environment.SpecialFolder.LocalApplicationData : Environment.SpecialFolder.ApplicationData);
var appFolder = Path.Combine(appData, appName);
if (!Directory.Exists(appFolder))
{
Directory.CreateDirectory(appFolder);
}
return Path.Combine(appFolder, fname);
}
public static DateTime getFileDate(string fname)
{//will create a file if needed
var ret = new DateTime(0);
try
{
if (File.Exists(fname))
{
ret = File.GetLastWriteTime(fname);
}
else
{
File.Create(fname).Dispose();
}
}
catch (Exception ex) { debugWrite(ex.ToString()); }
return ret;
}
public static bool setFileDate(string fname)
{
try
{
File.SetLastWriteTime(fname, DateTime.Now);
return true;
}
catch (Exception ex) { debugWrite(ex.ToString()); }
return false;
}
public static void removeFile(string fname)
{
try
{
if (File.Exists(fname)) { File.Delete(fname); }
}
catch (Exception ex) { debugWrite(ex.ToString()); }
}
}
public class LaunchUtils
{
public static string promptForFile(string startFolder, string filter)
{
OpenFileDialog d = new OpenFileDialog();
d.InitialDirectory = startFolder;
d.Filter = filter;
if (d.ShowDialog() != true)
{
return null;
}
return d.FileName;
}
public static bool launchGame()
{
try
{
string exename = @"eldenring.exe";
string path = exename;
if (File.Exists(path)) // prioritize running Elden Ring from the folder this exe is in.
{
Utils.debugWrite("Found Elden Ring exe at: " + path);
}
else // otherwise dynamically search for the game in steam config files
{
path = GetEldenRingExePath();
Utils.debugWrite("Found Elden Ring exe at: " + path);
}
var psi = new ProcessStartInfo(path);
psi.EnvironmentVariables["SteamAppId"] = "1245620";
psi.UseShellExecute = false;
psi.WorkingDirectory = System.IO.Path.GetDirectoryName(path);
Process.Start(psi);
return true;
}
catch
{
return false;
}
}
public static string GetEldenRingExePath()
{
string steamPath = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Valve\Steam", "InstallPath", null) as string;
if (string.IsNullOrEmpty(steamPath))
return null;
List<string> libraries = new List<string>();
string steamInstallConfigPath = Path.Combine(steamPath, "steamapps", "libraryfolders.vdf"); // contains info about steam games install locations
if (File.Exists(steamInstallConfigPath))
{
string[] lines = File.ReadAllLines(steamInstallConfigPath);
var regex = new Regex(@"""path""\s+""(.+?)"""); // search the config for lines with the text: "path"
foreach (string line in lines)
{
var match = regex.Match(line);
if (match.Success)
{
string path = match.Groups[1].Value.Replace(@"\\", @"\");
libraries.Add(path);
}
}
}
foreach (string installDir in libraries)
{
string gamePath = Path.Combine(installDir, "steamapps", "common", "ELDEN RING", "Game", "eldenring.exe");
if (File.Exists(gamePath))
{
return gamePath;
}
}
return null;
}
}
#if NO_WPF
//alternative/dummy implementations for console tools
enum MessageBoxButton { OK }
enum MessageBoxImage { Information }
class MessageBox
{
public static void Show(string str = "", string str2 = "", MessageBoxButton b = MessageBoxButton.OK, MessageBoxImage i = MessageBoxImage.Information)
{
Console.WriteLine($"{str2} {str}");
}
}
class OpenFileDialog
{
public string InitialDirectory { get; set; }
public string Filter { get; set; }
public string FileName { get; set; }
public bool? ShowDialog() { return null; }
}
#endif
public class AOBScanner : IDisposable
{
[DllImport("ntdll.dll")]
static extern int NtReadVirtualMemory(IntPtr ProcessHandle, IntPtr BaseAddress, byte[] Buffer, UInt32 NumberOfBytesToRead, ref UInt32 NumberOfBytesRead);
public uint textOneSize = 0;
public int textOneAddr = 0;
public uint textTwoSize = 0;
public int textTwoAddr = 0;
public byte[] sectionOne = new byte[0];
public byte[] sectionTwo = new byte[0];
public AOBScanner(IntPtr handle, IntPtr baseAddr, int size)
{
#if !DEBUG
outputConsole = false;
#endif
//TODO: switch to .NET 5+ and use PEHeaders?
//for now: assume two text sections, and aob scan for them, of course.
var buf = new byte[0x600];
uint bytesRead = 0;
NtReadVirtualMemory(handle, baseAddr, buf, (uint)buf.Length, ref bytesRead);
var dotText = Encoding.ASCII.GetBytes(".text");
var dummy = new byte[5];
int textOne = FindBytes(buf, dotText, dummy);
if (textOne < 0)
{
Console.WriteLine("Cannot find text section");
return;
}
textOneSize = BitConverter.ToUInt32(buf, textOne + 8);
textOneAddr = BitConverter.ToInt32(buf, textOne + 12);
sectionOne = new byte[textOneSize];
NtReadVirtualMemory(handle, baseAddr + textOneAddr, sectionOne, textOneSize, ref bytesRead);
int textTwo = FindBytes(buf, dotText, dummy, textOne + 0x28);
if (textTwo > 0)
{
textTwoSize = BitConverter.ToUInt32(buf, textTwo + 8);
textTwoAddr = BitConverter.ToInt32(buf, textTwo + 12);
sectionTwo = new byte[textTwoSize];
NtReadVirtualMemory(handle, baseAddr + textTwoAddr, sectionTwo, textTwoSize, ref bytesRead);
}
Console.ReadLine();
}
//originally from https://github.com/Wulf2k/ER-Patcher.git
//try and keep in sync with https://github.com/kh0nsu/FromAobScan
public byte[] hs2b(string hex)
{
hex = hex.Replace(" ", "");
hex = hex.Replace("-", "");
hex = hex.Replace(":", "");
byte[] b = new byte[hex.Length >> 1];
for (int i = 0; i <= b.Length - 1; ++i)
{
b[i] = (byte)((hex[i * 2] - (hex[i * 2] < 58 ? 48 : (hex[i * 2] < 97 ? 55 : 87))) * 16 + (hex[i * 2 + 1] - (hex[i * 2 + 1] < 58 ? 48 : (hex[i * 2 + 1] < 97 ? 55 : 87))));
}
return b;
}
public byte[] hs2w(string hex)
{
hex = hex.Replace(" ", "");
hex = hex.Replace("-", "");
hex = hex.Replace(":", "");
byte[] wild = new byte[hex.Length >> 1];
for (int i = 0; i <= wild.Length - 1; ++i)
{
if (hex[i * 2].Equals('?'))
{
wild[i] = 1;
}
}
return wild;
}
public int FindBytes(byte[] buf, byte[] find, byte[] wild, int startIndex = 0, int lastIndex = -1)
{
if (buf == null || find == null || buf.Length == 0 || find.Length == 0 || find.Length > buf.Length) return -1;
if (lastIndex < 1) { lastIndex = buf.Length - find.Length; }
for (int i = startIndex; i < lastIndex + 1; i++)
{
if (buf[i] == find[0])
{
for (int m = 1; m < find.Length; m++)
{
if ((buf[i + m] != find[m]) && (wild[m] != 1)) break;
if (m == find.Length - 1) return i;
}
}
}
return -1;
}
public bool outputConsole = true;
public int findAddr(byte[] buf, int blockVirtualAddr, string find, string desc, int readoffset32 = -1000, int nextInstOffset = -1000, int justOffset = -1000, int startIndex = 0, bool singleMatch = true, Action<int> callback = null)
{//TODO: for single match and non-zero start index, try zero start index if no match is found?
int count = 0;
byte[] fb = hs2b(find);
byte[] fwb = hs2w(find);
int index = startIndex;
int result = -1;
do
{
index = FindBytes(buf, fb, fwb, index);
if (index != -1)
{
count++;
int rva = index + blockVirtualAddr;
result = rva;
string output = desc + " found at index " + index + " offset hex " + rva.ToString("X2");
if (readoffset32 > -1000)
{
int index32 = index + readoffset32;
var val = BitConverter.ToInt32(buf, index32);
result = val;
output += " raw val " + val.ToString("X2");
if (nextInstOffset > -1000)
{
int next = blockVirtualAddr + index + nextInstOffset + val;
result = next;
output += " final offset " + next.ToString("X2");
}
}
if (justOffset > -1000)
{
result = rva + justOffset;
output += " with offset " + (rva + justOffset).ToString("X2");
}
if (outputConsole) { Console.WriteLine(output); }
index += fb.Length; //keep searching in case there's multiple.
}
if (index != -1 && callback != null) { callback(result); }
}
while (index != -1 && !singleMatch);
if (0 == count) { Console.WriteLine("Nothing found for " + desc); }
return result;
}
public void Dispose()
{
sectionOne = null;
sectionTwo = null;
}
}
public class FileUtils
{
public static List<string[]> importGenericTextResource(string name, char separator = '\t')
{
var ret = new List<string[]>();
try
{
var assembly = Assembly.GetExecutingAssembly();
string resourceName = assembly.GetManifestResourceNames().Single(str => str.EndsWith(name));
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
var spl = line.Split(separator);
if (spl.Length < 1) { continue; }
ret.Add(spl);
}
}
return ret;
}
catch
{
return ret;
}
}
}
public class StringWrap
{
public string DisplayStr { get; set; } = "";
public object o = null;
public override string ToString() { return DisplayStr; }
}
}