Spaces:
Sleeping
Sleeping
Upload 22 files
Browse files- cffi/__init__.py +14 -0
- cffi/_cffi_errors.h +149 -0
- cffi/_cffi_include.h +389 -0
- cffi/_embedding.h +550 -0
- cffi/_imp_emulation.py +83 -0
- cffi/_shimmed_dist_utils.py +45 -0
- cffi/api.py +967 -0
- cffi/backend_ctypes.py +1121 -0
- cffi/cffi_opcode.py +187 -0
- cffi/commontypes.py +82 -0
- cffi/cparser.py +1015 -0
- cffi/error.py +31 -0
- cffi/ffiplatform.py +113 -0
- cffi/lock.py +30 -0
- cffi/model.py +618 -0
- cffi/parse_c_type.h +181 -0
- cffi/pkgconfig.py +121 -0
- cffi/recompiler.py +1598 -0
- cffi/setuptools_ext.py +216 -0
- cffi/vengine_cpy.py +1084 -0
- cffi/vengine_gen.py +679 -0
- cffi/verifier.py +306 -0
cffi/__init__.py
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError',
|
2 |
+
'FFIError']
|
3 |
+
|
4 |
+
from .api import FFI
|
5 |
+
from .error import CDefError, FFIError, VerificationError, VerificationMissing
|
6 |
+
from .error import PkgConfigError
|
7 |
+
|
8 |
+
__version__ = "1.17.1"
|
9 |
+
__version_info__ = (1, 17, 1)
|
10 |
+
|
11 |
+
# The verifier module file names are based on the CRC32 of a string that
|
12 |
+
# contains the following version number. It may be older than __version__
|
13 |
+
# if nothing is clearly incompatible.
|
14 |
+
__version_verifier_modules__ = "0.8.6"
|
cffi/_cffi_errors.h
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef CFFI_MESSAGEBOX
|
2 |
+
# ifdef _MSC_VER
|
3 |
+
# define CFFI_MESSAGEBOX 1
|
4 |
+
# else
|
5 |
+
# define CFFI_MESSAGEBOX 0
|
6 |
+
# endif
|
7 |
+
#endif
|
8 |
+
|
9 |
+
|
10 |
+
#if CFFI_MESSAGEBOX
|
11 |
+
/* Windows only: logic to take the Python-CFFI embedding logic
|
12 |
+
initialization errors and display them in a background thread
|
13 |
+
with MessageBox. The idea is that if the whole program closes
|
14 |
+
as a result of this problem, then likely it is already a console
|
15 |
+
program and you can read the stderr output in the console too.
|
16 |
+
If it is not a console program, then it will likely show its own
|
17 |
+
dialog to complain, or generally not abruptly close, and for this
|
18 |
+
case the background thread should stay alive.
|
19 |
+
*/
|
20 |
+
static void *volatile _cffi_bootstrap_text;
|
21 |
+
|
22 |
+
static PyObject *_cffi_start_error_capture(void)
|
23 |
+
{
|
24 |
+
PyObject *result = NULL;
|
25 |
+
PyObject *x, *m, *bi;
|
26 |
+
|
27 |
+
if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text,
|
28 |
+
(void *)1, NULL) != NULL)
|
29 |
+
return (PyObject *)1;
|
30 |
+
|
31 |
+
m = PyImport_AddModule("_cffi_error_capture");
|
32 |
+
if (m == NULL)
|
33 |
+
goto error;
|
34 |
+
|
35 |
+
result = PyModule_GetDict(m);
|
36 |
+
if (result == NULL)
|
37 |
+
goto error;
|
38 |
+
|
39 |
+
#if PY_MAJOR_VERSION >= 3
|
40 |
+
bi = PyImport_ImportModule("builtins");
|
41 |
+
#else
|
42 |
+
bi = PyImport_ImportModule("__builtin__");
|
43 |
+
#endif
|
44 |
+
if (bi == NULL)
|
45 |
+
goto error;
|
46 |
+
PyDict_SetItemString(result, "__builtins__", bi);
|
47 |
+
Py_DECREF(bi);
|
48 |
+
|
49 |
+
x = PyRun_String(
|
50 |
+
"import sys\n"
|
51 |
+
"class FileLike:\n"
|
52 |
+
" def write(self, x):\n"
|
53 |
+
" try:\n"
|
54 |
+
" of.write(x)\n"
|
55 |
+
" except: pass\n"
|
56 |
+
" self.buf += x\n"
|
57 |
+
" def flush(self):\n"
|
58 |
+
" pass\n"
|
59 |
+
"fl = FileLike()\n"
|
60 |
+
"fl.buf = ''\n"
|
61 |
+
"of = sys.stderr\n"
|
62 |
+
"sys.stderr = fl\n"
|
63 |
+
"def done():\n"
|
64 |
+
" sys.stderr = of\n"
|
65 |
+
" return fl.buf\n", /* make sure the returned value stays alive */
|
66 |
+
Py_file_input,
|
67 |
+
result, result);
|
68 |
+
Py_XDECREF(x);
|
69 |
+
|
70 |
+
error:
|
71 |
+
if (PyErr_Occurred())
|
72 |
+
{
|
73 |
+
PyErr_WriteUnraisable(Py_None);
|
74 |
+
PyErr_Clear();
|
75 |
+
}
|
76 |
+
return result;
|
77 |
+
}
|
78 |
+
|
79 |
+
#pragma comment(lib, "user32.lib")
|
80 |
+
|
81 |
+
static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored)
|
82 |
+
{
|
83 |
+
Sleep(666); /* may be interrupted if the whole process is closing */
|
84 |
+
#if PY_MAJOR_VERSION >= 3
|
85 |
+
MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text,
|
86 |
+
L"Python-CFFI error",
|
87 |
+
MB_OK | MB_ICONERROR);
|
88 |
+
#else
|
89 |
+
MessageBoxA(NULL, (char *)_cffi_bootstrap_text,
|
90 |
+
"Python-CFFI error",
|
91 |
+
MB_OK | MB_ICONERROR);
|
92 |
+
#endif
|
93 |
+
_cffi_bootstrap_text = NULL;
|
94 |
+
return 0;
|
95 |
+
}
|
96 |
+
|
97 |
+
static void _cffi_stop_error_capture(PyObject *ecap)
|
98 |
+
{
|
99 |
+
PyObject *s;
|
100 |
+
void *text;
|
101 |
+
|
102 |
+
if (ecap == (PyObject *)1)
|
103 |
+
return;
|
104 |
+
|
105 |
+
if (ecap == NULL)
|
106 |
+
goto error;
|
107 |
+
|
108 |
+
s = PyRun_String("done()", Py_eval_input, ecap, ecap);
|
109 |
+
if (s == NULL)
|
110 |
+
goto error;
|
111 |
+
|
112 |
+
/* Show a dialog box, but in a background thread, and
|
113 |
+
never show multiple dialog boxes at once. */
|
114 |
+
#if PY_MAJOR_VERSION >= 3
|
115 |
+
text = PyUnicode_AsWideCharString(s, NULL);
|
116 |
+
#else
|
117 |
+
text = PyString_AsString(s);
|
118 |
+
#endif
|
119 |
+
|
120 |
+
_cffi_bootstrap_text = text;
|
121 |
+
|
122 |
+
if (text != NULL)
|
123 |
+
{
|
124 |
+
HANDLE h;
|
125 |
+
h = CreateThread(NULL, 0, _cffi_bootstrap_dialog,
|
126 |
+
NULL, 0, NULL);
|
127 |
+
if (h != NULL)
|
128 |
+
CloseHandle(h);
|
129 |
+
}
|
130 |
+
/* decref the string, but it should stay alive as 'fl.buf'
|
131 |
+
in the small module above. It will really be freed only if
|
132 |
+
we later get another similar error. So it's a leak of at
|
133 |
+
most one copy of the small module. That's fine for this
|
134 |
+
situation which is usually a "fatal error" anyway. */
|
135 |
+
Py_DECREF(s);
|
136 |
+
PyErr_Clear();
|
137 |
+
return;
|
138 |
+
|
139 |
+
error:
|
140 |
+
_cffi_bootstrap_text = NULL;
|
141 |
+
PyErr_Clear();
|
142 |
+
}
|
143 |
+
|
144 |
+
#else
|
145 |
+
|
146 |
+
static PyObject *_cffi_start_error_capture(void) { return NULL; }
|
147 |
+
static void _cffi_stop_error_capture(PyObject *ecap) { }
|
148 |
+
|
149 |
+
#endif
|
cffi/_cffi_include.h
ADDED
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#define _CFFI_
|
2 |
+
|
3 |
+
/* We try to define Py_LIMITED_API before including Python.h.
|
4 |
+
|
5 |
+
Mess: we can only define it if Py_DEBUG, Py_TRACE_REFS and
|
6 |
+
Py_REF_DEBUG are not defined. This is a best-effort approximation:
|
7 |
+
we can learn about Py_DEBUG from pyconfig.h, but it is unclear if
|
8 |
+
the same works for the other two macros. Py_DEBUG implies them,
|
9 |
+
but not the other way around.
|
10 |
+
|
11 |
+
The implementation is messy (issue #350): on Windows, with _MSC_VER,
|
12 |
+
we have to define Py_LIMITED_API even before including pyconfig.h.
|
13 |
+
In that case, we guess what pyconfig.h will do to the macros above,
|
14 |
+
and check our guess after the #include.
|
15 |
+
|
16 |
+
Note that on Windows, with CPython 3.x, you need >= 3.5 and virtualenv
|
17 |
+
version >= 16.0.0. With older versions of either, you don't get a
|
18 |
+
copy of PYTHON3.DLL in the virtualenv. We can't check the version of
|
19 |
+
CPython *before* we even include pyconfig.h. ffi.set_source() puts
|
20 |
+
a ``#define _CFFI_NO_LIMITED_API'' at the start of this file if it is
|
21 |
+
running on Windows < 3.5, as an attempt at fixing it, but that's
|
22 |
+
arguably wrong because it may not be the target version of Python.
|
23 |
+
Still better than nothing I guess. As another workaround, you can
|
24 |
+
remove the definition of Py_LIMITED_API here.
|
25 |
+
|
26 |
+
See also 'py_limited_api' in cffi/setuptools_ext.py.
|
27 |
+
*/
|
28 |
+
#if !defined(_CFFI_USE_EMBEDDING) && !defined(Py_LIMITED_API)
|
29 |
+
# ifdef _MSC_VER
|
30 |
+
# if !defined(_DEBUG) && !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API)
|
31 |
+
# define Py_LIMITED_API
|
32 |
+
# endif
|
33 |
+
# include <pyconfig.h>
|
34 |
+
/* sanity-check: Py_LIMITED_API will cause crashes if any of these
|
35 |
+
are also defined. Normally, the Python file PC/pyconfig.h does not
|
36 |
+
cause any of these to be defined, with the exception that _DEBUG
|
37 |
+
causes Py_DEBUG. Double-check that. */
|
38 |
+
# ifdef Py_LIMITED_API
|
39 |
+
# if defined(Py_DEBUG)
|
40 |
+
# error "pyconfig.h unexpectedly defines Py_DEBUG, but Py_LIMITED_API is set"
|
41 |
+
# endif
|
42 |
+
# if defined(Py_TRACE_REFS)
|
43 |
+
# error "pyconfig.h unexpectedly defines Py_TRACE_REFS, but Py_LIMITED_API is set"
|
44 |
+
# endif
|
45 |
+
# if defined(Py_REF_DEBUG)
|
46 |
+
# error "pyconfig.h unexpectedly defines Py_REF_DEBUG, but Py_LIMITED_API is set"
|
47 |
+
# endif
|
48 |
+
# endif
|
49 |
+
# else
|
50 |
+
# include <pyconfig.h>
|
51 |
+
# if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API)
|
52 |
+
# define Py_LIMITED_API
|
53 |
+
# endif
|
54 |
+
# endif
|
55 |
+
#endif
|
56 |
+
|
57 |
+
#include <Python.h>
|
58 |
+
#ifdef __cplusplus
|
59 |
+
extern "C" {
|
60 |
+
#endif
|
61 |
+
#include <stddef.h>
|
62 |
+
#include "parse_c_type.h"
|
63 |
+
|
64 |
+
/* this block of #ifs should be kept exactly identical between
|
65 |
+
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
|
66 |
+
and cffi/_cffi_include.h */
|
67 |
+
#if defined(_MSC_VER)
|
68 |
+
# include <malloc.h> /* for alloca() */
|
69 |
+
# if _MSC_VER < 1600 /* MSVC < 2010 */
|
70 |
+
typedef __int8 int8_t;
|
71 |
+
typedef __int16 int16_t;
|
72 |
+
typedef __int32 int32_t;
|
73 |
+
typedef __int64 int64_t;
|
74 |
+
typedef unsigned __int8 uint8_t;
|
75 |
+
typedef unsigned __int16 uint16_t;
|
76 |
+
typedef unsigned __int32 uint32_t;
|
77 |
+
typedef unsigned __int64 uint64_t;
|
78 |
+
typedef __int8 int_least8_t;
|
79 |
+
typedef __int16 int_least16_t;
|
80 |
+
typedef __int32 int_least32_t;
|
81 |
+
typedef __int64 int_least64_t;
|
82 |
+
typedef unsigned __int8 uint_least8_t;
|
83 |
+
typedef unsigned __int16 uint_least16_t;
|
84 |
+
typedef unsigned __int32 uint_least32_t;
|
85 |
+
typedef unsigned __int64 uint_least64_t;
|
86 |
+
typedef __int8 int_fast8_t;
|
87 |
+
typedef __int16 int_fast16_t;
|
88 |
+
typedef __int32 int_fast32_t;
|
89 |
+
typedef __int64 int_fast64_t;
|
90 |
+
typedef unsigned __int8 uint_fast8_t;
|
91 |
+
typedef unsigned __int16 uint_fast16_t;
|
92 |
+
typedef unsigned __int32 uint_fast32_t;
|
93 |
+
typedef unsigned __int64 uint_fast64_t;
|
94 |
+
typedef __int64 intmax_t;
|
95 |
+
typedef unsigned __int64 uintmax_t;
|
96 |
+
# else
|
97 |
+
# include <stdint.h>
|
98 |
+
# endif
|
99 |
+
# if _MSC_VER < 1800 /* MSVC < 2013 */
|
100 |
+
# ifndef __cplusplus
|
101 |
+
typedef unsigned char _Bool;
|
102 |
+
# endif
|
103 |
+
# endif
|
104 |
+
# define _cffi_float_complex_t _Fcomplex /* include <complex.h> for it */
|
105 |
+
# define _cffi_double_complex_t _Dcomplex /* include <complex.h> for it */
|
106 |
+
#else
|
107 |
+
# include <stdint.h>
|
108 |
+
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
|
109 |
+
# include <alloca.h>
|
110 |
+
# endif
|
111 |
+
# define _cffi_float_complex_t float _Complex
|
112 |
+
# define _cffi_double_complex_t double _Complex
|
113 |
+
#endif
|
114 |
+
|
115 |
+
#ifdef __GNUC__
|
116 |
+
# define _CFFI_UNUSED_FN __attribute__((unused))
|
117 |
+
#else
|
118 |
+
# define _CFFI_UNUSED_FN /* nothing */
|
119 |
+
#endif
|
120 |
+
|
121 |
+
#ifdef __cplusplus
|
122 |
+
# ifndef _Bool
|
123 |
+
typedef bool _Bool; /* semi-hackish: C++ has no _Bool; bool is builtin */
|
124 |
+
# endif
|
125 |
+
#endif
|
126 |
+
|
127 |
+
/********** CPython-specific section **********/
|
128 |
+
#ifndef PYPY_VERSION
|
129 |
+
|
130 |
+
|
131 |
+
#if PY_MAJOR_VERSION >= 3
|
132 |
+
# define PyInt_FromLong PyLong_FromLong
|
133 |
+
#endif
|
134 |
+
|
135 |
+
#define _cffi_from_c_double PyFloat_FromDouble
|
136 |
+
#define _cffi_from_c_float PyFloat_FromDouble
|
137 |
+
#define _cffi_from_c_long PyInt_FromLong
|
138 |
+
#define _cffi_from_c_ulong PyLong_FromUnsignedLong
|
139 |
+
#define _cffi_from_c_longlong PyLong_FromLongLong
|
140 |
+
#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong
|
141 |
+
#define _cffi_from_c__Bool PyBool_FromLong
|
142 |
+
|
143 |
+
#define _cffi_to_c_double PyFloat_AsDouble
|
144 |
+
#define _cffi_to_c_float PyFloat_AsDouble
|
145 |
+
|
146 |
+
#define _cffi_from_c_int(x, type) \
|
147 |
+
(((type)-1) > 0 ? /* unsigned */ \
|
148 |
+
(sizeof(type) < sizeof(long) ? \
|
149 |
+
PyInt_FromLong((long)x) : \
|
150 |
+
sizeof(type) == sizeof(long) ? \
|
151 |
+
PyLong_FromUnsignedLong((unsigned long)x) : \
|
152 |
+
PyLong_FromUnsignedLongLong((unsigned long long)x)) : \
|
153 |
+
(sizeof(type) <= sizeof(long) ? \
|
154 |
+
PyInt_FromLong((long)x) : \
|
155 |
+
PyLong_FromLongLong((long long)x)))
|
156 |
+
|
157 |
+
#define _cffi_to_c_int(o, type) \
|
158 |
+
((type)( \
|
159 |
+
sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \
|
160 |
+
: (type)_cffi_to_c_i8(o)) : \
|
161 |
+
sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \
|
162 |
+
: (type)_cffi_to_c_i16(o)) : \
|
163 |
+
sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \
|
164 |
+
: (type)_cffi_to_c_i32(o)) : \
|
165 |
+
sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \
|
166 |
+
: (type)_cffi_to_c_i64(o)) : \
|
167 |
+
(Py_FatalError("unsupported size for type " #type), (type)0)))
|
168 |
+
|
169 |
+
#define _cffi_to_c_i8 \
|
170 |
+
((int(*)(PyObject *))_cffi_exports[1])
|
171 |
+
#define _cffi_to_c_u8 \
|
172 |
+
((int(*)(PyObject *))_cffi_exports[2])
|
173 |
+
#define _cffi_to_c_i16 \
|
174 |
+
((int(*)(PyObject *))_cffi_exports[3])
|
175 |
+
#define _cffi_to_c_u16 \
|
176 |
+
((int(*)(PyObject *))_cffi_exports[4])
|
177 |
+
#define _cffi_to_c_i32 \
|
178 |
+
((int(*)(PyObject *))_cffi_exports[5])
|
179 |
+
#define _cffi_to_c_u32 \
|
180 |
+
((unsigned int(*)(PyObject *))_cffi_exports[6])
|
181 |
+
#define _cffi_to_c_i64 \
|
182 |
+
((long long(*)(PyObject *))_cffi_exports[7])
|
183 |
+
#define _cffi_to_c_u64 \
|
184 |
+
((unsigned long long(*)(PyObject *))_cffi_exports[8])
|
185 |
+
#define _cffi_to_c_char \
|
186 |
+
((int(*)(PyObject *))_cffi_exports[9])
|
187 |
+
#define _cffi_from_c_pointer \
|
188 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[10])
|
189 |
+
#define _cffi_to_c_pointer \
|
190 |
+
((char *(*)(PyObject *, struct _cffi_ctypedescr *))_cffi_exports[11])
|
191 |
+
#define _cffi_get_struct_layout \
|
192 |
+
not used any more
|
193 |
+
#define _cffi_restore_errno \
|
194 |
+
((void(*)(void))_cffi_exports[13])
|
195 |
+
#define _cffi_save_errno \
|
196 |
+
((void(*)(void))_cffi_exports[14])
|
197 |
+
#define _cffi_from_c_char \
|
198 |
+
((PyObject *(*)(char))_cffi_exports[15])
|
199 |
+
#define _cffi_from_c_deref \
|
200 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[16])
|
201 |
+
#define _cffi_to_c \
|
202 |
+
((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[17])
|
203 |
+
#define _cffi_from_c_struct \
|
204 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[18])
|
205 |
+
#define _cffi_to_c_wchar_t \
|
206 |
+
((_cffi_wchar_t(*)(PyObject *))_cffi_exports[19])
|
207 |
+
#define _cffi_from_c_wchar_t \
|
208 |
+
((PyObject *(*)(_cffi_wchar_t))_cffi_exports[20])
|
209 |
+
#define _cffi_to_c_long_double \
|
210 |
+
((long double(*)(PyObject *))_cffi_exports[21])
|
211 |
+
#define _cffi_to_c__Bool \
|
212 |
+
((_Bool(*)(PyObject *))_cffi_exports[22])
|
213 |
+
#define _cffi_prepare_pointer_call_argument \
|
214 |
+
((Py_ssize_t(*)(struct _cffi_ctypedescr *, \
|
215 |
+
PyObject *, char **))_cffi_exports[23])
|
216 |
+
#define _cffi_convert_array_from_object \
|
217 |
+
((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[24])
|
218 |
+
#define _CFFI_CPIDX 25
|
219 |
+
#define _cffi_call_python \
|
220 |
+
((void(*)(struct _cffi_externpy_s *, char *))_cffi_exports[_CFFI_CPIDX])
|
221 |
+
#define _cffi_to_c_wchar3216_t \
|
222 |
+
((int(*)(PyObject *))_cffi_exports[26])
|
223 |
+
#define _cffi_from_c_wchar3216_t \
|
224 |
+
((PyObject *(*)(int))_cffi_exports[27])
|
225 |
+
#define _CFFI_NUM_EXPORTS 28
|
226 |
+
|
227 |
+
struct _cffi_ctypedescr;
|
228 |
+
|
229 |
+
static void *_cffi_exports[_CFFI_NUM_EXPORTS];
|
230 |
+
|
231 |
+
#define _cffi_type(index) ( \
|
232 |
+
assert((((uintptr_t)_cffi_types[index]) & 1) == 0), \
|
233 |
+
(struct _cffi_ctypedescr *)_cffi_types[index])
|
234 |
+
|
235 |
+
static PyObject *_cffi_init(const char *module_name, Py_ssize_t version,
|
236 |
+
const struct _cffi_type_context_s *ctx)
|
237 |
+
{
|
238 |
+
PyObject *module, *o_arg, *new_module;
|
239 |
+
void *raw[] = {
|
240 |
+
(void *)module_name,
|
241 |
+
(void *)version,
|
242 |
+
(void *)_cffi_exports,
|
243 |
+
(void *)ctx,
|
244 |
+
};
|
245 |
+
|
246 |
+
module = PyImport_ImportModule("_cffi_backend");
|
247 |
+
if (module == NULL)
|
248 |
+
goto failure;
|
249 |
+
|
250 |
+
o_arg = PyLong_FromVoidPtr((void *)raw);
|
251 |
+
if (o_arg == NULL)
|
252 |
+
goto failure;
|
253 |
+
|
254 |
+
new_module = PyObject_CallMethod(
|
255 |
+
module, (char *)"_init_cffi_1_0_external_module", (char *)"O", o_arg);
|
256 |
+
|
257 |
+
Py_DECREF(o_arg);
|
258 |
+
Py_DECREF(module);
|
259 |
+
return new_module;
|
260 |
+
|
261 |
+
failure:
|
262 |
+
Py_XDECREF(module);
|
263 |
+
return NULL;
|
264 |
+
}
|
265 |
+
|
266 |
+
|
267 |
+
#ifdef HAVE_WCHAR_H
|
268 |
+
typedef wchar_t _cffi_wchar_t;
|
269 |
+
#else
|
270 |
+
typedef uint16_t _cffi_wchar_t; /* same random pick as _cffi_backend.c */
|
271 |
+
#endif
|
272 |
+
|
273 |
+
_CFFI_UNUSED_FN static uint16_t _cffi_to_c_char16_t(PyObject *o)
|
274 |
+
{
|
275 |
+
if (sizeof(_cffi_wchar_t) == 2)
|
276 |
+
return (uint16_t)_cffi_to_c_wchar_t(o);
|
277 |
+
else
|
278 |
+
return (uint16_t)_cffi_to_c_wchar3216_t(o);
|
279 |
+
}
|
280 |
+
|
281 |
+
_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char16_t(uint16_t x)
|
282 |
+
{
|
283 |
+
if (sizeof(_cffi_wchar_t) == 2)
|
284 |
+
return _cffi_from_c_wchar_t((_cffi_wchar_t)x);
|
285 |
+
else
|
286 |
+
return _cffi_from_c_wchar3216_t((int)x);
|
287 |
+
}
|
288 |
+
|
289 |
+
_CFFI_UNUSED_FN static int _cffi_to_c_char32_t(PyObject *o)
|
290 |
+
{
|
291 |
+
if (sizeof(_cffi_wchar_t) == 4)
|
292 |
+
return (int)_cffi_to_c_wchar_t(o);
|
293 |
+
else
|
294 |
+
return (int)_cffi_to_c_wchar3216_t(o);
|
295 |
+
}
|
296 |
+
|
297 |
+
_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char32_t(unsigned int x)
|
298 |
+
{
|
299 |
+
if (sizeof(_cffi_wchar_t) == 4)
|
300 |
+
return _cffi_from_c_wchar_t((_cffi_wchar_t)x);
|
301 |
+
else
|
302 |
+
return _cffi_from_c_wchar3216_t((int)x);
|
303 |
+
}
|
304 |
+
|
305 |
+
union _cffi_union_alignment_u {
|
306 |
+
unsigned char m_char;
|
307 |
+
unsigned short m_short;
|
308 |
+
unsigned int m_int;
|
309 |
+
unsigned long m_long;
|
310 |
+
unsigned long long m_longlong;
|
311 |
+
float m_float;
|
312 |
+
double m_double;
|
313 |
+
long double m_longdouble;
|
314 |
+
};
|
315 |
+
|
316 |
+
struct _cffi_freeme_s {
|
317 |
+
struct _cffi_freeme_s *next;
|
318 |
+
union _cffi_union_alignment_u alignment;
|
319 |
+
};
|
320 |
+
|
321 |
+
_CFFI_UNUSED_FN static int
|
322 |
+
_cffi_convert_array_argument(struct _cffi_ctypedescr *ctptr, PyObject *arg,
|
323 |
+
char **output_data, Py_ssize_t datasize,
|
324 |
+
struct _cffi_freeme_s **freeme)
|
325 |
+
{
|
326 |
+
char *p;
|
327 |
+
if (datasize < 0)
|
328 |
+
return -1;
|
329 |
+
|
330 |
+
p = *output_data;
|
331 |
+
if (p == NULL) {
|
332 |
+
struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc(
|
333 |
+
offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize);
|
334 |
+
if (fp == NULL)
|
335 |
+
return -1;
|
336 |
+
fp->next = *freeme;
|
337 |
+
*freeme = fp;
|
338 |
+
p = *output_data = (char *)&fp->alignment;
|
339 |
+
}
|
340 |
+
memset((void *)p, 0, (size_t)datasize);
|
341 |
+
return _cffi_convert_array_from_object(p, ctptr, arg);
|
342 |
+
}
|
343 |
+
|
344 |
+
_CFFI_UNUSED_FN static void
|
345 |
+
_cffi_free_array_arguments(struct _cffi_freeme_s *freeme)
|
346 |
+
{
|
347 |
+
do {
|
348 |
+
void *p = (void *)freeme;
|
349 |
+
freeme = freeme->next;
|
350 |
+
PyObject_Free(p);
|
351 |
+
} while (freeme != NULL);
|
352 |
+
}
|
353 |
+
|
354 |
+
/********** end CPython-specific section **********/
|
355 |
+
#else
|
356 |
+
_CFFI_UNUSED_FN
|
357 |
+
static void (*_cffi_call_python_org)(struct _cffi_externpy_s *, char *);
|
358 |
+
# define _cffi_call_python _cffi_call_python_org
|
359 |
+
#endif
|
360 |
+
|
361 |
+
|
362 |
+
#define _cffi_array_len(array) (sizeof(array) / sizeof((array)[0]))
|
363 |
+
|
364 |
+
#define _cffi_prim_int(size, sign) \
|
365 |
+
((size) == 1 ? ((sign) ? _CFFI_PRIM_INT8 : _CFFI_PRIM_UINT8) : \
|
366 |
+
(size) == 2 ? ((sign) ? _CFFI_PRIM_INT16 : _CFFI_PRIM_UINT16) : \
|
367 |
+
(size) == 4 ? ((sign) ? _CFFI_PRIM_INT32 : _CFFI_PRIM_UINT32) : \
|
368 |
+
(size) == 8 ? ((sign) ? _CFFI_PRIM_INT64 : _CFFI_PRIM_UINT64) : \
|
369 |
+
_CFFI__UNKNOWN_PRIM)
|
370 |
+
|
371 |
+
#define _cffi_prim_float(size) \
|
372 |
+
((size) == sizeof(float) ? _CFFI_PRIM_FLOAT : \
|
373 |
+
(size) == sizeof(double) ? _CFFI_PRIM_DOUBLE : \
|
374 |
+
(size) == sizeof(long double) ? _CFFI__UNKNOWN_LONG_DOUBLE : \
|
375 |
+
_CFFI__UNKNOWN_FLOAT_PRIM)
|
376 |
+
|
377 |
+
#define _cffi_check_int(got, got_nonpos, expected) \
|
378 |
+
((got_nonpos) == (expected <= 0) && \
|
379 |
+
(got) == (unsigned long long)expected)
|
380 |
+
|
381 |
+
#ifdef MS_WIN32
|
382 |
+
# define _cffi_stdcall __stdcall
|
383 |
+
#else
|
384 |
+
# define _cffi_stdcall /* nothing */
|
385 |
+
#endif
|
386 |
+
|
387 |
+
#ifdef __cplusplus
|
388 |
+
}
|
389 |
+
#endif
|
cffi/_embedding.h
ADDED
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
/***** Support code for embedding *****/
|
3 |
+
|
4 |
+
#ifdef __cplusplus
|
5 |
+
extern "C" {
|
6 |
+
#endif
|
7 |
+
|
8 |
+
|
9 |
+
#if defined(_WIN32)
|
10 |
+
# define CFFI_DLLEXPORT __declspec(dllexport)
|
11 |
+
#elif defined(__GNUC__)
|
12 |
+
# define CFFI_DLLEXPORT __attribute__((visibility("default")))
|
13 |
+
#else
|
14 |
+
# define CFFI_DLLEXPORT /* nothing */
|
15 |
+
#endif
|
16 |
+
|
17 |
+
|
18 |
+
/* There are two global variables of type _cffi_call_python_fnptr:
|
19 |
+
|
20 |
+
* _cffi_call_python, which we declare just below, is the one called
|
21 |
+
by ``extern "Python"`` implementations.
|
22 |
+
|
23 |
+
* _cffi_call_python_org, which on CPython is actually part of the
|
24 |
+
_cffi_exports[] array, is the function pointer copied from
|
25 |
+
_cffi_backend. If _cffi_start_python() fails, then this is set
|
26 |
+
to NULL; otherwise, it should never be NULL.
|
27 |
+
|
28 |
+
After initialization is complete, both are equal. However, the
|
29 |
+
first one remains equal to &_cffi_start_and_call_python until the
|
30 |
+
very end of initialization, when we are (or should be) sure that
|
31 |
+
concurrent threads also see a completely initialized world, and
|
32 |
+
only then is it changed.
|
33 |
+
*/
|
34 |
+
#undef _cffi_call_python
|
35 |
+
typedef void (*_cffi_call_python_fnptr)(struct _cffi_externpy_s *, char *);
|
36 |
+
static void _cffi_start_and_call_python(struct _cffi_externpy_s *, char *);
|
37 |
+
static _cffi_call_python_fnptr _cffi_call_python = &_cffi_start_and_call_python;
|
38 |
+
|
39 |
+
|
40 |
+
#ifndef _MSC_VER
|
41 |
+
/* --- Assuming a GCC not infinitely old --- */
|
42 |
+
# define cffi_compare_and_swap(l,o,n) __sync_bool_compare_and_swap(l,o,n)
|
43 |
+
# define cffi_write_barrier() __sync_synchronize()
|
44 |
+
# if !defined(__amd64__) && !defined(__x86_64__) && \
|
45 |
+
!defined(__i386__) && !defined(__i386)
|
46 |
+
# define cffi_read_barrier() __sync_synchronize()
|
47 |
+
# else
|
48 |
+
# define cffi_read_barrier() (void)0
|
49 |
+
# endif
|
50 |
+
#else
|
51 |
+
/* --- Windows threads version --- */
|
52 |
+
# include <Windows.h>
|
53 |
+
# define cffi_compare_and_swap(l,o,n) \
|
54 |
+
(InterlockedCompareExchangePointer(l,n,o) == (o))
|
55 |
+
# define cffi_write_barrier() InterlockedCompareExchange(&_cffi_dummy,0,0)
|
56 |
+
# define cffi_read_barrier() (void)0
|
57 |
+
static volatile LONG _cffi_dummy;
|
58 |
+
#endif
|
59 |
+
|
60 |
+
#ifdef WITH_THREAD
|
61 |
+
# ifndef _MSC_VER
|
62 |
+
# include <pthread.h>
|
63 |
+
static pthread_mutex_t _cffi_embed_startup_lock;
|
64 |
+
# else
|
65 |
+
static CRITICAL_SECTION _cffi_embed_startup_lock;
|
66 |
+
# endif
|
67 |
+
static char _cffi_embed_startup_lock_ready = 0;
|
68 |
+
#endif
|
69 |
+
|
70 |
+
static void _cffi_acquire_reentrant_mutex(void)
|
71 |
+
{
|
72 |
+
static void *volatile lock = NULL;
|
73 |
+
|
74 |
+
while (!cffi_compare_and_swap(&lock, NULL, (void *)1)) {
|
75 |
+
/* should ideally do a spin loop instruction here, but
|
76 |
+
hard to do it portably and doesn't really matter I
|
77 |
+
think: pthread_mutex_init() should be very fast, and
|
78 |
+
this is only run at start-up anyway. */
|
79 |
+
}
|
80 |
+
|
81 |
+
#ifdef WITH_THREAD
|
82 |
+
if (!_cffi_embed_startup_lock_ready) {
|
83 |
+
# ifndef _MSC_VER
|
84 |
+
pthread_mutexattr_t attr;
|
85 |
+
pthread_mutexattr_init(&attr);
|
86 |
+
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
|
87 |
+
pthread_mutex_init(&_cffi_embed_startup_lock, &attr);
|
88 |
+
# else
|
89 |
+
InitializeCriticalSection(&_cffi_embed_startup_lock);
|
90 |
+
# endif
|
91 |
+
_cffi_embed_startup_lock_ready = 1;
|
92 |
+
}
|
93 |
+
#endif
|
94 |
+
|
95 |
+
while (!cffi_compare_and_swap(&lock, (void *)1, NULL))
|
96 |
+
;
|
97 |
+
|
98 |
+
#ifndef _MSC_VER
|
99 |
+
pthread_mutex_lock(&_cffi_embed_startup_lock);
|
100 |
+
#else
|
101 |
+
EnterCriticalSection(&_cffi_embed_startup_lock);
|
102 |
+
#endif
|
103 |
+
}
|
104 |
+
|
105 |
+
static void _cffi_release_reentrant_mutex(void)
|
106 |
+
{
|
107 |
+
#ifndef _MSC_VER
|
108 |
+
pthread_mutex_unlock(&_cffi_embed_startup_lock);
|
109 |
+
#else
|
110 |
+
LeaveCriticalSection(&_cffi_embed_startup_lock);
|
111 |
+
#endif
|
112 |
+
}
|
113 |
+
|
114 |
+
|
115 |
+
/********** CPython-specific section **********/
|
116 |
+
#ifndef PYPY_VERSION
|
117 |
+
|
118 |
+
#include "_cffi_errors.h"
|
119 |
+
|
120 |
+
|
121 |
+
#define _cffi_call_python_org _cffi_exports[_CFFI_CPIDX]
|
122 |
+
|
123 |
+
PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(void); /* forward */
|
124 |
+
|
125 |
+
static void _cffi_py_initialize(void)
|
126 |
+
{
|
127 |
+
/* XXX use initsigs=0, which "skips initialization registration of
|
128 |
+
signal handlers, which might be useful when Python is
|
129 |
+
embedded" according to the Python docs. But review and think
|
130 |
+
if it should be a user-controllable setting.
|
131 |
+
|
132 |
+
XXX we should also give a way to write errors to a buffer
|
133 |
+
instead of to stderr.
|
134 |
+
|
135 |
+
XXX if importing 'site' fails, CPython (any version) calls
|
136 |
+
exit(). Should we try to work around this behavior here?
|
137 |
+
*/
|
138 |
+
Py_InitializeEx(0);
|
139 |
+
}
|
140 |
+
|
141 |
+
static int _cffi_initialize_python(void)
|
142 |
+
{
|
143 |
+
/* This initializes Python, imports _cffi_backend, and then the
|
144 |
+
present .dll/.so is set up as a CPython C extension module.
|
145 |
+
*/
|
146 |
+
int result;
|
147 |
+
PyGILState_STATE state;
|
148 |
+
PyObject *pycode=NULL, *global_dict=NULL, *x;
|
149 |
+
PyObject *builtins;
|
150 |
+
|
151 |
+
state = PyGILState_Ensure();
|
152 |
+
|
153 |
+
/* Call the initxxx() function from the present module. It will
|
154 |
+
create and initialize us as a CPython extension module, instead
|
155 |
+
of letting the startup Python code do it---it might reimport
|
156 |
+
the same .dll/.so and get maybe confused on some platforms.
|
157 |
+
It might also have troubles locating the .dll/.so again for all
|
158 |
+
I know.
|
159 |
+
*/
|
160 |
+
(void)_CFFI_PYTHON_STARTUP_FUNC();
|
161 |
+
if (PyErr_Occurred())
|
162 |
+
goto error;
|
163 |
+
|
164 |
+
/* Now run the Python code provided to ffi.embedding_init_code().
|
165 |
+
*/
|
166 |
+
pycode = Py_CompileString(_CFFI_PYTHON_STARTUP_CODE,
|
167 |
+
"<init code for '" _CFFI_MODULE_NAME "'>",
|
168 |
+
Py_file_input);
|
169 |
+
if (pycode == NULL)
|
170 |
+
goto error;
|
171 |
+
global_dict = PyDict_New();
|
172 |
+
if (global_dict == NULL)
|
173 |
+
goto error;
|
174 |
+
builtins = PyEval_GetBuiltins();
|
175 |
+
if (builtins == NULL)
|
176 |
+
goto error;
|
177 |
+
if (PyDict_SetItemString(global_dict, "__builtins__", builtins) < 0)
|
178 |
+
goto error;
|
179 |
+
x = PyEval_EvalCode(
|
180 |
+
#if PY_MAJOR_VERSION < 3
|
181 |
+
(PyCodeObject *)
|
182 |
+
#endif
|
183 |
+
pycode, global_dict, global_dict);
|
184 |
+
if (x == NULL)
|
185 |
+
goto error;
|
186 |
+
Py_DECREF(x);
|
187 |
+
|
188 |
+
/* Done! Now if we've been called from
|
189 |
+
_cffi_start_and_call_python() in an ``extern "Python"``, we can
|
190 |
+
only hope that the Python code did correctly set up the
|
191 |
+
corresponding @ffi.def_extern() function. Otherwise, the
|
192 |
+
general logic of ``extern "Python"`` functions (inside the
|
193 |
+
_cffi_backend module) will find that the reference is still
|
194 |
+
missing and print an error.
|
195 |
+
*/
|
196 |
+
result = 0;
|
197 |
+
done:
|
198 |
+
Py_XDECREF(pycode);
|
199 |
+
Py_XDECREF(global_dict);
|
200 |
+
PyGILState_Release(state);
|
201 |
+
return result;
|
202 |
+
|
203 |
+
error:;
|
204 |
+
{
|
205 |
+
/* Print as much information as potentially useful.
|
206 |
+
Debugging load-time failures with embedding is not fun
|
207 |
+
*/
|
208 |
+
PyObject *ecap;
|
209 |
+
PyObject *exception, *v, *tb, *f, *modules, *mod;
|
210 |
+
PyErr_Fetch(&exception, &v, &tb);
|
211 |
+
ecap = _cffi_start_error_capture();
|
212 |
+
f = PySys_GetObject((char *)"stderr");
|
213 |
+
if (f != NULL && f != Py_None) {
|
214 |
+
PyFile_WriteString(
|
215 |
+
"Failed to initialize the Python-CFFI embedding logic:\n\n", f);
|
216 |
+
}
|
217 |
+
|
218 |
+
if (exception != NULL) {
|
219 |
+
PyErr_NormalizeException(&exception, &v, &tb);
|
220 |
+
PyErr_Display(exception, v, tb);
|
221 |
+
}
|
222 |
+
Py_XDECREF(exception);
|
223 |
+
Py_XDECREF(v);
|
224 |
+
Py_XDECREF(tb);
|
225 |
+
|
226 |
+
if (f != NULL && f != Py_None) {
|
227 |
+
PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME
|
228 |
+
"\ncompiled with cffi version: 1.17.1"
|
229 |
+
"\n_cffi_backend module: ", f);
|
230 |
+
modules = PyImport_GetModuleDict();
|
231 |
+
mod = PyDict_GetItemString(modules, "_cffi_backend");
|
232 |
+
if (mod == NULL) {
|
233 |
+
PyFile_WriteString("not loaded", f);
|
234 |
+
}
|
235 |
+
else {
|
236 |
+
v = PyObject_GetAttrString(mod, "__file__");
|
237 |
+
PyFile_WriteObject(v, f, 0);
|
238 |
+
Py_XDECREF(v);
|
239 |
+
}
|
240 |
+
PyFile_WriteString("\nsys.path: ", f);
|
241 |
+
PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0);
|
242 |
+
PyFile_WriteString("\n\n", f);
|
243 |
+
}
|
244 |
+
_cffi_stop_error_capture(ecap);
|
245 |
+
}
|
246 |
+
result = -1;
|
247 |
+
goto done;
|
248 |
+
}
|
249 |
+
|
250 |
+
#if PY_VERSION_HEX < 0x03080000
|
251 |
+
PyAPI_DATA(char *) _PyParser_TokenNames[]; /* from CPython */
|
252 |
+
#endif
|
253 |
+
|
254 |
+
static int _cffi_carefully_make_gil(void)
|
255 |
+
{
|
256 |
+
/* This does the basic initialization of Python. It can be called
|
257 |
+
completely concurrently from unrelated threads. It assumes
|
258 |
+
that we don't hold the GIL before (if it exists), and we don't
|
259 |
+
hold it afterwards.
|
260 |
+
|
261 |
+
(What it really does used to be completely different in Python 2
|
262 |
+
and Python 3, with the Python 2 solution avoiding the spin-lock
|
263 |
+
around the Py_InitializeEx() call. However, after recent changes
|
264 |
+
to CPython 2.7 (issue #358) it no longer works. So we use the
|
265 |
+
Python 3 solution everywhere.)
|
266 |
+
|
267 |
+
This initializes Python by calling Py_InitializeEx().
|
268 |
+
Important: this must not be called concurrently at all.
|
269 |
+
So we use a global variable as a simple spin lock. This global
|
270 |
+
variable must be from 'libpythonX.Y.so', not from this
|
271 |
+
cffi-based extension module, because it must be shared from
|
272 |
+
different cffi-based extension modules.
|
273 |
+
|
274 |
+
In Python < 3.8, we choose
|
275 |
+
_PyParser_TokenNames[0] as a completely arbitrary pointer value
|
276 |
+
that is never written to. The default is to point to the
|
277 |
+
string "ENDMARKER". We change it temporarily to point to the
|
278 |
+
next character in that string. (Yes, I know it's REALLY
|
279 |
+
obscure.)
|
280 |
+
|
281 |
+
In Python >= 3.8, this string array is no longer writable, so
|
282 |
+
instead we pick PyCapsuleType.tp_version_tag. We can't change
|
283 |
+
Python < 3.8 because someone might use a mixture of cffi
|
284 |
+
embedded modules, some of which were compiled before this file
|
285 |
+
changed.
|
286 |
+
|
287 |
+
In Python >= 3.12, this stopped working because that particular
|
288 |
+
tp_version_tag gets modified during interpreter startup. It's
|
289 |
+
arguably a bad idea before 3.12 too, but again we can't change
|
290 |
+
that because someone might use a mixture of cffi embedded
|
291 |
+
modules, and no-one reported a bug so far. In Python >= 3.12
|
292 |
+
we go instead for PyCapsuleType.tp_as_buffer, which is supposed
|
293 |
+
to always be NULL. We write to it temporarily a pointer to
|
294 |
+
a struct full of NULLs, which is semantically the same.
|
295 |
+
*/
|
296 |
+
|
297 |
+
#ifdef WITH_THREAD
|
298 |
+
# if PY_VERSION_HEX < 0x03080000
|
299 |
+
char *volatile *lock = (char *volatile *)_PyParser_TokenNames;
|
300 |
+
char *old_value, *locked_value;
|
301 |
+
|
302 |
+
while (1) { /* spin loop */
|
303 |
+
old_value = *lock;
|
304 |
+
locked_value = old_value + 1;
|
305 |
+
if (old_value[0] == 'E') {
|
306 |
+
assert(old_value[1] == 'N');
|
307 |
+
if (cffi_compare_and_swap(lock, old_value, locked_value))
|
308 |
+
break;
|
309 |
+
}
|
310 |
+
else {
|
311 |
+
assert(old_value[0] == 'N');
|
312 |
+
/* should ideally do a spin loop instruction here, but
|
313 |
+
hard to do it portably and doesn't really matter I
|
314 |
+
think: PyEval_InitThreads() should be very fast, and
|
315 |
+
this is only run at start-up anyway. */
|
316 |
+
}
|
317 |
+
}
|
318 |
+
# else
|
319 |
+
# if PY_VERSION_HEX < 0x030C0000
|
320 |
+
int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag;
|
321 |
+
int old_value, locked_value = -42;
|
322 |
+
assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG));
|
323 |
+
# else
|
324 |
+
static struct ebp_s { PyBufferProcs buf; int mark; } empty_buffer_procs;
|
325 |
+
empty_buffer_procs.mark = -42;
|
326 |
+
PyBufferProcs *volatile *lock = (PyBufferProcs *volatile *)
|
327 |
+
&PyCapsule_Type.tp_as_buffer;
|
328 |
+
PyBufferProcs *old_value, *locked_value = &empty_buffer_procs.buf;
|
329 |
+
# endif
|
330 |
+
|
331 |
+
while (1) { /* spin loop */
|
332 |
+
old_value = *lock;
|
333 |
+
if (old_value == 0) {
|
334 |
+
if (cffi_compare_and_swap(lock, old_value, locked_value))
|
335 |
+
break;
|
336 |
+
}
|
337 |
+
else {
|
338 |
+
# if PY_VERSION_HEX < 0x030C0000
|
339 |
+
assert(old_value == locked_value);
|
340 |
+
# else
|
341 |
+
/* The pointer should point to a possibly different
|
342 |
+
empty_buffer_procs from another C extension module */
|
343 |
+
assert(((struct ebp_s *)old_value)->mark == -42);
|
344 |
+
# endif
|
345 |
+
/* should ideally do a spin loop instruction here, but
|
346 |
+
hard to do it portably and doesn't really matter I
|
347 |
+
think: PyEval_InitThreads() should be very fast, and
|
348 |
+
this is only run at start-up anyway. */
|
349 |
+
}
|
350 |
+
}
|
351 |
+
# endif
|
352 |
+
#endif
|
353 |
+
|
354 |
+
/* call Py_InitializeEx() */
|
355 |
+
if (!Py_IsInitialized()) {
|
356 |
+
_cffi_py_initialize();
|
357 |
+
#if PY_VERSION_HEX < 0x03070000
|
358 |
+
PyEval_InitThreads();
|
359 |
+
#endif
|
360 |
+
PyEval_SaveThread(); /* release the GIL */
|
361 |
+
/* the returned tstate must be the one that has been stored into the
|
362 |
+
autoTLSkey by _PyGILState_Init() called from Py_Initialize(). */
|
363 |
+
}
|
364 |
+
else {
|
365 |
+
#if PY_VERSION_HEX < 0x03070000
|
366 |
+
/* PyEval_InitThreads() is always a no-op from CPython 3.7 */
|
367 |
+
PyGILState_STATE state = PyGILState_Ensure();
|
368 |
+
PyEval_InitThreads();
|
369 |
+
PyGILState_Release(state);
|
370 |
+
#endif
|
371 |
+
}
|
372 |
+
|
373 |
+
#ifdef WITH_THREAD
|
374 |
+
/* release the lock */
|
375 |
+
while (!cffi_compare_and_swap(lock, locked_value, old_value))
|
376 |
+
;
|
377 |
+
#endif
|
378 |
+
|
379 |
+
return 0;
|
380 |
+
}
|
381 |
+
|
382 |
+
/********** end CPython-specific section **********/
|
383 |
+
|
384 |
+
|
385 |
+
#else
|
386 |
+
|
387 |
+
|
388 |
+
/********** PyPy-specific section **********/
|
389 |
+
|
390 |
+
PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */
|
391 |
+
|
392 |
+
static struct _cffi_pypy_init_s {
|
393 |
+
const char *name;
|
394 |
+
void *func; /* function pointer */
|
395 |
+
const char *code;
|
396 |
+
} _cffi_pypy_init = {
|
397 |
+
_CFFI_MODULE_NAME,
|
398 |
+
_CFFI_PYTHON_STARTUP_FUNC,
|
399 |
+
_CFFI_PYTHON_STARTUP_CODE,
|
400 |
+
};
|
401 |
+
|
402 |
+
extern int pypy_carefully_make_gil(const char *);
|
403 |
+
extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *);
|
404 |
+
|
405 |
+
static int _cffi_carefully_make_gil(void)
|
406 |
+
{
|
407 |
+
return pypy_carefully_make_gil(_CFFI_MODULE_NAME);
|
408 |
+
}
|
409 |
+
|
410 |
+
static int _cffi_initialize_python(void)
|
411 |
+
{
|
412 |
+
return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init);
|
413 |
+
}
|
414 |
+
|
415 |
+
/********** end PyPy-specific section **********/
|
416 |
+
|
417 |
+
|
418 |
+
#endif
|
419 |
+
|
420 |
+
|
421 |
+
#ifdef __GNUC__
|
422 |
+
__attribute__((noinline))
|
423 |
+
#endif
|
424 |
+
static _cffi_call_python_fnptr _cffi_start_python(void)
|
425 |
+
{
|
426 |
+
/* Delicate logic to initialize Python. This function can be
|
427 |
+
called multiple times concurrently, e.g. when the process calls
|
428 |
+
its first ``extern "Python"`` functions in multiple threads at
|
429 |
+
once. It can also be called recursively, in which case we must
|
430 |
+
ignore it. We also have to consider what occurs if several
|
431 |
+
different cffi-based extensions reach this code in parallel
|
432 |
+
threads---it is a different copy of the code, then, and we
|
433 |
+
can't have any shared global variable unless it comes from
|
434 |
+
'libpythonX.Y.so'.
|
435 |
+
|
436 |
+
Idea:
|
437 |
+
|
438 |
+
* _cffi_carefully_make_gil(): "carefully" call
|
439 |
+
PyEval_InitThreads() (possibly with Py_InitializeEx() first).
|
440 |
+
|
441 |
+
* then we use a (local) custom lock to make sure that a call to this
|
442 |
+
cffi-based extension will wait if another call to the *same*
|
443 |
+
extension is running the initialization in another thread.
|
444 |
+
It is reentrant, so that a recursive call will not block, but
|
445 |
+
only one from a different thread.
|
446 |
+
|
447 |
+
* then we grab the GIL and (Python 2) we call Py_InitializeEx().
|
448 |
+
At this point, concurrent calls to Py_InitializeEx() are not
|
449 |
+
possible: we have the GIL.
|
450 |
+
|
451 |
+
* do the rest of the specific initialization, which may
|
452 |
+
temporarily release the GIL but not the custom lock.
|
453 |
+
Only release the custom lock when we are done.
|
454 |
+
*/
|
455 |
+
static char called = 0;
|
456 |
+
|
457 |
+
if (_cffi_carefully_make_gil() != 0)
|
458 |
+
return NULL;
|
459 |
+
|
460 |
+
_cffi_acquire_reentrant_mutex();
|
461 |
+
|
462 |
+
/* Here the GIL exists, but we don't have it. We're only protected
|
463 |
+
from concurrency by the reentrant mutex. */
|
464 |
+
|
465 |
+
/* This file only initializes the embedded module once, the first
|
466 |
+
time this is called, even if there are subinterpreters. */
|
467 |
+
if (!called) {
|
468 |
+
called = 1; /* invoke _cffi_initialize_python() only once,
|
469 |
+
but don't set '_cffi_call_python' right now,
|
470 |
+
otherwise concurrent threads won't call
|
471 |
+
this function at all (we need them to wait) */
|
472 |
+
if (_cffi_initialize_python() == 0) {
|
473 |
+
/* now initialization is finished. Switch to the fast-path. */
|
474 |
+
|
475 |
+
/* We would like nobody to see the new value of
|
476 |
+
'_cffi_call_python' without also seeing the rest of the
|
477 |
+
data initialized. However, this is not possible. But
|
478 |
+
the new value of '_cffi_call_python' is the function
|
479 |
+
'cffi_call_python()' from _cffi_backend. So: */
|
480 |
+
cffi_write_barrier();
|
481 |
+
/* ^^^ we put a write barrier here, and a corresponding
|
482 |
+
read barrier at the start of cffi_call_python(). This
|
483 |
+
ensures that after that read barrier, we see everything
|
484 |
+
done here before the write barrier.
|
485 |
+
*/
|
486 |
+
|
487 |
+
assert(_cffi_call_python_org != NULL);
|
488 |
+
_cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org;
|
489 |
+
}
|
490 |
+
else {
|
491 |
+
/* initialization failed. Reset this to NULL, even if it was
|
492 |
+
already set to some other value. Future calls to
|
493 |
+
_cffi_start_python() are still forced to occur, and will
|
494 |
+
always return NULL from now on. */
|
495 |
+
_cffi_call_python_org = NULL;
|
496 |
+
}
|
497 |
+
}
|
498 |
+
|
499 |
+
_cffi_release_reentrant_mutex();
|
500 |
+
|
501 |
+
return (_cffi_call_python_fnptr)_cffi_call_python_org;
|
502 |
+
}
|
503 |
+
|
504 |
+
static
|
505 |
+
void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args)
|
506 |
+
{
|
507 |
+
_cffi_call_python_fnptr fnptr;
|
508 |
+
int current_err = errno;
|
509 |
+
#ifdef _MSC_VER
|
510 |
+
int current_lasterr = GetLastError();
|
511 |
+
#endif
|
512 |
+
fnptr = _cffi_start_python();
|
513 |
+
if (fnptr == NULL) {
|
514 |
+
fprintf(stderr, "function %s() called, but initialization code "
|
515 |
+
"failed. Returning 0.\n", externpy->name);
|
516 |
+
memset(args, 0, externpy->size_of_result);
|
517 |
+
}
|
518 |
+
#ifdef _MSC_VER
|
519 |
+
SetLastError(current_lasterr);
|
520 |
+
#endif
|
521 |
+
errno = current_err;
|
522 |
+
|
523 |
+
if (fnptr != NULL)
|
524 |
+
fnptr(externpy, args);
|
525 |
+
}
|
526 |
+
|
527 |
+
|
528 |
+
/* The cffi_start_python() function makes sure Python is initialized
|
529 |
+
and our cffi module is set up. It can be called manually from the
|
530 |
+
user C code. The same effect is obtained automatically from any
|
531 |
+
dll-exported ``extern "Python"`` function. This function returns
|
532 |
+
-1 if initialization failed, 0 if all is OK. */
|
533 |
+
_CFFI_UNUSED_FN
|
534 |
+
static int cffi_start_python(void)
|
535 |
+
{
|
536 |
+
if (_cffi_call_python == &_cffi_start_and_call_python) {
|
537 |
+
if (_cffi_start_python() == NULL)
|
538 |
+
return -1;
|
539 |
+
}
|
540 |
+
cffi_read_barrier();
|
541 |
+
return 0;
|
542 |
+
}
|
543 |
+
|
544 |
+
#undef cffi_compare_and_swap
|
545 |
+
#undef cffi_write_barrier
|
546 |
+
#undef cffi_read_barrier
|
547 |
+
|
548 |
+
#ifdef __cplusplus
|
549 |
+
}
|
550 |
+
#endif
|
cffi/_imp_emulation.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
try:
|
3 |
+
# this works on Python < 3.12
|
4 |
+
from imp import *
|
5 |
+
|
6 |
+
except ImportError:
|
7 |
+
# this is a limited emulation for Python >= 3.12.
|
8 |
+
# Note that this is used only for tests or for the old ffi.verify().
|
9 |
+
# This is copied from the source code of Python 3.11.
|
10 |
+
|
11 |
+
from _imp import (acquire_lock, release_lock,
|
12 |
+
is_builtin, is_frozen)
|
13 |
+
|
14 |
+
from importlib._bootstrap import _load
|
15 |
+
|
16 |
+
from importlib import machinery
|
17 |
+
import os
|
18 |
+
import sys
|
19 |
+
import tokenize
|
20 |
+
|
21 |
+
SEARCH_ERROR = 0
|
22 |
+
PY_SOURCE = 1
|
23 |
+
PY_COMPILED = 2
|
24 |
+
C_EXTENSION = 3
|
25 |
+
PY_RESOURCE = 4
|
26 |
+
PKG_DIRECTORY = 5
|
27 |
+
C_BUILTIN = 6
|
28 |
+
PY_FROZEN = 7
|
29 |
+
PY_CODERESOURCE = 8
|
30 |
+
IMP_HOOK = 9
|
31 |
+
|
32 |
+
def get_suffixes():
|
33 |
+
extensions = [(s, 'rb', C_EXTENSION)
|
34 |
+
for s in machinery.EXTENSION_SUFFIXES]
|
35 |
+
source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
|
36 |
+
bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
|
37 |
+
return extensions + source + bytecode
|
38 |
+
|
39 |
+
def find_module(name, path=None):
|
40 |
+
if not isinstance(name, str):
|
41 |
+
raise TypeError("'name' must be a str, not {}".format(type(name)))
|
42 |
+
elif not isinstance(path, (type(None), list)):
|
43 |
+
# Backwards-compatibility
|
44 |
+
raise RuntimeError("'path' must be None or a list, "
|
45 |
+
"not {}".format(type(path)))
|
46 |
+
|
47 |
+
if path is None:
|
48 |
+
if is_builtin(name):
|
49 |
+
return None, None, ('', '', C_BUILTIN)
|
50 |
+
elif is_frozen(name):
|
51 |
+
return None, None, ('', '', PY_FROZEN)
|
52 |
+
else:
|
53 |
+
path = sys.path
|
54 |
+
|
55 |
+
for entry in path:
|
56 |
+
package_directory = os.path.join(entry, name)
|
57 |
+
for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
|
58 |
+
package_file_name = '__init__' + suffix
|
59 |
+
file_path = os.path.join(package_directory, package_file_name)
|
60 |
+
if os.path.isfile(file_path):
|
61 |
+
return None, package_directory, ('', '', PKG_DIRECTORY)
|
62 |
+
for suffix, mode, type_ in get_suffixes():
|
63 |
+
file_name = name + suffix
|
64 |
+
file_path = os.path.join(entry, file_name)
|
65 |
+
if os.path.isfile(file_path):
|
66 |
+
break
|
67 |
+
else:
|
68 |
+
continue
|
69 |
+
break # Break out of outer loop when breaking out of inner loop.
|
70 |
+
else:
|
71 |
+
raise ImportError(name, name=name)
|
72 |
+
|
73 |
+
encoding = None
|
74 |
+
if 'b' not in mode:
|
75 |
+
with open(file_path, 'rb') as file:
|
76 |
+
encoding = tokenize.detect_encoding(file.readline)[0]
|
77 |
+
file = open(file_path, mode, encoding=encoding)
|
78 |
+
return file, file_path, (suffix, mode, type_)
|
79 |
+
|
80 |
+
def load_dynamic(name, path, file=None):
|
81 |
+
loader = machinery.ExtensionFileLoader(name, path)
|
82 |
+
spec = machinery.ModuleSpec(name=name, loader=loader, origin=path)
|
83 |
+
return _load(spec)
|
cffi/_shimmed_dist_utils.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Temporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful
|
3 |
+
error messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken.
|
4 |
+
|
5 |
+
This is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since many users don't need runtime compilation support from CFFI.
|
6 |
+
"""
|
7 |
+
import sys
|
8 |
+
|
9 |
+
try:
|
10 |
+
# import setuptools first; this is the most robust way to ensure its embedded distutils is available
|
11 |
+
# (the .pth shim should usually work, but this is even more robust)
|
12 |
+
import setuptools
|
13 |
+
except Exception as ex:
|
14 |
+
if sys.version_info >= (3, 12):
|
15 |
+
# Python 3.12 has no built-in distutils to fall back on, so any import problem is fatal
|
16 |
+
raise Exception("This CFFI feature requires setuptools on Python >= 3.12. The setuptools module is missing or non-functional.") from ex
|
17 |
+
|
18 |
+
# silently ignore on older Pythons (support fallback to stdlib distutils where available)
|
19 |
+
else:
|
20 |
+
del setuptools
|
21 |
+
|
22 |
+
try:
|
23 |
+
# bring in just the bits of distutils we need, whether they really came from setuptools or stdlib-embedded distutils
|
24 |
+
from distutils import log, sysconfig
|
25 |
+
from distutils.ccompiler import CCompiler
|
26 |
+
from distutils.command.build_ext import build_ext
|
27 |
+
from distutils.core import Distribution, Extension
|
28 |
+
from distutils.dir_util import mkpath
|
29 |
+
from distutils.errors import DistutilsSetupError, CompileError, LinkError
|
30 |
+
from distutils.log import set_threshold, set_verbosity
|
31 |
+
|
32 |
+
if sys.platform == 'win32':
|
33 |
+
try:
|
34 |
+
# FUTURE: msvc9compiler module was removed in setuptools 74; consider removing, as it's only used by an ancient patch in `recompiler`
|
35 |
+
from distutils.msvc9compiler import MSVCCompiler
|
36 |
+
except ImportError:
|
37 |
+
MSVCCompiler = None
|
38 |
+
except Exception as ex:
|
39 |
+
if sys.version_info >= (3, 12):
|
40 |
+
raise Exception("This CFFI feature requires setuptools on Python >= 3.12. Please install the setuptools package.") from ex
|
41 |
+
|
42 |
+
# anything older, just let the underlying distutils import error fly
|
43 |
+
raise Exception("This CFFI feature requires distutils. Please install the distutils or setuptools package.") from ex
|
44 |
+
|
45 |
+
del sys
|
cffi/api.py
ADDED
@@ -0,0 +1,967 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys, types
|
2 |
+
from .lock import allocate_lock
|
3 |
+
from .error import CDefError
|
4 |
+
from . import model
|
5 |
+
|
6 |
+
try:
|
7 |
+
callable
|
8 |
+
except NameError:
|
9 |
+
# Python 3.1
|
10 |
+
from collections import Callable
|
11 |
+
callable = lambda x: isinstance(x, Callable)
|
12 |
+
|
13 |
+
try:
|
14 |
+
basestring
|
15 |
+
except NameError:
|
16 |
+
# Python 3.x
|
17 |
+
basestring = str
|
18 |
+
|
19 |
+
_unspecified = object()
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
class FFI(object):
|
24 |
+
r'''
|
25 |
+
The main top-level class that you instantiate once, or once per module.
|
26 |
+
|
27 |
+
Example usage:
|
28 |
+
|
29 |
+
ffi = FFI()
|
30 |
+
ffi.cdef("""
|
31 |
+
int printf(const char *, ...);
|
32 |
+
""")
|
33 |
+
|
34 |
+
C = ffi.dlopen(None) # standard library
|
35 |
+
-or-
|
36 |
+
C = ffi.verify() # use a C compiler: verify the decl above is right
|
37 |
+
|
38 |
+
C.printf("hello, %s!\n", ffi.new("char[]", "world"))
|
39 |
+
'''
|
40 |
+
|
41 |
+
def __init__(self, backend=None):
|
42 |
+
"""Create an FFI instance. The 'backend' argument is used to
|
43 |
+
select a non-default backend, mostly for tests.
|
44 |
+
"""
|
45 |
+
if backend is None:
|
46 |
+
# You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with
|
47 |
+
# _cffi_backend.so compiled.
|
48 |
+
import _cffi_backend as backend
|
49 |
+
from . import __version__
|
50 |
+
if backend.__version__ != __version__:
|
51 |
+
# bad version! Try to be as explicit as possible.
|
52 |
+
if hasattr(backend, '__file__'):
|
53 |
+
# CPython
|
54 |
+
raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % (
|
55 |
+
__version__, __file__,
|
56 |
+
backend.__version__, backend.__file__))
|
57 |
+
else:
|
58 |
+
# PyPy
|
59 |
+
raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % (
|
60 |
+
__version__, __file__, backend.__version__))
|
61 |
+
# (If you insist you can also try to pass the option
|
62 |
+
# 'backend=backend_ctypes.CTypesBackend()', but don't
|
63 |
+
# rely on it! It's probably not going to work well.)
|
64 |
+
|
65 |
+
from . import cparser
|
66 |
+
self._backend = backend
|
67 |
+
self._lock = allocate_lock()
|
68 |
+
self._parser = cparser.Parser()
|
69 |
+
self._cached_btypes = {}
|
70 |
+
self._parsed_types = types.ModuleType('parsed_types').__dict__
|
71 |
+
self._new_types = types.ModuleType('new_types').__dict__
|
72 |
+
self._function_caches = []
|
73 |
+
self._libraries = []
|
74 |
+
self._cdefsources = []
|
75 |
+
self._included_ffis = []
|
76 |
+
self._windows_unicode = None
|
77 |
+
self._init_once_cache = {}
|
78 |
+
self._cdef_version = None
|
79 |
+
self._embedding = None
|
80 |
+
self._typecache = model.get_typecache(backend)
|
81 |
+
if hasattr(backend, 'set_ffi'):
|
82 |
+
backend.set_ffi(self)
|
83 |
+
for name in list(backend.__dict__):
|
84 |
+
if name.startswith('RTLD_'):
|
85 |
+
setattr(self, name, getattr(backend, name))
|
86 |
+
#
|
87 |
+
with self._lock:
|
88 |
+
self.BVoidP = self._get_cached_btype(model.voidp_type)
|
89 |
+
self.BCharA = self._get_cached_btype(model.char_array_type)
|
90 |
+
if isinstance(backend, types.ModuleType):
|
91 |
+
# _cffi_backend: attach these constants to the class
|
92 |
+
if not hasattr(FFI, 'NULL'):
|
93 |
+
FFI.NULL = self.cast(self.BVoidP, 0)
|
94 |
+
FFI.CData, FFI.CType = backend._get_types()
|
95 |
+
else:
|
96 |
+
# ctypes backend: attach these constants to the instance
|
97 |
+
self.NULL = self.cast(self.BVoidP, 0)
|
98 |
+
self.CData, self.CType = backend._get_types()
|
99 |
+
self.buffer = backend.buffer
|
100 |
+
|
101 |
+
def cdef(self, csource, override=False, packed=False, pack=None):
|
102 |
+
"""Parse the given C source. This registers all declared functions,
|
103 |
+
types, and global variables. The functions and global variables can
|
104 |
+
then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'.
|
105 |
+
The types can be used in 'ffi.new()' and other functions.
|
106 |
+
If 'packed' is specified as True, all structs declared inside this
|
107 |
+
cdef are packed, i.e. laid out without any field alignment at all.
|
108 |
+
Alternatively, 'pack' can be a small integer, and requests for
|
109 |
+
alignment greater than that are ignored (pack=1 is equivalent to
|
110 |
+
packed=True).
|
111 |
+
"""
|
112 |
+
self._cdef(csource, override=override, packed=packed, pack=pack)
|
113 |
+
|
114 |
+
def embedding_api(self, csource, packed=False, pack=None):
|
115 |
+
self._cdef(csource, packed=packed, pack=pack, dllexport=True)
|
116 |
+
if self._embedding is None:
|
117 |
+
self._embedding = ''
|
118 |
+
|
119 |
+
def _cdef(self, csource, override=False, **options):
|
120 |
+
if not isinstance(csource, str): # unicode, on Python 2
|
121 |
+
if not isinstance(csource, basestring):
|
122 |
+
raise TypeError("cdef() argument must be a string")
|
123 |
+
csource = csource.encode('ascii')
|
124 |
+
with self._lock:
|
125 |
+
self._cdef_version = object()
|
126 |
+
self._parser.parse(csource, override=override, **options)
|
127 |
+
self._cdefsources.append(csource)
|
128 |
+
if override:
|
129 |
+
for cache in self._function_caches:
|
130 |
+
cache.clear()
|
131 |
+
finishlist = self._parser._recomplete
|
132 |
+
if finishlist:
|
133 |
+
self._parser._recomplete = []
|
134 |
+
for tp in finishlist:
|
135 |
+
tp.finish_backend_type(self, finishlist)
|
136 |
+
|
137 |
+
def dlopen(self, name, flags=0):
|
138 |
+
"""Load and return a dynamic library identified by 'name'.
|
139 |
+
The standard C library can be loaded by passing None.
|
140 |
+
Note that functions and types declared by 'ffi.cdef()' are not
|
141 |
+
linked to a particular library, just like C headers; in the
|
142 |
+
library we only look for the actual (untyped) symbols.
|
143 |
+
"""
|
144 |
+
if not (isinstance(name, basestring) or
|
145 |
+
name is None or
|
146 |
+
isinstance(name, self.CData)):
|
147 |
+
raise TypeError("dlopen(name): name must be a file name, None, "
|
148 |
+
"or an already-opened 'void *' handle")
|
149 |
+
with self._lock:
|
150 |
+
lib, function_cache = _make_ffi_library(self, name, flags)
|
151 |
+
self._function_caches.append(function_cache)
|
152 |
+
self._libraries.append(lib)
|
153 |
+
return lib
|
154 |
+
|
155 |
+
def dlclose(self, lib):
|
156 |
+
"""Close a library obtained with ffi.dlopen(). After this call,
|
157 |
+
access to functions or variables from the library will fail
|
158 |
+
(possibly with a segmentation fault).
|
159 |
+
"""
|
160 |
+
type(lib).__cffi_close__(lib)
|
161 |
+
|
162 |
+
def _typeof_locked(self, cdecl):
|
163 |
+
# call me with the lock!
|
164 |
+
key = cdecl
|
165 |
+
if key in self._parsed_types:
|
166 |
+
return self._parsed_types[key]
|
167 |
+
#
|
168 |
+
if not isinstance(cdecl, str): # unicode, on Python 2
|
169 |
+
cdecl = cdecl.encode('ascii')
|
170 |
+
#
|
171 |
+
type = self._parser.parse_type(cdecl)
|
172 |
+
really_a_function_type = type.is_raw_function
|
173 |
+
if really_a_function_type:
|
174 |
+
type = type.as_function_pointer()
|
175 |
+
btype = self._get_cached_btype(type)
|
176 |
+
result = btype, really_a_function_type
|
177 |
+
self._parsed_types[key] = result
|
178 |
+
return result
|
179 |
+
|
180 |
+
def _typeof(self, cdecl, consider_function_as_funcptr=False):
|
181 |
+
# string -> ctype object
|
182 |
+
try:
|
183 |
+
result = self._parsed_types[cdecl]
|
184 |
+
except KeyError:
|
185 |
+
with self._lock:
|
186 |
+
result = self._typeof_locked(cdecl)
|
187 |
+
#
|
188 |
+
btype, really_a_function_type = result
|
189 |
+
if really_a_function_type and not consider_function_as_funcptr:
|
190 |
+
raise CDefError("the type %r is a function type, not a "
|
191 |
+
"pointer-to-function type" % (cdecl,))
|
192 |
+
return btype
|
193 |
+
|
194 |
+
def typeof(self, cdecl):
|
195 |
+
"""Parse the C type given as a string and return the
|
196 |
+
corresponding <ctype> object.
|
197 |
+
It can also be used on 'cdata' instance to get its C type.
|
198 |
+
"""
|
199 |
+
if isinstance(cdecl, basestring):
|
200 |
+
return self._typeof(cdecl)
|
201 |
+
if isinstance(cdecl, self.CData):
|
202 |
+
return self._backend.typeof(cdecl)
|
203 |
+
if isinstance(cdecl, types.BuiltinFunctionType):
|
204 |
+
res = _builtin_function_type(cdecl)
|
205 |
+
if res is not None:
|
206 |
+
return res
|
207 |
+
if (isinstance(cdecl, types.FunctionType)
|
208 |
+
and hasattr(cdecl, '_cffi_base_type')):
|
209 |
+
with self._lock:
|
210 |
+
return self._get_cached_btype(cdecl._cffi_base_type)
|
211 |
+
raise TypeError(type(cdecl))
|
212 |
+
|
213 |
+
def sizeof(self, cdecl):
|
214 |
+
"""Return the size in bytes of the argument. It can be a
|
215 |
+
string naming a C type, or a 'cdata' instance.
|
216 |
+
"""
|
217 |
+
if isinstance(cdecl, basestring):
|
218 |
+
BType = self._typeof(cdecl)
|
219 |
+
return self._backend.sizeof(BType)
|
220 |
+
else:
|
221 |
+
return self._backend.sizeof(cdecl)
|
222 |
+
|
223 |
+
def alignof(self, cdecl):
|
224 |
+
"""Return the natural alignment size in bytes of the C type
|
225 |
+
given as a string.
|
226 |
+
"""
|
227 |
+
if isinstance(cdecl, basestring):
|
228 |
+
cdecl = self._typeof(cdecl)
|
229 |
+
return self._backend.alignof(cdecl)
|
230 |
+
|
231 |
+
def offsetof(self, cdecl, *fields_or_indexes):
|
232 |
+
"""Return the offset of the named field inside the given
|
233 |
+
structure or array, which must be given as a C type name.
|
234 |
+
You can give several field names in case of nested structures.
|
235 |
+
You can also give numeric values which correspond to array
|
236 |
+
items, in case of an array type.
|
237 |
+
"""
|
238 |
+
if isinstance(cdecl, basestring):
|
239 |
+
cdecl = self._typeof(cdecl)
|
240 |
+
return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
|
241 |
+
|
242 |
+
def new(self, cdecl, init=None):
|
243 |
+
"""Allocate an instance according to the specified C type and
|
244 |
+
return a pointer to it. The specified C type must be either a
|
245 |
+
pointer or an array: ``new('X *')`` allocates an X and returns
|
246 |
+
a pointer to it, whereas ``new('X[n]')`` allocates an array of
|
247 |
+
n X'es and returns an array referencing it (which works
|
248 |
+
mostly like a pointer, like in C). You can also use
|
249 |
+
``new('X[]', n)`` to allocate an array of a non-constant
|
250 |
+
length n.
|
251 |
+
|
252 |
+
The memory is initialized following the rules of declaring a
|
253 |
+
global variable in C: by default it is zero-initialized, but
|
254 |
+
an explicit initializer can be given which can be used to
|
255 |
+
fill all or part of the memory.
|
256 |
+
|
257 |
+
When the returned <cdata> object goes out of scope, the memory
|
258 |
+
is freed. In other words the returned <cdata> object has
|
259 |
+
ownership of the value of type 'cdecl' that it points to. This
|
260 |
+
means that the raw data can be used as long as this object is
|
261 |
+
kept alive, but must not be used for a longer time. Be careful
|
262 |
+
about that when copying the pointer to the memory somewhere
|
263 |
+
else, e.g. into another structure.
|
264 |
+
"""
|
265 |
+
if isinstance(cdecl, basestring):
|
266 |
+
cdecl = self._typeof(cdecl)
|
267 |
+
return self._backend.newp(cdecl, init)
|
268 |
+
|
269 |
+
def new_allocator(self, alloc=None, free=None,
|
270 |
+
should_clear_after_alloc=True):
|
271 |
+
"""Return a new allocator, i.e. a function that behaves like ffi.new()
|
272 |
+
but uses the provided low-level 'alloc' and 'free' functions.
|
273 |
+
|
274 |
+
'alloc' is called with the size as argument. If it returns NULL, a
|
275 |
+
MemoryError is raised. 'free' is called with the result of 'alloc'
|
276 |
+
as argument. Both can be either Python function or directly C
|
277 |
+
functions. If 'free' is None, then no free function is called.
|
278 |
+
If both 'alloc' and 'free' are None, the default is used.
|
279 |
+
|
280 |
+
If 'should_clear_after_alloc' is set to False, then the memory
|
281 |
+
returned by 'alloc' is assumed to be already cleared (or you are
|
282 |
+
fine with garbage); otherwise CFFI will clear it.
|
283 |
+
"""
|
284 |
+
compiled_ffi = self._backend.FFI()
|
285 |
+
allocator = compiled_ffi.new_allocator(alloc, free,
|
286 |
+
should_clear_after_alloc)
|
287 |
+
def allocate(cdecl, init=None):
|
288 |
+
if isinstance(cdecl, basestring):
|
289 |
+
cdecl = self._typeof(cdecl)
|
290 |
+
return allocator(cdecl, init)
|
291 |
+
return allocate
|
292 |
+
|
293 |
+
def cast(self, cdecl, source):
|
294 |
+
"""Similar to a C cast: returns an instance of the named C
|
295 |
+
type initialized with the given 'source'. The source is
|
296 |
+
casted between integers or pointers of any type.
|
297 |
+
"""
|
298 |
+
if isinstance(cdecl, basestring):
|
299 |
+
cdecl = self._typeof(cdecl)
|
300 |
+
return self._backend.cast(cdecl, source)
|
301 |
+
|
302 |
+
def string(self, cdata, maxlen=-1):
|
303 |
+
"""Return a Python string (or unicode string) from the 'cdata'.
|
304 |
+
If 'cdata' is a pointer or array of characters or bytes, returns
|
305 |
+
the null-terminated string. The returned string extends until
|
306 |
+
the first null character, or at most 'maxlen' characters. If
|
307 |
+
'cdata' is an array then 'maxlen' defaults to its length.
|
308 |
+
|
309 |
+
If 'cdata' is a pointer or array of wchar_t, returns a unicode
|
310 |
+
string following the same rules.
|
311 |
+
|
312 |
+
If 'cdata' is a single character or byte or a wchar_t, returns
|
313 |
+
it as a string or unicode string.
|
314 |
+
|
315 |
+
If 'cdata' is an enum, returns the value of the enumerator as a
|
316 |
+
string, or 'NUMBER' if the value is out of range.
|
317 |
+
"""
|
318 |
+
return self._backend.string(cdata, maxlen)
|
319 |
+
|
320 |
+
def unpack(self, cdata, length):
|
321 |
+
"""Unpack an array of C data of the given length,
|
322 |
+
returning a Python string/unicode/list.
|
323 |
+
|
324 |
+
If 'cdata' is a pointer to 'char', returns a byte string.
|
325 |
+
It does not stop at the first null. This is equivalent to:
|
326 |
+
ffi.buffer(cdata, length)[:]
|
327 |
+
|
328 |
+
If 'cdata' is a pointer to 'wchar_t', returns a unicode string.
|
329 |
+
'length' is measured in wchar_t's; it is not the size in bytes.
|
330 |
+
|
331 |
+
If 'cdata' is a pointer to anything else, returns a list of
|
332 |
+
'length' items. This is a faster equivalent to:
|
333 |
+
[cdata[i] for i in range(length)]
|
334 |
+
"""
|
335 |
+
return self._backend.unpack(cdata, length)
|
336 |
+
|
337 |
+
#def buffer(self, cdata, size=-1):
|
338 |
+
# """Return a read-write buffer object that references the raw C data
|
339 |
+
# pointed to by the given 'cdata'. The 'cdata' must be a pointer or
|
340 |
+
# an array. Can be passed to functions expecting a buffer, or directly
|
341 |
+
# manipulated with:
|
342 |
+
#
|
343 |
+
# buf[:] get a copy of it in a regular string, or
|
344 |
+
# buf[idx] as a single character
|
345 |
+
# buf[:] = ...
|
346 |
+
# buf[idx] = ... change the content
|
347 |
+
# """
|
348 |
+
# note that 'buffer' is a type, set on this instance by __init__
|
349 |
+
|
350 |
+
def from_buffer(self, cdecl, python_buffer=_unspecified,
|
351 |
+
require_writable=False):
|
352 |
+
"""Return a cdata of the given type pointing to the data of the
|
353 |
+
given Python object, which must support the buffer interface.
|
354 |
+
Note that this is not meant to be used on the built-in types
|
355 |
+
str or unicode (you can build 'char[]' arrays explicitly)
|
356 |
+
but only on objects containing large quantities of raw data
|
357 |
+
in some other format, like 'array.array' or numpy arrays.
|
358 |
+
|
359 |
+
The first argument is optional and default to 'char[]'.
|
360 |
+
"""
|
361 |
+
if python_buffer is _unspecified:
|
362 |
+
cdecl, python_buffer = self.BCharA, cdecl
|
363 |
+
elif isinstance(cdecl, basestring):
|
364 |
+
cdecl = self._typeof(cdecl)
|
365 |
+
return self._backend.from_buffer(cdecl, python_buffer,
|
366 |
+
require_writable)
|
367 |
+
|
368 |
+
def memmove(self, dest, src, n):
|
369 |
+
"""ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.
|
370 |
+
|
371 |
+
Like the C function memmove(), the memory areas may overlap;
|
372 |
+
apart from that it behaves like the C function memcpy().
|
373 |
+
|
374 |
+
'src' can be any cdata ptr or array, or any Python buffer object.
|
375 |
+
'dest' can be any cdata ptr or array, or a writable Python buffer
|
376 |
+
object. The size to copy, 'n', is always measured in bytes.
|
377 |
+
|
378 |
+
Unlike other methods, this one supports all Python buffer including
|
379 |
+
byte strings and bytearrays---but it still does not support
|
380 |
+
non-contiguous buffers.
|
381 |
+
"""
|
382 |
+
return self._backend.memmove(dest, src, n)
|
383 |
+
|
384 |
+
def callback(self, cdecl, python_callable=None, error=None, onerror=None):
|
385 |
+
"""Return a callback object or a decorator making such a
|
386 |
+
callback object. 'cdecl' must name a C function pointer type.
|
387 |
+
The callback invokes the specified 'python_callable' (which may
|
388 |
+
be provided either directly or via a decorator). Important: the
|
389 |
+
callback object must be manually kept alive for as long as the
|
390 |
+
callback may be invoked from the C level.
|
391 |
+
"""
|
392 |
+
def callback_decorator_wrap(python_callable):
|
393 |
+
if not callable(python_callable):
|
394 |
+
raise TypeError("the 'python_callable' argument "
|
395 |
+
"is not callable")
|
396 |
+
return self._backend.callback(cdecl, python_callable,
|
397 |
+
error, onerror)
|
398 |
+
if isinstance(cdecl, basestring):
|
399 |
+
cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
|
400 |
+
if python_callable is None:
|
401 |
+
return callback_decorator_wrap # decorator mode
|
402 |
+
else:
|
403 |
+
return callback_decorator_wrap(python_callable) # direct mode
|
404 |
+
|
405 |
+
def getctype(self, cdecl, replace_with=''):
|
406 |
+
"""Return a string giving the C type 'cdecl', which may be itself
|
407 |
+
a string or a <ctype> object. If 'replace_with' is given, it gives
|
408 |
+
extra text to append (or insert for more complicated C types), like
|
409 |
+
a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
|
410 |
+
"""
|
411 |
+
if isinstance(cdecl, basestring):
|
412 |
+
cdecl = self._typeof(cdecl)
|
413 |
+
replace_with = replace_with.strip()
|
414 |
+
if (replace_with.startswith('*')
|
415 |
+
and '&[' in self._backend.getcname(cdecl, '&')):
|
416 |
+
replace_with = '(%s)' % replace_with
|
417 |
+
elif replace_with and not replace_with[0] in '[(':
|
418 |
+
replace_with = ' ' + replace_with
|
419 |
+
return self._backend.getcname(cdecl, replace_with)
|
420 |
+
|
421 |
+
def gc(self, cdata, destructor, size=0):
|
422 |
+
"""Return a new cdata object that points to the same
|
423 |
+
data. Later, when this new cdata object is garbage-collected,
|
424 |
+
'destructor(old_cdata_object)' will be called.
|
425 |
+
|
426 |
+
The optional 'size' gives an estimate of the size, used to
|
427 |
+
trigger the garbage collection more eagerly. So far only used
|
428 |
+
on PyPy. It tells the GC that the returned object keeps alive
|
429 |
+
roughly 'size' bytes of external memory.
|
430 |
+
"""
|
431 |
+
return self._backend.gcp(cdata, destructor, size)
|
432 |
+
|
433 |
+
def _get_cached_btype(self, type):
|
434 |
+
assert self._lock.acquire(False) is False
|
435 |
+
# call me with the lock!
|
436 |
+
try:
|
437 |
+
BType = self._cached_btypes[type]
|
438 |
+
except KeyError:
|
439 |
+
finishlist = []
|
440 |
+
BType = type.get_cached_btype(self, finishlist)
|
441 |
+
for type in finishlist:
|
442 |
+
type.finish_backend_type(self, finishlist)
|
443 |
+
return BType
|
444 |
+
|
445 |
+
def verify(self, source='', tmpdir=None, **kwargs):
|
446 |
+
"""Verify that the current ffi signatures compile on this
|
447 |
+
machine, and return a dynamic library object. The dynamic
|
448 |
+
library can be used to call functions and access global
|
449 |
+
variables declared in this 'ffi'. The library is compiled
|
450 |
+
by the C compiler: it gives you C-level API compatibility
|
451 |
+
(including calling macros). This is unlike 'ffi.dlopen()',
|
452 |
+
which requires binary compatibility in the signatures.
|
453 |
+
"""
|
454 |
+
from .verifier import Verifier, _caller_dir_pycache
|
455 |
+
#
|
456 |
+
# If set_unicode(True) was called, insert the UNICODE and
|
457 |
+
# _UNICODE macro declarations
|
458 |
+
if self._windows_unicode:
|
459 |
+
self._apply_windows_unicode(kwargs)
|
460 |
+
#
|
461 |
+
# Set the tmpdir here, and not in Verifier.__init__: it picks
|
462 |
+
# up the caller's directory, which we want to be the caller of
|
463 |
+
# ffi.verify(), as opposed to the caller of Veritier().
|
464 |
+
tmpdir = tmpdir or _caller_dir_pycache()
|
465 |
+
#
|
466 |
+
# Make a Verifier() and use it to load the library.
|
467 |
+
self.verifier = Verifier(self, source, tmpdir, **kwargs)
|
468 |
+
lib = self.verifier.load_library()
|
469 |
+
#
|
470 |
+
# Save the loaded library for keep-alive purposes, even
|
471 |
+
# if the caller doesn't keep it alive itself (it should).
|
472 |
+
self._libraries.append(lib)
|
473 |
+
return lib
|
474 |
+
|
475 |
+
def _get_errno(self):
|
476 |
+
return self._backend.get_errno()
|
477 |
+
def _set_errno(self, errno):
|
478 |
+
self._backend.set_errno(errno)
|
479 |
+
errno = property(_get_errno, _set_errno, None,
|
480 |
+
"the value of 'errno' from/to the C calls")
|
481 |
+
|
482 |
+
def getwinerror(self, code=-1):
|
483 |
+
return self._backend.getwinerror(code)
|
484 |
+
|
485 |
+
def _pointer_to(self, ctype):
|
486 |
+
with self._lock:
|
487 |
+
return model.pointer_cache(self, ctype)
|
488 |
+
|
489 |
+
def addressof(self, cdata, *fields_or_indexes):
|
490 |
+
"""Return the address of a <cdata 'struct-or-union'>.
|
491 |
+
If 'fields_or_indexes' are given, returns the address of that
|
492 |
+
field or array item in the structure or array, recursively in
|
493 |
+
case of nested structures.
|
494 |
+
"""
|
495 |
+
try:
|
496 |
+
ctype = self._backend.typeof(cdata)
|
497 |
+
except TypeError:
|
498 |
+
if '__addressof__' in type(cdata).__dict__:
|
499 |
+
return type(cdata).__addressof__(cdata, *fields_or_indexes)
|
500 |
+
raise
|
501 |
+
if fields_or_indexes:
|
502 |
+
ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes)
|
503 |
+
else:
|
504 |
+
if ctype.kind == "pointer":
|
505 |
+
raise TypeError("addressof(pointer)")
|
506 |
+
offset = 0
|
507 |
+
ctypeptr = self._pointer_to(ctype)
|
508 |
+
return self._backend.rawaddressof(ctypeptr, cdata, offset)
|
509 |
+
|
510 |
+
def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes):
|
511 |
+
ctype, offset = self._backend.typeoffsetof(ctype, field_or_index)
|
512 |
+
for field1 in fields_or_indexes:
|
513 |
+
ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1)
|
514 |
+
offset += offset1
|
515 |
+
return ctype, offset
|
516 |
+
|
517 |
+
def include(self, ffi_to_include):
|
518 |
+
"""Includes the typedefs, structs, unions and enums defined
|
519 |
+
in another FFI instance. Usage is similar to a #include in C,
|
520 |
+
where a part of the program might include types defined in
|
521 |
+
another part for its own usage. Note that the include()
|
522 |
+
method has no effect on functions, constants and global
|
523 |
+
variables, which must anyway be accessed directly from the
|
524 |
+
lib object returned by the original FFI instance.
|
525 |
+
"""
|
526 |
+
if not isinstance(ffi_to_include, FFI):
|
527 |
+
raise TypeError("ffi.include() expects an argument that is also of"
|
528 |
+
" type cffi.FFI, not %r" % (
|
529 |
+
type(ffi_to_include).__name__,))
|
530 |
+
if ffi_to_include is self:
|
531 |
+
raise ValueError("self.include(self)")
|
532 |
+
with ffi_to_include._lock:
|
533 |
+
with self._lock:
|
534 |
+
self._parser.include(ffi_to_include._parser)
|
535 |
+
self._cdefsources.append('[')
|
536 |
+
self._cdefsources.extend(ffi_to_include._cdefsources)
|
537 |
+
self._cdefsources.append(']')
|
538 |
+
self._included_ffis.append(ffi_to_include)
|
539 |
+
|
540 |
+
def new_handle(self, x):
|
541 |
+
return self._backend.newp_handle(self.BVoidP, x)
|
542 |
+
|
543 |
+
def from_handle(self, x):
|
544 |
+
return self._backend.from_handle(x)
|
545 |
+
|
546 |
+
def release(self, x):
|
547 |
+
self._backend.release(x)
|
548 |
+
|
549 |
+
def set_unicode(self, enabled_flag):
|
550 |
+
"""Windows: if 'enabled_flag' is True, enable the UNICODE and
|
551 |
+
_UNICODE defines in C, and declare the types like TCHAR and LPTCSTR
|
552 |
+
to be (pointers to) wchar_t. If 'enabled_flag' is False,
|
553 |
+
declare these types to be (pointers to) plain 8-bit characters.
|
554 |
+
This is mostly for backward compatibility; you usually want True.
|
555 |
+
"""
|
556 |
+
if self._windows_unicode is not None:
|
557 |
+
raise ValueError("set_unicode() can only be called once")
|
558 |
+
enabled_flag = bool(enabled_flag)
|
559 |
+
if enabled_flag:
|
560 |
+
self.cdef("typedef wchar_t TBYTE;"
|
561 |
+
"typedef wchar_t TCHAR;"
|
562 |
+
"typedef const wchar_t *LPCTSTR;"
|
563 |
+
"typedef const wchar_t *PCTSTR;"
|
564 |
+
"typedef wchar_t *LPTSTR;"
|
565 |
+
"typedef wchar_t *PTSTR;"
|
566 |
+
"typedef TBYTE *PTBYTE;"
|
567 |
+
"typedef TCHAR *PTCHAR;")
|
568 |
+
else:
|
569 |
+
self.cdef("typedef char TBYTE;"
|
570 |
+
"typedef char TCHAR;"
|
571 |
+
"typedef const char *LPCTSTR;"
|
572 |
+
"typedef const char *PCTSTR;"
|
573 |
+
"typedef char *LPTSTR;"
|
574 |
+
"typedef char *PTSTR;"
|
575 |
+
"typedef TBYTE *PTBYTE;"
|
576 |
+
"typedef TCHAR *PTCHAR;")
|
577 |
+
self._windows_unicode = enabled_flag
|
578 |
+
|
579 |
+
def _apply_windows_unicode(self, kwds):
|
580 |
+
defmacros = kwds.get('define_macros', ())
|
581 |
+
if not isinstance(defmacros, (list, tuple)):
|
582 |
+
raise TypeError("'define_macros' must be a list or tuple")
|
583 |
+
defmacros = list(defmacros) + [('UNICODE', '1'),
|
584 |
+
('_UNICODE', '1')]
|
585 |
+
kwds['define_macros'] = defmacros
|
586 |
+
|
587 |
+
def _apply_embedding_fix(self, kwds):
|
588 |
+
# must include an argument like "-lpython2.7" for the compiler
|
589 |
+
def ensure(key, value):
|
590 |
+
lst = kwds.setdefault(key, [])
|
591 |
+
if value not in lst:
|
592 |
+
lst.append(value)
|
593 |
+
#
|
594 |
+
if '__pypy__' in sys.builtin_module_names:
|
595 |
+
import os
|
596 |
+
if sys.platform == "win32":
|
597 |
+
# we need 'libpypy-c.lib'. Current distributions of
|
598 |
+
# pypy (>= 4.1) contain it as 'libs/python27.lib'.
|
599 |
+
pythonlib = "python{0[0]}{0[1]}".format(sys.version_info)
|
600 |
+
if hasattr(sys, 'prefix'):
|
601 |
+
ensure('library_dirs', os.path.join(sys.prefix, 'libs'))
|
602 |
+
else:
|
603 |
+
# we need 'libpypy-c.{so,dylib}', which should be by
|
604 |
+
# default located in 'sys.prefix/bin' for installed
|
605 |
+
# systems.
|
606 |
+
if sys.version_info < (3,):
|
607 |
+
pythonlib = "pypy-c"
|
608 |
+
else:
|
609 |
+
pythonlib = "pypy3-c"
|
610 |
+
if hasattr(sys, 'prefix'):
|
611 |
+
ensure('library_dirs', os.path.join(sys.prefix, 'bin'))
|
612 |
+
# On uninstalled pypy's, the libpypy-c is typically found in
|
613 |
+
# .../pypy/goal/.
|
614 |
+
if hasattr(sys, 'prefix'):
|
615 |
+
ensure('library_dirs', os.path.join(sys.prefix, 'pypy', 'goal'))
|
616 |
+
else:
|
617 |
+
if sys.platform == "win32":
|
618 |
+
template = "python%d%d"
|
619 |
+
if hasattr(sys, 'gettotalrefcount'):
|
620 |
+
template += '_d'
|
621 |
+
else:
|
622 |
+
try:
|
623 |
+
import sysconfig
|
624 |
+
except ImportError: # 2.6
|
625 |
+
from cffi._shimmed_dist_utils import sysconfig
|
626 |
+
template = "python%d.%d"
|
627 |
+
if sysconfig.get_config_var('DEBUG_EXT'):
|
628 |
+
template += sysconfig.get_config_var('DEBUG_EXT')
|
629 |
+
pythonlib = (template %
|
630 |
+
(sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
|
631 |
+
if hasattr(sys, 'abiflags'):
|
632 |
+
pythonlib += sys.abiflags
|
633 |
+
ensure('libraries', pythonlib)
|
634 |
+
if sys.platform == "win32":
|
635 |
+
ensure('extra_link_args', '/MANIFEST')
|
636 |
+
|
637 |
+
def set_source(self, module_name, source, source_extension='.c', **kwds):
|
638 |
+
import os
|
639 |
+
if hasattr(self, '_assigned_source'):
|
640 |
+
raise ValueError("set_source() cannot be called several times "
|
641 |
+
"per ffi object")
|
642 |
+
if not isinstance(module_name, basestring):
|
643 |
+
raise TypeError("'module_name' must be a string")
|
644 |
+
if os.sep in module_name or (os.altsep and os.altsep in module_name):
|
645 |
+
raise ValueError("'module_name' must not contain '/': use a dotted "
|
646 |
+
"name to make a 'package.module' location")
|
647 |
+
self._assigned_source = (str(module_name), source,
|
648 |
+
source_extension, kwds)
|
649 |
+
|
650 |
+
def set_source_pkgconfig(self, module_name, pkgconfig_libs, source,
|
651 |
+
source_extension='.c', **kwds):
|
652 |
+
from . import pkgconfig
|
653 |
+
if not isinstance(pkgconfig_libs, list):
|
654 |
+
raise TypeError("the pkgconfig_libs argument must be a list "
|
655 |
+
"of package names")
|
656 |
+
kwds2 = pkgconfig.flags_from_pkgconfig(pkgconfig_libs)
|
657 |
+
pkgconfig.merge_flags(kwds, kwds2)
|
658 |
+
self.set_source(module_name, source, source_extension, **kwds)
|
659 |
+
|
660 |
+
def distutils_extension(self, tmpdir='build', verbose=True):
|
661 |
+
from cffi._shimmed_dist_utils import mkpath
|
662 |
+
from .recompiler import recompile
|
663 |
+
#
|
664 |
+
if not hasattr(self, '_assigned_source'):
|
665 |
+
if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored
|
666 |
+
return self.verifier.get_extension()
|
667 |
+
raise ValueError("set_source() must be called before"
|
668 |
+
" distutils_extension()")
|
669 |
+
module_name, source, source_extension, kwds = self._assigned_source
|
670 |
+
if source is None:
|
671 |
+
raise TypeError("distutils_extension() is only for C extension "
|
672 |
+
"modules, not for dlopen()-style pure Python "
|
673 |
+
"modules")
|
674 |
+
mkpath(tmpdir)
|
675 |
+
ext, updated = recompile(self, module_name,
|
676 |
+
source, tmpdir=tmpdir, extradir=tmpdir,
|
677 |
+
source_extension=source_extension,
|
678 |
+
call_c_compiler=False, **kwds)
|
679 |
+
if verbose:
|
680 |
+
if updated:
|
681 |
+
sys.stderr.write("regenerated: %r\n" % (ext.sources[0],))
|
682 |
+
else:
|
683 |
+
sys.stderr.write("not modified: %r\n" % (ext.sources[0],))
|
684 |
+
return ext
|
685 |
+
|
686 |
+
def emit_c_code(self, filename):
|
687 |
+
from .recompiler import recompile
|
688 |
+
#
|
689 |
+
if not hasattr(self, '_assigned_source'):
|
690 |
+
raise ValueError("set_source() must be called before emit_c_code()")
|
691 |
+
module_name, source, source_extension, kwds = self._assigned_source
|
692 |
+
if source is None:
|
693 |
+
raise TypeError("emit_c_code() is only for C extension modules, "
|
694 |
+
"not for dlopen()-style pure Python modules")
|
695 |
+
recompile(self, module_name, source,
|
696 |
+
c_file=filename, call_c_compiler=False,
|
697 |
+
uses_ffiplatform=False, **kwds)
|
698 |
+
|
699 |
+
def emit_python_code(self, filename):
|
700 |
+
from .recompiler import recompile
|
701 |
+
#
|
702 |
+
if not hasattr(self, '_assigned_source'):
|
703 |
+
raise ValueError("set_source() must be called before emit_c_code()")
|
704 |
+
module_name, source, source_extension, kwds = self._assigned_source
|
705 |
+
if source is not None:
|
706 |
+
raise TypeError("emit_python_code() is only for dlopen()-style "
|
707 |
+
"pure Python modules, not for C extension modules")
|
708 |
+
recompile(self, module_name, source,
|
709 |
+
c_file=filename, call_c_compiler=False,
|
710 |
+
uses_ffiplatform=False, **kwds)
|
711 |
+
|
712 |
+
def compile(self, tmpdir='.', verbose=0, target=None, debug=None):
|
713 |
+
"""The 'target' argument gives the final file name of the
|
714 |
+
compiled DLL. Use '*' to force distutils' choice, suitable for
|
715 |
+
regular CPython C API modules. Use a file name ending in '.*'
|
716 |
+
to ask for the system's default extension for dynamic libraries
|
717 |
+
(.so/.dll/.dylib).
|
718 |
+
|
719 |
+
The default is '*' when building a non-embedded C API extension,
|
720 |
+
and (module_name + '.*') when building an embedded library.
|
721 |
+
"""
|
722 |
+
from .recompiler import recompile
|
723 |
+
#
|
724 |
+
if not hasattr(self, '_assigned_source'):
|
725 |
+
raise ValueError("set_source() must be called before compile()")
|
726 |
+
module_name, source, source_extension, kwds = self._assigned_source
|
727 |
+
return recompile(self, module_name, source, tmpdir=tmpdir,
|
728 |
+
target=target, source_extension=source_extension,
|
729 |
+
compiler_verbose=verbose, debug=debug, **kwds)
|
730 |
+
|
731 |
+
def init_once(self, func, tag):
|
732 |
+
# Read _init_once_cache[tag], which is either (False, lock) if
|
733 |
+
# we're calling the function now in some thread, or (True, result).
|
734 |
+
# Don't call setdefault() in most cases, to avoid allocating and
|
735 |
+
# immediately freeing a lock; but still use setdefaut() to avoid
|
736 |
+
# races.
|
737 |
+
try:
|
738 |
+
x = self._init_once_cache[tag]
|
739 |
+
except KeyError:
|
740 |
+
x = self._init_once_cache.setdefault(tag, (False, allocate_lock()))
|
741 |
+
# Common case: we got (True, result), so we return the result.
|
742 |
+
if x[0]:
|
743 |
+
return x[1]
|
744 |
+
# Else, it's a lock. Acquire it to serialize the following tests.
|
745 |
+
with x[1]:
|
746 |
+
# Read again from _init_once_cache the current status.
|
747 |
+
x = self._init_once_cache[tag]
|
748 |
+
if x[0]:
|
749 |
+
return x[1]
|
750 |
+
# Call the function and store the result back.
|
751 |
+
result = func()
|
752 |
+
self._init_once_cache[tag] = (True, result)
|
753 |
+
return result
|
754 |
+
|
755 |
+
def embedding_init_code(self, pysource):
|
756 |
+
if self._embedding:
|
757 |
+
raise ValueError("embedding_init_code() can only be called once")
|
758 |
+
# fix 'pysource' before it gets dumped into the C file:
|
759 |
+
# - remove empty lines at the beginning, so it starts at "line 1"
|
760 |
+
# - dedent, if all non-empty lines are indented
|
761 |
+
# - check for SyntaxErrors
|
762 |
+
import re
|
763 |
+
match = re.match(r'\s*\n', pysource)
|
764 |
+
if match:
|
765 |
+
pysource = pysource[match.end():]
|
766 |
+
lines = pysource.splitlines() or ['']
|
767 |
+
prefix = re.match(r'\s*', lines[0]).group()
|
768 |
+
for i in range(1, len(lines)):
|
769 |
+
line = lines[i]
|
770 |
+
if line.rstrip():
|
771 |
+
while not line.startswith(prefix):
|
772 |
+
prefix = prefix[:-1]
|
773 |
+
i = len(prefix)
|
774 |
+
lines = [line[i:]+'\n' for line in lines]
|
775 |
+
pysource = ''.join(lines)
|
776 |
+
#
|
777 |
+
compile(pysource, "cffi_init", "exec")
|
778 |
+
#
|
779 |
+
self._embedding = pysource
|
780 |
+
|
781 |
+
def def_extern(self, *args, **kwds):
|
782 |
+
raise ValueError("ffi.def_extern() is only available on API-mode FFI "
|
783 |
+
"objects")
|
784 |
+
|
785 |
+
def list_types(self):
|
786 |
+
"""Returns the user type names known to this FFI instance.
|
787 |
+
This returns a tuple containing three lists of names:
|
788 |
+
(typedef_names, names_of_structs, names_of_unions)
|
789 |
+
"""
|
790 |
+
typedefs = []
|
791 |
+
structs = []
|
792 |
+
unions = []
|
793 |
+
for key in self._parser._declarations:
|
794 |
+
if key.startswith('typedef '):
|
795 |
+
typedefs.append(key[8:])
|
796 |
+
elif key.startswith('struct '):
|
797 |
+
structs.append(key[7:])
|
798 |
+
elif key.startswith('union '):
|
799 |
+
unions.append(key[6:])
|
800 |
+
typedefs.sort()
|
801 |
+
structs.sort()
|
802 |
+
unions.sort()
|
803 |
+
return (typedefs, structs, unions)
|
804 |
+
|
805 |
+
|
806 |
+
def _load_backend_lib(backend, name, flags):
|
807 |
+
import os
|
808 |
+
if not isinstance(name, basestring):
|
809 |
+
if sys.platform != "win32" or name is not None:
|
810 |
+
return backend.load_library(name, flags)
|
811 |
+
name = "c" # Windows: load_library(None) fails, but this works
|
812 |
+
# on Python 2 (backward compatibility hack only)
|
813 |
+
first_error = None
|
814 |
+
if '.' in name or '/' in name or os.sep in name:
|
815 |
+
try:
|
816 |
+
return backend.load_library(name, flags)
|
817 |
+
except OSError as e:
|
818 |
+
first_error = e
|
819 |
+
import ctypes.util
|
820 |
+
path = ctypes.util.find_library(name)
|
821 |
+
if path is None:
|
822 |
+
if name == "c" and sys.platform == "win32" and sys.version_info >= (3,):
|
823 |
+
raise OSError("dlopen(None) cannot work on Windows for Python 3 "
|
824 |
+
"(see http://bugs.python.org/issue23606)")
|
825 |
+
msg = ("ctypes.util.find_library() did not manage "
|
826 |
+
"to locate a library called %r" % (name,))
|
827 |
+
if first_error is not None:
|
828 |
+
msg = "%s. Additionally, %s" % (first_error, msg)
|
829 |
+
raise OSError(msg)
|
830 |
+
return backend.load_library(path, flags)
|
831 |
+
|
832 |
+
def _make_ffi_library(ffi, libname, flags):
|
833 |
+
backend = ffi._backend
|
834 |
+
backendlib = _load_backend_lib(backend, libname, flags)
|
835 |
+
#
|
836 |
+
def accessor_function(name):
|
837 |
+
key = 'function ' + name
|
838 |
+
tp, _ = ffi._parser._declarations[key]
|
839 |
+
BType = ffi._get_cached_btype(tp)
|
840 |
+
value = backendlib.load_function(BType, name)
|
841 |
+
library.__dict__[name] = value
|
842 |
+
#
|
843 |
+
def accessor_variable(name):
|
844 |
+
key = 'variable ' + name
|
845 |
+
tp, _ = ffi._parser._declarations[key]
|
846 |
+
BType = ffi._get_cached_btype(tp)
|
847 |
+
read_variable = backendlib.read_variable
|
848 |
+
write_variable = backendlib.write_variable
|
849 |
+
setattr(FFILibrary, name, property(
|
850 |
+
lambda self: read_variable(BType, name),
|
851 |
+
lambda self, value: write_variable(BType, name, value)))
|
852 |
+
#
|
853 |
+
def addressof_var(name):
|
854 |
+
try:
|
855 |
+
return addr_variables[name]
|
856 |
+
except KeyError:
|
857 |
+
with ffi._lock:
|
858 |
+
if name not in addr_variables:
|
859 |
+
key = 'variable ' + name
|
860 |
+
tp, _ = ffi._parser._declarations[key]
|
861 |
+
BType = ffi._get_cached_btype(tp)
|
862 |
+
if BType.kind != 'array':
|
863 |
+
BType = model.pointer_cache(ffi, BType)
|
864 |
+
p = backendlib.load_function(BType, name)
|
865 |
+
addr_variables[name] = p
|
866 |
+
return addr_variables[name]
|
867 |
+
#
|
868 |
+
def accessor_constant(name):
|
869 |
+
raise NotImplementedError("non-integer constant '%s' cannot be "
|
870 |
+
"accessed from a dlopen() library" % (name,))
|
871 |
+
#
|
872 |
+
def accessor_int_constant(name):
|
873 |
+
library.__dict__[name] = ffi._parser._int_constants[name]
|
874 |
+
#
|
875 |
+
accessors = {}
|
876 |
+
accessors_version = [False]
|
877 |
+
addr_variables = {}
|
878 |
+
#
|
879 |
+
def update_accessors():
|
880 |
+
if accessors_version[0] is ffi._cdef_version:
|
881 |
+
return
|
882 |
+
#
|
883 |
+
for key, (tp, _) in ffi._parser._declarations.items():
|
884 |
+
if not isinstance(tp, model.EnumType):
|
885 |
+
tag, name = key.split(' ', 1)
|
886 |
+
if tag == 'function':
|
887 |
+
accessors[name] = accessor_function
|
888 |
+
elif tag == 'variable':
|
889 |
+
accessors[name] = accessor_variable
|
890 |
+
elif tag == 'constant':
|
891 |
+
accessors[name] = accessor_constant
|
892 |
+
else:
|
893 |
+
for i, enumname in enumerate(tp.enumerators):
|
894 |
+
def accessor_enum(name, tp=tp, i=i):
|
895 |
+
tp.check_not_partial()
|
896 |
+
library.__dict__[name] = tp.enumvalues[i]
|
897 |
+
accessors[enumname] = accessor_enum
|
898 |
+
for name in ffi._parser._int_constants:
|
899 |
+
accessors.setdefault(name, accessor_int_constant)
|
900 |
+
accessors_version[0] = ffi._cdef_version
|
901 |
+
#
|
902 |
+
def make_accessor(name):
|
903 |
+
with ffi._lock:
|
904 |
+
if name in library.__dict__ or name in FFILibrary.__dict__:
|
905 |
+
return # added by another thread while waiting for the lock
|
906 |
+
if name not in accessors:
|
907 |
+
update_accessors()
|
908 |
+
if name not in accessors:
|
909 |
+
raise AttributeError(name)
|
910 |
+
accessors[name](name)
|
911 |
+
#
|
912 |
+
class FFILibrary(object):
|
913 |
+
def __getattr__(self, name):
|
914 |
+
make_accessor(name)
|
915 |
+
return getattr(self, name)
|
916 |
+
def __setattr__(self, name, value):
|
917 |
+
try:
|
918 |
+
property = getattr(self.__class__, name)
|
919 |
+
except AttributeError:
|
920 |
+
make_accessor(name)
|
921 |
+
setattr(self, name, value)
|
922 |
+
else:
|
923 |
+
property.__set__(self, value)
|
924 |
+
def __dir__(self):
|
925 |
+
with ffi._lock:
|
926 |
+
update_accessors()
|
927 |
+
return accessors.keys()
|
928 |
+
def __addressof__(self, name):
|
929 |
+
if name in library.__dict__:
|
930 |
+
return library.__dict__[name]
|
931 |
+
if name in FFILibrary.__dict__:
|
932 |
+
return addressof_var(name)
|
933 |
+
make_accessor(name)
|
934 |
+
if name in library.__dict__:
|
935 |
+
return library.__dict__[name]
|
936 |
+
if name in FFILibrary.__dict__:
|
937 |
+
return addressof_var(name)
|
938 |
+
raise AttributeError("cffi library has no function or "
|
939 |
+
"global variable named '%s'" % (name,))
|
940 |
+
def __cffi_close__(self):
|
941 |
+
backendlib.close_lib()
|
942 |
+
self.__dict__.clear()
|
943 |
+
#
|
944 |
+
if isinstance(libname, basestring):
|
945 |
+
try:
|
946 |
+
if not isinstance(libname, str): # unicode, on Python 2
|
947 |
+
libname = libname.encode('utf-8')
|
948 |
+
FFILibrary.__name__ = 'FFILibrary_%s' % libname
|
949 |
+
except UnicodeError:
|
950 |
+
pass
|
951 |
+
library = FFILibrary()
|
952 |
+
return library, library.__dict__
|
953 |
+
|
954 |
+
def _builtin_function_type(func):
|
955 |
+
# a hack to make at least ffi.typeof(builtin_function) work,
|
956 |
+
# if the builtin function was obtained by 'vengine_cpy'.
|
957 |
+
import sys
|
958 |
+
try:
|
959 |
+
module = sys.modules[func.__module__]
|
960 |
+
ffi = module._cffi_original_ffi
|
961 |
+
types_of_builtin_funcs = module._cffi_types_of_builtin_funcs
|
962 |
+
tp = types_of_builtin_funcs[func]
|
963 |
+
except (KeyError, AttributeError, TypeError):
|
964 |
+
return None
|
965 |
+
else:
|
966 |
+
with ffi._lock:
|
967 |
+
return ffi._get_cached_btype(tp)
|
cffi/backend_ctypes.py
ADDED
@@ -0,0 +1,1121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import ctypes, ctypes.util, operator, sys
|
2 |
+
from . import model
|
3 |
+
|
4 |
+
if sys.version_info < (3,):
|
5 |
+
bytechr = chr
|
6 |
+
else:
|
7 |
+
unicode = str
|
8 |
+
long = int
|
9 |
+
xrange = range
|
10 |
+
bytechr = lambda num: bytes([num])
|
11 |
+
|
12 |
+
class CTypesType(type):
|
13 |
+
pass
|
14 |
+
|
15 |
+
class CTypesData(object):
|
16 |
+
__metaclass__ = CTypesType
|
17 |
+
__slots__ = ['__weakref__']
|
18 |
+
__name__ = '<cdata>'
|
19 |
+
|
20 |
+
def __init__(self, *args):
|
21 |
+
raise TypeError("cannot instantiate %r" % (self.__class__,))
|
22 |
+
|
23 |
+
@classmethod
|
24 |
+
def _newp(cls, init):
|
25 |
+
raise TypeError("expected a pointer or array ctype, got '%s'"
|
26 |
+
% (cls._get_c_name(),))
|
27 |
+
|
28 |
+
@staticmethod
|
29 |
+
def _to_ctypes(value):
|
30 |
+
raise TypeError
|
31 |
+
|
32 |
+
@classmethod
|
33 |
+
def _arg_to_ctypes(cls, *value):
|
34 |
+
try:
|
35 |
+
ctype = cls._ctype
|
36 |
+
except AttributeError:
|
37 |
+
raise TypeError("cannot create an instance of %r" % (cls,))
|
38 |
+
if value:
|
39 |
+
res = cls._to_ctypes(*value)
|
40 |
+
if not isinstance(res, ctype):
|
41 |
+
res = cls._ctype(res)
|
42 |
+
else:
|
43 |
+
res = cls._ctype()
|
44 |
+
return res
|
45 |
+
|
46 |
+
@classmethod
|
47 |
+
def _create_ctype_obj(cls, init):
|
48 |
+
if init is None:
|
49 |
+
return cls._arg_to_ctypes()
|
50 |
+
else:
|
51 |
+
return cls._arg_to_ctypes(init)
|
52 |
+
|
53 |
+
@staticmethod
|
54 |
+
def _from_ctypes(ctypes_value):
|
55 |
+
raise TypeError
|
56 |
+
|
57 |
+
@classmethod
|
58 |
+
def _get_c_name(cls, replace_with=''):
|
59 |
+
return cls._reftypename.replace(' &', replace_with)
|
60 |
+
|
61 |
+
@classmethod
|
62 |
+
def _fix_class(cls):
|
63 |
+
cls.__name__ = 'CData<%s>' % (cls._get_c_name(),)
|
64 |
+
cls.__qualname__ = 'CData<%s>' % (cls._get_c_name(),)
|
65 |
+
cls.__module__ = 'ffi'
|
66 |
+
|
67 |
+
def _get_own_repr(self):
|
68 |
+
raise NotImplementedError
|
69 |
+
|
70 |
+
def _addr_repr(self, address):
|
71 |
+
if address == 0:
|
72 |
+
return 'NULL'
|
73 |
+
else:
|
74 |
+
if address < 0:
|
75 |
+
address += 1 << (8*ctypes.sizeof(ctypes.c_void_p))
|
76 |
+
return '0x%x' % address
|
77 |
+
|
78 |
+
def __repr__(self, c_name=None):
|
79 |
+
own = self._get_own_repr()
|
80 |
+
return '<cdata %r %s>' % (c_name or self._get_c_name(), own)
|
81 |
+
|
82 |
+
def _convert_to_address(self, BClass):
|
83 |
+
if BClass is None:
|
84 |
+
raise TypeError("cannot convert %r to an address" % (
|
85 |
+
self._get_c_name(),))
|
86 |
+
else:
|
87 |
+
raise TypeError("cannot convert %r to %r" % (
|
88 |
+
self._get_c_name(), BClass._get_c_name()))
|
89 |
+
|
90 |
+
@classmethod
|
91 |
+
def _get_size(cls):
|
92 |
+
return ctypes.sizeof(cls._ctype)
|
93 |
+
|
94 |
+
def _get_size_of_instance(self):
|
95 |
+
return ctypes.sizeof(self._ctype)
|
96 |
+
|
97 |
+
@classmethod
|
98 |
+
def _cast_from(cls, source):
|
99 |
+
raise TypeError("cannot cast to %r" % (cls._get_c_name(),))
|
100 |
+
|
101 |
+
def _cast_to_integer(self):
|
102 |
+
return self._convert_to_address(None)
|
103 |
+
|
104 |
+
@classmethod
|
105 |
+
def _alignment(cls):
|
106 |
+
return ctypes.alignment(cls._ctype)
|
107 |
+
|
108 |
+
def __iter__(self):
|
109 |
+
raise TypeError("cdata %r does not support iteration" % (
|
110 |
+
self._get_c_name()),)
|
111 |
+
|
112 |
+
def _make_cmp(name):
|
113 |
+
cmpfunc = getattr(operator, name)
|
114 |
+
def cmp(self, other):
|
115 |
+
v_is_ptr = not isinstance(self, CTypesGenericPrimitive)
|
116 |
+
w_is_ptr = (isinstance(other, CTypesData) and
|
117 |
+
not isinstance(other, CTypesGenericPrimitive))
|
118 |
+
if v_is_ptr and w_is_ptr:
|
119 |
+
return cmpfunc(self._convert_to_address(None),
|
120 |
+
other._convert_to_address(None))
|
121 |
+
elif v_is_ptr or w_is_ptr:
|
122 |
+
return NotImplemented
|
123 |
+
else:
|
124 |
+
if isinstance(self, CTypesGenericPrimitive):
|
125 |
+
self = self._value
|
126 |
+
if isinstance(other, CTypesGenericPrimitive):
|
127 |
+
other = other._value
|
128 |
+
return cmpfunc(self, other)
|
129 |
+
cmp.func_name = name
|
130 |
+
return cmp
|
131 |
+
|
132 |
+
__eq__ = _make_cmp('__eq__')
|
133 |
+
__ne__ = _make_cmp('__ne__')
|
134 |
+
__lt__ = _make_cmp('__lt__')
|
135 |
+
__le__ = _make_cmp('__le__')
|
136 |
+
__gt__ = _make_cmp('__gt__')
|
137 |
+
__ge__ = _make_cmp('__ge__')
|
138 |
+
|
139 |
+
def __hash__(self):
|
140 |
+
return hash(self._convert_to_address(None))
|
141 |
+
|
142 |
+
def _to_string(self, maxlen):
|
143 |
+
raise TypeError("string(): %r" % (self,))
|
144 |
+
|
145 |
+
|
146 |
+
class CTypesGenericPrimitive(CTypesData):
|
147 |
+
__slots__ = []
|
148 |
+
|
149 |
+
def __hash__(self):
|
150 |
+
return hash(self._value)
|
151 |
+
|
152 |
+
def _get_own_repr(self):
|
153 |
+
return repr(self._from_ctypes(self._value))
|
154 |
+
|
155 |
+
|
156 |
+
class CTypesGenericArray(CTypesData):
|
157 |
+
__slots__ = []
|
158 |
+
|
159 |
+
@classmethod
|
160 |
+
def _newp(cls, init):
|
161 |
+
return cls(init)
|
162 |
+
|
163 |
+
def __iter__(self):
|
164 |
+
for i in xrange(len(self)):
|
165 |
+
yield self[i]
|
166 |
+
|
167 |
+
def _get_own_repr(self):
|
168 |
+
return self._addr_repr(ctypes.addressof(self._blob))
|
169 |
+
|
170 |
+
|
171 |
+
class CTypesGenericPtr(CTypesData):
|
172 |
+
__slots__ = ['_address', '_as_ctype_ptr']
|
173 |
+
_automatic_casts = False
|
174 |
+
kind = "pointer"
|
175 |
+
|
176 |
+
@classmethod
|
177 |
+
def _newp(cls, init):
|
178 |
+
return cls(init)
|
179 |
+
|
180 |
+
@classmethod
|
181 |
+
def _cast_from(cls, source):
|
182 |
+
if source is None:
|
183 |
+
address = 0
|
184 |
+
elif isinstance(source, CTypesData):
|
185 |
+
address = source._cast_to_integer()
|
186 |
+
elif isinstance(source, (int, long)):
|
187 |
+
address = source
|
188 |
+
else:
|
189 |
+
raise TypeError("bad type for cast to %r: %r" %
|
190 |
+
(cls, type(source).__name__))
|
191 |
+
return cls._new_pointer_at(address)
|
192 |
+
|
193 |
+
@classmethod
|
194 |
+
def _new_pointer_at(cls, address):
|
195 |
+
self = cls.__new__(cls)
|
196 |
+
self._address = address
|
197 |
+
self._as_ctype_ptr = ctypes.cast(address, cls._ctype)
|
198 |
+
return self
|
199 |
+
|
200 |
+
def _get_own_repr(self):
|
201 |
+
try:
|
202 |
+
return self._addr_repr(self._address)
|
203 |
+
except AttributeError:
|
204 |
+
return '???'
|
205 |
+
|
206 |
+
def _cast_to_integer(self):
|
207 |
+
return self._address
|
208 |
+
|
209 |
+
def __nonzero__(self):
|
210 |
+
return bool(self._address)
|
211 |
+
__bool__ = __nonzero__
|
212 |
+
|
213 |
+
@classmethod
|
214 |
+
def _to_ctypes(cls, value):
|
215 |
+
if not isinstance(value, CTypesData):
|
216 |
+
raise TypeError("unexpected %s object" % type(value).__name__)
|
217 |
+
address = value._convert_to_address(cls)
|
218 |
+
return ctypes.cast(address, cls._ctype)
|
219 |
+
|
220 |
+
@classmethod
|
221 |
+
def _from_ctypes(cls, ctypes_ptr):
|
222 |
+
address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0
|
223 |
+
return cls._new_pointer_at(address)
|
224 |
+
|
225 |
+
@classmethod
|
226 |
+
def _initialize(cls, ctypes_ptr, value):
|
227 |
+
if value:
|
228 |
+
ctypes_ptr.contents = cls._to_ctypes(value).contents
|
229 |
+
|
230 |
+
def _convert_to_address(self, BClass):
|
231 |
+
if (BClass in (self.__class__, None) or BClass._automatic_casts
|
232 |
+
or self._automatic_casts):
|
233 |
+
return self._address
|
234 |
+
else:
|
235 |
+
return CTypesData._convert_to_address(self, BClass)
|
236 |
+
|
237 |
+
|
238 |
+
class CTypesBaseStructOrUnion(CTypesData):
|
239 |
+
__slots__ = ['_blob']
|
240 |
+
|
241 |
+
@classmethod
|
242 |
+
def _create_ctype_obj(cls, init):
|
243 |
+
# may be overridden
|
244 |
+
raise TypeError("cannot instantiate opaque type %s" % (cls,))
|
245 |
+
|
246 |
+
def _get_own_repr(self):
|
247 |
+
return self._addr_repr(ctypes.addressof(self._blob))
|
248 |
+
|
249 |
+
@classmethod
|
250 |
+
def _offsetof(cls, fieldname):
|
251 |
+
return getattr(cls._ctype, fieldname).offset
|
252 |
+
|
253 |
+
def _convert_to_address(self, BClass):
|
254 |
+
if getattr(BClass, '_BItem', None) is self.__class__:
|
255 |
+
return ctypes.addressof(self._blob)
|
256 |
+
else:
|
257 |
+
return CTypesData._convert_to_address(self, BClass)
|
258 |
+
|
259 |
+
@classmethod
|
260 |
+
def _from_ctypes(cls, ctypes_struct_or_union):
|
261 |
+
self = cls.__new__(cls)
|
262 |
+
self._blob = ctypes_struct_or_union
|
263 |
+
return self
|
264 |
+
|
265 |
+
@classmethod
|
266 |
+
def _to_ctypes(cls, value):
|
267 |
+
return value._blob
|
268 |
+
|
269 |
+
def __repr__(self, c_name=None):
|
270 |
+
return CTypesData.__repr__(self, c_name or self._get_c_name(' &'))
|
271 |
+
|
272 |
+
|
273 |
+
class CTypesBackend(object):
|
274 |
+
|
275 |
+
PRIMITIVE_TYPES = {
|
276 |
+
'char': ctypes.c_char,
|
277 |
+
'short': ctypes.c_short,
|
278 |
+
'int': ctypes.c_int,
|
279 |
+
'long': ctypes.c_long,
|
280 |
+
'long long': ctypes.c_longlong,
|
281 |
+
'signed char': ctypes.c_byte,
|
282 |
+
'unsigned char': ctypes.c_ubyte,
|
283 |
+
'unsigned short': ctypes.c_ushort,
|
284 |
+
'unsigned int': ctypes.c_uint,
|
285 |
+
'unsigned long': ctypes.c_ulong,
|
286 |
+
'unsigned long long': ctypes.c_ulonglong,
|
287 |
+
'float': ctypes.c_float,
|
288 |
+
'double': ctypes.c_double,
|
289 |
+
'_Bool': ctypes.c_bool,
|
290 |
+
}
|
291 |
+
|
292 |
+
for _name in ['unsigned long long', 'unsigned long',
|
293 |
+
'unsigned int', 'unsigned short', 'unsigned char']:
|
294 |
+
_size = ctypes.sizeof(PRIMITIVE_TYPES[_name])
|
295 |
+
PRIMITIVE_TYPES['uint%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name]
|
296 |
+
if _size == ctypes.sizeof(ctypes.c_void_p):
|
297 |
+
PRIMITIVE_TYPES['uintptr_t'] = PRIMITIVE_TYPES[_name]
|
298 |
+
if _size == ctypes.sizeof(ctypes.c_size_t):
|
299 |
+
PRIMITIVE_TYPES['size_t'] = PRIMITIVE_TYPES[_name]
|
300 |
+
|
301 |
+
for _name in ['long long', 'long', 'int', 'short', 'signed char']:
|
302 |
+
_size = ctypes.sizeof(PRIMITIVE_TYPES[_name])
|
303 |
+
PRIMITIVE_TYPES['int%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name]
|
304 |
+
if _size == ctypes.sizeof(ctypes.c_void_p):
|
305 |
+
PRIMITIVE_TYPES['intptr_t'] = PRIMITIVE_TYPES[_name]
|
306 |
+
PRIMITIVE_TYPES['ptrdiff_t'] = PRIMITIVE_TYPES[_name]
|
307 |
+
if _size == ctypes.sizeof(ctypes.c_size_t):
|
308 |
+
PRIMITIVE_TYPES['ssize_t'] = PRIMITIVE_TYPES[_name]
|
309 |
+
|
310 |
+
|
311 |
+
def __init__(self):
|
312 |
+
self.RTLD_LAZY = 0 # not supported anyway by ctypes
|
313 |
+
self.RTLD_NOW = 0
|
314 |
+
self.RTLD_GLOBAL = ctypes.RTLD_GLOBAL
|
315 |
+
self.RTLD_LOCAL = ctypes.RTLD_LOCAL
|
316 |
+
|
317 |
+
def set_ffi(self, ffi):
|
318 |
+
self.ffi = ffi
|
319 |
+
|
320 |
+
def _get_types(self):
|
321 |
+
return CTypesData, CTypesType
|
322 |
+
|
323 |
+
def load_library(self, path, flags=0):
|
324 |
+
cdll = ctypes.CDLL(path, flags)
|
325 |
+
return CTypesLibrary(self, cdll)
|
326 |
+
|
327 |
+
def new_void_type(self):
|
328 |
+
class CTypesVoid(CTypesData):
|
329 |
+
__slots__ = []
|
330 |
+
_reftypename = 'void &'
|
331 |
+
@staticmethod
|
332 |
+
def _from_ctypes(novalue):
|
333 |
+
return None
|
334 |
+
@staticmethod
|
335 |
+
def _to_ctypes(novalue):
|
336 |
+
if novalue is not None:
|
337 |
+
raise TypeError("None expected, got %s object" %
|
338 |
+
(type(novalue).__name__,))
|
339 |
+
return None
|
340 |
+
CTypesVoid._fix_class()
|
341 |
+
return CTypesVoid
|
342 |
+
|
343 |
+
def new_primitive_type(self, name):
|
344 |
+
if name == 'wchar_t':
|
345 |
+
raise NotImplementedError(name)
|
346 |
+
ctype = self.PRIMITIVE_TYPES[name]
|
347 |
+
if name == 'char':
|
348 |
+
kind = 'char'
|
349 |
+
elif name in ('float', 'double'):
|
350 |
+
kind = 'float'
|
351 |
+
else:
|
352 |
+
if name in ('signed char', 'unsigned char'):
|
353 |
+
kind = 'byte'
|
354 |
+
elif name == '_Bool':
|
355 |
+
kind = 'bool'
|
356 |
+
else:
|
357 |
+
kind = 'int'
|
358 |
+
is_signed = (ctype(-1).value == -1)
|
359 |
+
#
|
360 |
+
def _cast_source_to_int(source):
|
361 |
+
if isinstance(source, (int, long, float)):
|
362 |
+
source = int(source)
|
363 |
+
elif isinstance(source, CTypesData):
|
364 |
+
source = source._cast_to_integer()
|
365 |
+
elif isinstance(source, bytes):
|
366 |
+
source = ord(source)
|
367 |
+
elif source is None:
|
368 |
+
source = 0
|
369 |
+
else:
|
370 |
+
raise TypeError("bad type for cast to %r: %r" %
|
371 |
+
(CTypesPrimitive, type(source).__name__))
|
372 |
+
return source
|
373 |
+
#
|
374 |
+
kind1 = kind
|
375 |
+
class CTypesPrimitive(CTypesGenericPrimitive):
|
376 |
+
__slots__ = ['_value']
|
377 |
+
_ctype = ctype
|
378 |
+
_reftypename = '%s &' % name
|
379 |
+
kind = kind1
|
380 |
+
|
381 |
+
def __init__(self, value):
|
382 |
+
self._value = value
|
383 |
+
|
384 |
+
@staticmethod
|
385 |
+
def _create_ctype_obj(init):
|
386 |
+
if init is None:
|
387 |
+
return ctype()
|
388 |
+
return ctype(CTypesPrimitive._to_ctypes(init))
|
389 |
+
|
390 |
+
if kind == 'int' or kind == 'byte':
|
391 |
+
@classmethod
|
392 |
+
def _cast_from(cls, source):
|
393 |
+
source = _cast_source_to_int(source)
|
394 |
+
source = ctype(source).value # cast within range
|
395 |
+
return cls(source)
|
396 |
+
def __int__(self):
|
397 |
+
return self._value
|
398 |
+
|
399 |
+
if kind == 'bool':
|
400 |
+
@classmethod
|
401 |
+
def _cast_from(cls, source):
|
402 |
+
if not isinstance(source, (int, long, float)):
|
403 |
+
source = _cast_source_to_int(source)
|
404 |
+
return cls(bool(source))
|
405 |
+
def __int__(self):
|
406 |
+
return int(self._value)
|
407 |
+
|
408 |
+
if kind == 'char':
|
409 |
+
@classmethod
|
410 |
+
def _cast_from(cls, source):
|
411 |
+
source = _cast_source_to_int(source)
|
412 |
+
source = bytechr(source & 0xFF)
|
413 |
+
return cls(source)
|
414 |
+
def __int__(self):
|
415 |
+
return ord(self._value)
|
416 |
+
|
417 |
+
if kind == 'float':
|
418 |
+
@classmethod
|
419 |
+
def _cast_from(cls, source):
|
420 |
+
if isinstance(source, float):
|
421 |
+
pass
|
422 |
+
elif isinstance(source, CTypesGenericPrimitive):
|
423 |
+
if hasattr(source, '__float__'):
|
424 |
+
source = float(source)
|
425 |
+
else:
|
426 |
+
source = int(source)
|
427 |
+
else:
|
428 |
+
source = _cast_source_to_int(source)
|
429 |
+
source = ctype(source).value # fix precision
|
430 |
+
return cls(source)
|
431 |
+
def __int__(self):
|
432 |
+
return int(self._value)
|
433 |
+
def __float__(self):
|
434 |
+
return self._value
|
435 |
+
|
436 |
+
_cast_to_integer = __int__
|
437 |
+
|
438 |
+
if kind == 'int' or kind == 'byte' or kind == 'bool':
|
439 |
+
@staticmethod
|
440 |
+
def _to_ctypes(x):
|
441 |
+
if not isinstance(x, (int, long)):
|
442 |
+
if isinstance(x, CTypesData):
|
443 |
+
x = int(x)
|
444 |
+
else:
|
445 |
+
raise TypeError("integer expected, got %s" %
|
446 |
+
type(x).__name__)
|
447 |
+
if ctype(x).value != x:
|
448 |
+
if not is_signed and x < 0:
|
449 |
+
raise OverflowError("%s: negative integer" % name)
|
450 |
+
else:
|
451 |
+
raise OverflowError("%s: integer out of bounds"
|
452 |
+
% name)
|
453 |
+
return x
|
454 |
+
|
455 |
+
if kind == 'char':
|
456 |
+
@staticmethod
|
457 |
+
def _to_ctypes(x):
|
458 |
+
if isinstance(x, bytes) and len(x) == 1:
|
459 |
+
return x
|
460 |
+
if isinstance(x, CTypesPrimitive): # <CData <char>>
|
461 |
+
return x._value
|
462 |
+
raise TypeError("character expected, got %s" %
|
463 |
+
type(x).__name__)
|
464 |
+
def __nonzero__(self):
|
465 |
+
return ord(self._value) != 0
|
466 |
+
else:
|
467 |
+
def __nonzero__(self):
|
468 |
+
return self._value != 0
|
469 |
+
__bool__ = __nonzero__
|
470 |
+
|
471 |
+
if kind == 'float':
|
472 |
+
@staticmethod
|
473 |
+
def _to_ctypes(x):
|
474 |
+
if not isinstance(x, (int, long, float, CTypesData)):
|
475 |
+
raise TypeError("float expected, got %s" %
|
476 |
+
type(x).__name__)
|
477 |
+
return ctype(x).value
|
478 |
+
|
479 |
+
@staticmethod
|
480 |
+
def _from_ctypes(value):
|
481 |
+
return getattr(value, 'value', value)
|
482 |
+
|
483 |
+
@staticmethod
|
484 |
+
def _initialize(blob, init):
|
485 |
+
blob.value = CTypesPrimitive._to_ctypes(init)
|
486 |
+
|
487 |
+
if kind == 'char':
|
488 |
+
def _to_string(self, maxlen):
|
489 |
+
return self._value
|
490 |
+
if kind == 'byte':
|
491 |
+
def _to_string(self, maxlen):
|
492 |
+
return chr(self._value & 0xff)
|
493 |
+
#
|
494 |
+
CTypesPrimitive._fix_class()
|
495 |
+
return CTypesPrimitive
|
496 |
+
|
497 |
+
def new_pointer_type(self, BItem):
|
498 |
+
getbtype = self.ffi._get_cached_btype
|
499 |
+
if BItem is getbtype(model.PrimitiveType('char')):
|
500 |
+
kind = 'charp'
|
501 |
+
elif BItem in (getbtype(model.PrimitiveType('signed char')),
|
502 |
+
getbtype(model.PrimitiveType('unsigned char'))):
|
503 |
+
kind = 'bytep'
|
504 |
+
elif BItem is getbtype(model.void_type):
|
505 |
+
kind = 'voidp'
|
506 |
+
else:
|
507 |
+
kind = 'generic'
|
508 |
+
#
|
509 |
+
class CTypesPtr(CTypesGenericPtr):
|
510 |
+
__slots__ = ['_own']
|
511 |
+
if kind == 'charp':
|
512 |
+
__slots__ += ['__as_strbuf']
|
513 |
+
_BItem = BItem
|
514 |
+
if hasattr(BItem, '_ctype'):
|
515 |
+
_ctype = ctypes.POINTER(BItem._ctype)
|
516 |
+
_bitem_size = ctypes.sizeof(BItem._ctype)
|
517 |
+
else:
|
518 |
+
_ctype = ctypes.c_void_p
|
519 |
+
if issubclass(BItem, CTypesGenericArray):
|
520 |
+
_reftypename = BItem._get_c_name('(* &)')
|
521 |
+
else:
|
522 |
+
_reftypename = BItem._get_c_name(' * &')
|
523 |
+
|
524 |
+
def __init__(self, init):
|
525 |
+
ctypeobj = BItem._create_ctype_obj(init)
|
526 |
+
if kind == 'charp':
|
527 |
+
self.__as_strbuf = ctypes.create_string_buffer(
|
528 |
+
ctypeobj.value + b'\x00')
|
529 |
+
self._as_ctype_ptr = ctypes.cast(
|
530 |
+
self.__as_strbuf, self._ctype)
|
531 |
+
else:
|
532 |
+
self._as_ctype_ptr = ctypes.pointer(ctypeobj)
|
533 |
+
self._address = ctypes.cast(self._as_ctype_ptr,
|
534 |
+
ctypes.c_void_p).value
|
535 |
+
self._own = True
|
536 |
+
|
537 |
+
def __add__(self, other):
|
538 |
+
if isinstance(other, (int, long)):
|
539 |
+
return self._new_pointer_at(self._address +
|
540 |
+
other * self._bitem_size)
|
541 |
+
else:
|
542 |
+
return NotImplemented
|
543 |
+
|
544 |
+
def __sub__(self, other):
|
545 |
+
if isinstance(other, (int, long)):
|
546 |
+
return self._new_pointer_at(self._address -
|
547 |
+
other * self._bitem_size)
|
548 |
+
elif type(self) is type(other):
|
549 |
+
return (self._address - other._address) // self._bitem_size
|
550 |
+
else:
|
551 |
+
return NotImplemented
|
552 |
+
|
553 |
+
def __getitem__(self, index):
|
554 |
+
if getattr(self, '_own', False) and index != 0:
|
555 |
+
raise IndexError
|
556 |
+
return BItem._from_ctypes(self._as_ctype_ptr[index])
|
557 |
+
|
558 |
+
def __setitem__(self, index, value):
|
559 |
+
self._as_ctype_ptr[index] = BItem._to_ctypes(value)
|
560 |
+
|
561 |
+
if kind == 'charp' or kind == 'voidp':
|
562 |
+
@classmethod
|
563 |
+
def _arg_to_ctypes(cls, *value):
|
564 |
+
if value and isinstance(value[0], bytes):
|
565 |
+
return ctypes.c_char_p(value[0])
|
566 |
+
else:
|
567 |
+
return super(CTypesPtr, cls)._arg_to_ctypes(*value)
|
568 |
+
|
569 |
+
if kind == 'charp' or kind == 'bytep':
|
570 |
+
def _to_string(self, maxlen):
|
571 |
+
if maxlen < 0:
|
572 |
+
maxlen = sys.maxsize
|
573 |
+
p = ctypes.cast(self._as_ctype_ptr,
|
574 |
+
ctypes.POINTER(ctypes.c_char))
|
575 |
+
n = 0
|
576 |
+
while n < maxlen and p[n] != b'\x00':
|
577 |
+
n += 1
|
578 |
+
return b''.join([p[i] for i in range(n)])
|
579 |
+
|
580 |
+
def _get_own_repr(self):
|
581 |
+
if getattr(self, '_own', False):
|
582 |
+
return 'owning %d bytes' % (
|
583 |
+
ctypes.sizeof(self._as_ctype_ptr.contents),)
|
584 |
+
return super(CTypesPtr, self)._get_own_repr()
|
585 |
+
#
|
586 |
+
if (BItem is self.ffi._get_cached_btype(model.void_type) or
|
587 |
+
BItem is self.ffi._get_cached_btype(model.PrimitiveType('char'))):
|
588 |
+
CTypesPtr._automatic_casts = True
|
589 |
+
#
|
590 |
+
CTypesPtr._fix_class()
|
591 |
+
return CTypesPtr
|
592 |
+
|
593 |
+
def new_array_type(self, CTypesPtr, length):
|
594 |
+
if length is None:
|
595 |
+
brackets = ' &[]'
|
596 |
+
else:
|
597 |
+
brackets = ' &[%d]' % length
|
598 |
+
BItem = CTypesPtr._BItem
|
599 |
+
getbtype = self.ffi._get_cached_btype
|
600 |
+
if BItem is getbtype(model.PrimitiveType('char')):
|
601 |
+
kind = 'char'
|
602 |
+
elif BItem in (getbtype(model.PrimitiveType('signed char')),
|
603 |
+
getbtype(model.PrimitiveType('unsigned char'))):
|
604 |
+
kind = 'byte'
|
605 |
+
else:
|
606 |
+
kind = 'generic'
|
607 |
+
#
|
608 |
+
class CTypesArray(CTypesGenericArray):
|
609 |
+
__slots__ = ['_blob', '_own']
|
610 |
+
if length is not None:
|
611 |
+
_ctype = BItem._ctype * length
|
612 |
+
else:
|
613 |
+
__slots__.append('_ctype')
|
614 |
+
_reftypename = BItem._get_c_name(brackets)
|
615 |
+
_declared_length = length
|
616 |
+
_CTPtr = CTypesPtr
|
617 |
+
|
618 |
+
def __init__(self, init):
|
619 |
+
if length is None:
|
620 |
+
if isinstance(init, (int, long)):
|
621 |
+
len1 = init
|
622 |
+
init = None
|
623 |
+
elif kind == 'char' and isinstance(init, bytes):
|
624 |
+
len1 = len(init) + 1 # extra null
|
625 |
+
else:
|
626 |
+
init = tuple(init)
|
627 |
+
len1 = len(init)
|
628 |
+
self._ctype = BItem._ctype * len1
|
629 |
+
self._blob = self._ctype()
|
630 |
+
self._own = True
|
631 |
+
if init is not None:
|
632 |
+
self._initialize(self._blob, init)
|
633 |
+
|
634 |
+
@staticmethod
|
635 |
+
def _initialize(blob, init):
|
636 |
+
if isinstance(init, bytes):
|
637 |
+
init = [init[i:i+1] for i in range(len(init))]
|
638 |
+
else:
|
639 |
+
if isinstance(init, CTypesGenericArray):
|
640 |
+
if (len(init) != len(blob) or
|
641 |
+
not isinstance(init, CTypesArray)):
|
642 |
+
raise TypeError("length/type mismatch: %s" % (init,))
|
643 |
+
init = tuple(init)
|
644 |
+
if len(init) > len(blob):
|
645 |
+
raise IndexError("too many initializers")
|
646 |
+
addr = ctypes.cast(blob, ctypes.c_void_p).value
|
647 |
+
PTR = ctypes.POINTER(BItem._ctype)
|
648 |
+
itemsize = ctypes.sizeof(BItem._ctype)
|
649 |
+
for i, value in enumerate(init):
|
650 |
+
p = ctypes.cast(addr + i * itemsize, PTR)
|
651 |
+
BItem._initialize(p.contents, value)
|
652 |
+
|
653 |
+
def __len__(self):
|
654 |
+
return len(self._blob)
|
655 |
+
|
656 |
+
def __getitem__(self, index):
|
657 |
+
if not (0 <= index < len(self._blob)):
|
658 |
+
raise IndexError
|
659 |
+
return BItem._from_ctypes(self._blob[index])
|
660 |
+
|
661 |
+
def __setitem__(self, index, value):
|
662 |
+
if not (0 <= index < len(self._blob)):
|
663 |
+
raise IndexError
|
664 |
+
self._blob[index] = BItem._to_ctypes(value)
|
665 |
+
|
666 |
+
if kind == 'char' or kind == 'byte':
|
667 |
+
def _to_string(self, maxlen):
|
668 |
+
if maxlen < 0:
|
669 |
+
maxlen = len(self._blob)
|
670 |
+
p = ctypes.cast(self._blob,
|
671 |
+
ctypes.POINTER(ctypes.c_char))
|
672 |
+
n = 0
|
673 |
+
while n < maxlen and p[n] != b'\x00':
|
674 |
+
n += 1
|
675 |
+
return b''.join([p[i] for i in range(n)])
|
676 |
+
|
677 |
+
def _get_own_repr(self):
|
678 |
+
if getattr(self, '_own', False):
|
679 |
+
return 'owning %d bytes' % (ctypes.sizeof(self._blob),)
|
680 |
+
return super(CTypesArray, self)._get_own_repr()
|
681 |
+
|
682 |
+
def _convert_to_address(self, BClass):
|
683 |
+
if BClass in (CTypesPtr, None) or BClass._automatic_casts:
|
684 |
+
return ctypes.addressof(self._blob)
|
685 |
+
else:
|
686 |
+
return CTypesData._convert_to_address(self, BClass)
|
687 |
+
|
688 |
+
@staticmethod
|
689 |
+
def _from_ctypes(ctypes_array):
|
690 |
+
self = CTypesArray.__new__(CTypesArray)
|
691 |
+
self._blob = ctypes_array
|
692 |
+
return self
|
693 |
+
|
694 |
+
@staticmethod
|
695 |
+
def _arg_to_ctypes(value):
|
696 |
+
return CTypesPtr._arg_to_ctypes(value)
|
697 |
+
|
698 |
+
def __add__(self, other):
|
699 |
+
if isinstance(other, (int, long)):
|
700 |
+
return CTypesPtr._new_pointer_at(
|
701 |
+
ctypes.addressof(self._blob) +
|
702 |
+
other * ctypes.sizeof(BItem._ctype))
|
703 |
+
else:
|
704 |
+
return NotImplemented
|
705 |
+
|
706 |
+
@classmethod
|
707 |
+
def _cast_from(cls, source):
|
708 |
+
raise NotImplementedError("casting to %r" % (
|
709 |
+
cls._get_c_name(),))
|
710 |
+
#
|
711 |
+
CTypesArray._fix_class()
|
712 |
+
return CTypesArray
|
713 |
+
|
714 |
+
def _new_struct_or_union(self, kind, name, base_ctypes_class):
|
715 |
+
#
|
716 |
+
class struct_or_union(base_ctypes_class):
|
717 |
+
pass
|
718 |
+
struct_or_union.__name__ = '%s_%s' % (kind, name)
|
719 |
+
kind1 = kind
|
720 |
+
#
|
721 |
+
class CTypesStructOrUnion(CTypesBaseStructOrUnion):
|
722 |
+
__slots__ = ['_blob']
|
723 |
+
_ctype = struct_or_union
|
724 |
+
_reftypename = '%s &' % (name,)
|
725 |
+
_kind = kind = kind1
|
726 |
+
#
|
727 |
+
CTypesStructOrUnion._fix_class()
|
728 |
+
return CTypesStructOrUnion
|
729 |
+
|
730 |
+
def new_struct_type(self, name):
|
731 |
+
return self._new_struct_or_union('struct', name, ctypes.Structure)
|
732 |
+
|
733 |
+
def new_union_type(self, name):
|
734 |
+
return self._new_struct_or_union('union', name, ctypes.Union)
|
735 |
+
|
736 |
+
def complete_struct_or_union(self, CTypesStructOrUnion, fields, tp,
|
737 |
+
totalsize=-1, totalalignment=-1, sflags=0,
|
738 |
+
pack=0):
|
739 |
+
if totalsize >= 0 or totalalignment >= 0:
|
740 |
+
raise NotImplementedError("the ctypes backend of CFFI does not support "
|
741 |
+
"structures completed by verify(); please "
|
742 |
+
"compile and install the _cffi_backend module.")
|
743 |
+
struct_or_union = CTypesStructOrUnion._ctype
|
744 |
+
fnames = [fname for (fname, BField, bitsize) in fields]
|
745 |
+
btypes = [BField for (fname, BField, bitsize) in fields]
|
746 |
+
bitfields = [bitsize for (fname, BField, bitsize) in fields]
|
747 |
+
#
|
748 |
+
bfield_types = {}
|
749 |
+
cfields = []
|
750 |
+
for (fname, BField, bitsize) in fields:
|
751 |
+
if bitsize < 0:
|
752 |
+
cfields.append((fname, BField._ctype))
|
753 |
+
bfield_types[fname] = BField
|
754 |
+
else:
|
755 |
+
cfields.append((fname, BField._ctype, bitsize))
|
756 |
+
bfield_types[fname] = Ellipsis
|
757 |
+
if sflags & 8:
|
758 |
+
struct_or_union._pack_ = 1
|
759 |
+
elif pack:
|
760 |
+
struct_or_union._pack_ = pack
|
761 |
+
struct_or_union._fields_ = cfields
|
762 |
+
CTypesStructOrUnion._bfield_types = bfield_types
|
763 |
+
#
|
764 |
+
@staticmethod
|
765 |
+
def _create_ctype_obj(init):
|
766 |
+
result = struct_or_union()
|
767 |
+
if init is not None:
|
768 |
+
initialize(result, init)
|
769 |
+
return result
|
770 |
+
CTypesStructOrUnion._create_ctype_obj = _create_ctype_obj
|
771 |
+
#
|
772 |
+
def initialize(blob, init):
|
773 |
+
if is_union:
|
774 |
+
if len(init) > 1:
|
775 |
+
raise ValueError("union initializer: %d items given, but "
|
776 |
+
"only one supported (use a dict if needed)"
|
777 |
+
% (len(init),))
|
778 |
+
if not isinstance(init, dict):
|
779 |
+
if isinstance(init, (bytes, unicode)):
|
780 |
+
raise TypeError("union initializer: got a str")
|
781 |
+
init = tuple(init)
|
782 |
+
if len(init) > len(fnames):
|
783 |
+
raise ValueError("too many values for %s initializer" %
|
784 |
+
CTypesStructOrUnion._get_c_name())
|
785 |
+
init = dict(zip(fnames, init))
|
786 |
+
addr = ctypes.addressof(blob)
|
787 |
+
for fname, value in init.items():
|
788 |
+
BField, bitsize = name2fieldtype[fname]
|
789 |
+
assert bitsize < 0, \
|
790 |
+
"not implemented: initializer with bit fields"
|
791 |
+
offset = CTypesStructOrUnion._offsetof(fname)
|
792 |
+
PTR = ctypes.POINTER(BField._ctype)
|
793 |
+
p = ctypes.cast(addr + offset, PTR)
|
794 |
+
BField._initialize(p.contents, value)
|
795 |
+
is_union = CTypesStructOrUnion._kind == 'union'
|
796 |
+
name2fieldtype = dict(zip(fnames, zip(btypes, bitfields)))
|
797 |
+
#
|
798 |
+
for fname, BField, bitsize in fields:
|
799 |
+
if fname == '':
|
800 |
+
raise NotImplementedError("nested anonymous structs/unions")
|
801 |
+
if hasattr(CTypesStructOrUnion, fname):
|
802 |
+
raise ValueError("the field name %r conflicts in "
|
803 |
+
"the ctypes backend" % fname)
|
804 |
+
if bitsize < 0:
|
805 |
+
def getter(self, fname=fname, BField=BField,
|
806 |
+
offset=CTypesStructOrUnion._offsetof(fname),
|
807 |
+
PTR=ctypes.POINTER(BField._ctype)):
|
808 |
+
addr = ctypes.addressof(self._blob)
|
809 |
+
p = ctypes.cast(addr + offset, PTR)
|
810 |
+
return BField._from_ctypes(p.contents)
|
811 |
+
def setter(self, value, fname=fname, BField=BField):
|
812 |
+
setattr(self._blob, fname, BField._to_ctypes(value))
|
813 |
+
#
|
814 |
+
if issubclass(BField, CTypesGenericArray):
|
815 |
+
setter = None
|
816 |
+
if BField._declared_length == 0:
|
817 |
+
def getter(self, fname=fname, BFieldPtr=BField._CTPtr,
|
818 |
+
offset=CTypesStructOrUnion._offsetof(fname),
|
819 |
+
PTR=ctypes.POINTER(BField._ctype)):
|
820 |
+
addr = ctypes.addressof(self._blob)
|
821 |
+
p = ctypes.cast(addr + offset, PTR)
|
822 |
+
return BFieldPtr._from_ctypes(p)
|
823 |
+
#
|
824 |
+
else:
|
825 |
+
def getter(self, fname=fname, BField=BField):
|
826 |
+
return BField._from_ctypes(getattr(self._blob, fname))
|
827 |
+
def setter(self, value, fname=fname, BField=BField):
|
828 |
+
# xxx obscure workaround
|
829 |
+
value = BField._to_ctypes(value)
|
830 |
+
oldvalue = getattr(self._blob, fname)
|
831 |
+
setattr(self._blob, fname, value)
|
832 |
+
if value != getattr(self._blob, fname):
|
833 |
+
setattr(self._blob, fname, oldvalue)
|
834 |
+
raise OverflowError("value too large for bitfield")
|
835 |
+
setattr(CTypesStructOrUnion, fname, property(getter, setter))
|
836 |
+
#
|
837 |
+
CTypesPtr = self.ffi._get_cached_btype(model.PointerType(tp))
|
838 |
+
for fname in fnames:
|
839 |
+
if hasattr(CTypesPtr, fname):
|
840 |
+
raise ValueError("the field name %r conflicts in "
|
841 |
+
"the ctypes backend" % fname)
|
842 |
+
def getter(self, fname=fname):
|
843 |
+
return getattr(self[0], fname)
|
844 |
+
def setter(self, value, fname=fname):
|
845 |
+
setattr(self[0], fname, value)
|
846 |
+
setattr(CTypesPtr, fname, property(getter, setter))
|
847 |
+
|
848 |
+
def new_function_type(self, BArgs, BResult, has_varargs):
|
849 |
+
nameargs = [BArg._get_c_name() for BArg in BArgs]
|
850 |
+
if has_varargs:
|
851 |
+
nameargs.append('...')
|
852 |
+
nameargs = ', '.join(nameargs)
|
853 |
+
#
|
854 |
+
class CTypesFunctionPtr(CTypesGenericPtr):
|
855 |
+
__slots__ = ['_own_callback', '_name']
|
856 |
+
_ctype = ctypes.CFUNCTYPE(getattr(BResult, '_ctype', None),
|
857 |
+
*[BArg._ctype for BArg in BArgs],
|
858 |
+
use_errno=True)
|
859 |
+
_reftypename = BResult._get_c_name('(* &)(%s)' % (nameargs,))
|
860 |
+
|
861 |
+
def __init__(self, init, error=None):
|
862 |
+
# create a callback to the Python callable init()
|
863 |
+
import traceback
|
864 |
+
assert not has_varargs, "varargs not supported for callbacks"
|
865 |
+
if getattr(BResult, '_ctype', None) is not None:
|
866 |
+
error = BResult._from_ctypes(
|
867 |
+
BResult._create_ctype_obj(error))
|
868 |
+
else:
|
869 |
+
error = None
|
870 |
+
def callback(*args):
|
871 |
+
args2 = []
|
872 |
+
for arg, BArg in zip(args, BArgs):
|
873 |
+
args2.append(BArg._from_ctypes(arg))
|
874 |
+
try:
|
875 |
+
res2 = init(*args2)
|
876 |
+
res2 = BResult._to_ctypes(res2)
|
877 |
+
except:
|
878 |
+
traceback.print_exc()
|
879 |
+
res2 = error
|
880 |
+
if issubclass(BResult, CTypesGenericPtr):
|
881 |
+
if res2:
|
882 |
+
res2 = ctypes.cast(res2, ctypes.c_void_p).value
|
883 |
+
# .value: http://bugs.python.org/issue1574593
|
884 |
+
else:
|
885 |
+
res2 = None
|
886 |
+
#print repr(res2)
|
887 |
+
return res2
|
888 |
+
if issubclass(BResult, CTypesGenericPtr):
|
889 |
+
# The only pointers callbacks can return are void*s:
|
890 |
+
# http://bugs.python.org/issue5710
|
891 |
+
callback_ctype = ctypes.CFUNCTYPE(
|
892 |
+
ctypes.c_void_p,
|
893 |
+
*[BArg._ctype for BArg in BArgs],
|
894 |
+
use_errno=True)
|
895 |
+
else:
|
896 |
+
callback_ctype = CTypesFunctionPtr._ctype
|
897 |
+
self._as_ctype_ptr = callback_ctype(callback)
|
898 |
+
self._address = ctypes.cast(self._as_ctype_ptr,
|
899 |
+
ctypes.c_void_p).value
|
900 |
+
self._own_callback = init
|
901 |
+
|
902 |
+
@staticmethod
|
903 |
+
def _initialize(ctypes_ptr, value):
|
904 |
+
if value:
|
905 |
+
raise NotImplementedError("ctypes backend: not supported: "
|
906 |
+
"initializers for function pointers")
|
907 |
+
|
908 |
+
def __repr__(self):
|
909 |
+
c_name = getattr(self, '_name', None)
|
910 |
+
if c_name:
|
911 |
+
i = self._reftypename.index('(* &)')
|
912 |
+
if self._reftypename[i-1] not in ' )*':
|
913 |
+
c_name = ' ' + c_name
|
914 |
+
c_name = self._reftypename.replace('(* &)', c_name)
|
915 |
+
return CTypesData.__repr__(self, c_name)
|
916 |
+
|
917 |
+
def _get_own_repr(self):
|
918 |
+
if getattr(self, '_own_callback', None) is not None:
|
919 |
+
return 'calling %r' % (self._own_callback,)
|
920 |
+
return super(CTypesFunctionPtr, self)._get_own_repr()
|
921 |
+
|
922 |
+
def __call__(self, *args):
|
923 |
+
if has_varargs:
|
924 |
+
assert len(args) >= len(BArgs)
|
925 |
+
extraargs = args[len(BArgs):]
|
926 |
+
args = args[:len(BArgs)]
|
927 |
+
else:
|
928 |
+
assert len(args) == len(BArgs)
|
929 |
+
ctypes_args = []
|
930 |
+
for arg, BArg in zip(args, BArgs):
|
931 |
+
ctypes_args.append(BArg._arg_to_ctypes(arg))
|
932 |
+
if has_varargs:
|
933 |
+
for i, arg in enumerate(extraargs):
|
934 |
+
if arg is None:
|
935 |
+
ctypes_args.append(ctypes.c_void_p(0)) # NULL
|
936 |
+
continue
|
937 |
+
if not isinstance(arg, CTypesData):
|
938 |
+
raise TypeError(
|
939 |
+
"argument %d passed in the variadic part "
|
940 |
+
"needs to be a cdata object (got %s)" %
|
941 |
+
(1 + len(BArgs) + i, type(arg).__name__))
|
942 |
+
ctypes_args.append(arg._arg_to_ctypes(arg))
|
943 |
+
result = self._as_ctype_ptr(*ctypes_args)
|
944 |
+
return BResult._from_ctypes(result)
|
945 |
+
#
|
946 |
+
CTypesFunctionPtr._fix_class()
|
947 |
+
return CTypesFunctionPtr
|
948 |
+
|
949 |
+
def new_enum_type(self, name, enumerators, enumvalues, CTypesInt):
|
950 |
+
assert isinstance(name, str)
|
951 |
+
reverse_mapping = dict(zip(reversed(enumvalues),
|
952 |
+
reversed(enumerators)))
|
953 |
+
#
|
954 |
+
class CTypesEnum(CTypesInt):
|
955 |
+
__slots__ = []
|
956 |
+
_reftypename = '%s &' % name
|
957 |
+
|
958 |
+
def _get_own_repr(self):
|
959 |
+
value = self._value
|
960 |
+
try:
|
961 |
+
return '%d: %s' % (value, reverse_mapping[value])
|
962 |
+
except KeyError:
|
963 |
+
return str(value)
|
964 |
+
|
965 |
+
def _to_string(self, maxlen):
|
966 |
+
value = self._value
|
967 |
+
try:
|
968 |
+
return reverse_mapping[value]
|
969 |
+
except KeyError:
|
970 |
+
return str(value)
|
971 |
+
#
|
972 |
+
CTypesEnum._fix_class()
|
973 |
+
return CTypesEnum
|
974 |
+
|
975 |
+
def get_errno(self):
|
976 |
+
return ctypes.get_errno()
|
977 |
+
|
978 |
+
def set_errno(self, value):
|
979 |
+
ctypes.set_errno(value)
|
980 |
+
|
981 |
+
def string(self, b, maxlen=-1):
|
982 |
+
return b._to_string(maxlen)
|
983 |
+
|
984 |
+
def buffer(self, bptr, size=-1):
|
985 |
+
raise NotImplementedError("buffer() with ctypes backend")
|
986 |
+
|
987 |
+
def sizeof(self, cdata_or_BType):
|
988 |
+
if isinstance(cdata_or_BType, CTypesData):
|
989 |
+
return cdata_or_BType._get_size_of_instance()
|
990 |
+
else:
|
991 |
+
assert issubclass(cdata_or_BType, CTypesData)
|
992 |
+
return cdata_or_BType._get_size()
|
993 |
+
|
994 |
+
def alignof(self, BType):
|
995 |
+
assert issubclass(BType, CTypesData)
|
996 |
+
return BType._alignment()
|
997 |
+
|
998 |
+
def newp(self, BType, source):
|
999 |
+
if not issubclass(BType, CTypesData):
|
1000 |
+
raise TypeError
|
1001 |
+
return BType._newp(source)
|
1002 |
+
|
1003 |
+
def cast(self, BType, source):
|
1004 |
+
return BType._cast_from(source)
|
1005 |
+
|
1006 |
+
def callback(self, BType, source, error, onerror):
|
1007 |
+
assert onerror is None # XXX not implemented
|
1008 |
+
return BType(source, error)
|
1009 |
+
|
1010 |
+
_weakref_cache_ref = None
|
1011 |
+
|
1012 |
+
def gcp(self, cdata, destructor, size=0):
|
1013 |
+
if self._weakref_cache_ref is None:
|
1014 |
+
import weakref
|
1015 |
+
class MyRef(weakref.ref):
|
1016 |
+
def __eq__(self, other):
|
1017 |
+
myref = self()
|
1018 |
+
return self is other or (
|
1019 |
+
myref is not None and myref is other())
|
1020 |
+
def __ne__(self, other):
|
1021 |
+
return not (self == other)
|
1022 |
+
def __hash__(self):
|
1023 |
+
try:
|
1024 |
+
return self._hash
|
1025 |
+
except AttributeError:
|
1026 |
+
self._hash = hash(self())
|
1027 |
+
return self._hash
|
1028 |
+
self._weakref_cache_ref = {}, MyRef
|
1029 |
+
weak_cache, MyRef = self._weakref_cache_ref
|
1030 |
+
|
1031 |
+
if destructor is None:
|
1032 |
+
try:
|
1033 |
+
del weak_cache[MyRef(cdata)]
|
1034 |
+
except KeyError:
|
1035 |
+
raise TypeError("Can remove destructor only on a object "
|
1036 |
+
"previously returned by ffi.gc()")
|
1037 |
+
return None
|
1038 |
+
|
1039 |
+
def remove(k):
|
1040 |
+
cdata, destructor = weak_cache.pop(k, (None, None))
|
1041 |
+
if destructor is not None:
|
1042 |
+
destructor(cdata)
|
1043 |
+
|
1044 |
+
new_cdata = self.cast(self.typeof(cdata), cdata)
|
1045 |
+
assert new_cdata is not cdata
|
1046 |
+
weak_cache[MyRef(new_cdata, remove)] = (cdata, destructor)
|
1047 |
+
return new_cdata
|
1048 |
+
|
1049 |
+
typeof = type
|
1050 |
+
|
1051 |
+
def getcname(self, BType, replace_with):
|
1052 |
+
return BType._get_c_name(replace_with)
|
1053 |
+
|
1054 |
+
def typeoffsetof(self, BType, fieldname, num=0):
|
1055 |
+
if isinstance(fieldname, str):
|
1056 |
+
if num == 0 and issubclass(BType, CTypesGenericPtr):
|
1057 |
+
BType = BType._BItem
|
1058 |
+
if not issubclass(BType, CTypesBaseStructOrUnion):
|
1059 |
+
raise TypeError("expected a struct or union ctype")
|
1060 |
+
BField = BType._bfield_types[fieldname]
|
1061 |
+
if BField is Ellipsis:
|
1062 |
+
raise TypeError("not supported for bitfields")
|
1063 |
+
return (BField, BType._offsetof(fieldname))
|
1064 |
+
elif isinstance(fieldname, (int, long)):
|
1065 |
+
if issubclass(BType, CTypesGenericArray):
|
1066 |
+
BType = BType._CTPtr
|
1067 |
+
if not issubclass(BType, CTypesGenericPtr):
|
1068 |
+
raise TypeError("expected an array or ptr ctype")
|
1069 |
+
BItem = BType._BItem
|
1070 |
+
offset = BItem._get_size() * fieldname
|
1071 |
+
if offset > sys.maxsize:
|
1072 |
+
raise OverflowError
|
1073 |
+
return (BItem, offset)
|
1074 |
+
else:
|
1075 |
+
raise TypeError(type(fieldname))
|
1076 |
+
|
1077 |
+
def rawaddressof(self, BTypePtr, cdata, offset=None):
|
1078 |
+
if isinstance(cdata, CTypesBaseStructOrUnion):
|
1079 |
+
ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata))
|
1080 |
+
elif isinstance(cdata, CTypesGenericPtr):
|
1081 |
+
if offset is None or not issubclass(type(cdata)._BItem,
|
1082 |
+
CTypesBaseStructOrUnion):
|
1083 |
+
raise TypeError("unexpected cdata type")
|
1084 |
+
ptr = type(cdata)._to_ctypes(cdata)
|
1085 |
+
elif isinstance(cdata, CTypesGenericArray):
|
1086 |
+
ptr = type(cdata)._to_ctypes(cdata)
|
1087 |
+
else:
|
1088 |
+
raise TypeError("expected a <cdata 'struct-or-union'>")
|
1089 |
+
if offset:
|
1090 |
+
ptr = ctypes.cast(
|
1091 |
+
ctypes.c_void_p(
|
1092 |
+
ctypes.cast(ptr, ctypes.c_void_p).value + offset),
|
1093 |
+
type(ptr))
|
1094 |
+
return BTypePtr._from_ctypes(ptr)
|
1095 |
+
|
1096 |
+
|
1097 |
+
class CTypesLibrary(object):
|
1098 |
+
|
1099 |
+
def __init__(self, backend, cdll):
|
1100 |
+
self.backend = backend
|
1101 |
+
self.cdll = cdll
|
1102 |
+
|
1103 |
+
def load_function(self, BType, name):
|
1104 |
+
c_func = getattr(self.cdll, name)
|
1105 |
+
funcobj = BType._from_ctypes(c_func)
|
1106 |
+
funcobj._name = name
|
1107 |
+
return funcobj
|
1108 |
+
|
1109 |
+
def read_variable(self, BType, name):
|
1110 |
+
try:
|
1111 |
+
ctypes_obj = BType._ctype.in_dll(self.cdll, name)
|
1112 |
+
except AttributeError as e:
|
1113 |
+
raise NotImplementedError(e)
|
1114 |
+
return BType._from_ctypes(ctypes_obj)
|
1115 |
+
|
1116 |
+
def write_variable(self, BType, name, value):
|
1117 |
+
new_ctypes_obj = BType._to_ctypes(value)
|
1118 |
+
ctypes_obj = BType._ctype.in_dll(self.cdll, name)
|
1119 |
+
ctypes.memmove(ctypes.addressof(ctypes_obj),
|
1120 |
+
ctypes.addressof(new_ctypes_obj),
|
1121 |
+
ctypes.sizeof(BType._ctype))
|
cffi/cffi_opcode.py
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .error import VerificationError
|
2 |
+
|
3 |
+
class CffiOp(object):
|
4 |
+
def __init__(self, op, arg):
|
5 |
+
self.op = op
|
6 |
+
self.arg = arg
|
7 |
+
|
8 |
+
def as_c_expr(self):
|
9 |
+
if self.op is None:
|
10 |
+
assert isinstance(self.arg, str)
|
11 |
+
return '(_cffi_opcode_t)(%s)' % (self.arg,)
|
12 |
+
classname = CLASS_NAME[self.op]
|
13 |
+
return '_CFFI_OP(_CFFI_OP_%s, %s)' % (classname, self.arg)
|
14 |
+
|
15 |
+
def as_python_bytes(self):
|
16 |
+
if self.op is None and self.arg.isdigit():
|
17 |
+
value = int(self.arg) # non-negative: '-' not in self.arg
|
18 |
+
if value >= 2**31:
|
19 |
+
raise OverflowError("cannot emit %r: limited to 2**31-1"
|
20 |
+
% (self.arg,))
|
21 |
+
return format_four_bytes(value)
|
22 |
+
if isinstance(self.arg, str):
|
23 |
+
raise VerificationError("cannot emit to Python: %r" % (self.arg,))
|
24 |
+
return format_four_bytes((self.arg << 8) | self.op)
|
25 |
+
|
26 |
+
def __str__(self):
|
27 |
+
classname = CLASS_NAME.get(self.op, self.op)
|
28 |
+
return '(%s %s)' % (classname, self.arg)
|
29 |
+
|
30 |
+
def format_four_bytes(num):
|
31 |
+
return '\\x%02X\\x%02X\\x%02X\\x%02X' % (
|
32 |
+
(num >> 24) & 0xFF,
|
33 |
+
(num >> 16) & 0xFF,
|
34 |
+
(num >> 8) & 0xFF,
|
35 |
+
(num ) & 0xFF)
|
36 |
+
|
37 |
+
OP_PRIMITIVE = 1
|
38 |
+
OP_POINTER = 3
|
39 |
+
OP_ARRAY = 5
|
40 |
+
OP_OPEN_ARRAY = 7
|
41 |
+
OP_STRUCT_UNION = 9
|
42 |
+
OP_ENUM = 11
|
43 |
+
OP_FUNCTION = 13
|
44 |
+
OP_FUNCTION_END = 15
|
45 |
+
OP_NOOP = 17
|
46 |
+
OP_BITFIELD = 19
|
47 |
+
OP_TYPENAME = 21
|
48 |
+
OP_CPYTHON_BLTN_V = 23 # varargs
|
49 |
+
OP_CPYTHON_BLTN_N = 25 # noargs
|
50 |
+
OP_CPYTHON_BLTN_O = 27 # O (i.e. a single arg)
|
51 |
+
OP_CONSTANT = 29
|
52 |
+
OP_CONSTANT_INT = 31
|
53 |
+
OP_GLOBAL_VAR = 33
|
54 |
+
OP_DLOPEN_FUNC = 35
|
55 |
+
OP_DLOPEN_CONST = 37
|
56 |
+
OP_GLOBAL_VAR_F = 39
|
57 |
+
OP_EXTERN_PYTHON = 41
|
58 |
+
|
59 |
+
PRIM_VOID = 0
|
60 |
+
PRIM_BOOL = 1
|
61 |
+
PRIM_CHAR = 2
|
62 |
+
PRIM_SCHAR = 3
|
63 |
+
PRIM_UCHAR = 4
|
64 |
+
PRIM_SHORT = 5
|
65 |
+
PRIM_USHORT = 6
|
66 |
+
PRIM_INT = 7
|
67 |
+
PRIM_UINT = 8
|
68 |
+
PRIM_LONG = 9
|
69 |
+
PRIM_ULONG = 10
|
70 |
+
PRIM_LONGLONG = 11
|
71 |
+
PRIM_ULONGLONG = 12
|
72 |
+
PRIM_FLOAT = 13
|
73 |
+
PRIM_DOUBLE = 14
|
74 |
+
PRIM_LONGDOUBLE = 15
|
75 |
+
|
76 |
+
PRIM_WCHAR = 16
|
77 |
+
PRIM_INT8 = 17
|
78 |
+
PRIM_UINT8 = 18
|
79 |
+
PRIM_INT16 = 19
|
80 |
+
PRIM_UINT16 = 20
|
81 |
+
PRIM_INT32 = 21
|
82 |
+
PRIM_UINT32 = 22
|
83 |
+
PRIM_INT64 = 23
|
84 |
+
PRIM_UINT64 = 24
|
85 |
+
PRIM_INTPTR = 25
|
86 |
+
PRIM_UINTPTR = 26
|
87 |
+
PRIM_PTRDIFF = 27
|
88 |
+
PRIM_SIZE = 28
|
89 |
+
PRIM_SSIZE = 29
|
90 |
+
PRIM_INT_LEAST8 = 30
|
91 |
+
PRIM_UINT_LEAST8 = 31
|
92 |
+
PRIM_INT_LEAST16 = 32
|
93 |
+
PRIM_UINT_LEAST16 = 33
|
94 |
+
PRIM_INT_LEAST32 = 34
|
95 |
+
PRIM_UINT_LEAST32 = 35
|
96 |
+
PRIM_INT_LEAST64 = 36
|
97 |
+
PRIM_UINT_LEAST64 = 37
|
98 |
+
PRIM_INT_FAST8 = 38
|
99 |
+
PRIM_UINT_FAST8 = 39
|
100 |
+
PRIM_INT_FAST16 = 40
|
101 |
+
PRIM_UINT_FAST16 = 41
|
102 |
+
PRIM_INT_FAST32 = 42
|
103 |
+
PRIM_UINT_FAST32 = 43
|
104 |
+
PRIM_INT_FAST64 = 44
|
105 |
+
PRIM_UINT_FAST64 = 45
|
106 |
+
PRIM_INTMAX = 46
|
107 |
+
PRIM_UINTMAX = 47
|
108 |
+
PRIM_FLOATCOMPLEX = 48
|
109 |
+
PRIM_DOUBLECOMPLEX = 49
|
110 |
+
PRIM_CHAR16 = 50
|
111 |
+
PRIM_CHAR32 = 51
|
112 |
+
|
113 |
+
_NUM_PRIM = 52
|
114 |
+
_UNKNOWN_PRIM = -1
|
115 |
+
_UNKNOWN_FLOAT_PRIM = -2
|
116 |
+
_UNKNOWN_LONG_DOUBLE = -3
|
117 |
+
|
118 |
+
_IO_FILE_STRUCT = -1
|
119 |
+
|
120 |
+
PRIMITIVE_TO_INDEX = {
|
121 |
+
'char': PRIM_CHAR,
|
122 |
+
'short': PRIM_SHORT,
|
123 |
+
'int': PRIM_INT,
|
124 |
+
'long': PRIM_LONG,
|
125 |
+
'long long': PRIM_LONGLONG,
|
126 |
+
'signed char': PRIM_SCHAR,
|
127 |
+
'unsigned char': PRIM_UCHAR,
|
128 |
+
'unsigned short': PRIM_USHORT,
|
129 |
+
'unsigned int': PRIM_UINT,
|
130 |
+
'unsigned long': PRIM_ULONG,
|
131 |
+
'unsigned long long': PRIM_ULONGLONG,
|
132 |
+
'float': PRIM_FLOAT,
|
133 |
+
'double': PRIM_DOUBLE,
|
134 |
+
'long double': PRIM_LONGDOUBLE,
|
135 |
+
'_cffi_float_complex_t': PRIM_FLOATCOMPLEX,
|
136 |
+
'_cffi_double_complex_t': PRIM_DOUBLECOMPLEX,
|
137 |
+
'_Bool': PRIM_BOOL,
|
138 |
+
'wchar_t': PRIM_WCHAR,
|
139 |
+
'char16_t': PRIM_CHAR16,
|
140 |
+
'char32_t': PRIM_CHAR32,
|
141 |
+
'int8_t': PRIM_INT8,
|
142 |
+
'uint8_t': PRIM_UINT8,
|
143 |
+
'int16_t': PRIM_INT16,
|
144 |
+
'uint16_t': PRIM_UINT16,
|
145 |
+
'int32_t': PRIM_INT32,
|
146 |
+
'uint32_t': PRIM_UINT32,
|
147 |
+
'int64_t': PRIM_INT64,
|
148 |
+
'uint64_t': PRIM_UINT64,
|
149 |
+
'intptr_t': PRIM_INTPTR,
|
150 |
+
'uintptr_t': PRIM_UINTPTR,
|
151 |
+
'ptrdiff_t': PRIM_PTRDIFF,
|
152 |
+
'size_t': PRIM_SIZE,
|
153 |
+
'ssize_t': PRIM_SSIZE,
|
154 |
+
'int_least8_t': PRIM_INT_LEAST8,
|
155 |
+
'uint_least8_t': PRIM_UINT_LEAST8,
|
156 |
+
'int_least16_t': PRIM_INT_LEAST16,
|
157 |
+
'uint_least16_t': PRIM_UINT_LEAST16,
|
158 |
+
'int_least32_t': PRIM_INT_LEAST32,
|
159 |
+
'uint_least32_t': PRIM_UINT_LEAST32,
|
160 |
+
'int_least64_t': PRIM_INT_LEAST64,
|
161 |
+
'uint_least64_t': PRIM_UINT_LEAST64,
|
162 |
+
'int_fast8_t': PRIM_INT_FAST8,
|
163 |
+
'uint_fast8_t': PRIM_UINT_FAST8,
|
164 |
+
'int_fast16_t': PRIM_INT_FAST16,
|
165 |
+
'uint_fast16_t': PRIM_UINT_FAST16,
|
166 |
+
'int_fast32_t': PRIM_INT_FAST32,
|
167 |
+
'uint_fast32_t': PRIM_UINT_FAST32,
|
168 |
+
'int_fast64_t': PRIM_INT_FAST64,
|
169 |
+
'uint_fast64_t': PRIM_UINT_FAST64,
|
170 |
+
'intmax_t': PRIM_INTMAX,
|
171 |
+
'uintmax_t': PRIM_UINTMAX,
|
172 |
+
}
|
173 |
+
|
174 |
+
F_UNION = 0x01
|
175 |
+
F_CHECK_FIELDS = 0x02
|
176 |
+
F_PACKED = 0x04
|
177 |
+
F_EXTERNAL = 0x08
|
178 |
+
F_OPAQUE = 0x10
|
179 |
+
|
180 |
+
G_FLAGS = dict([('_CFFI_' + _key, globals()[_key])
|
181 |
+
for _key in ['F_UNION', 'F_CHECK_FIELDS', 'F_PACKED',
|
182 |
+
'F_EXTERNAL', 'F_OPAQUE']])
|
183 |
+
|
184 |
+
CLASS_NAME = {}
|
185 |
+
for _name, _value in list(globals().items()):
|
186 |
+
if _name.startswith('OP_') and isinstance(_value, int):
|
187 |
+
CLASS_NAME[_value] = _name[3:]
|
cffi/commontypes.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from . import model
|
3 |
+
from .error import FFIError
|
4 |
+
|
5 |
+
|
6 |
+
COMMON_TYPES = {}
|
7 |
+
|
8 |
+
try:
|
9 |
+
# fetch "bool" and all simple Windows types
|
10 |
+
from _cffi_backend import _get_common_types
|
11 |
+
_get_common_types(COMMON_TYPES)
|
12 |
+
except ImportError:
|
13 |
+
pass
|
14 |
+
|
15 |
+
COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE')
|
16 |
+
COMMON_TYPES['bool'] = '_Bool' # in case we got ImportError above
|
17 |
+
COMMON_TYPES['float _Complex'] = '_cffi_float_complex_t'
|
18 |
+
COMMON_TYPES['double _Complex'] = '_cffi_double_complex_t'
|
19 |
+
|
20 |
+
for _type in model.PrimitiveType.ALL_PRIMITIVE_TYPES:
|
21 |
+
if _type.endswith('_t'):
|
22 |
+
COMMON_TYPES[_type] = _type
|
23 |
+
del _type
|
24 |
+
|
25 |
+
_CACHE = {}
|
26 |
+
|
27 |
+
def resolve_common_type(parser, commontype):
|
28 |
+
try:
|
29 |
+
return _CACHE[commontype]
|
30 |
+
except KeyError:
|
31 |
+
cdecl = COMMON_TYPES.get(commontype, commontype)
|
32 |
+
if not isinstance(cdecl, str):
|
33 |
+
result, quals = cdecl, 0 # cdecl is already a BaseType
|
34 |
+
elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES:
|
35 |
+
result, quals = model.PrimitiveType(cdecl), 0
|
36 |
+
elif cdecl == 'set-unicode-needed':
|
37 |
+
raise FFIError("The Windows type %r is only available after "
|
38 |
+
"you call ffi.set_unicode()" % (commontype,))
|
39 |
+
else:
|
40 |
+
if commontype == cdecl:
|
41 |
+
raise FFIError(
|
42 |
+
"Unsupported type: %r. Please look at "
|
43 |
+
"http://cffi.readthedocs.io/en/latest/cdef.html#ffi-cdef-limitations "
|
44 |
+
"and file an issue if you think this type should really "
|
45 |
+
"be supported." % (commontype,))
|
46 |
+
result, quals = parser.parse_type_and_quals(cdecl) # recursive
|
47 |
+
|
48 |
+
assert isinstance(result, model.BaseTypeByIdentity)
|
49 |
+
_CACHE[commontype] = result, quals
|
50 |
+
return result, quals
|
51 |
+
|
52 |
+
|
53 |
+
# ____________________________________________________________
|
54 |
+
# extra types for Windows (most of them are in commontypes.c)
|
55 |
+
|
56 |
+
|
57 |
+
def win_common_types():
|
58 |
+
return {
|
59 |
+
"UNICODE_STRING": model.StructType(
|
60 |
+
"_UNICODE_STRING",
|
61 |
+
["Length",
|
62 |
+
"MaximumLength",
|
63 |
+
"Buffer"],
|
64 |
+
[model.PrimitiveType("unsigned short"),
|
65 |
+
model.PrimitiveType("unsigned short"),
|
66 |
+
model.PointerType(model.PrimitiveType("wchar_t"))],
|
67 |
+
[-1, -1, -1]),
|
68 |
+
"PUNICODE_STRING": "UNICODE_STRING *",
|
69 |
+
"PCUNICODE_STRING": "const UNICODE_STRING *",
|
70 |
+
|
71 |
+
"TBYTE": "set-unicode-needed",
|
72 |
+
"TCHAR": "set-unicode-needed",
|
73 |
+
"LPCTSTR": "set-unicode-needed",
|
74 |
+
"PCTSTR": "set-unicode-needed",
|
75 |
+
"LPTSTR": "set-unicode-needed",
|
76 |
+
"PTSTR": "set-unicode-needed",
|
77 |
+
"PTBYTE": "set-unicode-needed",
|
78 |
+
"PTCHAR": "set-unicode-needed",
|
79 |
+
}
|
80 |
+
|
81 |
+
if sys.platform == 'win32':
|
82 |
+
COMMON_TYPES.update(win_common_types())
|
cffi/cparser.py
ADDED
@@ -0,0 +1,1015 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from . import model
|
2 |
+
from .commontypes import COMMON_TYPES, resolve_common_type
|
3 |
+
from .error import FFIError, CDefError
|
4 |
+
try:
|
5 |
+
from . import _pycparser as pycparser
|
6 |
+
except ImportError:
|
7 |
+
import pycparser
|
8 |
+
import weakref, re, sys
|
9 |
+
|
10 |
+
try:
|
11 |
+
if sys.version_info < (3,):
|
12 |
+
import thread as _thread
|
13 |
+
else:
|
14 |
+
import _thread
|
15 |
+
lock = _thread.allocate_lock()
|
16 |
+
except ImportError:
|
17 |
+
lock = None
|
18 |
+
|
19 |
+
def _workaround_for_static_import_finders():
|
20 |
+
# Issue #392: packaging tools like cx_Freeze can not find these
|
21 |
+
# because pycparser uses exec dynamic import. This is an obscure
|
22 |
+
# workaround. This function is never called.
|
23 |
+
import pycparser.yacctab
|
24 |
+
import pycparser.lextab
|
25 |
+
|
26 |
+
CDEF_SOURCE_STRING = "<cdef source string>"
|
27 |
+
_r_comment = re.compile(r"/\*.*?\*/|//([^\n\\]|\\.)*?$",
|
28 |
+
re.DOTALL | re.MULTILINE)
|
29 |
+
_r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)"
|
30 |
+
r"\b((?:[^\n\\]|\\.)*?)$",
|
31 |
+
re.DOTALL | re.MULTILINE)
|
32 |
+
_r_line_directive = re.compile(r"^[ \t]*#[ \t]*(?:line|\d+)\b.*$", re.MULTILINE)
|
33 |
+
_r_partial_enum = re.compile(r"=\s*\.\.\.\s*[,}]|\.\.\.\s*\}")
|
34 |
+
_r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$")
|
35 |
+
_r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]")
|
36 |
+
_r_words = re.compile(r"\w+|\S")
|
37 |
+
_parser_cache = None
|
38 |
+
_r_int_literal = re.compile(r"-?0?x?[0-9a-f]+[lu]*$", re.IGNORECASE)
|
39 |
+
_r_stdcall1 = re.compile(r"\b(__stdcall|WINAPI)\b")
|
40 |
+
_r_stdcall2 = re.compile(r"[(]\s*(__stdcall|WINAPI)\b")
|
41 |
+
_r_cdecl = re.compile(r"\b__cdecl\b")
|
42 |
+
_r_extern_python = re.compile(r'\bextern\s*"'
|
43 |
+
r'(Python|Python\s*\+\s*C|C\s*\+\s*Python)"\s*.')
|
44 |
+
_r_star_const_space = re.compile( # matches "* const "
|
45 |
+
r"[*]\s*((const|volatile|restrict)\b\s*)+")
|
46 |
+
_r_int_dotdotdot = re.compile(r"(\b(int|long|short|signed|unsigned|char)\s*)+"
|
47 |
+
r"\.\.\.")
|
48 |
+
_r_float_dotdotdot = re.compile(r"\b(double|float)\s*\.\.\.")
|
49 |
+
|
50 |
+
def _get_parser():
|
51 |
+
global _parser_cache
|
52 |
+
if _parser_cache is None:
|
53 |
+
_parser_cache = pycparser.CParser()
|
54 |
+
return _parser_cache
|
55 |
+
|
56 |
+
def _workaround_for_old_pycparser(csource):
|
57 |
+
# Workaround for a pycparser issue (fixed between pycparser 2.10 and
|
58 |
+
# 2.14): "char*const***" gives us a wrong syntax tree, the same as
|
59 |
+
# for "char***(*const)". This means we can't tell the difference
|
60 |
+
# afterwards. But "char(*const(***))" gives us the right syntax
|
61 |
+
# tree. The issue only occurs if there are several stars in
|
62 |
+
# sequence with no parenthesis inbetween, just possibly qualifiers.
|
63 |
+
# Attempt to fix it by adding some parentheses in the source: each
|
64 |
+
# time we see "* const" or "* const *", we add an opening
|
65 |
+
# parenthesis before each star---the hard part is figuring out where
|
66 |
+
# to close them.
|
67 |
+
parts = []
|
68 |
+
while True:
|
69 |
+
match = _r_star_const_space.search(csource)
|
70 |
+
if not match:
|
71 |
+
break
|
72 |
+
#print repr(''.join(parts)+csource), '=>',
|
73 |
+
parts.append(csource[:match.start()])
|
74 |
+
parts.append('('); closing = ')'
|
75 |
+
parts.append(match.group()) # e.g. "* const "
|
76 |
+
endpos = match.end()
|
77 |
+
if csource.startswith('*', endpos):
|
78 |
+
parts.append('('); closing += ')'
|
79 |
+
level = 0
|
80 |
+
i = endpos
|
81 |
+
while i < len(csource):
|
82 |
+
c = csource[i]
|
83 |
+
if c == '(':
|
84 |
+
level += 1
|
85 |
+
elif c == ')':
|
86 |
+
if level == 0:
|
87 |
+
break
|
88 |
+
level -= 1
|
89 |
+
elif c in ',;=':
|
90 |
+
if level == 0:
|
91 |
+
break
|
92 |
+
i += 1
|
93 |
+
csource = csource[endpos:i] + closing + csource[i:]
|
94 |
+
#print repr(''.join(parts)+csource)
|
95 |
+
parts.append(csource)
|
96 |
+
return ''.join(parts)
|
97 |
+
|
98 |
+
def _preprocess_extern_python(csource):
|
99 |
+
# input: `extern "Python" int foo(int);` or
|
100 |
+
# `extern "Python" { int foo(int); }`
|
101 |
+
# output:
|
102 |
+
# void __cffi_extern_python_start;
|
103 |
+
# int foo(int);
|
104 |
+
# void __cffi_extern_python_stop;
|
105 |
+
#
|
106 |
+
# input: `extern "Python+C" int foo(int);`
|
107 |
+
# output:
|
108 |
+
# void __cffi_extern_python_plus_c_start;
|
109 |
+
# int foo(int);
|
110 |
+
# void __cffi_extern_python_stop;
|
111 |
+
parts = []
|
112 |
+
while True:
|
113 |
+
match = _r_extern_python.search(csource)
|
114 |
+
if not match:
|
115 |
+
break
|
116 |
+
endpos = match.end() - 1
|
117 |
+
#print
|
118 |
+
#print ''.join(parts)+csource
|
119 |
+
#print '=>'
|
120 |
+
parts.append(csource[:match.start()])
|
121 |
+
if 'C' in match.group(1):
|
122 |
+
parts.append('void __cffi_extern_python_plus_c_start; ')
|
123 |
+
else:
|
124 |
+
parts.append('void __cffi_extern_python_start; ')
|
125 |
+
if csource[endpos] == '{':
|
126 |
+
# grouping variant
|
127 |
+
closing = csource.find('}', endpos)
|
128 |
+
if closing < 0:
|
129 |
+
raise CDefError("'extern \"Python\" {': no '}' found")
|
130 |
+
if csource.find('{', endpos + 1, closing) >= 0:
|
131 |
+
raise NotImplementedError("cannot use { } inside a block "
|
132 |
+
"'extern \"Python\" { ... }'")
|
133 |
+
parts.append(csource[endpos+1:closing])
|
134 |
+
csource = csource[closing+1:]
|
135 |
+
else:
|
136 |
+
# non-grouping variant
|
137 |
+
semicolon = csource.find(';', endpos)
|
138 |
+
if semicolon < 0:
|
139 |
+
raise CDefError("'extern \"Python\": no ';' found")
|
140 |
+
parts.append(csource[endpos:semicolon+1])
|
141 |
+
csource = csource[semicolon+1:]
|
142 |
+
parts.append(' void __cffi_extern_python_stop;')
|
143 |
+
#print ''.join(parts)+csource
|
144 |
+
#print
|
145 |
+
parts.append(csource)
|
146 |
+
return ''.join(parts)
|
147 |
+
|
148 |
+
def _warn_for_string_literal(csource):
|
149 |
+
if '"' not in csource:
|
150 |
+
return
|
151 |
+
for line in csource.splitlines():
|
152 |
+
if '"' in line and not line.lstrip().startswith('#'):
|
153 |
+
import warnings
|
154 |
+
warnings.warn("String literal found in cdef() or type source. "
|
155 |
+
"String literals are ignored here, but you should "
|
156 |
+
"remove them anyway because some character sequences "
|
157 |
+
"confuse pre-parsing.")
|
158 |
+
break
|
159 |
+
|
160 |
+
def _warn_for_non_extern_non_static_global_variable(decl):
|
161 |
+
if not decl.storage:
|
162 |
+
import warnings
|
163 |
+
warnings.warn("Global variable '%s' in cdef(): for consistency "
|
164 |
+
"with C it should have a storage class specifier "
|
165 |
+
"(usually 'extern')" % (decl.name,))
|
166 |
+
|
167 |
+
def _remove_line_directives(csource):
|
168 |
+
# _r_line_directive matches whole lines, without the final \n, if they
|
169 |
+
# start with '#line' with some spacing allowed, or '#NUMBER'. This
|
170 |
+
# function stores them away and replaces them with exactly the string
|
171 |
+
# '#line@N', where N is the index in the list 'line_directives'.
|
172 |
+
line_directives = []
|
173 |
+
def replace(m):
|
174 |
+
i = len(line_directives)
|
175 |
+
line_directives.append(m.group())
|
176 |
+
return '#line@%d' % i
|
177 |
+
csource = _r_line_directive.sub(replace, csource)
|
178 |
+
return csource, line_directives
|
179 |
+
|
180 |
+
def _put_back_line_directives(csource, line_directives):
|
181 |
+
def replace(m):
|
182 |
+
s = m.group()
|
183 |
+
if not s.startswith('#line@'):
|
184 |
+
raise AssertionError("unexpected #line directive "
|
185 |
+
"(should have been processed and removed")
|
186 |
+
return line_directives[int(s[6:])]
|
187 |
+
return _r_line_directive.sub(replace, csource)
|
188 |
+
|
189 |
+
def _preprocess(csource):
|
190 |
+
# First, remove the lines of the form '#line N "filename"' because
|
191 |
+
# the "filename" part could confuse the rest
|
192 |
+
csource, line_directives = _remove_line_directives(csource)
|
193 |
+
# Remove comments. NOTE: this only work because the cdef() section
|
194 |
+
# should not contain any string literals (except in line directives)!
|
195 |
+
def replace_keeping_newlines(m):
|
196 |
+
return ' ' + m.group().count('\n') * '\n'
|
197 |
+
csource = _r_comment.sub(replace_keeping_newlines, csource)
|
198 |
+
# Remove the "#define FOO x" lines
|
199 |
+
macros = {}
|
200 |
+
for match in _r_define.finditer(csource):
|
201 |
+
macroname, macrovalue = match.groups()
|
202 |
+
macrovalue = macrovalue.replace('\\\n', '').strip()
|
203 |
+
macros[macroname] = macrovalue
|
204 |
+
csource = _r_define.sub('', csource)
|
205 |
+
#
|
206 |
+
if pycparser.__version__ < '2.14':
|
207 |
+
csource = _workaround_for_old_pycparser(csource)
|
208 |
+
#
|
209 |
+
# BIG HACK: replace WINAPI or __stdcall with "volatile const".
|
210 |
+
# It doesn't make sense for the return type of a function to be
|
211 |
+
# "volatile volatile const", so we abuse it to detect __stdcall...
|
212 |
+
# Hack number 2 is that "int(volatile *fptr)();" is not valid C
|
213 |
+
# syntax, so we place the "volatile" before the opening parenthesis.
|
214 |
+
csource = _r_stdcall2.sub(' volatile volatile const(', csource)
|
215 |
+
csource = _r_stdcall1.sub(' volatile volatile const ', csource)
|
216 |
+
csource = _r_cdecl.sub(' ', csource)
|
217 |
+
#
|
218 |
+
# Replace `extern "Python"` with start/end markers
|
219 |
+
csource = _preprocess_extern_python(csource)
|
220 |
+
#
|
221 |
+
# Now there should not be any string literal left; warn if we get one
|
222 |
+
_warn_for_string_literal(csource)
|
223 |
+
#
|
224 |
+
# Replace "[...]" with "[__dotdotdotarray__]"
|
225 |
+
csource = _r_partial_array.sub('[__dotdotdotarray__]', csource)
|
226 |
+
#
|
227 |
+
# Replace "...}" with "__dotdotdotNUM__}". This construction should
|
228 |
+
# occur only at the end of enums; at the end of structs we have "...;}"
|
229 |
+
# and at the end of vararg functions "...);". Also replace "=...[,}]"
|
230 |
+
# with ",__dotdotdotNUM__[,}]": this occurs in the enums too, when
|
231 |
+
# giving an unknown value.
|
232 |
+
matches = list(_r_partial_enum.finditer(csource))
|
233 |
+
for number, match in enumerate(reversed(matches)):
|
234 |
+
p = match.start()
|
235 |
+
if csource[p] == '=':
|
236 |
+
p2 = csource.find('...', p, match.end())
|
237 |
+
assert p2 > p
|
238 |
+
csource = '%s,__dotdotdot%d__ %s' % (csource[:p], number,
|
239 |
+
csource[p2+3:])
|
240 |
+
else:
|
241 |
+
assert csource[p:p+3] == '...'
|
242 |
+
csource = '%s __dotdotdot%d__ %s' % (csource[:p], number,
|
243 |
+
csource[p+3:])
|
244 |
+
# Replace "int ..." or "unsigned long int..." with "__dotdotdotint__"
|
245 |
+
csource = _r_int_dotdotdot.sub(' __dotdotdotint__ ', csource)
|
246 |
+
# Replace "float ..." or "double..." with "__dotdotdotfloat__"
|
247 |
+
csource = _r_float_dotdotdot.sub(' __dotdotdotfloat__ ', csource)
|
248 |
+
# Replace all remaining "..." with the same name, "__dotdotdot__",
|
249 |
+
# which is declared with a typedef for the purpose of C parsing.
|
250 |
+
csource = csource.replace('...', ' __dotdotdot__ ')
|
251 |
+
# Finally, put back the line directives
|
252 |
+
csource = _put_back_line_directives(csource, line_directives)
|
253 |
+
return csource, macros
|
254 |
+
|
255 |
+
def _common_type_names(csource):
|
256 |
+
# Look in the source for what looks like usages of types from the
|
257 |
+
# list of common types. A "usage" is approximated here as the
|
258 |
+
# appearance of the word, minus a "definition" of the type, which
|
259 |
+
# is the last word in a "typedef" statement. Approximative only
|
260 |
+
# but should be fine for all the common types.
|
261 |
+
look_for_words = set(COMMON_TYPES)
|
262 |
+
look_for_words.add(';')
|
263 |
+
look_for_words.add(',')
|
264 |
+
look_for_words.add('(')
|
265 |
+
look_for_words.add(')')
|
266 |
+
look_for_words.add('typedef')
|
267 |
+
words_used = set()
|
268 |
+
is_typedef = False
|
269 |
+
paren = 0
|
270 |
+
previous_word = ''
|
271 |
+
for word in _r_words.findall(csource):
|
272 |
+
if word in look_for_words:
|
273 |
+
if word == ';':
|
274 |
+
if is_typedef:
|
275 |
+
words_used.discard(previous_word)
|
276 |
+
look_for_words.discard(previous_word)
|
277 |
+
is_typedef = False
|
278 |
+
elif word == 'typedef':
|
279 |
+
is_typedef = True
|
280 |
+
paren = 0
|
281 |
+
elif word == '(':
|
282 |
+
paren += 1
|
283 |
+
elif word == ')':
|
284 |
+
paren -= 1
|
285 |
+
elif word == ',':
|
286 |
+
if is_typedef and paren == 0:
|
287 |
+
words_used.discard(previous_word)
|
288 |
+
look_for_words.discard(previous_word)
|
289 |
+
else: # word in COMMON_TYPES
|
290 |
+
words_used.add(word)
|
291 |
+
previous_word = word
|
292 |
+
return words_used
|
293 |
+
|
294 |
+
|
295 |
+
class Parser(object):
|
296 |
+
|
297 |
+
def __init__(self):
|
298 |
+
self._declarations = {}
|
299 |
+
self._included_declarations = set()
|
300 |
+
self._anonymous_counter = 0
|
301 |
+
self._structnode2type = weakref.WeakKeyDictionary()
|
302 |
+
self._options = {}
|
303 |
+
self._int_constants = {}
|
304 |
+
self._recomplete = []
|
305 |
+
self._uses_new_feature = None
|
306 |
+
|
307 |
+
def _parse(self, csource):
|
308 |
+
csource, macros = _preprocess(csource)
|
309 |
+
# XXX: for more efficiency we would need to poke into the
|
310 |
+
# internals of CParser... the following registers the
|
311 |
+
# typedefs, because their presence or absence influences the
|
312 |
+
# parsing itself (but what they are typedef'ed to plays no role)
|
313 |
+
ctn = _common_type_names(csource)
|
314 |
+
typenames = []
|
315 |
+
for name in sorted(self._declarations):
|
316 |
+
if name.startswith('typedef '):
|
317 |
+
name = name[8:]
|
318 |
+
typenames.append(name)
|
319 |
+
ctn.discard(name)
|
320 |
+
typenames += sorted(ctn)
|
321 |
+
#
|
322 |
+
csourcelines = []
|
323 |
+
csourcelines.append('# 1 "<cdef automatic initialization code>"')
|
324 |
+
for typename in typenames:
|
325 |
+
csourcelines.append('typedef int %s;' % typename)
|
326 |
+
csourcelines.append('typedef int __dotdotdotint__, __dotdotdotfloat__,'
|
327 |
+
' __dotdotdot__;')
|
328 |
+
# this forces pycparser to consider the following in the file
|
329 |
+
# called <cdef source string> from line 1
|
330 |
+
csourcelines.append('# 1 "%s"' % (CDEF_SOURCE_STRING,))
|
331 |
+
csourcelines.append(csource)
|
332 |
+
csourcelines.append('') # see test_missing_newline_bug
|
333 |
+
fullcsource = '\n'.join(csourcelines)
|
334 |
+
if lock is not None:
|
335 |
+
lock.acquire() # pycparser is not thread-safe...
|
336 |
+
try:
|
337 |
+
ast = _get_parser().parse(fullcsource)
|
338 |
+
except pycparser.c_parser.ParseError as e:
|
339 |
+
self.convert_pycparser_error(e, csource)
|
340 |
+
finally:
|
341 |
+
if lock is not None:
|
342 |
+
lock.release()
|
343 |
+
# csource will be used to find buggy source text
|
344 |
+
return ast, macros, csource
|
345 |
+
|
346 |
+
def _convert_pycparser_error(self, e, csource):
|
347 |
+
# xxx look for "<cdef source string>:NUM:" at the start of str(e)
|
348 |
+
# and interpret that as a line number. This will not work if
|
349 |
+
# the user gives explicit ``# NUM "FILE"`` directives.
|
350 |
+
line = None
|
351 |
+
msg = str(e)
|
352 |
+
match = re.match(r"%s:(\d+):" % (CDEF_SOURCE_STRING,), msg)
|
353 |
+
if match:
|
354 |
+
linenum = int(match.group(1), 10)
|
355 |
+
csourcelines = csource.splitlines()
|
356 |
+
if 1 <= linenum <= len(csourcelines):
|
357 |
+
line = csourcelines[linenum-1]
|
358 |
+
return line
|
359 |
+
|
360 |
+
def convert_pycparser_error(self, e, csource):
|
361 |
+
line = self._convert_pycparser_error(e, csource)
|
362 |
+
|
363 |
+
msg = str(e)
|
364 |
+
if line:
|
365 |
+
msg = 'cannot parse "%s"\n%s' % (line.strip(), msg)
|
366 |
+
else:
|
367 |
+
msg = 'parse error\n%s' % (msg,)
|
368 |
+
raise CDefError(msg)
|
369 |
+
|
370 |
+
def parse(self, csource, override=False, packed=False, pack=None,
|
371 |
+
dllexport=False):
|
372 |
+
if packed:
|
373 |
+
if packed != True:
|
374 |
+
raise ValueError("'packed' should be False or True; use "
|
375 |
+
"'pack' to give another value")
|
376 |
+
if pack:
|
377 |
+
raise ValueError("cannot give both 'pack' and 'packed'")
|
378 |
+
pack = 1
|
379 |
+
elif pack:
|
380 |
+
if pack & (pack - 1):
|
381 |
+
raise ValueError("'pack' must be a power of two, not %r" %
|
382 |
+
(pack,))
|
383 |
+
else:
|
384 |
+
pack = 0
|
385 |
+
prev_options = self._options
|
386 |
+
try:
|
387 |
+
self._options = {'override': override,
|
388 |
+
'packed': pack,
|
389 |
+
'dllexport': dllexport}
|
390 |
+
self._internal_parse(csource)
|
391 |
+
finally:
|
392 |
+
self._options = prev_options
|
393 |
+
|
394 |
+
def _internal_parse(self, csource):
|
395 |
+
ast, macros, csource = self._parse(csource)
|
396 |
+
# add the macros
|
397 |
+
self._process_macros(macros)
|
398 |
+
# find the first "__dotdotdot__" and use that as a separator
|
399 |
+
# between the repeated typedefs and the real csource
|
400 |
+
iterator = iter(ast.ext)
|
401 |
+
for decl in iterator:
|
402 |
+
if decl.name == '__dotdotdot__':
|
403 |
+
break
|
404 |
+
else:
|
405 |
+
assert 0
|
406 |
+
current_decl = None
|
407 |
+
#
|
408 |
+
try:
|
409 |
+
self._inside_extern_python = '__cffi_extern_python_stop'
|
410 |
+
for decl in iterator:
|
411 |
+
current_decl = decl
|
412 |
+
if isinstance(decl, pycparser.c_ast.Decl):
|
413 |
+
self._parse_decl(decl)
|
414 |
+
elif isinstance(decl, pycparser.c_ast.Typedef):
|
415 |
+
if not decl.name:
|
416 |
+
raise CDefError("typedef does not declare any name",
|
417 |
+
decl)
|
418 |
+
quals = 0
|
419 |
+
if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType) and
|
420 |
+
decl.type.type.names[-1].startswith('__dotdotdot')):
|
421 |
+
realtype = self._get_unknown_type(decl)
|
422 |
+
elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and
|
423 |
+
isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and
|
424 |
+
isinstance(decl.type.type.type,
|
425 |
+
pycparser.c_ast.IdentifierType) and
|
426 |
+
decl.type.type.type.names[-1].startswith('__dotdotdot')):
|
427 |
+
realtype = self._get_unknown_ptr_type(decl)
|
428 |
+
else:
|
429 |
+
realtype, quals = self._get_type_and_quals(
|
430 |
+
decl.type, name=decl.name, partial_length_ok=True,
|
431 |
+
typedef_example="*(%s *)0" % (decl.name,))
|
432 |
+
self._declare('typedef ' + decl.name, realtype, quals=quals)
|
433 |
+
elif decl.__class__.__name__ == 'Pragma':
|
434 |
+
# skip pragma, only in pycparser 2.15
|
435 |
+
import warnings
|
436 |
+
warnings.warn(
|
437 |
+
"#pragma in cdef() are entirely ignored. "
|
438 |
+
"They should be removed for now, otherwise your "
|
439 |
+
"code might behave differently in a future version "
|
440 |
+
"of CFFI if #pragma support gets added. Note that "
|
441 |
+
"'#pragma pack' needs to be replaced with the "
|
442 |
+
"'packed' keyword argument to cdef().")
|
443 |
+
else:
|
444 |
+
raise CDefError("unexpected <%s>: this construct is valid "
|
445 |
+
"C but not valid in cdef()" %
|
446 |
+
decl.__class__.__name__, decl)
|
447 |
+
except CDefError as e:
|
448 |
+
if len(e.args) == 1:
|
449 |
+
e.args = e.args + (current_decl,)
|
450 |
+
raise
|
451 |
+
except FFIError as e:
|
452 |
+
msg = self._convert_pycparser_error(e, csource)
|
453 |
+
if msg:
|
454 |
+
e.args = (e.args[0] + "\n *** Err: %s" % msg,)
|
455 |
+
raise
|
456 |
+
|
457 |
+
def _add_constants(self, key, val):
|
458 |
+
if key in self._int_constants:
|
459 |
+
if self._int_constants[key] == val:
|
460 |
+
return # ignore identical double declarations
|
461 |
+
raise FFIError(
|
462 |
+
"multiple declarations of constant: %s" % (key,))
|
463 |
+
self._int_constants[key] = val
|
464 |
+
|
465 |
+
def _add_integer_constant(self, name, int_str):
|
466 |
+
int_str = int_str.lower().rstrip("ul")
|
467 |
+
neg = int_str.startswith('-')
|
468 |
+
if neg:
|
469 |
+
int_str = int_str[1:]
|
470 |
+
# "010" is not valid oct in py3
|
471 |
+
if (int_str.startswith("0") and int_str != '0'
|
472 |
+
and not int_str.startswith("0x")):
|
473 |
+
int_str = "0o" + int_str[1:]
|
474 |
+
pyvalue = int(int_str, 0)
|
475 |
+
if neg:
|
476 |
+
pyvalue = -pyvalue
|
477 |
+
self._add_constants(name, pyvalue)
|
478 |
+
self._declare('macro ' + name, pyvalue)
|
479 |
+
|
480 |
+
def _process_macros(self, macros):
|
481 |
+
for key, value in macros.items():
|
482 |
+
value = value.strip()
|
483 |
+
if _r_int_literal.match(value):
|
484 |
+
self._add_integer_constant(key, value)
|
485 |
+
elif value == '...':
|
486 |
+
self._declare('macro ' + key, value)
|
487 |
+
else:
|
488 |
+
raise CDefError(
|
489 |
+
'only supports one of the following syntax:\n'
|
490 |
+
' #define %s ... (literally dot-dot-dot)\n'
|
491 |
+
' #define %s NUMBER (with NUMBER an integer'
|
492 |
+
' constant, decimal/hex/octal)\n'
|
493 |
+
'got:\n'
|
494 |
+
' #define %s %s'
|
495 |
+
% (key, key, key, value))
|
496 |
+
|
497 |
+
def _declare_function(self, tp, quals, decl):
|
498 |
+
tp = self._get_type_pointer(tp, quals)
|
499 |
+
if self._options.get('dllexport'):
|
500 |
+
tag = 'dllexport_python '
|
501 |
+
elif self._inside_extern_python == '__cffi_extern_python_start':
|
502 |
+
tag = 'extern_python '
|
503 |
+
elif self._inside_extern_python == '__cffi_extern_python_plus_c_start':
|
504 |
+
tag = 'extern_python_plus_c '
|
505 |
+
else:
|
506 |
+
tag = 'function '
|
507 |
+
self._declare(tag + decl.name, tp)
|
508 |
+
|
509 |
+
def _parse_decl(self, decl):
|
510 |
+
node = decl.type
|
511 |
+
if isinstance(node, pycparser.c_ast.FuncDecl):
|
512 |
+
tp, quals = self._get_type_and_quals(node, name=decl.name)
|
513 |
+
assert isinstance(tp, model.RawFunctionType)
|
514 |
+
self._declare_function(tp, quals, decl)
|
515 |
+
else:
|
516 |
+
if isinstance(node, pycparser.c_ast.Struct):
|
517 |
+
self._get_struct_union_enum_type('struct', node)
|
518 |
+
elif isinstance(node, pycparser.c_ast.Union):
|
519 |
+
self._get_struct_union_enum_type('union', node)
|
520 |
+
elif isinstance(node, pycparser.c_ast.Enum):
|
521 |
+
self._get_struct_union_enum_type('enum', node)
|
522 |
+
elif not decl.name:
|
523 |
+
raise CDefError("construct does not declare any variable",
|
524 |
+
decl)
|
525 |
+
#
|
526 |
+
if decl.name:
|
527 |
+
tp, quals = self._get_type_and_quals(node,
|
528 |
+
partial_length_ok=True)
|
529 |
+
if tp.is_raw_function:
|
530 |
+
self._declare_function(tp, quals, decl)
|
531 |
+
elif (tp.is_integer_type() and
|
532 |
+
hasattr(decl, 'init') and
|
533 |
+
hasattr(decl.init, 'value') and
|
534 |
+
_r_int_literal.match(decl.init.value)):
|
535 |
+
self._add_integer_constant(decl.name, decl.init.value)
|
536 |
+
elif (tp.is_integer_type() and
|
537 |
+
isinstance(decl.init, pycparser.c_ast.UnaryOp) and
|
538 |
+
decl.init.op == '-' and
|
539 |
+
hasattr(decl.init.expr, 'value') and
|
540 |
+
_r_int_literal.match(decl.init.expr.value)):
|
541 |
+
self._add_integer_constant(decl.name,
|
542 |
+
'-' + decl.init.expr.value)
|
543 |
+
elif (tp is model.void_type and
|
544 |
+
decl.name.startswith('__cffi_extern_python_')):
|
545 |
+
# hack: `extern "Python"` in the C source is replaced
|
546 |
+
# with "void __cffi_extern_python_start;" and
|
547 |
+
# "void __cffi_extern_python_stop;"
|
548 |
+
self._inside_extern_python = decl.name
|
549 |
+
else:
|
550 |
+
if self._inside_extern_python !='__cffi_extern_python_stop':
|
551 |
+
raise CDefError(
|
552 |
+
"cannot declare constants or "
|
553 |
+
"variables with 'extern \"Python\"'")
|
554 |
+
if (quals & model.Q_CONST) and not tp.is_array_type:
|
555 |
+
self._declare('constant ' + decl.name, tp, quals=quals)
|
556 |
+
else:
|
557 |
+
_warn_for_non_extern_non_static_global_variable(decl)
|
558 |
+
self._declare('variable ' + decl.name, tp, quals=quals)
|
559 |
+
|
560 |
+
def parse_type(self, cdecl):
|
561 |
+
return self.parse_type_and_quals(cdecl)[0]
|
562 |
+
|
563 |
+
def parse_type_and_quals(self, cdecl):
|
564 |
+
ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2]
|
565 |
+
assert not macros
|
566 |
+
exprnode = ast.ext[-1].type.args.params[0]
|
567 |
+
if isinstance(exprnode, pycparser.c_ast.ID):
|
568 |
+
raise CDefError("unknown identifier '%s'" % (exprnode.name,))
|
569 |
+
return self._get_type_and_quals(exprnode.type)
|
570 |
+
|
571 |
+
def _declare(self, name, obj, included=False, quals=0):
|
572 |
+
if name in self._declarations:
|
573 |
+
prevobj, prevquals = self._declarations[name]
|
574 |
+
if prevobj is obj and prevquals == quals:
|
575 |
+
return
|
576 |
+
if not self._options.get('override'):
|
577 |
+
raise FFIError(
|
578 |
+
"multiple declarations of %s (for interactive usage, "
|
579 |
+
"try cdef(xx, override=True))" % (name,))
|
580 |
+
assert '__dotdotdot__' not in name.split()
|
581 |
+
self._declarations[name] = (obj, quals)
|
582 |
+
if included:
|
583 |
+
self._included_declarations.add(obj)
|
584 |
+
|
585 |
+
def _extract_quals(self, type):
|
586 |
+
quals = 0
|
587 |
+
if isinstance(type, (pycparser.c_ast.TypeDecl,
|
588 |
+
pycparser.c_ast.PtrDecl)):
|
589 |
+
if 'const' in type.quals:
|
590 |
+
quals |= model.Q_CONST
|
591 |
+
if 'volatile' in type.quals:
|
592 |
+
quals |= model.Q_VOLATILE
|
593 |
+
if 'restrict' in type.quals:
|
594 |
+
quals |= model.Q_RESTRICT
|
595 |
+
return quals
|
596 |
+
|
597 |
+
def _get_type_pointer(self, type, quals, declname=None):
|
598 |
+
if isinstance(type, model.RawFunctionType):
|
599 |
+
return type.as_function_pointer()
|
600 |
+
if (isinstance(type, model.StructOrUnionOrEnum) and
|
601 |
+
type.name.startswith('$') and type.name[1:].isdigit() and
|
602 |
+
type.forcename is None and declname is not None):
|
603 |
+
return model.NamedPointerType(type, declname, quals)
|
604 |
+
return model.PointerType(type, quals)
|
605 |
+
|
606 |
+
def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False,
|
607 |
+
typedef_example=None):
|
608 |
+
# first, dereference typedefs, if we have it already parsed, we're good
|
609 |
+
if (isinstance(typenode, pycparser.c_ast.TypeDecl) and
|
610 |
+
isinstance(typenode.type, pycparser.c_ast.IdentifierType) and
|
611 |
+
len(typenode.type.names) == 1 and
|
612 |
+
('typedef ' + typenode.type.names[0]) in self._declarations):
|
613 |
+
tp, quals = self._declarations['typedef ' + typenode.type.names[0]]
|
614 |
+
quals |= self._extract_quals(typenode)
|
615 |
+
return tp, quals
|
616 |
+
#
|
617 |
+
if isinstance(typenode, pycparser.c_ast.ArrayDecl):
|
618 |
+
# array type
|
619 |
+
if typenode.dim is None:
|
620 |
+
length = None
|
621 |
+
else:
|
622 |
+
length = self._parse_constant(
|
623 |
+
typenode.dim, partial_length_ok=partial_length_ok)
|
624 |
+
# a hack: in 'typedef int foo_t[...][...];', don't use '...' as
|
625 |
+
# the length but use directly the C expression that would be
|
626 |
+
# generated by recompiler.py. This lets the typedef be used in
|
627 |
+
# many more places within recompiler.py
|
628 |
+
if typedef_example is not None:
|
629 |
+
if length == '...':
|
630 |
+
length = '_cffi_array_len(%s)' % (typedef_example,)
|
631 |
+
typedef_example = "*" + typedef_example
|
632 |
+
#
|
633 |
+
tp, quals = self._get_type_and_quals(typenode.type,
|
634 |
+
partial_length_ok=partial_length_ok,
|
635 |
+
typedef_example=typedef_example)
|
636 |
+
return model.ArrayType(tp, length), quals
|
637 |
+
#
|
638 |
+
if isinstance(typenode, pycparser.c_ast.PtrDecl):
|
639 |
+
# pointer type
|
640 |
+
itemtype, itemquals = self._get_type_and_quals(typenode.type)
|
641 |
+
tp = self._get_type_pointer(itemtype, itemquals, declname=name)
|
642 |
+
quals = self._extract_quals(typenode)
|
643 |
+
return tp, quals
|
644 |
+
#
|
645 |
+
if isinstance(typenode, pycparser.c_ast.TypeDecl):
|
646 |
+
quals = self._extract_quals(typenode)
|
647 |
+
type = typenode.type
|
648 |
+
if isinstance(type, pycparser.c_ast.IdentifierType):
|
649 |
+
# assume a primitive type. get it from .names, but reduce
|
650 |
+
# synonyms to a single chosen combination
|
651 |
+
names = list(type.names)
|
652 |
+
if names != ['signed', 'char']: # keep this unmodified
|
653 |
+
prefixes = {}
|
654 |
+
while names:
|
655 |
+
name = names[0]
|
656 |
+
if name in ('short', 'long', 'signed', 'unsigned'):
|
657 |
+
prefixes[name] = prefixes.get(name, 0) + 1
|
658 |
+
del names[0]
|
659 |
+
else:
|
660 |
+
break
|
661 |
+
# ignore the 'signed' prefix below, and reorder the others
|
662 |
+
newnames = []
|
663 |
+
for prefix in ('unsigned', 'short', 'long'):
|
664 |
+
for i in range(prefixes.get(prefix, 0)):
|
665 |
+
newnames.append(prefix)
|
666 |
+
if not names:
|
667 |
+
names = ['int'] # implicitly
|
668 |
+
if names == ['int']: # but kill it if 'short' or 'long'
|
669 |
+
if 'short' in prefixes or 'long' in prefixes:
|
670 |
+
names = []
|
671 |
+
names = newnames + names
|
672 |
+
ident = ' '.join(names)
|
673 |
+
if ident == 'void':
|
674 |
+
return model.void_type, quals
|
675 |
+
if ident == '__dotdotdot__':
|
676 |
+
raise FFIError(':%d: bad usage of "..."' %
|
677 |
+
typenode.coord.line)
|
678 |
+
tp0, quals0 = resolve_common_type(self, ident)
|
679 |
+
return tp0, (quals | quals0)
|
680 |
+
#
|
681 |
+
if isinstance(type, pycparser.c_ast.Struct):
|
682 |
+
# 'struct foobar'
|
683 |
+
tp = self._get_struct_union_enum_type('struct', type, name)
|
684 |
+
return tp, quals
|
685 |
+
#
|
686 |
+
if isinstance(type, pycparser.c_ast.Union):
|
687 |
+
# 'union foobar'
|
688 |
+
tp = self._get_struct_union_enum_type('union', type, name)
|
689 |
+
return tp, quals
|
690 |
+
#
|
691 |
+
if isinstance(type, pycparser.c_ast.Enum):
|
692 |
+
# 'enum foobar'
|
693 |
+
tp = self._get_struct_union_enum_type('enum', type, name)
|
694 |
+
return tp, quals
|
695 |
+
#
|
696 |
+
if isinstance(typenode, pycparser.c_ast.FuncDecl):
|
697 |
+
# a function type
|
698 |
+
return self._parse_function_type(typenode, name), 0
|
699 |
+
#
|
700 |
+
# nested anonymous structs or unions end up here
|
701 |
+
if isinstance(typenode, pycparser.c_ast.Struct):
|
702 |
+
return self._get_struct_union_enum_type('struct', typenode, name,
|
703 |
+
nested=True), 0
|
704 |
+
if isinstance(typenode, pycparser.c_ast.Union):
|
705 |
+
return self._get_struct_union_enum_type('union', typenode, name,
|
706 |
+
nested=True), 0
|
707 |
+
#
|
708 |
+
raise FFIError(":%d: bad or unsupported type declaration" %
|
709 |
+
typenode.coord.line)
|
710 |
+
|
711 |
+
def _parse_function_type(self, typenode, funcname=None):
|
712 |
+
params = list(getattr(typenode.args, 'params', []))
|
713 |
+
for i, arg in enumerate(params):
|
714 |
+
if not hasattr(arg, 'type'):
|
715 |
+
raise CDefError("%s arg %d: unknown type '%s'"
|
716 |
+
" (if you meant to use the old C syntax of giving"
|
717 |
+
" untyped arguments, it is not supported)"
|
718 |
+
% (funcname or 'in expression', i + 1,
|
719 |
+
getattr(arg, 'name', '?')))
|
720 |
+
ellipsis = (
|
721 |
+
len(params) > 0 and
|
722 |
+
isinstance(params[-1].type, pycparser.c_ast.TypeDecl) and
|
723 |
+
isinstance(params[-1].type.type,
|
724 |
+
pycparser.c_ast.IdentifierType) and
|
725 |
+
params[-1].type.type.names == ['__dotdotdot__'])
|
726 |
+
if ellipsis:
|
727 |
+
params.pop()
|
728 |
+
if not params:
|
729 |
+
raise CDefError(
|
730 |
+
"%s: a function with only '(...)' as argument"
|
731 |
+
" is not correct C" % (funcname or 'in expression'))
|
732 |
+
args = [self._as_func_arg(*self._get_type_and_quals(argdeclnode.type))
|
733 |
+
for argdeclnode in params]
|
734 |
+
if not ellipsis and args == [model.void_type]:
|
735 |
+
args = []
|
736 |
+
result, quals = self._get_type_and_quals(typenode.type)
|
737 |
+
# the 'quals' on the result type are ignored. HACK: we absure them
|
738 |
+
# to detect __stdcall functions: we textually replace "__stdcall"
|
739 |
+
# with "volatile volatile const" above.
|
740 |
+
abi = None
|
741 |
+
if hasattr(typenode.type, 'quals'): # else, probable syntax error anyway
|
742 |
+
if typenode.type.quals[-3:] == ['volatile', 'volatile', 'const']:
|
743 |
+
abi = '__stdcall'
|
744 |
+
return model.RawFunctionType(tuple(args), result, ellipsis, abi)
|
745 |
+
|
746 |
+
def _as_func_arg(self, type, quals):
|
747 |
+
if isinstance(type, model.ArrayType):
|
748 |
+
return model.PointerType(type.item, quals)
|
749 |
+
elif isinstance(type, model.RawFunctionType):
|
750 |
+
return type.as_function_pointer()
|
751 |
+
else:
|
752 |
+
return type
|
753 |
+
|
754 |
+
def _get_struct_union_enum_type(self, kind, type, name=None, nested=False):
|
755 |
+
# First, a level of caching on the exact 'type' node of the AST.
|
756 |
+
# This is obscure, but needed because pycparser "unrolls" declarations
|
757 |
+
# such as "typedef struct { } foo_t, *foo_p" and we end up with
|
758 |
+
# an AST that is not a tree, but a DAG, with the "type" node of the
|
759 |
+
# two branches foo_t and foo_p of the trees being the same node.
|
760 |
+
# It's a bit silly but detecting "DAG-ness" in the AST tree seems
|
761 |
+
# to be the only way to distinguish this case from two independent
|
762 |
+
# structs. See test_struct_with_two_usages.
|
763 |
+
try:
|
764 |
+
return self._structnode2type[type]
|
765 |
+
except KeyError:
|
766 |
+
pass
|
767 |
+
#
|
768 |
+
# Note that this must handle parsing "struct foo" any number of
|
769 |
+
# times and always return the same StructType object. Additionally,
|
770 |
+
# one of these times (not necessarily the first), the fields of
|
771 |
+
# the struct can be specified with "struct foo { ...fields... }".
|
772 |
+
# If no name is given, then we have to create a new anonymous struct
|
773 |
+
# with no caching; in this case, the fields are either specified
|
774 |
+
# right now or never.
|
775 |
+
#
|
776 |
+
force_name = name
|
777 |
+
name = type.name
|
778 |
+
#
|
779 |
+
# get the type or create it if needed
|
780 |
+
if name is None:
|
781 |
+
# 'force_name' is used to guess a more readable name for
|
782 |
+
# anonymous structs, for the common case "typedef struct { } foo".
|
783 |
+
if force_name is not None:
|
784 |
+
explicit_name = '$%s' % force_name
|
785 |
+
else:
|
786 |
+
self._anonymous_counter += 1
|
787 |
+
explicit_name = '$%d' % self._anonymous_counter
|
788 |
+
tp = None
|
789 |
+
else:
|
790 |
+
explicit_name = name
|
791 |
+
key = '%s %s' % (kind, name)
|
792 |
+
tp, _ = self._declarations.get(key, (None, None))
|
793 |
+
#
|
794 |
+
if tp is None:
|
795 |
+
if kind == 'struct':
|
796 |
+
tp = model.StructType(explicit_name, None, None, None)
|
797 |
+
elif kind == 'union':
|
798 |
+
tp = model.UnionType(explicit_name, None, None, None)
|
799 |
+
elif kind == 'enum':
|
800 |
+
if explicit_name == '__dotdotdot__':
|
801 |
+
raise CDefError("Enums cannot be declared with ...")
|
802 |
+
tp = self._build_enum_type(explicit_name, type.values)
|
803 |
+
else:
|
804 |
+
raise AssertionError("kind = %r" % (kind,))
|
805 |
+
if name is not None:
|
806 |
+
self._declare(key, tp)
|
807 |
+
else:
|
808 |
+
if kind == 'enum' and type.values is not None:
|
809 |
+
raise NotImplementedError(
|
810 |
+
"enum %s: the '{}' declaration should appear on the first "
|
811 |
+
"time the enum is mentioned, not later" % explicit_name)
|
812 |
+
if not tp.forcename:
|
813 |
+
tp.force_the_name(force_name)
|
814 |
+
if tp.forcename and '$' in tp.name:
|
815 |
+
self._declare('anonymous %s' % tp.forcename, tp)
|
816 |
+
#
|
817 |
+
self._structnode2type[type] = tp
|
818 |
+
#
|
819 |
+
# enums: done here
|
820 |
+
if kind == 'enum':
|
821 |
+
return tp
|
822 |
+
#
|
823 |
+
# is there a 'type.decls'? If yes, then this is the place in the
|
824 |
+
# C sources that declare the fields. If no, then just return the
|
825 |
+
# existing type, possibly still incomplete.
|
826 |
+
if type.decls is None:
|
827 |
+
return tp
|
828 |
+
#
|
829 |
+
if tp.fldnames is not None:
|
830 |
+
raise CDefError("duplicate declaration of struct %s" % name)
|
831 |
+
fldnames = []
|
832 |
+
fldtypes = []
|
833 |
+
fldbitsize = []
|
834 |
+
fldquals = []
|
835 |
+
for decl in type.decls:
|
836 |
+
if (isinstance(decl.type, pycparser.c_ast.IdentifierType) and
|
837 |
+
''.join(decl.type.names) == '__dotdotdot__'):
|
838 |
+
# XXX pycparser is inconsistent: 'names' should be a list
|
839 |
+
# of strings, but is sometimes just one string. Use
|
840 |
+
# str.join() as a way to cope with both.
|
841 |
+
self._make_partial(tp, nested)
|
842 |
+
continue
|
843 |
+
if decl.bitsize is None:
|
844 |
+
bitsize = -1
|
845 |
+
else:
|
846 |
+
bitsize = self._parse_constant(decl.bitsize)
|
847 |
+
self._partial_length = False
|
848 |
+
type, fqual = self._get_type_and_quals(decl.type,
|
849 |
+
partial_length_ok=True)
|
850 |
+
if self._partial_length:
|
851 |
+
self._make_partial(tp, nested)
|
852 |
+
if isinstance(type, model.StructType) and type.partial:
|
853 |
+
self._make_partial(tp, nested)
|
854 |
+
fldnames.append(decl.name or '')
|
855 |
+
fldtypes.append(type)
|
856 |
+
fldbitsize.append(bitsize)
|
857 |
+
fldquals.append(fqual)
|
858 |
+
tp.fldnames = tuple(fldnames)
|
859 |
+
tp.fldtypes = tuple(fldtypes)
|
860 |
+
tp.fldbitsize = tuple(fldbitsize)
|
861 |
+
tp.fldquals = tuple(fldquals)
|
862 |
+
if fldbitsize != [-1] * len(fldbitsize):
|
863 |
+
if isinstance(tp, model.StructType) and tp.partial:
|
864 |
+
raise NotImplementedError("%s: using both bitfields and '...;'"
|
865 |
+
% (tp,))
|
866 |
+
tp.packed = self._options.get('packed')
|
867 |
+
if tp.completed: # must be re-completed: it is not opaque any more
|
868 |
+
tp.completed = 0
|
869 |
+
self._recomplete.append(tp)
|
870 |
+
return tp
|
871 |
+
|
872 |
+
def _make_partial(self, tp, nested):
|
873 |
+
if not isinstance(tp, model.StructOrUnion):
|
874 |
+
raise CDefError("%s cannot be partial" % (tp,))
|
875 |
+
if not tp.has_c_name() and not nested:
|
876 |
+
raise NotImplementedError("%s is partial but has no C name" %(tp,))
|
877 |
+
tp.partial = True
|
878 |
+
|
879 |
+
def _parse_constant(self, exprnode, partial_length_ok=False):
|
880 |
+
# for now, limited to expressions that are an immediate number
|
881 |
+
# or positive/negative number
|
882 |
+
if isinstance(exprnode, pycparser.c_ast.Constant):
|
883 |
+
s = exprnode.value
|
884 |
+
if '0' <= s[0] <= '9':
|
885 |
+
s = s.rstrip('uUlL')
|
886 |
+
try:
|
887 |
+
if s.startswith('0'):
|
888 |
+
return int(s, 8)
|
889 |
+
else:
|
890 |
+
return int(s, 10)
|
891 |
+
except ValueError:
|
892 |
+
if len(s) > 1:
|
893 |
+
if s.lower()[0:2] == '0x':
|
894 |
+
return int(s, 16)
|
895 |
+
elif s.lower()[0:2] == '0b':
|
896 |
+
return int(s, 2)
|
897 |
+
raise CDefError("invalid constant %r" % (s,))
|
898 |
+
elif s[0] == "'" and s[-1] == "'" and (
|
899 |
+
len(s) == 3 or (len(s) == 4 and s[1] == "\\")):
|
900 |
+
return ord(s[-2])
|
901 |
+
else:
|
902 |
+
raise CDefError("invalid constant %r" % (s,))
|
903 |
+
#
|
904 |
+
if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
|
905 |
+
exprnode.op == '+'):
|
906 |
+
return self._parse_constant(exprnode.expr)
|
907 |
+
#
|
908 |
+
if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
|
909 |
+
exprnode.op == '-'):
|
910 |
+
return -self._parse_constant(exprnode.expr)
|
911 |
+
# load previously defined int constant
|
912 |
+
if (isinstance(exprnode, pycparser.c_ast.ID) and
|
913 |
+
exprnode.name in self._int_constants):
|
914 |
+
return self._int_constants[exprnode.name]
|
915 |
+
#
|
916 |
+
if (isinstance(exprnode, pycparser.c_ast.ID) and
|
917 |
+
exprnode.name == '__dotdotdotarray__'):
|
918 |
+
if partial_length_ok:
|
919 |
+
self._partial_length = True
|
920 |
+
return '...'
|
921 |
+
raise FFIError(":%d: unsupported '[...]' here, cannot derive "
|
922 |
+
"the actual array length in this context"
|
923 |
+
% exprnode.coord.line)
|
924 |
+
#
|
925 |
+
if isinstance(exprnode, pycparser.c_ast.BinaryOp):
|
926 |
+
left = self._parse_constant(exprnode.left)
|
927 |
+
right = self._parse_constant(exprnode.right)
|
928 |
+
if exprnode.op == '+':
|
929 |
+
return left + right
|
930 |
+
elif exprnode.op == '-':
|
931 |
+
return left - right
|
932 |
+
elif exprnode.op == '*':
|
933 |
+
return left * right
|
934 |
+
elif exprnode.op == '/':
|
935 |
+
return self._c_div(left, right)
|
936 |
+
elif exprnode.op == '%':
|
937 |
+
return left - self._c_div(left, right) * right
|
938 |
+
elif exprnode.op == '<<':
|
939 |
+
return left << right
|
940 |
+
elif exprnode.op == '>>':
|
941 |
+
return left >> right
|
942 |
+
elif exprnode.op == '&':
|
943 |
+
return left & right
|
944 |
+
elif exprnode.op == '|':
|
945 |
+
return left | right
|
946 |
+
elif exprnode.op == '^':
|
947 |
+
return left ^ right
|
948 |
+
#
|
949 |
+
raise FFIError(":%d: unsupported expression: expected a "
|
950 |
+
"simple numeric constant" % exprnode.coord.line)
|
951 |
+
|
952 |
+
def _c_div(self, a, b):
|
953 |
+
result = a // b
|
954 |
+
if ((a < 0) ^ (b < 0)) and (a % b) != 0:
|
955 |
+
result += 1
|
956 |
+
return result
|
957 |
+
|
958 |
+
def _build_enum_type(self, explicit_name, decls):
|
959 |
+
if decls is not None:
|
960 |
+
partial = False
|
961 |
+
enumerators = []
|
962 |
+
enumvalues = []
|
963 |
+
nextenumvalue = 0
|
964 |
+
for enum in decls.enumerators:
|
965 |
+
if _r_enum_dotdotdot.match(enum.name):
|
966 |
+
partial = True
|
967 |
+
continue
|
968 |
+
if enum.value is not None:
|
969 |
+
nextenumvalue = self._parse_constant(enum.value)
|
970 |
+
enumerators.append(enum.name)
|
971 |
+
enumvalues.append(nextenumvalue)
|
972 |
+
self._add_constants(enum.name, nextenumvalue)
|
973 |
+
nextenumvalue += 1
|
974 |
+
enumerators = tuple(enumerators)
|
975 |
+
enumvalues = tuple(enumvalues)
|
976 |
+
tp = model.EnumType(explicit_name, enumerators, enumvalues)
|
977 |
+
tp.partial = partial
|
978 |
+
else: # opaque enum
|
979 |
+
tp = model.EnumType(explicit_name, (), ())
|
980 |
+
return tp
|
981 |
+
|
982 |
+
def include(self, other):
|
983 |
+
for name, (tp, quals) in other._declarations.items():
|
984 |
+
if name.startswith('anonymous $enum_$'):
|
985 |
+
continue # fix for test_anonymous_enum_include
|
986 |
+
kind = name.split(' ', 1)[0]
|
987 |
+
if kind in ('struct', 'union', 'enum', 'anonymous', 'typedef'):
|
988 |
+
self._declare(name, tp, included=True, quals=quals)
|
989 |
+
for k, v in other._int_constants.items():
|
990 |
+
self._add_constants(k, v)
|
991 |
+
|
992 |
+
def _get_unknown_type(self, decl):
|
993 |
+
typenames = decl.type.type.names
|
994 |
+
if typenames == ['__dotdotdot__']:
|
995 |
+
return model.unknown_type(decl.name)
|
996 |
+
|
997 |
+
if typenames == ['__dotdotdotint__']:
|
998 |
+
if self._uses_new_feature is None:
|
999 |
+
self._uses_new_feature = "'typedef int... %s'" % decl.name
|
1000 |
+
return model.UnknownIntegerType(decl.name)
|
1001 |
+
|
1002 |
+
if typenames == ['__dotdotdotfloat__']:
|
1003 |
+
# note: not for 'long double' so far
|
1004 |
+
if self._uses_new_feature is None:
|
1005 |
+
self._uses_new_feature = "'typedef float... %s'" % decl.name
|
1006 |
+
return model.UnknownFloatType(decl.name)
|
1007 |
+
|
1008 |
+
raise FFIError(':%d: unsupported usage of "..." in typedef'
|
1009 |
+
% decl.coord.line)
|
1010 |
+
|
1011 |
+
def _get_unknown_ptr_type(self, decl):
|
1012 |
+
if decl.type.type.type.names == ['__dotdotdot__']:
|
1013 |
+
return model.unknown_ptr_type(decl.name)
|
1014 |
+
raise FFIError(':%d: unsupported usage of "..." in typedef'
|
1015 |
+
% decl.coord.line)
|
cffi/error.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
class FFIError(Exception):
|
3 |
+
__module__ = 'cffi'
|
4 |
+
|
5 |
+
class CDefError(Exception):
|
6 |
+
__module__ = 'cffi'
|
7 |
+
def __str__(self):
|
8 |
+
try:
|
9 |
+
current_decl = self.args[1]
|
10 |
+
filename = current_decl.coord.file
|
11 |
+
linenum = current_decl.coord.line
|
12 |
+
prefix = '%s:%d: ' % (filename, linenum)
|
13 |
+
except (AttributeError, TypeError, IndexError):
|
14 |
+
prefix = ''
|
15 |
+
return '%s%s' % (prefix, self.args[0])
|
16 |
+
|
17 |
+
class VerificationError(Exception):
|
18 |
+
""" An error raised when verification fails
|
19 |
+
"""
|
20 |
+
__module__ = 'cffi'
|
21 |
+
|
22 |
+
class VerificationMissing(Exception):
|
23 |
+
""" An error raised when incomplete structures are passed into
|
24 |
+
cdef, but no verification has been done
|
25 |
+
"""
|
26 |
+
__module__ = 'cffi'
|
27 |
+
|
28 |
+
class PkgConfigError(Exception):
|
29 |
+
""" An error raised for missing modules in pkg-config
|
30 |
+
"""
|
31 |
+
__module__ = 'cffi'
|
cffi/ffiplatform.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys, os
|
2 |
+
from .error import VerificationError
|
3 |
+
|
4 |
+
|
5 |
+
LIST_OF_FILE_NAMES = ['sources', 'include_dirs', 'library_dirs',
|
6 |
+
'extra_objects', 'depends']
|
7 |
+
|
8 |
+
def get_extension(srcfilename, modname, sources=(), **kwds):
|
9 |
+
from cffi._shimmed_dist_utils import Extension
|
10 |
+
allsources = [srcfilename]
|
11 |
+
for src in sources:
|
12 |
+
allsources.append(os.path.normpath(src))
|
13 |
+
return Extension(name=modname, sources=allsources, **kwds)
|
14 |
+
|
15 |
+
def compile(tmpdir, ext, compiler_verbose=0, debug=None):
|
16 |
+
"""Compile a C extension module using distutils."""
|
17 |
+
|
18 |
+
saved_environ = os.environ.copy()
|
19 |
+
try:
|
20 |
+
outputfilename = _build(tmpdir, ext, compiler_verbose, debug)
|
21 |
+
outputfilename = os.path.abspath(outputfilename)
|
22 |
+
finally:
|
23 |
+
# workaround for a distutils bugs where some env vars can
|
24 |
+
# become longer and longer every time it is used
|
25 |
+
for key, value in saved_environ.items():
|
26 |
+
if os.environ.get(key) != value:
|
27 |
+
os.environ[key] = value
|
28 |
+
return outputfilename
|
29 |
+
|
30 |
+
def _build(tmpdir, ext, compiler_verbose=0, debug=None):
|
31 |
+
# XXX compact but horrible :-(
|
32 |
+
from cffi._shimmed_dist_utils import Distribution, CompileError, LinkError, set_threshold, set_verbosity
|
33 |
+
|
34 |
+
dist = Distribution({'ext_modules': [ext]})
|
35 |
+
dist.parse_config_files()
|
36 |
+
options = dist.get_option_dict('build_ext')
|
37 |
+
if debug is None:
|
38 |
+
debug = sys.flags.debug
|
39 |
+
options['debug'] = ('ffiplatform', debug)
|
40 |
+
options['force'] = ('ffiplatform', True)
|
41 |
+
options['build_lib'] = ('ffiplatform', tmpdir)
|
42 |
+
options['build_temp'] = ('ffiplatform', tmpdir)
|
43 |
+
#
|
44 |
+
try:
|
45 |
+
old_level = set_threshold(0) or 0
|
46 |
+
try:
|
47 |
+
set_verbosity(compiler_verbose)
|
48 |
+
dist.run_command('build_ext')
|
49 |
+
cmd_obj = dist.get_command_obj('build_ext')
|
50 |
+
[soname] = cmd_obj.get_outputs()
|
51 |
+
finally:
|
52 |
+
set_threshold(old_level)
|
53 |
+
except (CompileError, LinkError) as e:
|
54 |
+
raise VerificationError('%s: %s' % (e.__class__.__name__, e))
|
55 |
+
#
|
56 |
+
return soname
|
57 |
+
|
58 |
+
try:
|
59 |
+
from os.path import samefile
|
60 |
+
except ImportError:
|
61 |
+
def samefile(f1, f2):
|
62 |
+
return os.path.abspath(f1) == os.path.abspath(f2)
|
63 |
+
|
64 |
+
def maybe_relative_path(path):
|
65 |
+
if not os.path.isabs(path):
|
66 |
+
return path # already relative
|
67 |
+
dir = path
|
68 |
+
names = []
|
69 |
+
while True:
|
70 |
+
prevdir = dir
|
71 |
+
dir, name = os.path.split(prevdir)
|
72 |
+
if dir == prevdir or not dir:
|
73 |
+
return path # failed to make it relative
|
74 |
+
names.append(name)
|
75 |
+
try:
|
76 |
+
if samefile(dir, os.curdir):
|
77 |
+
names.reverse()
|
78 |
+
return os.path.join(*names)
|
79 |
+
except OSError:
|
80 |
+
pass
|
81 |
+
|
82 |
+
# ____________________________________________________________
|
83 |
+
|
84 |
+
try:
|
85 |
+
int_or_long = (int, long)
|
86 |
+
import cStringIO
|
87 |
+
except NameError:
|
88 |
+
int_or_long = int # Python 3
|
89 |
+
import io as cStringIO
|
90 |
+
|
91 |
+
def _flatten(x, f):
|
92 |
+
if isinstance(x, str):
|
93 |
+
f.write('%ds%s' % (len(x), x))
|
94 |
+
elif isinstance(x, dict):
|
95 |
+
keys = sorted(x.keys())
|
96 |
+
f.write('%dd' % len(keys))
|
97 |
+
for key in keys:
|
98 |
+
_flatten(key, f)
|
99 |
+
_flatten(x[key], f)
|
100 |
+
elif isinstance(x, (list, tuple)):
|
101 |
+
f.write('%dl' % len(x))
|
102 |
+
for value in x:
|
103 |
+
_flatten(value, f)
|
104 |
+
elif isinstance(x, int_or_long):
|
105 |
+
f.write('%di' % (x,))
|
106 |
+
else:
|
107 |
+
raise TypeError(
|
108 |
+
"the keywords to verify() contains unsupported object %r" % (x,))
|
109 |
+
|
110 |
+
def flatten(x):
|
111 |
+
f = cStringIO.StringIO()
|
112 |
+
_flatten(x, f)
|
113 |
+
return f.getvalue()
|
cffi/lock.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
|
3 |
+
if sys.version_info < (3,):
|
4 |
+
try:
|
5 |
+
from thread import allocate_lock
|
6 |
+
except ImportError:
|
7 |
+
from dummy_thread import allocate_lock
|
8 |
+
else:
|
9 |
+
try:
|
10 |
+
from _thread import allocate_lock
|
11 |
+
except ImportError:
|
12 |
+
from _dummy_thread import allocate_lock
|
13 |
+
|
14 |
+
|
15 |
+
##import sys
|
16 |
+
##l1 = allocate_lock
|
17 |
+
|
18 |
+
##class allocate_lock(object):
|
19 |
+
## def __init__(self):
|
20 |
+
## self._real = l1()
|
21 |
+
## def __enter__(self):
|
22 |
+
## for i in range(4, 0, -1):
|
23 |
+
## print sys._getframe(i).f_code
|
24 |
+
## print
|
25 |
+
## return self._real.__enter__()
|
26 |
+
## def __exit__(self, *args):
|
27 |
+
## return self._real.__exit__(*args)
|
28 |
+
## def acquire(self, f):
|
29 |
+
## assert f is False
|
30 |
+
## return self._real.acquire(f)
|
cffi/model.py
ADDED
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import types
|
2 |
+
import weakref
|
3 |
+
|
4 |
+
from .lock import allocate_lock
|
5 |
+
from .error import CDefError, VerificationError, VerificationMissing
|
6 |
+
|
7 |
+
# type qualifiers
|
8 |
+
Q_CONST = 0x01
|
9 |
+
Q_RESTRICT = 0x02
|
10 |
+
Q_VOLATILE = 0x04
|
11 |
+
|
12 |
+
def qualify(quals, replace_with):
|
13 |
+
if quals & Q_CONST:
|
14 |
+
replace_with = ' const ' + replace_with.lstrip()
|
15 |
+
if quals & Q_VOLATILE:
|
16 |
+
replace_with = ' volatile ' + replace_with.lstrip()
|
17 |
+
if quals & Q_RESTRICT:
|
18 |
+
# It seems that __restrict is supported by gcc and msvc.
|
19 |
+
# If you hit some different compiler, add a #define in
|
20 |
+
# _cffi_include.h for it (and in its copies, documented there)
|
21 |
+
replace_with = ' __restrict ' + replace_with.lstrip()
|
22 |
+
return replace_with
|
23 |
+
|
24 |
+
|
25 |
+
class BaseTypeByIdentity(object):
|
26 |
+
is_array_type = False
|
27 |
+
is_raw_function = False
|
28 |
+
|
29 |
+
def get_c_name(self, replace_with='', context='a C file', quals=0):
|
30 |
+
result = self.c_name_with_marker
|
31 |
+
assert result.count('&') == 1
|
32 |
+
# some logic duplication with ffi.getctype()... :-(
|
33 |
+
replace_with = replace_with.strip()
|
34 |
+
if replace_with:
|
35 |
+
if replace_with.startswith('*') and '&[' in result:
|
36 |
+
replace_with = '(%s)' % replace_with
|
37 |
+
elif not replace_with[0] in '[(':
|
38 |
+
replace_with = ' ' + replace_with
|
39 |
+
replace_with = qualify(quals, replace_with)
|
40 |
+
result = result.replace('&', replace_with)
|
41 |
+
if '$' in result:
|
42 |
+
raise VerificationError(
|
43 |
+
"cannot generate '%s' in %s: unknown type name"
|
44 |
+
% (self._get_c_name(), context))
|
45 |
+
return result
|
46 |
+
|
47 |
+
def _get_c_name(self):
|
48 |
+
return self.c_name_with_marker.replace('&', '')
|
49 |
+
|
50 |
+
def has_c_name(self):
|
51 |
+
return '$' not in self._get_c_name()
|
52 |
+
|
53 |
+
def is_integer_type(self):
|
54 |
+
return False
|
55 |
+
|
56 |
+
def get_cached_btype(self, ffi, finishlist, can_delay=False):
|
57 |
+
try:
|
58 |
+
BType = ffi._cached_btypes[self]
|
59 |
+
except KeyError:
|
60 |
+
BType = self.build_backend_type(ffi, finishlist)
|
61 |
+
BType2 = ffi._cached_btypes.setdefault(self, BType)
|
62 |
+
assert BType2 is BType
|
63 |
+
return BType
|
64 |
+
|
65 |
+
def __repr__(self):
|
66 |
+
return '<%s>' % (self._get_c_name(),)
|
67 |
+
|
68 |
+
def _get_items(self):
|
69 |
+
return [(name, getattr(self, name)) for name in self._attrs_]
|
70 |
+
|
71 |
+
|
72 |
+
class BaseType(BaseTypeByIdentity):
|
73 |
+
|
74 |
+
def __eq__(self, other):
|
75 |
+
return (self.__class__ == other.__class__ and
|
76 |
+
self._get_items() == other._get_items())
|
77 |
+
|
78 |
+
def __ne__(self, other):
|
79 |
+
return not self == other
|
80 |
+
|
81 |
+
def __hash__(self):
|
82 |
+
return hash((self.__class__, tuple(self._get_items())))
|
83 |
+
|
84 |
+
|
85 |
+
class VoidType(BaseType):
|
86 |
+
_attrs_ = ()
|
87 |
+
|
88 |
+
def __init__(self):
|
89 |
+
self.c_name_with_marker = 'void&'
|
90 |
+
|
91 |
+
def build_backend_type(self, ffi, finishlist):
|
92 |
+
return global_cache(self, ffi, 'new_void_type')
|
93 |
+
|
94 |
+
void_type = VoidType()
|
95 |
+
|
96 |
+
|
97 |
+
class BasePrimitiveType(BaseType):
|
98 |
+
def is_complex_type(self):
|
99 |
+
return False
|
100 |
+
|
101 |
+
|
102 |
+
class PrimitiveType(BasePrimitiveType):
|
103 |
+
_attrs_ = ('name',)
|
104 |
+
|
105 |
+
ALL_PRIMITIVE_TYPES = {
|
106 |
+
'char': 'c',
|
107 |
+
'short': 'i',
|
108 |
+
'int': 'i',
|
109 |
+
'long': 'i',
|
110 |
+
'long long': 'i',
|
111 |
+
'signed char': 'i',
|
112 |
+
'unsigned char': 'i',
|
113 |
+
'unsigned short': 'i',
|
114 |
+
'unsigned int': 'i',
|
115 |
+
'unsigned long': 'i',
|
116 |
+
'unsigned long long': 'i',
|
117 |
+
'float': 'f',
|
118 |
+
'double': 'f',
|
119 |
+
'long double': 'f',
|
120 |
+
'_cffi_float_complex_t': 'j',
|
121 |
+
'_cffi_double_complex_t': 'j',
|
122 |
+
'_Bool': 'i',
|
123 |
+
# the following types are not primitive in the C sense
|
124 |
+
'wchar_t': 'c',
|
125 |
+
'char16_t': 'c',
|
126 |
+
'char32_t': 'c',
|
127 |
+
'int8_t': 'i',
|
128 |
+
'uint8_t': 'i',
|
129 |
+
'int16_t': 'i',
|
130 |
+
'uint16_t': 'i',
|
131 |
+
'int32_t': 'i',
|
132 |
+
'uint32_t': 'i',
|
133 |
+
'int64_t': 'i',
|
134 |
+
'uint64_t': 'i',
|
135 |
+
'int_least8_t': 'i',
|
136 |
+
'uint_least8_t': 'i',
|
137 |
+
'int_least16_t': 'i',
|
138 |
+
'uint_least16_t': 'i',
|
139 |
+
'int_least32_t': 'i',
|
140 |
+
'uint_least32_t': 'i',
|
141 |
+
'int_least64_t': 'i',
|
142 |
+
'uint_least64_t': 'i',
|
143 |
+
'int_fast8_t': 'i',
|
144 |
+
'uint_fast8_t': 'i',
|
145 |
+
'int_fast16_t': 'i',
|
146 |
+
'uint_fast16_t': 'i',
|
147 |
+
'int_fast32_t': 'i',
|
148 |
+
'uint_fast32_t': 'i',
|
149 |
+
'int_fast64_t': 'i',
|
150 |
+
'uint_fast64_t': 'i',
|
151 |
+
'intptr_t': 'i',
|
152 |
+
'uintptr_t': 'i',
|
153 |
+
'intmax_t': 'i',
|
154 |
+
'uintmax_t': 'i',
|
155 |
+
'ptrdiff_t': 'i',
|
156 |
+
'size_t': 'i',
|
157 |
+
'ssize_t': 'i',
|
158 |
+
}
|
159 |
+
|
160 |
+
def __init__(self, name):
|
161 |
+
assert name in self.ALL_PRIMITIVE_TYPES
|
162 |
+
self.name = name
|
163 |
+
self.c_name_with_marker = name + '&'
|
164 |
+
|
165 |
+
def is_char_type(self):
|
166 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'c'
|
167 |
+
def is_integer_type(self):
|
168 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'i'
|
169 |
+
def is_float_type(self):
|
170 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'f'
|
171 |
+
def is_complex_type(self):
|
172 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'j'
|
173 |
+
|
174 |
+
def build_backend_type(self, ffi, finishlist):
|
175 |
+
return global_cache(self, ffi, 'new_primitive_type', self.name)
|
176 |
+
|
177 |
+
|
178 |
+
class UnknownIntegerType(BasePrimitiveType):
|
179 |
+
_attrs_ = ('name',)
|
180 |
+
|
181 |
+
def __init__(self, name):
|
182 |
+
self.name = name
|
183 |
+
self.c_name_with_marker = name + '&'
|
184 |
+
|
185 |
+
def is_integer_type(self):
|
186 |
+
return True
|
187 |
+
|
188 |
+
def build_backend_type(self, ffi, finishlist):
|
189 |
+
raise NotImplementedError("integer type '%s' can only be used after "
|
190 |
+
"compilation" % self.name)
|
191 |
+
|
192 |
+
class UnknownFloatType(BasePrimitiveType):
|
193 |
+
_attrs_ = ('name', )
|
194 |
+
|
195 |
+
def __init__(self, name):
|
196 |
+
self.name = name
|
197 |
+
self.c_name_with_marker = name + '&'
|
198 |
+
|
199 |
+
def build_backend_type(self, ffi, finishlist):
|
200 |
+
raise NotImplementedError("float type '%s' can only be used after "
|
201 |
+
"compilation" % self.name)
|
202 |
+
|
203 |
+
|
204 |
+
class BaseFunctionType(BaseType):
|
205 |
+
_attrs_ = ('args', 'result', 'ellipsis', 'abi')
|
206 |
+
|
207 |
+
def __init__(self, args, result, ellipsis, abi=None):
|
208 |
+
self.args = args
|
209 |
+
self.result = result
|
210 |
+
self.ellipsis = ellipsis
|
211 |
+
self.abi = abi
|
212 |
+
#
|
213 |
+
reprargs = [arg._get_c_name() for arg in self.args]
|
214 |
+
if self.ellipsis:
|
215 |
+
reprargs.append('...')
|
216 |
+
reprargs = reprargs or ['void']
|
217 |
+
replace_with = self._base_pattern % (', '.join(reprargs),)
|
218 |
+
if abi is not None:
|
219 |
+
replace_with = replace_with[:1] + abi + ' ' + replace_with[1:]
|
220 |
+
self.c_name_with_marker = (
|
221 |
+
self.result.c_name_with_marker.replace('&', replace_with))
|
222 |
+
|
223 |
+
|
224 |
+
class RawFunctionType(BaseFunctionType):
|
225 |
+
# Corresponds to a C type like 'int(int)', which is the C type of
|
226 |
+
# a function, but not a pointer-to-function. The backend has no
|
227 |
+
# notion of such a type; it's used temporarily by parsing.
|
228 |
+
_base_pattern = '(&)(%s)'
|
229 |
+
is_raw_function = True
|
230 |
+
|
231 |
+
def build_backend_type(self, ffi, finishlist):
|
232 |
+
raise CDefError("cannot render the type %r: it is a function "
|
233 |
+
"type, not a pointer-to-function type" % (self,))
|
234 |
+
|
235 |
+
def as_function_pointer(self):
|
236 |
+
return FunctionPtrType(self.args, self.result, self.ellipsis, self.abi)
|
237 |
+
|
238 |
+
|
239 |
+
class FunctionPtrType(BaseFunctionType):
|
240 |
+
_base_pattern = '(*&)(%s)'
|
241 |
+
|
242 |
+
def build_backend_type(self, ffi, finishlist):
|
243 |
+
result = self.result.get_cached_btype(ffi, finishlist)
|
244 |
+
args = []
|
245 |
+
for tp in self.args:
|
246 |
+
args.append(tp.get_cached_btype(ffi, finishlist))
|
247 |
+
abi_args = ()
|
248 |
+
if self.abi == "__stdcall":
|
249 |
+
if not self.ellipsis: # __stdcall ignored for variadic funcs
|
250 |
+
try:
|
251 |
+
abi_args = (ffi._backend.FFI_STDCALL,)
|
252 |
+
except AttributeError:
|
253 |
+
pass
|
254 |
+
return global_cache(self, ffi, 'new_function_type',
|
255 |
+
tuple(args), result, self.ellipsis, *abi_args)
|
256 |
+
|
257 |
+
def as_raw_function(self):
|
258 |
+
return RawFunctionType(self.args, self.result, self.ellipsis, self.abi)
|
259 |
+
|
260 |
+
|
261 |
+
class PointerType(BaseType):
|
262 |
+
_attrs_ = ('totype', 'quals')
|
263 |
+
|
264 |
+
def __init__(self, totype, quals=0):
|
265 |
+
self.totype = totype
|
266 |
+
self.quals = quals
|
267 |
+
extra = " *&"
|
268 |
+
if totype.is_array_type:
|
269 |
+
extra = "(%s)" % (extra.lstrip(),)
|
270 |
+
extra = qualify(quals, extra)
|
271 |
+
self.c_name_with_marker = totype.c_name_with_marker.replace('&', extra)
|
272 |
+
|
273 |
+
def build_backend_type(self, ffi, finishlist):
|
274 |
+
BItem = self.totype.get_cached_btype(ffi, finishlist, can_delay=True)
|
275 |
+
return global_cache(self, ffi, 'new_pointer_type', BItem)
|
276 |
+
|
277 |
+
voidp_type = PointerType(void_type)
|
278 |
+
|
279 |
+
def ConstPointerType(totype):
|
280 |
+
return PointerType(totype, Q_CONST)
|
281 |
+
|
282 |
+
const_voidp_type = ConstPointerType(void_type)
|
283 |
+
|
284 |
+
|
285 |
+
class NamedPointerType(PointerType):
|
286 |
+
_attrs_ = ('totype', 'name')
|
287 |
+
|
288 |
+
def __init__(self, totype, name, quals=0):
|
289 |
+
PointerType.__init__(self, totype, quals)
|
290 |
+
self.name = name
|
291 |
+
self.c_name_with_marker = name + '&'
|
292 |
+
|
293 |
+
|
294 |
+
class ArrayType(BaseType):
|
295 |
+
_attrs_ = ('item', 'length')
|
296 |
+
is_array_type = True
|
297 |
+
|
298 |
+
def __init__(self, item, length):
|
299 |
+
self.item = item
|
300 |
+
self.length = length
|
301 |
+
#
|
302 |
+
if length is None:
|
303 |
+
brackets = '&[]'
|
304 |
+
elif length == '...':
|
305 |
+
brackets = '&[/*...*/]'
|
306 |
+
else:
|
307 |
+
brackets = '&[%s]' % length
|
308 |
+
self.c_name_with_marker = (
|
309 |
+
self.item.c_name_with_marker.replace('&', brackets))
|
310 |
+
|
311 |
+
def length_is_unknown(self):
|
312 |
+
return isinstance(self.length, str)
|
313 |
+
|
314 |
+
def resolve_length(self, newlength):
|
315 |
+
return ArrayType(self.item, newlength)
|
316 |
+
|
317 |
+
def build_backend_type(self, ffi, finishlist):
|
318 |
+
if self.length_is_unknown():
|
319 |
+
raise CDefError("cannot render the type %r: unknown length" %
|
320 |
+
(self,))
|
321 |
+
self.item.get_cached_btype(ffi, finishlist) # force the item BType
|
322 |
+
BPtrItem = PointerType(self.item).get_cached_btype(ffi, finishlist)
|
323 |
+
return global_cache(self, ffi, 'new_array_type', BPtrItem, self.length)
|
324 |
+
|
325 |
+
char_array_type = ArrayType(PrimitiveType('char'), None)
|
326 |
+
|
327 |
+
|
328 |
+
class StructOrUnionOrEnum(BaseTypeByIdentity):
|
329 |
+
_attrs_ = ('name',)
|
330 |
+
forcename = None
|
331 |
+
|
332 |
+
def build_c_name_with_marker(self):
|
333 |
+
name = self.forcename or '%s %s' % (self.kind, self.name)
|
334 |
+
self.c_name_with_marker = name + '&'
|
335 |
+
|
336 |
+
def force_the_name(self, forcename):
|
337 |
+
self.forcename = forcename
|
338 |
+
self.build_c_name_with_marker()
|
339 |
+
|
340 |
+
def get_official_name(self):
|
341 |
+
assert self.c_name_with_marker.endswith('&')
|
342 |
+
return self.c_name_with_marker[:-1]
|
343 |
+
|
344 |
+
|
345 |
+
class StructOrUnion(StructOrUnionOrEnum):
|
346 |
+
fixedlayout = None
|
347 |
+
completed = 0
|
348 |
+
partial = False
|
349 |
+
packed = 0
|
350 |
+
|
351 |
+
def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None):
|
352 |
+
self.name = name
|
353 |
+
self.fldnames = fldnames
|
354 |
+
self.fldtypes = fldtypes
|
355 |
+
self.fldbitsize = fldbitsize
|
356 |
+
self.fldquals = fldquals
|
357 |
+
self.build_c_name_with_marker()
|
358 |
+
|
359 |
+
def anonymous_struct_fields(self):
|
360 |
+
if self.fldtypes is not None:
|
361 |
+
for name, type in zip(self.fldnames, self.fldtypes):
|
362 |
+
if name == '' and isinstance(type, StructOrUnion):
|
363 |
+
yield type
|
364 |
+
|
365 |
+
def enumfields(self, expand_anonymous_struct_union=True):
|
366 |
+
fldquals = self.fldquals
|
367 |
+
if fldquals is None:
|
368 |
+
fldquals = (0,) * len(self.fldnames)
|
369 |
+
for name, type, bitsize, quals in zip(self.fldnames, self.fldtypes,
|
370 |
+
self.fldbitsize, fldquals):
|
371 |
+
if (name == '' and isinstance(type, StructOrUnion)
|
372 |
+
and expand_anonymous_struct_union):
|
373 |
+
# nested anonymous struct/union
|
374 |
+
for result in type.enumfields():
|
375 |
+
yield result
|
376 |
+
else:
|
377 |
+
yield (name, type, bitsize, quals)
|
378 |
+
|
379 |
+
def force_flatten(self):
|
380 |
+
# force the struct or union to have a declaration that lists
|
381 |
+
# directly all fields returned by enumfields(), flattening
|
382 |
+
# nested anonymous structs/unions.
|
383 |
+
names = []
|
384 |
+
types = []
|
385 |
+
bitsizes = []
|
386 |
+
fldquals = []
|
387 |
+
for name, type, bitsize, quals in self.enumfields():
|
388 |
+
names.append(name)
|
389 |
+
types.append(type)
|
390 |
+
bitsizes.append(bitsize)
|
391 |
+
fldquals.append(quals)
|
392 |
+
self.fldnames = tuple(names)
|
393 |
+
self.fldtypes = tuple(types)
|
394 |
+
self.fldbitsize = tuple(bitsizes)
|
395 |
+
self.fldquals = tuple(fldquals)
|
396 |
+
|
397 |
+
def get_cached_btype(self, ffi, finishlist, can_delay=False):
|
398 |
+
BType = StructOrUnionOrEnum.get_cached_btype(self, ffi, finishlist,
|
399 |
+
can_delay)
|
400 |
+
if not can_delay:
|
401 |
+
self.finish_backend_type(ffi, finishlist)
|
402 |
+
return BType
|
403 |
+
|
404 |
+
def finish_backend_type(self, ffi, finishlist):
|
405 |
+
if self.completed:
|
406 |
+
if self.completed != 2:
|
407 |
+
raise NotImplementedError("recursive structure declaration "
|
408 |
+
"for '%s'" % (self.name,))
|
409 |
+
return
|
410 |
+
BType = ffi._cached_btypes[self]
|
411 |
+
#
|
412 |
+
self.completed = 1
|
413 |
+
#
|
414 |
+
if self.fldtypes is None:
|
415 |
+
pass # not completing it: it's an opaque struct
|
416 |
+
#
|
417 |
+
elif self.fixedlayout is None:
|
418 |
+
fldtypes = [tp.get_cached_btype(ffi, finishlist)
|
419 |
+
for tp in self.fldtypes]
|
420 |
+
lst = list(zip(self.fldnames, fldtypes, self.fldbitsize))
|
421 |
+
extra_flags = ()
|
422 |
+
if self.packed:
|
423 |
+
if self.packed == 1:
|
424 |
+
extra_flags = (8,) # SF_PACKED
|
425 |
+
else:
|
426 |
+
extra_flags = (0, self.packed)
|
427 |
+
ffi._backend.complete_struct_or_union(BType, lst, self,
|
428 |
+
-1, -1, *extra_flags)
|
429 |
+
#
|
430 |
+
else:
|
431 |
+
fldtypes = []
|
432 |
+
fieldofs, fieldsize, totalsize, totalalignment = self.fixedlayout
|
433 |
+
for i in range(len(self.fldnames)):
|
434 |
+
fsize = fieldsize[i]
|
435 |
+
ftype = self.fldtypes[i]
|
436 |
+
#
|
437 |
+
if isinstance(ftype, ArrayType) and ftype.length_is_unknown():
|
438 |
+
# fix the length to match the total size
|
439 |
+
BItemType = ftype.item.get_cached_btype(ffi, finishlist)
|
440 |
+
nlen, nrest = divmod(fsize, ffi.sizeof(BItemType))
|
441 |
+
if nrest != 0:
|
442 |
+
self._verification_error(
|
443 |
+
"field '%s.%s' has a bogus size?" % (
|
444 |
+
self.name, self.fldnames[i] or '{}'))
|
445 |
+
ftype = ftype.resolve_length(nlen)
|
446 |
+
self.fldtypes = (self.fldtypes[:i] + (ftype,) +
|
447 |
+
self.fldtypes[i+1:])
|
448 |
+
#
|
449 |
+
BFieldType = ftype.get_cached_btype(ffi, finishlist)
|
450 |
+
if isinstance(ftype, ArrayType) and ftype.length is None:
|
451 |
+
assert fsize == 0
|
452 |
+
else:
|
453 |
+
bitemsize = ffi.sizeof(BFieldType)
|
454 |
+
if bitemsize != fsize:
|
455 |
+
self._verification_error(
|
456 |
+
"field '%s.%s' is declared as %d bytes, but is "
|
457 |
+
"really %d bytes" % (self.name,
|
458 |
+
self.fldnames[i] or '{}',
|
459 |
+
bitemsize, fsize))
|
460 |
+
fldtypes.append(BFieldType)
|
461 |
+
#
|
462 |
+
lst = list(zip(self.fldnames, fldtypes, self.fldbitsize, fieldofs))
|
463 |
+
ffi._backend.complete_struct_or_union(BType, lst, self,
|
464 |
+
totalsize, totalalignment)
|
465 |
+
self.completed = 2
|
466 |
+
|
467 |
+
def _verification_error(self, msg):
|
468 |
+
raise VerificationError(msg)
|
469 |
+
|
470 |
+
def check_not_partial(self):
|
471 |
+
if self.partial and self.fixedlayout is None:
|
472 |
+
raise VerificationMissing(self._get_c_name())
|
473 |
+
|
474 |
+
def build_backend_type(self, ffi, finishlist):
|
475 |
+
self.check_not_partial()
|
476 |
+
finishlist.append(self)
|
477 |
+
#
|
478 |
+
return global_cache(self, ffi, 'new_%s_type' % self.kind,
|
479 |
+
self.get_official_name(), key=self)
|
480 |
+
|
481 |
+
|
482 |
+
class StructType(StructOrUnion):
|
483 |
+
kind = 'struct'
|
484 |
+
|
485 |
+
|
486 |
+
class UnionType(StructOrUnion):
|
487 |
+
kind = 'union'
|
488 |
+
|
489 |
+
|
490 |
+
class EnumType(StructOrUnionOrEnum):
|
491 |
+
kind = 'enum'
|
492 |
+
partial = False
|
493 |
+
partial_resolved = False
|
494 |
+
|
495 |
+
def __init__(self, name, enumerators, enumvalues, baseinttype=None):
|
496 |
+
self.name = name
|
497 |
+
self.enumerators = enumerators
|
498 |
+
self.enumvalues = enumvalues
|
499 |
+
self.baseinttype = baseinttype
|
500 |
+
self.build_c_name_with_marker()
|
501 |
+
|
502 |
+
def force_the_name(self, forcename):
|
503 |
+
StructOrUnionOrEnum.force_the_name(self, forcename)
|
504 |
+
if self.forcename is None:
|
505 |
+
name = self.get_official_name()
|
506 |
+
self.forcename = '$' + name.replace(' ', '_')
|
507 |
+
|
508 |
+
def check_not_partial(self):
|
509 |
+
if self.partial and not self.partial_resolved:
|
510 |
+
raise VerificationMissing(self._get_c_name())
|
511 |
+
|
512 |
+
def build_backend_type(self, ffi, finishlist):
|
513 |
+
self.check_not_partial()
|
514 |
+
base_btype = self.build_baseinttype(ffi, finishlist)
|
515 |
+
return global_cache(self, ffi, 'new_enum_type',
|
516 |
+
self.get_official_name(),
|
517 |
+
self.enumerators, self.enumvalues,
|
518 |
+
base_btype, key=self)
|
519 |
+
|
520 |
+
def build_baseinttype(self, ffi, finishlist):
|
521 |
+
if self.baseinttype is not None:
|
522 |
+
return self.baseinttype.get_cached_btype(ffi, finishlist)
|
523 |
+
#
|
524 |
+
if self.enumvalues:
|
525 |
+
smallest_value = min(self.enumvalues)
|
526 |
+
largest_value = max(self.enumvalues)
|
527 |
+
else:
|
528 |
+
import warnings
|
529 |
+
try:
|
530 |
+
# XXX! The goal is to ensure that the warnings.warn()
|
531 |
+
# will not suppress the warning. We want to get it
|
532 |
+
# several times if we reach this point several times.
|
533 |
+
__warningregistry__.clear()
|
534 |
+
except NameError:
|
535 |
+
pass
|
536 |
+
warnings.warn("%r has no values explicitly defined; "
|
537 |
+
"guessing that it is equivalent to 'unsigned int'"
|
538 |
+
% self._get_c_name())
|
539 |
+
smallest_value = largest_value = 0
|
540 |
+
if smallest_value < 0: # needs a signed type
|
541 |
+
sign = 1
|
542 |
+
candidate1 = PrimitiveType("int")
|
543 |
+
candidate2 = PrimitiveType("long")
|
544 |
+
else:
|
545 |
+
sign = 0
|
546 |
+
candidate1 = PrimitiveType("unsigned int")
|
547 |
+
candidate2 = PrimitiveType("unsigned long")
|
548 |
+
btype1 = candidate1.get_cached_btype(ffi, finishlist)
|
549 |
+
btype2 = candidate2.get_cached_btype(ffi, finishlist)
|
550 |
+
size1 = ffi.sizeof(btype1)
|
551 |
+
size2 = ffi.sizeof(btype2)
|
552 |
+
if (smallest_value >= ((-1) << (8*size1-1)) and
|
553 |
+
largest_value < (1 << (8*size1-sign))):
|
554 |
+
return btype1
|
555 |
+
if (smallest_value >= ((-1) << (8*size2-1)) and
|
556 |
+
largest_value < (1 << (8*size2-sign))):
|
557 |
+
return btype2
|
558 |
+
raise CDefError("%s values don't all fit into either 'long' "
|
559 |
+
"or 'unsigned long'" % self._get_c_name())
|
560 |
+
|
561 |
+
def unknown_type(name, structname=None):
|
562 |
+
if structname is None:
|
563 |
+
structname = '$%s' % name
|
564 |
+
tp = StructType(structname, None, None, None)
|
565 |
+
tp.force_the_name(name)
|
566 |
+
tp.origin = "unknown_type"
|
567 |
+
return tp
|
568 |
+
|
569 |
+
def unknown_ptr_type(name, structname=None):
|
570 |
+
if structname is None:
|
571 |
+
structname = '$$%s' % name
|
572 |
+
tp = StructType(structname, None, None, None)
|
573 |
+
return NamedPointerType(tp, name)
|
574 |
+
|
575 |
+
|
576 |
+
global_lock = allocate_lock()
|
577 |
+
_typecache_cffi_backend = weakref.WeakValueDictionary()
|
578 |
+
|
579 |
+
def get_typecache(backend):
|
580 |
+
# returns _typecache_cffi_backend if backend is the _cffi_backend
|
581 |
+
# module, or type(backend).__typecache if backend is an instance of
|
582 |
+
# CTypesBackend (or some FakeBackend class during tests)
|
583 |
+
if isinstance(backend, types.ModuleType):
|
584 |
+
return _typecache_cffi_backend
|
585 |
+
with global_lock:
|
586 |
+
if not hasattr(type(backend), '__typecache'):
|
587 |
+
type(backend).__typecache = weakref.WeakValueDictionary()
|
588 |
+
return type(backend).__typecache
|
589 |
+
|
590 |
+
def global_cache(srctype, ffi, funcname, *args, **kwds):
|
591 |
+
key = kwds.pop('key', (funcname, args))
|
592 |
+
assert not kwds
|
593 |
+
try:
|
594 |
+
return ffi._typecache[key]
|
595 |
+
except KeyError:
|
596 |
+
pass
|
597 |
+
try:
|
598 |
+
res = getattr(ffi._backend, funcname)(*args)
|
599 |
+
except NotImplementedError as e:
|
600 |
+
raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e))
|
601 |
+
# note that setdefault() on WeakValueDictionary is not atomic
|
602 |
+
# and contains a rare bug (http://bugs.python.org/issue19542);
|
603 |
+
# we have to use a lock and do it ourselves
|
604 |
+
cache = ffi._typecache
|
605 |
+
with global_lock:
|
606 |
+
res1 = cache.get(key)
|
607 |
+
if res1 is None:
|
608 |
+
cache[key] = res
|
609 |
+
return res
|
610 |
+
else:
|
611 |
+
return res1
|
612 |
+
|
613 |
+
def pointer_cache(ffi, BType):
|
614 |
+
return global_cache('?', ffi, 'new_pointer_type', BType)
|
615 |
+
|
616 |
+
def attach_exception_info(e, name):
|
617 |
+
if e.args and type(e.args[0]) is str:
|
618 |
+
e.args = ('%s: %s' % (name, e.args[0]),) + e.args[1:]
|
cffi/parse_c_type.h
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
/* This part is from file 'cffi/parse_c_type.h'. It is copied at the
|
3 |
+
beginning of C sources generated by CFFI's ffi.set_source(). */
|
4 |
+
|
5 |
+
typedef void *_cffi_opcode_t;
|
6 |
+
|
7 |
+
#define _CFFI_OP(opcode, arg) (_cffi_opcode_t)(opcode | (((uintptr_t)(arg)) << 8))
|
8 |
+
#define _CFFI_GETOP(cffi_opcode) ((unsigned char)(uintptr_t)cffi_opcode)
|
9 |
+
#define _CFFI_GETARG(cffi_opcode) (((intptr_t)cffi_opcode) >> 8)
|
10 |
+
|
11 |
+
#define _CFFI_OP_PRIMITIVE 1
|
12 |
+
#define _CFFI_OP_POINTER 3
|
13 |
+
#define _CFFI_OP_ARRAY 5
|
14 |
+
#define _CFFI_OP_OPEN_ARRAY 7
|
15 |
+
#define _CFFI_OP_STRUCT_UNION 9
|
16 |
+
#define _CFFI_OP_ENUM 11
|
17 |
+
#define _CFFI_OP_FUNCTION 13
|
18 |
+
#define _CFFI_OP_FUNCTION_END 15
|
19 |
+
#define _CFFI_OP_NOOP 17
|
20 |
+
#define _CFFI_OP_BITFIELD 19
|
21 |
+
#define _CFFI_OP_TYPENAME 21
|
22 |
+
#define _CFFI_OP_CPYTHON_BLTN_V 23 // varargs
|
23 |
+
#define _CFFI_OP_CPYTHON_BLTN_N 25 // noargs
|
24 |
+
#define _CFFI_OP_CPYTHON_BLTN_O 27 // O (i.e. a single arg)
|
25 |
+
#define _CFFI_OP_CONSTANT 29
|
26 |
+
#define _CFFI_OP_CONSTANT_INT 31
|
27 |
+
#define _CFFI_OP_GLOBAL_VAR 33
|
28 |
+
#define _CFFI_OP_DLOPEN_FUNC 35
|
29 |
+
#define _CFFI_OP_DLOPEN_CONST 37
|
30 |
+
#define _CFFI_OP_GLOBAL_VAR_F 39
|
31 |
+
#define _CFFI_OP_EXTERN_PYTHON 41
|
32 |
+
|
33 |
+
#define _CFFI_PRIM_VOID 0
|
34 |
+
#define _CFFI_PRIM_BOOL 1
|
35 |
+
#define _CFFI_PRIM_CHAR 2
|
36 |
+
#define _CFFI_PRIM_SCHAR 3
|
37 |
+
#define _CFFI_PRIM_UCHAR 4
|
38 |
+
#define _CFFI_PRIM_SHORT 5
|
39 |
+
#define _CFFI_PRIM_USHORT 6
|
40 |
+
#define _CFFI_PRIM_INT 7
|
41 |
+
#define _CFFI_PRIM_UINT 8
|
42 |
+
#define _CFFI_PRIM_LONG 9
|
43 |
+
#define _CFFI_PRIM_ULONG 10
|
44 |
+
#define _CFFI_PRIM_LONGLONG 11
|
45 |
+
#define _CFFI_PRIM_ULONGLONG 12
|
46 |
+
#define _CFFI_PRIM_FLOAT 13
|
47 |
+
#define _CFFI_PRIM_DOUBLE 14
|
48 |
+
#define _CFFI_PRIM_LONGDOUBLE 15
|
49 |
+
|
50 |
+
#define _CFFI_PRIM_WCHAR 16
|
51 |
+
#define _CFFI_PRIM_INT8 17
|
52 |
+
#define _CFFI_PRIM_UINT8 18
|
53 |
+
#define _CFFI_PRIM_INT16 19
|
54 |
+
#define _CFFI_PRIM_UINT16 20
|
55 |
+
#define _CFFI_PRIM_INT32 21
|
56 |
+
#define _CFFI_PRIM_UINT32 22
|
57 |
+
#define _CFFI_PRIM_INT64 23
|
58 |
+
#define _CFFI_PRIM_UINT64 24
|
59 |
+
#define _CFFI_PRIM_INTPTR 25
|
60 |
+
#define _CFFI_PRIM_UINTPTR 26
|
61 |
+
#define _CFFI_PRIM_PTRDIFF 27
|
62 |
+
#define _CFFI_PRIM_SIZE 28
|
63 |
+
#define _CFFI_PRIM_SSIZE 29
|
64 |
+
#define _CFFI_PRIM_INT_LEAST8 30
|
65 |
+
#define _CFFI_PRIM_UINT_LEAST8 31
|
66 |
+
#define _CFFI_PRIM_INT_LEAST16 32
|
67 |
+
#define _CFFI_PRIM_UINT_LEAST16 33
|
68 |
+
#define _CFFI_PRIM_INT_LEAST32 34
|
69 |
+
#define _CFFI_PRIM_UINT_LEAST32 35
|
70 |
+
#define _CFFI_PRIM_INT_LEAST64 36
|
71 |
+
#define _CFFI_PRIM_UINT_LEAST64 37
|
72 |
+
#define _CFFI_PRIM_INT_FAST8 38
|
73 |
+
#define _CFFI_PRIM_UINT_FAST8 39
|
74 |
+
#define _CFFI_PRIM_INT_FAST16 40
|
75 |
+
#define _CFFI_PRIM_UINT_FAST16 41
|
76 |
+
#define _CFFI_PRIM_INT_FAST32 42
|
77 |
+
#define _CFFI_PRIM_UINT_FAST32 43
|
78 |
+
#define _CFFI_PRIM_INT_FAST64 44
|
79 |
+
#define _CFFI_PRIM_UINT_FAST64 45
|
80 |
+
#define _CFFI_PRIM_INTMAX 46
|
81 |
+
#define _CFFI_PRIM_UINTMAX 47
|
82 |
+
#define _CFFI_PRIM_FLOATCOMPLEX 48
|
83 |
+
#define _CFFI_PRIM_DOUBLECOMPLEX 49
|
84 |
+
#define _CFFI_PRIM_CHAR16 50
|
85 |
+
#define _CFFI_PRIM_CHAR32 51
|
86 |
+
|
87 |
+
#define _CFFI__NUM_PRIM 52
|
88 |
+
#define _CFFI__UNKNOWN_PRIM (-1)
|
89 |
+
#define _CFFI__UNKNOWN_FLOAT_PRIM (-2)
|
90 |
+
#define _CFFI__UNKNOWN_LONG_DOUBLE (-3)
|
91 |
+
|
92 |
+
#define _CFFI__IO_FILE_STRUCT (-1)
|
93 |
+
|
94 |
+
|
95 |
+
struct _cffi_global_s {
|
96 |
+
const char *name;
|
97 |
+
void *address;
|
98 |
+
_cffi_opcode_t type_op;
|
99 |
+
void *size_or_direct_fn; // OP_GLOBAL_VAR: size, or 0 if unknown
|
100 |
+
// OP_CPYTHON_BLTN_*: addr of direct function
|
101 |
+
};
|
102 |
+
|
103 |
+
struct _cffi_getconst_s {
|
104 |
+
unsigned long long value;
|
105 |
+
const struct _cffi_type_context_s *ctx;
|
106 |
+
int gindex;
|
107 |
+
};
|
108 |
+
|
109 |
+
struct _cffi_struct_union_s {
|
110 |
+
const char *name;
|
111 |
+
int type_index; // -> _cffi_types, on a OP_STRUCT_UNION
|
112 |
+
int flags; // _CFFI_F_* flags below
|
113 |
+
size_t size;
|
114 |
+
int alignment;
|
115 |
+
int first_field_index; // -> _cffi_fields array
|
116 |
+
int num_fields;
|
117 |
+
};
|
118 |
+
#define _CFFI_F_UNION 0x01 // is a union, not a struct
|
119 |
+
#define _CFFI_F_CHECK_FIELDS 0x02 // complain if fields are not in the
|
120 |
+
// "standard layout" or if some are missing
|
121 |
+
#define _CFFI_F_PACKED 0x04 // for CHECK_FIELDS, assume a packed struct
|
122 |
+
#define _CFFI_F_EXTERNAL 0x08 // in some other ffi.include()
|
123 |
+
#define _CFFI_F_OPAQUE 0x10 // opaque
|
124 |
+
|
125 |
+
struct _cffi_field_s {
|
126 |
+
const char *name;
|
127 |
+
size_t field_offset;
|
128 |
+
size_t field_size;
|
129 |
+
_cffi_opcode_t field_type_op;
|
130 |
+
};
|
131 |
+
|
132 |
+
struct _cffi_enum_s {
|
133 |
+
const char *name;
|
134 |
+
int type_index; // -> _cffi_types, on a OP_ENUM
|
135 |
+
int type_prim; // _CFFI_PRIM_xxx
|
136 |
+
const char *enumerators; // comma-delimited string
|
137 |
+
};
|
138 |
+
|
139 |
+
struct _cffi_typename_s {
|
140 |
+
const char *name;
|
141 |
+
int type_index; /* if opaque, points to a possibly artificial
|
142 |
+
OP_STRUCT which is itself opaque */
|
143 |
+
};
|
144 |
+
|
145 |
+
struct _cffi_type_context_s {
|
146 |
+
_cffi_opcode_t *types;
|
147 |
+
const struct _cffi_global_s *globals;
|
148 |
+
const struct _cffi_field_s *fields;
|
149 |
+
const struct _cffi_struct_union_s *struct_unions;
|
150 |
+
const struct _cffi_enum_s *enums;
|
151 |
+
const struct _cffi_typename_s *typenames;
|
152 |
+
int num_globals;
|
153 |
+
int num_struct_unions;
|
154 |
+
int num_enums;
|
155 |
+
int num_typenames;
|
156 |
+
const char *const *includes;
|
157 |
+
int num_types;
|
158 |
+
int flags; /* future extension */
|
159 |
+
};
|
160 |
+
|
161 |
+
struct _cffi_parse_info_s {
|
162 |
+
const struct _cffi_type_context_s *ctx;
|
163 |
+
_cffi_opcode_t *output;
|
164 |
+
unsigned int output_size;
|
165 |
+
size_t error_location;
|
166 |
+
const char *error_message;
|
167 |
+
};
|
168 |
+
|
169 |
+
struct _cffi_externpy_s {
|
170 |
+
const char *name;
|
171 |
+
size_t size_of_result;
|
172 |
+
void *reserved1, *reserved2;
|
173 |
+
};
|
174 |
+
|
175 |
+
#ifdef _CFFI_INTERNAL
|
176 |
+
static int parse_c_type(struct _cffi_parse_info_s *info, const char *input);
|
177 |
+
static int search_in_globals(const struct _cffi_type_context_s *ctx,
|
178 |
+
const char *search, size_t search_len);
|
179 |
+
static int search_in_struct_unions(const struct _cffi_type_context_s *ctx,
|
180 |
+
const char *search, size_t search_len);
|
181 |
+
#endif
|
cffi/pkgconfig.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# pkg-config, https://www.freedesktop.org/wiki/Software/pkg-config/ integration for cffi
|
2 |
+
import sys, os, subprocess
|
3 |
+
|
4 |
+
from .error import PkgConfigError
|
5 |
+
|
6 |
+
|
7 |
+
def merge_flags(cfg1, cfg2):
|
8 |
+
"""Merge values from cffi config flags cfg2 to cf1
|
9 |
+
|
10 |
+
Example:
|
11 |
+
merge_flags({"libraries": ["one"]}, {"libraries": ["two"]})
|
12 |
+
{"libraries": ["one", "two"]}
|
13 |
+
"""
|
14 |
+
for key, value in cfg2.items():
|
15 |
+
if key not in cfg1:
|
16 |
+
cfg1[key] = value
|
17 |
+
else:
|
18 |
+
if not isinstance(cfg1[key], list):
|
19 |
+
raise TypeError("cfg1[%r] should be a list of strings" % (key,))
|
20 |
+
if not isinstance(value, list):
|
21 |
+
raise TypeError("cfg2[%r] should be a list of strings" % (key,))
|
22 |
+
cfg1[key].extend(value)
|
23 |
+
return cfg1
|
24 |
+
|
25 |
+
|
26 |
+
def call(libname, flag, encoding=sys.getfilesystemencoding()):
|
27 |
+
"""Calls pkg-config and returns the output if found
|
28 |
+
"""
|
29 |
+
a = ["pkg-config", "--print-errors"]
|
30 |
+
a.append(flag)
|
31 |
+
a.append(libname)
|
32 |
+
try:
|
33 |
+
pc = subprocess.Popen(a, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
34 |
+
except EnvironmentError as e:
|
35 |
+
raise PkgConfigError("cannot run pkg-config: %s" % (str(e).strip(),))
|
36 |
+
|
37 |
+
bout, berr = pc.communicate()
|
38 |
+
if pc.returncode != 0:
|
39 |
+
try:
|
40 |
+
berr = berr.decode(encoding)
|
41 |
+
except Exception:
|
42 |
+
pass
|
43 |
+
raise PkgConfigError(berr.strip())
|
44 |
+
|
45 |
+
if sys.version_info >= (3,) and not isinstance(bout, str): # Python 3.x
|
46 |
+
try:
|
47 |
+
bout = bout.decode(encoding)
|
48 |
+
except UnicodeDecodeError:
|
49 |
+
raise PkgConfigError("pkg-config %s %s returned bytes that cannot "
|
50 |
+
"be decoded with encoding %r:\n%r" %
|
51 |
+
(flag, libname, encoding, bout))
|
52 |
+
|
53 |
+
if os.altsep != '\\' and '\\' in bout:
|
54 |
+
raise PkgConfigError("pkg-config %s %s returned an unsupported "
|
55 |
+
"backslash-escaped output:\n%r" %
|
56 |
+
(flag, libname, bout))
|
57 |
+
return bout
|
58 |
+
|
59 |
+
|
60 |
+
def flags_from_pkgconfig(libs):
|
61 |
+
r"""Return compiler line flags for FFI.set_source based on pkg-config output
|
62 |
+
|
63 |
+
Usage
|
64 |
+
...
|
65 |
+
ffibuilder.set_source("_foo", pkgconfig = ["libfoo", "libbar >= 1.8.3"])
|
66 |
+
|
67 |
+
If pkg-config is installed on build machine, then arguments include_dirs,
|
68 |
+
library_dirs, libraries, define_macros, extra_compile_args and
|
69 |
+
extra_link_args are extended with an output of pkg-config for libfoo and
|
70 |
+
libbar.
|
71 |
+
|
72 |
+
Raises PkgConfigError in case the pkg-config call fails.
|
73 |
+
"""
|
74 |
+
|
75 |
+
def get_include_dirs(string):
|
76 |
+
return [x[2:] for x in string.split() if x.startswith("-I")]
|
77 |
+
|
78 |
+
def get_library_dirs(string):
|
79 |
+
return [x[2:] for x in string.split() if x.startswith("-L")]
|
80 |
+
|
81 |
+
def get_libraries(string):
|
82 |
+
return [x[2:] for x in string.split() if x.startswith("-l")]
|
83 |
+
|
84 |
+
# convert -Dfoo=bar to list of tuples [("foo", "bar")] expected by distutils
|
85 |
+
def get_macros(string):
|
86 |
+
def _macro(x):
|
87 |
+
x = x[2:] # drop "-D"
|
88 |
+
if '=' in x:
|
89 |
+
return tuple(x.split("=", 1)) # "-Dfoo=bar" => ("foo", "bar")
|
90 |
+
else:
|
91 |
+
return (x, None) # "-Dfoo" => ("foo", None)
|
92 |
+
return [_macro(x) for x in string.split() if x.startswith("-D")]
|
93 |
+
|
94 |
+
def get_other_cflags(string):
|
95 |
+
return [x for x in string.split() if not x.startswith("-I") and
|
96 |
+
not x.startswith("-D")]
|
97 |
+
|
98 |
+
def get_other_libs(string):
|
99 |
+
return [x for x in string.split() if not x.startswith("-L") and
|
100 |
+
not x.startswith("-l")]
|
101 |
+
|
102 |
+
# return kwargs for given libname
|
103 |
+
def kwargs(libname):
|
104 |
+
fse = sys.getfilesystemencoding()
|
105 |
+
all_cflags = call(libname, "--cflags")
|
106 |
+
all_libs = call(libname, "--libs")
|
107 |
+
return {
|
108 |
+
"include_dirs": get_include_dirs(all_cflags),
|
109 |
+
"library_dirs": get_library_dirs(all_libs),
|
110 |
+
"libraries": get_libraries(all_libs),
|
111 |
+
"define_macros": get_macros(all_cflags),
|
112 |
+
"extra_compile_args": get_other_cflags(all_cflags),
|
113 |
+
"extra_link_args": get_other_libs(all_libs),
|
114 |
+
}
|
115 |
+
|
116 |
+
# merge all arguments together
|
117 |
+
ret = {}
|
118 |
+
for libname in libs:
|
119 |
+
lib_flags = kwargs(libname)
|
120 |
+
merge_flags(ret, lib_flags)
|
121 |
+
return ret
|
cffi/recompiler.py
ADDED
@@ -0,0 +1,1598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, sys, io
|
2 |
+
from . import ffiplatform, model
|
3 |
+
from .error import VerificationError
|
4 |
+
from .cffi_opcode import *
|
5 |
+
|
6 |
+
VERSION_BASE = 0x2601
|
7 |
+
VERSION_EMBEDDED = 0x2701
|
8 |
+
VERSION_CHAR16CHAR32 = 0x2801
|
9 |
+
|
10 |
+
USE_LIMITED_API = (sys.platform != 'win32' or sys.version_info < (3, 0) or
|
11 |
+
sys.version_info >= (3, 5))
|
12 |
+
|
13 |
+
|
14 |
+
class GlobalExpr:
|
15 |
+
def __init__(self, name, address, type_op, size=0, check_value=0):
|
16 |
+
self.name = name
|
17 |
+
self.address = address
|
18 |
+
self.type_op = type_op
|
19 |
+
self.size = size
|
20 |
+
self.check_value = check_value
|
21 |
+
|
22 |
+
def as_c_expr(self):
|
23 |
+
return ' { "%s", (void *)%s, %s, (void *)%s },' % (
|
24 |
+
self.name, self.address, self.type_op.as_c_expr(), self.size)
|
25 |
+
|
26 |
+
def as_python_expr(self):
|
27 |
+
return "b'%s%s',%d" % (self.type_op.as_python_bytes(), self.name,
|
28 |
+
self.check_value)
|
29 |
+
|
30 |
+
class FieldExpr:
|
31 |
+
def __init__(self, name, field_offset, field_size, fbitsize, field_type_op):
|
32 |
+
self.name = name
|
33 |
+
self.field_offset = field_offset
|
34 |
+
self.field_size = field_size
|
35 |
+
self.fbitsize = fbitsize
|
36 |
+
self.field_type_op = field_type_op
|
37 |
+
|
38 |
+
def as_c_expr(self):
|
39 |
+
spaces = " " * len(self.name)
|
40 |
+
return (' { "%s", %s,\n' % (self.name, self.field_offset) +
|
41 |
+
' %s %s,\n' % (spaces, self.field_size) +
|
42 |
+
' %s %s },' % (spaces, self.field_type_op.as_c_expr()))
|
43 |
+
|
44 |
+
def as_python_expr(self):
|
45 |
+
raise NotImplementedError
|
46 |
+
|
47 |
+
def as_field_python_expr(self):
|
48 |
+
if self.field_type_op.op == OP_NOOP:
|
49 |
+
size_expr = ''
|
50 |
+
elif self.field_type_op.op == OP_BITFIELD:
|
51 |
+
size_expr = format_four_bytes(self.fbitsize)
|
52 |
+
else:
|
53 |
+
raise NotImplementedError
|
54 |
+
return "b'%s%s%s'" % (self.field_type_op.as_python_bytes(),
|
55 |
+
size_expr,
|
56 |
+
self.name)
|
57 |
+
|
58 |
+
class StructUnionExpr:
|
59 |
+
def __init__(self, name, type_index, flags, size, alignment, comment,
|
60 |
+
first_field_index, c_fields):
|
61 |
+
self.name = name
|
62 |
+
self.type_index = type_index
|
63 |
+
self.flags = flags
|
64 |
+
self.size = size
|
65 |
+
self.alignment = alignment
|
66 |
+
self.comment = comment
|
67 |
+
self.first_field_index = first_field_index
|
68 |
+
self.c_fields = c_fields
|
69 |
+
|
70 |
+
def as_c_expr(self):
|
71 |
+
return (' { "%s", %d, %s,' % (self.name, self.type_index, self.flags)
|
72 |
+
+ '\n %s, %s, ' % (self.size, self.alignment)
|
73 |
+
+ '%d, %d ' % (self.first_field_index, len(self.c_fields))
|
74 |
+
+ ('/* %s */ ' % self.comment if self.comment else '')
|
75 |
+
+ '},')
|
76 |
+
|
77 |
+
def as_python_expr(self):
|
78 |
+
flags = eval(self.flags, G_FLAGS)
|
79 |
+
fields_expr = [c_field.as_field_python_expr()
|
80 |
+
for c_field in self.c_fields]
|
81 |
+
return "(b'%s%s%s',%s)" % (
|
82 |
+
format_four_bytes(self.type_index),
|
83 |
+
format_four_bytes(flags),
|
84 |
+
self.name,
|
85 |
+
','.join(fields_expr))
|
86 |
+
|
87 |
+
class EnumExpr:
|
88 |
+
def __init__(self, name, type_index, size, signed, allenums):
|
89 |
+
self.name = name
|
90 |
+
self.type_index = type_index
|
91 |
+
self.size = size
|
92 |
+
self.signed = signed
|
93 |
+
self.allenums = allenums
|
94 |
+
|
95 |
+
def as_c_expr(self):
|
96 |
+
return (' { "%s", %d, _cffi_prim_int(%s, %s),\n'
|
97 |
+
' "%s" },' % (self.name, self.type_index,
|
98 |
+
self.size, self.signed, self.allenums))
|
99 |
+
|
100 |
+
def as_python_expr(self):
|
101 |
+
prim_index = {
|
102 |
+
(1, 0): PRIM_UINT8, (1, 1): PRIM_INT8,
|
103 |
+
(2, 0): PRIM_UINT16, (2, 1): PRIM_INT16,
|
104 |
+
(4, 0): PRIM_UINT32, (4, 1): PRIM_INT32,
|
105 |
+
(8, 0): PRIM_UINT64, (8, 1): PRIM_INT64,
|
106 |
+
}[self.size, self.signed]
|
107 |
+
return "b'%s%s%s\\x00%s'" % (format_four_bytes(self.type_index),
|
108 |
+
format_four_bytes(prim_index),
|
109 |
+
self.name, self.allenums)
|
110 |
+
|
111 |
+
class TypenameExpr:
|
112 |
+
def __init__(self, name, type_index):
|
113 |
+
self.name = name
|
114 |
+
self.type_index = type_index
|
115 |
+
|
116 |
+
def as_c_expr(self):
|
117 |
+
return ' { "%s", %d },' % (self.name, self.type_index)
|
118 |
+
|
119 |
+
def as_python_expr(self):
|
120 |
+
return "b'%s%s'" % (format_four_bytes(self.type_index), self.name)
|
121 |
+
|
122 |
+
|
123 |
+
# ____________________________________________________________
|
124 |
+
|
125 |
+
|
126 |
+
class Recompiler:
|
127 |
+
_num_externpy = 0
|
128 |
+
|
129 |
+
def __init__(self, ffi, module_name, target_is_python=False):
|
130 |
+
self.ffi = ffi
|
131 |
+
self.module_name = module_name
|
132 |
+
self.target_is_python = target_is_python
|
133 |
+
self._version = VERSION_BASE
|
134 |
+
|
135 |
+
def needs_version(self, ver):
|
136 |
+
self._version = max(self._version, ver)
|
137 |
+
|
138 |
+
def collect_type_table(self):
|
139 |
+
self._typesdict = {}
|
140 |
+
self._generate("collecttype")
|
141 |
+
#
|
142 |
+
all_decls = sorted(self._typesdict, key=str)
|
143 |
+
#
|
144 |
+
# prepare all FUNCTION bytecode sequences first
|
145 |
+
self.cffi_types = []
|
146 |
+
for tp in all_decls:
|
147 |
+
if tp.is_raw_function:
|
148 |
+
assert self._typesdict[tp] is None
|
149 |
+
self._typesdict[tp] = len(self.cffi_types)
|
150 |
+
self.cffi_types.append(tp) # placeholder
|
151 |
+
for tp1 in tp.args:
|
152 |
+
assert isinstance(tp1, (model.VoidType,
|
153 |
+
model.BasePrimitiveType,
|
154 |
+
model.PointerType,
|
155 |
+
model.StructOrUnionOrEnum,
|
156 |
+
model.FunctionPtrType))
|
157 |
+
if self._typesdict[tp1] is None:
|
158 |
+
self._typesdict[tp1] = len(self.cffi_types)
|
159 |
+
self.cffi_types.append(tp1) # placeholder
|
160 |
+
self.cffi_types.append('END') # placeholder
|
161 |
+
#
|
162 |
+
# prepare all OTHER bytecode sequences
|
163 |
+
for tp in all_decls:
|
164 |
+
if not tp.is_raw_function and self._typesdict[tp] is None:
|
165 |
+
self._typesdict[tp] = len(self.cffi_types)
|
166 |
+
self.cffi_types.append(tp) # placeholder
|
167 |
+
if tp.is_array_type and tp.length is not None:
|
168 |
+
self.cffi_types.append('LEN') # placeholder
|
169 |
+
assert None not in self._typesdict.values()
|
170 |
+
#
|
171 |
+
# collect all structs and unions and enums
|
172 |
+
self._struct_unions = {}
|
173 |
+
self._enums = {}
|
174 |
+
for tp in all_decls:
|
175 |
+
if isinstance(tp, model.StructOrUnion):
|
176 |
+
self._struct_unions[tp] = None
|
177 |
+
elif isinstance(tp, model.EnumType):
|
178 |
+
self._enums[tp] = None
|
179 |
+
for i, tp in enumerate(sorted(self._struct_unions,
|
180 |
+
key=lambda tp: tp.name)):
|
181 |
+
self._struct_unions[tp] = i
|
182 |
+
for i, tp in enumerate(sorted(self._enums,
|
183 |
+
key=lambda tp: tp.name)):
|
184 |
+
self._enums[tp] = i
|
185 |
+
#
|
186 |
+
# emit all bytecode sequences now
|
187 |
+
for tp in all_decls:
|
188 |
+
method = getattr(self, '_emit_bytecode_' + tp.__class__.__name__)
|
189 |
+
method(tp, self._typesdict[tp])
|
190 |
+
#
|
191 |
+
# consistency check
|
192 |
+
for op in self.cffi_types:
|
193 |
+
assert isinstance(op, CffiOp)
|
194 |
+
self.cffi_types = tuple(self.cffi_types) # don't change any more
|
195 |
+
|
196 |
+
def _enum_fields(self, tp):
|
197 |
+
# When producing C, expand all anonymous struct/union fields.
|
198 |
+
# That's necessary to have C code checking the offsets of the
|
199 |
+
# individual fields contained in them. When producing Python,
|
200 |
+
# don't do it and instead write it like it is, with the
|
201 |
+
# corresponding fields having an empty name. Empty names are
|
202 |
+
# recognized at runtime when we import the generated Python
|
203 |
+
# file.
|
204 |
+
expand_anonymous_struct_union = not self.target_is_python
|
205 |
+
return tp.enumfields(expand_anonymous_struct_union)
|
206 |
+
|
207 |
+
def _do_collect_type(self, tp):
|
208 |
+
if not isinstance(tp, model.BaseTypeByIdentity):
|
209 |
+
if isinstance(tp, tuple):
|
210 |
+
for x in tp:
|
211 |
+
self._do_collect_type(x)
|
212 |
+
return
|
213 |
+
if tp not in self._typesdict:
|
214 |
+
self._typesdict[tp] = None
|
215 |
+
if isinstance(tp, model.FunctionPtrType):
|
216 |
+
self._do_collect_type(tp.as_raw_function())
|
217 |
+
elif isinstance(tp, model.StructOrUnion):
|
218 |
+
if tp.fldtypes is not None and (
|
219 |
+
tp not in self.ffi._parser._included_declarations):
|
220 |
+
for name1, tp1, _, _ in self._enum_fields(tp):
|
221 |
+
self._do_collect_type(self._field_type(tp, name1, tp1))
|
222 |
+
else:
|
223 |
+
for _, x in tp._get_items():
|
224 |
+
self._do_collect_type(x)
|
225 |
+
|
226 |
+
def _generate(self, step_name):
|
227 |
+
lst = self.ffi._parser._declarations.items()
|
228 |
+
for name, (tp, quals) in sorted(lst):
|
229 |
+
kind, realname = name.split(' ', 1)
|
230 |
+
try:
|
231 |
+
method = getattr(self, '_generate_cpy_%s_%s' % (kind,
|
232 |
+
step_name))
|
233 |
+
except AttributeError:
|
234 |
+
raise VerificationError(
|
235 |
+
"not implemented in recompile(): %r" % name)
|
236 |
+
try:
|
237 |
+
self._current_quals = quals
|
238 |
+
method(tp, realname)
|
239 |
+
except Exception as e:
|
240 |
+
model.attach_exception_info(e, name)
|
241 |
+
raise
|
242 |
+
|
243 |
+
# ----------
|
244 |
+
|
245 |
+
ALL_STEPS = ["global", "field", "struct_union", "enum", "typename"]
|
246 |
+
|
247 |
+
def collect_step_tables(self):
|
248 |
+
# collect the declarations for '_cffi_globals', '_cffi_typenames', etc.
|
249 |
+
self._lsts = {}
|
250 |
+
for step_name in self.ALL_STEPS:
|
251 |
+
self._lsts[step_name] = []
|
252 |
+
self._seen_struct_unions = set()
|
253 |
+
self._generate("ctx")
|
254 |
+
self._add_missing_struct_unions()
|
255 |
+
#
|
256 |
+
for step_name in self.ALL_STEPS:
|
257 |
+
lst = self._lsts[step_name]
|
258 |
+
if step_name != "field":
|
259 |
+
lst.sort(key=lambda entry: entry.name)
|
260 |
+
self._lsts[step_name] = tuple(lst) # don't change any more
|
261 |
+
#
|
262 |
+
# check for a possible internal inconsistency: _cffi_struct_unions
|
263 |
+
# should have been generated with exactly self._struct_unions
|
264 |
+
lst = self._lsts["struct_union"]
|
265 |
+
for tp, i in self._struct_unions.items():
|
266 |
+
assert i < len(lst)
|
267 |
+
assert lst[i].name == tp.name
|
268 |
+
assert len(lst) == len(self._struct_unions)
|
269 |
+
# same with enums
|
270 |
+
lst = self._lsts["enum"]
|
271 |
+
for tp, i in self._enums.items():
|
272 |
+
assert i < len(lst)
|
273 |
+
assert lst[i].name == tp.name
|
274 |
+
assert len(lst) == len(self._enums)
|
275 |
+
|
276 |
+
# ----------
|
277 |
+
|
278 |
+
def _prnt(self, what=''):
|
279 |
+
self._f.write(what + '\n')
|
280 |
+
|
281 |
+
def write_source_to_f(self, f, preamble):
|
282 |
+
if self.target_is_python:
|
283 |
+
assert preamble is None
|
284 |
+
self.write_py_source_to_f(f)
|
285 |
+
else:
|
286 |
+
assert preamble is not None
|
287 |
+
self.write_c_source_to_f(f, preamble)
|
288 |
+
|
289 |
+
def _rel_readlines(self, filename):
|
290 |
+
g = open(os.path.join(os.path.dirname(__file__), filename), 'r')
|
291 |
+
lines = g.readlines()
|
292 |
+
g.close()
|
293 |
+
return lines
|
294 |
+
|
295 |
+
def write_c_source_to_f(self, f, preamble):
|
296 |
+
self._f = f
|
297 |
+
prnt = self._prnt
|
298 |
+
if self.ffi._embedding is not None:
|
299 |
+
prnt('#define _CFFI_USE_EMBEDDING')
|
300 |
+
if not USE_LIMITED_API:
|
301 |
+
prnt('#define _CFFI_NO_LIMITED_API')
|
302 |
+
#
|
303 |
+
# first the '#include' (actually done by inlining the file's content)
|
304 |
+
lines = self._rel_readlines('_cffi_include.h')
|
305 |
+
i = lines.index('#include "parse_c_type.h"\n')
|
306 |
+
lines[i:i+1] = self._rel_readlines('parse_c_type.h')
|
307 |
+
prnt(''.join(lines))
|
308 |
+
#
|
309 |
+
# if we have ffi._embedding != None, we give it here as a macro
|
310 |
+
# and include an extra file
|
311 |
+
base_module_name = self.module_name.split('.')[-1]
|
312 |
+
if self.ffi._embedding is not None:
|
313 |
+
prnt('#define _CFFI_MODULE_NAME "%s"' % (self.module_name,))
|
314 |
+
prnt('static const char _CFFI_PYTHON_STARTUP_CODE[] = {')
|
315 |
+
self._print_string_literal_in_array(self.ffi._embedding)
|
316 |
+
prnt('0 };')
|
317 |
+
prnt('#ifdef PYPY_VERSION')
|
318 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_%s' % (
|
319 |
+
base_module_name,))
|
320 |
+
prnt('#elif PY_MAJOR_VERSION >= 3')
|
321 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC PyInit_%s' % (
|
322 |
+
base_module_name,))
|
323 |
+
prnt('#else')
|
324 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC init%s' % (
|
325 |
+
base_module_name,))
|
326 |
+
prnt('#endif')
|
327 |
+
lines = self._rel_readlines('_embedding.h')
|
328 |
+
i = lines.index('#include "_cffi_errors.h"\n')
|
329 |
+
lines[i:i+1] = self._rel_readlines('_cffi_errors.h')
|
330 |
+
prnt(''.join(lines))
|
331 |
+
self.needs_version(VERSION_EMBEDDED)
|
332 |
+
#
|
333 |
+
# then paste the C source given by the user, verbatim.
|
334 |
+
prnt('/************************************************************/')
|
335 |
+
prnt()
|
336 |
+
prnt(preamble)
|
337 |
+
prnt()
|
338 |
+
prnt('/************************************************************/')
|
339 |
+
prnt()
|
340 |
+
#
|
341 |
+
# the declaration of '_cffi_types'
|
342 |
+
prnt('static void *_cffi_types[] = {')
|
343 |
+
typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()])
|
344 |
+
for i, op in enumerate(self.cffi_types):
|
345 |
+
comment = ''
|
346 |
+
if i in typeindex2type:
|
347 |
+
comment = ' // ' + typeindex2type[i]._get_c_name()
|
348 |
+
prnt('/* %2d */ %s,%s' % (i, op.as_c_expr(), comment))
|
349 |
+
if not self.cffi_types:
|
350 |
+
prnt(' 0')
|
351 |
+
prnt('};')
|
352 |
+
prnt()
|
353 |
+
#
|
354 |
+
# call generate_cpy_xxx_decl(), for every xxx found from
|
355 |
+
# ffi._parser._declarations. This generates all the functions.
|
356 |
+
self._seen_constants = set()
|
357 |
+
self._generate("decl")
|
358 |
+
#
|
359 |
+
# the declaration of '_cffi_globals' and '_cffi_typenames'
|
360 |
+
nums = {}
|
361 |
+
for step_name in self.ALL_STEPS:
|
362 |
+
lst = self._lsts[step_name]
|
363 |
+
nums[step_name] = len(lst)
|
364 |
+
if nums[step_name] > 0:
|
365 |
+
prnt('static const struct _cffi_%s_s _cffi_%ss[] = {' % (
|
366 |
+
step_name, step_name))
|
367 |
+
for entry in lst:
|
368 |
+
prnt(entry.as_c_expr())
|
369 |
+
prnt('};')
|
370 |
+
prnt()
|
371 |
+
#
|
372 |
+
# the declaration of '_cffi_includes'
|
373 |
+
if self.ffi._included_ffis:
|
374 |
+
prnt('static const char * const _cffi_includes[] = {')
|
375 |
+
for ffi_to_include in self.ffi._included_ffis:
|
376 |
+
try:
|
377 |
+
included_module_name, included_source = (
|
378 |
+
ffi_to_include._assigned_source[:2])
|
379 |
+
except AttributeError:
|
380 |
+
raise VerificationError(
|
381 |
+
"ffi object %r includes %r, but the latter has not "
|
382 |
+
"been prepared with set_source()" % (
|
383 |
+
self.ffi, ffi_to_include,))
|
384 |
+
if included_source is None:
|
385 |
+
raise VerificationError(
|
386 |
+
"not implemented yet: ffi.include() of a Python-based "
|
387 |
+
"ffi inside a C-based ffi")
|
388 |
+
prnt(' "%s",' % (included_module_name,))
|
389 |
+
prnt(' NULL')
|
390 |
+
prnt('};')
|
391 |
+
prnt()
|
392 |
+
#
|
393 |
+
# the declaration of '_cffi_type_context'
|
394 |
+
prnt('static const struct _cffi_type_context_s _cffi_type_context = {')
|
395 |
+
prnt(' _cffi_types,')
|
396 |
+
for step_name in self.ALL_STEPS:
|
397 |
+
if nums[step_name] > 0:
|
398 |
+
prnt(' _cffi_%ss,' % step_name)
|
399 |
+
else:
|
400 |
+
prnt(' NULL, /* no %ss */' % step_name)
|
401 |
+
for step_name in self.ALL_STEPS:
|
402 |
+
if step_name != "field":
|
403 |
+
prnt(' %d, /* num_%ss */' % (nums[step_name], step_name))
|
404 |
+
if self.ffi._included_ffis:
|
405 |
+
prnt(' _cffi_includes,')
|
406 |
+
else:
|
407 |
+
prnt(' NULL, /* no includes */')
|
408 |
+
prnt(' %d, /* num_types */' % (len(self.cffi_types),))
|
409 |
+
flags = 0
|
410 |
+
if self._num_externpy > 0 or self.ffi._embedding is not None:
|
411 |
+
flags |= 1 # set to mean that we use extern "Python"
|
412 |
+
prnt(' %d, /* flags */' % flags)
|
413 |
+
prnt('};')
|
414 |
+
prnt()
|
415 |
+
#
|
416 |
+
# the init function
|
417 |
+
prnt('#ifdef __GNUC__')
|
418 |
+
prnt('# pragma GCC visibility push(default) /* for -fvisibility= */')
|
419 |
+
prnt('#endif')
|
420 |
+
prnt()
|
421 |
+
prnt('#ifdef PYPY_VERSION')
|
422 |
+
prnt('PyMODINIT_FUNC')
|
423 |
+
prnt('_cffi_pypyinit_%s(const void *p[])' % (base_module_name,))
|
424 |
+
prnt('{')
|
425 |
+
if flags & 1:
|
426 |
+
prnt(' if (((intptr_t)p[0]) >= 0x0A03) {')
|
427 |
+
prnt(' _cffi_call_python_org = '
|
428 |
+
'(void(*)(struct _cffi_externpy_s *, char *))p[1];')
|
429 |
+
prnt(' }')
|
430 |
+
prnt(' p[0] = (const void *)0x%x;' % self._version)
|
431 |
+
prnt(' p[1] = &_cffi_type_context;')
|
432 |
+
prnt('#if PY_MAJOR_VERSION >= 3')
|
433 |
+
prnt(' return NULL;')
|
434 |
+
prnt('#endif')
|
435 |
+
prnt('}')
|
436 |
+
# on Windows, distutils insists on putting init_cffi_xyz in
|
437 |
+
# 'export_symbols', so instead of fighting it, just give up and
|
438 |
+
# give it one
|
439 |
+
prnt('# ifdef _MSC_VER')
|
440 |
+
prnt(' PyMODINIT_FUNC')
|
441 |
+
prnt('# if PY_MAJOR_VERSION >= 3')
|
442 |
+
prnt(' PyInit_%s(void) { return NULL; }' % (base_module_name,))
|
443 |
+
prnt('# else')
|
444 |
+
prnt(' init%s(void) { }' % (base_module_name,))
|
445 |
+
prnt('# endif')
|
446 |
+
prnt('# endif')
|
447 |
+
prnt('#elif PY_MAJOR_VERSION >= 3')
|
448 |
+
prnt('PyMODINIT_FUNC')
|
449 |
+
prnt('PyInit_%s(void)' % (base_module_name,))
|
450 |
+
prnt('{')
|
451 |
+
prnt(' return _cffi_init("%s", 0x%x, &_cffi_type_context);' % (
|
452 |
+
self.module_name, self._version))
|
453 |
+
prnt('}')
|
454 |
+
prnt('#else')
|
455 |
+
prnt('PyMODINIT_FUNC')
|
456 |
+
prnt('init%s(void)' % (base_module_name,))
|
457 |
+
prnt('{')
|
458 |
+
prnt(' _cffi_init("%s", 0x%x, &_cffi_type_context);' % (
|
459 |
+
self.module_name, self._version))
|
460 |
+
prnt('}')
|
461 |
+
prnt('#endif')
|
462 |
+
prnt()
|
463 |
+
prnt('#ifdef __GNUC__')
|
464 |
+
prnt('# pragma GCC visibility pop')
|
465 |
+
prnt('#endif')
|
466 |
+
self._version = None
|
467 |
+
|
468 |
+
def _to_py(self, x):
|
469 |
+
if isinstance(x, str):
|
470 |
+
return "b'%s'" % (x,)
|
471 |
+
if isinstance(x, (list, tuple)):
|
472 |
+
rep = [self._to_py(item) for item in x]
|
473 |
+
if len(rep) == 1:
|
474 |
+
rep.append('')
|
475 |
+
return "(%s)" % (','.join(rep),)
|
476 |
+
return x.as_python_expr() # Py2: unicode unexpected; Py3: bytes unexp.
|
477 |
+
|
478 |
+
def write_py_source_to_f(self, f):
|
479 |
+
self._f = f
|
480 |
+
prnt = self._prnt
|
481 |
+
#
|
482 |
+
# header
|
483 |
+
prnt("# auto-generated file")
|
484 |
+
prnt("import _cffi_backend")
|
485 |
+
#
|
486 |
+
# the 'import' of the included ffis
|
487 |
+
num_includes = len(self.ffi._included_ffis or ())
|
488 |
+
for i in range(num_includes):
|
489 |
+
ffi_to_include = self.ffi._included_ffis[i]
|
490 |
+
try:
|
491 |
+
included_module_name, included_source = (
|
492 |
+
ffi_to_include._assigned_source[:2])
|
493 |
+
except AttributeError:
|
494 |
+
raise VerificationError(
|
495 |
+
"ffi object %r includes %r, but the latter has not "
|
496 |
+
"been prepared with set_source()" % (
|
497 |
+
self.ffi, ffi_to_include,))
|
498 |
+
if included_source is not None:
|
499 |
+
raise VerificationError(
|
500 |
+
"not implemented yet: ffi.include() of a C-based "
|
501 |
+
"ffi inside a Python-based ffi")
|
502 |
+
prnt('from %s import ffi as _ffi%d' % (included_module_name, i))
|
503 |
+
prnt()
|
504 |
+
prnt("ffi = _cffi_backend.FFI('%s'," % (self.module_name,))
|
505 |
+
prnt(" _version = 0x%x," % (self._version,))
|
506 |
+
self._version = None
|
507 |
+
#
|
508 |
+
# the '_types' keyword argument
|
509 |
+
self.cffi_types = tuple(self.cffi_types) # don't change any more
|
510 |
+
types_lst = [op.as_python_bytes() for op in self.cffi_types]
|
511 |
+
prnt(' _types = %s,' % (self._to_py(''.join(types_lst)),))
|
512 |
+
typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()])
|
513 |
+
#
|
514 |
+
# the keyword arguments from ALL_STEPS
|
515 |
+
for step_name in self.ALL_STEPS:
|
516 |
+
lst = self._lsts[step_name]
|
517 |
+
if len(lst) > 0 and step_name != "field":
|
518 |
+
prnt(' _%ss = %s,' % (step_name, self._to_py(lst)))
|
519 |
+
#
|
520 |
+
# the '_includes' keyword argument
|
521 |
+
if num_includes > 0:
|
522 |
+
prnt(' _includes = (%s,),' % (
|
523 |
+
', '.join(['_ffi%d' % i for i in range(num_includes)]),))
|
524 |
+
#
|
525 |
+
# the footer
|
526 |
+
prnt(')')
|
527 |
+
|
528 |
+
# ----------
|
529 |
+
|
530 |
+
def _gettypenum(self, type):
|
531 |
+
# a KeyError here is a bug. please report it! :-)
|
532 |
+
return self._typesdict[type]
|
533 |
+
|
534 |
+
def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode):
|
535 |
+
extraarg = ''
|
536 |
+
if isinstance(tp, model.BasePrimitiveType) and not tp.is_complex_type():
|
537 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
538 |
+
converter = '_cffi_to_c_int'
|
539 |
+
extraarg = ', %s' % tp.name
|
540 |
+
elif isinstance(tp, model.UnknownFloatType):
|
541 |
+
# don't check with is_float_type(): it may be a 'long
|
542 |
+
# double' here, and _cffi_to_c_double would loose precision
|
543 |
+
converter = '(%s)_cffi_to_c_double' % (tp.get_c_name(''),)
|
544 |
+
else:
|
545 |
+
cname = tp.get_c_name('')
|
546 |
+
converter = '(%s)_cffi_to_c_%s' % (cname,
|
547 |
+
tp.name.replace(' ', '_'))
|
548 |
+
if cname in ('char16_t', 'char32_t'):
|
549 |
+
self.needs_version(VERSION_CHAR16CHAR32)
|
550 |
+
errvalue = '-1'
|
551 |
+
#
|
552 |
+
elif isinstance(tp, model.PointerType):
|
553 |
+
self._convert_funcarg_to_c_ptr_or_array(tp, fromvar,
|
554 |
+
tovar, errcode)
|
555 |
+
return
|
556 |
+
#
|
557 |
+
elif (isinstance(tp, model.StructOrUnionOrEnum) or
|
558 |
+
isinstance(tp, model.BasePrimitiveType)):
|
559 |
+
# a struct (not a struct pointer) as a function argument;
|
560 |
+
# or, a complex (the same code works)
|
561 |
+
self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)'
|
562 |
+
% (tovar, self._gettypenum(tp), fromvar))
|
563 |
+
self._prnt(' %s;' % errcode)
|
564 |
+
return
|
565 |
+
#
|
566 |
+
elif isinstance(tp, model.FunctionPtrType):
|
567 |
+
converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('')
|
568 |
+
extraarg = ', _cffi_type(%d)' % self._gettypenum(tp)
|
569 |
+
errvalue = 'NULL'
|
570 |
+
#
|
571 |
+
else:
|
572 |
+
raise NotImplementedError(tp)
|
573 |
+
#
|
574 |
+
self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg))
|
575 |
+
self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % (
|
576 |
+
tovar, tp.get_c_name(''), errvalue))
|
577 |
+
self._prnt(' %s;' % errcode)
|
578 |
+
|
579 |
+
def _extra_local_variables(self, tp, localvars, freelines):
|
580 |
+
if isinstance(tp, model.PointerType):
|
581 |
+
localvars.add('Py_ssize_t datasize')
|
582 |
+
localvars.add('struct _cffi_freeme_s *large_args_free = NULL')
|
583 |
+
freelines.add('if (large_args_free != NULL)'
|
584 |
+
' _cffi_free_array_arguments(large_args_free);')
|
585 |
+
|
586 |
+
def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode):
|
587 |
+
self._prnt(' datasize = _cffi_prepare_pointer_call_argument(')
|
588 |
+
self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % (
|
589 |
+
self._gettypenum(tp), fromvar, tovar))
|
590 |
+
self._prnt(' if (datasize != 0) {')
|
591 |
+
self._prnt(' %s = ((size_t)datasize) <= 640 ? '
|
592 |
+
'(%s)alloca((size_t)datasize) : NULL;' % (
|
593 |
+
tovar, tp.get_c_name('')))
|
594 |
+
self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, '
|
595 |
+
'(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar))
|
596 |
+
self._prnt(' datasize, &large_args_free) < 0)')
|
597 |
+
self._prnt(' %s;' % errcode)
|
598 |
+
self._prnt(' }')
|
599 |
+
|
600 |
+
def _convert_expr_from_c(self, tp, var, context):
|
601 |
+
if isinstance(tp, model.BasePrimitiveType):
|
602 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
603 |
+
return '_cffi_from_c_int(%s, %s)' % (var, tp.name)
|
604 |
+
elif isinstance(tp, model.UnknownFloatType):
|
605 |
+
return '_cffi_from_c_double(%s)' % (var,)
|
606 |
+
elif tp.name != 'long double' and not tp.is_complex_type():
|
607 |
+
cname = tp.name.replace(' ', '_')
|
608 |
+
if cname in ('char16_t', 'char32_t'):
|
609 |
+
self.needs_version(VERSION_CHAR16CHAR32)
|
610 |
+
return '_cffi_from_c_%s(%s)' % (cname, var)
|
611 |
+
else:
|
612 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
613 |
+
var, self._gettypenum(tp))
|
614 |
+
elif isinstance(tp, (model.PointerType, model.FunctionPtrType)):
|
615 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
616 |
+
var, self._gettypenum(tp))
|
617 |
+
elif isinstance(tp, model.ArrayType):
|
618 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
619 |
+
var, self._gettypenum(model.PointerType(tp.item)))
|
620 |
+
elif isinstance(tp, model.StructOrUnion):
|
621 |
+
if tp.fldnames is None:
|
622 |
+
raise TypeError("'%s' is used as %s, but is opaque" % (
|
623 |
+
tp._get_c_name(), context))
|
624 |
+
return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % (
|
625 |
+
var, self._gettypenum(tp))
|
626 |
+
elif isinstance(tp, model.EnumType):
|
627 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
628 |
+
var, self._gettypenum(tp))
|
629 |
+
else:
|
630 |
+
raise NotImplementedError(tp)
|
631 |
+
|
632 |
+
# ----------
|
633 |
+
# typedefs
|
634 |
+
|
635 |
+
def _typedef_type(self, tp, name):
|
636 |
+
return self._global_type(tp, "(*(%s *)0)" % (name,))
|
637 |
+
|
638 |
+
def _generate_cpy_typedef_collecttype(self, tp, name):
|
639 |
+
self._do_collect_type(self._typedef_type(tp, name))
|
640 |
+
|
641 |
+
def _generate_cpy_typedef_decl(self, tp, name):
|
642 |
+
pass
|
643 |
+
|
644 |
+
def _typedef_ctx(self, tp, name):
|
645 |
+
type_index = self._typesdict[tp]
|
646 |
+
self._lsts["typename"].append(TypenameExpr(name, type_index))
|
647 |
+
|
648 |
+
def _generate_cpy_typedef_ctx(self, tp, name):
|
649 |
+
tp = self._typedef_type(tp, name)
|
650 |
+
self._typedef_ctx(tp, name)
|
651 |
+
if getattr(tp, "origin", None) == "unknown_type":
|
652 |
+
self._struct_ctx(tp, tp.name, approxname=None)
|
653 |
+
elif isinstance(tp, model.NamedPointerType):
|
654 |
+
self._struct_ctx(tp.totype, tp.totype.name, approxname=tp.name,
|
655 |
+
named_ptr=tp)
|
656 |
+
|
657 |
+
# ----------
|
658 |
+
# function declarations
|
659 |
+
|
660 |
+
def _generate_cpy_function_collecttype(self, tp, name):
|
661 |
+
self._do_collect_type(tp.as_raw_function())
|
662 |
+
if tp.ellipsis and not self.target_is_python:
|
663 |
+
self._do_collect_type(tp)
|
664 |
+
|
665 |
+
def _generate_cpy_function_decl(self, tp, name):
|
666 |
+
assert not self.target_is_python
|
667 |
+
assert isinstance(tp, model.FunctionPtrType)
|
668 |
+
if tp.ellipsis:
|
669 |
+
# cannot support vararg functions better than this: check for its
|
670 |
+
# exact type (including the fixed arguments), and build it as a
|
671 |
+
# constant function pointer (no CPython wrapper)
|
672 |
+
self._generate_cpy_constant_decl(tp, name)
|
673 |
+
return
|
674 |
+
prnt = self._prnt
|
675 |
+
numargs = len(tp.args)
|
676 |
+
if numargs == 0:
|
677 |
+
argname = 'noarg'
|
678 |
+
elif numargs == 1:
|
679 |
+
argname = 'arg0'
|
680 |
+
else:
|
681 |
+
argname = 'args'
|
682 |
+
#
|
683 |
+
# ------------------------------
|
684 |
+
# the 'd' version of the function, only for addressof(lib, 'func')
|
685 |
+
arguments = []
|
686 |
+
call_arguments = []
|
687 |
+
context = 'argument of %s' % name
|
688 |
+
for i, type in enumerate(tp.args):
|
689 |
+
arguments.append(type.get_c_name(' x%d' % i, context))
|
690 |
+
call_arguments.append('x%d' % i)
|
691 |
+
repr_arguments = ', '.join(arguments)
|
692 |
+
repr_arguments = repr_arguments or 'void'
|
693 |
+
if tp.abi:
|
694 |
+
abi = tp.abi + ' '
|
695 |
+
else:
|
696 |
+
abi = ''
|
697 |
+
name_and_arguments = '%s_cffi_d_%s(%s)' % (abi, name, repr_arguments)
|
698 |
+
prnt('static %s' % (tp.result.get_c_name(name_and_arguments),))
|
699 |
+
prnt('{')
|
700 |
+
call_arguments = ', '.join(call_arguments)
|
701 |
+
result_code = 'return '
|
702 |
+
if isinstance(tp.result, model.VoidType):
|
703 |
+
result_code = ''
|
704 |
+
prnt(' %s%s(%s);' % (result_code, name, call_arguments))
|
705 |
+
prnt('}')
|
706 |
+
#
|
707 |
+
prnt('#ifndef PYPY_VERSION') # ------------------------------
|
708 |
+
#
|
709 |
+
prnt('static PyObject *')
|
710 |
+
prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname))
|
711 |
+
prnt('{')
|
712 |
+
#
|
713 |
+
context = 'argument of %s' % name
|
714 |
+
for i, type in enumerate(tp.args):
|
715 |
+
arg = type.get_c_name(' x%d' % i, context)
|
716 |
+
prnt(' %s;' % arg)
|
717 |
+
#
|
718 |
+
localvars = set()
|
719 |
+
freelines = set()
|
720 |
+
for type in tp.args:
|
721 |
+
self._extra_local_variables(type, localvars, freelines)
|
722 |
+
for decl in sorted(localvars):
|
723 |
+
prnt(' %s;' % (decl,))
|
724 |
+
#
|
725 |
+
if not isinstance(tp.result, model.VoidType):
|
726 |
+
result_code = 'result = '
|
727 |
+
context = 'result of %s' % name
|
728 |
+
result_decl = ' %s;' % tp.result.get_c_name(' result', context)
|
729 |
+
prnt(result_decl)
|
730 |
+
prnt(' PyObject *pyresult;')
|
731 |
+
else:
|
732 |
+
result_decl = None
|
733 |
+
result_code = ''
|
734 |
+
#
|
735 |
+
if len(tp.args) > 1:
|
736 |
+
rng = range(len(tp.args))
|
737 |
+
for i in rng:
|
738 |
+
prnt(' PyObject *arg%d;' % i)
|
739 |
+
prnt()
|
740 |
+
prnt(' if (!PyArg_UnpackTuple(args, "%s", %d, %d, %s))' % (
|
741 |
+
name, len(rng), len(rng),
|
742 |
+
', '.join(['&arg%d' % i for i in rng])))
|
743 |
+
prnt(' return NULL;')
|
744 |
+
prnt()
|
745 |
+
#
|
746 |
+
for i, type in enumerate(tp.args):
|
747 |
+
self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i,
|
748 |
+
'return NULL')
|
749 |
+
prnt()
|
750 |
+
#
|
751 |
+
prnt(' Py_BEGIN_ALLOW_THREADS')
|
752 |
+
prnt(' _cffi_restore_errno();')
|
753 |
+
call_arguments = ['x%d' % i for i in range(len(tp.args))]
|
754 |
+
call_arguments = ', '.join(call_arguments)
|
755 |
+
prnt(' { %s%s(%s); }' % (result_code, name, call_arguments))
|
756 |
+
prnt(' _cffi_save_errno();')
|
757 |
+
prnt(' Py_END_ALLOW_THREADS')
|
758 |
+
prnt()
|
759 |
+
#
|
760 |
+
prnt(' (void)self; /* unused */')
|
761 |
+
if numargs == 0:
|
762 |
+
prnt(' (void)noarg; /* unused */')
|
763 |
+
if result_code:
|
764 |
+
prnt(' pyresult = %s;' %
|
765 |
+
self._convert_expr_from_c(tp.result, 'result', 'result type'))
|
766 |
+
for freeline in freelines:
|
767 |
+
prnt(' ' + freeline)
|
768 |
+
prnt(' return pyresult;')
|
769 |
+
else:
|
770 |
+
for freeline in freelines:
|
771 |
+
prnt(' ' + freeline)
|
772 |
+
prnt(' Py_INCREF(Py_None);')
|
773 |
+
prnt(' return Py_None;')
|
774 |
+
prnt('}')
|
775 |
+
#
|
776 |
+
prnt('#else') # ------------------------------
|
777 |
+
#
|
778 |
+
# the PyPy version: need to replace struct/union arguments with
|
779 |
+
# pointers, and if the result is a struct/union, insert a first
|
780 |
+
# arg that is a pointer to the result. We also do that for
|
781 |
+
# complex args and return type.
|
782 |
+
def need_indirection(type):
|
783 |
+
return (isinstance(type, model.StructOrUnion) or
|
784 |
+
(isinstance(type, model.PrimitiveType) and
|
785 |
+
type.is_complex_type()))
|
786 |
+
difference = False
|
787 |
+
arguments = []
|
788 |
+
call_arguments = []
|
789 |
+
context = 'argument of %s' % name
|
790 |
+
for i, type in enumerate(tp.args):
|
791 |
+
indirection = ''
|
792 |
+
if need_indirection(type):
|
793 |
+
indirection = '*'
|
794 |
+
difference = True
|
795 |
+
arg = type.get_c_name(' %sx%d' % (indirection, i), context)
|
796 |
+
arguments.append(arg)
|
797 |
+
call_arguments.append('%sx%d' % (indirection, i))
|
798 |
+
tp_result = tp.result
|
799 |
+
if need_indirection(tp_result):
|
800 |
+
context = 'result of %s' % name
|
801 |
+
arg = tp_result.get_c_name(' *result', context)
|
802 |
+
arguments.insert(0, arg)
|
803 |
+
tp_result = model.void_type
|
804 |
+
result_decl = None
|
805 |
+
result_code = '*result = '
|
806 |
+
difference = True
|
807 |
+
if difference:
|
808 |
+
repr_arguments = ', '.join(arguments)
|
809 |
+
repr_arguments = repr_arguments or 'void'
|
810 |
+
name_and_arguments = '%s_cffi_f_%s(%s)' % (abi, name,
|
811 |
+
repr_arguments)
|
812 |
+
prnt('static %s' % (tp_result.get_c_name(name_and_arguments),))
|
813 |
+
prnt('{')
|
814 |
+
if result_decl:
|
815 |
+
prnt(result_decl)
|
816 |
+
call_arguments = ', '.join(call_arguments)
|
817 |
+
prnt(' { %s%s(%s); }' % (result_code, name, call_arguments))
|
818 |
+
if result_decl:
|
819 |
+
prnt(' return result;')
|
820 |
+
prnt('}')
|
821 |
+
else:
|
822 |
+
prnt('# define _cffi_f_%s _cffi_d_%s' % (name, name))
|
823 |
+
#
|
824 |
+
prnt('#endif') # ------------------------------
|
825 |
+
prnt()
|
826 |
+
|
827 |
+
def _generate_cpy_function_ctx(self, tp, name):
|
828 |
+
if tp.ellipsis and not self.target_is_python:
|
829 |
+
self._generate_cpy_constant_ctx(tp, name)
|
830 |
+
return
|
831 |
+
type_index = self._typesdict[tp.as_raw_function()]
|
832 |
+
numargs = len(tp.args)
|
833 |
+
if self.target_is_python:
|
834 |
+
meth_kind = OP_DLOPEN_FUNC
|
835 |
+
elif numargs == 0:
|
836 |
+
meth_kind = OP_CPYTHON_BLTN_N # 'METH_NOARGS'
|
837 |
+
elif numargs == 1:
|
838 |
+
meth_kind = OP_CPYTHON_BLTN_O # 'METH_O'
|
839 |
+
else:
|
840 |
+
meth_kind = OP_CPYTHON_BLTN_V # 'METH_VARARGS'
|
841 |
+
self._lsts["global"].append(
|
842 |
+
GlobalExpr(name, '_cffi_f_%s' % name,
|
843 |
+
CffiOp(meth_kind, type_index),
|
844 |
+
size='_cffi_d_%s' % name))
|
845 |
+
|
846 |
+
# ----------
|
847 |
+
# named structs or unions
|
848 |
+
|
849 |
+
def _field_type(self, tp_struct, field_name, tp_field):
|
850 |
+
if isinstance(tp_field, model.ArrayType):
|
851 |
+
actual_length = tp_field.length
|
852 |
+
if actual_length == '...':
|
853 |
+
ptr_struct_name = tp_struct.get_c_name('*')
|
854 |
+
actual_length = '_cffi_array_len(((%s)0)->%s)' % (
|
855 |
+
ptr_struct_name, field_name)
|
856 |
+
tp_item = self._field_type(tp_struct, '%s[0]' % field_name,
|
857 |
+
tp_field.item)
|
858 |
+
tp_field = model.ArrayType(tp_item, actual_length)
|
859 |
+
return tp_field
|
860 |
+
|
861 |
+
def _struct_collecttype(self, tp):
|
862 |
+
self._do_collect_type(tp)
|
863 |
+
if self.target_is_python:
|
864 |
+
# also requires nested anon struct/unions in ABI mode, recursively
|
865 |
+
for fldtype in tp.anonymous_struct_fields():
|
866 |
+
self._struct_collecttype(fldtype)
|
867 |
+
|
868 |
+
def _struct_decl(self, tp, cname, approxname):
|
869 |
+
if tp.fldtypes is None:
|
870 |
+
return
|
871 |
+
prnt = self._prnt
|
872 |
+
checkfuncname = '_cffi_checkfld_%s' % (approxname,)
|
873 |
+
prnt('_CFFI_UNUSED_FN')
|
874 |
+
prnt('static void %s(%s *p)' % (checkfuncname, cname))
|
875 |
+
prnt('{')
|
876 |
+
prnt(' /* only to generate compile-time warnings or errors */')
|
877 |
+
prnt(' (void)p;')
|
878 |
+
for fname, ftype, fbitsize, fqual in self._enum_fields(tp):
|
879 |
+
try:
|
880 |
+
if ftype.is_integer_type() or fbitsize >= 0:
|
881 |
+
# accept all integers, but complain on float or double
|
882 |
+
if fname != '':
|
883 |
+
prnt(" (void)((p->%s) | 0); /* check that '%s.%s' is "
|
884 |
+
"an integer */" % (fname, cname, fname))
|
885 |
+
continue
|
886 |
+
# only accept exactly the type declared, except that '[]'
|
887 |
+
# is interpreted as a '*' and so will match any array length.
|
888 |
+
# (It would also match '*', but that's harder to detect...)
|
889 |
+
while (isinstance(ftype, model.ArrayType)
|
890 |
+
and (ftype.length is None or ftype.length == '...')):
|
891 |
+
ftype = ftype.item
|
892 |
+
fname = fname + '[0]'
|
893 |
+
prnt(' { %s = &p->%s; (void)tmp; }' % (
|
894 |
+
ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
|
895 |
+
fname))
|
896 |
+
except VerificationError as e:
|
897 |
+
prnt(' /* %s */' % str(e)) # cannot verify it, ignore
|
898 |
+
prnt('}')
|
899 |
+
prnt('struct _cffi_align_%s { char x; %s y; };' % (approxname, cname))
|
900 |
+
prnt()
|
901 |
+
|
902 |
+
def _struct_ctx(self, tp, cname, approxname, named_ptr=None):
|
903 |
+
type_index = self._typesdict[tp]
|
904 |
+
reason_for_not_expanding = None
|
905 |
+
flags = []
|
906 |
+
if isinstance(tp, model.UnionType):
|
907 |
+
flags.append("_CFFI_F_UNION")
|
908 |
+
if tp.fldtypes is None:
|
909 |
+
flags.append("_CFFI_F_OPAQUE")
|
910 |
+
reason_for_not_expanding = "opaque"
|
911 |
+
if (tp not in self.ffi._parser._included_declarations and
|
912 |
+
(named_ptr is None or
|
913 |
+
named_ptr not in self.ffi._parser._included_declarations)):
|
914 |
+
if tp.fldtypes is None:
|
915 |
+
pass # opaque
|
916 |
+
elif tp.partial or any(tp.anonymous_struct_fields()):
|
917 |
+
pass # field layout obtained silently from the C compiler
|
918 |
+
else:
|
919 |
+
flags.append("_CFFI_F_CHECK_FIELDS")
|
920 |
+
if tp.packed:
|
921 |
+
if tp.packed > 1:
|
922 |
+
raise NotImplementedError(
|
923 |
+
"%r is declared with 'pack=%r'; only 0 or 1 are "
|
924 |
+
"supported in API mode (try to use \"...;\", which "
|
925 |
+
"does not require a 'pack' declaration)" %
|
926 |
+
(tp, tp.packed))
|
927 |
+
flags.append("_CFFI_F_PACKED")
|
928 |
+
else:
|
929 |
+
flags.append("_CFFI_F_EXTERNAL")
|
930 |
+
reason_for_not_expanding = "external"
|
931 |
+
flags = '|'.join(flags) or '0'
|
932 |
+
c_fields = []
|
933 |
+
if reason_for_not_expanding is None:
|
934 |
+
enumfields = list(self._enum_fields(tp))
|
935 |
+
for fldname, fldtype, fbitsize, fqual in enumfields:
|
936 |
+
fldtype = self._field_type(tp, fldname, fldtype)
|
937 |
+
self._check_not_opaque(fldtype,
|
938 |
+
"field '%s.%s'" % (tp.name, fldname))
|
939 |
+
# cname is None for _add_missing_struct_unions() only
|
940 |
+
op = OP_NOOP
|
941 |
+
if fbitsize >= 0:
|
942 |
+
op = OP_BITFIELD
|
943 |
+
size = '%d /* bits */' % fbitsize
|
944 |
+
elif cname is None or (
|
945 |
+
isinstance(fldtype, model.ArrayType) and
|
946 |
+
fldtype.length is None):
|
947 |
+
size = '(size_t)-1'
|
948 |
+
else:
|
949 |
+
size = 'sizeof(((%s)0)->%s)' % (
|
950 |
+
tp.get_c_name('*') if named_ptr is None
|
951 |
+
else named_ptr.name,
|
952 |
+
fldname)
|
953 |
+
if cname is None or fbitsize >= 0:
|
954 |
+
offset = '(size_t)-1'
|
955 |
+
elif named_ptr is not None:
|
956 |
+
offset = '((char *)&((%s)4096)->%s) - (char *)4096' % (
|
957 |
+
named_ptr.name, fldname)
|
958 |
+
else:
|
959 |
+
offset = 'offsetof(%s, %s)' % (tp.get_c_name(''), fldname)
|
960 |
+
c_fields.append(
|
961 |
+
FieldExpr(fldname, offset, size, fbitsize,
|
962 |
+
CffiOp(op, self._typesdict[fldtype])))
|
963 |
+
first_field_index = len(self._lsts["field"])
|
964 |
+
self._lsts["field"].extend(c_fields)
|
965 |
+
#
|
966 |
+
if cname is None: # unknown name, for _add_missing_struct_unions
|
967 |
+
size = '(size_t)-2'
|
968 |
+
align = -2
|
969 |
+
comment = "unnamed"
|
970 |
+
else:
|
971 |
+
if named_ptr is not None:
|
972 |
+
size = 'sizeof(*(%s)0)' % (named_ptr.name,)
|
973 |
+
align = '-1 /* unknown alignment */'
|
974 |
+
else:
|
975 |
+
size = 'sizeof(%s)' % (cname,)
|
976 |
+
align = 'offsetof(struct _cffi_align_%s, y)' % (approxname,)
|
977 |
+
comment = None
|
978 |
+
else:
|
979 |
+
size = '(size_t)-1'
|
980 |
+
align = -1
|
981 |
+
first_field_index = -1
|
982 |
+
comment = reason_for_not_expanding
|
983 |
+
self._lsts["struct_union"].append(
|
984 |
+
StructUnionExpr(tp.name, type_index, flags, size, align, comment,
|
985 |
+
first_field_index, c_fields))
|
986 |
+
self._seen_struct_unions.add(tp)
|
987 |
+
|
988 |
+
def _check_not_opaque(self, tp, location):
|
989 |
+
while isinstance(tp, model.ArrayType):
|
990 |
+
tp = tp.item
|
991 |
+
if isinstance(tp, model.StructOrUnion) and tp.fldtypes is None:
|
992 |
+
raise TypeError(
|
993 |
+
"%s is of an opaque type (not declared in cdef())" % location)
|
994 |
+
|
995 |
+
def _add_missing_struct_unions(self):
|
996 |
+
# not very nice, but some struct declarations might be missing
|
997 |
+
# because they don't have any known C name. Check that they are
|
998 |
+
# not partial (we can't complete or verify them!) and emit them
|
999 |
+
# anonymously.
|
1000 |
+
lst = list(self._struct_unions.items())
|
1001 |
+
lst.sort(key=lambda tp_order: tp_order[1])
|
1002 |
+
for tp, order in lst:
|
1003 |
+
if tp not in self._seen_struct_unions:
|
1004 |
+
if tp.partial:
|
1005 |
+
raise NotImplementedError("internal inconsistency: %r is "
|
1006 |
+
"partial but was not seen at "
|
1007 |
+
"this point" % (tp,))
|
1008 |
+
if tp.name.startswith('$') and tp.name[1:].isdigit():
|
1009 |
+
approxname = tp.name[1:]
|
1010 |
+
elif tp.name == '_IO_FILE' and tp.forcename == 'FILE':
|
1011 |
+
approxname = 'FILE'
|
1012 |
+
self._typedef_ctx(tp, 'FILE')
|
1013 |
+
else:
|
1014 |
+
raise NotImplementedError("internal inconsistency: %r" %
|
1015 |
+
(tp,))
|
1016 |
+
self._struct_ctx(tp, None, approxname)
|
1017 |
+
|
1018 |
+
def _generate_cpy_struct_collecttype(self, tp, name):
|
1019 |
+
self._struct_collecttype(tp)
|
1020 |
+
_generate_cpy_union_collecttype = _generate_cpy_struct_collecttype
|
1021 |
+
|
1022 |
+
def _struct_names(self, tp):
|
1023 |
+
cname = tp.get_c_name('')
|
1024 |
+
if ' ' in cname:
|
1025 |
+
return cname, cname.replace(' ', '_')
|
1026 |
+
else:
|
1027 |
+
return cname, '_' + cname
|
1028 |
+
|
1029 |
+
def _generate_cpy_struct_decl(self, tp, name):
|
1030 |
+
self._struct_decl(tp, *self._struct_names(tp))
|
1031 |
+
_generate_cpy_union_decl = _generate_cpy_struct_decl
|
1032 |
+
|
1033 |
+
def _generate_cpy_struct_ctx(self, tp, name):
|
1034 |
+
self._struct_ctx(tp, *self._struct_names(tp))
|
1035 |
+
_generate_cpy_union_ctx = _generate_cpy_struct_ctx
|
1036 |
+
|
1037 |
+
# ----------
|
1038 |
+
# 'anonymous' declarations. These are produced for anonymous structs
|
1039 |
+
# or unions; the 'name' is obtained by a typedef.
|
1040 |
+
|
1041 |
+
def _generate_cpy_anonymous_collecttype(self, tp, name):
|
1042 |
+
if isinstance(tp, model.EnumType):
|
1043 |
+
self._generate_cpy_enum_collecttype(tp, name)
|
1044 |
+
else:
|
1045 |
+
self._struct_collecttype(tp)
|
1046 |
+
|
1047 |
+
def _generate_cpy_anonymous_decl(self, tp, name):
|
1048 |
+
if isinstance(tp, model.EnumType):
|
1049 |
+
self._generate_cpy_enum_decl(tp)
|
1050 |
+
else:
|
1051 |
+
self._struct_decl(tp, name, 'typedef_' + name)
|
1052 |
+
|
1053 |
+
def _generate_cpy_anonymous_ctx(self, tp, name):
|
1054 |
+
if isinstance(tp, model.EnumType):
|
1055 |
+
self._enum_ctx(tp, name)
|
1056 |
+
else:
|
1057 |
+
self._struct_ctx(tp, name, 'typedef_' + name)
|
1058 |
+
|
1059 |
+
# ----------
|
1060 |
+
# constants, declared with "static const ..."
|
1061 |
+
|
1062 |
+
def _generate_cpy_const(self, is_int, name, tp=None, category='const',
|
1063 |
+
check_value=None):
|
1064 |
+
if (category, name) in self._seen_constants:
|
1065 |
+
raise VerificationError(
|
1066 |
+
"duplicate declaration of %s '%s'" % (category, name))
|
1067 |
+
self._seen_constants.add((category, name))
|
1068 |
+
#
|
1069 |
+
prnt = self._prnt
|
1070 |
+
funcname = '_cffi_%s_%s' % (category, name)
|
1071 |
+
if is_int:
|
1072 |
+
prnt('static int %s(unsigned long long *o)' % funcname)
|
1073 |
+
prnt('{')
|
1074 |
+
prnt(' int n = (%s) <= 0;' % (name,))
|
1075 |
+
prnt(' *o = (unsigned long long)((%s) | 0);'
|
1076 |
+
' /* check that %s is an integer */' % (name, name))
|
1077 |
+
if check_value is not None:
|
1078 |
+
if check_value > 0:
|
1079 |
+
check_value = '%dU' % (check_value,)
|
1080 |
+
prnt(' if (!_cffi_check_int(*o, n, %s))' % (check_value,))
|
1081 |
+
prnt(' n |= 2;')
|
1082 |
+
prnt(' return n;')
|
1083 |
+
prnt('}')
|
1084 |
+
else:
|
1085 |
+
assert check_value is None
|
1086 |
+
prnt('static void %s(char *o)' % funcname)
|
1087 |
+
prnt('{')
|
1088 |
+
prnt(' *(%s)o = %s;' % (tp.get_c_name('*'), name))
|
1089 |
+
prnt('}')
|
1090 |
+
prnt()
|
1091 |
+
|
1092 |
+
def _generate_cpy_constant_collecttype(self, tp, name):
|
1093 |
+
is_int = tp.is_integer_type()
|
1094 |
+
if not is_int or self.target_is_python:
|
1095 |
+
self._do_collect_type(tp)
|
1096 |
+
|
1097 |
+
def _generate_cpy_constant_decl(self, tp, name):
|
1098 |
+
is_int = tp.is_integer_type()
|
1099 |
+
self._generate_cpy_const(is_int, name, tp)
|
1100 |
+
|
1101 |
+
def _generate_cpy_constant_ctx(self, tp, name):
|
1102 |
+
if not self.target_is_python and tp.is_integer_type():
|
1103 |
+
type_op = CffiOp(OP_CONSTANT_INT, -1)
|
1104 |
+
else:
|
1105 |
+
if self.target_is_python:
|
1106 |
+
const_kind = OP_DLOPEN_CONST
|
1107 |
+
else:
|
1108 |
+
const_kind = OP_CONSTANT
|
1109 |
+
type_index = self._typesdict[tp]
|
1110 |
+
type_op = CffiOp(const_kind, type_index)
|
1111 |
+
self._lsts["global"].append(
|
1112 |
+
GlobalExpr(name, '_cffi_const_%s' % name, type_op))
|
1113 |
+
|
1114 |
+
# ----------
|
1115 |
+
# enums
|
1116 |
+
|
1117 |
+
def _generate_cpy_enum_collecttype(self, tp, name):
|
1118 |
+
self._do_collect_type(tp)
|
1119 |
+
|
1120 |
+
def _generate_cpy_enum_decl(self, tp, name=None):
|
1121 |
+
for enumerator in tp.enumerators:
|
1122 |
+
self._generate_cpy_const(True, enumerator)
|
1123 |
+
|
1124 |
+
def _enum_ctx(self, tp, cname):
|
1125 |
+
type_index = self._typesdict[tp]
|
1126 |
+
type_op = CffiOp(OP_ENUM, -1)
|
1127 |
+
if self.target_is_python:
|
1128 |
+
tp.check_not_partial()
|
1129 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
1130 |
+
self._lsts["global"].append(
|
1131 |
+
GlobalExpr(enumerator, '_cffi_const_%s' % enumerator, type_op,
|
1132 |
+
check_value=enumvalue))
|
1133 |
+
#
|
1134 |
+
if cname is not None and '$' not in cname and not self.target_is_python:
|
1135 |
+
size = "sizeof(%s)" % cname
|
1136 |
+
signed = "((%s)-1) <= 0" % cname
|
1137 |
+
else:
|
1138 |
+
basetp = tp.build_baseinttype(self.ffi, [])
|
1139 |
+
size = self.ffi.sizeof(basetp)
|
1140 |
+
signed = int(int(self.ffi.cast(basetp, -1)) < 0)
|
1141 |
+
allenums = ",".join(tp.enumerators)
|
1142 |
+
self._lsts["enum"].append(
|
1143 |
+
EnumExpr(tp.name, type_index, size, signed, allenums))
|
1144 |
+
|
1145 |
+
def _generate_cpy_enum_ctx(self, tp, name):
|
1146 |
+
self._enum_ctx(tp, tp._get_c_name())
|
1147 |
+
|
1148 |
+
# ----------
|
1149 |
+
# macros: for now only for integers
|
1150 |
+
|
1151 |
+
def _generate_cpy_macro_collecttype(self, tp, name):
|
1152 |
+
pass
|
1153 |
+
|
1154 |
+
def _generate_cpy_macro_decl(self, tp, name):
|
1155 |
+
if tp == '...':
|
1156 |
+
check_value = None
|
1157 |
+
else:
|
1158 |
+
check_value = tp # an integer
|
1159 |
+
self._generate_cpy_const(True, name, check_value=check_value)
|
1160 |
+
|
1161 |
+
def _generate_cpy_macro_ctx(self, tp, name):
|
1162 |
+
if tp == '...':
|
1163 |
+
if self.target_is_python:
|
1164 |
+
raise VerificationError(
|
1165 |
+
"cannot use the syntax '...' in '#define %s ...' when "
|
1166 |
+
"using the ABI mode" % (name,))
|
1167 |
+
check_value = None
|
1168 |
+
else:
|
1169 |
+
check_value = tp # an integer
|
1170 |
+
type_op = CffiOp(OP_CONSTANT_INT, -1)
|
1171 |
+
self._lsts["global"].append(
|
1172 |
+
GlobalExpr(name, '_cffi_const_%s' % name, type_op,
|
1173 |
+
check_value=check_value))
|
1174 |
+
|
1175 |
+
# ----------
|
1176 |
+
# global variables
|
1177 |
+
|
1178 |
+
def _global_type(self, tp, global_name):
|
1179 |
+
if isinstance(tp, model.ArrayType):
|
1180 |
+
actual_length = tp.length
|
1181 |
+
if actual_length == '...':
|
1182 |
+
actual_length = '_cffi_array_len(%s)' % (global_name,)
|
1183 |
+
tp_item = self._global_type(tp.item, '%s[0]' % global_name)
|
1184 |
+
tp = model.ArrayType(tp_item, actual_length)
|
1185 |
+
return tp
|
1186 |
+
|
1187 |
+
def _generate_cpy_variable_collecttype(self, tp, name):
|
1188 |
+
self._do_collect_type(self._global_type(tp, name))
|
1189 |
+
|
1190 |
+
def _generate_cpy_variable_decl(self, tp, name):
|
1191 |
+
prnt = self._prnt
|
1192 |
+
tp = self._global_type(tp, name)
|
1193 |
+
if isinstance(tp, model.ArrayType) and tp.length is None:
|
1194 |
+
tp = tp.item
|
1195 |
+
ampersand = ''
|
1196 |
+
else:
|
1197 |
+
ampersand = '&'
|
1198 |
+
# This code assumes that casts from "tp *" to "void *" is a
|
1199 |
+
# no-op, i.e. a function that returns a "tp *" can be called
|
1200 |
+
# as if it returned a "void *". This should be generally true
|
1201 |
+
# on any modern machine. The only exception to that rule (on
|
1202 |
+
# uncommon architectures, and as far as I can tell) might be
|
1203 |
+
# if 'tp' were a function type, but that is not possible here.
|
1204 |
+
# (If 'tp' is a function _pointer_ type, then casts from "fn_t
|
1205 |
+
# **" to "void *" are again no-ops, as far as I can tell.)
|
1206 |
+
decl = '*_cffi_var_%s(void)' % (name,)
|
1207 |
+
prnt('static ' + tp.get_c_name(decl, quals=self._current_quals))
|
1208 |
+
prnt('{')
|
1209 |
+
prnt(' return %s(%s);' % (ampersand, name))
|
1210 |
+
prnt('}')
|
1211 |
+
prnt()
|
1212 |
+
|
1213 |
+
def _generate_cpy_variable_ctx(self, tp, name):
|
1214 |
+
tp = self._global_type(tp, name)
|
1215 |
+
type_index = self._typesdict[tp]
|
1216 |
+
if self.target_is_python:
|
1217 |
+
op = OP_GLOBAL_VAR
|
1218 |
+
else:
|
1219 |
+
op = OP_GLOBAL_VAR_F
|
1220 |
+
self._lsts["global"].append(
|
1221 |
+
GlobalExpr(name, '_cffi_var_%s' % name, CffiOp(op, type_index)))
|
1222 |
+
|
1223 |
+
# ----------
|
1224 |
+
# extern "Python"
|
1225 |
+
|
1226 |
+
def _generate_cpy_extern_python_collecttype(self, tp, name):
|
1227 |
+
assert isinstance(tp, model.FunctionPtrType)
|
1228 |
+
self._do_collect_type(tp)
|
1229 |
+
_generate_cpy_dllexport_python_collecttype = \
|
1230 |
+
_generate_cpy_extern_python_plus_c_collecttype = \
|
1231 |
+
_generate_cpy_extern_python_collecttype
|
1232 |
+
|
1233 |
+
def _extern_python_decl(self, tp, name, tag_and_space):
|
1234 |
+
prnt = self._prnt
|
1235 |
+
if isinstance(tp.result, model.VoidType):
|
1236 |
+
size_of_result = '0'
|
1237 |
+
else:
|
1238 |
+
context = 'result of %s' % name
|
1239 |
+
size_of_result = '(int)sizeof(%s)' % (
|
1240 |
+
tp.result.get_c_name('', context),)
|
1241 |
+
prnt('static struct _cffi_externpy_s _cffi_externpy__%s =' % name)
|
1242 |
+
prnt(' { "%s.%s", %s, 0, 0 };' % (
|
1243 |
+
self.module_name, name, size_of_result))
|
1244 |
+
prnt()
|
1245 |
+
#
|
1246 |
+
arguments = []
|
1247 |
+
context = 'argument of %s' % name
|
1248 |
+
for i, type in enumerate(tp.args):
|
1249 |
+
arg = type.get_c_name(' a%d' % i, context)
|
1250 |
+
arguments.append(arg)
|
1251 |
+
#
|
1252 |
+
repr_arguments = ', '.join(arguments)
|
1253 |
+
repr_arguments = repr_arguments or 'void'
|
1254 |
+
name_and_arguments = '%s(%s)' % (name, repr_arguments)
|
1255 |
+
if tp.abi == "__stdcall":
|
1256 |
+
name_and_arguments = '_cffi_stdcall ' + name_and_arguments
|
1257 |
+
#
|
1258 |
+
def may_need_128_bits(tp):
|
1259 |
+
return (isinstance(tp, model.PrimitiveType) and
|
1260 |
+
tp.name == 'long double')
|
1261 |
+
#
|
1262 |
+
size_of_a = max(len(tp.args)*8, 8)
|
1263 |
+
if may_need_128_bits(tp.result):
|
1264 |
+
size_of_a = max(size_of_a, 16)
|
1265 |
+
if isinstance(tp.result, model.StructOrUnion):
|
1266 |
+
size_of_a = 'sizeof(%s) > %d ? sizeof(%s) : %d' % (
|
1267 |
+
tp.result.get_c_name(''), size_of_a,
|
1268 |
+
tp.result.get_c_name(''), size_of_a)
|
1269 |
+
prnt('%s%s' % (tag_and_space, tp.result.get_c_name(name_and_arguments)))
|
1270 |
+
prnt('{')
|
1271 |
+
prnt(' char a[%s];' % size_of_a)
|
1272 |
+
prnt(' char *p = a;')
|
1273 |
+
for i, type in enumerate(tp.args):
|
1274 |
+
arg = 'a%d' % i
|
1275 |
+
if (isinstance(type, model.StructOrUnion) or
|
1276 |
+
may_need_128_bits(type)):
|
1277 |
+
arg = '&' + arg
|
1278 |
+
type = model.PointerType(type)
|
1279 |
+
prnt(' *(%s)(p + %d) = %s;' % (type.get_c_name('*'), i*8, arg))
|
1280 |
+
prnt(' _cffi_call_python(&_cffi_externpy__%s, p);' % name)
|
1281 |
+
if not isinstance(tp.result, model.VoidType):
|
1282 |
+
prnt(' return *(%s)p;' % (tp.result.get_c_name('*'),))
|
1283 |
+
prnt('}')
|
1284 |
+
prnt()
|
1285 |
+
self._num_externpy += 1
|
1286 |
+
|
1287 |
+
def _generate_cpy_extern_python_decl(self, tp, name):
|
1288 |
+
self._extern_python_decl(tp, name, 'static ')
|
1289 |
+
|
1290 |
+
def _generate_cpy_dllexport_python_decl(self, tp, name):
|
1291 |
+
self._extern_python_decl(tp, name, 'CFFI_DLLEXPORT ')
|
1292 |
+
|
1293 |
+
def _generate_cpy_extern_python_plus_c_decl(self, tp, name):
|
1294 |
+
self._extern_python_decl(tp, name, '')
|
1295 |
+
|
1296 |
+
def _generate_cpy_extern_python_ctx(self, tp, name):
|
1297 |
+
if self.target_is_python:
|
1298 |
+
raise VerificationError(
|
1299 |
+
"cannot use 'extern \"Python\"' in the ABI mode")
|
1300 |
+
if tp.ellipsis:
|
1301 |
+
raise NotImplementedError("a vararg function is extern \"Python\"")
|
1302 |
+
type_index = self._typesdict[tp]
|
1303 |
+
type_op = CffiOp(OP_EXTERN_PYTHON, type_index)
|
1304 |
+
self._lsts["global"].append(
|
1305 |
+
GlobalExpr(name, '&_cffi_externpy__%s' % name, type_op, name))
|
1306 |
+
|
1307 |
+
_generate_cpy_dllexport_python_ctx = \
|
1308 |
+
_generate_cpy_extern_python_plus_c_ctx = \
|
1309 |
+
_generate_cpy_extern_python_ctx
|
1310 |
+
|
1311 |
+
def _print_string_literal_in_array(self, s):
|
1312 |
+
prnt = self._prnt
|
1313 |
+
prnt('// # NB. this is not a string because of a size limit in MSVC')
|
1314 |
+
if not isinstance(s, bytes): # unicode
|
1315 |
+
s = s.encode('utf-8') # -> bytes
|
1316 |
+
else:
|
1317 |
+
s.decode('utf-8') # got bytes, check for valid utf-8
|
1318 |
+
try:
|
1319 |
+
s.decode('ascii')
|
1320 |
+
except UnicodeDecodeError:
|
1321 |
+
s = b'# -*- encoding: utf8 -*-\n' + s
|
1322 |
+
for line in s.splitlines(True):
|
1323 |
+
comment = line
|
1324 |
+
if type('//') is bytes: # python2
|
1325 |
+
line = map(ord, line) # make a list of integers
|
1326 |
+
else: # python3
|
1327 |
+
# type(line) is bytes, which enumerates like a list of integers
|
1328 |
+
comment = ascii(comment)[1:-1]
|
1329 |
+
prnt(('// ' + comment).rstrip())
|
1330 |
+
printed_line = ''
|
1331 |
+
for c in line:
|
1332 |
+
if len(printed_line) >= 76:
|
1333 |
+
prnt(printed_line)
|
1334 |
+
printed_line = ''
|
1335 |
+
printed_line += '%d,' % (c,)
|
1336 |
+
prnt(printed_line)
|
1337 |
+
|
1338 |
+
# ----------
|
1339 |
+
# emitting the opcodes for individual types
|
1340 |
+
|
1341 |
+
def _emit_bytecode_VoidType(self, tp, index):
|
1342 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, PRIM_VOID)
|
1343 |
+
|
1344 |
+
def _emit_bytecode_PrimitiveType(self, tp, index):
|
1345 |
+
prim_index = PRIMITIVE_TO_INDEX[tp.name]
|
1346 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, prim_index)
|
1347 |
+
|
1348 |
+
def _emit_bytecode_UnknownIntegerType(self, tp, index):
|
1349 |
+
s = ('_cffi_prim_int(sizeof(%s), (\n'
|
1350 |
+
' ((%s)-1) | 0 /* check that %s is an integer type */\n'
|
1351 |
+
' ) <= 0)' % (tp.name, tp.name, tp.name))
|
1352 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s)
|
1353 |
+
|
1354 |
+
def _emit_bytecode_UnknownFloatType(self, tp, index):
|
1355 |
+
s = ('_cffi_prim_float(sizeof(%s) *\n'
|
1356 |
+
' (((%s)1) / 2) * 2 /* integer => 0, float => 1 */\n'
|
1357 |
+
' )' % (tp.name, tp.name))
|
1358 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s)
|
1359 |
+
|
1360 |
+
def _emit_bytecode_RawFunctionType(self, tp, index):
|
1361 |
+
self.cffi_types[index] = CffiOp(OP_FUNCTION, self._typesdict[tp.result])
|
1362 |
+
index += 1
|
1363 |
+
for tp1 in tp.args:
|
1364 |
+
realindex = self._typesdict[tp1]
|
1365 |
+
if index != realindex:
|
1366 |
+
if isinstance(tp1, model.PrimitiveType):
|
1367 |
+
self._emit_bytecode_PrimitiveType(tp1, index)
|
1368 |
+
else:
|
1369 |
+
self.cffi_types[index] = CffiOp(OP_NOOP, realindex)
|
1370 |
+
index += 1
|
1371 |
+
flags = int(tp.ellipsis)
|
1372 |
+
if tp.abi is not None:
|
1373 |
+
if tp.abi == '__stdcall':
|
1374 |
+
flags |= 2
|
1375 |
+
else:
|
1376 |
+
raise NotImplementedError("abi=%r" % (tp.abi,))
|
1377 |
+
self.cffi_types[index] = CffiOp(OP_FUNCTION_END, flags)
|
1378 |
+
|
1379 |
+
def _emit_bytecode_PointerType(self, tp, index):
|
1380 |
+
self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[tp.totype])
|
1381 |
+
|
1382 |
+
_emit_bytecode_ConstPointerType = _emit_bytecode_PointerType
|
1383 |
+
_emit_bytecode_NamedPointerType = _emit_bytecode_PointerType
|
1384 |
+
|
1385 |
+
def _emit_bytecode_FunctionPtrType(self, tp, index):
|
1386 |
+
raw = tp.as_raw_function()
|
1387 |
+
self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[raw])
|
1388 |
+
|
1389 |
+
def _emit_bytecode_ArrayType(self, tp, index):
|
1390 |
+
item_index = self._typesdict[tp.item]
|
1391 |
+
if tp.length is None:
|
1392 |
+
self.cffi_types[index] = CffiOp(OP_OPEN_ARRAY, item_index)
|
1393 |
+
elif tp.length == '...':
|
1394 |
+
raise VerificationError(
|
1395 |
+
"type %s badly placed: the '...' array length can only be "
|
1396 |
+
"used on global arrays or on fields of structures" % (
|
1397 |
+
str(tp).replace('/*...*/', '...'),))
|
1398 |
+
else:
|
1399 |
+
assert self.cffi_types[index + 1] == 'LEN'
|
1400 |
+
self.cffi_types[index] = CffiOp(OP_ARRAY, item_index)
|
1401 |
+
self.cffi_types[index + 1] = CffiOp(None, str(tp.length))
|
1402 |
+
|
1403 |
+
def _emit_bytecode_StructType(self, tp, index):
|
1404 |
+
struct_index = self._struct_unions[tp]
|
1405 |
+
self.cffi_types[index] = CffiOp(OP_STRUCT_UNION, struct_index)
|
1406 |
+
_emit_bytecode_UnionType = _emit_bytecode_StructType
|
1407 |
+
|
1408 |
+
def _emit_bytecode_EnumType(self, tp, index):
|
1409 |
+
enum_index = self._enums[tp]
|
1410 |
+
self.cffi_types[index] = CffiOp(OP_ENUM, enum_index)
|
1411 |
+
|
1412 |
+
|
1413 |
+
if sys.version_info >= (3,):
|
1414 |
+
NativeIO = io.StringIO
|
1415 |
+
else:
|
1416 |
+
class NativeIO(io.BytesIO):
|
1417 |
+
def write(self, s):
|
1418 |
+
if isinstance(s, unicode):
|
1419 |
+
s = s.encode('ascii')
|
1420 |
+
super(NativeIO, self).write(s)
|
1421 |
+
|
1422 |
+
def _is_file_like(maybefile):
|
1423 |
+
# compare to xml.etree.ElementTree._get_writer
|
1424 |
+
return hasattr(maybefile, 'write')
|
1425 |
+
|
1426 |
+
def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose):
|
1427 |
+
if verbose:
|
1428 |
+
print("generating %s" % (target_file,))
|
1429 |
+
recompiler = Recompiler(ffi, module_name,
|
1430 |
+
target_is_python=(preamble is None))
|
1431 |
+
recompiler.collect_type_table()
|
1432 |
+
recompiler.collect_step_tables()
|
1433 |
+
if _is_file_like(target_file):
|
1434 |
+
recompiler.write_source_to_f(target_file, preamble)
|
1435 |
+
return True
|
1436 |
+
f = NativeIO()
|
1437 |
+
recompiler.write_source_to_f(f, preamble)
|
1438 |
+
output = f.getvalue()
|
1439 |
+
try:
|
1440 |
+
with open(target_file, 'r') as f1:
|
1441 |
+
if f1.read(len(output) + 1) != output:
|
1442 |
+
raise IOError
|
1443 |
+
if verbose:
|
1444 |
+
print("(already up-to-date)")
|
1445 |
+
return False # already up-to-date
|
1446 |
+
except IOError:
|
1447 |
+
tmp_file = '%s.~%d' % (target_file, os.getpid())
|
1448 |
+
with open(tmp_file, 'w') as f1:
|
1449 |
+
f1.write(output)
|
1450 |
+
try:
|
1451 |
+
os.rename(tmp_file, target_file)
|
1452 |
+
except OSError:
|
1453 |
+
os.unlink(target_file)
|
1454 |
+
os.rename(tmp_file, target_file)
|
1455 |
+
return True
|
1456 |
+
|
1457 |
+
def make_c_source(ffi, module_name, preamble, target_c_file, verbose=False):
|
1458 |
+
assert preamble is not None
|
1459 |
+
return _make_c_or_py_source(ffi, module_name, preamble, target_c_file,
|
1460 |
+
verbose)
|
1461 |
+
|
1462 |
+
def make_py_source(ffi, module_name, target_py_file, verbose=False):
|
1463 |
+
return _make_c_or_py_source(ffi, module_name, None, target_py_file,
|
1464 |
+
verbose)
|
1465 |
+
|
1466 |
+
def _modname_to_file(outputdir, modname, extension):
|
1467 |
+
parts = modname.split('.')
|
1468 |
+
try:
|
1469 |
+
os.makedirs(os.path.join(outputdir, *parts[:-1]))
|
1470 |
+
except OSError:
|
1471 |
+
pass
|
1472 |
+
parts[-1] += extension
|
1473 |
+
return os.path.join(outputdir, *parts), parts
|
1474 |
+
|
1475 |
+
|
1476 |
+
# Aaargh. Distutils is not tested at all for the purpose of compiling
|
1477 |
+
# DLLs that are not extension modules. Here are some hacks to work
|
1478 |
+
# around that, in the _patch_for_*() functions...
|
1479 |
+
|
1480 |
+
def _patch_meth(patchlist, cls, name, new_meth):
|
1481 |
+
old = getattr(cls, name)
|
1482 |
+
patchlist.append((cls, name, old))
|
1483 |
+
setattr(cls, name, new_meth)
|
1484 |
+
return old
|
1485 |
+
|
1486 |
+
def _unpatch_meths(patchlist):
|
1487 |
+
for cls, name, old_meth in reversed(patchlist):
|
1488 |
+
setattr(cls, name, old_meth)
|
1489 |
+
|
1490 |
+
def _patch_for_embedding(patchlist):
|
1491 |
+
if sys.platform == 'win32':
|
1492 |
+
# we must not remove the manifest when building for embedding!
|
1493 |
+
# FUTURE: this module was removed in setuptools 74; this is likely dead code and should be removed,
|
1494 |
+
# since the toolchain it supports (VS2005-2008) is also long dead.
|
1495 |
+
from cffi._shimmed_dist_utils import MSVCCompiler
|
1496 |
+
if MSVCCompiler is not None:
|
1497 |
+
_patch_meth(patchlist, MSVCCompiler, '_remove_visual_c_ref',
|
1498 |
+
lambda self, manifest_file: manifest_file)
|
1499 |
+
|
1500 |
+
if sys.platform == 'darwin':
|
1501 |
+
# we must not make a '-bundle', but a '-dynamiclib' instead
|
1502 |
+
from cffi._shimmed_dist_utils import CCompiler
|
1503 |
+
def my_link_shared_object(self, *args, **kwds):
|
1504 |
+
if '-bundle' in self.linker_so:
|
1505 |
+
self.linker_so = list(self.linker_so)
|
1506 |
+
i = self.linker_so.index('-bundle')
|
1507 |
+
self.linker_so[i] = '-dynamiclib'
|
1508 |
+
return old_link_shared_object(self, *args, **kwds)
|
1509 |
+
old_link_shared_object = _patch_meth(patchlist, CCompiler,
|
1510 |
+
'link_shared_object',
|
1511 |
+
my_link_shared_object)
|
1512 |
+
|
1513 |
+
def _patch_for_target(patchlist, target):
|
1514 |
+
from cffi._shimmed_dist_utils import build_ext
|
1515 |
+
# if 'target' is different from '*', we need to patch some internal
|
1516 |
+
# method to just return this 'target' value, instead of having it
|
1517 |
+
# built from module_name
|
1518 |
+
if target.endswith('.*'):
|
1519 |
+
target = target[:-2]
|
1520 |
+
if sys.platform == 'win32':
|
1521 |
+
target += '.dll'
|
1522 |
+
elif sys.platform == 'darwin':
|
1523 |
+
target += '.dylib'
|
1524 |
+
else:
|
1525 |
+
target += '.so'
|
1526 |
+
_patch_meth(patchlist, build_ext, 'get_ext_filename',
|
1527 |
+
lambda self, ext_name: target)
|
1528 |
+
|
1529 |
+
|
1530 |
+
def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True,
|
1531 |
+
c_file=None, source_extension='.c', extradir=None,
|
1532 |
+
compiler_verbose=1, target=None, debug=None,
|
1533 |
+
uses_ffiplatform=True, **kwds):
|
1534 |
+
if not isinstance(module_name, str):
|
1535 |
+
module_name = module_name.encode('ascii')
|
1536 |
+
if ffi._windows_unicode:
|
1537 |
+
ffi._apply_windows_unicode(kwds)
|
1538 |
+
if preamble is not None:
|
1539 |
+
if call_c_compiler and _is_file_like(c_file):
|
1540 |
+
raise TypeError("Writing to file-like objects is not supported "
|
1541 |
+
"with call_c_compiler=True")
|
1542 |
+
embedding = (ffi._embedding is not None)
|
1543 |
+
if embedding:
|
1544 |
+
ffi._apply_embedding_fix(kwds)
|
1545 |
+
if c_file is None:
|
1546 |
+
c_file, parts = _modname_to_file(tmpdir, module_name,
|
1547 |
+
source_extension)
|
1548 |
+
if extradir:
|
1549 |
+
parts = [extradir] + parts
|
1550 |
+
ext_c_file = os.path.join(*parts)
|
1551 |
+
else:
|
1552 |
+
ext_c_file = c_file
|
1553 |
+
#
|
1554 |
+
if target is None:
|
1555 |
+
if embedding:
|
1556 |
+
target = '%s.*' % module_name
|
1557 |
+
else:
|
1558 |
+
target = '*'
|
1559 |
+
#
|
1560 |
+
if uses_ffiplatform:
|
1561 |
+
ext = ffiplatform.get_extension(ext_c_file, module_name, **kwds)
|
1562 |
+
else:
|
1563 |
+
ext = None
|
1564 |
+
updated = make_c_source(ffi, module_name, preamble, c_file,
|
1565 |
+
verbose=compiler_verbose)
|
1566 |
+
if call_c_compiler:
|
1567 |
+
patchlist = []
|
1568 |
+
cwd = os.getcwd()
|
1569 |
+
try:
|
1570 |
+
if embedding:
|
1571 |
+
_patch_for_embedding(patchlist)
|
1572 |
+
if target != '*':
|
1573 |
+
_patch_for_target(patchlist, target)
|
1574 |
+
if compiler_verbose:
|
1575 |
+
if tmpdir == '.':
|
1576 |
+
msg = 'the current directory is'
|
1577 |
+
else:
|
1578 |
+
msg = 'setting the current directory to'
|
1579 |
+
print('%s %r' % (msg, os.path.abspath(tmpdir)))
|
1580 |
+
os.chdir(tmpdir)
|
1581 |
+
outputfilename = ffiplatform.compile('.', ext,
|
1582 |
+
compiler_verbose, debug)
|
1583 |
+
finally:
|
1584 |
+
os.chdir(cwd)
|
1585 |
+
_unpatch_meths(patchlist)
|
1586 |
+
return outputfilename
|
1587 |
+
else:
|
1588 |
+
return ext, updated
|
1589 |
+
else:
|
1590 |
+
if c_file is None:
|
1591 |
+
c_file, _ = _modname_to_file(tmpdir, module_name, '.py')
|
1592 |
+
updated = make_py_source(ffi, module_name, c_file,
|
1593 |
+
verbose=compiler_verbose)
|
1594 |
+
if call_c_compiler:
|
1595 |
+
return c_file
|
1596 |
+
else:
|
1597 |
+
return None, updated
|
1598 |
+
|
cffi/setuptools_ext.py
ADDED
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
|
4 |
+
try:
|
5 |
+
basestring
|
6 |
+
except NameError:
|
7 |
+
# Python 3.x
|
8 |
+
basestring = str
|
9 |
+
|
10 |
+
def error(msg):
|
11 |
+
from cffi._shimmed_dist_utils import DistutilsSetupError
|
12 |
+
raise DistutilsSetupError(msg)
|
13 |
+
|
14 |
+
|
15 |
+
def execfile(filename, glob):
|
16 |
+
# We use execfile() (here rewritten for Python 3) instead of
|
17 |
+
# __import__() to load the build script. The problem with
|
18 |
+
# a normal import is that in some packages, the intermediate
|
19 |
+
# __init__.py files may already try to import the file that
|
20 |
+
# we are generating.
|
21 |
+
with open(filename) as f:
|
22 |
+
src = f.read()
|
23 |
+
src += '\n' # Python 2.6 compatibility
|
24 |
+
code = compile(src, filename, 'exec')
|
25 |
+
exec(code, glob, glob)
|
26 |
+
|
27 |
+
|
28 |
+
def add_cffi_module(dist, mod_spec):
|
29 |
+
from cffi.api import FFI
|
30 |
+
|
31 |
+
if not isinstance(mod_spec, basestring):
|
32 |
+
error("argument to 'cffi_modules=...' must be a str or a list of str,"
|
33 |
+
" not %r" % (type(mod_spec).__name__,))
|
34 |
+
mod_spec = str(mod_spec)
|
35 |
+
try:
|
36 |
+
build_file_name, ffi_var_name = mod_spec.split(':')
|
37 |
+
except ValueError:
|
38 |
+
error("%r must be of the form 'path/build.py:ffi_variable'" %
|
39 |
+
(mod_spec,))
|
40 |
+
if not os.path.exists(build_file_name):
|
41 |
+
ext = ''
|
42 |
+
rewritten = build_file_name.replace('.', '/') + '.py'
|
43 |
+
if os.path.exists(rewritten):
|
44 |
+
ext = ' (rewrite cffi_modules to [%r])' % (
|
45 |
+
rewritten + ':' + ffi_var_name,)
|
46 |
+
error("%r does not name an existing file%s" % (build_file_name, ext))
|
47 |
+
|
48 |
+
mod_vars = {'__name__': '__cffi__', '__file__': build_file_name}
|
49 |
+
execfile(build_file_name, mod_vars)
|
50 |
+
|
51 |
+
try:
|
52 |
+
ffi = mod_vars[ffi_var_name]
|
53 |
+
except KeyError:
|
54 |
+
error("%r: object %r not found in module" % (mod_spec,
|
55 |
+
ffi_var_name))
|
56 |
+
if not isinstance(ffi, FFI):
|
57 |
+
ffi = ffi() # maybe it's a function instead of directly an ffi
|
58 |
+
if not isinstance(ffi, FFI):
|
59 |
+
error("%r is not an FFI instance (got %r)" % (mod_spec,
|
60 |
+
type(ffi).__name__))
|
61 |
+
if not hasattr(ffi, '_assigned_source'):
|
62 |
+
error("%r: the set_source() method was not called" % (mod_spec,))
|
63 |
+
module_name, source, source_extension, kwds = ffi._assigned_source
|
64 |
+
if ffi._windows_unicode:
|
65 |
+
kwds = kwds.copy()
|
66 |
+
ffi._apply_windows_unicode(kwds)
|
67 |
+
|
68 |
+
if source is None:
|
69 |
+
_add_py_module(dist, ffi, module_name)
|
70 |
+
else:
|
71 |
+
_add_c_module(dist, ffi, module_name, source, source_extension, kwds)
|
72 |
+
|
73 |
+
def _set_py_limited_api(Extension, kwds):
|
74 |
+
"""
|
75 |
+
Add py_limited_api to kwds if setuptools >= 26 is in use.
|
76 |
+
Do not alter the setting if it already exists.
|
77 |
+
Setuptools takes care of ignoring the flag on Python 2 and PyPy.
|
78 |
+
|
79 |
+
CPython itself should ignore the flag in a debugging version
|
80 |
+
(by not listing .abi3.so in the extensions it supports), but
|
81 |
+
it doesn't so far, creating troubles. That's why we check
|
82 |
+
for "not hasattr(sys, 'gettotalrefcount')" (the 2.7 compatible equivalent
|
83 |
+
of 'd' not in sys.abiflags). (http://bugs.python.org/issue28401)
|
84 |
+
|
85 |
+
On Windows, with CPython <= 3.4, it's better not to use py_limited_api
|
86 |
+
because virtualenv *still* doesn't copy PYTHON3.DLL on these versions.
|
87 |
+
Recently (2020) we started shipping only >= 3.5 wheels, though. So
|
88 |
+
we'll give it another try and set py_limited_api on Windows >= 3.5.
|
89 |
+
"""
|
90 |
+
from cffi import recompiler
|
91 |
+
|
92 |
+
if ('py_limited_api' not in kwds and not hasattr(sys, 'gettotalrefcount')
|
93 |
+
and recompiler.USE_LIMITED_API):
|
94 |
+
import setuptools
|
95 |
+
try:
|
96 |
+
setuptools_major_version = int(setuptools.__version__.partition('.')[0])
|
97 |
+
if setuptools_major_version >= 26:
|
98 |
+
kwds['py_limited_api'] = True
|
99 |
+
except ValueError: # certain development versions of setuptools
|
100 |
+
# If we don't know the version number of setuptools, we
|
101 |
+
# try to set 'py_limited_api' anyway. At worst, we get a
|
102 |
+
# warning.
|
103 |
+
kwds['py_limited_api'] = True
|
104 |
+
return kwds
|
105 |
+
|
106 |
+
def _add_c_module(dist, ffi, module_name, source, source_extension, kwds):
|
107 |
+
# We are a setuptools extension. Need this build_ext for py_limited_api.
|
108 |
+
from setuptools.command.build_ext import build_ext
|
109 |
+
from cffi._shimmed_dist_utils import Extension, log, mkpath
|
110 |
+
from cffi import recompiler
|
111 |
+
|
112 |
+
allsources = ['$PLACEHOLDER']
|
113 |
+
allsources.extend(kwds.pop('sources', []))
|
114 |
+
kwds = _set_py_limited_api(Extension, kwds)
|
115 |
+
ext = Extension(name=module_name, sources=allsources, **kwds)
|
116 |
+
|
117 |
+
def make_mod(tmpdir, pre_run=None):
|
118 |
+
c_file = os.path.join(tmpdir, module_name + source_extension)
|
119 |
+
log.info("generating cffi module %r" % c_file)
|
120 |
+
mkpath(tmpdir)
|
121 |
+
# a setuptools-only, API-only hook: called with the "ext" and "ffi"
|
122 |
+
# arguments just before we turn the ffi into C code. To use it,
|
123 |
+
# subclass the 'distutils.command.build_ext.build_ext' class and
|
124 |
+
# add a method 'def pre_run(self, ext, ffi)'.
|
125 |
+
if pre_run is not None:
|
126 |
+
pre_run(ext, ffi)
|
127 |
+
updated = recompiler.make_c_source(ffi, module_name, source, c_file)
|
128 |
+
if not updated:
|
129 |
+
log.info("already up-to-date")
|
130 |
+
return c_file
|
131 |
+
|
132 |
+
if dist.ext_modules is None:
|
133 |
+
dist.ext_modules = []
|
134 |
+
dist.ext_modules.append(ext)
|
135 |
+
|
136 |
+
base_class = dist.cmdclass.get('build_ext', build_ext)
|
137 |
+
class build_ext_make_mod(base_class):
|
138 |
+
def run(self):
|
139 |
+
if ext.sources[0] == '$PLACEHOLDER':
|
140 |
+
pre_run = getattr(self, 'pre_run', None)
|
141 |
+
ext.sources[0] = make_mod(self.build_temp, pre_run)
|
142 |
+
base_class.run(self)
|
143 |
+
dist.cmdclass['build_ext'] = build_ext_make_mod
|
144 |
+
# NB. multiple runs here will create multiple 'build_ext_make_mod'
|
145 |
+
# classes. Even in this case the 'build_ext' command should be
|
146 |
+
# run once; but just in case, the logic above does nothing if
|
147 |
+
# called again.
|
148 |
+
|
149 |
+
|
150 |
+
def _add_py_module(dist, ffi, module_name):
|
151 |
+
from setuptools.command.build_py import build_py
|
152 |
+
from setuptools.command.build_ext import build_ext
|
153 |
+
from cffi._shimmed_dist_utils import log, mkpath
|
154 |
+
from cffi import recompiler
|
155 |
+
|
156 |
+
def generate_mod(py_file):
|
157 |
+
log.info("generating cffi module %r" % py_file)
|
158 |
+
mkpath(os.path.dirname(py_file))
|
159 |
+
updated = recompiler.make_py_source(ffi, module_name, py_file)
|
160 |
+
if not updated:
|
161 |
+
log.info("already up-to-date")
|
162 |
+
|
163 |
+
base_class = dist.cmdclass.get('build_py', build_py)
|
164 |
+
class build_py_make_mod(base_class):
|
165 |
+
def run(self):
|
166 |
+
base_class.run(self)
|
167 |
+
module_path = module_name.split('.')
|
168 |
+
module_path[-1] += '.py'
|
169 |
+
generate_mod(os.path.join(self.build_lib, *module_path))
|
170 |
+
def get_source_files(self):
|
171 |
+
# This is called from 'setup.py sdist' only. Exclude
|
172 |
+
# the generate .py module in this case.
|
173 |
+
saved_py_modules = self.py_modules
|
174 |
+
try:
|
175 |
+
if saved_py_modules:
|
176 |
+
self.py_modules = [m for m in saved_py_modules
|
177 |
+
if m != module_name]
|
178 |
+
return base_class.get_source_files(self)
|
179 |
+
finally:
|
180 |
+
self.py_modules = saved_py_modules
|
181 |
+
dist.cmdclass['build_py'] = build_py_make_mod
|
182 |
+
|
183 |
+
# distutils and setuptools have no notion I could find of a
|
184 |
+
# generated python module. If we don't add module_name to
|
185 |
+
# dist.py_modules, then things mostly work but there are some
|
186 |
+
# combination of options (--root and --record) that will miss
|
187 |
+
# the module. So we add it here, which gives a few apparently
|
188 |
+
# harmless warnings about not finding the file outside the
|
189 |
+
# build directory.
|
190 |
+
# Then we need to hack more in get_source_files(); see above.
|
191 |
+
if dist.py_modules is None:
|
192 |
+
dist.py_modules = []
|
193 |
+
dist.py_modules.append(module_name)
|
194 |
+
|
195 |
+
# the following is only for "build_ext -i"
|
196 |
+
base_class_2 = dist.cmdclass.get('build_ext', build_ext)
|
197 |
+
class build_ext_make_mod(base_class_2):
|
198 |
+
def run(self):
|
199 |
+
base_class_2.run(self)
|
200 |
+
if self.inplace:
|
201 |
+
# from get_ext_fullpath() in distutils/command/build_ext.py
|
202 |
+
module_path = module_name.split('.')
|
203 |
+
package = '.'.join(module_path[:-1])
|
204 |
+
build_py = self.get_finalized_command('build_py')
|
205 |
+
package_dir = build_py.get_package_dir(package)
|
206 |
+
file_name = module_path[-1] + '.py'
|
207 |
+
generate_mod(os.path.join(package_dir, file_name))
|
208 |
+
dist.cmdclass['build_ext'] = build_ext_make_mod
|
209 |
+
|
210 |
+
def cffi_modules(dist, attr, value):
|
211 |
+
assert attr == 'cffi_modules'
|
212 |
+
if isinstance(value, basestring):
|
213 |
+
value = [value]
|
214 |
+
|
215 |
+
for cffi_module in value:
|
216 |
+
add_cffi_module(dist, cffi_module)
|
cffi/vengine_cpy.py
ADDED
@@ -0,0 +1,1084 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# DEPRECATED: implementation for ffi.verify()
|
3 |
+
#
|
4 |
+
import sys
|
5 |
+
from . import model
|
6 |
+
from .error import VerificationError
|
7 |
+
from . import _imp_emulation as imp
|
8 |
+
|
9 |
+
|
10 |
+
class VCPythonEngine(object):
|
11 |
+
_class_key = 'x'
|
12 |
+
_gen_python_module = True
|
13 |
+
|
14 |
+
def __init__(self, verifier):
|
15 |
+
self.verifier = verifier
|
16 |
+
self.ffi = verifier.ffi
|
17 |
+
self._struct_pending_verification = {}
|
18 |
+
self._types_of_builtin_functions = {}
|
19 |
+
|
20 |
+
def patch_extension_kwds(self, kwds):
|
21 |
+
pass
|
22 |
+
|
23 |
+
def find_module(self, module_name, path, so_suffixes):
|
24 |
+
try:
|
25 |
+
f, filename, descr = imp.find_module(module_name, path)
|
26 |
+
except ImportError:
|
27 |
+
return None
|
28 |
+
if f is not None:
|
29 |
+
f.close()
|
30 |
+
# Note that after a setuptools installation, there are both .py
|
31 |
+
# and .so files with the same basename. The code here relies on
|
32 |
+
# imp.find_module() locating the .so in priority.
|
33 |
+
if descr[0] not in so_suffixes:
|
34 |
+
return None
|
35 |
+
return filename
|
36 |
+
|
37 |
+
def collect_types(self):
|
38 |
+
self._typesdict = {}
|
39 |
+
self._generate("collecttype")
|
40 |
+
|
41 |
+
def _prnt(self, what=''):
|
42 |
+
self._f.write(what + '\n')
|
43 |
+
|
44 |
+
def _gettypenum(self, type):
|
45 |
+
# a KeyError here is a bug. please report it! :-)
|
46 |
+
return self._typesdict[type]
|
47 |
+
|
48 |
+
def _do_collect_type(self, tp):
|
49 |
+
if ((not isinstance(tp, model.PrimitiveType)
|
50 |
+
or tp.name == 'long double')
|
51 |
+
and tp not in self._typesdict):
|
52 |
+
num = len(self._typesdict)
|
53 |
+
self._typesdict[tp] = num
|
54 |
+
|
55 |
+
def write_source_to_f(self):
|
56 |
+
self.collect_types()
|
57 |
+
#
|
58 |
+
# The new module will have a _cffi_setup() function that receives
|
59 |
+
# objects from the ffi world, and that calls some setup code in
|
60 |
+
# the module. This setup code is split in several independent
|
61 |
+
# functions, e.g. one per constant. The functions are "chained"
|
62 |
+
# by ending in a tail call to each other.
|
63 |
+
#
|
64 |
+
# This is further split in two chained lists, depending on if we
|
65 |
+
# can do it at import-time or if we must wait for _cffi_setup() to
|
66 |
+
# provide us with the <ctype> objects. This is needed because we
|
67 |
+
# need the values of the enum constants in order to build the
|
68 |
+
# <ctype 'enum'> that we may have to pass to _cffi_setup().
|
69 |
+
#
|
70 |
+
# The following two 'chained_list_constants' items contains
|
71 |
+
# the head of these two chained lists, as a string that gives the
|
72 |
+
# call to do, if any.
|
73 |
+
self._chained_list_constants = ['((void)lib,0)', '((void)lib,0)']
|
74 |
+
#
|
75 |
+
prnt = self._prnt
|
76 |
+
# first paste some standard set of lines that are mostly '#define'
|
77 |
+
prnt(cffimod_header)
|
78 |
+
prnt()
|
79 |
+
# then paste the C source given by the user, verbatim.
|
80 |
+
prnt(self.verifier.preamble)
|
81 |
+
prnt()
|
82 |
+
#
|
83 |
+
# call generate_cpy_xxx_decl(), for every xxx found from
|
84 |
+
# ffi._parser._declarations. This generates all the functions.
|
85 |
+
self._generate("decl")
|
86 |
+
#
|
87 |
+
# implement the function _cffi_setup_custom() as calling the
|
88 |
+
# head of the chained list.
|
89 |
+
self._generate_setup_custom()
|
90 |
+
prnt()
|
91 |
+
#
|
92 |
+
# produce the method table, including the entries for the
|
93 |
+
# generated Python->C function wrappers, which are done
|
94 |
+
# by generate_cpy_function_method().
|
95 |
+
prnt('static PyMethodDef _cffi_methods[] = {')
|
96 |
+
self._generate("method")
|
97 |
+
prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL},')
|
98 |
+
prnt(' {NULL, NULL, 0, NULL} /* Sentinel */')
|
99 |
+
prnt('};')
|
100 |
+
prnt()
|
101 |
+
#
|
102 |
+
# standard init.
|
103 |
+
modname = self.verifier.get_module_name()
|
104 |
+
constants = self._chained_list_constants[False]
|
105 |
+
prnt('#if PY_MAJOR_VERSION >= 3')
|
106 |
+
prnt()
|
107 |
+
prnt('static struct PyModuleDef _cffi_module_def = {')
|
108 |
+
prnt(' PyModuleDef_HEAD_INIT,')
|
109 |
+
prnt(' "%s",' % modname)
|
110 |
+
prnt(' NULL,')
|
111 |
+
prnt(' -1,')
|
112 |
+
prnt(' _cffi_methods,')
|
113 |
+
prnt(' NULL, NULL, NULL, NULL')
|
114 |
+
prnt('};')
|
115 |
+
prnt()
|
116 |
+
prnt('PyMODINIT_FUNC')
|
117 |
+
prnt('PyInit_%s(void)' % modname)
|
118 |
+
prnt('{')
|
119 |
+
prnt(' PyObject *lib;')
|
120 |
+
prnt(' lib = PyModule_Create(&_cffi_module_def);')
|
121 |
+
prnt(' if (lib == NULL)')
|
122 |
+
prnt(' return NULL;')
|
123 |
+
prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,))
|
124 |
+
prnt(' Py_DECREF(lib);')
|
125 |
+
prnt(' return NULL;')
|
126 |
+
prnt(' }')
|
127 |
+
prnt(' return lib;')
|
128 |
+
prnt('}')
|
129 |
+
prnt()
|
130 |
+
prnt('#else')
|
131 |
+
prnt()
|
132 |
+
prnt('PyMODINIT_FUNC')
|
133 |
+
prnt('init%s(void)' % modname)
|
134 |
+
prnt('{')
|
135 |
+
prnt(' PyObject *lib;')
|
136 |
+
prnt(' lib = Py_InitModule("%s", _cffi_methods);' % modname)
|
137 |
+
prnt(' if (lib == NULL)')
|
138 |
+
prnt(' return;')
|
139 |
+
prnt(' if (%s < 0 || _cffi_init() < 0)' % (constants,))
|
140 |
+
prnt(' return;')
|
141 |
+
prnt(' return;')
|
142 |
+
prnt('}')
|
143 |
+
prnt()
|
144 |
+
prnt('#endif')
|
145 |
+
|
146 |
+
def load_library(self, flags=None):
|
147 |
+
# XXX review all usages of 'self' here!
|
148 |
+
# import it as a new extension module
|
149 |
+
imp.acquire_lock()
|
150 |
+
try:
|
151 |
+
if hasattr(sys, "getdlopenflags"):
|
152 |
+
previous_flags = sys.getdlopenflags()
|
153 |
+
try:
|
154 |
+
if hasattr(sys, "setdlopenflags") and flags is not None:
|
155 |
+
sys.setdlopenflags(flags)
|
156 |
+
module = imp.load_dynamic(self.verifier.get_module_name(),
|
157 |
+
self.verifier.modulefilename)
|
158 |
+
except ImportError as e:
|
159 |
+
error = "importing %r: %s" % (self.verifier.modulefilename, e)
|
160 |
+
raise VerificationError(error)
|
161 |
+
finally:
|
162 |
+
if hasattr(sys, "setdlopenflags"):
|
163 |
+
sys.setdlopenflags(previous_flags)
|
164 |
+
finally:
|
165 |
+
imp.release_lock()
|
166 |
+
#
|
167 |
+
# call loading_cpy_struct() to get the struct layout inferred by
|
168 |
+
# the C compiler
|
169 |
+
self._load(module, 'loading')
|
170 |
+
#
|
171 |
+
# the C code will need the <ctype> objects. Collect them in
|
172 |
+
# order in a list.
|
173 |
+
revmapping = dict([(value, key)
|
174 |
+
for (key, value) in self._typesdict.items()])
|
175 |
+
lst = [revmapping[i] for i in range(len(revmapping))]
|
176 |
+
lst = list(map(self.ffi._get_cached_btype, lst))
|
177 |
+
#
|
178 |
+
# build the FFILibrary class and instance and call _cffi_setup().
|
179 |
+
# this will set up some fields like '_cffi_types', and only then
|
180 |
+
# it will invoke the chained list of functions that will really
|
181 |
+
# build (notably) the constant objects, as <cdata> if they are
|
182 |
+
# pointers, and store them as attributes on the 'library' object.
|
183 |
+
class FFILibrary(object):
|
184 |
+
_cffi_python_module = module
|
185 |
+
_cffi_ffi = self.ffi
|
186 |
+
_cffi_dir = []
|
187 |
+
def __dir__(self):
|
188 |
+
return FFILibrary._cffi_dir + list(self.__dict__)
|
189 |
+
library = FFILibrary()
|
190 |
+
if module._cffi_setup(lst, VerificationError, library):
|
191 |
+
import warnings
|
192 |
+
warnings.warn("reimporting %r might overwrite older definitions"
|
193 |
+
% (self.verifier.get_module_name()))
|
194 |
+
#
|
195 |
+
# finally, call the loaded_cpy_xxx() functions. This will perform
|
196 |
+
# the final adjustments, like copying the Python->C wrapper
|
197 |
+
# functions from the module to the 'library' object, and setting
|
198 |
+
# up the FFILibrary class with properties for the global C variables.
|
199 |
+
self._load(module, 'loaded', library=library)
|
200 |
+
module._cffi_original_ffi = self.ffi
|
201 |
+
module._cffi_types_of_builtin_funcs = self._types_of_builtin_functions
|
202 |
+
return library
|
203 |
+
|
204 |
+
def _get_declarations(self):
|
205 |
+
lst = [(key, tp) for (key, (tp, qual)) in
|
206 |
+
self.ffi._parser._declarations.items()]
|
207 |
+
lst.sort()
|
208 |
+
return lst
|
209 |
+
|
210 |
+
def _generate(self, step_name):
|
211 |
+
for name, tp in self._get_declarations():
|
212 |
+
kind, realname = name.split(' ', 1)
|
213 |
+
try:
|
214 |
+
method = getattr(self, '_generate_cpy_%s_%s' % (kind,
|
215 |
+
step_name))
|
216 |
+
except AttributeError:
|
217 |
+
raise VerificationError(
|
218 |
+
"not implemented in verify(): %r" % name)
|
219 |
+
try:
|
220 |
+
method(tp, realname)
|
221 |
+
except Exception as e:
|
222 |
+
model.attach_exception_info(e, name)
|
223 |
+
raise
|
224 |
+
|
225 |
+
def _load(self, module, step_name, **kwds):
|
226 |
+
for name, tp in self._get_declarations():
|
227 |
+
kind, realname = name.split(' ', 1)
|
228 |
+
method = getattr(self, '_%s_cpy_%s' % (step_name, kind))
|
229 |
+
try:
|
230 |
+
method(tp, realname, module, **kwds)
|
231 |
+
except Exception as e:
|
232 |
+
model.attach_exception_info(e, name)
|
233 |
+
raise
|
234 |
+
|
235 |
+
def _generate_nothing(self, tp, name):
|
236 |
+
pass
|
237 |
+
|
238 |
+
def _loaded_noop(self, tp, name, module, **kwds):
|
239 |
+
pass
|
240 |
+
|
241 |
+
# ----------
|
242 |
+
|
243 |
+
def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode):
|
244 |
+
extraarg = ''
|
245 |
+
if isinstance(tp, model.PrimitiveType):
|
246 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
247 |
+
converter = '_cffi_to_c_int'
|
248 |
+
extraarg = ', %s' % tp.name
|
249 |
+
elif tp.is_complex_type():
|
250 |
+
raise VerificationError(
|
251 |
+
"not implemented in verify(): complex types")
|
252 |
+
else:
|
253 |
+
converter = '(%s)_cffi_to_c_%s' % (tp.get_c_name(''),
|
254 |
+
tp.name.replace(' ', '_'))
|
255 |
+
errvalue = '-1'
|
256 |
+
#
|
257 |
+
elif isinstance(tp, model.PointerType):
|
258 |
+
self._convert_funcarg_to_c_ptr_or_array(tp, fromvar,
|
259 |
+
tovar, errcode)
|
260 |
+
return
|
261 |
+
#
|
262 |
+
elif isinstance(tp, (model.StructOrUnion, model.EnumType)):
|
263 |
+
# a struct (not a struct pointer) as a function argument
|
264 |
+
self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)'
|
265 |
+
% (tovar, self._gettypenum(tp), fromvar))
|
266 |
+
self._prnt(' %s;' % errcode)
|
267 |
+
return
|
268 |
+
#
|
269 |
+
elif isinstance(tp, model.FunctionPtrType):
|
270 |
+
converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('')
|
271 |
+
extraarg = ', _cffi_type(%d)' % self._gettypenum(tp)
|
272 |
+
errvalue = 'NULL'
|
273 |
+
#
|
274 |
+
else:
|
275 |
+
raise NotImplementedError(tp)
|
276 |
+
#
|
277 |
+
self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg))
|
278 |
+
self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % (
|
279 |
+
tovar, tp.get_c_name(''), errvalue))
|
280 |
+
self._prnt(' %s;' % errcode)
|
281 |
+
|
282 |
+
def _extra_local_variables(self, tp, localvars, freelines):
|
283 |
+
if isinstance(tp, model.PointerType):
|
284 |
+
localvars.add('Py_ssize_t datasize')
|
285 |
+
localvars.add('struct _cffi_freeme_s *large_args_free = NULL')
|
286 |
+
freelines.add('if (large_args_free != NULL)'
|
287 |
+
' _cffi_free_array_arguments(large_args_free);')
|
288 |
+
|
289 |
+
def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode):
|
290 |
+
self._prnt(' datasize = _cffi_prepare_pointer_call_argument(')
|
291 |
+
self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % (
|
292 |
+
self._gettypenum(tp), fromvar, tovar))
|
293 |
+
self._prnt(' if (datasize != 0) {')
|
294 |
+
self._prnt(' %s = ((size_t)datasize) <= 640 ? '
|
295 |
+
'alloca((size_t)datasize) : NULL;' % (tovar,))
|
296 |
+
self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, '
|
297 |
+
'(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar))
|
298 |
+
self._prnt(' datasize, &large_args_free) < 0)')
|
299 |
+
self._prnt(' %s;' % errcode)
|
300 |
+
self._prnt(' }')
|
301 |
+
|
302 |
+
def _convert_expr_from_c(self, tp, var, context):
|
303 |
+
if isinstance(tp, model.PrimitiveType):
|
304 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
305 |
+
return '_cffi_from_c_int(%s, %s)' % (var, tp.name)
|
306 |
+
elif tp.name != 'long double':
|
307 |
+
return '_cffi_from_c_%s(%s)' % (tp.name.replace(' ', '_'), var)
|
308 |
+
else:
|
309 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
310 |
+
var, self._gettypenum(tp))
|
311 |
+
elif isinstance(tp, (model.PointerType, model.FunctionPtrType)):
|
312 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
313 |
+
var, self._gettypenum(tp))
|
314 |
+
elif isinstance(tp, model.ArrayType):
|
315 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
316 |
+
var, self._gettypenum(model.PointerType(tp.item)))
|
317 |
+
elif isinstance(tp, model.StructOrUnion):
|
318 |
+
if tp.fldnames is None:
|
319 |
+
raise TypeError("'%s' is used as %s, but is opaque" % (
|
320 |
+
tp._get_c_name(), context))
|
321 |
+
return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % (
|
322 |
+
var, self._gettypenum(tp))
|
323 |
+
elif isinstance(tp, model.EnumType):
|
324 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
325 |
+
var, self._gettypenum(tp))
|
326 |
+
else:
|
327 |
+
raise NotImplementedError(tp)
|
328 |
+
|
329 |
+
# ----------
|
330 |
+
# typedefs: generates no code so far
|
331 |
+
|
332 |
+
_generate_cpy_typedef_collecttype = _generate_nothing
|
333 |
+
_generate_cpy_typedef_decl = _generate_nothing
|
334 |
+
_generate_cpy_typedef_method = _generate_nothing
|
335 |
+
_loading_cpy_typedef = _loaded_noop
|
336 |
+
_loaded_cpy_typedef = _loaded_noop
|
337 |
+
|
338 |
+
# ----------
|
339 |
+
# function declarations
|
340 |
+
|
341 |
+
def _generate_cpy_function_collecttype(self, tp, name):
|
342 |
+
assert isinstance(tp, model.FunctionPtrType)
|
343 |
+
if tp.ellipsis:
|
344 |
+
self._do_collect_type(tp)
|
345 |
+
else:
|
346 |
+
# don't call _do_collect_type(tp) in this common case,
|
347 |
+
# otherwise test_autofilled_struct_as_argument fails
|
348 |
+
for type in tp.args:
|
349 |
+
self._do_collect_type(type)
|
350 |
+
self._do_collect_type(tp.result)
|
351 |
+
|
352 |
+
def _generate_cpy_function_decl(self, tp, name):
|
353 |
+
assert isinstance(tp, model.FunctionPtrType)
|
354 |
+
if tp.ellipsis:
|
355 |
+
# cannot support vararg functions better than this: check for its
|
356 |
+
# exact type (including the fixed arguments), and build it as a
|
357 |
+
# constant function pointer (no CPython wrapper)
|
358 |
+
self._generate_cpy_const(False, name, tp)
|
359 |
+
return
|
360 |
+
prnt = self._prnt
|
361 |
+
numargs = len(tp.args)
|
362 |
+
if numargs == 0:
|
363 |
+
argname = 'noarg'
|
364 |
+
elif numargs == 1:
|
365 |
+
argname = 'arg0'
|
366 |
+
else:
|
367 |
+
argname = 'args'
|
368 |
+
prnt('static PyObject *')
|
369 |
+
prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname))
|
370 |
+
prnt('{')
|
371 |
+
#
|
372 |
+
context = 'argument of %s' % name
|
373 |
+
for i, type in enumerate(tp.args):
|
374 |
+
prnt(' %s;' % type.get_c_name(' x%d' % i, context))
|
375 |
+
#
|
376 |
+
localvars = set()
|
377 |
+
freelines = set()
|
378 |
+
for type in tp.args:
|
379 |
+
self._extra_local_variables(type, localvars, freelines)
|
380 |
+
for decl in sorted(localvars):
|
381 |
+
prnt(' %s;' % (decl,))
|
382 |
+
#
|
383 |
+
if not isinstance(tp.result, model.VoidType):
|
384 |
+
result_code = 'result = '
|
385 |
+
context = 'result of %s' % name
|
386 |
+
prnt(' %s;' % tp.result.get_c_name(' result', context))
|
387 |
+
prnt(' PyObject *pyresult;')
|
388 |
+
else:
|
389 |
+
result_code = ''
|
390 |
+
#
|
391 |
+
if len(tp.args) > 1:
|
392 |
+
rng = range(len(tp.args))
|
393 |
+
for i in rng:
|
394 |
+
prnt(' PyObject *arg%d;' % i)
|
395 |
+
prnt()
|
396 |
+
prnt(' if (!PyArg_ParseTuple(args, "%s:%s", %s))' % (
|
397 |
+
'O' * numargs, name, ', '.join(['&arg%d' % i for i in rng])))
|
398 |
+
prnt(' return NULL;')
|
399 |
+
prnt()
|
400 |
+
#
|
401 |
+
for i, type in enumerate(tp.args):
|
402 |
+
self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i,
|
403 |
+
'return NULL')
|
404 |
+
prnt()
|
405 |
+
#
|
406 |
+
prnt(' Py_BEGIN_ALLOW_THREADS')
|
407 |
+
prnt(' _cffi_restore_errno();')
|
408 |
+
prnt(' { %s%s(%s); }' % (
|
409 |
+
result_code, name,
|
410 |
+
', '.join(['x%d' % i for i in range(len(tp.args))])))
|
411 |
+
prnt(' _cffi_save_errno();')
|
412 |
+
prnt(' Py_END_ALLOW_THREADS')
|
413 |
+
prnt()
|
414 |
+
#
|
415 |
+
prnt(' (void)self; /* unused */')
|
416 |
+
if numargs == 0:
|
417 |
+
prnt(' (void)noarg; /* unused */')
|
418 |
+
if result_code:
|
419 |
+
prnt(' pyresult = %s;' %
|
420 |
+
self._convert_expr_from_c(tp.result, 'result', 'result type'))
|
421 |
+
for freeline in freelines:
|
422 |
+
prnt(' ' + freeline)
|
423 |
+
prnt(' return pyresult;')
|
424 |
+
else:
|
425 |
+
for freeline in freelines:
|
426 |
+
prnt(' ' + freeline)
|
427 |
+
prnt(' Py_INCREF(Py_None);')
|
428 |
+
prnt(' return Py_None;')
|
429 |
+
prnt('}')
|
430 |
+
prnt()
|
431 |
+
|
432 |
+
def _generate_cpy_function_method(self, tp, name):
|
433 |
+
if tp.ellipsis:
|
434 |
+
return
|
435 |
+
numargs = len(tp.args)
|
436 |
+
if numargs == 0:
|
437 |
+
meth = 'METH_NOARGS'
|
438 |
+
elif numargs == 1:
|
439 |
+
meth = 'METH_O'
|
440 |
+
else:
|
441 |
+
meth = 'METH_VARARGS'
|
442 |
+
self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth))
|
443 |
+
|
444 |
+
_loading_cpy_function = _loaded_noop
|
445 |
+
|
446 |
+
def _loaded_cpy_function(self, tp, name, module, library):
|
447 |
+
if tp.ellipsis:
|
448 |
+
return
|
449 |
+
func = getattr(module, name)
|
450 |
+
setattr(library, name, func)
|
451 |
+
self._types_of_builtin_functions[func] = tp
|
452 |
+
|
453 |
+
# ----------
|
454 |
+
# named structs
|
455 |
+
|
456 |
+
_generate_cpy_struct_collecttype = _generate_nothing
|
457 |
+
def _generate_cpy_struct_decl(self, tp, name):
|
458 |
+
assert name == tp.name
|
459 |
+
self._generate_struct_or_union_decl(tp, 'struct', name)
|
460 |
+
def _generate_cpy_struct_method(self, tp, name):
|
461 |
+
self._generate_struct_or_union_method(tp, 'struct', name)
|
462 |
+
def _loading_cpy_struct(self, tp, name, module):
|
463 |
+
self._loading_struct_or_union(tp, 'struct', name, module)
|
464 |
+
def _loaded_cpy_struct(self, tp, name, module, **kwds):
|
465 |
+
self._loaded_struct_or_union(tp)
|
466 |
+
|
467 |
+
_generate_cpy_union_collecttype = _generate_nothing
|
468 |
+
def _generate_cpy_union_decl(self, tp, name):
|
469 |
+
assert name == tp.name
|
470 |
+
self._generate_struct_or_union_decl(tp, 'union', name)
|
471 |
+
def _generate_cpy_union_method(self, tp, name):
|
472 |
+
self._generate_struct_or_union_method(tp, 'union', name)
|
473 |
+
def _loading_cpy_union(self, tp, name, module):
|
474 |
+
self._loading_struct_or_union(tp, 'union', name, module)
|
475 |
+
def _loaded_cpy_union(self, tp, name, module, **kwds):
|
476 |
+
self._loaded_struct_or_union(tp)
|
477 |
+
|
478 |
+
def _generate_struct_or_union_decl(self, tp, prefix, name):
|
479 |
+
if tp.fldnames is None:
|
480 |
+
return # nothing to do with opaque structs
|
481 |
+
checkfuncname = '_cffi_check_%s_%s' % (prefix, name)
|
482 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
483 |
+
cname = ('%s %s' % (prefix, name)).strip()
|
484 |
+
#
|
485 |
+
prnt = self._prnt
|
486 |
+
prnt('static void %s(%s *p)' % (checkfuncname, cname))
|
487 |
+
prnt('{')
|
488 |
+
prnt(' /* only to generate compile-time warnings or errors */')
|
489 |
+
prnt(' (void)p;')
|
490 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
491 |
+
if (isinstance(ftype, model.PrimitiveType)
|
492 |
+
and ftype.is_integer_type()) or fbitsize >= 0:
|
493 |
+
# accept all integers, but complain on float or double
|
494 |
+
prnt(' (void)((p->%s) << 1);' % fname)
|
495 |
+
else:
|
496 |
+
# only accept exactly the type declared.
|
497 |
+
try:
|
498 |
+
prnt(' { %s = &p->%s; (void)tmp; }' % (
|
499 |
+
ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
|
500 |
+
fname))
|
501 |
+
except VerificationError as e:
|
502 |
+
prnt(' /* %s */' % str(e)) # cannot verify it, ignore
|
503 |
+
prnt('}')
|
504 |
+
prnt('static PyObject *')
|
505 |
+
prnt('%s(PyObject *self, PyObject *noarg)' % (layoutfuncname,))
|
506 |
+
prnt('{')
|
507 |
+
prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname)
|
508 |
+
prnt(' static Py_ssize_t nums[] = {')
|
509 |
+
prnt(' sizeof(%s),' % cname)
|
510 |
+
prnt(' offsetof(struct _cffi_aligncheck, y),')
|
511 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
512 |
+
if fbitsize >= 0:
|
513 |
+
continue # xxx ignore fbitsize for now
|
514 |
+
prnt(' offsetof(%s, %s),' % (cname, fname))
|
515 |
+
if isinstance(ftype, model.ArrayType) and ftype.length is None:
|
516 |
+
prnt(' 0, /* %s */' % ftype._get_c_name())
|
517 |
+
else:
|
518 |
+
prnt(' sizeof(((%s *)0)->%s),' % (cname, fname))
|
519 |
+
prnt(' -1')
|
520 |
+
prnt(' };')
|
521 |
+
prnt(' (void)self; /* unused */')
|
522 |
+
prnt(' (void)noarg; /* unused */')
|
523 |
+
prnt(' return _cffi_get_struct_layout(nums);')
|
524 |
+
prnt(' /* the next line is not executed, but compiled */')
|
525 |
+
prnt(' %s(0);' % (checkfuncname,))
|
526 |
+
prnt('}')
|
527 |
+
prnt()
|
528 |
+
|
529 |
+
def _generate_struct_or_union_method(self, tp, prefix, name):
|
530 |
+
if tp.fldnames is None:
|
531 |
+
return # nothing to do with opaque structs
|
532 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
533 |
+
self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname,
|
534 |
+
layoutfuncname))
|
535 |
+
|
536 |
+
def _loading_struct_or_union(self, tp, prefix, name, module):
|
537 |
+
if tp.fldnames is None:
|
538 |
+
return # nothing to do with opaque structs
|
539 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
540 |
+
#
|
541 |
+
function = getattr(module, layoutfuncname)
|
542 |
+
layout = function()
|
543 |
+
if isinstance(tp, model.StructOrUnion) and tp.partial:
|
544 |
+
# use the function()'s sizes and offsets to guide the
|
545 |
+
# layout of the struct
|
546 |
+
totalsize = layout[0]
|
547 |
+
totalalignment = layout[1]
|
548 |
+
fieldofs = layout[2::2]
|
549 |
+
fieldsize = layout[3::2]
|
550 |
+
tp.force_flatten()
|
551 |
+
assert len(fieldofs) == len(fieldsize) == len(tp.fldnames)
|
552 |
+
tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment
|
553 |
+
else:
|
554 |
+
cname = ('%s %s' % (prefix, name)).strip()
|
555 |
+
self._struct_pending_verification[tp] = layout, cname
|
556 |
+
|
557 |
+
def _loaded_struct_or_union(self, tp):
|
558 |
+
if tp.fldnames is None:
|
559 |
+
return # nothing to do with opaque structs
|
560 |
+
self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered
|
561 |
+
|
562 |
+
if tp in self._struct_pending_verification:
|
563 |
+
# check that the layout sizes and offsets match the real ones
|
564 |
+
def check(realvalue, expectedvalue, msg):
|
565 |
+
if realvalue != expectedvalue:
|
566 |
+
raise VerificationError(
|
567 |
+
"%s (we have %d, but C compiler says %d)"
|
568 |
+
% (msg, expectedvalue, realvalue))
|
569 |
+
ffi = self.ffi
|
570 |
+
BStruct = ffi._get_cached_btype(tp)
|
571 |
+
layout, cname = self._struct_pending_verification.pop(tp)
|
572 |
+
check(layout[0], ffi.sizeof(BStruct), "wrong total size")
|
573 |
+
check(layout[1], ffi.alignof(BStruct), "wrong total alignment")
|
574 |
+
i = 2
|
575 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
576 |
+
if fbitsize >= 0:
|
577 |
+
continue # xxx ignore fbitsize for now
|
578 |
+
check(layout[i], ffi.offsetof(BStruct, fname),
|
579 |
+
"wrong offset for field %r" % (fname,))
|
580 |
+
if layout[i+1] != 0:
|
581 |
+
BField = ffi._get_cached_btype(ftype)
|
582 |
+
check(layout[i+1], ffi.sizeof(BField),
|
583 |
+
"wrong size for field %r" % (fname,))
|
584 |
+
i += 2
|
585 |
+
assert i == len(layout)
|
586 |
+
|
587 |
+
# ----------
|
588 |
+
# 'anonymous' declarations. These are produced for anonymous structs
|
589 |
+
# or unions; the 'name' is obtained by a typedef.
|
590 |
+
|
591 |
+
_generate_cpy_anonymous_collecttype = _generate_nothing
|
592 |
+
|
593 |
+
def _generate_cpy_anonymous_decl(self, tp, name):
|
594 |
+
if isinstance(tp, model.EnumType):
|
595 |
+
self._generate_cpy_enum_decl(tp, name, '')
|
596 |
+
else:
|
597 |
+
self._generate_struct_or_union_decl(tp, '', name)
|
598 |
+
|
599 |
+
def _generate_cpy_anonymous_method(self, tp, name):
|
600 |
+
if not isinstance(tp, model.EnumType):
|
601 |
+
self._generate_struct_or_union_method(tp, '', name)
|
602 |
+
|
603 |
+
def _loading_cpy_anonymous(self, tp, name, module):
|
604 |
+
if isinstance(tp, model.EnumType):
|
605 |
+
self._loading_cpy_enum(tp, name, module)
|
606 |
+
else:
|
607 |
+
self._loading_struct_or_union(tp, '', name, module)
|
608 |
+
|
609 |
+
def _loaded_cpy_anonymous(self, tp, name, module, **kwds):
|
610 |
+
if isinstance(tp, model.EnumType):
|
611 |
+
self._loaded_cpy_enum(tp, name, module, **kwds)
|
612 |
+
else:
|
613 |
+
self._loaded_struct_or_union(tp)
|
614 |
+
|
615 |
+
# ----------
|
616 |
+
# constants, likely declared with '#define'
|
617 |
+
|
618 |
+
def _generate_cpy_const(self, is_int, name, tp=None, category='const',
|
619 |
+
vartp=None, delayed=True, size_too=False,
|
620 |
+
check_value=None):
|
621 |
+
prnt = self._prnt
|
622 |
+
funcname = '_cffi_%s_%s' % (category, name)
|
623 |
+
prnt('static int %s(PyObject *lib)' % funcname)
|
624 |
+
prnt('{')
|
625 |
+
prnt(' PyObject *o;')
|
626 |
+
prnt(' int res;')
|
627 |
+
if not is_int:
|
628 |
+
prnt(' %s;' % (vartp or tp).get_c_name(' i', name))
|
629 |
+
else:
|
630 |
+
assert category == 'const'
|
631 |
+
#
|
632 |
+
if check_value is not None:
|
633 |
+
self._check_int_constant_value(name, check_value)
|
634 |
+
#
|
635 |
+
if not is_int:
|
636 |
+
if category == 'var':
|
637 |
+
realexpr = '&' + name
|
638 |
+
else:
|
639 |
+
realexpr = name
|
640 |
+
prnt(' i = (%s);' % (realexpr,))
|
641 |
+
prnt(' o = %s;' % (self._convert_expr_from_c(tp, 'i',
|
642 |
+
'variable type'),))
|
643 |
+
assert delayed
|
644 |
+
else:
|
645 |
+
prnt(' o = _cffi_from_c_int_const(%s);' % name)
|
646 |
+
prnt(' if (o == NULL)')
|
647 |
+
prnt(' return -1;')
|
648 |
+
if size_too:
|
649 |
+
prnt(' {')
|
650 |
+
prnt(' PyObject *o1 = o;')
|
651 |
+
prnt(' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof(%s));'
|
652 |
+
% (name,))
|
653 |
+
prnt(' Py_DECREF(o1);')
|
654 |
+
prnt(' if (o == NULL)')
|
655 |
+
prnt(' return -1;')
|
656 |
+
prnt(' }')
|
657 |
+
prnt(' res = PyObject_SetAttrString(lib, "%s", o);' % name)
|
658 |
+
prnt(' Py_DECREF(o);')
|
659 |
+
prnt(' if (res < 0)')
|
660 |
+
prnt(' return -1;')
|
661 |
+
prnt(' return %s;' % self._chained_list_constants[delayed])
|
662 |
+
self._chained_list_constants[delayed] = funcname + '(lib)'
|
663 |
+
prnt('}')
|
664 |
+
prnt()
|
665 |
+
|
666 |
+
def _generate_cpy_constant_collecttype(self, tp, name):
|
667 |
+
is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
|
668 |
+
if not is_int:
|
669 |
+
self._do_collect_type(tp)
|
670 |
+
|
671 |
+
def _generate_cpy_constant_decl(self, tp, name):
|
672 |
+
is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
|
673 |
+
self._generate_cpy_const(is_int, name, tp)
|
674 |
+
|
675 |
+
_generate_cpy_constant_method = _generate_nothing
|
676 |
+
_loading_cpy_constant = _loaded_noop
|
677 |
+
_loaded_cpy_constant = _loaded_noop
|
678 |
+
|
679 |
+
# ----------
|
680 |
+
# enums
|
681 |
+
|
682 |
+
def _check_int_constant_value(self, name, value, err_prefix=''):
|
683 |
+
prnt = self._prnt
|
684 |
+
if value <= 0:
|
685 |
+
prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % (
|
686 |
+
name, name, value))
|
687 |
+
else:
|
688 |
+
prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % (
|
689 |
+
name, name, value))
|
690 |
+
prnt(' char buf[64];')
|
691 |
+
prnt(' if ((%s) <= 0)' % name)
|
692 |
+
prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % name)
|
693 |
+
prnt(' else')
|
694 |
+
prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' %
|
695 |
+
name)
|
696 |
+
prnt(' PyErr_Format(_cffi_VerificationError,')
|
697 |
+
prnt(' "%s%s has the real value %s, not %s",')
|
698 |
+
prnt(' "%s", "%s", buf, "%d");' % (
|
699 |
+
err_prefix, name, value))
|
700 |
+
prnt(' return -1;')
|
701 |
+
prnt(' }')
|
702 |
+
|
703 |
+
def _enum_funcname(self, prefix, name):
|
704 |
+
# "$enum_$1" => "___D_enum____D_1"
|
705 |
+
name = name.replace('$', '___D_')
|
706 |
+
return '_cffi_e_%s_%s' % (prefix, name)
|
707 |
+
|
708 |
+
def _generate_cpy_enum_decl(self, tp, name, prefix='enum'):
|
709 |
+
if tp.partial:
|
710 |
+
for enumerator in tp.enumerators:
|
711 |
+
self._generate_cpy_const(True, enumerator, delayed=False)
|
712 |
+
return
|
713 |
+
#
|
714 |
+
funcname = self._enum_funcname(prefix, name)
|
715 |
+
prnt = self._prnt
|
716 |
+
prnt('static int %s(PyObject *lib)' % funcname)
|
717 |
+
prnt('{')
|
718 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
719 |
+
self._check_int_constant_value(enumerator, enumvalue,
|
720 |
+
"enum %s: " % name)
|
721 |
+
prnt(' return %s;' % self._chained_list_constants[True])
|
722 |
+
self._chained_list_constants[True] = funcname + '(lib)'
|
723 |
+
prnt('}')
|
724 |
+
prnt()
|
725 |
+
|
726 |
+
_generate_cpy_enum_collecttype = _generate_nothing
|
727 |
+
_generate_cpy_enum_method = _generate_nothing
|
728 |
+
|
729 |
+
def _loading_cpy_enum(self, tp, name, module):
|
730 |
+
if tp.partial:
|
731 |
+
enumvalues = [getattr(module, enumerator)
|
732 |
+
for enumerator in tp.enumerators]
|
733 |
+
tp.enumvalues = tuple(enumvalues)
|
734 |
+
tp.partial_resolved = True
|
735 |
+
|
736 |
+
def _loaded_cpy_enum(self, tp, name, module, library):
|
737 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
738 |
+
setattr(library, enumerator, enumvalue)
|
739 |
+
|
740 |
+
# ----------
|
741 |
+
# macros: for now only for integers
|
742 |
+
|
743 |
+
def _generate_cpy_macro_decl(self, tp, name):
|
744 |
+
if tp == '...':
|
745 |
+
check_value = None
|
746 |
+
else:
|
747 |
+
check_value = tp # an integer
|
748 |
+
self._generate_cpy_const(True, name, check_value=check_value)
|
749 |
+
|
750 |
+
_generate_cpy_macro_collecttype = _generate_nothing
|
751 |
+
_generate_cpy_macro_method = _generate_nothing
|
752 |
+
_loading_cpy_macro = _loaded_noop
|
753 |
+
_loaded_cpy_macro = _loaded_noop
|
754 |
+
|
755 |
+
# ----------
|
756 |
+
# global variables
|
757 |
+
|
758 |
+
def _generate_cpy_variable_collecttype(self, tp, name):
|
759 |
+
if isinstance(tp, model.ArrayType):
|
760 |
+
tp_ptr = model.PointerType(tp.item)
|
761 |
+
else:
|
762 |
+
tp_ptr = model.PointerType(tp)
|
763 |
+
self._do_collect_type(tp_ptr)
|
764 |
+
|
765 |
+
def _generate_cpy_variable_decl(self, tp, name):
|
766 |
+
if isinstance(tp, model.ArrayType):
|
767 |
+
tp_ptr = model.PointerType(tp.item)
|
768 |
+
self._generate_cpy_const(False, name, tp, vartp=tp_ptr,
|
769 |
+
size_too = tp.length_is_unknown())
|
770 |
+
else:
|
771 |
+
tp_ptr = model.PointerType(tp)
|
772 |
+
self._generate_cpy_const(False, name, tp_ptr, category='var')
|
773 |
+
|
774 |
+
_generate_cpy_variable_method = _generate_nothing
|
775 |
+
_loading_cpy_variable = _loaded_noop
|
776 |
+
|
777 |
+
def _loaded_cpy_variable(self, tp, name, module, library):
|
778 |
+
value = getattr(library, name)
|
779 |
+
if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the
|
780 |
+
# sense that "a=..." is forbidden
|
781 |
+
if tp.length_is_unknown():
|
782 |
+
assert isinstance(value, tuple)
|
783 |
+
(value, size) = value
|
784 |
+
BItemType = self.ffi._get_cached_btype(tp.item)
|
785 |
+
length, rest = divmod(size, self.ffi.sizeof(BItemType))
|
786 |
+
if rest != 0:
|
787 |
+
raise VerificationError(
|
788 |
+
"bad size: %r does not seem to be an array of %s" %
|
789 |
+
(name, tp.item))
|
790 |
+
tp = tp.resolve_length(length)
|
791 |
+
# 'value' is a <cdata 'type *'> which we have to replace with
|
792 |
+
# a <cdata 'type[N]'> if the N is actually known
|
793 |
+
if tp.length is not None:
|
794 |
+
BArray = self.ffi._get_cached_btype(tp)
|
795 |
+
value = self.ffi.cast(BArray, value)
|
796 |
+
setattr(library, name, value)
|
797 |
+
return
|
798 |
+
# remove ptr=<cdata 'int *'> from the library instance, and replace
|
799 |
+
# it by a property on the class, which reads/writes into ptr[0].
|
800 |
+
ptr = value
|
801 |
+
delattr(library, name)
|
802 |
+
def getter(library):
|
803 |
+
return ptr[0]
|
804 |
+
def setter(library, value):
|
805 |
+
ptr[0] = value
|
806 |
+
setattr(type(library), name, property(getter, setter))
|
807 |
+
type(library)._cffi_dir.append(name)
|
808 |
+
|
809 |
+
# ----------
|
810 |
+
|
811 |
+
def _generate_setup_custom(self):
|
812 |
+
prnt = self._prnt
|
813 |
+
prnt('static int _cffi_setup_custom(PyObject *lib)')
|
814 |
+
prnt('{')
|
815 |
+
prnt(' return %s;' % self._chained_list_constants[True])
|
816 |
+
prnt('}')
|
817 |
+
|
818 |
+
cffimod_header = r'''
|
819 |
+
#include <Python.h>
|
820 |
+
#include <stddef.h>
|
821 |
+
|
822 |
+
/* this block of #ifs should be kept exactly identical between
|
823 |
+
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
|
824 |
+
and cffi/_cffi_include.h */
|
825 |
+
#if defined(_MSC_VER)
|
826 |
+
# include <malloc.h> /* for alloca() */
|
827 |
+
# if _MSC_VER < 1600 /* MSVC < 2010 */
|
828 |
+
typedef __int8 int8_t;
|
829 |
+
typedef __int16 int16_t;
|
830 |
+
typedef __int32 int32_t;
|
831 |
+
typedef __int64 int64_t;
|
832 |
+
typedef unsigned __int8 uint8_t;
|
833 |
+
typedef unsigned __int16 uint16_t;
|
834 |
+
typedef unsigned __int32 uint32_t;
|
835 |
+
typedef unsigned __int64 uint64_t;
|
836 |
+
typedef __int8 int_least8_t;
|
837 |
+
typedef __int16 int_least16_t;
|
838 |
+
typedef __int32 int_least32_t;
|
839 |
+
typedef __int64 int_least64_t;
|
840 |
+
typedef unsigned __int8 uint_least8_t;
|
841 |
+
typedef unsigned __int16 uint_least16_t;
|
842 |
+
typedef unsigned __int32 uint_least32_t;
|
843 |
+
typedef unsigned __int64 uint_least64_t;
|
844 |
+
typedef __int8 int_fast8_t;
|
845 |
+
typedef __int16 int_fast16_t;
|
846 |
+
typedef __int32 int_fast32_t;
|
847 |
+
typedef __int64 int_fast64_t;
|
848 |
+
typedef unsigned __int8 uint_fast8_t;
|
849 |
+
typedef unsigned __int16 uint_fast16_t;
|
850 |
+
typedef unsigned __int32 uint_fast32_t;
|
851 |
+
typedef unsigned __int64 uint_fast64_t;
|
852 |
+
typedef __int64 intmax_t;
|
853 |
+
typedef unsigned __int64 uintmax_t;
|
854 |
+
# else
|
855 |
+
# include <stdint.h>
|
856 |
+
# endif
|
857 |
+
# if _MSC_VER < 1800 /* MSVC < 2013 */
|
858 |
+
# ifndef __cplusplus
|
859 |
+
typedef unsigned char _Bool;
|
860 |
+
# endif
|
861 |
+
# endif
|
862 |
+
# define _cffi_float_complex_t _Fcomplex /* include <complex.h> for it */
|
863 |
+
# define _cffi_double_complex_t _Dcomplex /* include <complex.h> for it */
|
864 |
+
#else
|
865 |
+
# include <stdint.h>
|
866 |
+
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
|
867 |
+
# include <alloca.h>
|
868 |
+
# endif
|
869 |
+
# define _cffi_float_complex_t float _Complex
|
870 |
+
# define _cffi_double_complex_t double _Complex
|
871 |
+
#endif
|
872 |
+
|
873 |
+
#if PY_MAJOR_VERSION < 3
|
874 |
+
# undef PyCapsule_CheckExact
|
875 |
+
# undef PyCapsule_GetPointer
|
876 |
+
# define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
|
877 |
+
# define PyCapsule_GetPointer(capsule, name) \
|
878 |
+
(PyCObject_AsVoidPtr(capsule))
|
879 |
+
#endif
|
880 |
+
|
881 |
+
#if PY_MAJOR_VERSION >= 3
|
882 |
+
# define PyInt_FromLong PyLong_FromLong
|
883 |
+
#endif
|
884 |
+
|
885 |
+
#define _cffi_from_c_double PyFloat_FromDouble
|
886 |
+
#define _cffi_from_c_float PyFloat_FromDouble
|
887 |
+
#define _cffi_from_c_long PyInt_FromLong
|
888 |
+
#define _cffi_from_c_ulong PyLong_FromUnsignedLong
|
889 |
+
#define _cffi_from_c_longlong PyLong_FromLongLong
|
890 |
+
#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong
|
891 |
+
#define _cffi_from_c__Bool PyBool_FromLong
|
892 |
+
|
893 |
+
#define _cffi_to_c_double PyFloat_AsDouble
|
894 |
+
#define _cffi_to_c_float PyFloat_AsDouble
|
895 |
+
|
896 |
+
#define _cffi_from_c_int_const(x) \
|
897 |
+
(((x) > 0) ? \
|
898 |
+
((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \
|
899 |
+
PyInt_FromLong((long)(x)) : \
|
900 |
+
PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \
|
901 |
+
((long long)(x) >= (long long)LONG_MIN) ? \
|
902 |
+
PyInt_FromLong((long)(x)) : \
|
903 |
+
PyLong_FromLongLong((long long)(x)))
|
904 |
+
|
905 |
+
#define _cffi_from_c_int(x, type) \
|
906 |
+
(((type)-1) > 0 ? /* unsigned */ \
|
907 |
+
(sizeof(type) < sizeof(long) ? \
|
908 |
+
PyInt_FromLong((long)x) : \
|
909 |
+
sizeof(type) == sizeof(long) ? \
|
910 |
+
PyLong_FromUnsignedLong((unsigned long)x) : \
|
911 |
+
PyLong_FromUnsignedLongLong((unsigned long long)x)) : \
|
912 |
+
(sizeof(type) <= sizeof(long) ? \
|
913 |
+
PyInt_FromLong((long)x) : \
|
914 |
+
PyLong_FromLongLong((long long)x)))
|
915 |
+
|
916 |
+
#define _cffi_to_c_int(o, type) \
|
917 |
+
((type)( \
|
918 |
+
sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \
|
919 |
+
: (type)_cffi_to_c_i8(o)) : \
|
920 |
+
sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \
|
921 |
+
: (type)_cffi_to_c_i16(o)) : \
|
922 |
+
sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \
|
923 |
+
: (type)_cffi_to_c_i32(o)) : \
|
924 |
+
sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \
|
925 |
+
: (type)_cffi_to_c_i64(o)) : \
|
926 |
+
(Py_FatalError("unsupported size for type " #type), (type)0)))
|
927 |
+
|
928 |
+
#define _cffi_to_c_i8 \
|
929 |
+
((int(*)(PyObject *))_cffi_exports[1])
|
930 |
+
#define _cffi_to_c_u8 \
|
931 |
+
((int(*)(PyObject *))_cffi_exports[2])
|
932 |
+
#define _cffi_to_c_i16 \
|
933 |
+
((int(*)(PyObject *))_cffi_exports[3])
|
934 |
+
#define _cffi_to_c_u16 \
|
935 |
+
((int(*)(PyObject *))_cffi_exports[4])
|
936 |
+
#define _cffi_to_c_i32 \
|
937 |
+
((int(*)(PyObject *))_cffi_exports[5])
|
938 |
+
#define _cffi_to_c_u32 \
|
939 |
+
((unsigned int(*)(PyObject *))_cffi_exports[6])
|
940 |
+
#define _cffi_to_c_i64 \
|
941 |
+
((long long(*)(PyObject *))_cffi_exports[7])
|
942 |
+
#define _cffi_to_c_u64 \
|
943 |
+
((unsigned long long(*)(PyObject *))_cffi_exports[8])
|
944 |
+
#define _cffi_to_c_char \
|
945 |
+
((int(*)(PyObject *))_cffi_exports[9])
|
946 |
+
#define _cffi_from_c_pointer \
|
947 |
+
((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[10])
|
948 |
+
#define _cffi_to_c_pointer \
|
949 |
+
((char *(*)(PyObject *, CTypeDescrObject *))_cffi_exports[11])
|
950 |
+
#define _cffi_get_struct_layout \
|
951 |
+
((PyObject *(*)(Py_ssize_t[]))_cffi_exports[12])
|
952 |
+
#define _cffi_restore_errno \
|
953 |
+
((void(*)(void))_cffi_exports[13])
|
954 |
+
#define _cffi_save_errno \
|
955 |
+
((void(*)(void))_cffi_exports[14])
|
956 |
+
#define _cffi_from_c_char \
|
957 |
+
((PyObject *(*)(char))_cffi_exports[15])
|
958 |
+
#define _cffi_from_c_deref \
|
959 |
+
((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[16])
|
960 |
+
#define _cffi_to_c \
|
961 |
+
((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[17])
|
962 |
+
#define _cffi_from_c_struct \
|
963 |
+
((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[18])
|
964 |
+
#define _cffi_to_c_wchar_t \
|
965 |
+
((wchar_t(*)(PyObject *))_cffi_exports[19])
|
966 |
+
#define _cffi_from_c_wchar_t \
|
967 |
+
((PyObject *(*)(wchar_t))_cffi_exports[20])
|
968 |
+
#define _cffi_to_c_long_double \
|
969 |
+
((long double(*)(PyObject *))_cffi_exports[21])
|
970 |
+
#define _cffi_to_c__Bool \
|
971 |
+
((_Bool(*)(PyObject *))_cffi_exports[22])
|
972 |
+
#define _cffi_prepare_pointer_call_argument \
|
973 |
+
((Py_ssize_t(*)(CTypeDescrObject *, PyObject *, char **))_cffi_exports[23])
|
974 |
+
#define _cffi_convert_array_from_object \
|
975 |
+
((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[24])
|
976 |
+
#define _CFFI_NUM_EXPORTS 25
|
977 |
+
|
978 |
+
typedef struct _ctypedescr CTypeDescrObject;
|
979 |
+
|
980 |
+
static void *_cffi_exports[_CFFI_NUM_EXPORTS];
|
981 |
+
static PyObject *_cffi_types, *_cffi_VerificationError;
|
982 |
+
|
983 |
+
static int _cffi_setup_custom(PyObject *lib); /* forward */
|
984 |
+
|
985 |
+
static PyObject *_cffi_setup(PyObject *self, PyObject *args)
|
986 |
+
{
|
987 |
+
PyObject *library;
|
988 |
+
int was_alive = (_cffi_types != NULL);
|
989 |
+
(void)self; /* unused */
|
990 |
+
if (!PyArg_ParseTuple(args, "OOO", &_cffi_types, &_cffi_VerificationError,
|
991 |
+
&library))
|
992 |
+
return NULL;
|
993 |
+
Py_INCREF(_cffi_types);
|
994 |
+
Py_INCREF(_cffi_VerificationError);
|
995 |
+
if (_cffi_setup_custom(library) < 0)
|
996 |
+
return NULL;
|
997 |
+
return PyBool_FromLong(was_alive);
|
998 |
+
}
|
999 |
+
|
1000 |
+
union _cffi_union_alignment_u {
|
1001 |
+
unsigned char m_char;
|
1002 |
+
unsigned short m_short;
|
1003 |
+
unsigned int m_int;
|
1004 |
+
unsigned long m_long;
|
1005 |
+
unsigned long long m_longlong;
|
1006 |
+
float m_float;
|
1007 |
+
double m_double;
|
1008 |
+
long double m_longdouble;
|
1009 |
+
};
|
1010 |
+
|
1011 |
+
struct _cffi_freeme_s {
|
1012 |
+
struct _cffi_freeme_s *next;
|
1013 |
+
union _cffi_union_alignment_u alignment;
|
1014 |
+
};
|
1015 |
+
|
1016 |
+
#ifdef __GNUC__
|
1017 |
+
__attribute__((unused))
|
1018 |
+
#endif
|
1019 |
+
static int _cffi_convert_array_argument(CTypeDescrObject *ctptr, PyObject *arg,
|
1020 |
+
char **output_data, Py_ssize_t datasize,
|
1021 |
+
struct _cffi_freeme_s **freeme)
|
1022 |
+
{
|
1023 |
+
char *p;
|
1024 |
+
if (datasize < 0)
|
1025 |
+
return -1;
|
1026 |
+
|
1027 |
+
p = *output_data;
|
1028 |
+
if (p == NULL) {
|
1029 |
+
struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc(
|
1030 |
+
offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize);
|
1031 |
+
if (fp == NULL)
|
1032 |
+
return -1;
|
1033 |
+
fp->next = *freeme;
|
1034 |
+
*freeme = fp;
|
1035 |
+
p = *output_data = (char *)&fp->alignment;
|
1036 |
+
}
|
1037 |
+
memset((void *)p, 0, (size_t)datasize);
|
1038 |
+
return _cffi_convert_array_from_object(p, ctptr, arg);
|
1039 |
+
}
|
1040 |
+
|
1041 |
+
#ifdef __GNUC__
|
1042 |
+
__attribute__((unused))
|
1043 |
+
#endif
|
1044 |
+
static void _cffi_free_array_arguments(struct _cffi_freeme_s *freeme)
|
1045 |
+
{
|
1046 |
+
do {
|
1047 |
+
void *p = (void *)freeme;
|
1048 |
+
freeme = freeme->next;
|
1049 |
+
PyObject_Free(p);
|
1050 |
+
} while (freeme != NULL);
|
1051 |
+
}
|
1052 |
+
|
1053 |
+
static int _cffi_init(void)
|
1054 |
+
{
|
1055 |
+
PyObject *module, *c_api_object = NULL;
|
1056 |
+
|
1057 |
+
module = PyImport_ImportModule("_cffi_backend");
|
1058 |
+
if (module == NULL)
|
1059 |
+
goto failure;
|
1060 |
+
|
1061 |
+
c_api_object = PyObject_GetAttrString(module, "_C_API");
|
1062 |
+
if (c_api_object == NULL)
|
1063 |
+
goto failure;
|
1064 |
+
if (!PyCapsule_CheckExact(c_api_object)) {
|
1065 |
+
PyErr_SetNone(PyExc_ImportError);
|
1066 |
+
goto failure;
|
1067 |
+
}
|
1068 |
+
memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"),
|
1069 |
+
_CFFI_NUM_EXPORTS * sizeof(void *));
|
1070 |
+
|
1071 |
+
Py_DECREF(module);
|
1072 |
+
Py_DECREF(c_api_object);
|
1073 |
+
return 0;
|
1074 |
+
|
1075 |
+
failure:
|
1076 |
+
Py_XDECREF(module);
|
1077 |
+
Py_XDECREF(c_api_object);
|
1078 |
+
return -1;
|
1079 |
+
}
|
1080 |
+
|
1081 |
+
#define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num))
|
1082 |
+
|
1083 |
+
/**********/
|
1084 |
+
'''
|
cffi/vengine_gen.py
ADDED
@@ -0,0 +1,679 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# DEPRECATED: implementation for ffi.verify()
|
3 |
+
#
|
4 |
+
import sys, os
|
5 |
+
import types
|
6 |
+
|
7 |
+
from . import model
|
8 |
+
from .error import VerificationError
|
9 |
+
|
10 |
+
|
11 |
+
class VGenericEngine(object):
|
12 |
+
_class_key = 'g'
|
13 |
+
_gen_python_module = False
|
14 |
+
|
15 |
+
def __init__(self, verifier):
|
16 |
+
self.verifier = verifier
|
17 |
+
self.ffi = verifier.ffi
|
18 |
+
self.export_symbols = []
|
19 |
+
self._struct_pending_verification = {}
|
20 |
+
|
21 |
+
def patch_extension_kwds(self, kwds):
|
22 |
+
# add 'export_symbols' to the dictionary. Note that we add the
|
23 |
+
# list before filling it. When we fill it, it will thus also show
|
24 |
+
# up in kwds['export_symbols'].
|
25 |
+
kwds.setdefault('export_symbols', self.export_symbols)
|
26 |
+
|
27 |
+
def find_module(self, module_name, path, so_suffixes):
|
28 |
+
for so_suffix in so_suffixes:
|
29 |
+
basename = module_name + so_suffix
|
30 |
+
if path is None:
|
31 |
+
path = sys.path
|
32 |
+
for dirname in path:
|
33 |
+
filename = os.path.join(dirname, basename)
|
34 |
+
if os.path.isfile(filename):
|
35 |
+
return filename
|
36 |
+
|
37 |
+
def collect_types(self):
|
38 |
+
pass # not needed in the generic engine
|
39 |
+
|
40 |
+
def _prnt(self, what=''):
|
41 |
+
self._f.write(what + '\n')
|
42 |
+
|
43 |
+
def write_source_to_f(self):
|
44 |
+
prnt = self._prnt
|
45 |
+
# first paste some standard set of lines that are mostly '#include'
|
46 |
+
prnt(cffimod_header)
|
47 |
+
# then paste the C source given by the user, verbatim.
|
48 |
+
prnt(self.verifier.preamble)
|
49 |
+
#
|
50 |
+
# call generate_gen_xxx_decl(), for every xxx found from
|
51 |
+
# ffi._parser._declarations. This generates all the functions.
|
52 |
+
self._generate('decl')
|
53 |
+
#
|
54 |
+
# on Windows, distutils insists on putting init_cffi_xyz in
|
55 |
+
# 'export_symbols', so instead of fighting it, just give up and
|
56 |
+
# give it one
|
57 |
+
if sys.platform == 'win32':
|
58 |
+
if sys.version_info >= (3,):
|
59 |
+
prefix = 'PyInit_'
|
60 |
+
else:
|
61 |
+
prefix = 'init'
|
62 |
+
modname = self.verifier.get_module_name()
|
63 |
+
prnt("void %s%s(void) { }\n" % (prefix, modname))
|
64 |
+
|
65 |
+
def load_library(self, flags=0):
|
66 |
+
# import it with the CFFI backend
|
67 |
+
backend = self.ffi._backend
|
68 |
+
# needs to make a path that contains '/', on Posix
|
69 |
+
filename = os.path.join(os.curdir, self.verifier.modulefilename)
|
70 |
+
module = backend.load_library(filename, flags)
|
71 |
+
#
|
72 |
+
# call loading_gen_struct() to get the struct layout inferred by
|
73 |
+
# the C compiler
|
74 |
+
self._load(module, 'loading')
|
75 |
+
|
76 |
+
# build the FFILibrary class and instance, this is a module subclass
|
77 |
+
# because modules are expected to have usually-constant-attributes and
|
78 |
+
# in PyPy this means the JIT is able to treat attributes as constant,
|
79 |
+
# which we want.
|
80 |
+
class FFILibrary(types.ModuleType):
|
81 |
+
_cffi_generic_module = module
|
82 |
+
_cffi_ffi = self.ffi
|
83 |
+
_cffi_dir = []
|
84 |
+
def __dir__(self):
|
85 |
+
return FFILibrary._cffi_dir
|
86 |
+
library = FFILibrary("")
|
87 |
+
#
|
88 |
+
# finally, call the loaded_gen_xxx() functions. This will set
|
89 |
+
# up the 'library' object.
|
90 |
+
self._load(module, 'loaded', library=library)
|
91 |
+
return library
|
92 |
+
|
93 |
+
def _get_declarations(self):
|
94 |
+
lst = [(key, tp) for (key, (tp, qual)) in
|
95 |
+
self.ffi._parser._declarations.items()]
|
96 |
+
lst.sort()
|
97 |
+
return lst
|
98 |
+
|
99 |
+
def _generate(self, step_name):
|
100 |
+
for name, tp in self._get_declarations():
|
101 |
+
kind, realname = name.split(' ', 1)
|
102 |
+
try:
|
103 |
+
method = getattr(self, '_generate_gen_%s_%s' % (kind,
|
104 |
+
step_name))
|
105 |
+
except AttributeError:
|
106 |
+
raise VerificationError(
|
107 |
+
"not implemented in verify(): %r" % name)
|
108 |
+
try:
|
109 |
+
method(tp, realname)
|
110 |
+
except Exception as e:
|
111 |
+
model.attach_exception_info(e, name)
|
112 |
+
raise
|
113 |
+
|
114 |
+
def _load(self, module, step_name, **kwds):
|
115 |
+
for name, tp in self._get_declarations():
|
116 |
+
kind, realname = name.split(' ', 1)
|
117 |
+
method = getattr(self, '_%s_gen_%s' % (step_name, kind))
|
118 |
+
try:
|
119 |
+
method(tp, realname, module, **kwds)
|
120 |
+
except Exception as e:
|
121 |
+
model.attach_exception_info(e, name)
|
122 |
+
raise
|
123 |
+
|
124 |
+
def _generate_nothing(self, tp, name):
|
125 |
+
pass
|
126 |
+
|
127 |
+
def _loaded_noop(self, tp, name, module, **kwds):
|
128 |
+
pass
|
129 |
+
|
130 |
+
# ----------
|
131 |
+
# typedefs: generates no code so far
|
132 |
+
|
133 |
+
_generate_gen_typedef_decl = _generate_nothing
|
134 |
+
_loading_gen_typedef = _loaded_noop
|
135 |
+
_loaded_gen_typedef = _loaded_noop
|
136 |
+
|
137 |
+
# ----------
|
138 |
+
# function declarations
|
139 |
+
|
140 |
+
def _generate_gen_function_decl(self, tp, name):
|
141 |
+
assert isinstance(tp, model.FunctionPtrType)
|
142 |
+
if tp.ellipsis:
|
143 |
+
# cannot support vararg functions better than this: check for its
|
144 |
+
# exact type (including the fixed arguments), and build it as a
|
145 |
+
# constant function pointer (no _cffi_f_%s wrapper)
|
146 |
+
self._generate_gen_const(False, name, tp)
|
147 |
+
return
|
148 |
+
prnt = self._prnt
|
149 |
+
numargs = len(tp.args)
|
150 |
+
argnames = []
|
151 |
+
for i, type in enumerate(tp.args):
|
152 |
+
indirection = ''
|
153 |
+
if isinstance(type, model.StructOrUnion):
|
154 |
+
indirection = '*'
|
155 |
+
argnames.append('%sx%d' % (indirection, i))
|
156 |
+
context = 'argument of %s' % name
|
157 |
+
arglist = [type.get_c_name(' %s' % arg, context)
|
158 |
+
for type, arg in zip(tp.args, argnames)]
|
159 |
+
tpresult = tp.result
|
160 |
+
if isinstance(tpresult, model.StructOrUnion):
|
161 |
+
arglist.insert(0, tpresult.get_c_name(' *r', context))
|
162 |
+
tpresult = model.void_type
|
163 |
+
arglist = ', '.join(arglist) or 'void'
|
164 |
+
wrappername = '_cffi_f_%s' % name
|
165 |
+
self.export_symbols.append(wrappername)
|
166 |
+
if tp.abi:
|
167 |
+
abi = tp.abi + ' '
|
168 |
+
else:
|
169 |
+
abi = ''
|
170 |
+
funcdecl = ' %s%s(%s)' % (abi, wrappername, arglist)
|
171 |
+
context = 'result of %s' % name
|
172 |
+
prnt(tpresult.get_c_name(funcdecl, context))
|
173 |
+
prnt('{')
|
174 |
+
#
|
175 |
+
if isinstance(tp.result, model.StructOrUnion):
|
176 |
+
result_code = '*r = '
|
177 |
+
elif not isinstance(tp.result, model.VoidType):
|
178 |
+
result_code = 'return '
|
179 |
+
else:
|
180 |
+
result_code = ''
|
181 |
+
prnt(' %s%s(%s);' % (result_code, name, ', '.join(argnames)))
|
182 |
+
prnt('}')
|
183 |
+
prnt()
|
184 |
+
|
185 |
+
_loading_gen_function = _loaded_noop
|
186 |
+
|
187 |
+
def _loaded_gen_function(self, tp, name, module, library):
|
188 |
+
assert isinstance(tp, model.FunctionPtrType)
|
189 |
+
if tp.ellipsis:
|
190 |
+
newfunction = self._load_constant(False, tp, name, module)
|
191 |
+
else:
|
192 |
+
indirections = []
|
193 |
+
base_tp = tp
|
194 |
+
if (any(isinstance(typ, model.StructOrUnion) for typ in tp.args)
|
195 |
+
or isinstance(tp.result, model.StructOrUnion)):
|
196 |
+
indirect_args = []
|
197 |
+
for i, typ in enumerate(tp.args):
|
198 |
+
if isinstance(typ, model.StructOrUnion):
|
199 |
+
typ = model.PointerType(typ)
|
200 |
+
indirections.append((i, typ))
|
201 |
+
indirect_args.append(typ)
|
202 |
+
indirect_result = tp.result
|
203 |
+
if isinstance(indirect_result, model.StructOrUnion):
|
204 |
+
if indirect_result.fldtypes is None:
|
205 |
+
raise TypeError("'%s' is used as result type, "
|
206 |
+
"but is opaque" % (
|
207 |
+
indirect_result._get_c_name(),))
|
208 |
+
indirect_result = model.PointerType(indirect_result)
|
209 |
+
indirect_args.insert(0, indirect_result)
|
210 |
+
indirections.insert(0, ("result", indirect_result))
|
211 |
+
indirect_result = model.void_type
|
212 |
+
tp = model.FunctionPtrType(tuple(indirect_args),
|
213 |
+
indirect_result, tp.ellipsis)
|
214 |
+
BFunc = self.ffi._get_cached_btype(tp)
|
215 |
+
wrappername = '_cffi_f_%s' % name
|
216 |
+
newfunction = module.load_function(BFunc, wrappername)
|
217 |
+
for i, typ in indirections:
|
218 |
+
newfunction = self._make_struct_wrapper(newfunction, i, typ,
|
219 |
+
base_tp)
|
220 |
+
setattr(library, name, newfunction)
|
221 |
+
type(library)._cffi_dir.append(name)
|
222 |
+
|
223 |
+
def _make_struct_wrapper(self, oldfunc, i, tp, base_tp):
|
224 |
+
backend = self.ffi._backend
|
225 |
+
BType = self.ffi._get_cached_btype(tp)
|
226 |
+
if i == "result":
|
227 |
+
ffi = self.ffi
|
228 |
+
def newfunc(*args):
|
229 |
+
res = ffi.new(BType)
|
230 |
+
oldfunc(res, *args)
|
231 |
+
return res[0]
|
232 |
+
else:
|
233 |
+
def newfunc(*args):
|
234 |
+
args = args[:i] + (backend.newp(BType, args[i]),) + args[i+1:]
|
235 |
+
return oldfunc(*args)
|
236 |
+
newfunc._cffi_base_type = base_tp
|
237 |
+
return newfunc
|
238 |
+
|
239 |
+
# ----------
|
240 |
+
# named structs
|
241 |
+
|
242 |
+
def _generate_gen_struct_decl(self, tp, name):
|
243 |
+
assert name == tp.name
|
244 |
+
self._generate_struct_or_union_decl(tp, 'struct', name)
|
245 |
+
|
246 |
+
def _loading_gen_struct(self, tp, name, module):
|
247 |
+
self._loading_struct_or_union(tp, 'struct', name, module)
|
248 |
+
|
249 |
+
def _loaded_gen_struct(self, tp, name, module, **kwds):
|
250 |
+
self._loaded_struct_or_union(tp)
|
251 |
+
|
252 |
+
def _generate_gen_union_decl(self, tp, name):
|
253 |
+
assert name == tp.name
|
254 |
+
self._generate_struct_or_union_decl(tp, 'union', name)
|
255 |
+
|
256 |
+
def _loading_gen_union(self, tp, name, module):
|
257 |
+
self._loading_struct_or_union(tp, 'union', name, module)
|
258 |
+
|
259 |
+
def _loaded_gen_union(self, tp, name, module, **kwds):
|
260 |
+
self._loaded_struct_or_union(tp)
|
261 |
+
|
262 |
+
def _generate_struct_or_union_decl(self, tp, prefix, name):
|
263 |
+
if tp.fldnames is None:
|
264 |
+
return # nothing to do with opaque structs
|
265 |
+
checkfuncname = '_cffi_check_%s_%s' % (prefix, name)
|
266 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
267 |
+
cname = ('%s %s' % (prefix, name)).strip()
|
268 |
+
#
|
269 |
+
prnt = self._prnt
|
270 |
+
prnt('static void %s(%s *p)' % (checkfuncname, cname))
|
271 |
+
prnt('{')
|
272 |
+
prnt(' /* only to generate compile-time warnings or errors */')
|
273 |
+
prnt(' (void)p;')
|
274 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
275 |
+
if (isinstance(ftype, model.PrimitiveType)
|
276 |
+
and ftype.is_integer_type()) or fbitsize >= 0:
|
277 |
+
# accept all integers, but complain on float or double
|
278 |
+
prnt(' (void)((p->%s) << 1);' % fname)
|
279 |
+
else:
|
280 |
+
# only accept exactly the type declared.
|
281 |
+
try:
|
282 |
+
prnt(' { %s = &p->%s; (void)tmp; }' % (
|
283 |
+
ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
|
284 |
+
fname))
|
285 |
+
except VerificationError as e:
|
286 |
+
prnt(' /* %s */' % str(e)) # cannot verify it, ignore
|
287 |
+
prnt('}')
|
288 |
+
self.export_symbols.append(layoutfuncname)
|
289 |
+
prnt('intptr_t %s(intptr_t i)' % (layoutfuncname,))
|
290 |
+
prnt('{')
|
291 |
+
prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname)
|
292 |
+
prnt(' static intptr_t nums[] = {')
|
293 |
+
prnt(' sizeof(%s),' % cname)
|
294 |
+
prnt(' offsetof(struct _cffi_aligncheck, y),')
|
295 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
296 |
+
if fbitsize >= 0:
|
297 |
+
continue # xxx ignore fbitsize for now
|
298 |
+
prnt(' offsetof(%s, %s),' % (cname, fname))
|
299 |
+
if isinstance(ftype, model.ArrayType) and ftype.length is None:
|
300 |
+
prnt(' 0, /* %s */' % ftype._get_c_name())
|
301 |
+
else:
|
302 |
+
prnt(' sizeof(((%s *)0)->%s),' % (cname, fname))
|
303 |
+
prnt(' -1')
|
304 |
+
prnt(' };')
|
305 |
+
prnt(' return nums[i];')
|
306 |
+
prnt(' /* the next line is not executed, but compiled */')
|
307 |
+
prnt(' %s(0);' % (checkfuncname,))
|
308 |
+
prnt('}')
|
309 |
+
prnt()
|
310 |
+
|
311 |
+
def _loading_struct_or_union(self, tp, prefix, name, module):
|
312 |
+
if tp.fldnames is None:
|
313 |
+
return # nothing to do with opaque structs
|
314 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
315 |
+
#
|
316 |
+
BFunc = self.ffi._typeof_locked("intptr_t(*)(intptr_t)")[0]
|
317 |
+
function = module.load_function(BFunc, layoutfuncname)
|
318 |
+
layout = []
|
319 |
+
num = 0
|
320 |
+
while True:
|
321 |
+
x = function(num)
|
322 |
+
if x < 0: break
|
323 |
+
layout.append(x)
|
324 |
+
num += 1
|
325 |
+
if isinstance(tp, model.StructOrUnion) and tp.partial:
|
326 |
+
# use the function()'s sizes and offsets to guide the
|
327 |
+
# layout of the struct
|
328 |
+
totalsize = layout[0]
|
329 |
+
totalalignment = layout[1]
|
330 |
+
fieldofs = layout[2::2]
|
331 |
+
fieldsize = layout[3::2]
|
332 |
+
tp.force_flatten()
|
333 |
+
assert len(fieldofs) == len(fieldsize) == len(tp.fldnames)
|
334 |
+
tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment
|
335 |
+
else:
|
336 |
+
cname = ('%s %s' % (prefix, name)).strip()
|
337 |
+
self._struct_pending_verification[tp] = layout, cname
|
338 |
+
|
339 |
+
def _loaded_struct_or_union(self, tp):
|
340 |
+
if tp.fldnames is None:
|
341 |
+
return # nothing to do with opaque structs
|
342 |
+
self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered
|
343 |
+
|
344 |
+
if tp in self._struct_pending_verification:
|
345 |
+
# check that the layout sizes and offsets match the real ones
|
346 |
+
def check(realvalue, expectedvalue, msg):
|
347 |
+
if realvalue != expectedvalue:
|
348 |
+
raise VerificationError(
|
349 |
+
"%s (we have %d, but C compiler says %d)"
|
350 |
+
% (msg, expectedvalue, realvalue))
|
351 |
+
ffi = self.ffi
|
352 |
+
BStruct = ffi._get_cached_btype(tp)
|
353 |
+
layout, cname = self._struct_pending_verification.pop(tp)
|
354 |
+
check(layout[0], ffi.sizeof(BStruct), "wrong total size")
|
355 |
+
check(layout[1], ffi.alignof(BStruct), "wrong total alignment")
|
356 |
+
i = 2
|
357 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
358 |
+
if fbitsize >= 0:
|
359 |
+
continue # xxx ignore fbitsize for now
|
360 |
+
check(layout[i], ffi.offsetof(BStruct, fname),
|
361 |
+
"wrong offset for field %r" % (fname,))
|
362 |
+
if layout[i+1] != 0:
|
363 |
+
BField = ffi._get_cached_btype(ftype)
|
364 |
+
check(layout[i+1], ffi.sizeof(BField),
|
365 |
+
"wrong size for field %r" % (fname,))
|
366 |
+
i += 2
|
367 |
+
assert i == len(layout)
|
368 |
+
|
369 |
+
# ----------
|
370 |
+
# 'anonymous' declarations. These are produced for anonymous structs
|
371 |
+
# or unions; the 'name' is obtained by a typedef.
|
372 |
+
|
373 |
+
def _generate_gen_anonymous_decl(self, tp, name):
|
374 |
+
if isinstance(tp, model.EnumType):
|
375 |
+
self._generate_gen_enum_decl(tp, name, '')
|
376 |
+
else:
|
377 |
+
self._generate_struct_or_union_decl(tp, '', name)
|
378 |
+
|
379 |
+
def _loading_gen_anonymous(self, tp, name, module):
|
380 |
+
if isinstance(tp, model.EnumType):
|
381 |
+
self._loading_gen_enum(tp, name, module, '')
|
382 |
+
else:
|
383 |
+
self._loading_struct_or_union(tp, '', name, module)
|
384 |
+
|
385 |
+
def _loaded_gen_anonymous(self, tp, name, module, **kwds):
|
386 |
+
if isinstance(tp, model.EnumType):
|
387 |
+
self._loaded_gen_enum(tp, name, module, **kwds)
|
388 |
+
else:
|
389 |
+
self._loaded_struct_or_union(tp)
|
390 |
+
|
391 |
+
# ----------
|
392 |
+
# constants, likely declared with '#define'
|
393 |
+
|
394 |
+
def _generate_gen_const(self, is_int, name, tp=None, category='const',
|
395 |
+
check_value=None):
|
396 |
+
prnt = self._prnt
|
397 |
+
funcname = '_cffi_%s_%s' % (category, name)
|
398 |
+
self.export_symbols.append(funcname)
|
399 |
+
if check_value is not None:
|
400 |
+
assert is_int
|
401 |
+
assert category == 'const'
|
402 |
+
prnt('int %s(char *out_error)' % funcname)
|
403 |
+
prnt('{')
|
404 |
+
self._check_int_constant_value(name, check_value)
|
405 |
+
prnt(' return 0;')
|
406 |
+
prnt('}')
|
407 |
+
elif is_int:
|
408 |
+
assert category == 'const'
|
409 |
+
prnt('int %s(long long *out_value)' % funcname)
|
410 |
+
prnt('{')
|
411 |
+
prnt(' *out_value = (long long)(%s);' % (name,))
|
412 |
+
prnt(' return (%s) <= 0;' % (name,))
|
413 |
+
prnt('}')
|
414 |
+
else:
|
415 |
+
assert tp is not None
|
416 |
+
assert check_value is None
|
417 |
+
if category == 'var':
|
418 |
+
ampersand = '&'
|
419 |
+
else:
|
420 |
+
ampersand = ''
|
421 |
+
extra = ''
|
422 |
+
if category == 'const' and isinstance(tp, model.StructOrUnion):
|
423 |
+
extra = 'const *'
|
424 |
+
ampersand = '&'
|
425 |
+
prnt(tp.get_c_name(' %s%s(void)' % (extra, funcname), name))
|
426 |
+
prnt('{')
|
427 |
+
prnt(' return (%s%s);' % (ampersand, name))
|
428 |
+
prnt('}')
|
429 |
+
prnt()
|
430 |
+
|
431 |
+
def _generate_gen_constant_decl(self, tp, name):
|
432 |
+
is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
|
433 |
+
self._generate_gen_const(is_int, name, tp)
|
434 |
+
|
435 |
+
_loading_gen_constant = _loaded_noop
|
436 |
+
|
437 |
+
def _load_constant(self, is_int, tp, name, module, check_value=None):
|
438 |
+
funcname = '_cffi_const_%s' % name
|
439 |
+
if check_value is not None:
|
440 |
+
assert is_int
|
441 |
+
self._load_known_int_constant(module, funcname)
|
442 |
+
value = check_value
|
443 |
+
elif is_int:
|
444 |
+
BType = self.ffi._typeof_locked("long long*")[0]
|
445 |
+
BFunc = self.ffi._typeof_locked("int(*)(long long*)")[0]
|
446 |
+
function = module.load_function(BFunc, funcname)
|
447 |
+
p = self.ffi.new(BType)
|
448 |
+
negative = function(p)
|
449 |
+
value = int(p[0])
|
450 |
+
if value < 0 and not negative:
|
451 |
+
BLongLong = self.ffi._typeof_locked("long long")[0]
|
452 |
+
value += (1 << (8*self.ffi.sizeof(BLongLong)))
|
453 |
+
else:
|
454 |
+
assert check_value is None
|
455 |
+
fntypeextra = '(*)(void)'
|
456 |
+
if isinstance(tp, model.StructOrUnion):
|
457 |
+
fntypeextra = '*' + fntypeextra
|
458 |
+
BFunc = self.ffi._typeof_locked(tp.get_c_name(fntypeextra, name))[0]
|
459 |
+
function = module.load_function(BFunc, funcname)
|
460 |
+
value = function()
|
461 |
+
if isinstance(tp, model.StructOrUnion):
|
462 |
+
value = value[0]
|
463 |
+
return value
|
464 |
+
|
465 |
+
def _loaded_gen_constant(self, tp, name, module, library):
|
466 |
+
is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
|
467 |
+
value = self._load_constant(is_int, tp, name, module)
|
468 |
+
setattr(library, name, value)
|
469 |
+
type(library)._cffi_dir.append(name)
|
470 |
+
|
471 |
+
# ----------
|
472 |
+
# enums
|
473 |
+
|
474 |
+
def _check_int_constant_value(self, name, value):
|
475 |
+
prnt = self._prnt
|
476 |
+
if value <= 0:
|
477 |
+
prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % (
|
478 |
+
name, name, value))
|
479 |
+
else:
|
480 |
+
prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % (
|
481 |
+
name, name, value))
|
482 |
+
prnt(' char buf[64];')
|
483 |
+
prnt(' if ((%s) <= 0)' % name)
|
484 |
+
prnt(' sprintf(buf, "%%ld", (long)(%s));' % name)
|
485 |
+
prnt(' else')
|
486 |
+
prnt(' sprintf(buf, "%%lu", (unsigned long)(%s));' %
|
487 |
+
name)
|
488 |
+
prnt(' sprintf(out_error, "%s has the real value %s, not %s",')
|
489 |
+
prnt(' "%s", buf, "%d");' % (name[:100], value))
|
490 |
+
prnt(' return -1;')
|
491 |
+
prnt(' }')
|
492 |
+
|
493 |
+
def _load_known_int_constant(self, module, funcname):
|
494 |
+
BType = self.ffi._typeof_locked("char[]")[0]
|
495 |
+
BFunc = self.ffi._typeof_locked("int(*)(char*)")[0]
|
496 |
+
function = module.load_function(BFunc, funcname)
|
497 |
+
p = self.ffi.new(BType, 256)
|
498 |
+
if function(p) < 0:
|
499 |
+
error = self.ffi.string(p)
|
500 |
+
if sys.version_info >= (3,):
|
501 |
+
error = str(error, 'utf-8')
|
502 |
+
raise VerificationError(error)
|
503 |
+
|
504 |
+
def _enum_funcname(self, prefix, name):
|
505 |
+
# "$enum_$1" => "___D_enum____D_1"
|
506 |
+
name = name.replace('$', '___D_')
|
507 |
+
return '_cffi_e_%s_%s' % (prefix, name)
|
508 |
+
|
509 |
+
def _generate_gen_enum_decl(self, tp, name, prefix='enum'):
|
510 |
+
if tp.partial:
|
511 |
+
for enumerator in tp.enumerators:
|
512 |
+
self._generate_gen_const(True, enumerator)
|
513 |
+
return
|
514 |
+
#
|
515 |
+
funcname = self._enum_funcname(prefix, name)
|
516 |
+
self.export_symbols.append(funcname)
|
517 |
+
prnt = self._prnt
|
518 |
+
prnt('int %s(char *out_error)' % funcname)
|
519 |
+
prnt('{')
|
520 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
521 |
+
self._check_int_constant_value(enumerator, enumvalue)
|
522 |
+
prnt(' return 0;')
|
523 |
+
prnt('}')
|
524 |
+
prnt()
|
525 |
+
|
526 |
+
def _loading_gen_enum(self, tp, name, module, prefix='enum'):
|
527 |
+
if tp.partial:
|
528 |
+
enumvalues = [self._load_constant(True, tp, enumerator, module)
|
529 |
+
for enumerator in tp.enumerators]
|
530 |
+
tp.enumvalues = tuple(enumvalues)
|
531 |
+
tp.partial_resolved = True
|
532 |
+
else:
|
533 |
+
funcname = self._enum_funcname(prefix, name)
|
534 |
+
self._load_known_int_constant(module, funcname)
|
535 |
+
|
536 |
+
def _loaded_gen_enum(self, tp, name, module, library):
|
537 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
538 |
+
setattr(library, enumerator, enumvalue)
|
539 |
+
type(library)._cffi_dir.append(enumerator)
|
540 |
+
|
541 |
+
# ----------
|
542 |
+
# macros: for now only for integers
|
543 |
+
|
544 |
+
def _generate_gen_macro_decl(self, tp, name):
|
545 |
+
if tp == '...':
|
546 |
+
check_value = None
|
547 |
+
else:
|
548 |
+
check_value = tp # an integer
|
549 |
+
self._generate_gen_const(True, name, check_value=check_value)
|
550 |
+
|
551 |
+
_loading_gen_macro = _loaded_noop
|
552 |
+
|
553 |
+
def _loaded_gen_macro(self, tp, name, module, library):
|
554 |
+
if tp == '...':
|
555 |
+
check_value = None
|
556 |
+
else:
|
557 |
+
check_value = tp # an integer
|
558 |
+
value = self._load_constant(True, tp, name, module,
|
559 |
+
check_value=check_value)
|
560 |
+
setattr(library, name, value)
|
561 |
+
type(library)._cffi_dir.append(name)
|
562 |
+
|
563 |
+
# ----------
|
564 |
+
# global variables
|
565 |
+
|
566 |
+
def _generate_gen_variable_decl(self, tp, name):
|
567 |
+
if isinstance(tp, model.ArrayType):
|
568 |
+
if tp.length_is_unknown():
|
569 |
+
prnt = self._prnt
|
570 |
+
funcname = '_cffi_sizeof_%s' % (name,)
|
571 |
+
self.export_symbols.append(funcname)
|
572 |
+
prnt("size_t %s(void)" % funcname)
|
573 |
+
prnt("{")
|
574 |
+
prnt(" return sizeof(%s);" % (name,))
|
575 |
+
prnt("}")
|
576 |
+
tp_ptr = model.PointerType(tp.item)
|
577 |
+
self._generate_gen_const(False, name, tp_ptr)
|
578 |
+
else:
|
579 |
+
tp_ptr = model.PointerType(tp)
|
580 |
+
self._generate_gen_const(False, name, tp_ptr, category='var')
|
581 |
+
|
582 |
+
_loading_gen_variable = _loaded_noop
|
583 |
+
|
584 |
+
def _loaded_gen_variable(self, tp, name, module, library):
|
585 |
+
if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the
|
586 |
+
# sense that "a=..." is forbidden
|
587 |
+
if tp.length_is_unknown():
|
588 |
+
funcname = '_cffi_sizeof_%s' % (name,)
|
589 |
+
BFunc = self.ffi._typeof_locked('size_t(*)(void)')[0]
|
590 |
+
function = module.load_function(BFunc, funcname)
|
591 |
+
size = function()
|
592 |
+
BItemType = self.ffi._get_cached_btype(tp.item)
|
593 |
+
length, rest = divmod(size, self.ffi.sizeof(BItemType))
|
594 |
+
if rest != 0:
|
595 |
+
raise VerificationError(
|
596 |
+
"bad size: %r does not seem to be an array of %s" %
|
597 |
+
(name, tp.item))
|
598 |
+
tp = tp.resolve_length(length)
|
599 |
+
tp_ptr = model.PointerType(tp.item)
|
600 |
+
value = self._load_constant(False, tp_ptr, name, module)
|
601 |
+
# 'value' is a <cdata 'type *'> which we have to replace with
|
602 |
+
# a <cdata 'type[N]'> if the N is actually known
|
603 |
+
if tp.length is not None:
|
604 |
+
BArray = self.ffi._get_cached_btype(tp)
|
605 |
+
value = self.ffi.cast(BArray, value)
|
606 |
+
setattr(library, name, value)
|
607 |
+
type(library)._cffi_dir.append(name)
|
608 |
+
return
|
609 |
+
# remove ptr=<cdata 'int *'> from the library instance, and replace
|
610 |
+
# it by a property on the class, which reads/writes into ptr[0].
|
611 |
+
funcname = '_cffi_var_%s' % name
|
612 |
+
BFunc = self.ffi._typeof_locked(tp.get_c_name('*(*)(void)', name))[0]
|
613 |
+
function = module.load_function(BFunc, funcname)
|
614 |
+
ptr = function()
|
615 |
+
def getter(library):
|
616 |
+
return ptr[0]
|
617 |
+
def setter(library, value):
|
618 |
+
ptr[0] = value
|
619 |
+
setattr(type(library), name, property(getter, setter))
|
620 |
+
type(library)._cffi_dir.append(name)
|
621 |
+
|
622 |
+
cffimod_header = r'''
|
623 |
+
#include <stdio.h>
|
624 |
+
#include <stddef.h>
|
625 |
+
#include <stdarg.h>
|
626 |
+
#include <errno.h>
|
627 |
+
#include <sys/types.h> /* XXX for ssize_t on some platforms */
|
628 |
+
|
629 |
+
/* this block of #ifs should be kept exactly identical between
|
630 |
+
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
|
631 |
+
and cffi/_cffi_include.h */
|
632 |
+
#if defined(_MSC_VER)
|
633 |
+
# include <malloc.h> /* for alloca() */
|
634 |
+
# if _MSC_VER < 1600 /* MSVC < 2010 */
|
635 |
+
typedef __int8 int8_t;
|
636 |
+
typedef __int16 int16_t;
|
637 |
+
typedef __int32 int32_t;
|
638 |
+
typedef __int64 int64_t;
|
639 |
+
typedef unsigned __int8 uint8_t;
|
640 |
+
typedef unsigned __int16 uint16_t;
|
641 |
+
typedef unsigned __int32 uint32_t;
|
642 |
+
typedef unsigned __int64 uint64_t;
|
643 |
+
typedef __int8 int_least8_t;
|
644 |
+
typedef __int16 int_least16_t;
|
645 |
+
typedef __int32 int_least32_t;
|
646 |
+
typedef __int64 int_least64_t;
|
647 |
+
typedef unsigned __int8 uint_least8_t;
|
648 |
+
typedef unsigned __int16 uint_least16_t;
|
649 |
+
typedef unsigned __int32 uint_least32_t;
|
650 |
+
typedef unsigned __int64 uint_least64_t;
|
651 |
+
typedef __int8 int_fast8_t;
|
652 |
+
typedef __int16 int_fast16_t;
|
653 |
+
typedef __int32 int_fast32_t;
|
654 |
+
typedef __int64 int_fast64_t;
|
655 |
+
typedef unsigned __int8 uint_fast8_t;
|
656 |
+
typedef unsigned __int16 uint_fast16_t;
|
657 |
+
typedef unsigned __int32 uint_fast32_t;
|
658 |
+
typedef unsigned __int64 uint_fast64_t;
|
659 |
+
typedef __int64 intmax_t;
|
660 |
+
typedef unsigned __int64 uintmax_t;
|
661 |
+
# else
|
662 |
+
# include <stdint.h>
|
663 |
+
# endif
|
664 |
+
# if _MSC_VER < 1800 /* MSVC < 2013 */
|
665 |
+
# ifndef __cplusplus
|
666 |
+
typedef unsigned char _Bool;
|
667 |
+
# endif
|
668 |
+
# endif
|
669 |
+
# define _cffi_float_complex_t _Fcomplex /* include <complex.h> for it */
|
670 |
+
# define _cffi_double_complex_t _Dcomplex /* include <complex.h> for it */
|
671 |
+
#else
|
672 |
+
# include <stdint.h>
|
673 |
+
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
|
674 |
+
# include <alloca.h>
|
675 |
+
# endif
|
676 |
+
# define _cffi_float_complex_t float _Complex
|
677 |
+
# define _cffi_double_complex_t double _Complex
|
678 |
+
#endif
|
679 |
+
'''
|
cffi/verifier.py
ADDED
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# DEPRECATED: implementation for ffi.verify()
|
3 |
+
#
|
4 |
+
import sys, os, binascii, shutil, io
|
5 |
+
from . import __version_verifier_modules__
|
6 |
+
from . import ffiplatform
|
7 |
+
from .error import VerificationError
|
8 |
+
|
9 |
+
if sys.version_info >= (3, 3):
|
10 |
+
import importlib.machinery
|
11 |
+
def _extension_suffixes():
|
12 |
+
return importlib.machinery.EXTENSION_SUFFIXES[:]
|
13 |
+
else:
|
14 |
+
import imp
|
15 |
+
def _extension_suffixes():
|
16 |
+
return [suffix for suffix, _, type in imp.get_suffixes()
|
17 |
+
if type == imp.C_EXTENSION]
|
18 |
+
|
19 |
+
|
20 |
+
if sys.version_info >= (3,):
|
21 |
+
NativeIO = io.StringIO
|
22 |
+
else:
|
23 |
+
class NativeIO(io.BytesIO):
|
24 |
+
def write(self, s):
|
25 |
+
if isinstance(s, unicode):
|
26 |
+
s = s.encode('ascii')
|
27 |
+
super(NativeIO, self).write(s)
|
28 |
+
|
29 |
+
|
30 |
+
class Verifier(object):
|
31 |
+
|
32 |
+
def __init__(self, ffi, preamble, tmpdir=None, modulename=None,
|
33 |
+
ext_package=None, tag='', force_generic_engine=False,
|
34 |
+
source_extension='.c', flags=None, relative_to=None, **kwds):
|
35 |
+
if ffi._parser._uses_new_feature:
|
36 |
+
raise VerificationError(
|
37 |
+
"feature not supported with ffi.verify(), but only "
|
38 |
+
"with ffi.set_source(): %s" % (ffi._parser._uses_new_feature,))
|
39 |
+
self.ffi = ffi
|
40 |
+
self.preamble = preamble
|
41 |
+
if not modulename:
|
42 |
+
flattened_kwds = ffiplatform.flatten(kwds)
|
43 |
+
vengine_class = _locate_engine_class(ffi, force_generic_engine)
|
44 |
+
self._vengine = vengine_class(self)
|
45 |
+
self._vengine.patch_extension_kwds(kwds)
|
46 |
+
self.flags = flags
|
47 |
+
self.kwds = self.make_relative_to(kwds, relative_to)
|
48 |
+
#
|
49 |
+
if modulename:
|
50 |
+
if tag:
|
51 |
+
raise TypeError("can't specify both 'modulename' and 'tag'")
|
52 |
+
else:
|
53 |
+
key = '\x00'.join(['%d.%d' % sys.version_info[:2],
|
54 |
+
__version_verifier_modules__,
|
55 |
+
preamble, flattened_kwds] +
|
56 |
+
ffi._cdefsources)
|
57 |
+
if sys.version_info >= (3,):
|
58 |
+
key = key.encode('utf-8')
|
59 |
+
k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff)
|
60 |
+
k1 = k1.lstrip('0x').rstrip('L')
|
61 |
+
k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff)
|
62 |
+
k2 = k2.lstrip('0').rstrip('L')
|
63 |
+
modulename = '_cffi_%s_%s%s%s' % (tag, self._vengine._class_key,
|
64 |
+
k1, k2)
|
65 |
+
suffix = _get_so_suffixes()[0]
|
66 |
+
self.tmpdir = tmpdir or _caller_dir_pycache()
|
67 |
+
self.sourcefilename = os.path.join(self.tmpdir, modulename + source_extension)
|
68 |
+
self.modulefilename = os.path.join(self.tmpdir, modulename + suffix)
|
69 |
+
self.ext_package = ext_package
|
70 |
+
self._has_source = False
|
71 |
+
self._has_module = False
|
72 |
+
|
73 |
+
def write_source(self, file=None):
|
74 |
+
"""Write the C source code. It is produced in 'self.sourcefilename',
|
75 |
+
which can be tweaked beforehand."""
|
76 |
+
with self.ffi._lock:
|
77 |
+
if self._has_source and file is None:
|
78 |
+
raise VerificationError(
|
79 |
+
"source code already written")
|
80 |
+
self._write_source(file)
|
81 |
+
|
82 |
+
def compile_module(self):
|
83 |
+
"""Write the C source code (if not done already) and compile it.
|
84 |
+
This produces a dynamic link library in 'self.modulefilename'."""
|
85 |
+
with self.ffi._lock:
|
86 |
+
if self._has_module:
|
87 |
+
raise VerificationError("module already compiled")
|
88 |
+
if not self._has_source:
|
89 |
+
self._write_source()
|
90 |
+
self._compile_module()
|
91 |
+
|
92 |
+
def load_library(self):
|
93 |
+
"""Get a C module from this Verifier instance.
|
94 |
+
Returns an instance of a FFILibrary class that behaves like the
|
95 |
+
objects returned by ffi.dlopen(), but that delegates all
|
96 |
+
operations to the C module. If necessary, the C code is written
|
97 |
+
and compiled first.
|
98 |
+
"""
|
99 |
+
with self.ffi._lock:
|
100 |
+
if not self._has_module:
|
101 |
+
self._locate_module()
|
102 |
+
if not self._has_module:
|
103 |
+
if not self._has_source:
|
104 |
+
self._write_source()
|
105 |
+
self._compile_module()
|
106 |
+
return self._load_library()
|
107 |
+
|
108 |
+
def get_module_name(self):
|
109 |
+
basename = os.path.basename(self.modulefilename)
|
110 |
+
# kill both the .so extension and the other .'s, as introduced
|
111 |
+
# by Python 3: 'basename.cpython-33m.so'
|
112 |
+
basename = basename.split('.', 1)[0]
|
113 |
+
# and the _d added in Python 2 debug builds --- but try to be
|
114 |
+
# conservative and not kill a legitimate _d
|
115 |
+
if basename.endswith('_d') and hasattr(sys, 'gettotalrefcount'):
|
116 |
+
basename = basename[:-2]
|
117 |
+
return basename
|
118 |
+
|
119 |
+
def get_extension(self):
|
120 |
+
if not self._has_source:
|
121 |
+
with self.ffi._lock:
|
122 |
+
if not self._has_source:
|
123 |
+
self._write_source()
|
124 |
+
sourcename = ffiplatform.maybe_relative_path(self.sourcefilename)
|
125 |
+
modname = self.get_module_name()
|
126 |
+
return ffiplatform.get_extension(sourcename, modname, **self.kwds)
|
127 |
+
|
128 |
+
def generates_python_module(self):
|
129 |
+
return self._vengine._gen_python_module
|
130 |
+
|
131 |
+
def make_relative_to(self, kwds, relative_to):
|
132 |
+
if relative_to and os.path.dirname(relative_to):
|
133 |
+
dirname = os.path.dirname(relative_to)
|
134 |
+
kwds = kwds.copy()
|
135 |
+
for key in ffiplatform.LIST_OF_FILE_NAMES:
|
136 |
+
if key in kwds:
|
137 |
+
lst = kwds[key]
|
138 |
+
if not isinstance(lst, (list, tuple)):
|
139 |
+
raise TypeError("keyword '%s' should be a list or tuple"
|
140 |
+
% (key,))
|
141 |
+
lst = [os.path.join(dirname, fn) for fn in lst]
|
142 |
+
kwds[key] = lst
|
143 |
+
return kwds
|
144 |
+
|
145 |
+
# ----------
|
146 |
+
|
147 |
+
def _locate_module(self):
|
148 |
+
if not os.path.isfile(self.modulefilename):
|
149 |
+
if self.ext_package:
|
150 |
+
try:
|
151 |
+
pkg = __import__(self.ext_package, None, None, ['__doc__'])
|
152 |
+
except ImportError:
|
153 |
+
return # cannot import the package itself, give up
|
154 |
+
# (e.g. it might be called differently before installation)
|
155 |
+
path = pkg.__path__
|
156 |
+
else:
|
157 |
+
path = None
|
158 |
+
filename = self._vengine.find_module(self.get_module_name(), path,
|
159 |
+
_get_so_suffixes())
|
160 |
+
if filename is None:
|
161 |
+
return
|
162 |
+
self.modulefilename = filename
|
163 |
+
self._vengine.collect_types()
|
164 |
+
self._has_module = True
|
165 |
+
|
166 |
+
def _write_source_to(self, file):
|
167 |
+
self._vengine._f = file
|
168 |
+
try:
|
169 |
+
self._vengine.write_source_to_f()
|
170 |
+
finally:
|
171 |
+
del self._vengine._f
|
172 |
+
|
173 |
+
def _write_source(self, file=None):
|
174 |
+
if file is not None:
|
175 |
+
self._write_source_to(file)
|
176 |
+
else:
|
177 |
+
# Write our source file to an in memory file.
|
178 |
+
f = NativeIO()
|
179 |
+
self._write_source_to(f)
|
180 |
+
source_data = f.getvalue()
|
181 |
+
|
182 |
+
# Determine if this matches the current file
|
183 |
+
if os.path.exists(self.sourcefilename):
|
184 |
+
with open(self.sourcefilename, "r") as fp:
|
185 |
+
needs_written = not (fp.read() == source_data)
|
186 |
+
else:
|
187 |
+
needs_written = True
|
188 |
+
|
189 |
+
# Actually write the file out if it doesn't match
|
190 |
+
if needs_written:
|
191 |
+
_ensure_dir(self.sourcefilename)
|
192 |
+
with open(self.sourcefilename, "w") as fp:
|
193 |
+
fp.write(source_data)
|
194 |
+
|
195 |
+
# Set this flag
|
196 |
+
self._has_source = True
|
197 |
+
|
198 |
+
def _compile_module(self):
|
199 |
+
# compile this C source
|
200 |
+
tmpdir = os.path.dirname(self.sourcefilename)
|
201 |
+
outputfilename = ffiplatform.compile(tmpdir, self.get_extension())
|
202 |
+
try:
|
203 |
+
same = ffiplatform.samefile(outputfilename, self.modulefilename)
|
204 |
+
except OSError:
|
205 |
+
same = False
|
206 |
+
if not same:
|
207 |
+
_ensure_dir(self.modulefilename)
|
208 |
+
shutil.move(outputfilename, self.modulefilename)
|
209 |
+
self._has_module = True
|
210 |
+
|
211 |
+
def _load_library(self):
|
212 |
+
assert self._has_module
|
213 |
+
if self.flags is not None:
|
214 |
+
return self._vengine.load_library(self.flags)
|
215 |
+
else:
|
216 |
+
return self._vengine.load_library()
|
217 |
+
|
218 |
+
# ____________________________________________________________
|
219 |
+
|
220 |
+
_FORCE_GENERIC_ENGINE = False # for tests
|
221 |
+
|
222 |
+
def _locate_engine_class(ffi, force_generic_engine):
|
223 |
+
if _FORCE_GENERIC_ENGINE:
|
224 |
+
force_generic_engine = True
|
225 |
+
if not force_generic_engine:
|
226 |
+
if '__pypy__' in sys.builtin_module_names:
|
227 |
+
force_generic_engine = True
|
228 |
+
else:
|
229 |
+
try:
|
230 |
+
import _cffi_backend
|
231 |
+
except ImportError:
|
232 |
+
_cffi_backend = '?'
|
233 |
+
if ffi._backend is not _cffi_backend:
|
234 |
+
force_generic_engine = True
|
235 |
+
if force_generic_engine:
|
236 |
+
from . import vengine_gen
|
237 |
+
return vengine_gen.VGenericEngine
|
238 |
+
else:
|
239 |
+
from . import vengine_cpy
|
240 |
+
return vengine_cpy.VCPythonEngine
|
241 |
+
|
242 |
+
# ____________________________________________________________
|
243 |
+
|
244 |
+
_TMPDIR = None
|
245 |
+
|
246 |
+
def _caller_dir_pycache():
|
247 |
+
if _TMPDIR:
|
248 |
+
return _TMPDIR
|
249 |
+
result = os.environ.get('CFFI_TMPDIR')
|
250 |
+
if result:
|
251 |
+
return result
|
252 |
+
filename = sys._getframe(2).f_code.co_filename
|
253 |
+
return os.path.abspath(os.path.join(os.path.dirname(filename),
|
254 |
+
'__pycache__'))
|
255 |
+
|
256 |
+
def set_tmpdir(dirname):
|
257 |
+
"""Set the temporary directory to use instead of __pycache__."""
|
258 |
+
global _TMPDIR
|
259 |
+
_TMPDIR = dirname
|
260 |
+
|
261 |
+
def cleanup_tmpdir(tmpdir=None, keep_so=False):
|
262 |
+
"""Clean up the temporary directory by removing all files in it
|
263 |
+
called `_cffi_*.{c,so}` as well as the `build` subdirectory."""
|
264 |
+
tmpdir = tmpdir or _caller_dir_pycache()
|
265 |
+
try:
|
266 |
+
filelist = os.listdir(tmpdir)
|
267 |
+
except OSError:
|
268 |
+
return
|
269 |
+
if keep_so:
|
270 |
+
suffix = '.c' # only remove .c files
|
271 |
+
else:
|
272 |
+
suffix = _get_so_suffixes()[0].lower()
|
273 |
+
for fn in filelist:
|
274 |
+
if fn.lower().startswith('_cffi_') and (
|
275 |
+
fn.lower().endswith(suffix) or fn.lower().endswith('.c')):
|
276 |
+
try:
|
277 |
+
os.unlink(os.path.join(tmpdir, fn))
|
278 |
+
except OSError:
|
279 |
+
pass
|
280 |
+
clean_dir = [os.path.join(tmpdir, 'build')]
|
281 |
+
for dir in clean_dir:
|
282 |
+
try:
|
283 |
+
for fn in os.listdir(dir):
|
284 |
+
fn = os.path.join(dir, fn)
|
285 |
+
if os.path.isdir(fn):
|
286 |
+
clean_dir.append(fn)
|
287 |
+
else:
|
288 |
+
os.unlink(fn)
|
289 |
+
except OSError:
|
290 |
+
pass
|
291 |
+
|
292 |
+
def _get_so_suffixes():
|
293 |
+
suffixes = _extension_suffixes()
|
294 |
+
if not suffixes:
|
295 |
+
# bah, no C_EXTENSION available. Occurs on pypy without cpyext
|
296 |
+
if sys.platform == 'win32':
|
297 |
+
suffixes = [".pyd"]
|
298 |
+
else:
|
299 |
+
suffixes = [".so"]
|
300 |
+
|
301 |
+
return suffixes
|
302 |
+
|
303 |
+
def _ensure_dir(filename):
|
304 |
+
dirname = os.path.dirname(filename)
|
305 |
+
if dirname and not os.path.isdir(dirname):
|
306 |
+
os.makedirs(dirname)
|