-
Notifications
You must be signed in to change notification settings - Fork 487
Expand file tree
/
Copy pathModuleScope.cs
More file actions
566 lines (510 loc) · 21.5 KB
/
ModuleScope.cs
File metadata and controls
566 lines (510 loc) · 21.5 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// Copyright 2004-2021 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#nullable enable
namespace Castle.DynamicProxy
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Threading;
using Castle.Core.Internal;
using Castle.DynamicProxy.Generators;
#if FEATURE_SERIALIZATION
using Castle.DynamicProxy.Serialization;
#endif
public class ModuleScope
{
/// <summary>
/// The default file name used when the assembly is saved using <see cref = "DEFAULT_FILE_NAME" />.
/// </summary>
public static readonly string DEFAULT_FILE_NAME = "CastleDynProxy2.dll";
/// <summary>
/// The default assembly (simple) name used for the assemblies generated by a <see cref = "ModuleScope" /> instance.
/// </summary>
public static readonly string DEFAULT_ASSEMBLY_NAME = "DynamicProxyGenAssembly2";
private ModuleBuilder? moduleBuilderWithStrongName;
private ModuleBuilder? moduleBuilder;
// The names to use for the generated assemblies and the paths (including the names) of their manifest modules
private readonly string strongAssemblyName;
private readonly string weakAssemblyName;
private readonly string strongModulePath;
private readonly string weakModulePath;
// Keeps track of generated types
private readonly SynchronizedDictionary<CacheKey, Type> typeCache = new SynchronizedDictionary<CacheKey, Type>();
// Used to lock the module builder creation
private readonly object moduleLocker = new object();
// Specified whether the generated assemblies are intended to be saved
private readonly AssemblyBuilderAccess assemblyBuilderAccess;
private readonly bool disableSignedModule;
private readonly INamingScope namingScope;
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class; assemblies created by this instance will not be saved.
/// </summary>
public ModuleScope() : this(false, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
/// should be saved.
/// </summary>
/// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
public ModuleScope(bool savePhysicalAssembly)
: this(savePhysicalAssembly, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModuleScope" /> class,
/// using the specified <see cref="AssemblyBuilderAccess" /> for generated assemblies.
/// </summary>
/// <param name = "assemblyBuilderAccess">The desired <see cref="AssemblyBuilderAccess" /> to be used for generated assemblies.</param>
internal ModuleScope(AssemblyBuilderAccess assemblyBuilderAccess)
: this(assemblyBuilderAccess, disableSignedModule: false, new NamingScope(), DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME, DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
/// should be saved.
/// </summary>
/// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
/// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule)
: this(
savePhysicalAssembly, disableSignedModule, DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME, DEFAULT_ASSEMBLY_NAME,
DEFAULT_FILE_NAME)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
/// should be saved and what simple names are to be assigned to them.
/// </summary>
/// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
/// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
/// <param name = "strongAssemblyName">The simple name of the strong-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
/// <param name = "strongModulePath">The path and file name of the manifest module of the strong-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
/// <param name = "weakAssemblyName">The simple name of the weak-named assembly generated by this <see cref = "ModuleScope" />.</param>
/// <param name = "weakModulePath">The path and file name of the manifest module of the weak-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, string strongAssemblyName,
string strongModulePath,
string weakAssemblyName, string weakModulePath)
: this(
savePhysicalAssembly, disableSignedModule, new NamingScope(), strongAssemblyName, strongModulePath, weakAssemblyName,
weakModulePath)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
/// should be saved and what simple names are to be assigned to them.
/// </summary>
/// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
/// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
/// <param name = "namingScope">Naming scope used to provide unique names to generated types and their members (usually via sub-scopes).</param>
/// <param name = "strongAssemblyName">The simple name of the strong-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
/// <param name = "strongModulePath">The path and file name of the manifest module of the strong-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
/// <param name = "weakAssemblyName">The simple name of the weak-named assembly generated by this <see cref = "ModuleScope" />.</param>
/// <param name = "weakModulePath">The path and file name of the manifest module of the weak-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
internal ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, INamingScope namingScope,
string strongAssemblyName, string strongModulePath,
string weakAssemblyName, string weakModulePath)
: this(
#if FEATURE_ASSEMBLYBUILDER_SAVE
assemblyBuilderAccess: savePhysicalAssembly ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run,
#else
assemblyBuilderAccess: AssemblyBuilderAccess.Run,
#endif
disableSignedModule, namingScope, strongAssemblyName, strongModulePath, weakAssemblyName, weakModulePath)
{
}
internal ModuleScope(AssemblyBuilderAccess assemblyBuilderAccess, bool disableSignedModule, INamingScope namingScope,
string strongAssemblyName, string strongModulePath,
string weakAssemblyName, string weakModulePath)
{
this.assemblyBuilderAccess = assemblyBuilderAccess;
this.disableSignedModule = disableSignedModule;
this.namingScope = namingScope;
this.strongAssemblyName = strongAssemblyName;
this.strongModulePath = strongModulePath;
this.weakAssemblyName = weakAssemblyName;
this.weakModulePath = weakModulePath;
}
internal INamingScope NamingScope
{
get { return namingScope; }
}
internal SynchronizedDictionary<CacheKey, Type> TypeCache => typeCache;
/// <summary>
/// Gets the key pair used to sign the strong-named assembly generated by this <see cref = "ModuleScope" />.
/// </summary>
public static byte[] GetKeyPair()
{
using (var stream = typeof(ModuleScope).Assembly.GetManifestResourceStream("Castle.DynamicProxy.DynProxy.snk"))
{
if (stream == null)
{
throw new MissingManifestResourceException(
"Should have a Castle.DynamicProxy.DynProxy.snk as an embedded resource, so Dynamic Proxy could sign generated assembly");
}
var length = (int)stream.Length;
var keyPair = new byte[length];
stream.Read(keyPair, 0, length);
return keyPair;
}
}
/// <summary>
/// Gets the strong-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.
/// </summary>
/// <value>The strong-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.</value>
internal ModuleBuilder? StrongNamedModule
{
get { return moduleBuilderWithStrongName; }
}
/// <summary>
/// Gets the file name of the strongly named module generated by this scope.
/// </summary>
/// <value>The file name of the strongly named module generated by this scope.</value>
public string StrongNamedModuleName
{
get { return Path.GetFileName(strongModulePath); }
}
#if FEATURE_ASSEMBLYBUILDER_SAVE
/// <summary>
/// Gets the directory where the strongly named module generated by this scope will be saved, or <see langword = "null" /> if the current directory
/// is used.
/// </summary>
/// <value>The directory where the strongly named module generated by this scope will be saved when <see
/// cref = "SaveAssembly()" /> is called
/// (if this scope was created to save modules).</value>
public string? StrongNamedModuleDirectory
{
get
{
var directory = Path.GetDirectoryName(strongModulePath);
if (string.IsNullOrEmpty(directory))
{
return null;
}
return directory;
}
}
#endif
/// <summary>
/// Gets the weak-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.
/// </summary>
/// <value>The weak-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.</value>
internal ModuleBuilder? WeakNamedModule
{
get { return moduleBuilder; }
}
/// <summary>
/// Gets the file name of the weakly named module generated by this scope.
/// </summary>
/// <value>The file name of the weakly named module generated by this scope.</value>
public string WeakNamedModuleName
{
get { return Path.GetFileName(weakModulePath); }
}
#if FEATURE_ASSEMBLYBUILDER_SAVE
/// <summary>
/// Gets the directory where the weakly named module generated by this scope will be saved, or <see langword = "null" /> if the current directory
/// is used.
/// </summary>
/// <value>The directory where the weakly named module generated by this scope will be saved when <see
/// cref = "SaveAssembly()" /> is called
/// (if this scope was created to save modules).</value>
public string? WeakNamedModuleDirectory
{
get
{
var directory = Path.GetDirectoryName(weakModulePath);
if (directory == string.Empty)
{
return null;
}
return directory;
}
}
#endif
/// <summary>
/// Gets the specified module generated by this scope, creating a new one if none has yet been generated.
/// </summary>
/// <param name = "isStrongNamed">If set to true, a strong-named module is returned; otherwise, a weak-named module is returned.</param>
/// <returns>A strong-named or weak-named module generated by this scope, as specified by the <paramref
/// name = "isStrongNamed" /> parameter.</returns>
internal ModuleBuilder ObtainDynamicModule(bool isStrongNamed)
{
if (isStrongNamed)
{
return ObtainDynamicModuleWithStrongName();
}
return ObtainDynamicModuleWithWeakName();
}
/// <summary>
/// Gets the strong-named module generated by this scope, creating a new one if none has yet been generated.
/// </summary>
/// <returns>A strong-named module generated by this scope.</returns>
[MemberNotNull(nameof(moduleBuilderWithStrongName))]
internal ModuleBuilder ObtainDynamicModuleWithStrongName()
{
if (disableSignedModule)
{
throw new InvalidOperationException(
"Usage of signed module has been disabled. Use unsigned module or enable signed module.");
}
lock (moduleLocker)
{
if (moduleBuilderWithStrongName == null)
{
moduleBuilderWithStrongName = CreateModule(true);
}
return moduleBuilderWithStrongName;
}
}
/// <summary>
/// Gets the weak-named module generated by this scope, creating a new one if none has yet been generated.
/// </summary>
/// <returns>A weak-named module generated by this scope.</returns>
[MemberNotNull(nameof(moduleBuilder))]
internal ModuleBuilder ObtainDynamicModuleWithWeakName()
{
lock (moduleLocker)
{
if (moduleBuilder == null)
{
moduleBuilder = CreateModule(false);
}
return moduleBuilder;
}
}
private ModuleBuilder CreateModule(bool signStrongName)
{
var assemblyName = GetAssemblyName(signStrongName);
var moduleName = signStrongName ? StrongNamedModuleName : WeakNamedModuleName;
#if FEATURE_APPDOMAIN && FEATURE_ASSEMBLYBUILDER_SAVE
if ((assemblyBuilderAccess & AssemblyBuilderAccess.Save) != 0)
{
AssemblyBuilder assemblyBuilder;
try
{
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
assemblyName, assemblyBuilderAccess, signStrongName ? StrongNamedModuleDirectory : WeakNamedModuleDirectory);
}
catch (ArgumentException e)
{
if (signStrongName == false && e.StackTrace.Contains("ComputePublicKey") == false)
{
// I have no idea what that could be
throw;
}
var message = string.Format(
"There was an error creating dynamic assembly for your proxies - you don't have permissions " +
"required to sign the assembly. To workaround it you can enforce generating non-signed assembly " +
"only when creating {0}. Alternatively ensure that your account has all the required permissions.",
GetType());
throw new ArgumentException(message, e);
}
var module = assemblyBuilder.DefineDynamicModule(moduleName, moduleName, false);
return module;
}
else
#endif
{
#if FEATURE_APPDOMAIN
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, assemblyBuilderAccess);
#else
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, assemblyBuilderAccess);
#endif
var module = assemblyBuilder.DefineDynamicModule(moduleName);
return module;
}
}
private AssemblyName GetAssemblyName(bool signStrongName)
{
var assemblyName = new AssemblyName {
Name = signStrongName ? strongAssemblyName : weakAssemblyName
};
if (signStrongName)
{
#if FEATURE_ASSEMBLYBUILDER_SAVE
assemblyName.KeyPair = new StrongNameKeyPair(GetKeyPair());
#else
assemblyName.SetPublicKey(InternalsVisible.DynamicProxyGenAssembly2PublicKey);
#endif
}
return assemblyName;
}
#if FEATURE_ASSEMBLYBUILDER_SAVE
/// <summary>
/// Saves the generated assembly with the name and directory information given when this <see cref = "ModuleScope" /> instance was created (or with
/// the <see cref = "DEFAULT_FILE_NAME" /> and current directory if none was given).
/// </summary>
/// <remarks>
/// <para>
/// This method stores the generated assembly in the directory passed as part of the module information specified when this instance was
/// constructed (if any, else the current directory is used). If both a strong-named and a weak-named assembly
/// have been generated, it will throw an exception; in this case, use the <see cref = "SaveAssembly (bool)" /> overload.
/// </para>
/// <para>
/// If this <see cref = "ModuleScope" /> was created without indicating that the assembly should be saved, this method does nothing.
/// </para>
/// </remarks>
/// <exception cref = "InvalidOperationException">Both a strong-named and a weak-named assembly have been generated.</exception>
/// <returns>The path of the generated assembly file, or null if no file has been generated.</returns>
public string? SaveAssembly()
{
if ((assemblyBuilderAccess & AssemblyBuilderAccess.Save) == 0)
{
return null;
}
if (StrongNamedModule != null && WeakNamedModule != null)
{
throw new InvalidOperationException("Both a strong-named and a weak-named assembly have been generated.");
}
if (StrongNamedModule != null)
{
return SaveAssembly(true);
}
if (WeakNamedModule != null)
{
return SaveAssembly(false);
}
return null;
}
/// <summary>
/// Saves the specified generated assembly with the name and directory information given when this <see
/// cref = "ModuleScope" /> instance was created
/// (or with the <see cref = "DEFAULT_FILE_NAME" /> and current directory if none was given).
/// </summary>
/// <param name = "strongNamed">True if the generated assembly with a strong name should be saved (see <see
/// cref = "StrongNamedModule" />);
/// false if the generated assembly without a strong name should be saved (see <see cref = "WeakNamedModule" />.</param>
/// <remarks>
/// <para>
/// This method stores the specified generated assembly in the directory passed as part of the module information specified when this instance was
/// constructed (if any, else the current directory is used).
/// </para>
/// <para>
/// If this <see cref = "ModuleScope" /> was created without indicating that the assembly should be saved, this method does nothing.
/// </para>
/// </remarks>
/// <exception cref = "InvalidOperationException">No assembly has been generated that matches the <paramref
/// name = "strongNamed" /> parameter.
/// </exception>
/// <returns>The path of the generated assembly file, or null if no file has been generated.</returns>
public string? SaveAssembly(bool strongNamed)
{
if ((assemblyBuilderAccess & AssemblyBuilderAccess.Save) == 0)
{
return null;
}
AssemblyBuilder assemblyBuilder;
string assemblyFileName;
string assemblyFilePath;
if (strongNamed)
{
if (StrongNamedModule == null)
{
throw new InvalidOperationException("No strong-named assembly has been generated.");
}
assemblyBuilder = (AssemblyBuilder)StrongNamedModule.Assembly;
assemblyFileName = StrongNamedModuleName;
assemblyFilePath = StrongNamedModule.FullyQualifiedName;
}
else
{
if (WeakNamedModule == null)
{
throw new InvalidOperationException("No weak-named assembly has been generated.");
}
assemblyBuilder = (AssemblyBuilder)WeakNamedModule.Assembly;
assemblyFileName = WeakNamedModuleName;
assemblyFilePath = WeakNamedModule.FullyQualifiedName;
}
if (File.Exists(assemblyFilePath))
{
File.Delete(assemblyFilePath);
}
#if FEATURE_SERIALIZATION
AddCacheMappings(assemblyBuilder);
#endif
assemblyBuilder.Save(assemblyFileName);
return assemblyFilePath;
}
#endif
#if FEATURE_SERIALIZATION
private void AddCacheMappings(AssemblyBuilder builder)
{
var mappings = new Dictionary<CacheKey, string>();
typeCache.ForEach((key, value) =>
{
// NOTE: using == returns invalid results.
// we need to use Equals here for it to work properly
if (builder.Equals(value.Assembly))
{
mappings.Add(key, value.FullName);
}
});
CacheMappingsAttribute.ApplyTo(builder, mappings);
}
/// <summary>
/// Loads the generated types from the given assembly into this <see cref = "ModuleScope" />'s cache.
/// </summary>
/// <param name = "assembly">The assembly to load types from. This assembly must have been saved via <see
/// cref = "SaveAssembly(bool)" /> or
/// <see cref = "SaveAssembly()" />, or it must have the <see cref = "CacheMappingsAttribute" /> manually applied.</param>
/// <remarks>
/// This method can be used to load previously generated and persisted proxy types from disk into this scope's type cache, e.g. in order
/// to avoid the performance hit associated with proxy generation.
/// </remarks>
public void LoadAssemblyIntoCache(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
var cacheMappings =
(CacheMappingsAttribute[])assembly.GetCustomAttributes(typeof(CacheMappingsAttribute), false);
if (cacheMappings.Length == 0)
{
var message = string.Format(
"The given assembly '{0}' does not contain any cache information for generated types.",
assembly.FullName);
throw new ArgumentException(message, nameof(assembly));
}
foreach (var mapping in cacheMappings[0].GetDeserializedMappings())
{
var loadedType = assembly.GetType(mapping.Value);
if (loadedType != null)
{
typeCache.AddOrUpdateWithoutTakingLock(mapping.Key, loadedType);
}
}
}
#endif
internal TypeBuilder DefineType(bool inSignedModulePreferably, string name, TypeAttributes flags)
{
var module = ObtainDynamicModule(disableSignedModule == false && inSignedModulePreferably);
return module.DefineType(name, flags);
}
}
}