-
Notifications
You must be signed in to change notification settings - Fork 516
/
Runtime.cs
2247 lines (1932 loc) · 73.3 KB
/
Runtime.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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Runtime.cs: Mac/iOS shared runtime code
//
// Authors:
// Miguel de Icaza
//
// Copyright 2013 Xamarin Inc.
#nullable enable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using CoreFoundation;
using Foundation;
using Registrar;
#if MONOMAC
using AppKit;
#endif
namespace ObjCRuntime {
public partial class Runtime {
#if !COREBUILD
#pragma warning disable 8618 // "Non-nullable field '...' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.": we make sure through other means that these will never be null
static Dictionary<IntPtrTypeValueTuple, Delegate> block_to_delegate_cache;
static Dictionary<Type, ConstructorInfo> intptr_ctor_cache;
static Dictionary<Type, ConstructorInfo> intptr_bool_ctor_cache;
internal static Dictionary<IntPtr, Dictionary<IntPtr, bool>> protocol_cache;
static List<object> delegates;
static List<Assembly> assemblies;
static Dictionary<IntPtr, GCHandle> object_map;
static Dictionary<IntPtr, bool> usertype_cache;
static object lock_obj;
static IntPtr NSObjectClass;
static bool initialized;
internal static IntPtrEqualityComparer IntPtrEqualityComparer;
internal static TypeEqualityComparer TypeEqualityComparer;
internal static DynamicRegistrar Registrar;
#pragma warning restore 8618
internal const uint INVALID_TOKEN_REF = 0xFFFFFFFF;
#pragma warning disable 649 // Field 'X' is never assigned to, and will always have its default value
internal unsafe struct MTRegistrationMap {
public IntPtr product_hash;
public MTAssembly* assemblies;
public MTClassMap* map;
public MTFullTokenReference* full_token_references;
public MTManagedClassMap* skipped_map;
public MTProtocolWrapperMap* protocol_wrapper_map;
public MTProtocolMap protocol_map;
public int assembly_count;
public int map_count;
public int full_token_reference_count;
public int skipped_map_count;
public int protocol_wrapper_count;
public int protocol_count;
}
#pragma warning restore 649
[Flags]
internal enum MTTypeFlags : uint {
None = 0,
CustomType = 1,
UserType = 2,
}
[StructLayout (LayoutKind.Sequential, Pack = 1)]
internal unsafe struct MTFullTokenReference {
public uint assembly_index;
public uint module_token;
public uint token;
}
[StructLayout (LayoutKind.Sequential, Pack = 1)]
internal struct MTClassMap {
public IntPtr handle;
public uint type_reference;
public MTTypeFlags flags;
}
[StructLayout (LayoutKind.Sequential, Pack = 1)]
internal struct MTManagedClassMap {
public uint skipped_reference; // implied token type: TypeDef
public uint actual_reference; // implied token type: TypeDef
}
[StructLayout (LayoutKind.Sequential, Pack = 1)]
internal struct MTProtocolWrapperMap {
public uint protocol_token;
public uint wrapper_token;
}
[StructLayout (LayoutKind.Sequential, Pack = 1)]
internal unsafe struct MTProtocolMap {
public uint* protocol_tokens;
public IntPtr* protocols;
}
[StructLayout (LayoutKind.Sequential, Pack = 1)]
internal unsafe struct MTAssembly {
public IntPtr name;
public IntPtr mvid;
}
/* Keep Delegates, Trampolines and InitializationOptions in sync with monotouch-glue.m */
#pragma warning disable 649 // Field 'X' is never assigned to, and will always have its default value
internal struct Trampolines {
public IntPtr tramp;
public IntPtr stret_tramp;
public IntPtr fpret_single_tramp;
public IntPtr fpret_double_tramp;
public IntPtr release_tramp;
public IntPtr retain_tramp;
public IntPtr static_tramp;
public IntPtr ctor_tramp;
public IntPtr x86_double_abi_stret_tramp;
public IntPtr static_fpret_single_tramp;
public IntPtr static_fpret_double_tramp;
public IntPtr static_stret_tramp;
public IntPtr x86_double_abi_static_stret_tramp;
public IntPtr long_tramp;
public IntPtr static_long_tramp;
#if MONOMAC
public IntPtr copy_with_zone_1;
public IntPtr copy_with_zone_2;
#endif
public IntPtr get_gchandle_tramp;
public IntPtr set_gchandle_tramp;
public IntPtr get_flags_tramp;
public IntPtr set_flags_tramp;
}
#pragma warning restore 649
[Flags]
internal enum InitializationFlags : int {
IsPartialStaticRegistrar = 0x01,
/* unused = 0x02,*/
/* unused = 0x04,*/
/* unused = 0x08,*/
IsSimulator = 0x10,
#if NET
IsCoreCLR = 0x20,
#endif
}
#if MONOMAC
/* This enum must always match the identical enum in runtime/xamarin/main.h */
internal enum LaunchMode : int {
App = 0,
Extension = 1,
Embedded = 2,
}
#endif
[StructLayout (LayoutKind.Sequential)]
internal unsafe struct InitializationOptions {
public int Size;
public InitializationFlags Flags;
public Delegates* Delegates;
public Trampolines* Trampolines;
public MTRegistrationMap* RegistrationMap;
public MarshalObjectiveCExceptionMode MarshalObjectiveCExceptionMode;
public MarshalManagedExceptionMode MarshalManagedExceptionMode;
#if MONOMAC
public LaunchMode LaunchMode;
public IntPtr EntryAssemblyPath; /* char * */
#endif
IntPtr AssemblyLocations;
#if NET
public IntPtr xamarin_objc_msgsend;
public IntPtr xamarin_objc_msgsend_super;
public IntPtr xamarin_objc_msgsend_stret;
public IntPtr xamarin_objc_msgsend_super_stret;
public IntPtr unhandled_exception_handler;
public IntPtr reference_tracking_begin_end_callback;
public IntPtr reference_tracking_is_referenced_callback;
public IntPtr reference_tracking_tracked_object_entered_finalization;
#endif
public bool IsSimulator {
get {
return (Flags & InitializationFlags.IsSimulator) == InitializationFlags.IsSimulator;
}
}
}
internal static unsafe InitializationOptions* options;
#if NET
[BindingImpl (BindingImplOptions.Optimizable)]
internal unsafe static bool IsCoreCLR {
get {
// The linker may turn calls to this property into a constant
return (options->Flags.HasFlag (InitializationFlags.IsCoreCLR));
}
}
#endif
[BindingImpl (BindingImplOptions.Optimizable)]
public static bool DynamicRegistrationSupported {
get {
// The linker may turn calls to this property into a constant
return true;
}
}
internal static bool Initialized {
get { return initialized; }
}
#if MONOMAC
[DllImport (Constants.libcLibrary)]
static extern int _NSGetExecutablePath (byte[] buf, ref int bufsize);
#endif
[Preserve] // called from native - runtime.m.
[BindingImpl (BindingImplOptions.Optimizable)] // To inline the Runtime.DynamicRegistrationSupported code if possible.
unsafe static void Initialize (InitializationOptions* options)
{
#if PROFILE
var watch = new Stopwatch ();
#endif
if (options->Size != Marshal.SizeOf (typeof (InitializationOptions))) {
var msg = $"Version mismatch between the native {ProductName} runtime and {AssemblyName}. Please reinstall {ProductName}.";
NSLog (msg);
#if MONOMAC
try {
// Print out where Xamarin.Mac.dll and the native runtime was loaded from.
NSLog ($"{AssemblyName} was loaded from {typeof (NSObject).Assembly.Location}");
var sym2 = Dlfcn.dlsym (Dlfcn.RTLD.Default, "xamarin_initialize");
Dlfcn.Dl_info info2;
if (Dlfcn.dladdr (sym2, out info2) == 0) {
NSLog ($"The native runtime was loaded from {Marshal.PtrToStringAuto (info2.dli_fname)}");
} else if (Dlfcn.dlsym (Dlfcn.RTLD.MainOnly, "xamarin_initialize") != IntPtr.Zero) {
var buf = new byte [128];
int length = buf.Length;
if (_NSGetExecutablePath (buf, ref length) == -1) {
Array.Resize (ref buf, length);
length = buf.Length;
if (_NSGetExecutablePath (buf, ref length) != 0) {
NSLog ("Could not find out where the native runtime was loaded from.");
buf = null;
}
}
if (buf is not null) {
var str_length = 0;
for (int i = 0; i < buf.Length && buf [i] != 0; i++)
str_length++;
NSLog ($"The native runtime was loaded from {Encoding.UTF8.GetString (buf, 0, str_length)}");
}
} else {
NSLog ("Could not find out where the native runtime was loaded from.");
}
} catch {
// Just ignore any exceptions, the above code is just a debug help, and if it fails,
// any exception show to the user will likely confuse more than help
}
#endif
throw ErrorHelper.CreateError (8001, msg);
}
if (IntPtr.Size != sizeof (nint)) {
string msg = $"Native type size mismatch between {AssemblyName} and the executing architecture. {AssemblyName} was built for {(IntPtr.Size == 4 ? 64 : 32)}-bit, while the current process is {(IntPtr.Size == 4 ? 32 : 64)}-bit.";
NSLog (msg);
throw ErrorHelper.CreateError (8010, msg);
}
IntPtrEqualityComparer = new IntPtrEqualityComparer ();
TypeEqualityComparer = new TypeEqualityComparer ();
Runtime.options = options;
delegates = new List<object> ();
object_map = new Dictionary<IntPtr, GCHandle> (IntPtrEqualityComparer);
usertype_cache = new Dictionary<IntPtr, bool> (IntPtrEqualityComparer);
intptr_ctor_cache = new Dictionary<Type, ConstructorInfo> (TypeEqualityComparer);
intptr_bool_ctor_cache = new Dictionary<Type, ConstructorInfo> (TypeEqualityComparer);
lock_obj = new object ();
NSObjectClass = NSObject.Initialize ();
if (DynamicRegistrationSupported) {
Registrar = new DynamicRegistrar ();
protocol_cache = new Dictionary<IntPtr, Dictionary<IntPtr, bool>> (IntPtrEqualityComparer);
}
RegisterDelegates (options);
Class.Initialize (options);
#if !NET
// This is not needed for .NET 5:
// * https://github.com/xamarin/xamarin-macios/issues/7924#issuecomment-588331822
// * https://github.com/xamarin/xamarin-macios/issues/7924#issuecomment-589356481
Mono.SystemDependencyProvider.Initialize ();
#endif
InitializePlatform (options);
#if !XAMMAC_SYSTEM_MONO && !NET
UseAutoreleasePoolInThreadPool = true;
#endif
IsARM64CallingConvention = GetIsARM64CallingConvention (); // Can only be done after Runtime.Arch is set (i.e. InitializePlatform has been called).
objc_exception_mode = options->MarshalObjectiveCExceptionMode;
managed_exception_mode = options->MarshalManagedExceptionMode;
#if NET
if (IsCoreCLR)
InitializeCoreCLRBridge (options);
#endif
initialized = true;
#if PROFILE
Console.WriteLine ("Runtime.Initialize completed in {0} ms", watch.ElapsedMilliseconds);
#endif
}
#if !XAMMAC_SYSTEM_MONO
#if !NET
static bool has_autoreleasepool_in_thread_pool;
public static bool UseAutoreleasePoolInThreadPool {
get {
return has_autoreleasepool_in_thread_pool;
}
set {
System.Threading._ThreadPoolWaitCallback.SetDispatcher (value ? new Func<Func<bool>, bool> (ThreadPoolDispatcher) : null);
has_autoreleasepool_in_thread_pool = value;
}
}
static bool ThreadPoolDispatcher (Func<bool> callback)
{
using (var pool = new NSAutoreleasePool ())
return callback ();
}
#endif // !NET
#endif
#if MONOMAC
public static event AssemblyRegistrationHandler? AssemblyRegistration;
static bool OnAssemblyRegistration (AssemblyName assembly_name)
{
if (AssemblyRegistration is not null) {
var args = new AssemblyRegistrationEventArgs
{
Register = true,
AssemblyName = assembly_name
};
AssemblyRegistration (null, args);
return args.Register;
}
return true;
}
#endif
static MarshalObjectiveCExceptionMode objc_exception_mode;
static MarshalManagedExceptionMode managed_exception_mode;
public static event MarshalObjectiveCExceptionHandler? MarshalObjectiveCException;
public static event MarshalManagedExceptionHandler? MarshalManagedException;
static MarshalObjectiveCExceptionMode OnMarshalObjectiveCException (IntPtr exception_handle, sbyte throwManagedAsDefault)
{
if (throwManagedAsDefault != 0 && MarshalObjectiveCException is null)
return MarshalObjectiveCExceptionMode.ThrowManagedException;
if (MarshalObjectiveCException is not null) {
var exception = GetNSObject<NSException> (exception_handle);
var args = new MarshalObjectiveCExceptionEventArgs () {
Exception = exception,
ExceptionMode = (throwManagedAsDefault != 0) ? MarshalObjectiveCExceptionMode.ThrowManagedException : objc_exception_mode,
};
MarshalObjectiveCException (null, args);
return args.ExceptionMode;
}
return objc_exception_mode;
}
static MarshalManagedExceptionMode OnMarshalManagedException (IntPtr exception_handle)
{
if (MarshalManagedException is not null) {
var exception = GCHandle.FromIntPtr (exception_handle).Target as Exception;
var args = new MarshalManagedExceptionEventArgs () {
Exception = exception,
ExceptionMode = managed_exception_mode,
};
MarshalManagedException (null, args);
return args.ExceptionMode;
}
return managed_exception_mode;
}
static IntPtr GetFunctionPointer (Delegate d)
{
delegates.Add (d);
return Marshal.GetFunctionPointerForDelegate (d);
}
// value_handle: GCHandle to a (smart) enum value
// returns: a handle to a native NSString *
static IntPtr ConvertSmartEnumToNSString (IntPtr value_handle)
{
var value = GetGCHandleTarget (value_handle)!;
var smart_type = value.GetType ();
MethodBase getConstantMethod, getValueMethod;
if (!Registrar.IsSmartEnum (smart_type, out getConstantMethod, out getValueMethod))
throw ErrorHelper.CreateError (8024, $"Could not find a valid extension type for the smart enum '{smart_type.FullName}'. Please file a bug at https://github.com/xamarin/xamarin-macios/issues/new.");
var rv = (NSString?) ((MethodInfo) getConstantMethod).Invoke (null, new object [] { value });
if (rv is null)
return IntPtr.Zero;
rv.DangerousRetain ().DangerousAutorelease ();
return rv.Handle;
}
// value: native NSString *
// returns: GCHandle to a (smart) enum value. Caller must free the GCHandle.
static IntPtr ConvertNSStringToSmartEnum (IntPtr value, IntPtr type)
{
var smart_type = (Type) GetGCHandleTarget (type)!;
var str = GetNSObject<NSString> (value)!;
MethodBase getConstantMethod, getValueMethod;
if (!Registrar.IsSmartEnum (smart_type, out getConstantMethod, out getValueMethod))
throw ErrorHelper.CreateError (8024, $"Could not find a valid extension type for the smart enum '{smart_type.FullName}'. Please file a bug at https://github.com/xamarin/xamarin-macios/issues/new.");
var rv = ((MethodInfo) getValueMethod).Invoke (null, new object [] { str });
return AllocGCHandle (rv);
}
#region Wrappers for delegate callbacks
static void RegisterAssembly (IntPtr a)
{
RegisterAssembly ((Assembly) GetGCHandleTarget (a)!);
}
static void RegisterEntryAssembly (IntPtr a)
{
RegisterEntryAssembly ((Assembly) GetGCHandleTarget (a)!);
}
static void ThrowNSException (IntPtr ns_exception)
{
#if MONOMAC || NET
throw new ObjCException (new NSException (ns_exception));
#else
throw new MonoTouchException (new NSException (ns_exception));
#endif
}
static void RethrowManagedException (IntPtr exception_gchandle)
{
var e = (Exception) GCHandle.FromIntPtr ((IntPtr) exception_gchandle).Target!;
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture (e).Throw ();
}
static IntPtr CreateNSException (IntPtr ns_exception)
{
Exception ex;
#if MONOMAC || NET
ex = new ObjCException (Runtime.GetNSObject<NSException> (ns_exception)!);
#else
ex = new MonoTouchException (Runtime.GetNSObject<NSException> (ns_exception)!);
#endif
return AllocGCHandle (ex);
}
static IntPtr CreateRuntimeException (int code, IntPtr message)
{
var ex = ErrorHelper.CreateError (code, Marshal.PtrToStringAuto (message)!);
return AllocGCHandle (ex);
}
static IntPtr UnwrapNSException (IntPtr exc_handle)
{
var obj = GCHandle.FromIntPtr (exc_handle).Target;
#if MONOMAC || NET
var exc = obj as ObjCException;
#else
var exc = obj as MonoTouchException;
#endif
var nsexc = exc?.NSException;
if (nsexc is not null) {
return nsexc.DangerousRetain ().DangerousAutorelease ().Handle;
} else {
return IntPtr.Zero;
}
}
static IntPtr GetBlockWrapperCreator (IntPtr method, int parameter)
{
return AllocGCHandle (GetBlockWrapperCreator ((MethodInfo) GetGCHandleTarget (method)!, parameter));
}
static IntPtr CreateBlockProxy (IntPtr method, IntPtr block)
{
return AllocGCHandle (CreateBlockProxy ((MethodInfo) GetGCHandleTarget (method)!, block));
}
static IntPtr CreateDelegateProxy (IntPtr method, IntPtr @delegate, IntPtr signature, uint token_ref)
{
return BlockLiteral.GetBlockForDelegate ((MethodInfo) GetGCHandleTarget (method)!, GetGCHandleTarget (@delegate), token_ref, Marshal.PtrToStringAuto (signature));
}
static IntPtr GetExceptionMessage (IntPtr exception_gchandle)
{
var exc = (Exception) GetGCHandleTarget (exception_gchandle)!;
return Marshal.StringToHGlobalAuto (exc.Message);
}
static void PrintException (Exception exc, bool isInnerException, StringBuilder sb)
{
if (isInnerException)
sb.AppendLine (" --- inner exception ---");
sb.Append (exc.Message).Append (" (").Append (exc.GetType ().FullName).AppendLine (")");
var trace = exc.StackTrace;
if (!string.IsNullOrEmpty (trace))
sb.AppendLine (trace);
}
static IntPtr PrintAllExceptions (IntPtr exception_gchandle)
{
var str = new StringBuilder ();
try {
var exc = (Exception?) GetGCHandleTarget (exception_gchandle);
if (exc is null) {
str.Append ($"Unable to print exception handle 0x{exception_gchandle.ToString ("x")}: null exception");
} else {
int counter = 0;
do {
PrintException (exc, counter > 0, str);
exc = exc.InnerException;
} while (counter < 10 && exc is not null);
}
} catch (Exception exception) {
str.Append ("Failed to print exception: ").Append (exception);
}
return Marshal.StringToHGlobalAuto (str.ToString ());
}
static unsafe Assembly? GetEntryAssembly ()
{
var asm = Assembly.GetEntryAssembly ();
#if MONOMAC
if (asm is null)
asm = Assembly.LoadFile (Marshal.PtrToStringAuto (options->EntryAssemblyPath)!);
#endif
return asm;
}
// This method will register all assemblies referenced by the entry assembly.
// For XM it will also register all assemblies loaded in the current appdomain.
internal static void RegisterAssemblies ()
{
#if PROFILE
var watch = new Stopwatch ();
#endif
RegisterEntryAssembly (GetEntryAssembly ());
#if PROFILE
Console.WriteLine ("RegisterAssemblies completed in {0} ms", watch.ElapsedMilliseconds);
#endif
}
// This method will register all assemblies referenced by the entry assembly.
// For XM it will also register all assemblies loaded in the current appdomain.
//
// NOTE: the linker will remove this method when the dynamic registrar has been optimized away (RemoveCode.cs)
// and as such cannot be renamed without updating the linker
internal static void RegisterEntryAssembly (Assembly? entry_assembly)
{
var assemblies = new List<Assembly> ();
assemblies.Add (NSObject.PlatformAssembly); // make sure our platform assembly comes first
// Recursively get all assemblies referenced by the entry assembly.
if (entry_assembly is not null) {
var register_entry_assembly = true;
#if MONOMAC
register_entry_assembly = OnAssemblyRegistration (entry_assembly.GetName ());
#endif
if (register_entry_assembly)
CollectReferencedAssemblies (assemblies, entry_assembly);
} else {
NSLog ("Could not find the entry assembly.");
}
#if MONOMAC
// Add all assemblies already loaded
foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()) {
if (!OnAssemblyRegistration (a.GetName ()))
continue;
if (!assemblies.Contains (a))
assemblies.Add (a);
}
#endif
foreach (var a in assemblies)
RegisterAssembly (a);
}
static void CollectReferencedAssemblies (List<Assembly> assemblies, Assembly assembly)
{
assemblies.Add (assembly);
foreach (var rf in assembly.GetReferencedAssemblies ()) {
#if MONOMAC
if (!OnAssemblyRegistration (rf))
continue;
#endif
try {
var a = Assembly.Load (rf);
if (!assemblies.Contains (a))
CollectReferencedAssemblies (assemblies, a);
} catch (FileNotFoundException fefe) {
// that's more important for XI because device builds don't go thru this step
// and we can end up with simulator-only failures - bug #29211
NSLog ($"Could not find `{fefe.FileName}` referenced by assembly `{assembly.FullName}`.");
#if MONOMAC && !NET
if (!NSApplication.IgnoreMissingAssembliesDuringRegistration)
throw;
#endif
}
}
}
internal static IEnumerable<Assembly> GetAssemblies ()
{
return Registrar.GetAssemblies ();
}
internal static string ComputeSignature (MethodInfo method, bool isBlockSignature)
{
return Registrar.ComputeSignature (method, isBlockSignature);
}
[BindingImpl (BindingImplOptions.Optimizable)]
public static void RegisterAssembly (Assembly a)
{
if (a is null)
throw new ArgumentNullException (nameof (a));
if (!DynamicRegistrationSupported)
throw ErrorHelper.CreateError (8026, "Runtime.RegisterAssembly is not supported when the dynamic registrar has been linked away.");
#if MONOMAC
var attributes = a.GetCustomAttributes (typeof (RequiredFrameworkAttribute), false);
foreach (var attribute in attributes) {
var requiredFramework = (RequiredFrameworkAttribute)attribute;
string libPath;
string libName = requiredFramework.Name;
if (libName.Contains (".dylib")) {
libPath = ResourcesPath!;
}
else {
libPath = FrameworksPath!;
libPath = Path.Combine (libPath, libName);
libName = libName.Replace (".frameworks", "");
}
libPath = Path.Combine (libPath, libName);
if (Dlfcn.dlopen (libPath, 0) == IntPtr.Zero)
throw new Exception ($"Unable to load required framework: '{requiredFramework.Name}'",
new Exception (Dlfcn.dlerror()));
}
attributes = a.GetCustomAttributes (typeof (DelayedRegistrationAttribute), false);
foreach (var attribute in attributes) {
var delayedRegistration = (DelayedRegistrationAttribute) attribute;
if (delayedRegistration.Delay)
return;
}
#endif
if (assemblies is null) {
assemblies = new List<Assembly> ();
Class.Register (typeof (NSObject));
}
if (assemblies.Contains (a))
return;
assemblies.Add (a);
#if PROFILE
var watch = new Stopwatch ();
watch.Start ();
#endif
Registrar.RegisterAssembly (a);
#if PROFILE
watch.Stop ();
Console.WriteLine ("RegisterAssembly ({0}) completed in {1} ms", a.FullName, watch.ElapsedMilliseconds);
#endif
}
static IntPtr GetClass (IntPtr klass)
{
return AllocGCHandle (new Class (klass));
}
static IntPtr GetSelector (IntPtr sel)
{
return AllocGCHandle (new Selector (sel));
}
static void GetMethodForSelector (IntPtr cls, IntPtr sel, sbyte is_static, IntPtr desc)
{
// This is called by the old registrar code.
Registrar.GetMethodDescription (Class.Lookup (cls), sel, is_static != 0, desc);
}
static sbyte HasNSObject (IntPtr ptr)
{
var rv = TryGetNSObject (ptr, evenInFinalizerQueue: false) is not null;
return (sbyte) (rv ? 1 : 0);
}
static IntPtr GetHandleForINativeObject (IntPtr ptr)
{
return ((INativeObject) GetGCHandleTarget (ptr)!).Handle;
}
static void UnregisterNSObject (IntPtr native_obj, IntPtr managed_obj)
{
NativeObjectHasDied (native_obj, GetGCHandleTarget (managed_obj) as NSObject);
}
static unsafe IntPtr GetMethodFromToken (uint token_ref)
{
var method = Class.ResolveMethodTokenReference (token_ref);
if (method is not null)
return AllocGCHandle (method);
return IntPtr.Zero;
}
static unsafe IntPtr GetGenericMethodFromToken (IntPtr obj, uint token_ref)
{
var method = Class.ResolveMethodTokenReference (token_ref);
if (method is null)
return IntPtr.Zero;
var nsobj = GetGCHandleTarget (obj) as NSObject;
if (nsobj is null)
throw ErrorHelper.CreateError (8023, $"An instance object is required to construct a closed generic method for the open generic method: {method.DeclaringType!.FullName}.{method.Name} (token reference: 0x{token_ref:X}). {Constants.PleaseFileBugReport}");
return AllocGCHandle (FindClosedMethod (nsobj.GetType (), method));
}
static IntPtr TryGetOrConstructNSObjectWrapped (IntPtr ptr)
{
return AllocGCHandle (GetNSObject (ptr, MissingCtorResolution.Ignore, true));
}
static IntPtr GetINativeObject_Dynamic (IntPtr ptr, sbyte owns, IntPtr type_ptr)
{
/*
* This method is called from marshalling bridge (dynamic mode).
*/
var type = (System.Type) GetGCHandleTarget (type_ptr)!;
return AllocGCHandle (GetINativeObject (ptr, owns != 0, type, null));
}
static IntPtr GetINativeObject_Static (IntPtr ptr, sbyte owns, uint iface_token, uint implementation_token)
{
/*
* This method is called from generated code from the static registrar.
*/
var iface = Class.ResolveTypeTokenReference (iface_token)!;
var type = Class.ResolveTypeTokenReference (implementation_token);
return AllocGCHandle (GetINativeObject (ptr, owns != 0, iface, type));
}
unsafe static IntPtr GetNSObjectWithType (IntPtr ptr, IntPtr type_ptr, int* createdPtr)
{
var type = (System.Type) GetGCHandleTarget (type_ptr)!;
var rv = AllocGCHandle (GetNSObject (ptr, type, MissingCtorResolution.ThrowConstructor1NotFound, true, true, out var created));
*createdPtr = created ? 1 : 0;
return rv;
}
static void Dispose (IntPtr gchandle)
{
((IDisposable?) GetGCHandleTarget (gchandle))?.Dispose ();
}
static sbyte IsParameterTransient (IntPtr info, int parameter)
{
var minfo = GetGCHandleTarget (info) as MethodInfo;
if (minfo is null)
return 0; // might be a ConstructorInfo (bug #15583), but we don't care about that (yet at least).
minfo = minfo.GetBaseDefinition ();
var parameters = minfo.GetParameters ();
if (parameters.Length <= parameter)
return 0;
var rv = parameters [parameter].IsDefined (typeof (TransientAttribute), false);
return (sbyte) (rv ? 1 : 0);
}
static sbyte IsParameterOut (IntPtr info, int parameter)
{
var minfo = GetGCHandleTarget (info) as MethodInfo;
if (minfo is null)
return 0; // might be a ConstructorInfo (bug #15583), but we don't care about that (yet at least).
minfo = minfo.GetBaseDefinition ();
var parameters = minfo.GetParameters ();
if (parameters.Length <= parameter)
return 0;
var rv = parameters [parameter].IsOut;
return (sbyte) (rv ? 1 : 0);
}
unsafe static void GetMethodAndObjectForSelector (IntPtr klass, IntPtr sel, sbyte is_static, IntPtr obj, IntPtr* mthisPtr, IntPtr desc)
{
IntPtr mthis = *mthisPtr;
Registrar.GetMethodDescriptionAndObject (Class.Lookup (klass), sel, is_static != 0, obj, ref mthis, desc);
*mthisPtr = mthis;
}
// If inner_exception_gchandle is provided, it will be freed.
static IntPtr CreateProductException (int code, IntPtr inner_exception_gchandle, IntPtr utf8Message)
{
Exception? inner_exception = null;
if (inner_exception_gchandle != IntPtr.Zero) {
GCHandle gchandle = GCHandle.FromIntPtr (inner_exception_gchandle);
inner_exception = (Exception?) gchandle.Target;
gchandle.Free ();
}
var msg = Marshal.PtrToStringAuto (utf8Message)!;
Exception ex = ErrorHelper.CreateError (code, inner_exception, msg);
return AllocGCHandle (ex);
}
static IntPtr TypeGetFullName (IntPtr type)
{
return Marshal.StringToHGlobalAuto (((Type) GetGCHandleTarget (type)!).FullName);
}
static IntPtr GetObjectTypeFullName (IntPtr gchandle)
{
var obj = GetGCHandleTarget (gchandle);
if (obj is null)
return IntPtr.Zero;
return Marshal.StringToHGlobalAuto (obj.GetType ().FullName);
}
static IntPtr LookupManagedTypeName (IntPtr klass)
{
return Marshal.StringToHGlobalAuto (Class.Lookup (klass)?.FullName);
}
#endregion
static MethodInfo? GetBlockProxyAttributeMethod (MethodInfo method, int parameter)
{
var attrs = method.GetParameters () [parameter].GetCustomAttributes (typeof (BlockProxyAttribute), true);
if (attrs.Length == 1) {
try {
var attr = attrs [0] as BlockProxyAttribute;
return attr?.Type?.GetMethod ("Create");
} catch {
return null;
}
}
return null;
}
internal static ProtocolMemberAttribute? GetProtocolMemberAttribute (Type type, string selector, MethodInfo method)
{
var memberAttributes = type.GetCustomAttributes<ProtocolMemberAttribute> ();
if (memberAttributes is null)
return null;
foreach (var attrib in memberAttributes) {
if (attrib.IsStatic != method.IsStatic)
continue;
if (attrib.Selector != selector)
continue;
if (!attrib.IsProperty) {
var methodParameters = method.GetParameters ();
if ((attrib.ParameterType?.Length ?? 0) != methodParameters.Length)
continue;
var notApplicable = false;
for (int i = 0; i < methodParameters.Length; i++) {
var paramType = methodParameters [i].ParameterType;
var isByRef = paramType.IsByRef;
if (isByRef)
paramType = paramType.GetElementType ();
if (isByRef != attrib.ParameterByRef! [i]) {
notApplicable = true;
break;
}
if (paramType != attrib.ParameterType! [i]) {
notApplicable = true;
break;
}
}
if (notApplicable)
continue;
}
return attrib;
}
return null;
}
//
// Returns a MethodInfo that represents the method that can be used to turn
// a the block in the given method at the given parameter into a strongly typed
// delegate
//
[EditorBrowsable (EditorBrowsableState.Never)]
static MethodInfo? GetBlockWrapperCreator (MethodInfo method, int parameter)
{
// A mirror of this method is also implemented in StaticRegistrar:FindBlockProxyCreatorMethod
// If this method is changed, that method will probably have to be updated too (tests!!!)
MethodInfo first = method;
MethodInfo? last = null;
Type []? extensionParameters = null;
while (method != last) {
last = method;
var createMethod = GetBlockProxyAttributeMethod (method, parameter);
if (createMethod is not null)
return createMethod;
method = method.GetBaseDefinition ();
}
string? selector = null;
// Might be the implementation of an interface method, so find the corresponding
// MethodInfo for the interface, and check for BlockProxy attributes there as well.
foreach (var iface in method.DeclaringType!.GetInterfaces ()) {
if (!iface.IsDefined (typeof (ProtocolAttribute), false))
continue;
var map = method.DeclaringType.GetInterfaceMap (iface);
for (int i = 0; i < map.TargetMethods.Length; i++) {
if (map.TargetMethods [i] == first) {
var createMethod = GetBlockProxyAttributeMethod (map.InterfaceMethods [i], parameter);
if (createMethod is not null)
return createMethod;
}
}
// We store the BlockProxy type in the ProtocolMemberAttribute, so check those.
// We may run into binding assemblies built with earlier versions of the generator,
// which means we can't rely on finding the BlockProxy attribute in the ProtocolMemberAttribute.
if (selector is null)
selector = GetExportAttribute (method)?.Selector ?? string.Empty;
if (!string.IsNullOrEmpty (selector)) {
var attrib = GetProtocolMemberAttribute (iface, selector, method);
if (attrib is not null && attrib.ParameterBlockProxy!.Length > parameter && attrib.ParameterBlockProxy [parameter] is not null)
return attrib.ParameterBlockProxy [parameter]!.GetMethod ("Create");
}
// Might be an implementation of an optional protocol member.
// We look that up on the corresponding extension method.
string extensionName = string.Empty;
if (!string.IsNullOrEmpty (iface.Namespace))
extensionName = iface.Namespace + ".";
extensionName += iface.Name.Substring (1) + "_Extensions";
var extensionType = iface.Assembly.GetType (extensionName, false);
if (extensionType is not null) {
if (extensionParameters is null) {
var methodParameters = method.GetParameters ();
extensionParameters = new Type [methodParameters.Length + 1];
for (int i = 0; i < methodParameters.Length; i++)
extensionParameters [i + 1] = methodParameters [i].ParameterType;
}
extensionParameters [0] = iface;
var extensionMethod = extensionType.GetMethod (method.Name, BindingFlags.Public | BindingFlags.Static, null, extensionParameters, null);
if (extensionMethod is not null) {
var createMethod = GetBlockProxyAttributeMethod (extensionMethod, parameter + 1);
if (createMethod is not null)
return createMethod;
}
}
}
throw new RuntimeException (8009, true, $"Unable to locate the block to delegate conversion method for the method {method.DeclaringType.FullName}.{method.Name}'s parameter #{parameter + 1}. {Constants.PleaseFileBugReport}");
}