-
-
Notifications
You must be signed in to change notification settings - Fork 274
/
Common.cs
307 lines (266 loc) · 10.1 KB
/
Common.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
// ReSharper disable CommentTypo
internal static class Common
{
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hReservedNull, uint dwFlags);
[Conditional("DEBUG")]
public static void Log(string format, params object[] args)
{
// Should this be trace?
Debug.WriteLine("=== COSTURA === " + string.Format(format, args));
}
static void CopyTo(Stream source, Stream destination)
{
var array = new byte[81920];
int count;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
destination.Write(array, 0, count);
}
}
static void CreateDirectory(string tempBasePath)
{
if (!Directory.Exists(tempBasePath))
{
Directory.CreateDirectory(tempBasePath);
}
}
static byte[] ReadStream(Stream stream)
{
var data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
return data;
}
public static string CalculateChecksum(string filename)
{
using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
using (var bs = new BufferedStream(fs))
using (var sha1 = new SHA1CryptoServiceProvider())
{
var hash = sha1.ComputeHash(bs);
var formatted = new StringBuilder(2 * hash.Length);
foreach (var b in hash)
{
formatted.AppendFormat("{0:X2}", b);
}
return formatted.ToString();
}
}
public static Assembly ReadExistingAssembly(AssemblyName name)
{
var currentDomain = AppDomain.CurrentDomain;
var assemblies = currentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var currentName = assembly.GetName();
if (string.Equals(currentName.Name, name.Name, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(CultureToString(currentName.CultureInfo), CultureToString(name.CultureInfo), StringComparison.InvariantCultureIgnoreCase))
{
Log("Assembly '{0}' already loaded, returning existing assembly", assembly.FullName);
return assembly;
}
}
return null;
}
static string CultureToString(CultureInfo culture)
{
if (culture is null)
{
return "";
}
return culture.Name;
}
public static Assembly ReadFromDiskCache(string tempBasePath, AssemblyName requestedAssemblyName)
{
var name = requestedAssemblyName.Name.ToLowerInvariant();
if (requestedAssemblyName.CultureInfo is not null && !string.IsNullOrEmpty(requestedAssemblyName.CultureInfo.Name))
{
name = $"{requestedAssemblyName.CultureInfo.Name}.{name}";
}
var bittyness = IntPtr.Size == 8 ? "64" : "32";
var assemblyTempFilePath = Path.Combine(tempBasePath, string.Concat(name, ".dll"));
if (File.Exists(assemblyTempFilePath))
{
return Assembly.LoadFile(assemblyTempFilePath);
}
assemblyTempFilePath = Path.ChangeExtension(assemblyTempFilePath, "exe");
if (File.Exists(assemblyTempFilePath))
{
return Assembly.LoadFile(assemblyTempFilePath);
}
assemblyTempFilePath = Path.Combine(Path.Combine(tempBasePath, bittyness), string.Concat(name, ".dll"));
if (File.Exists(assemblyTempFilePath))
{
return Assembly.LoadFile(assemblyTempFilePath);
}
assemblyTempFilePath = Path.ChangeExtension(assemblyTempFilePath, "exe");
if (File.Exists(assemblyTempFilePath))
{
return Assembly.LoadFile(assemblyTempFilePath);
}
return null;
}
public static Assembly ReadFromEmbeddedResources(Dictionary<string, string> assemblyNames, Dictionary<string, string> symbolNames, AssemblyName requestedAssemblyName)
{
var name = requestedAssemblyName.Name.ToLowerInvariant();
if (requestedAssemblyName.CultureInfo is not null && !string.IsNullOrEmpty(requestedAssemblyName.CultureInfo.Name))
{
name = $"{requestedAssemblyName.CultureInfo.Name}.{name}";
}
byte[] assemblyData;
using (var assemblyStream = LoadStream(assemblyNames, name))
{
if (assemblyStream is null)
{
return null;
}
assemblyData = ReadStream(assemblyStream);
}
using (var pdbStream = LoadStream(symbolNames, name))
{
if (pdbStream is not null)
{
var pdbData = ReadStream(pdbStream);
return Assembly.Load(assemblyData, pdbData);
}
}
return Assembly.Load(assemblyData);
}
static Stream LoadStream(Dictionary<string, string> resourceNames, string name)
{
if (resourceNames.TryGetValue(name, out var value))
{
return LoadStream(value);
}
return null;
}
static Stream LoadStream(string fullName)
{
var executingAssembly = Assembly.GetExecutingAssembly();
if (fullName.EndsWith(".compressed"))
{
using (var stream = executingAssembly.GetManifestResourceStream(fullName))
using (var compressStream = new DeflateStream(stream, CompressionMode.Decompress))
{
var memStream = new MemoryStream();
CopyTo(compressStream, memStream);
memStream.Position = 0;
return memStream;
}
}
return executingAssembly.GetManifestResourceStream(fullName);
}
public static void PreloadUnmanagedLibraries(string hash, string tempBasePath, List<string> libs, Dictionary<string, string> checksums)
{
// since tempBasePath is per user, the mutex can be per user
var mutexId = $"Costura{hash}";
using (var mutex = new Mutex(false, mutexId))
{
var hasHandle = false;
try
{
try
{
hasHandle = mutex.WaitOne(60000, false);
if (hasHandle == false)
{
throw new TimeoutException("Timeout waiting for exclusive access");
}
}
catch (AbandonedMutexException)
{
hasHandle = true;
}
var bittyness = IntPtr.Size == 8 ? "64" : "32";
CreateDirectory(Path.Combine(tempBasePath, bittyness));
InternalPreloadUnmanagedLibraries(tempBasePath, libs, checksums);
}
finally
{
if (hasHandle)
{
mutex.ReleaseMutex();
}
}
}
}
static void InternalPreloadUnmanagedLibraries(string tempBasePath, IList<string> libs, Dictionary<string, string> checksums)
{
string name;
foreach (var lib in libs)
{
name = ResourceNameToPath(lib);
var assemblyTempFilePath = Path.Combine(tempBasePath, name);
if (File.Exists(assemblyTempFilePath))
{
var checksum = CalculateChecksum(assemblyTempFilePath);
if (checksum != checksums[lib])
{
File.Delete(assemblyTempFilePath);
}
}
if (!File.Exists(assemblyTempFilePath))
{
using (var copyStream = LoadStream(lib))
using (var assemblyTempFile = File.OpenWrite(assemblyTempFilePath))
{
CopyTo(copyStream, assemblyTempFile);
}
}
}
// prevent system-generated error message when LoadLibrary is called on a dll with an unmet dependency
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621(v=vs.85).aspx
//
// SEM_FAILCRITICALERRORS - The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
// SEM_NOGPFAULTERRORBOX - The system does not display the Windows Error Reporting dialog.
// SEM_NOOPENFILEERRORBOX - The OpenFile function does not display a message box when it fails to find a file. Instead, the error is returned to the caller.
//
// return value is the previous state of the error-mode bit flags.
// ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX;
uint errorModes = 32771;
var originalErrorMode = SetErrorMode(errorModes);
foreach (var lib in libs)
{
name = ResourceNameToPath(lib);
if (name.EndsWith(".dll"))
{
var assemblyTempFilePath = Path.Combine(tempBasePath, name);
// LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008
LoadLibraryEx(assemblyTempFilePath, IntPtr.Zero, 0x00000008);
}
}
// restore to previous state
SetErrorMode(originalErrorMode);
}
[DllImport("kernel32.dll")]
static extern uint SetErrorMode(uint uMode);
static string ResourceNameToPath(string lib)
{
var bittyness = IntPtr.Size == 8 ? "64" : "32";
var name = lib;
if (lib.StartsWith(string.Concat("costura", bittyness, ".")))
{
name = Path.Combine(bittyness, lib.Substring(10));
}
else if (lib.StartsWith("costura."))
{
name = lib.Substring(8);
}
if (name.EndsWith(".compressed"))
{
name = name.Substring(0, name.Length - 11);
}
return name;
}
}