-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
AssemblyBuilder.Mono.cs
402 lines (341 loc) · 14.9 KB
/
AssemblyBuilder.Mono.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
397
398
399
400
401
402
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// System.Reflection.Emit/AssemblyBuilder.cs
//
// Author:
// Paolo Molaro (lupus@ximian.com)
//
// (C) 2001 Ximian, Inc. http://www.ximian.com
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if MONO_FEATURE_SRE
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection.Emit
{
internal sealed class GenericInstanceKey
{
private Type gtd;
internal Type[] args;
private int hash_code;
internal GenericInstanceKey(Type gtd, Type[] args)
{
this.gtd = gtd;
this.args = args;
hash_code = gtd.GetHashCode();
for (int i = 0; i < args.Length; ++i)
hash_code ^= args[i].GetHashCode();
}
private static bool IsBoundedVector(Type type)
{
ArrayType? at = type as ArrayType;
if (at != null)
return at.GetEffectiveRank() == 1;
return type.ToString().EndsWith("[*]", StringComparison.Ordinal); /*Super uggly hack, SR doesn't allow one to query for it */
}
private static bool TypeEquals(Type a, Type b)
{
if (a == b)
return true;
if (a.HasElementType)
{
if (!b.HasElementType)
return false;
if (!TypeEquals(a.GetElementType()!, b.GetElementType()!))
return false;
if (a.IsArray)
{
if (!b.IsArray)
return false;
int rank = a.GetArrayRank();
if (rank != b.GetArrayRank())
return false;
if (rank == 1 && IsBoundedVector(a) != IsBoundedVector(b))
return false;
}
else if (a.IsByRef)
{
if (!b.IsByRef)
return false;
}
else if (a.IsPointer)
{
if (!b.IsPointer)
return false;
}
return true;
}
if (a.IsGenericType)
{
if (!b.IsGenericType)
return false;
if (a.IsGenericParameter)
return a == b;
if (a.IsGenericParameter) //previous test should have caught it
return false;
if (a.IsGenericTypeDefinition)
{
if (!b.IsGenericTypeDefinition)
return false;
}
else
{
if (b.IsGenericTypeDefinition)
return false;
if (!TypeEquals(a.GetGenericTypeDefinition(), b.GetGenericTypeDefinition()))
return false;
Type[] argsA = a.GetGenericArguments();
Type[] argsB = b.GetGenericArguments();
for (int i = 0; i < argsA.Length; ++i)
{
if (!TypeEquals(argsA[i], argsB[i]))
return false;
}
}
}
/*
Now only non-generic, non compound types are left. To properly deal with user
types we would have to call UnderlyingSystemType, but we let them have their
own instantiation as this is MS behavior and mcs (pre C# 4.0, at least) doesn't
depend on proper UT canonicalization.
*/
return a == b;
}
public override bool Equals(object? obj)
{
GenericInstanceKey? other = obj as GenericInstanceKey;
if (other == null)
return false;
if (gtd != other.gtd)
return false;
for (int i = 0; i < args.Length; ++i)
{
Type a = args[i];
Type b = other.args[i];
/*
We must cannonicalize as much as we can. Using equals means that some resulting types
won't have the exact same types as the argument ones.
For example, flyweight types used array, pointer and byref will should this behavior.
MCS seens to be resilient to this problem so hopefully this won't show up.
*/
if (a != b && !a.Equals(b))
return false;
}
return true;
}
public override int GetHashCode()
{
return hash_code;
}
}
[StructLayout(LayoutKind.Sequential)]
public sealed partial class AssemblyBuilder : Assembly
{
//
// AssemblyBuilder inherits from Assembly, but the runtime thinks its layout inherits from RuntimeAssembly
//
#region Sync with RuntimeAssembly.cs and ReflectionAssembly in object-internals.h
internal IntPtr _mono_assembly;
private UIntPtr dynamic_assembly; /* GC-tracked */
private ModuleBuilder[] modules;
private string? name;
private CustomAttributeBuilder[]? cattrs;
private string? version;
private string? culture;
private Module[]? loaded_modules;
private uint access;
#endregion
private AssemblyName aname;
private ModuleBuilder manifest_module;
private bool manifest_module_used;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[DynamicDependency("RuntimeResolve", typeof(ModuleBuilder))]
private static extern void basic_init(AssemblyBuilder ab);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void UpdateNativeCustomAttributes(AssemblyBuilder ab);
[DynamicDependency(nameof(access))] // Automatically keeps all previous fields too due to StructLayout
private AssemblyBuilder(AssemblyName n, AssemblyBuilderAccess access)
{
aname = (AssemblyName)n.Clone();
if (!Enum.IsDefined(typeof(AssemblyBuilderAccess), access))
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Argument value {0} is not valid.", (int)access),
nameof(access));
name = n.Name;
this.access = (uint)access;
/* Set defaults from n */
if (n.CultureInfo != null)
culture = n.CultureInfo.Name;
Version? v = n.Version;
if (v != null)
{
version = v.ToString();
}
basic_init(this);
// Netcore only allows one module per assembly
manifest_module = new ModuleBuilder(this, "RefEmit_InMemoryManifestModule", false);
modules = new ModuleBuilder[] { manifest_module };
}
public override bool ReflectionOnly
{
get { return base.ReflectionOnly; }
}
public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return new AssemblyBuilder(name, access);
}
public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder>? assemblyAttributes)
{
AssemblyBuilder ab = DefineDynamicAssembly(name, access);
if (assemblyAttributes != null)
{
foreach (CustomAttributeBuilder attr in assemblyAttributes)
ab.SetCustomAttribute(attr);
}
return ab;
}
public ModuleBuilder DefineDynamicModule(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException("Empty name is not legal.", nameof(name));
if (name[0] == '\0')
throw new ArgumentException(SR.Argument_InvalidName, nameof(name));
if (manifest_module_used)
throw new InvalidOperationException(SR.InvalidOperation_NoMultiModuleAssembly);
manifest_module_used = true;
return manifest_module;
}
public ModuleBuilder? GetDynamicModule(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException("Empty name is not legal.", nameof(name));
if (modules != null)
for (int i = 0; i < modules.Length; ++i)
if (modules[i].name == name)
return modules[i];
return null;
}
public override bool IsCollectible => access == (uint)AssemblyBuilderAccess.RunAndCollect;
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
throw new ArgumentNullException(nameof(customBuilder));
if (cattrs != null)
{
CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1];
cattrs.CopyTo(new_array, 0);
new_array[cattrs.Length] = customBuilder;
cattrs = new_array;
}
else
{
cattrs = new CustomAttributeBuilder[1];
cattrs[0] = customBuilder;
}
UpdateNativeCustomAttributes(this);
}
[ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute));
}
/*Warning, @typeArguments must be a mscorlib internal array. So make a copy before passing it in*/
internal static Type MakeGenericType(Type gtd, Type[] typeArguments) =>
new TypeBuilderInstantiation(gtd, typeArguments);
[RequiresUnreferencedCode("Types might be removed")]
public override Type? GetType(string name, bool throwOnError, bool ignoreCase)
{
if (name == null)
throw new ArgumentNullException(name);
if (name.Length == 0)
throw new ArgumentException("Name cannot be empty", nameof(name));
Type res = InternalGetType(null, name, throwOnError, ignoreCase);
if (res is TypeBuilder)
{
if (throwOnError)
throw new TypeLoadException(string.Format("Could not load type '{0}' from assembly '{1}'", name, this.name));
return null;
}
return res;
}
public override Module? GetModule(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException("Name can't be empty");
if (modules == null)
return null;
foreach (Module module in modules)
{
if (module.ScopeName == name)
return module;
}
return null;
}
public override Module[] GetModules(bool getResourceModules)
{
if (modules == null)
return Array.Empty<Module>();
return (Module[])modules.Clone();
}
public override AssemblyName GetName(bool copiedName) => AssemblyName.Create(_mono_assembly, null);
[RequiresUnreferencedCode("Assembly references might be removed")]
public override AssemblyName[] GetReferencedAssemblies() => RuntimeAssembly.GetReferencedAssemblies(this);
public override Module[] GetLoadedModules(bool getResourceModules) => GetModules(getResourceModules);
//FIXME MS has issues loading satelite assemblies from SRE
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture) => GetSatelliteAssembly(culture, null);
//FIXME MS has issues loading satelite assemblies from SRE
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture, Version? version) =>
RuntimeAssembly.InternalGetSatelliteAssembly(this, culture, version, true)!;
public override Module ManifestModule => manifest_module;
public override string? FullName => aname.ToString();
public override bool Equals(object? obj) => base.Equals(obj);
public override int GetHashCode() => base.GetHashCode();
public override bool IsDefined(Type attributeType, bool inherit) =>
CustomAttribute.IsDefined(this, attributeType, inherit);
public override object[] GetCustomAttributes(bool inherit) => CustomAttribute.GetCustomAttributes(this, inherit);
public override object[] GetCustomAttributes(Type attributeType, bool inherit) =>
CustomAttribute.GetCustomAttributes(this, attributeType, inherit);
public override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributeData.GetCustomAttributes(this);
}
}
#endif