-
Notifications
You must be signed in to change notification settings - Fork 31
/
pyml_stubs.c
1559 lines (1429 loc) · 40.4 KB
/
pyml_stubs.c
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
#define _GNU_SOURCE
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/fail.h>
#include <caml/callback.h>
#include <caml/custom.h>
#include <caml/alloc.h>
#include <caml/intext.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdcompat.h>
#include <assert.h>
#include "pyml_stubs.h"
static FILE *(*Python__Py_fopen)(const char *pathname, const char *mode);
static FILE *(*Python__Py_wfopen)(const wchar_t *pathname, const wchar_t *mode);
static void *xmalloc(size_t size)
{
void *p = malloc(size);
if (!p) {
caml_failwith("Virtual memory exhausted\n");
}
return p;
}
#ifdef _WIN32
#include <windows.h>
typedef HINSTANCE library_t;
static library_t
open_library(const char *filename)
{
return LoadLibrary(filename);
}
static char *
get_library_error()
{
return "Unable to load library";
}
static void
close_library(library_t library)
{
if (!FreeLibrary(library)) {
fprintf(stderr, "close_library.\n");
exit(EXIT_FAILURE);
}
}
static library_t
get_default_library(void)
{
return GetModuleHandle(0);
}
static void *
find_symbol(library_t library, const char *name)
{
return GetProcAddress(library, name);
}
int
unsetenv(const char *name)
{
size_t len = strlen(name);
char *string = xmalloc(len + 2);
int result;
snprintf(string, len + 2, "%s=", name);
result = _putenv(string);
free(string);
return result;
}
extern int win_CRT_fd_of_filedescr(value handle);
static FILE *
file_of_file_descr(value file_descr, const char *mode)
{
CAMLparam1(file_descr);
int fd = win_CRT_fd_of_filedescr(file_descr);
FILE *result = _fdopen(_dup(fd), mode);
CAMLreturnT(FILE *, result);
}
#else
#include <dlfcn.h>
typedef void *library_t;
static library_t
open_library(const char *filename)
{
return dlopen(filename, RTLD_LAZY | RTLD_GLOBAL);
}
static char *
get_library_error()
{
return dlerror();
}
void
close_library(library_t filename)
{
if (dlclose(filename)) {
fprintf(stderr, "close_library: %s.\n", dlerror());
exit(EXIT_FAILURE);
}
}
static library_t
get_default_library(void)
{
return RTLD_DEFAULT;
}
static void *
find_symbol(library_t library, const char *name)
{
return dlsym(library, name);
}
static FILE *
file_of_file_descr(value file_descr, const char *mode)
{
CAMLparam1(file_descr);
int fd = Int_val(file_descr);
FILE *result = fdopen(dup(fd), mode);
CAMLreturnT(FILE *, result);
}
#endif
/* Global variables for the library */
/* version_major != 0 iff the library is initialized */
static int version_major;
static int version_minor;
static library_t library;
/* Functions that are special enough to deserved to be wrapped specifically */
/* Wrapped by pywrap_closure */
static PyObject *(*Python_PyCFunction_NewEx)
(PyMethodDef *, PyObject *, PyObject *);
/* Wrapped by closure and capsule */
static void *(*Python27_PyCapsule_New)
(void *, const char *, PyCapsule_Destructor);
static void *(*Python27_PyCapsule_GetPointer)(PyObject *, const char *);
static int (*Python27_PyCapsule_IsValid)(PyObject *, const char *);
static void *(*Python2_PyCObject_FromVoidPtr)(void *, void (*)(void *));
static void *(*Python2_PyCObject_AsVoidPtr)(PyObject *);
/* Hack for multi-arguments */
static PyObject *(*Python_PyObject_CallFunctionObjArgs)(PyObject *, ...);
static PyObject *(*Python_PyObject_CallMethodObjArgs)(
PyObject *, PyObject *, ...);
/* Wrapped by PyErr_Fetch_wrapper */
static void (*Python_PyErr_Fetch)(PyObject **, PyObject **, PyObject **);
static void (*Python_PyErr_Restore)(PyObject *, PyObject *, PyObject *);
static void (*Python_PyErr_NormalizeException)
(PyObject **, PyObject **, PyObject **);
/* Resolved differently between Python 2 and Python 3 */
static PyObject *Python__Py_FalseStruct;
/* Buffer and size */
static int (*Python_PyString_AsStringAndSize)
(PyObject *, char **, Py_ssize_t *);
static int (*Python_PyObject_AsCharBuffer)
(PyObject *, const char **, Py_ssize_t *);
static int (*Python_PyObject_AsReadBuffer)
(PyObject *, const void **, Py_ssize_t *);
static int (*Python_PyObject_AsWriteBuffer)
(PyObject *, void **, Py_ssize_t *);
/* Length argument */
static PyObject *(*Python_PyLong_FromString)(const char *, const char **, int);
/* Internal use only */
static void (*Python_PyMem_Free)(void *);
/* Generate traceback objects. */
static PyObject *(*Python_PyThreadState_Get)();
static PyObject *(*Python_PyFrame_New)(PyObject*, PyObject*, PyObject*, PyObject*);
static PyObject *(*Python_PyCode_NewEmpty)(const char*, const char*, int);
static enum UCS { UCS_NONE, UCS2, UCS4 } ucs;
/* Single instance of () */
static PyObject *tuple_empty;
#include "pyml.h"
#include <stdio.h>
static void *getcustom( value v )
{
return *((void **)Data_custom_val(v));
}
static void pydecref( value v )
{
if (getcustom(v)) {
Py_DECREF((PyObject *)getcustom(v));
}
}
static int
rich_compare_bool_nofail
(PyObject *o1, PyObject *o2, int opid)
{
int result = Python_PyObject_RichCompareBool(o1, o2, opid);
if (result == -1) {
Python_PyErr_Clear();
result = 0;
}
return result;
}
static int
pycompare(value v1, value v2)
{
int result;
PyObject *o1 = getcustom(v1);
PyObject *o2 = getcustom(v2);
if (o1 && !o2)
result = -1;
else if (o2 && !o1)
result = 1;
else if (!o1 && !o2)
result = 0;
else if (version_major < 3)
Python2_PyObject_Cmp(o1, o2, &result);
else if (rich_compare_bool_nofail(o1, o2, Py_EQ))
result = 0;
else if (rich_compare_bool_nofail(o1, o2, Py_LT))
result = -1;
else if (rich_compare_bool_nofail(o1, o2, Py_GT))
result = 1;
else
result = -1;
return result;
}
static intnat
pyhash( value v )
{
if (getcustom(v)) {
intnat result = Python_PyObject_Hash((PyObject *)getcustom(v));
if (result == -1) {
Python_PyErr_Clear();
}
return result;
}
else {
return 0;
}
}
void
pyml_assert_initialized()
{
if (!version_major) {
caml_failwith("Run 'Py.initialize ()' first");
}
}
/** Creates a Python tuple initialized with a single element given by the
argument. The reference to the argument is stolen. */
static PyObject *
singleton(PyObject *value)
{
PyObject *result = Python_PyTuple_New(1);
if (!result) {
caml_failwith("PyTuple_New");
}
if (Python_PyTuple_SetItem(result, 0, value)) {
caml_failwith("PyTuple_SetItem");
}
return result;
}
static void
pyserialize(value v, uintnat *bsize_32, uintnat *bsize_64)
{
pyml_assert_initialized();
PyObject *value = getcustom(v);
PyObject *pickle = Python_PyImport_ImportModule("pickle");
if (pickle == NULL) {
caml_failwith("Cannot import pickle");
}
PyObject *dumps = Python_PyObject_GetAttrString(pickle, "dumps");
if (dumps == NULL) {
caml_failwith("pickle.dumps unavailable");
}
PyObject *args = singleton(value);
PyObject *bytes = Python_PyObject_Call(dumps, args, NULL);
if (bytes == NULL) {
caml_failwith("pickle.dumps failed");
}
Py_ssize_t size;
char *contents;
if (version_major >= 3) {
size = Python3_PyBytes_Size(bytes);
contents = (char *) Python3_PyBytes_AsString(bytes);
}
else {
size = Python2_PyString_Size(bytes);
contents = (char *) Python2_PyString_AsString(bytes);
}
caml_serialize_int_8(size);
caml_serialize_block_1(contents, size);
*bsize_32 = 4;
*bsize_64 = 8;
/*Py_DECREF(bytes);*/ /* reference stolen by args */
Py_DECREF(args);
Py_DECREF(dumps);
Py_DECREF(pickle);
}
static uintnat
pydeserialize(void *dst)
{
pyml_assert_initialized();
Py_ssize_t size = caml_deserialize_uint_8();
PyObject *bytes;
char *contents;
if (version_major >= 3) {
bytes = Python3_PyBytes_FromStringAndSize(NULL, size);
contents = (char *) Python3_PyBytes_AsString(bytes);
}
else {
bytes = Python2_PyString_FromStringAndSize(NULL, size);
contents = (char *) Python2_PyString_AsString(bytes);
}
caml_deserialize_block_1(contents, size);
PyObject *pickle = Python_PyImport_ImportModule("pickle");
if (pickle == NULL) {
caml_failwith("Cannot import pickle");
}
PyObject *loads = Python_PyObject_GetAttrString(pickle, "loads");
if (loads == NULL) {
caml_failwith("pickle.loads unavailable");
}
PyObject *args = singleton(bytes);
PyObject *value = Python_PyObject_Call(loads, args, NULL);
if (value == NULL) {
caml_failwith("pickle.loads failed");
}
*((PyObject **) dst) = value;
/*Py_DECREF(bytes);*/ /* reference stolen by args */
Py_DECREF(args);
Py_DECREF(loads);
Py_DECREF(pickle);
return sizeof(PyObject *);
}
struct custom_operations pyops =
{
"PythonObject",
pydecref,
pycompare,
pyhash,
pyserialize,
pydeserialize
};
enum code {
CODE_NULL,
CODE_NONE,
CODE_TRUE,
CODE_FALSE,
CODE_TUPLE_EMPTY
};
static void *
resolve(const char *symbol)
{
void *result = find_symbol(library, symbol);
if (!result) {
char *fmt = "Cannot resolve %s.\n";
ssize_t size = snprintf(NULL, 0, fmt, symbol);
char *msg = xmalloc(size + 1);
snprintf(msg, size + 1, fmt, symbol);
caml_failwith(msg);
}
return result;
}
static void *
resolve_optional(const char *symbol)
{
return find_symbol(library, symbol);
}
value
pyml_wrap(PyObject *object, bool steal)
{
CAMLparam0();
CAMLlocal1(v);
if (!object) {
CAMLreturn(Val_int(CODE_NULL));
}
if (object == Python__Py_NoneStruct) {
CAMLreturn(Val_int(CODE_NONE));
}
if (object == Python__Py_TrueStruct) {
CAMLreturn(Val_int(CODE_TRUE));
}
if (object == Python__Py_FalseStruct) {
CAMLreturn(Val_int(CODE_FALSE));
}
unsigned long flags =
((struct _typeobject *) pyobjectdescr(pyobjectdescr(object)->ob_type))
->tp_flags;
if (flags & Py_TPFLAGS_TUPLE_SUBCLASS
&& Python_PySequence_Length(object) == 0) {
CAMLreturn(Val_int(CODE_TUPLE_EMPTY));
}
if (!steal) {
Py_INCREF(object);
}
v = caml_alloc_custom(&pyops, sizeof(PyObject *), 100, 30000000);
*((PyObject **)Data_custom_val(v)) = object;
CAMLreturn(v);
}
PyObject *
pyml_unwrap(value v)
{
if (Is_long(v))
switch (Int_val(v)) {
case CODE_NULL:
return NULL;
case CODE_NONE:
return Python__Py_NoneStruct;
case CODE_TRUE:
return Python__Py_TrueStruct;
case CODE_FALSE:
return Python__Py_FalseStruct;
case CODE_TUPLE_EMPTY:
return tuple_empty;
}
return *((PyObject **)Data_custom_val(v));
}
/*
static value
pyml_wrap_compilerflags(PyCompilerFlags *flags)
{
CAMLparam0();
CAMLlocal2(ref, some);
if (!flags) {
CAMLreturn(Val_int(0));
}
else {
ref = caml_alloc(0, 1);
Store_field(ref, 0, Val_int(flags->cf_flags));
some = caml_alloc(0, 1);
Store_field(some, 0, ref);
CAMLreturn(some);
}
}
*/
static PyCompilerFlags *
pyml_unwrap_compilerflags(value v)
{
CAMLparam1(v);
if (Is_block(v)) {
PyCompilerFlags *flags = malloc(sizeof(PyCompilerFlags));
flags->cf_flags = Int_val(Field(Field(v, 0), 0));
/* only useful for Python >= 3.8 */
flags->cf_feature_version = version_minor;
CAMLreturnT(PyCompilerFlags *, flags);
}
else {
CAMLreturnT(PyCompilerFlags *, NULL);
}
}
/*
static value
pyml_wrap_intref(int v)
{
CAMLparam0();
CAMLlocal1(ref);
ref = caml_alloc(0, 1);
Store_field(ref, 0, Val_int(v));
CAMLreturn(ref);
}
*/
static int
pyml_unwrap_intref(value v)
{
CAMLparam1(v);
CAMLreturnT(int, Int_val(Field(v, 0)));
}
static void *
unwrap_capsule(PyObject *obj, const char *type)
{
if (Python27_PyCapsule_GetPointer) {
return Python27_PyCapsule_GetPointer(obj, type);
}
else {
return Python2_PyCObject_AsVoidPtr(obj);
}
}
static PyObject *
wrap_capsule(void *ptr, char *type, void (*destr)(PyObject *))
{
if (Python27_PyCapsule_New) {
return Python27_PyCapsule_New(ptr, type, destr);
}
else {
return Python2_PyCObject_FromVoidPtr(ptr, (void(*)(void *))destr);
}
}
static PyObject *
pycall_callback(PyObject *obj, PyObject *args)
{
CAMLparam0();
CAMLlocal3(ml_out, ml_func, ml_args);
PyObject *out;
void *p = unwrap_capsule(obj, "ocaml-closure");
if (!p) {
Py_INCREF(Python__Py_NoneStruct);
CAMLreturnT(PyObject *, Python__Py_NoneStruct);
}
ml_func = *(value *) p;
ml_args = pyml_wrap(args, false);
ml_out = caml_callback(ml_func, ml_args);
out = pyml_unwrap(ml_out);
Py_XINCREF(out);
CAMLreturnT(PyObject *, out);
}
static PyObject *
pycall_callback_with_keywords(PyObject *obj, PyObject *args, PyObject *keywords)
{
CAMLparam0();
CAMLlocal4(ml_out, ml_func, ml_args, ml_keywords);
PyObject *out;
void *p = unwrap_capsule(obj, "ocaml-closure");
if (!p) {
Py_INCREF(Python__Py_NoneStruct);
CAMLreturnT(PyObject *, Python__Py_NoneStruct);
}
ml_func = *(value *) p;
ml_args = pyml_wrap(args, false);
ml_keywords = pyml_wrap(keywords, false);
ml_out = caml_callback2(ml_func, ml_args, ml_keywords);
out = pyml_unwrap(ml_out);
Py_XINCREF(out);
CAMLreturnT(PyObject *, out);
}
static void
caml_destructor(PyObject *v, const char *capsule_name)
{
value *valptr = (value *) unwrap_capsule(v, capsule_name);
caml_remove_global_root(valptr);
free(valptr);
}
static void
camldestr_capsule(PyObject *v)
{
caml_destructor(v, "ocaml-capsule");
}
static PyObject *
camlwrap_capsule(value val, void *aux_str, int size)
{
value *v = (value *) malloc(sizeof(value) + size);
*v = val;
memcpy((char *)v + sizeof(value), aux_str, size);
caml_register_global_root(v);
return wrap_capsule(v, "ocaml-capsule", camldestr_capsule);
}
static void *
caml_aux(PyObject *obj)
{
value *v = (value *) unwrap_capsule(obj, "ocaml-closure");
return (char *) v + sizeof(value);
}
void
pyml_assert_python2()
{
if (version_major != 2) {
pyml_assert_initialized();
caml_failwith("Python 2 needed");
}
}
void
pyml_assert_ucs2()
{
if (ucs != UCS2) {
pyml_assert_initialized();
caml_failwith("Python with UCS2 needed");
}
}
void
pyml_assert_ucs4()
{
if (ucs != UCS4) {
pyml_assert_initialized();
caml_failwith("Python with UCS4 needed");
}
}
void
pyml_assert_python3()
{
if (version_major != 3) {
pyml_assert_initialized();
caml_failwith("Python 3 needed");
}
}
void
pyml_check_symbol_available(void *symbol, char *symbol_name)
{
if (!symbol) {
char *fmt = "Symbol unavailable with this version of Python: %s.\n";
ssize_t size = snprintf(NULL, 0, fmt, symbol_name);
if (size < 0) {
caml_failwith("Symbol unavailable with this version of Python.\n");
return;
}
char *msg = xmalloc(size + 1);
size = snprintf(msg, size + 1, fmt, symbol_name);
if (size < 0) {
caml_failwith("Symbol unavailable with this version of Python.\n");
return;
}
caml_failwith(msg);
}
}
void *
deref_not_null(void *pointer)
{
if (pointer) {
return *(void **) pointer;
}
else {
return NULL;
}
}
struct pyml_closure {
value value;
PyMethodDef method;
};
static char *anon_closure = "anonymous_closure";
static void
camldestr_closure(PyObject *v)
{
struct pyml_closure *valptr = unwrap_capsule(v, "ocaml-closure");
const char *ml_doc = valptr->method.ml_doc;
const char *ml_name = valptr->method.ml_name;
caml_remove_global_root((value *)valptr);
free(valptr);
free((void *) ml_doc);
if (ml_name != anon_closure) free((void *) ml_name);
}
CAMLprim value
pyml_wrap_closure(value name, value docstring, value closure)
{
CAMLparam3(name, docstring, closure);
pyml_assert_initialized();
PyMethodDef ml;
PyObject *obj;
PyMethodDef *ml_def;
ml.ml_name = anon_closure;
if (name != Val_int(0)) {
ml.ml_name = strdup(String_val(Field(name, 0)));
}
if (Tag_val(closure) == 0) {
ml.ml_flags = 1;
ml.ml_meth = pycall_callback;
}
else {
ml.ml_flags = 3;
ml.ml_meth = (PyCFunction) pycall_callback_with_keywords;
}
ml.ml_doc = strdup(String_val(docstring));
struct pyml_closure *v = malloc(sizeof(struct pyml_closure));
v->value = Field(closure, 0);
v->method = ml;
caml_register_global_root(&v->value);
obj = wrap_capsule(v, "ocaml-closure", camldestr_closure);
ml_def = (PyMethodDef *) caml_aux(obj);
PyObject *f = Python_PyCFunction_NewEx(ml_def, obj, NULL);
Py_DECREF(obj);
CAMLreturn(pyml_wrap(f, true));
}
int debug_build;
int trace_refs_build;
static void
guess_debug_build()
{
PyObject *sysconfig = Python_PyImport_ImportModule("sysconfig");
if (!sysconfig) {
caml_failwith("Cannot import sysconfig");
}
PyObject *get_config_var =
Python_PyObject_GetAttrString(sysconfig, "get_config_var");
assert(get_config_var);
PyObject *args;
PyObject *py_debug;
PyObject *debug_build_py;
char *py_debug_str = "Py_DEBUG";
if (version_major >= 3) {
py_debug = Python3_PyUnicode_FromStringAndSize(py_debug_str, strlen(py_debug_str));
}
else {
py_debug = Python2_PyString_FromStringAndSize(py_debug_str, strlen(py_debug_str));
}
assert(py_debug);
args = singleton(py_debug);
debug_build_py = Python_PyObject_Call(get_config_var, args, NULL);
if (!debug_build_py) {
Python_PyErr_Print();
caml_failwith("Cannot check for debug build");
}
if (debug_build_py == Python__Py_NoneStruct) {
debug_build = 0;
}
else {
if (version_major >= 3) {
debug_build = Python_PyLong_AsLong(debug_build_py);
}
else {
debug_build = Python2_PyInt_AsLong(debug_build_py);
}
if (debug_build == -1) {
caml_failwith("Cannot check for debug build");
}
}
Py_DECREF(args);
Py_DECREF(get_config_var);
Py_DECREF(sysconfig);
}
CAMLprim value
py_load_library(value filename_ocaml, value debug_build_ocaml)
{
CAMLparam2(filename_ocaml, debug_build_ocaml);
if (Is_block(filename_ocaml)) {
const char *filename = String_val(Field(filename_ocaml, 0));
library = open_library(filename);
if (!library) {
caml_failwith(get_library_error());
}
}
else {
library = get_default_library();
}
Python_Py_GetVersion = find_symbol(library, "Py_GetVersion");
if (!Python_Py_GetVersion) {
caml_failwith("No Python symbol");
}
const char *version = Python_Py_GetVersion();
version_major = version[0] - '0';
version_minor = version[2] - '0';
Python_PyCFunction_NewEx = resolve("PyCFunction_NewEx");
if ((version_major == 2 && version_minor >= 7) || version_major >= 3) {
Python27_PyCapsule_New = resolve("PyCapsule_New");
Python27_PyCapsule_GetPointer = resolve("PyCapsule_GetPointer");
Python27_PyCapsule_IsValid = resolve("PyCapsule_IsValid");
}
Python_PyObject_CallFunctionObjArgs =
resolve("PyObject_CallFunctionObjArgs");
Python_PyObject_CallMethodObjArgs =
resolve("PyObject_CallMethodObjArgs");
Python_PyErr_Fetch = resolve("PyErr_Fetch");
Python_PyErr_Restore = resolve("PyErr_Restore");
Python_PyErr_NormalizeException = resolve("PyErr_NormalizeException");
Python_PyObject_AsCharBuffer = resolve_optional("PyObject_AsCharBuffer");
Python_PyObject_AsReadBuffer = resolve_optional("PyObject_AsReadBuffer");
Python_PyObject_AsWriteBuffer = resolve_optional("PyObject_AsWriteBuffer");
if (version_major >= 3) {
Python__Py_FalseStruct = resolve("_Py_FalseStruct");
Python_PyString_AsStringAndSize = resolve("PyBytes_AsStringAndSize");
}
else {
Python__Py_FalseStruct = resolve("_Py_ZeroStruct");
Python_PyString_AsStringAndSize = resolve("PyString_AsStringAndSize");
}
Python_PyLong_FromString = resolve("PyLong_FromString");
Python_PyMem_Free = resolve("PyMem_Free");
Python_PyThreadState_Get = resolve("PyThreadState_Get");
Python_PyFrame_New = resolve("PyFrame_New");
Python_PyCode_NewEmpty = resolve("PyCode_NewEmpty");
if (version_major >= 3) {
Python__Py_wfopen = resolve_optional("_Py_wfopen"); /* Python >=3.10 */
Python__Py_fopen = resolve_optional("_Py_fopen");
}
else {
Python2_PyCObject_FromVoidPtr = resolve("PyCObject_FromVoidPtr");
Python2_PyCObject_AsVoidPtr = resolve("PyCObject_AsVoidPtr");
}
if (find_symbol(library, "PyUnicodeUCS2_AsEncodedString")) {
ucs = UCS2;
}
else if (find_symbol(library, "PyUnicodeUCS4_AsEncodedString")) {
ucs = UCS4;
}
else {
ucs = UCS_NONE;
}
#include "pyml_dlsyms.inc"
Python_Py_Initialize();
PyObject *sys = Python_PyImport_ImportModule("sys");
if (!sys) {
caml_failwith("cannot import module sys");
}
trace_refs_build = Python_PyObject_HasAttrString(sys, "getobjects");
if (Is_block(debug_build_ocaml)) {
debug_build = Int_val(Field(debug_build_ocaml, 0));
}
else {
guess_debug_build();
}
tuple_empty = Python_PyTuple_New(0);
caml_register_custom_operations(&pyops);
CAMLreturn(Val_unit);
}
struct PyObjectDebug {
PyObject *_ob_next; \
PyObject *_ob_prev;
PyObjectDescr descr;
};
PyObjectDescr *pyobjectdescr(PyObject *obj) {
if (trace_refs_build) {
return &((struct PyObjectDebug *) obj)->descr;
}
else {
return (PyObjectDescr *) obj;
}
}
CAMLprim value
py_is_debug_build()
{
CAMLparam0();
CAMLreturn(Val_int(debug_build));
}
CAMLprim value
py_finalize_library(value unit)
{
CAMLparam1(unit);
pyml_assert_initialized();
Py_DECREF(tuple_empty);
if (library != get_default_library()) {
close_library(library);
}
version_major = 0;
ucs = UCS_NONE;
CAMLreturn(Val_unit);
}
CAMLprim value
py_unsetenv(value name_ocaml)
{
CAMLparam1(name_ocaml);
const char *name = String_val(name_ocaml);
if (unsetenv(name) == -1) {
caml_failwith(strerror(errno));
}
CAMLreturn(Val_unit);
}
CAMLprim value
py_get_UCS(value unit)
{
CAMLparam1(unit);
pyml_assert_initialized();
CAMLreturn(Val_int(ucs));
}
CAMLprim value
PyNull_wrapper(value unit)
{
CAMLparam1(unit);
CAMLreturn(Val_int(CODE_NULL));
}
CAMLprim value
PyNone_wrapper(value unit)
{
CAMLparam1(unit);
CAMLreturn(Val_int(CODE_NONE));
}
CAMLprim value
PyTrue_wrapper(value unit)
{
CAMLparam1(unit);
CAMLreturn(Val_int(CODE_TRUE));
}
CAMLprim value
PyFalse_wrapper(value unit)
{
CAMLparam1(unit);
CAMLreturn(Val_int(CODE_FALSE));
}
CAMLprim value
PyTuple_Empty_wrapper(value unit)
{
CAMLparam1(unit);
CAMLreturn(Val_int(CODE_TUPLE_EMPTY));
}
enum pytype_labels {
PyUnknown,
Bool,
Bytes,
Callable,
Capsule,
Closure,
Dict,
Float,
List,
Int,
Long,
Module,
NoneType,
Null,
Tuple,
Type,
Unicode,
Iter,
Set
};
static bool is_iterable(PyObject *obj) {
PyObject *iter = Python_PyObject_GetIter(obj);
if (iter) {
Py_DECREF(iter);
return true;
} else {
Python_PyErr_Clear();
return false;
}
}
CAMLprim value
pytype(value object_ocaml)
{
CAMLparam1(object_ocaml);
pyml_assert_initialized();
PyObject *object = pyml_unwrap(object_ocaml);
if (!object) {
CAMLreturn(Val_int(Null));
}
PyObject *ob_type = pyobjectdescr(object)->ob_type;
struct _typeobject *typeobj = (struct _typeobject *) pyobjectdescr(ob_type);
unsigned long flags = typeobj->tp_flags;
int result;
if (ob_type == Python_PyBool_Type) {
result = Bool;
}
else if (flags & Py_TPFLAGS_BYTES_SUBCLASS) {
result = Bytes;