-
Notifications
You must be signed in to change notification settings - Fork 519
/
Copy pathRegistrar.cs
2888 lines (2503 loc) · 93.6 KB
/
Registrar.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
//
// Registrar.cs: Common code for the static and dynamic registrars.
//
// Authors:
// Rolf Bjarne Kvinge <[email protected]>
//
// Copyright 2013 Xamarin Inc.
//
// #define VERBOSE_REGISTRAR
#if IPHONE
#define MONOTOUCH
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Foundation;
using ObjCRuntime;
using Xamarin.Bundler;
#if MTOUCH || MMP || BUNDLER
using Xamarin.Utils;
using TAssembly = Mono.Cecil.AssemblyDefinition;
using TType = Mono.Cecil.TypeReference;
using TMethod = Mono.Cecil.MethodDefinition;
using TProperty = Mono.Cecil.PropertyDefinition;
using TField = Mono.Cecil.FieldDefinition;
using R = Registrar.Registrar;
#else
using TAssembly = System.Reflection.Assembly;
using TType = System.Type;
using TMethod = System.Reflection.MethodBase;
using TProperty = System.Reflection.PropertyInfo;
using TField = System.Reflection.FieldInfo;
using R = ObjCRuntime.Runtime;
#endif
#if !(MTOUCH || MMP || BUNDLER)
using ProductException = ObjCRuntime.RuntimeException;
#endif
#if !MTOUCH && !MMP && !BUNDLER
// static registrar needs them but they might not be marked (e.g. if System.Console is not used)
[assembly: Preserve (typeof (System.Action))]
[assembly: Preserve (typeof (System.Action<string>))]
#endif
// Disable until we get around to enable + fix any issues.
#nullable disable
//
// This file cannot use any cecil code, since it's also compiled into Xamarin.[iOS|Mac].dll
//
#if MONOMAC
namespace ObjCRuntime {
public delegate void AssemblyRegistrationHandler (object sender, AssemblyRegistrationEventArgs args);
public class AssemblyRegistrationEventArgs : EventArgs {
public bool Register { get; set; }
public System.Reflection.AssemblyName AssemblyName { get; internal set; }
}
}
#endif
namespace Registrar {
static class Shared {
public static List<ProductException> GetMT4127 (TMethod impl, List<TMethod> ifaceMethods)
{
var exceptions = new List<ProductException> ();
exceptions.Add (ErrorHelper.CreateError (4127, Errors.MT4127, impl.DeclaringType.FullName, impl.Name));
for (int i = 0; i < ifaceMethods.Count; i++) {
var ifaceM = ifaceMethods [i];
exceptions.Add (ErrorHelper.CreateError (4137, Errors.MT4137, impl.DeclaringType.FullName, impl.Name, ifaceM.DeclaringType.FullName, ifaceM.Name));
}
return exceptions;
}
}
abstract partial class Registrar {
#if MTOUCH || MMP || BUNDLER
public Application App { get; protected set; }
#endif
#if MMP || MTOUCH || BUNDLER
static string NFloatTypeName { get => Driver.IsDotNet ? "System.Runtime.InteropServices.NFloat" : "System.nfloat"; }
#elif NET
const string NFloatTypeName = "System.Runtime.InteropServices.NFloat";
#else
const string NFloatTypeName = "System.nfloat";
#endif
Dictionary<TAssembly, object> assemblies = new Dictionary<TAssembly, object> (); // Use Dictionary instead of HashSet to avoid pulling in System.Core.dll.
// locking: all accesses must lock 'types'.
Dictionary<TType, ObjCType> types = new Dictionary<TType, ObjCType> ();
// this is used to check if multiple types are registered with the same name.
// locking: all accesses must lock 'type_map'.
Dictionary<string, TType> type_map = new Dictionary<string, TType> ();
// this is used to check if multiple protocols are registered with the same name.
// locking: all accesses must lock 'protocol_map'.
Dictionary<string, TType> protocol_map = new Dictionary<string, TType> ();
// this is used to check if multiple categories are registered with the same name.
// locking: all accesses must lock 'categories_map'.
Dictionary<string, TType> categories_map = new Dictionary<string, TType> ();
TMethod conforms_to_protocol;
TMethod invoke_conforms_to_protocol;
public IEnumerable<TAssembly> GetAssemblies ()
{
return assemblies.Keys;
}
internal class ObjCType {
public Registrar Registrar;
public RegisterAttribute RegisterAttribute;
public CategoryAttribute CategoryAttribute;
public TType Type;
public ObjCType BaseType;
// This only contains the leaf protocols implemented by this type.
public ObjCType [] Protocols;
public string [] AdoptedProtocols;
public bool IsModel;
// if this type represents an ObjC protocol (!= has the protocol attribute, since that can be applied to all kinds of things).
public bool IsProtocol;
public bool IsInformalProtocol;
public bool IsWrapper;
public bool IsGeneric;
#if !MTOUCH && !MMP && !BUNDLER
public IntPtr Handle;
#else
public TType ProtocolWrapperType;
public int ClassMapIndex;
#endif
public Dictionary<string, ObjCField> Fields;
public List<ObjCMethod> Methods;
public List<ObjCProperty> Properties;
Dictionary<string, ObjCMember> Map = new Dictionary<string, ObjCMember> ();
ObjCType superType;
public bool IsCategory { get { return CategoryAttribute is not null; } }
#if MTOUCH || MMP || BUNDLER
HashSet<ObjCType> all_protocols;
// This contains all protocols in the type hierarchy.
// Given a type T that implements a protocol with super protocols:
// class T : NSObject, IProtocol2 {}
// [Protocol]
// interface IP1 {}
// [Protocol]
// interface IP2 : IP1 {}
// This property will contain both IP1 and IP2. The Protocols property only contains IP2.
public IEnumerable<ObjCType> AllProtocols {
get {
if (Protocols is null || Protocols.Length == 0)
return null;
if (all_protocols is null) {
var queue = new Queue<ObjCType> (Protocols);
var rv = new HashSet<ObjCType> ();
while (queue.Count > 0) {
var type = queue.Dequeue ();
if (rv.Add (type)) {
foreach (var iface in type.Type.Resolve ().Interfaces) {
if (!Registrar.Types.TryGetValue (iface.InterfaceType, out var superIface)) {
// This is not an interface that corresponds to a protocol.
continue;
}
queue.Enqueue (superIface);
}
}
}
all_protocols = rv;
}
return all_protocols;
}
}
HashSet<ObjCType> all_protocols_in_hierarchy;
public IEnumerable<ObjCType> AllProtocolsInHierarchy {
get {
if (all_protocols_in_hierarchy is null) {
all_protocols_in_hierarchy = new HashSet<ObjCType> ();
var type = this;
while (type is not null && (object) type != (object) type.BaseType) {
var allProtocols = type.AllProtocols;
if (allProtocols is not null)
all_protocols_in_hierarchy.UnionWith (allProtocols);
type = type.BaseType;
}
}
return all_protocols_in_hierarchy;
}
}
#endif
public void VerifyRegisterAttribute (ref List<Exception> exceptions)
{
if (RegisterAttribute is null)
return;
var name = RegisterAttribute.Name;
if (string.IsNullOrEmpty (name))
return;
for (int i = 0; i < name.Length; i++) {
if (!char.IsWhiteSpace (name [i]))
continue;
// There is no Objective-C spec, and the C/C++ spec mentions "implementation-defined characters",
// so afaict there's no list of valid identifier characters. However we do know that whitespace
// is not allowed, so notify the developer about that. We're only emitting an error if we can detect
// that it's a name that will cause the static registrar output to fail to compile
// (currently if the whitespace is not at the start or end of the name), since otherwise it's
// a breaking change.
// See also bug #25441.
var showError = false;
var trimmedName = name.Trim (); // Trim removes any characters that returns true for 'char.IsWhiteSpace', so it matches our condition above
for (int k = 0; k < trimmedName.Length; k++) {
if (char.IsWhiteSpace (trimmedName [k])) {
showError = true;
break;
}
}
AddException (ref exceptions, new ProductException (4146, showError, Errors.MT4146, Registrar.GetTypeFullName (Type), name [i], ((int) name [i]).ToString ("x"), name));
break;
}
}
// This list is duplicated in tests/mtouch/RegistrarTest.cs.
// Update that list whenever this list is updated.
static readonly char [] invalidSelectorCharacters = { ' ', '\t', '?', '\\', '!', '|', '@', '"', '\'', '%', '&', '/', '(', ')', '=', '^', '[', ']', '{', '}', ',', '.', ';', '-', '\n', '<', '>' };
void VerifySelector (ObjCMethod method, ref List<Exception> exceptions)
{
if (method.Method is null)
return;
var split = method.Selector.Split (':');
var nativeParamCount = split.Length - 1;
if (method.IsVariadic)
nativeParamCount++;
var pars = method.Parameters;
var paramCount = pars is null ? 0 : pars.Length;
if (method.IsCategoryInstance)
paramCount--;
if (nativeParamCount != paramCount) {
Exception ex;
if (method.IsVariadic) {
ex = Registrar.CreateException (4140, method, Errors.MT4140,
method.Method.DeclaringType.FullName, method.MethodName, nativeParamCount, paramCount, method.Selector);
} else {
ex = Registrar.CreateException (4117, method, Errors.MT4117,
method.Method.DeclaringType.FullName, method.MethodName, nativeParamCount, paramCount, method.Selector);
}
Registrar.AddException (ref exceptions, ex);
}
if (method.IsVariadic && pars is not null && Registrar.GetTypeFullName (pars [paramCount - 1]) != "System.IntPtr")
Registrar.AddException (ref exceptions, Registrar.CreateException (4123, method, Errors.MT4123, Registrar.GetDescriptiveMethodName (method.Method)));
char ch;
var idx = method.Selector.IndexOfAny (invalidSelectorCharacters);
if (idx != -1) {
ch = method.Selector [idx];
Registrar.AddException (ref exceptions, Registrar.CreateException (4160, method, Errors.MT4160,
ch, ((int) ch).ToString ("x"), method.Selector, Registrar.GetTypeFullName (Type), Registrar.GetDescriptiveMethodName (method.Method)));
}
}
public void VerifyAdoptedProtocolsNames (ref List<Exception> exceptions)
{
if (AdoptedProtocols is null)
return;
foreach (var adoptedProtocol in AdoptedProtocols) {
// Tested all of the current 'invalidSelectorCharacters' for protocol names and all of them are invalid.
char ch;
var idx = adoptedProtocol.IndexOfAny (invalidSelectorCharacters);
var ap = adoptedProtocol;
if (idx != -1) {
ch = adoptedProtocol [idx];
var str = ch.ToString ();
if (ch == '{') {
str = "{{";
ap = ap.Insert (idx, "{");
} else if (ch == '}') {
str = "}}";
ap = ap.Insert (idx, "}");
}
var m4177 = String.Format (Errors.MT4177, Registrar.GetTypeFullName (Type), ap, str);
AddException (ref exceptions, new ProductException (4177, true, m4177, new string [0]));
}
}
}
public void Add (ObjCField field, ref List<Exception> exceptions)
{
// Check if there are any base types with the same property.
var base_type = BaseType;
var fieldNameInDictionary = (field.IsStatic ? "+" : "-") + field.Name;
while (base_type is not null) {
if (base_type.Fields is not null && base_type.Fields.ContainsKey (fieldNameInDictionary)) {
// Maybe we should warn here? Not sure if this is something bad or not.
return;
}
if (base_type == base_type.BaseType)
break;
base_type = base_type.BaseType;
}
if (Fields is null)
Fields = new Dictionary<string, ObjCField> ();
// Do fields and methods live in the same objc namespace? // AddToMap (field, errorIfExists);
Fields.Add (fieldNameInDictionary, field);
}
public bool Add (ObjCMethod method, ref List<Exception> exceptions)
{
bool rv;
if (Methods is null)
Methods = new List<ObjCMethod> ();
VerifySelector (method, ref exceptions);
method.ValidateSignature (ref exceptions);
// Protocol members don't show up in the generated output, so it doesn't matter if we run into those.
// If a class implements a protocol, it will still hit this check on the implemented members.
if (!method.IsPropertyAccessor && !method.DeclaringType.IsProtocol)
Registrar.VerifyInSdk (ref exceptions, method);
rv = AddToMap (method, ref exceptions, out var alreadyAdded);
if (!alreadyAdded)
Methods.Add (method);
return rv;
}
public void Add (ObjCProperty property, ref List<Exception> exceptions)
{
if (Properties is null)
Properties = new List<ObjCProperty> ();
// Do properties and methods live in the same objc namespace? // AddToMap (property, errorIfExists);
Properties.Add (property);
// Protocol members don't show up in the generated output, so it doesn't matter if we run into those.
// If a class implements a protocol, it will still hit this check on the implemented members.
if (!property.DeclaringType.IsProtocol)
Registrar.VerifyInSdk (ref exceptions, property);
VerifyIsNotKeyword (ref exceptions, property);
}
public static bool IsObjectiveCKeyword (string name)
{
switch (name) {
case "auto":
case "break":
case "case":
case "char":
case "const":
case "continue":
case "default":
case "do":
case "double":
case "else":
case "enum":
case "export":
case "extern":
case "float":
case "for":
case "goto":
case "if":
case "inline":
case "int":
case "long":
case "register":
case "restrict":
case "return":
case "short":
case "signed":
case "sizeof":
case "static":
case "struct":
case "switch":
case "template":
case "typedef":
case "union":
case "unsigned":
case "void":
case "volatile":
case "while":
case "_Bool":
case "_Complex":
case "_Imaginery":
return true;
default:
return false;
}
}
void VerifyIsNotKeyword (ref List<Exception> exceptions, ObjCProperty property)
{
if (IsObjectiveCKeyword (property.Selector))
AddException (ref exceptions, CreateException (4164, property, Errors.MT4164, property.Name, property.Selector));
}
public bool TryGetMember (string selector, bool is_static, out ObjCMember member)
{
if (is_static)
selector = "+" + selector;
else
selector = "-" + selector;
return Map.TryGetValue (selector, out member);
}
bool AddToMap (ObjCMember member, ref List<Exception> exceptions, out bool alreadyAdded)
{
ObjCMember existing;
bool rv = true;
alreadyAdded = false;
if (TryGetMember (member.Selector, member.IsNativeStatic, out existing)) {
if (existing is ObjCMethod existingMethod && member is ObjCMethod method && object.ReferenceEquals (method.Method, existingMethod.Method)) {
// This can happen if we try to register:
// * A property declared on a type (we register the getter + setter)
// * The getter or setter matches the signature of an exported method from a protocol interface, in which case we'll try to export again.
alreadyAdded = true;
return true;
}
if (existing.IsImplicit) {
AddException (ref exceptions, CreateException (4141, member, Errors.MT4141, member.Selector, Registrar.GetTypeFullName (Type), Registrar.GetMemberName (member)));
} else {
AddException (ref exceptions, CreateException (4119, member, Errors.MT4119, member.Selector, Registrar.GetTypeFullName (Type), Registrar.GetMemberName (member), Registrar.GetMemberName (existing)));
}
rv = false;
}
Map [(member.IsNativeStatic ? "+" : "-") + member.Selector] = member;
return rv;
}
Exception CreateException (int code, ObjCMember member, string message, params object [] args)
{
var method = member as ObjCMethod;
if (method is not null)
return Registrar.CreateException (code, method.Method, message, args);
var property = member as ObjCProperty;
if (property is not null && property.Property is not null)
return Registrar.CreateException (code, property.Property.GetMethod ?? property.Property.SetMethod, message, args);
return Registrar.CreateException (code, message, args);
}
public string Name {
get { return RegisterAttribute is not null && RegisterAttribute.Name is not null ? RegisterAttribute.Name : Registrar.GetTypeFullName (Type); }
}
public string CategoryName {
get {
if (!IsCategory)
throw new InvalidOperationException ();
var attrib = CategoryAttribute;
var name = attrib.Name ?? Registrar.GetTypeFullName (Type);
return SanitizeObjectiveCName (name);
}
}
public string ProtocolName {
get {
if (!IsProtocol)
throw new InvalidOperationException ();
var attrib = Registrar.GetProtocolAttribute (Type);
var name = attrib.Name ?? Registrar.GetTypeFullName (Type);
return SanitizeObjectiveCName (name);
}
}
public string ExportedName {
get {
return Registrar.GetExportedTypeName (Type, RegisterAttribute);
}
}
public bool IsFakeProtocol {
get {
if (RegisterAttribute is null || IsProtocol || IsModel)
return false;
return Registrar.HasProtocolAttribute (Type);
}
}
/// <summary>
/// This is the first parent type which is not a model.
/// </summary>
public ObjCType SuperType {
get {
if (superType is not null)
return superType;
var super = BaseType;
while (super is not null && (super.IsModel || super.IsFakeProtocol))
super = super.BaseType;
superType = super;
return superType;
}
}
}
abstract internal class ObjCMember {
public Registrar Registrar;
public ObjCType DeclaringType;
public string Name;
public ObjCType CategoryType;
public ArgumentSemantic ArgumentSemantic = ArgumentSemantic.None;
public bool IsVariadic;
public bool IsOptional;
public bool SetExportAttribute (ExportAttribute ea, ref List<Exception> exceptions)
{
if (string.IsNullOrEmpty (ea.Selector)) {
AddException (ref exceptions, Registrar.CreateException (4135, this, Errors.MT4135, FullName));
return false;
}
Selector = ea.Selector;
ArgumentSemantic = ea.ArgumentSemantic;
IsVariadic = ea.IsVariadic;
return true;
}
public ObjCMember ()
{
}
public ObjCMember (Registrar registrar, ObjCType declaringType)
{
Registrar = registrar;
DeclaringType = declaringType;
}
string selector;
public string Selector {
get { return selector; }
set {
if (string.IsNullOrEmpty (value))
throw Registrar.CreateException (4135, this, Errors.MT4135, FullName);
selector = value;
}
}
public abstract string FullName { get; }
public abstract bool IsNativeStatic { get; }
public virtual bool IsImplicit { get { return false; } }
protected string ToSignature (TType type, ref bool success)
{
return Registrar.ToSignature (type, this, ref success);
}
}
internal class ObjCMethod : ObjCMember {
public readonly TMethod Method;
string signature;
Trampoline trampoline;
bool? is_static;
bool? is_ctor;
TType [] parameters;
TType [] native_parameters;
TType return_type;
TType native_return_type;
public ObjCMethod (Registrar registrar, ObjCType declaringType, TMethod method)
: base (registrar, declaringType)
{
Method = method;
}
public string MethodName {
get {
return Name ?? Registrar.GetMethodName (Method);
}
}
public override bool IsImplicit {
get {
if (Method is not null)
return false;
switch (trampoline) {
case Trampoline.Release:
case Trampoline.Retain:
case Trampoline.GetGCHandle:
case Trampoline.SetGCHandle:
case Trampoline.GetFlags:
case Trampoline.SetFlags:
return true;
default:
return false;
}
}
}
public bool IsConstructor {
get {
if (!is_ctor.HasValue)
is_ctor = Registrar.IsConstructor (Method);
return is_ctor.Value;
}
set {
is_ctor = value;
}
}
#if !MMP && !MTOUCH && !BUNDLER
// The ArgumentSemantic enum is public, and
// I don't want to add another enum value there which
// is just an internal implementation detail, so just
// use a constant instead. Eventually we'll use an internal
// enum instead.
const int RetainReturnValueFlag = 1 << 10;
const int InstanceCategoryFlag = 1 << 11;
internal bool IsInstanceCategory {
get {
return DynamicRegistrar.HasThisAttributeImpl (Method);
}
}
internal void WriteUnmanagedDescription (IntPtr desc)
{
WriteUnmanagedDescription (desc, (System.Reflection.MethodBase) (object) Method);
}
internal void WriteUnmanagedDescription (IntPtr desc, System.Reflection.MethodBase method_base)
{
var semantic = ArgumentSemantic;
var minfo = method_base as System.Reflection.MethodInfo;
var retainReturnValue = minfo is not null && minfo.GetBaseDefinition ().ReturnTypeCustomAttributes.IsDefined (typeof (ReleaseAttribute), false);
var instanceCategory = minfo is not null && DynamicRegistrar.HasThisAttributeImpl (minfo);
// bitfields and a default value of -1 don't go very well together.
if (semantic == ArgumentSemantic.None)
semantic = ArgumentSemantic.Assign;
if (retainReturnValue)
semantic |= (ArgumentSemantic) (RetainReturnValueFlag);
if (instanceCategory)
semantic |= (ArgumentSemantic) (InstanceCategoryFlag);
var bindas_count = Marshal.ReadInt32 (desc + IntPtr.Size + 4);
if (bindas_count < 1 + Parameters.Length)
throw ErrorHelper.CreateError (8018, $"Internal consistency error: BindAs array is not big enough (expected at least {1 + parameters.Length} elements, got {bindas_count} elements) for {method_base.DeclaringType.FullName + "." + method_base.Name}. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new.");
Marshal.WriteIntPtr (desc, Runtime.AllocGCHandle (method_base));
Marshal.WriteInt32 (desc + IntPtr.Size, (int) semantic);
if (!IsConstructor && ReturnType != NativeReturnType)
Marshal.WriteIntPtr (desc + IntPtr.Size + 8, Runtime.AllocGCHandle (NativeReturnType));
for (int i = 0; i < NativeParameters.Length; i++) {
if (parameters [i] == native_parameters [i])
continue;
Marshal.WriteIntPtr (desc + IntPtr.Size + 8 + IntPtr.Size * (i + 1), Runtime.AllocGCHandle (native_parameters [i]));
}
}
#endif
public bool HasParameters {
get {
return parameters is not null;
}
}
public TType [] Parameters {
get {
if (parameters is null)
parameters = Registrar.GetParameters (Method);
return parameters;
}
set {
parameters = value;
native_parameters = null;
}
}
public TType [] NativeParameters {
get {
if (native_parameters is null && Parameters is not null) {
// Put the parameters in a temporary variable, and only store them in the instance field once done,
// so that if an exception occurs, the same exception will be raised the next time too.
var native_parameters = new TType [parameters.Length];
for (int i = 0; i < parameters.Length; i++) {
var originalType = Registrar.GetBindAsAttribute (this, i)?.OriginalType;
if (originalType is not null) {
if (!IsValidToManagedTypeConversion (originalType, parameters [i]))
throw Registrar.CreateException (4172, Method, Errors.MT4172, Registrar.GetTypeFullName (parameters [i]), originalType.FullName, Registrar.GetParameterName (Method, i), DescriptiveMethodName);
native_parameters [i] = originalType;
} else {
native_parameters [i] = parameters [i];
}
}
this.native_parameters = native_parameters;
}
return native_parameters;
}
}
bool IsValidToManagedTypeConversion (TType inputType, TType outputType)
{
var nullableType = Registrar.GetNullableType (outputType);
var isNullable = nullableType is not null;
var arrayRank = 0;
var isArray = Registrar.IsArray (outputType, out arrayRank);
TType underlyingOutputType = outputType;
TType underlyingInputType = inputType;
if (isNullable) {
underlyingOutputType = nullableType;
} else if (isArray) {
if (arrayRank != 1)
return false;
if (!Registrar.IsArray (inputType))
return false;
underlyingOutputType = Registrar.GetElementType (outputType);
underlyingInputType = Registrar.GetElementType (inputType);
}
var outputTypeName = Registrar.GetTypeFullName (underlyingOutputType);
if (Registrar.Is (underlyingInputType, Foundation, "NSNumber")) {
switch (outputTypeName) {
case "System.Byte":
case "System.SByte":
case "System.Int16":
case "System.UInt16":
case "System.Int32":
case "System.UInt32":
case "System.Int64":
case "System.UInt64":
case "System.IntPtr":
case "System.UIntPtr":
case "System.nint":
case "System.nuint":
case "System.Single":
case "System.Double":
case "System.Boolean":
return true;
default:
if (outputTypeName == NFloatTypeName)
return true;
return Registrar.IsEnum (underlyingOutputType);
}
} else if (Registrar.Is (underlyingInputType, Foundation, "NSValue")) {
switch (outputTypeName) {
case "CoreAnimation.CATransform3D":
case "CoreGraphics.CGAffineTransform":
case "CoreGraphics.CGPoint":
case "CoreGraphics.CGRect":
case "CoreGraphics.CGSize":
case "CoreGraphics.CGVector":
case "CoreLocation.CLLocationCoordinate2D":
case "CoreMedia.CMTime":
case "CoreMedia.CMTimeMapping":
case "CoreMedia.CMTimeRange":
case "CoreMedia.CMVideoDimensions":
case "MapKit.MKCoordinateSpan":
case "Foundation.NSRange":
case "SceneKit.SCNMatrix4":
case "SceneKit.SCNVector3":
case "SceneKit.SCNVector4":
case "UIKit.UIEdgeInsets":
case "UIKit.UIOffset":
case "UIKit.NSDirectionalEdgeInsets":
return true;
default:
return false;
}
} else if (Registrar.Is (underlyingInputType, Foundation, "NSString")) {
return Registrar.IsSmartEnum (underlyingOutputType);
} else {
return false;
}
}
bool IsValidToNativeTypeConversion (TType inputType, TType outputType)
{
return IsValidToManagedTypeConversion (inputType: outputType, outputType: inputType);
}
public bool HasReturnType {
get {
return return_type is not null;
}
}
public TType ReturnType {
get {
if (return_type is null)
return_type = Registrar.GetReturnType (Method);
return return_type;
}
set {
return_type = value;
native_return_type = null;
}
}
public TType NativeReturnType {
get {
if (native_return_type is null) {
if (Registrar.Is (ReturnType, "System", "Void")) {
native_return_type = ReturnType;
} else {
var originalType = Registrar.GetBindAsAttribute (this, -1)?.OriginalType;
if (originalType is not null) {
if (!IsValidToManagedTypeConversion (originalType, ReturnType))
throw Registrar.CreateException (4170, Method, Errors.MT4170, Registrar.GetTypeFullName (ReturnType), originalType.FullName, DescriptiveMethodName);
native_return_type = originalType;
} else {
native_return_type = ReturnType;
}
}
}
return native_return_type;
}
}
// If the managed method is static.
public bool IsStatic {
get { return is_static.HasValue ? is_static.Value : Registrar.IsStatic (Method); }
set { is_static = value; }
}
public override bool IsNativeStatic {
get {
return IsStatic && !IsCategoryInstance;
}
}
public bool IsCategoryInstance {
get {
return IsCategory && Registrar.HasThisAttribute (Method);
}
}
public bool IsCategory {
get { return CategoryType is not null; }
}
public bool RetainReturnValue {
get {
return Registrar.HasReleaseAttribute (Method);
}
}
public Trampoline CurrentTrampoline {
get {
return trampoline;
}
}
public Trampoline Trampoline {
get {
if (trampoline != Trampoline.None)
return trampoline;
#if MTOUCH || MMP || BUNDLER
throw ErrorHelper.CreateError (8018, Errors.MT8018);
#else
var mi = (System.Reflection.MethodInfo) Method;
bool is_stret;
#if __WATCHOS__
if (Runtime.Arch == Arch.DEVICE) {
is_stret = Stret.ArmNeedStret (NativeReturnType, null);
} else {
is_stret = IntPtr.Size == 4 ? Stret.X86NeedStret (NativeReturnType, null) : Stret.X86_64NeedStret (NativeReturnType, null);
}
#elif MONOMAC || __MACCATALYST__
if (Runtime.IsARM64CallingConvention) {
is_stret = false;
} else {
is_stret = Stret.X86_64NeedStret (NativeReturnType, null);
}
#elif __IOS__
if (Runtime.Arch == Arch.DEVICE) {
is_stret = false;
} else {
is_stret = Stret.X86_64NeedStret (NativeReturnType, null);
}
#elif __TVOS__
is_stret = Runtime.Arch == Arch.SIMULATOR && Stret.X86_64NeedStret (NativeReturnType, null);
#else
#error unknown architecture
#endif
var is_static_trampoline = IsStatic && !IsCategoryInstance;
var is_value_type = Registrar.IsValueType (NativeReturnType) && !Registrar.IsEnum (NativeReturnType);
if (is_value_type && Registrar.IsGenericType (NativeReturnType))
throw Registrar.CreateException (4104, Method, "The registrar cannot marshal the return value of type `{0}` in the method `{1}.{2}`.", Registrar.GetTypeFullName (NativeReturnType), Registrar.GetTypeFullName (DeclaringType.Type), Registrar.GetDescriptiveMethodName (Method));
if (is_stret) {
if (Registrar.IsSimulatorOrDesktop && !Registrar.Is64Bits) {
trampoline = is_static_trampoline ? Trampoline.X86_DoubleABI_StaticStretTrampoline : Trampoline.X86_DoubleABI_StretTrampoline;
} else {
trampoline = is_static_trampoline ? Trampoline.StaticStret : Trampoline.Stret;
}
} else {
switch (Signature [0]) {
case 'Q':
case 'q':
trampoline = is_static_trampoline ? Trampoline.StaticLong : Trampoline.Long;
break;
case 'f':
trampoline = is_static_trampoline ? Trampoline.StaticSingle : Trampoline.Single;
break;
case 'd':
trampoline = is_static_trampoline ? Trampoline.StaticDouble : Trampoline.Double;
break;
default:
trampoline = is_static_trampoline ? Trampoline.Static : Trampoline.Normal;
break;
}
}
return trampoline;
#endif
}
set {
trampoline = value;
}
}
public string Signature {
get {
if (signature is null)
signature = ComputeSignature ();
return signature;
}
set {
signature = value;
}
}
public bool ValidateSignature (ref List<Exception> exceptions)
{
if (Registrar.LaxMode)
return true;
if (signature is null) {
try {
signature = ComputeSignature ();
} catch (ProductException mte) {
AddException (ref exceptions, mte);
return false;
}
}
return true;
}
string ComputeSignature ()
{
return Registrar.ComputeSignature (DeclaringType.Type, null, this, IsCategoryInstance);
}
public override string ToString ()
{
return string.Format ("[ObjCMethod: Name={0}, IsStatic={1}, Trampoline={2}, Signature={3}]", Method is not null ? Registrar.GetMethodName (Method) : "null", IsStatic, Trampoline, ""); //Signature);
}
public string DescriptiveMethodName {
get {
return Registrar.GetTypeFullName (DeclaringType.Type) + "." + (Method is null ? Name : Registrar.GetMethodName (Method));
}
}
public override string FullName {
get {
return DescriptiveMethodName;
}
}
public bool IsPropertyAccessor {
get {
return Registrar.IsPropertyAccessor (Method);
}
}