-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStableAbiModule.cs
More file actions
1013 lines (874 loc) · 31.5 KB
/
Copy pathStableAbiModule.cs
File metadata and controls
1013 lines (874 loc) · 31.5 KB
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
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace DotPython.Runtime.Native;
internal sealed class StableAbiModule : IDisposable
{
private const int MaximumGenericObjects = 8192;
private readonly nint _bridgeLibrary;
private readonly nint _moduleLibrary;
private readonly nint _module;
private readonly ModuleDestroy _destroy;
private readonly ErrorText _errorType;
private readonly ErrorText _errorMessage;
private readonly ActiveObjectCount _activeObjectCount;
private readonly long _initializedObjectCount;
private readonly long _activeObjectBaseline;
private readonly int _expectedCleanupCount;
private readonly bool _releaseLibraries;
private readonly CleanupCount? _cleanupCount;
private readonly GenericBridgeApi _generic;
private readonly List<nint> _genericObjects = [];
private readonly object _gate = new();
private int _disposed;
private StableAbiModule(
nint bridgeLibrary,
nint moduleLibrary,
nint module,
StableAbiSymbolManifest manifest,
bool multiPhase,
ModuleDestroy destroy,
ErrorText errorType,
ErrorText errorMessage,
ActiveObjectCount activeObjectCount,
long initializedObjectCount,
long activeObjectBaseline,
int expectedCleanupCount,
bool releaseLibraries,
CleanupCount? cleanupCount,
GenericBridgeApi generic
)
{
_bridgeLibrary = bridgeLibrary;
_moduleLibrary = moduleLibrary;
_module = module;
_destroy = destroy;
_errorType = errorType;
_errorMessage = errorMessage;
_activeObjectCount = activeObjectCount;
_initializedObjectCount = initializedObjectCount;
_activeObjectBaseline = activeObjectBaseline;
_expectedCleanupCount = expectedCleanupCount;
_releaseLibraries = releaseLibraries;
_cleanupCount = cleanupCount;
_generic = generic;
ManifestVersion = manifest.ManifestVersion;
ModuleName = manifest.ModuleName;
ArtifactSha256 = manifest.ArtifactSha256;
NativeEntrySha256 = manifest.NativeEntrySha256;
MultiPhase = multiPhase;
}
internal string ManifestVersion { get; }
internal string ModuleName { get; }
internal string? ArtifactSha256 { get; }
internal string? NativeEntrySha256 { get; }
internal bool MultiPhase { get; }
internal int CleanupCountAfterDispose { get; private set; }
internal IReadOnlyList<string> GetAttributeNames()
{
lock (_gate)
{
EnsureActive();
if (_generic.ModuleAttributeNames(_module, out var json) != 0)
{
throw InvocationFailure();
}
try
{
return JsonSerializer.Deserialize(
ReadUtf8(json),
StableAbiResultJsonContext.Default.StringArray
)
?? throw InvalidResult("Native module attribute discovery returned JSON null.");
}
catch (JsonException exception)
{
throw InvalidResult(
"Native module attribute discovery returned invalid JSON.",
exception
);
}
}
}
internal StableAbiObject GetAttribute(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
lock (_gate)
{
EnsureActive();
if (_generic.ObjectGetAttribute(_module, name, out var result) != 0 || result == 0)
{
throw InvocationFailure();
}
return Track(result);
}
}
internal StableAbiObject CreateText(string value)
{
ArgumentNullException.ThrowIfNull(value);
lock (_gate)
{
EnsureActive();
var bytes = System.Text.Encoding.UTF8.GetBytes(value);
var pointer = Marshal.AllocHGlobal(Math.Max(bytes.Length, 1));
try
{
Marshal.Copy(bytes, 0, pointer, bytes.Length);
if (_generic.ObjectFromUtf8(pointer, bytes.Length, out var result) != 0)
{
throw InvocationFailure();
}
return Track(result);
}
finally
{
Marshal.FreeHGlobal(pointer);
}
}
}
internal StableAbiObject CreateInt64(long value)
{
lock (_gate)
{
EnsureActive();
if (_generic.ObjectFromInt64(value, out var result) != 0)
{
throw InvocationFailure();
}
return Track(result);
}
}
internal StableAbiObject CreateBoolean(bool value)
{
lock (_gate)
{
EnsureActive();
if (_generic.ObjectFromBool(value ? 1 : 0, out var result) != 0)
{
throw InvocationFailure();
}
return Track(result);
}
}
internal StableAbiObject CreateNone()
{
lock (_gate)
{
EnsureActive();
if (_generic.ObjectFromNone(out var result) != 0)
{
throw InvocationFailure();
}
return Track(result);
}
}
internal StableAbiObject CreateSequence(
StableAbiObjectKind kind,
IReadOnlyList<StableAbiObject> items
)
{
ArgumentNullException.ThrowIfNull(items);
if (kind is not (StableAbiObjectKind.List or StableAbiObjectKind.Tuple))
{
throw InvalidArguments("A generic native sequence must be a list or tuple.");
}
lock (_gate)
{
EnsureActive();
var handles = ValidateHandles(items);
return Track(
InvokeObjectArray(
handles,
(nint pointer, long count, out nint result) =>
_generic.ObjectSequence((int)kind, pointer, count, out result)
)
);
}
}
public void Dispose()
{
lock (_gate)
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
for (var index = _genericObjects.Count - 1; index >= 0; index--)
{
_generic.ObjectRelease(_genericObjects[index]);
}
_genericObjects.Clear();
_destroy(_module);
CleanupCountAfterDispose = _cleanupCount?.Invoke() ?? 0;
var activeObjects = _activeObjectCount();
if (_releaseLibraries)
{
NativeLibrary.Free(_moduleLibrary);
NativeLibraryGlobalLoader.Free(_bridgeLibrary);
}
if (
(
_cleanupCount is not null
&& (
CleanupCountAfterDispose != _expectedCleanupCount
|| activeObjects != _activeObjectBaseline
)
) || (_cleanupCount is null && activeObjects > _initializedObjectCount)
)
{
throw Failure(
"DPY8006",
StableAbiLoadPhase.Cleanup,
$"Native module cleanup count was {CleanupCountAfterDispose} and active object count was {activeObjects}."
);
}
}
}
internal static StableAbiModule Initialize(
nint bridgeLibrary,
nint moduleLibrary,
StableAbiSymbolManifest manifest,
string modulePath,
string moduleHash,
bool releaseLibraries
)
{
var bridgeVersion = GetDelegate<BridgeVersion>(bridgeLibrary, "dp_abi3_bridge_version");
if (bridgeVersion() != manifest.BridgeAbiVersion)
{
throw Failure(
"DPY8003",
StableAbiLoadPhase.SymbolResolution,
"The native bridge ABI version does not match the symbol manifest.",
modulePath,
moduleHash
);
}
var initialize = GetDelegate<ModuleInitialize>(bridgeLibrary, "dp_abi3_module_initialize");
var destroy = GetDelegate<ModuleDestroy>(bridgeLibrary, "dp_abi3_module_destroy");
var errorType = GetDelegate<ErrorText>(bridgeLibrary, "dp_abi3_error_type");
var errorMessage = GetDelegate<ErrorText>(bridgeLibrary, "dp_abi3_error_message");
var activeObjectCount = GetDelegate<ActiveObjectCount>(
bridgeLibrary,
"dp_abi3_active_object_count"
);
var generic = GenericBridgeApi.Load(bridgeLibrary);
var moduleInitializer = GetDelegate<ModuleInitializer>(
moduleLibrary,
manifest.InitializationSymbol
);
var activeObjectBaseline = activeObjectCount();
var initializationResult = moduleInitializer();
if (
initialize(initializationResult, out var module, out var multiPhase) != 0
|| module == 0
)
{
var errorTypeText = ReadUtf8(errorType());
var errorMessageText = ReadUtf8(errorMessage());
destroy(0);
throw Failure(
"DPY8005",
StableAbiLoadPhase.ModuleInitialization,
$"{errorTypeText}: {errorMessageText}",
modulePath,
moduleHash
);
}
CleanupCount? cleanupCount = null;
var expectedCleanupCount = 0;
if (manifest.IsConformanceFixture)
{
cleanupCount = GetDelegate<CleanupCount>(
moduleLibrary,
$"{manifest.ModuleName}_cleanup_count"
);
expectedCleanupCount = checked(cleanupCount() + 1);
}
return new StableAbiModule(
bridgeLibrary,
moduleLibrary,
module,
manifest,
multiPhase != 0,
destroy,
errorType,
errorMessage,
activeObjectCount,
activeObjectCount(),
activeObjectBaseline,
expectedCleanupCount,
releaseLibraries,
cleanupCount,
generic
);
}
internal StableAbiObjectKind GetObjectKind(StableAbiObject value)
{
lock (_gate)
{
var handle = ValidateHandle(value);
if (_generic.ObjectKind(handle, out var kind) != 0)
{
throw InvocationFailure();
}
return Enum.IsDefined((StableAbiObjectKind)kind)
? (StableAbiObjectKind)kind
: throw InvalidResult($"Native object returned unknown kind {kind}.");
}
}
internal StableAbiObject GetObjectAttribute(StableAbiObject value, string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
lock (_gate)
{
var handle = ValidateHandle(value);
if (_generic.ObjectGetAttribute(handle, name, out var result) != 0 || result == 0)
{
throw InvocationFailure();
}
return Track(result);
}
}
internal StableAbiObject CallObject(
StableAbiObject callable,
IReadOnlyList<StableAbiObject> arguments
)
{
ArgumentNullException.ThrowIfNull(arguments);
lock (_gate)
{
var callableHandle = ValidateHandle(callable);
var handles = ValidateHandles(arguments);
return Track(
InvokeObjectArray(
handles,
(nint pointer, long count, out nint result) =>
_generic.ObjectCall(callableHandle, pointer, count, out result)
)
);
}
}
internal StableAbiObject CallObjectWithKeywords(
StableAbiObject callable,
IReadOnlyList<StableAbiObject> arguments,
IReadOnlyList<string> keywordNames,
IReadOnlyList<StableAbiObject> keywordValues
)
{
ArgumentNullException.ThrowIfNull(arguments);
ArgumentNullException.ThrowIfNull(keywordNames);
ArgumentNullException.ThrowIfNull(keywordValues);
if (keywordNames.Count != keywordValues.Count)
{
throw InvalidArguments("The keyword-argument names and values are misaligned.");
}
lock (_gate)
{
var callableHandle = ValidateHandle(callable);
var handles = ValidateHandles(arguments);
var keywordHandles = ValidateHandles(keywordValues);
nint argumentPointer = 0;
nint namePointer = 0;
nint valuePointer = 0;
var nameBuffers = new nint[keywordNames.Count];
try
{
if (handles.Length != 0)
{
argumentPointer = Marshal.AllocHGlobal(checked(handles.Length * IntPtr.Size));
Marshal.Copy(handles, 0, argumentPointer, handles.Length);
}
if (keywordHandles.Length != 0)
{
for (var index = 0; index < keywordNames.Count; index++)
{
nameBuffers[index] = Marshal.StringToCoTaskMemUTF8(keywordNames[index]);
}
namePointer = Marshal.AllocHGlobal(checked(nameBuffers.Length * IntPtr.Size));
Marshal.Copy(nameBuffers, 0, namePointer, nameBuffers.Length);
valuePointer = Marshal.AllocHGlobal(
checked(keywordHandles.Length * IntPtr.Size)
);
Marshal.Copy(keywordHandles, 0, valuePointer, keywordHandles.Length);
}
if (
_generic.ObjectCallKeywords(
callableHandle,
argumentPointer,
handles.Length,
namePointer,
valuePointer,
keywordHandles.Length,
out var result
) != 0
|| result == 0
)
{
throw InvocationFailure();
}
return Track(result);
}
finally
{
foreach (var buffer in nameBuffers)
{
if (buffer != 0)
{
Marshal.FreeCoTaskMem(buffer);
}
}
if (argumentPointer != 0)
{
Marshal.FreeHGlobal(argumentPointer);
}
if (namePointer != 0)
{
Marshal.FreeHGlobal(namePointer);
}
if (valuePointer != 0)
{
Marshal.FreeHGlobal(valuePointer);
}
}
}
}
internal long GetObjectHash(StableAbiObject value)
{
lock (_gate)
{
if (_generic.ObjectHash(ValidateHandle(value), out var result) != 0)
{
throw InvocationFailure();
}
return result;
}
}
internal long GetObjectInt64(StableAbiObject value)
{
lock (_gate)
{
if (_generic.ObjectAsInt64(ValidateHandle(value), out var result) != 0)
{
throw InvocationFailure();
}
return result;
}
}
internal bool GetObjectBoolean(StableAbiObject value)
{
lock (_gate)
{
if (_generic.ObjectAsBool(ValidateHandle(value), out var result) != 0)
{
throw InvocationFailure();
}
return result != 0;
}
}
internal string GetObjectText(StableAbiObject value)
{
lock (_gate)
{
if (_generic.ObjectAsUtf8(ValidateHandle(value), out var result, out var length) != 0)
{
throw InvocationFailure();
}
return ReadUtf8(result, length);
}
}
internal string GetObjectDisplay(StableAbiObject value)
{
lock (_gate)
{
if (_generic.ObjectString(ValidateHandle(value), out var result, out var length) != 0)
{
throw InvocationFailure();
}
return ReadUtf8(result, length);
}
}
internal string GetObjectRepresentation(StableAbiObject value)
{
lock (_gate)
{
if (
_generic.ObjectRepresentation(ValidateHandle(value), out var result, out var length)
!= 0
)
{
throw InvocationFailure();
}
return ReadUtf8(result, length);
}
}
internal StableAbiObject RichCompareObjects(
StableAbiObject left,
StableAbiObject right,
StableAbiRichComparison comparison
)
{
lock (_gate)
{
if (
_generic.ObjectRichCompare(
ValidateHandle(left),
ValidateHandle(right),
(int)comparison,
out var result
) != 0
|| result == 0
)
{
throw InvocationFailure();
}
return Track(result);
}
}
internal long GetObjectSize(StableAbiObject value)
{
lock (_gate)
{
if (_generic.ObjectSize(ValidateHandle(value), out var result) != 0)
{
throw InvocationFailure();
}
return result;
}
}
internal StableAbiObject GetObjectItem(StableAbiObject value, StableAbiObject key)
{
lock (_gate)
{
if (
_generic.ObjectGetItem(ValidateHandle(value), ValidateHandle(key), out var result)
!= 0
|| result == 0
)
{
throw InvocationFailure();
}
return Track(result);
}
}
internal void ReleaseObject(StableAbiObject value)
{
lock (_gate)
{
if (_disposed != 0)
{
return;
}
var handle = value.Detach(this);
if (handle == 0)
{
return;
}
var index = _genericObjects.LastIndexOf(handle);
if (index < 0)
{
throw new InvalidOperationException("The generic native object is not owned.");
}
_genericObjects.RemoveAt(index);
_generic.ObjectRelease(handle);
}
}
private StableAbiObject Track(nint handle)
{
if (handle == 0)
{
throw InvalidResult("The generic native bridge returned a null object.");
}
if (_genericObjects.Count >= MaximumGenericObjects)
{
_generic.ObjectRelease(handle);
throw InvalidArguments(
$"A native module session cannot own more than {MaximumGenericObjects} generic objects."
);
}
_genericObjects.Add(handle);
return new StableAbiObject(this, handle);
}
private nint ValidateHandle(StableAbiObject value)
{
ArgumentNullException.ThrowIfNull(value);
EnsureActive();
return value.GetHandle(this);
}
private nint[] ValidateHandles(IReadOnlyList<StableAbiObject> values)
{
if (values.Count > 4096)
{
throw InvalidArguments("A generic native operation accepts at most 4096 objects.");
}
var handles = new nint[values.Count];
for (var index = 0; index < values.Count; index++)
{
handles[index] = ValidateHandle(values[index]);
}
return handles;
}
private nint InvokeObjectArray(nint[] handles, ObjectArrayOperation operation)
{
nint pointer = 0;
try
{
if (handles.Length != 0)
{
pointer = Marshal.AllocHGlobal(checked(handles.Length * IntPtr.Size));
Marshal.Copy(handles, 0, pointer, handles.Length);
}
if (operation(pointer, handles.Length, out var result) != 0 || result == 0)
{
throw InvocationFailure();
}
return result;
}
finally
{
if (pointer != 0)
{
Marshal.FreeHGlobal(pointer);
}
}
}
private void EnsureActive() => ObjectDisposedException.ThrowIf(_disposed != 0, this);
private StableAbiLoadException InvocationFailure()
{
var errorType = ReadUtf8(_errorType());
return new StableAbiLoadException(
"DPY8005",
StableAbiLoadPhase.Invocation,
$"{errorType}: {ReadUtf8(_errorMessage())}",
artifactPath: null,
artifactSha256: null,
missingSymbol: null,
pythonErrorType: errorType.Length == 0 ? null : errorType
);
}
private static StableAbiLoadException InvalidArguments(string message) =>
Failure("DPY8005", StableAbiLoadPhase.Invocation, message);
private static T GetDelegate<T>(nint library, string symbol)
where T : Delegate =>
Marshal.GetDelegateForFunctionPointer<T>(NativeLibrary.GetExport(library, symbol));
private static string ReadUtf8(nint value) => Marshal.PtrToStringUTF8(value) ?? string.Empty;
private static string ReadUtf8(nint value, long length)
{
if (value == 0 || length < 0 || length > int.MaxValue)
{
throw InvalidResult("The native bridge returned invalid UTF-8 storage.");
}
return Marshal.PtrToStringUTF8(value, checked((int)length));
}
private static StableAbiLoadException InvalidResult(string message, Exception? inner = null) =>
Failure("DPY8005", StableAbiLoadPhase.Invocation, message, inner: inner);
private static StableAbiLoadException Failure(
string code,
StableAbiLoadPhase phase,
string message,
string? artifactPath = null,
string? artifactHash = null,
Exception? inner = null
) => new(code, phase, message, artifactPath, artifactHash, missingSymbol: null, inner);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int BridgeVersion();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate nint ModuleInitializer();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ModuleInitialize(
nint initializationResult,
out nint module,
out int multiPhase
);
private delegate int ObjectArrayOperation(nint values, long count, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ModuleAttributeNames(nint module, out nint resultJson);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectGetAttribute(
nint value,
[MarshalAs(UnmanagedType.LPUTF8Str)] string name,
out nint result
);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectCall(nint callable, nint arguments, long count, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectHash(nint value, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectCallKeywords(
nint callable,
nint arguments,
long count,
nint keywordNames,
nint keywordValues,
long keywordCount,
out nint result
);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectFromUtf8(nint value, long length, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectFromInt64(long value, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectFromBool(int value, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectFromNone(out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectSequence(int kind, nint items, long count, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectKind(nint value, out int kind);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectAsInt64(nint value, out long result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectAsBool(nint value, out int result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectAsUtf8(nint value, out nint result, out long length);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectString(nint value, out nint result, out long length);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectRepresentation(nint value, out nint result, out long length);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectRichCompare(nint left, nint right, int operation, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectSize(nint value, out long result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int ObjectGetItem(nint value, nint key, out nint result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ObjectRelease(nint value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ModuleDestroy(nint module);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate nint ErrorText();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate long ActiveObjectCount();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int CleanupCount();
private sealed record GenericBridgeApi(
ModuleAttributeNames ModuleAttributeNames,
ObjectGetAttribute ObjectGetAttribute,
ObjectCall ObjectCall,
ObjectCallKeywords ObjectCallKeywords,
ObjectHash ObjectHash,
ObjectFromUtf8 ObjectFromUtf8,
ObjectFromInt64 ObjectFromInt64,
ObjectFromBool ObjectFromBool,
ObjectFromNone ObjectFromNone,
ObjectSequence ObjectSequence,
ObjectKind ObjectKind,
ObjectAsInt64 ObjectAsInt64,
ObjectAsBool ObjectAsBool,
ObjectAsUtf8 ObjectAsUtf8,
ObjectString ObjectString,
ObjectRepresentation ObjectRepresentation,
ObjectRichCompare ObjectRichCompare,
ObjectSize ObjectSize,
ObjectGetItem ObjectGetItem,
ObjectRelease ObjectRelease
)
{
internal static GenericBridgeApi Load(nint library) =>
new(
GetDelegate<ModuleAttributeNames>(library, "dp_abi3_module_attribute_names"),
GetDelegate<ObjectGetAttribute>(library, "dp_abi3_object_get_attr"),
GetDelegate<ObjectCall>(library, "dp_abi3_object_call"),
GetDelegate<ObjectCallKeywords>(library, "dp_abi3_object_call_kw"),
GetDelegate<ObjectHash>(library, "dp_abi3_object_hash"),
GetDelegate<ObjectFromUtf8>(library, "dp_abi3_object_from_utf8"),
GetDelegate<ObjectFromInt64>(library, "dp_abi3_object_from_int64"),
GetDelegate<ObjectFromBool>(library, "dp_abi3_object_from_bool"),
GetDelegate<ObjectFromNone>(library, "dp_abi3_object_from_none"),
GetDelegate<ObjectSequence>(library, "dp_abi3_object_sequence"),
GetDelegate<ObjectKind>(library, "dp_abi3_object_kind_of"),
GetDelegate<ObjectAsInt64>(library, "dp_abi3_object_as_int64"),
GetDelegate<ObjectAsBool>(library, "dp_abi3_object_as_bool"),
GetDelegate<ObjectAsUtf8>(library, "dp_abi3_object_as_utf8"),
GetDelegate<ObjectString>(library, "dp_abi3_object_string"),
GetDelegate<ObjectRepresentation>(library, "dp_abi3_object_repr"),
GetDelegate<ObjectRichCompare>(library, "dp_abi3_object_rich_compare"),
GetDelegate<ObjectSize>(library, "dp_abi3_object_size"),
GetDelegate<ObjectGetItem>(library, "dp_abi3_object_get_item"),
GetDelegate<ObjectRelease>(library, "dp_abi3_object_release")
);
}
}
internal enum StableAbiObjectKind
{
Invalid = 0,
None = 1,
Boolean = 2,
Integer = 3,
Text = 4,
Bytes = 5,
List = 6,
Tuple = 7,
Dictionary = 8,
Module = 9,
Callable = 10,
Type = 11,
Instance = 12,
}
internal enum StableAbiRichComparison
{
LessThan = 0,
LessThanOrEqual = 1,
Equal = 2,
NotEqual = 3,
GreaterThan = 4,
GreaterThanOrEqual = 5,
}
internal sealed class StableAbiObject : IDisposable
{
private StableAbiModule? _owner;
private nint _handle;
internal StableAbiObject(StableAbiModule owner, nint handle)
{
_owner = owner;
_handle = handle;
}
internal StableAbiObjectKind Kind => RequireOwner().GetObjectKind(this);
internal StableAbiModule Owner => RequireOwner();
internal StableAbiObject GetAttribute(string name) =>
RequireOwner().GetObjectAttribute(this, name);
internal StableAbiObject Call(IReadOnlyList<StableAbiObject> arguments) =>
RequireOwner().CallObject(this, arguments);
internal StableAbiObject CallWithKeywords(
IReadOnlyList<StableAbiObject> arguments,
IReadOnlyList<string> keywordNames,
IReadOnlyList<StableAbiObject> keywordValues
) => RequireOwner().CallObjectWithKeywords(this, arguments, keywordNames, keywordValues);
internal long Hash() => RequireOwner().GetObjectHash(this);
internal long AsInt64() => RequireOwner().GetObjectInt64(this);
internal bool AsBoolean() => RequireOwner().GetObjectBoolean(this);
internal string AsText() => RequireOwner().GetObjectText(this);
internal string ToDisplayString() => RequireOwner().GetObjectDisplay(this);
internal string ToRepresentationString() => RequireOwner().GetObjectRepresentation(this);
internal StableAbiObject RichCompare(
StableAbiObject right,
StableAbiRichComparison comparison
) => RequireOwner().RichCompareObjects(this, right, comparison);
internal long GetSize() => RequireOwner().GetObjectSize(this);
internal StableAbiObject GetItem(StableAbiObject key) =>
RequireOwner().GetObjectItem(this, key);
public void Dispose()
{
var owner = _owner;
owner?.ReleaseObject(this);
}
internal nint Detach(StableAbiModule owner)
{
if (!ReferenceEquals(_owner, owner))
{
return 0;
}
_owner = null;
return Interlocked.Exchange(ref _handle, 0);
}