-
-
Notifications
You must be signed in to change notification settings - Fork 30.6k
/
callproc.c
2144 lines (1914 loc) · 61.4 KB
/
callproc.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
/*
* History: First version dated from 3/97, derived from my SCMLIB version
* for win16.
*/
/*
* Related Work:
* - calldll http://www.nightmare.com/software.html
* - libffi http://sourceware.cygnus.com/libffi/
* - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
* and, of course, Don Beaudry's MESS package, but this is more ctypes
* related.
*/
/*
How are functions called, and how are parameters converted to C ?
1. _ctypes.c::PyCFuncPtr_call receives an argument tuple 'inargs' and a
keyword dictionary 'kwds'.
2. After several checks, _build_callargs() is called which returns another
tuple 'callargs'. This may be the same tuple as 'inargs', a slice of
'inargs', or a completely fresh tuple, depending on several things (is it a
COM method?, are 'paramflags' available?).
3. _build_callargs also calculates bitarrays containing indexes into
the callargs tuple, specifying how to build the return value(s) of
the function.
4. _ctypes_callproc is then called with the 'callargs' tuple. _ctypes_callproc first
allocates two arrays. The first is an array of 'struct argument' items, the
second array has 'void *' entries.
5. If 'converters' are present (converters is a sequence of argtypes'
from_param methods), for each item in 'callargs' converter is called and the
result passed to ConvParam. If 'converters' are not present, each argument
is directly passed to ConvParm.
6. For each arg, ConvParam stores the contained C data (or a pointer to it,
for structures) into the 'struct argument' array.
7. Finally, a loop fills the 'void *' array so that each item points to the
data contained in or pointed to by the 'struct argument' array.
8. The 'void *' argument array is what _call_function_pointer
expects. _call_function_pointer then has very little to do - only some
libffi specific stuff, then it calls ffi_call.
So, there are 4 data structures holding processed arguments:
- the inargs tuple (in PyCFuncPtr_call)
- the callargs tuple (in PyCFuncPtr_call)
- the 'struct arguments' array
- the 'void *' array
*/
/*[clinic input]
module _ctypes
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=476a19c49b31a75c]*/
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "Python.h"
#include <stdbool.h>
#ifdef MS_WIN32
#include <windows.h>
#include <tchar.h>
#else
#include <dlfcn.h>
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#ifdef MS_WIN32
#include <malloc.h>
#endif
#include <ffi.h>
#include "ctypes.h"
#ifdef HAVE_ALLOCA_H
/* AIX needs alloca.h for alloca() */
#include <alloca.h>
#endif
#ifdef _Py_MEMORY_SANITIZER
#include <sanitizer/msan_interface.h>
#endif
#if defined(_DEBUG) || defined(__MINGW32__)
/* Don't use structured exception handling on Windows if this is defined.
MingW, AFAIK, doesn't support it.
*/
#define DONT_USE_SEH
#endif
#include "pycore_runtime.h" // _PyRuntime
#include "pycore_global_objects.h"// _Py_ID()
#include "pycore_traceback.h" // _PyTraceback_Add()
#if defined(Py_HAVE_C_COMPLEX) && defined(Py_FFI_SUPPORT_C_COMPLEX)
#include "../_complex.h" // complex
#endif
#include "clinic/callproc.c.h"
#define CTYPES_CAPSULE_NAME_PYMEM "_ctypes pymem"
static void pymem_destructor(PyObject *ptr)
{
void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
if (p) {
PyMem_Free(p);
}
}
/*
ctypes maintains thread-local storage that has space for two error numbers:
private copies of the system 'errno' value and, on Windows, the system error code
accessed by the GetLastError() and SetLastError() api functions.
Foreign functions created with CDLL(..., use_errno=True), when called, swap
the system 'errno' value with the private copy just before the actual
function call, and swapped again immediately afterwards. The 'use_errno'
parameter defaults to False, in this case 'ctypes_errno' is not touched.
On Windows, foreign functions created with CDLL(..., use_last_error=True) or
WinDLL(..., use_last_error=True) swap the system LastError value with the
ctypes private copy.
The values are also swapped immediately before and after ctypes callback
functions are called, if the callbacks are constructed using the new
optional use_errno parameter set to True: CFUNCTYPE(..., use_errno=TRUE) or
WINFUNCTYPE(..., use_errno=True).
New ctypes functions are provided to access the ctypes private copies from
Python:
- ctypes.set_errno(value) and ctypes.set_last_error(value) store 'value' in
the private copy and returns the previous value.
- ctypes.get_errno() and ctypes.get_last_error() returns the current ctypes
private copies value.
*/
/*
This function creates and returns a thread-local Python object that has
space to store two integer error numbers; once created the Python object is
kept alive in the thread state dictionary as long as the thread itself.
*/
PyObject *
_ctypes_get_errobj(ctypes_state *st, int **pspace)
{
PyObject *dict = PyThreadState_GetDict();
PyObject *errobj;
if (dict == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"cannot get thread state");
return NULL;
}
if (st->error_object_name == NULL) {
st->error_object_name = PyUnicode_InternFromString("ctypes.error_object");
if (st->error_object_name == NULL) {
return NULL;
}
}
if (PyDict_GetItemRef(dict, st->error_object_name, &errobj) < 0) {
return NULL;
}
if (errobj) {
if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) {
PyErr_SetString(PyExc_RuntimeError,
"ctypes.error_object is an invalid capsule");
Py_DECREF(errobj);
return NULL;
}
}
else {
void *space = PyMem_Calloc(2, sizeof(int));
if (space == NULL)
return NULL;
errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
if (errobj == NULL) {
PyMem_Free(space);
return NULL;
}
if (PyDict_SetItem(dict, st->error_object_name, errobj) < 0) {
Py_DECREF(errobj);
return NULL;
}
}
*pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
return errobj;
}
static PyObject *
get_error_internal(PyObject *self, PyObject *args, int index)
{
int *space;
ctypes_state *st = get_module_state(self);
PyObject *errobj = _ctypes_get_errobj(st, &space);
PyObject *result;
if (errobj == NULL)
return NULL;
result = PyLong_FromLong(space[index]);
Py_DECREF(errobj);
return result;
}
static PyObject *
set_error_internal(PyObject *self, PyObject *args, int index)
{
int new_errno, old_errno;
PyObject *errobj;
int *space;
if (!PyArg_ParseTuple(args, "i", &new_errno)) {
return NULL;
}
ctypes_state *st = get_module_state(self);
errobj = _ctypes_get_errobj(st, &space);
if (errobj == NULL)
return NULL;
old_errno = space[index];
space[index] = new_errno;
Py_DECREF(errobj);
return PyLong_FromLong(old_errno);
}
static PyObject *
get_errno(PyObject *self, PyObject *args)
{
if (PySys_Audit("ctypes.get_errno", NULL) < 0) {
return NULL;
}
return get_error_internal(self, args, 0);
}
static PyObject *
set_errno(PyObject *self, PyObject *args)
{
if (PySys_Audit("ctypes.set_errno", "O", args) < 0) {
return NULL;
}
return set_error_internal(self, args, 0);
}
#ifdef MS_WIN32
static PyObject *
get_last_error(PyObject *self, PyObject *args)
{
if (PySys_Audit("ctypes.get_last_error", NULL) < 0) {
return NULL;
}
return get_error_internal(self, args, 1);
}
static PyObject *
set_last_error(PyObject *self, PyObject *args)
{
if (PySys_Audit("ctypes.set_last_error", "O", args) < 0) {
return NULL;
}
return set_error_internal(self, args, 1);
}
static WCHAR *FormatError(DWORD code)
{
WCHAR *lpMsgBuf;
DWORD n;
n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
(LPWSTR) &lpMsgBuf,
0,
NULL);
if (n) {
while (iswspace(lpMsgBuf[n-1]))
--n;
lpMsgBuf[n] = L'\0'; /* rstrip() */
}
return lpMsgBuf;
}
#ifndef DONT_USE_SEH
static void SetException(DWORD code, EXCEPTION_RECORD *pr)
{
if (PySys_Audit("ctypes.set_exception", "I", code) < 0) {
/* An exception was set by the audit hook */
return;
}
/* The 'code' is a normal win32 error code so it could be handled by
PyErr_SetFromWindowsErr(). However, for some errors, we have additional
information not included in the error code. We handle those here and
delegate all others to the generic function. */
switch (code) {
case EXCEPTION_ACCESS_VIOLATION:
/* The thread attempted to read from or write
to a virtual address for which it does not
have the appropriate access. */
if (pr->ExceptionInformation[0] == 0)
PyErr_Format(PyExc_OSError,
"exception: access violation reading %p",
pr->ExceptionInformation[1]);
else
PyErr_Format(PyExc_OSError,
"exception: access violation writing %p",
pr->ExceptionInformation[1]);
break;
case EXCEPTION_BREAKPOINT:
/* A breakpoint was encountered. */
PyErr_SetString(PyExc_OSError,
"exception: breakpoint encountered");
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
/* The thread attempted to read or write data that is
misaligned on hardware that does not provide
alignment. For example, 16-bit values must be
aligned on 2-byte boundaries, 32-bit values on
4-byte boundaries, and so on. */
PyErr_SetString(PyExc_OSError,
"exception: datatype misalignment");
break;
case EXCEPTION_SINGLE_STEP:
/* A trace trap or other single-instruction mechanism
signaled that one instruction has been executed. */
PyErr_SetString(PyExc_OSError,
"exception: single step");
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
/* The thread attempted to access an array element
that is out of bounds, and the underlying hardware
supports bounds checking. */
PyErr_SetString(PyExc_OSError,
"exception: array bounds exceeded");
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
/* One of the operands in a floating-point operation
is denormal. A denormal value is one that is too
small to represent as a standard floating-point
value. */
PyErr_SetString(PyExc_OSError,
"exception: floating-point operand denormal");
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
/* The thread attempted to divide a floating-point
value by a floating-point divisor of zero. */
PyErr_SetString(PyExc_OSError,
"exception: float divide by zero");
break;
case EXCEPTION_FLT_INEXACT_RESULT:
/* The result of a floating-point operation cannot be
represented exactly as a decimal fraction. */
PyErr_SetString(PyExc_OSError,
"exception: float inexact");
break;
case EXCEPTION_FLT_INVALID_OPERATION:
/* This exception represents any floating-point
exception not included in this list. */
PyErr_SetString(PyExc_OSError,
"exception: float invalid operation");
break;
case EXCEPTION_FLT_OVERFLOW:
/* The exponent of a floating-point operation is
greater than the magnitude allowed by the
corresponding type. */
PyErr_SetString(PyExc_OSError,
"exception: float overflow");
break;
case EXCEPTION_FLT_STACK_CHECK:
/* The stack overflowed or underflowed as the result
of a floating-point operation. */
PyErr_SetString(PyExc_OSError,
"exception: stack over/underflow");
break;
case EXCEPTION_STACK_OVERFLOW:
/* The stack overflowed or underflowed as the result
of a floating-point operation. */
PyErr_SetString(PyExc_OSError,
"exception: stack overflow");
break;
case EXCEPTION_FLT_UNDERFLOW:
/* The exponent of a floating-point operation is less
than the magnitude allowed by the corresponding
type. */
PyErr_SetString(PyExc_OSError,
"exception: float underflow");
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
/* The thread attempted to divide an integer value by
an integer divisor of zero. */
PyErr_SetString(PyExc_OSError,
"exception: integer divide by zero");
break;
case EXCEPTION_INT_OVERFLOW:
/* The result of an integer operation caused a carry
out of the most significant bit of the result. */
PyErr_SetString(PyExc_OSError,
"exception: integer overflow");
break;
case EXCEPTION_PRIV_INSTRUCTION:
/* The thread attempted to execute an instruction
whose operation is not allowed in the current
machine mode. */
PyErr_SetString(PyExc_OSError,
"exception: privileged instruction");
break;
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
/* The thread attempted to continue execution after a
noncontinuable exception occurred. */
PyErr_SetString(PyExc_OSError,
"exception: nocontinuable");
break;
default:
PyErr_SetFromWindowsErr(code);
break;
}
}
static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
DWORD *pdw, EXCEPTION_RECORD *record)
{
*pdw = ptrs->ExceptionRecord->ExceptionCode;
*record = *ptrs->ExceptionRecord;
/* We don't want to catch breakpoint exceptions, they are used to attach
* a debugger to the process.
*/
if (*pdw == EXCEPTION_BREAKPOINT)
return EXCEPTION_CONTINUE_SEARCH;
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
static PyObject *
check_hresult(PyObject *self, PyObject *args)
{
HRESULT hr;
if (!PyArg_ParseTuple(args, "i", &hr))
return NULL;
if (FAILED(hr))
return PyErr_SetFromWindowsErr(hr);
return PyLong_FromLong(hr);
}
#endif
/**************************************************************/
PyCArgObject *
PyCArgObject_new(ctypes_state *st)
{
PyCArgObject *p;
p = PyObject_GC_New(PyCArgObject, st->PyCArg_Type);
if (p == NULL)
return NULL;
p->pffi_type = NULL;
p->tag = '\0';
p->obj = NULL;
memset(&p->value, 0, sizeof(p->value));
PyObject_GC_Track(p);
return p;
}
static int
PyCArg_traverse(PyCArgObject *self, visitproc visit, void *arg)
{
Py_VISIT(Py_TYPE(self));
Py_VISIT(self->obj);
return 0;
}
static int
PyCArg_clear(PyCArgObject *self)
{
Py_CLEAR(self->obj);
return 0;
}
static void
PyCArg_dealloc(PyCArgObject *self)
{
PyTypeObject *tp = Py_TYPE(self);
PyObject_GC_UnTrack(self);
(void)PyCArg_clear(self);
tp->tp_free((PyObject *)self);
Py_DECREF(tp);
}
static int
is_literal_char(unsigned char c)
{
return c < 128 && _PyUnicode_IsPrintable(c) && c != '\\' && c != '\'';
}
static PyObject *
PyCArg_repr(PyCArgObject *self)
{
switch(self->tag) {
case 'b':
case 'B':
return PyUnicode_FromFormat("<cparam '%c' (%d)>",
self->tag, self->value.b);
case 'h':
case 'H':
return PyUnicode_FromFormat("<cparam '%c' (%d)>",
self->tag, self->value.h);
case 'i':
case 'I':
return PyUnicode_FromFormat("<cparam '%c' (%d)>",
self->tag, self->value.i);
case 'l':
case 'L':
return PyUnicode_FromFormat("<cparam '%c' (%ld)>",
self->tag, self->value.l);
case 'q':
case 'Q':
return PyUnicode_FromFormat("<cparam '%c' (%lld)>",
self->tag, self->value.q);
case 'd':
case 'f': {
PyObject *f = PyFloat_FromDouble((self->tag == 'f') ? self->value.f : self->value.d);
if (f == NULL) {
return NULL;
}
PyObject *result = PyUnicode_FromFormat("<cparam '%c' (%R)>", self->tag, f);
Py_DECREF(f);
return result;
}
case 'c':
if (is_literal_char((unsigned char)self->value.c)) {
return PyUnicode_FromFormat("<cparam '%c' ('%c')>",
self->tag, self->value.c);
}
else {
return PyUnicode_FromFormat("<cparam '%c' ('\\x%02x')>",
self->tag, (unsigned char)self->value.c);
}
/* Hm, are these 'z' and 'Z' codes useful at all?
Shouldn't they be replaced by the functionality of create_string_buffer()
and c_wstring() ?
*/
case 'z':
case 'Z':
case 'P':
return PyUnicode_FromFormat("<cparam '%c' (%p)>",
self->tag, self->value.p);
break;
default:
if (is_literal_char((unsigned char)self->tag)) {
return PyUnicode_FromFormat("<cparam '%c' at %p>",
(unsigned char)self->tag, (void *)self);
}
else {
return PyUnicode_FromFormat("<cparam 0x%02x at %p>",
(unsigned char)self->tag, (void *)self);
}
}
}
static PyMemberDef PyCArgType_members[] = {
{ "_obj", _Py_T_OBJECT,
offsetof(PyCArgObject, obj), Py_READONLY,
"the wrapped object" },
{ NULL },
};
static PyType_Slot carg_slots[] = {
{Py_tp_dealloc, PyCArg_dealloc},
{Py_tp_traverse, PyCArg_traverse},
{Py_tp_clear, PyCArg_clear},
{Py_tp_repr, PyCArg_repr},
{Py_tp_members, PyCArgType_members},
{0, NULL},
};
PyType_Spec carg_spec = {
.name = "_ctypes.CArgObject",
.basicsize = sizeof(PyCArgObject),
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
.slots = carg_slots,
};
/****************************************************************/
/*
* Convert a PyObject * into a parameter suitable to pass to an
* C function call.
*
* 1. Python integers are converted to C int and passed by value.
* Py_None is converted to a C NULL pointer.
*
* 2. 3-tuples are expected to have a format character in the first
* item, which must be 'i', 'f', 'd', 'q', or 'P'.
* The second item will have to be an integer, float, double, long long
* or integer (denoting an address void *), will be converted to the
* corresponding C data type and passed by value.
*
* 3. Other Python objects are tested for an '_as_parameter_' attribute.
* The value of this attribute must be an integer which will be passed
* by value, or a 2-tuple or 3-tuple which will be used according
* to point 2 above. The third item (if any), is ignored. It is normally
* used to keep the object alive where this parameter refers to.
* XXX This convention is dangerous - you can construct arbitrary tuples
* in Python and pass them. Would it be safer to use a custom container
* datatype instead of a tuple?
*
* 4. Other Python objects cannot be passed as parameters - an exception is raised.
*
* 5. ConvParam will store the converted result in a struct containing format
* and value.
*/
union result {
char c;
char b;
short h;
int i;
long l;
long long q;
long double D;
double d;
float f;
void *p;
#if defined(Py_HAVE_C_COMPLEX) && defined(Py_FFI_SUPPORT_C_COMPLEX)
double complex C;
float complex E;
long double complex F;
#endif
};
struct argument {
ffi_type *ffi_type;
PyObject *keep;
union result value;
};
/*
* Convert a single Python object into a PyCArgObject and return it.
*/
static int ConvParam(ctypes_state *st,
PyObject *obj, Py_ssize_t index, struct argument *pa)
{
pa->keep = NULL; /* so we cannot forget it later */
StgInfo *info;
int result = PyStgInfo_FromObject(st, obj, &info);
if (result < 0) {
return -1;
}
if (info) {
assert(info);
PyCArgObject *carg;
assert(info->paramfunc);
/* If it has an stginfo, it is a CDataObject */
carg = info->paramfunc(st, (CDataObject *)obj);
if (carg == NULL)
return -1;
pa->ffi_type = carg->pffi_type;
memcpy(&pa->value, &carg->value, sizeof(pa->value));
pa->keep = (PyObject *)carg;
return 0;
}
if (PyCArg_CheckExact(st, obj)) {
PyCArgObject *carg = (PyCArgObject *)obj;
pa->ffi_type = carg->pffi_type;
pa->keep = Py_NewRef(obj);
memcpy(&pa->value, &carg->value, sizeof(pa->value));
return 0;
}
/* check for None, integer, string or unicode and use directly if successful */
if (obj == Py_None) {
pa->ffi_type = &ffi_type_pointer;
pa->value.p = NULL;
return 0;
}
if (PyLong_Check(obj)) {
pa->ffi_type = &ffi_type_sint;
pa->value.i = (long)PyLong_AsUnsignedLong(obj);
if (pa->value.i == -1 && PyErr_Occurred()) {
PyErr_Clear();
pa->value.i = PyLong_AsLong(obj);
if (pa->value.i == -1 && PyErr_Occurred()) {
PyErr_SetString(PyExc_OverflowError,
"int too long to convert");
return -1;
}
}
return 0;
}
if (PyBytes_Check(obj)) {
pa->ffi_type = &ffi_type_pointer;
pa->value.p = PyBytes_AsString(obj);
pa->keep = Py_NewRef(obj);
return 0;
}
if (PyUnicode_Check(obj)) {
pa->ffi_type = &ffi_type_pointer;
pa->value.p = PyUnicode_AsWideCharString(obj, NULL);
if (pa->value.p == NULL)
return -1;
pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
if (!pa->keep) {
PyMem_Free(pa->value.p);
return -1;
}
return 0;
}
{
PyObject *arg;
if (PyObject_GetOptionalAttr(obj, &_Py_ID(_as_parameter_), &arg) < 0) {
return -1;
}
/* Which types should we exactly allow here?
integers are required for using Python classes
as parameters (they have to expose the '_as_parameter_'
attribute)
*/
if (arg) {
int result;
result = ConvParam(st, arg, index, pa);
Py_DECREF(arg);
return result;
}
PyErr_Format(PyExc_TypeError,
"Don't know how to convert parameter %d",
Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
return -1;
}
}
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
/*
Per: https://msdn.microsoft.com/en-us/library/7572ztz4.aspx
To be returned by value in RAX, user-defined types must have a length
of 1, 2, 4, 8, 16, 32, or 64 bits
*/
int can_return_struct_as_int(size_t s)
{
return s == 1 || s == 2 || s == 4;
}
int can_return_struct_as_sint64(size_t s)
{
#ifdef _M_ARM
// 8 byte structs cannot be returned in a register on ARM32
return 0;
#else
return s == 8;
#endif
}
#endif
// returns NULL with exception set on error
ffi_type *_ctypes_get_ffi_type(ctypes_state *st, PyObject *obj)
{
if (obj == NULL) {
return &ffi_type_sint;
}
StgInfo *info;
if (PyStgInfo_FromType(st, obj, &info) < 0) {
return NULL;
}
if (info == NULL) {
return &ffi_type_sint;
}
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
/* This little trick works correctly with MSVC.
It returns small structures in registers
*/
if (info->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
if (can_return_struct_as_int(info->ffi_type_pointer.size))
return &ffi_type_sint32;
else if (can_return_struct_as_sint64 (info->ffi_type_pointer.size))
return &ffi_type_sint64;
}
#endif
return &info->ffi_type_pointer;
}
/*
* libffi uses:
*
* ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
* unsigned int nargs,
* ffi_type *rtype,
* ffi_type **atypes);
*
* and then
*
* void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
*/
static int _call_function_pointer(ctypes_state *st,
int flags,
PPROC pProc,
void **avalues,
ffi_type **atypes,
ffi_type *restype,
void *resmem,
int argcount,
int argtypecount)
{
PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
PyObject *error_object = NULL;
int *space;
ffi_cif cif;
int cc;
#if defined(MS_WIN32) && !defined(DONT_USE_SEH)
DWORD dwExceptionCode = 0;
EXCEPTION_RECORD record;
#endif
/* XXX check before here */
if (restype == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"No ffi_type for result");
return -1;
}
cc = FFI_DEFAULT_ABI;
#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE) && !defined(_M_ARM)
if ((flags & FUNCFLAG_CDECL) == 0)
cc = FFI_STDCALL;
#endif
# ifdef USING_APPLE_OS_LIBFFI
# ifdef HAVE_BUILTIN_AVAILABLE
# define HAVE_FFI_PREP_CIF_VAR_RUNTIME __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
# else
# define HAVE_FFI_PREP_CIF_VAR_RUNTIME (ffi_prep_cif_var != NULL)
# endif
# elif HAVE_FFI_PREP_CIF_VAR
# define HAVE_FFI_PREP_CIF_VAR_RUNTIME true
# else
# define HAVE_FFI_PREP_CIF_VAR_RUNTIME false
# endif
/* Even on Apple-arm64 the calling convention for variadic functions coincides
* with the standard calling convention in the case that the function called
* only with its fixed arguments. Thus, we do not need a special flag to be
* set on variadic functions. We treat a function as variadic if it is called
* with a nonzero number of variadic arguments */
bool is_variadic = (argtypecount != 0 && argcount > argtypecount);
(void) is_variadic;
#if defined(__APPLE__) && defined(__arm64__)
if (is_variadic) {
if (HAVE_FFI_PREP_CIF_VAR_RUNTIME) {
} else {
PyErr_SetString(PyExc_NotImplementedError, "ffi_prep_cif_var() is missing");
return -1;
}
}
#endif
#if HAVE_FFI_PREP_CIF_VAR
if (is_variadic) {
if (HAVE_FFI_PREP_CIF_VAR_RUNTIME) {
if (FFI_OK != ffi_prep_cif_var(&cif,
cc,
argtypecount,
argcount,
restype,
atypes)) {
PyErr_SetString(PyExc_RuntimeError,
"ffi_prep_cif_var failed");
return -1;
}
} else {
if (FFI_OK != ffi_prep_cif(&cif,
cc,
argcount,
restype,
atypes)) {
PyErr_SetString(PyExc_RuntimeError,
"ffi_prep_cif failed");
return -1;
}
}
} else
#endif
{
if (FFI_OK != ffi_prep_cif(&cif,
cc,
argcount,
restype,
atypes)) {
PyErr_SetString(PyExc_RuntimeError,
"ffi_prep_cif failed");
return -1;
}
}
if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
error_object = _ctypes_get_errobj(st, &space);
if (error_object == NULL)
return -1;
}
if ((flags & FUNCFLAG_PYTHONAPI) == 0)
Py_UNBLOCK_THREADS
if (flags & FUNCFLAG_USE_ERRNO) {
int temp = space[0];
space[0] = errno;
errno = temp;
}
#ifdef MS_WIN32
if (flags & FUNCFLAG_USE_LASTERROR) {
int temp = space[1];
space[1] = GetLastError();
SetLastError(temp);
}
#ifndef DONT_USE_SEH
__try {
#endif
#endif
ffi_call(&cif, (void *)pProc, resmem, avalues);
#ifdef MS_WIN32
#ifndef DONT_USE_SEH
}
__except (HandleException(GetExceptionInformation(),
&dwExceptionCode, &record)) {
;
}
#endif
if (flags & FUNCFLAG_USE_LASTERROR) {
int temp = space[1];
space[1] = GetLastError();
SetLastError(temp);
}
#endif
if (flags & FUNCFLAG_USE_ERRNO) {
int temp = space[0];
space[0] = errno;
errno = temp;
}
if ((flags & FUNCFLAG_PYTHONAPI) == 0)
Py_BLOCK_THREADS
Py_XDECREF(error_object);
#ifdef MS_WIN32
#ifndef DONT_USE_SEH
if (dwExceptionCode) {
SetException(dwExceptionCode, &record);
return -1;
}
#endif
#endif
if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
return -1;
return 0;
}
/*
* Convert the C value in result into a Python object, depending on restype.
*
* - If restype is NULL, return a Python integer.
* - If restype is None, return None.
* - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,