-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Assembly.cs
396 lines (325 loc) · 19.2 KB
/
Assembly.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Configuration.Assemblies;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Security;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
namespace System.Reflection
{
public abstract partial class Assembly : ICustomAttributeProvider, ISerializable
{
private static readonly Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>();
private static readonly List<string> s_loadFromAssemblyList = new List<string>();
private static bool s_loadFromHandlerSet;
private static int s_cachedSerializationSwitch;
protected Assembly() { }
public virtual IEnumerable<TypeInfo> DefinedTypes
{
[RequiresUnreferencedCode("Types might be removed")]
get
{
Type[] types = GetTypes();
TypeInfo[] typeinfos = new TypeInfo[types.Length];
for (int i = 0; i < types.Length; i++)
{
TypeInfo typeinfo = types[i].GetTypeInfo();
if (typeinfo == null)
throw new NotSupportedException(SR.Format(SR.NotSupported_NoTypeInfo, types[i].FullName));
typeinfos[i] = typeinfo;
}
return typeinfos;
}
}
[RequiresUnreferencedCode("Types might be removed")]
public virtual Type[] GetTypes()
{
Module[] m = GetModules(false);
if (m.Length == 1)
{
return m[0].GetTypes();
}
int finalLength = 0;
Type[][] moduleTypes = new Type[m.Length][];
for (int i = 0; i < moduleTypes.Length; i++)
{
moduleTypes[i] = m[i].GetTypes();
finalLength += moduleTypes[i].Length;
}
int current = 0;
Type[] ret = new Type[finalLength];
for (int i = 0; i < moduleTypes.Length; i++)
{
int length = moduleTypes[i].Length;
Array.Copy(moduleTypes[i], 0, ret, current, length);
current += length;
}
return ret;
}
public virtual IEnumerable<Type> ExportedTypes
{
[RequiresUnreferencedCode("Types might be removed")]
get => GetExportedTypes();
}
[RequiresUnreferencedCode("Types might be removed")]
public virtual Type[] GetExportedTypes() { throw NotImplemented.ByDesign; }
[RequiresUnreferencedCode("Types might be removed")]
public virtual Type[] GetForwardedTypes() { throw NotImplemented.ByDesign; }
internal const string ThrowingMessageInRAF = "This member throws an exception for assemblies embedded in a single-file app";
[RequiresAssemblyFiles(ThrowingMessageInRAF)]
public virtual string? CodeBase => throw NotImplemented.ByDesign;
public virtual MethodInfo? EntryPoint => throw NotImplemented.ByDesign;
public virtual string? FullName => throw NotImplemented.ByDesign;
public virtual string ImageRuntimeVersion => throw NotImplemented.ByDesign;
public virtual bool IsDynamic => false;
public virtual string Location => throw NotImplemented.ByDesign;
public virtual bool ReflectionOnly => throw NotImplemented.ByDesign;
public virtual bool IsCollectible => true;
public virtual ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { throw NotImplemented.ByDesign; }
public virtual string[] GetManifestResourceNames() { throw NotImplemented.ByDesign; }
public virtual Stream? GetManifestResourceStream(string name) { throw NotImplemented.ByDesign; }
public virtual Stream? GetManifestResourceStream(Type type, string name) { throw NotImplemented.ByDesign; }
public bool IsFullyTrusted => true;
public virtual AssemblyName GetName() => GetName(copiedName: false);
public virtual AssemblyName GetName(bool copiedName) { throw NotImplemented.ByDesign; }
[RequiresUnreferencedCode("Types might be removed")]
public virtual Type? GetType(string name) => GetType(name, throwOnError: false, ignoreCase: false);
[RequiresUnreferencedCode("Types might be removed")]
public virtual Type? GetType(string name, bool throwOnError) => GetType(name, throwOnError: throwOnError, ignoreCase: false);
[RequiresUnreferencedCode("Types might be removed")]
public virtual Type? GetType(string name, bool throwOnError, bool ignoreCase) { throw NotImplemented.ByDesign; }
public virtual bool IsDefined(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; }
public virtual IEnumerable<CustomAttributeData> CustomAttributes => GetCustomAttributesData();
public virtual IList<CustomAttributeData> GetCustomAttributesData() { throw NotImplemented.ByDesign; }
public virtual object[] GetCustomAttributes(bool inherit) { throw NotImplemented.ByDesign; }
public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; }
[RequiresAssemblyFiles(ThrowingMessageInRAF)]
public virtual string EscapedCodeBase => AssemblyName.EscapeCodeBase(CodeBase);
[RequiresUnreferencedCode("Assembly.CreateInstance is not supported with trimming. Use Type.GetType instead.")]
public object? CreateInstance(string typeName) => CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null);
[RequiresUnreferencedCode("Assembly.CreateInstance is not supported with trimming. Use Type.GetType instead.")]
public object? CreateInstance(string typeName, bool ignoreCase) => CreateInstance(typeName, ignoreCase, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null);
[RequiresUnreferencedCode("Assembly.CreateInstance is not supported with trimming. Use Type.GetType instead.")]
public virtual object? CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object[]? args, CultureInfo? culture, object[]? activationAttributes)
{
Type? t = GetType(typeName, throwOnError: false, ignoreCase: ignoreCase);
if (t == null)
return null;
return Activator.CreateInstance(t, bindingAttr, binder, args, culture, activationAttributes);
}
public virtual event ModuleResolveEventHandler? ModuleResolve { add { throw NotImplemented.ByDesign; } remove { throw NotImplemented.ByDesign; } }
public virtual Module ManifestModule => throw NotImplemented.ByDesign;
public virtual Module? GetModule(string name) { throw NotImplemented.ByDesign; }
public Module[] GetModules() => GetModules(getResourceModules: false);
public virtual Module[] GetModules(bool getResourceModules) { throw NotImplemented.ByDesign; }
public virtual IEnumerable<Module> Modules => GetLoadedModules(getResourceModules: true);
public Module[] GetLoadedModules() => GetLoadedModules(getResourceModules: false);
public virtual Module[] GetLoadedModules(bool getResourceModules) { throw NotImplemented.ByDesign; }
[RequiresUnreferencedCode("Assembly references might be removed")]
public virtual AssemblyName[] GetReferencedAssemblies() { throw NotImplemented.ByDesign; }
public virtual Assembly GetSatelliteAssembly(CultureInfo culture) { throw NotImplemented.ByDesign; }
public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version? version) { throw NotImplemented.ByDesign; }
[RequiresAssemblyFiles(ThrowingMessageInRAF)]
public virtual FileStream? GetFile(string name) { throw NotImplemented.ByDesign; }
[RequiresAssemblyFiles(ThrowingMessageInRAF)]
public virtual FileStream[] GetFiles() => GetFiles(getResourceModules: false);
[RequiresAssemblyFiles(ThrowingMessageInRAF)]
public virtual FileStream[] GetFiles(bool getResourceModules) { throw NotImplemented.ByDesign; }
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; }
public override string ToString()
{
return FullName ?? base.ToString()!;
}
/*
Returns true if the assembly was loaded from the global assembly cache.
*/
[Obsolete(Obsoletions.GlobalAssemblyCacheMessage, DiagnosticId = Obsoletions.GlobalAssemblyCacheDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public virtual bool GlobalAssemblyCache => throw NotImplemented.ByDesign;
public virtual long HostContext => throw NotImplemented.ByDesign;
public override bool Equals(object? o) => base.Equals(o);
public override int GetHashCode() => base.GetHashCode();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Assembly? left, Assembly? right)
{
// Test "right" first to allow branch elimination when inlined for null checks (== null)
// so it can become a simple test
if (right is null)
{
// return true/false not the test result https://github.com/dotnet/runtime/issues/4207
return (left is null) ? true : false;
}
// Try fast reference equality and opposite null check prior to calling the slower virtual Equals
if ((object?)left == (object)right)
{
return true;
}
return (left is null) ? false : left.Equals(right);
}
public static bool operator !=(Assembly? left, Assembly? right) => !(left == right);
public static string CreateQualifiedName(string? assemblyName, string? typeName) => typeName + ", " + assemblyName;
public static Assembly? GetAssembly(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
Module m = type.Module;
if (m == null)
return null;
else
return m.Assembly;
}
// internal test hook
private static bool s_forceNullEntryPoint;
public static Assembly? GetEntryAssembly()
{
if (s_forceNullEntryPoint)
return null;
return GetEntryAssemblyInternal();
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly Load(byte[] rawAssembly) => Load(rawAssembly, rawSymbolStore: null);
// Loads the assembly with a COFF based IMAGE containing
// an emitted assembly. The assembly is loaded into a fully isolated ALC with resolution fully deferred to the AssemblyLoadContext.Default.
// The second parameter is the raw bytes representing the symbol store that matches the assembly.
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore)
{
if (rawAssembly == null)
throw new ArgumentNullException(nameof(rawAssembly));
if (rawAssembly.Length == 0)
throw new BadImageFormatException(SR.BadImageFormat_BadILFormat);
SerializationInfo.ThrowIfDeserializationInProgress("AllowAssembliesFromByteArrays",
ref s_cachedSerializationSwitch);
AssemblyLoadContext alc = new IndividualAssemblyLoadContext("Assembly.Load(byte[], ...)");
return alc.InternalLoad(rawAssembly, rawSymbolStore);
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly LoadFile(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (PathInternal.IsPartiallyQualified(path))
{
throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, path), nameof(path));
}
string normalizedPath = Path.GetFullPath(path);
Assembly? result;
lock (s_loadfile)
{
if (s_loadfile.TryGetValue(normalizedPath, out result))
return result;
AssemblyLoadContext alc = new IndividualAssemblyLoadContext($"Assembly.LoadFile({normalizedPath})");
result = alc.LoadFromAssemblyPath(normalizedPath);
s_loadfile.Add(normalizedPath, result);
}
return result;
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
[UnconditionalSuppressMessage("SingleFile", "IL3000:Avoid accessing Assembly file path when publishing as a single file",
Justification = "The assembly is loaded by specifying a path outside of the single-file bundle, the location of the path will not be empty if the path exist, otherwise it will be handled as null")]
private static Assembly? LoadFromResolveHandler(object? sender, ResolveEventArgs args)
{
Assembly? requestingAssembly = args.RequestingAssembly;
if (requestingAssembly == null)
{
return null;
}
// Requesting assembly for LoadFrom is always loaded in defaultContext - proceed only if that
// is the case.
if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly))
return null;
// Get the path where requesting assembly lives and check if it is in the list
// of assemblies for which LoadFrom was invoked.
string requestorPath = Path.GetFullPath(requestingAssembly.Location);
if (string.IsNullOrEmpty(requestorPath))
return null;
lock (s_loadFromAssemblyList)
{
// If the requestor assembly was not loaded using LoadFrom, exit.
if (!s_loadFromAssemblyList.Contains(requestorPath))
{
#if CORECLR
if (AssemblyLoadContext.IsTracingEnabled())
{
AssemblyLoadContext.TraceAssemblyLoadFromResolveHandlerInvoked(args.Name, false, requestorPath, null);
}
#endif // CORECLR
return null;
}
}
// Requestor assembly was loaded using loadFrom, so look for its dependencies
// in the same folder as it.
// Form the name of the assembly using the path of the assembly that requested its load.
AssemblyName requestedAssemblyName = new AssemblyName(args.Name!);
string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath)!, requestedAssemblyName.Name + ".dll");
#if CORECLR
if (AssemblyLoadContext.IsTracingEnabled())
{
AssemblyLoadContext.TraceAssemblyLoadFromResolveHandlerInvoked(args.Name, true, requestorPath, requestedAssemblyPath);
}
#endif // CORECLR
try
{
// Load the dependency via LoadFrom so that it goes through the same path of being in the LoadFrom list.
return Assembly.LoadFrom(requestedAssemblyPath);
}
catch (FileNotFoundException)
{
// Catch FileNotFoundException when attempting to resolve assemblies via this handler to account for missing assemblies.
return null;
}
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly LoadFrom(string assemblyFile)
{
if (assemblyFile == null)
throw new ArgumentNullException(nameof(assemblyFile));
string fullPath = Path.GetFullPath(assemblyFile);
if (!s_loadFromHandlerSet)
{
lock (s_loadFromAssemblyList)
{
if (!s_loadFromHandlerSet)
{
AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler!;
s_loadFromHandlerSet = true;
}
}
}
// Add the path to the LoadFrom path list which we will consult
// before handling the resolves in our handler.
lock (s_loadFromAssemblyList)
{
if (!s_loadFromAssemblyList.Contains(fullPath))
{
s_loadFromAssemblyList.Add(fullPath);
}
}
return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly LoadFrom(string assemblyFile, byte[]? hashValue, AssemblyHashAlgorithm hashAlgorithm)
{
throw new NotSupportedException(SR.NotSupported_AssemblyLoadFromHash);
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly UnsafeLoadFrom(string assemblyFile) => LoadFrom(assemblyFile);
[RequiresUnreferencedCode("Types and members the loaded module depends on might be removed")]
public Module LoadModule(string moduleName, byte[]? rawModule) => LoadModule(moduleName, rawModule, null);
[RequiresUnreferencedCode("Types and members the loaded module depends on might be removed")]
public virtual Module LoadModule(string moduleName, byte[]? rawModule, byte[]? rawSymbolStore) { throw NotImplemented.ByDesign; }
[Obsolete(Obsoletions.ReflectionOnlyLoadingMessage, DiagnosticId = Obsoletions.ReflectionOnlyLoadingDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly ReflectionOnlyLoad(byte[] rawAssembly) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); }
[Obsolete(Obsoletions.ReflectionOnlyLoadingMessage, DiagnosticId = Obsoletions.ReflectionOnlyLoadingDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly ReflectionOnlyLoad(string assemblyString) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); }
[Obsolete(Obsoletions.ReflectionOnlyLoadingMessage, DiagnosticId = Obsoletions.ReflectionOnlyLoadingDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public static Assembly ReflectionOnlyLoadFrom(string assemblyFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); }
public virtual SecurityRuleSet SecurityRuleSet => SecurityRuleSet.None;
}
}