-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathWinRT.cs
1215 lines (1084 loc) · 47.3 KB
/
WinRT.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using WinRT.Interop;
#pragma warning disable 0169 // The field 'xxx' is never used
#pragma warning disable 0649 // Field 'xxx' is never assigned to, and will always have its default value
#pragma warning disable CA1060
namespace WinRT
{
internal static class DelegateExtensions
{
public static void DynamicInvokeAbi(this System.Delegate del, object[] invoke_params)
{
Marshal.ThrowExceptionForHR((int)del.DynamicInvoke(invoke_params));
}
}
internal sealed class Platform
{
[DllImport("api-ms-win-core-com-l1-1-0.dll")]
internal static extern unsafe int CoCreateInstance(Guid* clsid, IntPtr outer, uint clsContext, Guid* iid, IntPtr* instance);
internal static unsafe int CoCreateInstance(ref Guid clsid, IntPtr outer, uint clsContext, ref Guid iid, IntPtr* instance)
{
fixed (Guid* lpClsid = &clsid)
{
fixed (Guid* lpIid = &iid)
{
return CoCreateInstance(lpClsid, outer, clsContext, lpIid, instance);
}
}
}
[DllImport("api-ms-win-core-com-l1-1-0.dll")]
internal static extern int CoDecrementMTAUsage(IntPtr cookie);
[DllImport("api-ms-win-core-com-l1-1-0.dll")]
internal static extern unsafe int CoIncrementMTAUsage(IntPtr* cookie);
#if NET6_0_OR_GREATER
internal static bool FreeLibrary(IntPtr moduleHandle)
{
int lastError;
bool returnValue;
int nativeReturnValue;
{
Marshal.SetLastSystemError(0);
nativeReturnValue = PInvoke(moduleHandle);
lastError = Marshal.GetLastSystemError();
}
// Unmarshal - Convert native data to managed data.
returnValue = nativeReturnValue != 0;
Marshal.SetLastPInvokeError(lastError);
return returnValue;
// Local P/Invoke
[DllImportAttribute("kernel32.dll", EntryPoint = "FreeLibrary", ExactSpelling = true)]
static extern unsafe int PInvoke(IntPtr nativeModuleHandle);
}
internal static unsafe void* TryGetProcAddress(IntPtr moduleHandle, sbyte* functionName)
{
int lastError;
void* returnValue;
{
Marshal.SetLastSystemError(0);
returnValue = PInvoke(moduleHandle, functionName);
lastError = Marshal.GetLastSystemError();
}
Marshal.SetLastPInvokeError(lastError);
return returnValue;
// Local P/Invoke
[DllImportAttribute("kernel32.dll", EntryPoint = "GetProcAddress", ExactSpelling = true)]
static extern unsafe void* PInvoke(IntPtr nativeModuleHandle, sbyte* nativeFunctionName);
}
#else
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FreeLibrary(IntPtr moduleHandle);
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress", SetLastError = true, BestFitMapping = false)]
internal static unsafe extern void* TryGetProcAddress(IntPtr moduleHandle, sbyte* functionName);
#endif
internal static unsafe void* TryGetProcAddress(IntPtr moduleHandle, ReadOnlySpan<byte> functionName)
{
fixed (byte* lpFunctionName = functionName)
{
return TryGetProcAddress(moduleHandle, (sbyte*)lpFunctionName);
}
}
internal static unsafe void* TryGetProcAddress(IntPtr moduleHandle, string functionName)
{
bool allocated = false;
Span<byte> buffer = stackalloc byte[0x100];
if (functionName.Length * 3 >= 0x100) // Maximum of 3 bytes per UTF-8 character, stack allocation limit of 256 bytes (including the null terminator)
{
// Calculate accurate byte count when the provided stack-allocated buffer is not sufficient
int exactByteCount = checked(Encoding.UTF8.GetByteCount(functionName) + 1); // + 1 for null terminator
if (exactByteCount > 0x100)
{
#if NET6_0_OR_GREATER
buffer = new((byte*)NativeMemory.Alloc((nuint)exactByteCount), exactByteCount);
#else
buffer = new((byte*)Marshal.AllocHGlobal(exactByteCount), exactByteCount);
#endif
allocated = true;
}
}
var rawByte = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer));
int byteCount;
#if NET
byteCount = Encoding.UTF8.GetBytes(functionName, buffer);
#else
fixed (char* lpFunctionName = functionName)
{
byteCount = Encoding.UTF8.GetBytes(lpFunctionName, functionName.Length, rawByte, buffer.Length);
}
#endif
buffer[byteCount] = 0;
void* functionPtr = TryGetProcAddress(moduleHandle, (sbyte*)rawByte);
if (allocated)
#if NET6_0_OR_GREATER
NativeMemory.Free(rawByte);
#else
Marshal.FreeHGlobal((IntPtr)rawByte);
#endif
return functionPtr;
}
internal static unsafe void* GetProcAddress(IntPtr moduleHandle, ReadOnlySpan<byte> functionName)
{
fixed (byte* lpFunctionName = functionName)
{
void* functionPtr = Platform.TryGetProcAddress(moduleHandle, (sbyte*)lpFunctionName);
if (functionPtr == null)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error(), new IntPtr(-1));
}
return functionPtr;
}
}
internal static unsafe void* GetProcAddress(IntPtr moduleHandle, string functionName)
{
void* functionPtr = Platform.TryGetProcAddress(moduleHandle, functionName);
if (functionPtr == null)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error(), new IntPtr(-1));
}
return functionPtr;
}
#if NET6_0_OR_GREATER
internal static unsafe IntPtr LoadLibraryExW(ushort* fileName, IntPtr fileHandle, uint flags)
{
int lastError;
IntPtr returnValue;
{
Marshal.SetLastSystemError(0);
returnValue = PInvoke(fileName, fileHandle, flags);
lastError = Marshal.GetLastSystemError();
}
Marshal.SetLastPInvokeError(lastError);
return returnValue;
// Local P/Invoke
[DllImportAttribute("kernel32.dll", EntryPoint = "LoadLibraryExW", ExactSpelling = true)]
static extern unsafe IntPtr PInvoke(ushort* nativeFileName, IntPtr nativeFileHandle, uint nativeFlags);
}
#else
[DllImport("kernel32.dll", SetLastError = true)]
internal static unsafe extern IntPtr LoadLibraryExW(ushort* fileName, IntPtr fileHandle, uint flags);
#endif
internal static unsafe IntPtr LoadLibraryExW(string fileName, IntPtr fileHandle, uint flags)
{
fixed (char* lpFileName = fileName)
return LoadLibraryExW((ushort*)lpFileName, fileHandle, flags);
}
[DllImport("api-ms-win-core-winrt-l1-1-0.dll")]
internal static extern unsafe int RoGetActivationFactory(IntPtr runtimeClassId, Guid* iid, IntPtr* factory);
internal static unsafe int RoGetActivationFactory(IntPtr runtimeClassId, ref Guid iid, IntPtr* factory)
{
fixed (Guid* lpIid = &iid)
{
return RoGetActivationFactory(runtimeClassId, lpIid, factory);
}
}
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern unsafe int WindowsCreateString(ushort* sourceString,
int length,
IntPtr* hstring);
internal static unsafe int WindowsCreateString(string sourceString, int length, IntPtr* hstring)
{
fixed (char* lpSourceString = sourceString)
{
return WindowsCreateString((ushort*)lpSourceString, length, hstring);
}
}
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern unsafe int WindowsCreateStringReference(ushort* sourceString,
int length,
IntPtr* hstring_header,
IntPtr* hstring);
internal static unsafe int WindowsCreateStringReference(char* sourceString, int length, IntPtr* hstring_header, IntPtr* hstring)
{
return WindowsCreateStringReference((ushort*)sourceString, length, hstring_header, hstring);
}
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern int WindowsDeleteString(IntPtr hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern unsafe int WindowsDuplicateString(IntPtr sourceString,
IntPtr* hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern unsafe char* WindowsGetStringRawBuffer(IntPtr hstring, uint* length);
[DllImport("api-ms-win-core-com-l1-1-1.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern unsafe int RoGetAgileReference(uint options, Guid* iid, IntPtr unknown, IntPtr* agileReference);
internal static unsafe int RoGetAgileReference(uint options, ref Guid iid, IntPtr unknown, IntPtr* agileReference)
{
fixed (Guid* lpIid = &iid)
{
return RoGetAgileReference(options, lpIid, unknown, agileReference);
}
}
}
internal struct VftblPtr
{
public IntPtr Vftbl;
}
internal static partial class Context
{
[DllImport("api-ms-win-core-com-l1-1-0.dll")]
private static extern unsafe int CoGetContextToken(IntPtr* contextToken);
public unsafe static IntPtr GetContextToken()
{
IntPtr contextToken;
Marshal.ThrowExceptionForHR(CoGetContextToken(&contextToken));
return contextToken;
}
}
internal unsafe sealed class DllModule
{
readonly string _fileName;
readonly IntPtr _moduleHandle;
readonly delegate* unmanaged[Stdcall]<IntPtr, IntPtr*, int> _GetActivationFactory;
readonly delegate* unmanaged[Stdcall]<int> _CanUnloadNow; // TODO: Eventually periodically call
static readonly string _currentModuleDirectory = AppContext.BaseDirectory;
static Dictionary<string, DllModule> _cache = new System.Collections.Generic.Dictionary<string, DllModule>(StringComparer.Ordinal);
public static bool TryLoad(string fileName, out DllModule module)
{
lock (_cache)
{
if (_cache.TryGetValue(fileName, out module))
{
return true;
}
else if (TryCreate(fileName, out module))
{
_cache[fileName] = module;
return true;
}
return false;
}
}
private static unsafe bool TryCreate(string fileName, out DllModule module)
{
// Explicitly look for module in the same directory as this one, and
// use altered search path to ensure any dependencies in the same directory are found.
IntPtr moduleHandle = IntPtr.Zero;
moduleHandle = Platform.LoadLibraryExW(System.IO.Path.Combine(_currentModuleDirectory, fileName), IntPtr.Zero, /* LOAD_WITH_ALTERED_SEARCH_PATH */ 8);
#if NET
if (moduleHandle == IntPtr.Zero)
{
NativeLibrary.TryLoad(fileName, Assembly.GetExecutingAssembly(), null, out moduleHandle);
}
#endif
if (moduleHandle == IntPtr.Zero)
{
module = null;
return false;
}
void* getActivationFactory = null;
#if NET7_0_OR_GREATER || CsWinRT_LANG_11_FEATURES
ReadOnlySpan<byte> functionName = "DllGetActivationFactory"u8;
#else
string functionName = "DllGetActivationFactory";
#endif
getActivationFactory = Platform.TryGetProcAddress(moduleHandle, functionName);
if (getActivationFactory == null)
{
module = null;
return false;
}
module = new DllModule(
fileName,
moduleHandle,
getActivationFactory);
return true;
}
private DllModule(string fileName, IntPtr moduleHandle, void* getActivationFactory)
{
_fileName = fileName;
_moduleHandle = moduleHandle;
_GetActivationFactory = (delegate* unmanaged[Stdcall]<IntPtr, IntPtr*, int>)getActivationFactory;
void* canUnloadNow = null;
#if NET7_0_OR_GREATER || CsWinRT_LANG_11_FEATURES
ReadOnlySpan<byte> functionName = "DllCanUnloadNow"u8;
#else
string functionName = "DllCanUnloadNow";
#endif
canUnloadNow = Platform.TryGetProcAddress(_moduleHandle, functionName);
if (canUnloadNow != null)
{
_CanUnloadNow = (delegate* unmanaged[Stdcall]<int>)canUnloadNow;
}
}
public unsafe (FactoryObjectReference<IActivationFactoryVftbl> obj, int hr) GetActivationFactory(string runtimeClassId)
{
IntPtr instancePtr = IntPtr.Zero;
try
{
MarshalString.Pinnable __runtimeClassId = new(runtimeClassId);
fixed (void* ___runtimeClassId = __runtimeClassId)
{
int hr = _GetActivationFactory(MarshalString.GetAbi(ref __runtimeClassId), &instancePtr);
if (hr == 0)
{
var objRef = FactoryObjectReference<IActivationFactoryVftbl>.Attach(ref instancePtr);
return (objRef, hr);
}
else
{
return (null, hr);
}
}
}
finally
{
MarshalInspectable<object>.DisposeAbi(instancePtr);
}
}
~DllModule()
{
System.Diagnostics.Debug.Assert(_CanUnloadNow == null || _CanUnloadNow() == 0); // S_OK
lock (_cache)
{
_cache.Remove(_fileName);
}
if ((_moduleHandle != IntPtr.Zero) && !Platform.FreeLibrary(_moduleHandle))
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
}
internal sealed class WinrtModule
{
readonly IntPtr _mtaCookie;
volatile static WinrtModule _instance;
private static WinrtModule MakeWinRTModule()
{
global::System.Threading.Interlocked.CompareExchange(ref _instance, new WinrtModule(), null);
return _instance;
}
public static WinrtModule Instance => _instance ?? MakeWinRTModule();
public unsafe WinrtModule()
{
IntPtr mtaCookie;
Marshal.ThrowExceptionForHR(Platform.CoIncrementMTAUsage(&mtaCookie));
_mtaCookie = mtaCookie;
}
public static unsafe (FactoryObjectReference<I> obj, int hr) GetActivationFactory<I>(string runtimeClassId, Guid iid)
{
var module = Instance; // Ensure COM is initialized
IntPtr instancePtr = IntPtr.Zero;
try
{
MarshalString.Pinnable __runtimeClassId = new(runtimeClassId);
fixed (void* ___runtimeClassId = __runtimeClassId)
{
int hr = Platform.RoGetActivationFactory(MarshalString.GetAbi(ref __runtimeClassId), &iid, &instancePtr);
if (hr == 0)
{
var objRef = FactoryObjectReference<I>.Attach(ref instancePtr);
return (objRef, hr);
}
else
{
return (null, hr);
}
}
}
finally
{
MarshalInspectable<object>.DisposeAbi(instancePtr);
}
}
~WinrtModule()
{
Marshal.ThrowExceptionForHR(Platform.CoDecrementMTAUsage(_mtaCookie));
}
}
internal sealed class FactoryObjectReference<
#if NET
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)]
#endif
T> : IObjectReference
{
private readonly IntPtr _contextToken;
public static FactoryObjectReference<T> Attach(ref IntPtr thisPtr)
{
if (thisPtr == IntPtr.Zero)
{
return null;
}
var obj = new FactoryObjectReference<T>(thisPtr);
thisPtr = IntPtr.Zero;
return obj;
}
internal FactoryObjectReference(IntPtr thisPtr) :
base(thisPtr)
{
if (!IsFreeThreaded(this))
{
_contextToken = Context.GetContextToken();
}
}
internal FactoryObjectReference(IntPtr thisPtr, IntPtr contextToken)
: base(thisPtr)
{
_contextToken = contextToken;
}
public static new unsafe FactoryObjectReference<T> FromAbi(IntPtr thisPtr)
{
if (thisPtr == IntPtr.Zero)
{
return null;
}
var obj = new FactoryObjectReference<T>(thisPtr);
obj.VftblIUnknown.AddRef(obj.ThisPtr);
return obj;
}
public bool IsObjectInContext()
{
return _contextToken == IntPtr.Zero || _contextToken == Context.GetContextToken();
}
// If we are free threaded, we do not need to keep track of context.
// This can either be if the object implements IAgileObject or the free threaded marshaler.
// We only check IAgileObject for now as the necessary code to check the
// free threaded marshaler is not exposed from WinRT.Runtime.
private unsafe static bool IsFreeThreaded(IObjectReference objRef)
{
if (objRef.TryAs(InterfaceIIDs.IAgileObject_IID, out var agilePtr) >= 0)
{
Marshal.Release(agilePtr);
return true;
}
return false;
}
}
internal static class IActivationFactoryMethods
{
public static unsafe ObjectReference<I> ActivateInstance<I>(IObjectReference obj)
{
IntPtr instancePtr;
global::WinRT.ExceptionHelpers.ThrowExceptionForHR((*(delegate* unmanaged[Stdcall]<IntPtr, IntPtr*, int>**)obj.ThisPtr)[6](obj.ThisPtr, &instancePtr));
try
{
return ComWrappersSupport.GetObjectReferenceForInterface<I>(instancePtr);
}
finally
{
MarshalInspectable<object>.DisposeAbi(instancePtr);
}
}
}
internal static class ActivationFactory
{
public static FactoryObjectReference<IActivationFactoryVftbl> Get(string typeName)
{
// Prefer the RoGetActivationFactory HRESULT failure over the LoadLibrary/etc. failure
int hr;
FactoryObjectReference<IActivationFactoryVftbl> factory;
(factory, hr) = WinrtModule.GetActivationFactory<IActivationFactoryVftbl>(typeName, InterfaceIIDs.IActivationFactory_IID);
if (factory != null)
{
return factory;
}
var moduleName = typeName;
while (true)
{
var lastSegment = moduleName.LastIndexOf(".", StringComparison.Ordinal);
if (lastSegment <= 0)
{
Marshal.ThrowExceptionForHR(hr);
}
moduleName = moduleName.Remove(lastSegment);
DllModule module = null;
if (DllModule.TryLoad(moduleName + ".dll", out module))
{
(factory, hr) = module.GetActivationFactory(typeName);
if (factory != null)
{
return factory;
}
}
}
}
#if NET
public static FactoryObjectReference<I> Get<
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicFields)]
#else
public static ObjectReference<I> Get<
#endif
I>(string typeName, Guid iid)
{
// Prefer the RoGetActivationFactory HRESULT failure over the LoadLibrary/etc. failure
int hr;
FactoryObjectReference<I> factory;
(factory, hr) = WinrtModule.GetActivationFactory<I>(typeName, iid);
if (factory != null)
{
#if NET
return factory;
#else
using (factory)
{
return factory.As<I>(iid);
}
#endif
}
var moduleName = typeName;
while (true)
{
var lastSegment = moduleName.LastIndexOf(".", StringComparison.Ordinal);
if (lastSegment <= 0)
{
Marshal.ThrowExceptionForHR(hr);
}
moduleName = moduleName.Remove(lastSegment);
DllModule module = null;
if (DllModule.TryLoad(moduleName + ".dll", out module))
{
FactoryObjectReference<IActivationFactoryVftbl> activationFactory;
(activationFactory, hr) = module.GetActivationFactory(typeName);
if (activationFactory != null)
{
using (activationFactory)
{
#if NET
if (activationFactory.TryAs(iid, out IntPtr iidPtr) >= 0)
{
return FactoryObjectReference<I>.Attach(ref iidPtr);
}
#else
return activationFactory.As<I>(iid);
#endif
}
}
}
}
}
}
internal class ComponentActivationFactory : global::WinRT.Interop.IActivationFactory
{
public IntPtr ActivateInstance()
{
throw new NotImplementedException();
}
}
internal class ActivatableComponentActivationFactory<T> : ComponentActivationFactory, global::WinRT.Interop.IActivationFactory where T : class, new()
{
public new IntPtr ActivateInstance()
{
T comp = new T();
return MarshalInspectable<T>.FromManaged(comp);
}
}
#pragma warning disable CA2002
// Registration state and delegate cached separately to survive EventSource garbage collection
// and to prevent the generated event delegate from impacting the lifetime of the
// event source.
internal abstract class State : IDisposable
{
public EventRegistrationToken token;
public System.Delegate del;
public System.Delegate eventInvoke;
private bool disposedValue;
private readonly IntPtr obj;
private readonly int index;
private readonly System.WeakReference<State> cacheEntry;
private IntPtr eventInvokePtr;
private IntPtr referenceTrackerTargetPtr;
protected State(IntPtr obj, int index)
{
this.obj = obj;
this.index = index;
eventInvoke = GetEventInvoke();
cacheEntry = new System.WeakReference<State>(this);
}
// The lifetime of this object is managed by the delegate / eventInvoke
// through its target reference to it. Once the delegate no longer has
// any references, this object will also no longer have any references.
~State()
{
Dispose(false);
}
// Allows to retrieve a singleton like weak reference to use
// with the cache to allow for proper removal with comparision.
public System.WeakReference<State> GetWeakReferenceForCache()
{
return cacheEntry;
}
protected abstract System.Delegate GetEventInvoke();
protected virtual void Dispose(bool disposing)
{
// Uses the dispose pattern to ensure we only remove
// from the cache once: either via unsubscribe or via
// the finalizer.
if (!disposedValue)
{
Cache.Remove(obj, index, cacheEntry);
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void InitalizeReferenceTracking(IntPtr ptr)
{
eventInvokePtr = ptr;
Guid iid = IReferenceTrackerTargetVftbl.IID;
int hr = Marshal.QueryInterface(ptr, ref iid, out referenceTrackerTargetPtr);
if (hr != 0)
{
referenceTrackerTargetPtr = default;
}
else
{
// We don't want to keep ourselves alive and as long as this object
// is alive, the CCW still exists.
Marshal.Release(referenceTrackerTargetPtr);
}
}
public unsafe bool HasComReferences()
{
if (eventInvokePtr != default)
{
IUnknownVftbl vftblIUnknown = **(IUnknownVftbl**)eventInvokePtr;
vftblIUnknown.AddRef(eventInvokePtr);
uint comRefCount = vftblIUnknown.Release(eventInvokePtr);
if (comRefCount != 0)
{
return true;
}
}
if (referenceTrackerTargetPtr != default)
{
IReferenceTrackerTargetVftbl vftblReferenceTracker = **(IReferenceTrackerTargetVftbl**)referenceTrackerTargetPtr;
vftblReferenceTracker.AddRefFromReferenceTracker(referenceTrackerTargetPtr);
uint refTrackerCount = vftblReferenceTracker.ReleaseFromReferenceTracker(referenceTrackerTargetPtr);
if (refTrackerCount != 0)
{
// Note we can't tell if the reference tracker ref is pegged or not, so this is best effort where if there
// are any reference tracker references, we assume the event has references.
return true;
}
}
return false;
}
}
internal sealed class Cache
{
private Cache(IWeakReference target, int index, System.WeakReference<State> state)
{
this.target = target;
SetState(index, state);
}
private IWeakReference target;
private readonly ConcurrentDictionary<int, System.WeakReference<State>> states = new ConcurrentDictionary<int, System.WeakReference<State>>();
private static readonly ReaderWriterLockSlim cachesLock = new ReaderWriterLockSlim();
private static readonly ConcurrentDictionary<IntPtr, Cache> caches = new ConcurrentDictionary<IntPtr, Cache>();
private Cache Update(IWeakReference target, int index, System.WeakReference<State> state)
{
// If target no longer exists, destroy cache
lock (this)
{
using var resolved = this.target.Resolve(InterfaceIIDs.IUnknown_IID);
if (resolved == null)
{
this.target = target;
states.Clear();
}
}
SetState(index, state);
return this;
}
private System.WeakReference<State> GetState(int index)
{
// If target no longer exists, destroy cache
lock (this)
{
using var resolved = this.target.Resolve(InterfaceIIDs.IUnknown_IID);
if (resolved == null)
{
return null;
}
}
if (states.TryGetValue(index, out var weakState))
{
return weakState;
}
return null;
}
private void SetState(int index, System.WeakReference<State> state)
{
states[index] = state;
}
public static void Create(IObjectReference obj, int index, System.WeakReference<State> state)
{
// If event source implements weak reference support, track event registrations so that
// unsubscribes will work across garbage collections. Note that most static/factory classes
// do not implement IWeakReferenceSource, so static codegen caching approach is also used.
IWeakReference target = null;
#if !NET
try
{
var weakRefSource = (IWeakReferenceSource)typeof(IWeakReferenceSource).GetHelperType().GetConstructor(new[] { typeof(IObjectReference) }).Invoke(new object[] { obj });
if (weakRefSource == null)
{
return;
}
target = weakRefSource.GetWeakReference();
}
catch(Exception)
{
return;
}
#else
int hr = obj.TryAs<IUnknownVftbl>(InterfaceIIDs.IWeakReferenceSource_IID, out var weakRefSource);
if (hr != 0)
{
return;
}
target = ABI.WinRT.Interop.IWeakReferenceSourceMethods.GetWeakReference(weakRefSource);
#endif
cachesLock.EnterReadLock();
try
{
caches.AddOrUpdate(obj.ThisPtr,
(IntPtr ThisPtr) => new Cache(target, index, state),
(IntPtr ThisPtr, Cache cache) => cache.Update(target, index, state));
}
finally
{
cachesLock.ExitReadLock();
}
}
public static System.WeakReference<State> GetState(IObjectReference obj, int index)
{
if (caches.TryGetValue(obj.ThisPtr, out var cache))
{
return cache.GetState(index);
}
return null;
}
public static void Remove(IntPtr thisPtr, int index, System.WeakReference<State> state)
{
if (caches.TryGetValue(thisPtr, out var cache))
{
#if !NET
// https://devblogs.microsoft.com/pfxteam/little-known-gems-atomic-conditional-removals-from-concurrentdictionary/
((ICollection<KeyValuePair<int, System.WeakReference<State>>>)cache.states).Remove(
new KeyValuePair<int, System.WeakReference<State>>(index, state));
#else
cache.states.TryRemove(new KeyValuePair<int, System.WeakReference<State>>(index, state));
#endif
// using double-checked lock idiom
if (cache.states.IsEmpty)
{
cachesLock.EnterWriteLock();
try
{
if (cache.states.IsEmpty)
{
caches.TryRemove(thisPtr, out var _);
}
}
finally
{
cachesLock.ExitWriteLock();
}
}
}
}
}
internal unsafe abstract class EventSource<TDelegate>
where TDelegate : class, MulticastDelegate
{
protected readonly IObjectReference _obj;
protected readonly int _index;
#if NET
readonly delegate* unmanaged[Stdcall]<System.IntPtr, System.IntPtr, WinRT.EventRegistrationToken*, int> _addHandler;
#else
readonly delegate* unmanaged[Stdcall]<System.IntPtr, System.IntPtr, out WinRT.EventRegistrationToken, int> _addHandler;
#endif
readonly delegate* unmanaged[Stdcall]<System.IntPtr, WinRT.EventRegistrationToken, int> _removeHandler;
protected System.WeakReference<State> _state;
private readonly (Action<TDelegate>, Action<TDelegate>) _handlerTuple;
protected EventSource(IObjectReference obj,
#if NET
delegate* unmanaged[Stdcall]<System.IntPtr, System.IntPtr, WinRT.EventRegistrationToken*, int> addHandler,
#else
delegate* unmanaged[Stdcall]<System.IntPtr, System.IntPtr, out WinRT.EventRegistrationToken, int> addHandler,
#endif
delegate* unmanaged[Stdcall]<System.IntPtr, WinRT.EventRegistrationToken, int> removeHandler,
int index = 0)
{
_obj = obj;
_addHandler = addHandler;
_removeHandler = removeHandler;
_index = index;
_state = Cache.GetState(obj, index);
_handlerTuple = (Subscribe, Unsubscribe);
}
protected abstract ObjectReferenceValue CreateMarshaler(TDelegate del);
protected abstract State CreateEventState();
public void Subscribe(TDelegate del)
{
lock (this)
{
State state = null;
bool registerHandler =
_state is null ||
!_state.TryGetTarget(out state) ||
// We have a wrapper delegate, but no longer has any references from any event source.
!state.HasComReferences();
if (registerHandler)
{
state = CreateEventState();
_state = state.GetWeakReferenceForCache();
Cache.Create(_obj, _index, _state);
}
state.del = (TDelegate)global::System.Delegate.Combine(state.del, del);
if (registerHandler)
{
var eventInvoke = (TDelegate)state.eventInvoke;
var marshaler = CreateMarshaler(eventInvoke);
try
{
var nativeDelegate = marshaler.GetAbi();
state.InitalizeReferenceTracking(nativeDelegate);
#if NET
WinRT.EventRegistrationToken token;
ExceptionHelpers.ThrowExceptionForHR(_addHandler(_obj.ThisPtr, nativeDelegate, &token));
state.token = token;
#else
ExceptionHelpers.ThrowExceptionForHR(_addHandler(_obj.ThisPtr, nativeDelegate, out state.token));
#endif
}
finally
{
// Dispose our managed reference to the delegate's CCW.
// Either the native event holds a reference now or the _addHandler call failed.
marshaler.Dispose();
}
}
}
}
public void Unsubscribe(TDelegate del)
{
if (_state is null || !_state.TryGetTarget(out var state))
{
return;
}
lock (this)
{
var oldEvent = state.del;
state.del = (TDelegate)global::System.Delegate.Remove(state.del, del);
if (oldEvent is object && state.del is null)
{
UnsubscribeFromNative(state);
}
}
}
public (Action<TDelegate>, Action<TDelegate>) EventActions => _handlerTuple;
private void UnsubscribeFromNative(State state)
{
ExceptionHelpers.ThrowExceptionForHR(_removeHandler(_obj.ThisPtr, state.token));
state.Dispose();
_state = null;
}
}
internal unsafe sealed class EventSource__EventHandler<T> : EventSource<System.EventHandler<T>>