call_python.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #if PY_VERSION_HEX >= 0x03080000
  2. # define HAVE_PYINTERPSTATE_GETDICT
  3. #endif
  4. static PyObject *_current_interp_key(void)
  5. {
  6. PyInterpreterState *interp = PyThreadState_GET()->interp;
  7. #ifdef HAVE_PYINTERPSTATE_GETDICT
  8. return PyInterpreterState_GetDict(interp); /* shared reference */
  9. #else
  10. return interp->modules;
  11. #endif
  12. }
  13. static PyObject *_get_interpstate_dict(void)
  14. {
  15. /* Hack around to return a dict that is subinterpreter-local.
  16. Does not return a new reference. Returns NULL in case of
  17. error, but without setting any exception. (If called late
  18. during shutdown, we *can't* set an exception!)
  19. */
  20. static PyObject *attr_name = NULL;
  21. PyThreadState *tstate;
  22. PyObject *d, *interpdict;
  23. int err;
  24. PyInterpreterState *interp;
  25. tstate = PyThreadState_GET();
  26. if (tstate == NULL) {
  27. /* no thread state! */
  28. return NULL;
  29. }
  30. interp = tstate->interp;
  31. #ifdef HAVE_PYINTERPSTATE_GETDICT
  32. interpdict = PyInterpreterState_GetDict(interp); /* shared reference */
  33. #else
  34. interpdict = interp->builtins;
  35. #endif
  36. if (interpdict == NULL) {
  37. /* subinterpreter was cleared already, or is being cleared right now,
  38. to a point that is too much for us to continue */
  39. return NULL;
  40. }
  41. /* from there on, we know the (sub-)interpreter is still valid */
  42. if (attr_name == NULL) {
  43. attr_name = PyText_InternFromString("__cffi_backend_extern_py");
  44. if (attr_name == NULL)
  45. goto error;
  46. }
  47. d = PyDict_GetItem(interpdict, attr_name);
  48. if (d == NULL) {
  49. d = PyDict_New();
  50. if (d == NULL)
  51. goto error;
  52. err = PyDict_SetItem(interpdict, attr_name, d);
  53. Py_DECREF(d); /* if successful, there is one ref left in interpdict */
  54. if (err < 0)
  55. goto error;
  56. }
  57. return d;
  58. error:
  59. PyErr_Clear(); /* typically a MemoryError */
  60. return NULL;
  61. }
  62. static PyObject *_ffi_def_extern_decorator(PyObject *outer_args, PyObject *fn)
  63. {
  64. const char *s;
  65. PyObject *error, *onerror, *infotuple, *old1;
  66. int index, err;
  67. const struct _cffi_global_s *g;
  68. struct _cffi_externpy_s *externpy;
  69. CTypeDescrObject *ct;
  70. FFIObject *ffi;
  71. builder_c_t *types_builder;
  72. PyObject *name = NULL;
  73. PyObject *interpstate_dict;
  74. PyObject *interpstate_key;
  75. if (!PyArg_ParseTuple(outer_args, "OzOO", &ffi, &s, &error, &onerror))
  76. return NULL;
  77. if (s == NULL) {
  78. name = PyObject_GetAttrString(fn, "__name__");
  79. if (name == NULL)
  80. return NULL;
  81. s = PyText_AsUTF8(name);
  82. if (s == NULL) {
  83. Py_DECREF(name);
  84. return NULL;
  85. }
  86. }
  87. types_builder = &ffi->types_builder;
  88. index = search_in_globals(&types_builder->ctx, s, strlen(s));
  89. if (index < 0)
  90. goto not_found;
  91. g = &types_builder->ctx.globals[index];
  92. if (_CFFI_GETOP(g->type_op) != _CFFI_OP_EXTERN_PYTHON)
  93. goto not_found;
  94. Py_XDECREF(name);
  95. ct = realize_c_type(types_builder, types_builder->ctx.types,
  96. _CFFI_GETARG(g->type_op));
  97. if (ct == NULL)
  98. return NULL;
  99. infotuple = prepare_callback_info_tuple(ct, fn, error, onerror, 0);
  100. Py_DECREF(ct);
  101. if (infotuple == NULL)
  102. return NULL;
  103. /* don't directly attach infotuple to externpy: in the presence of
  104. subinterpreters, each time we switch to a different
  105. subinterpreter and call the C function, it will notice the
  106. change and look up infotuple from the interpstate_dict.
  107. */
  108. interpstate_dict = _get_interpstate_dict();
  109. if (interpstate_dict == NULL) {
  110. Py_DECREF(infotuple);
  111. return PyErr_NoMemory();
  112. }
  113. externpy = (struct _cffi_externpy_s *)g->address;
  114. interpstate_key = PyLong_FromVoidPtr((void *)externpy);
  115. if (interpstate_key == NULL) {
  116. Py_DECREF(infotuple);
  117. return NULL;
  118. }
  119. err = PyDict_SetItem(interpstate_dict, interpstate_key, infotuple);
  120. Py_DECREF(interpstate_key);
  121. Py_DECREF(infotuple); /* interpstate_dict owns the last ref */
  122. if (err < 0)
  123. return NULL;
  124. /* force _update_cache_to_call_python() to be called the next time
  125. the C function invokes cffi_call_python, to update the cache */
  126. old1 = externpy->reserved1;
  127. externpy->reserved1 = Py_None; /* a non-NULL value */
  128. Py_INCREF(Py_None);
  129. Py_XDECREF(old1);
  130. /* return the function object unmodified */
  131. Py_INCREF(fn);
  132. return fn;
  133. not_found:
  134. PyErr_Format(FFIError, "ffi.def_extern('%s'): no 'extern \"Python\"' "
  135. "function with this name", s);
  136. Py_XDECREF(name);
  137. return NULL;
  138. }
  139. static int _update_cache_to_call_python(struct _cffi_externpy_s *externpy)
  140. {
  141. PyObject *interpstate_dict, *interpstate_key, *infotuple, *old1, *new1;
  142. PyObject *old2;
  143. interpstate_dict = _get_interpstate_dict();
  144. if (interpstate_dict == NULL)
  145. return 4; /* oops, shutdown issue? */
  146. interpstate_key = PyLong_FromVoidPtr((void *)externpy);
  147. if (interpstate_key == NULL)
  148. goto error;
  149. infotuple = PyDict_GetItem(interpstate_dict, interpstate_key);
  150. Py_DECREF(interpstate_key);
  151. if (infotuple == NULL)
  152. return 3; /* no ffi.def_extern() from this subinterpreter */
  153. new1 = _current_interp_key();
  154. Py_INCREF(new1);
  155. Py_INCREF(infotuple);
  156. old1 = (PyObject *)externpy->reserved1;
  157. old2 = (PyObject *)externpy->reserved2;
  158. externpy->reserved1 = new1; /* holds a reference */
  159. externpy->reserved2 = infotuple; /* holds a reference (issue #246) */
  160. Py_XDECREF(old1);
  161. Py_XDECREF(old2);
  162. return 0; /* no error */
  163. error:
  164. PyErr_Clear();
  165. return 2; /* out of memory? */
  166. }
  167. #if (defined(WITH_THREAD) && !defined(_MSC_VER) && \
  168. !defined(__amd64__) && !defined(__x86_64__) && \
  169. !defined(__i386__) && !defined(__i386))
  170. # if defined(HAVE_SYNC_SYNCHRONIZE)
  171. # define read_barrier() __sync_synchronize()
  172. # elif defined(_AIX)
  173. # define read_barrier() __lwsync()
  174. # elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
  175. # error #include <mbarrier.h>
  176. # define read_barrier() __compiler_barrier()
  177. # elif defined(__hpux)
  178. # define read_barrier() _Asm_mf()
  179. # else
  180. # define read_barrier() /* missing */
  181. # warning "no definition for read_barrier(), missing synchronization for\
  182. multi-thread initialization in embedded mode"
  183. # endif
  184. #else
  185. # define read_barrier() (void)0
  186. #endif
  187. static void cffi_call_python(struct _cffi_externpy_s *externpy, char *args)
  188. {
  189. /* Invoked by the helpers generated from extern "Python" in the cdef.
  190. 'externpy' is a static structure that describes which of the
  191. extern "Python" functions is called. It has got fields 'name' and
  192. 'type_index' describing the function, and more reserved fields
  193. that are initially zero. These reserved fields are set up by
  194. ffi.def_extern(), which invokes _ffi_def_extern_decorator() above.
  195. 'args' is a pointer to an array of 8-byte entries. Each entry
  196. contains an argument. If an argument is less than 8 bytes, only
  197. the part at the beginning of the entry is initialized. If an
  198. argument is 'long double' or a struct/union, then it is passed
  199. by reference.
  200. 'args' is also used as the place to write the result to
  201. (directly, even if more than 8 bytes). In all cases, 'args' is
  202. at least 8 bytes in size.
  203. */
  204. int err = 0;
  205. /* This read barrier is needed for _embedding.h. It is paired
  206. with the write_barrier() there. Without this barrier, we can
  207. in theory see the following situation: the Python
  208. initialization code already ran (in another thread), and the
  209. '_cffi_call_python' function pointer directed execution here;
  210. but any number of other data could still be seen as
  211. uninitialized below. For example, 'externpy' would still
  212. contain NULLs even though it was correctly set up, or
  213. 'interpreter_lock' (the GIL inside CPython) would still be seen
  214. as NULL, or 'autoInterpreterState' (used by
  215. PyGILState_Ensure()) would be NULL or contain bogus fields.
  216. */
  217. read_barrier();
  218. save_errno();
  219. /* We need the infotuple here. We could always go through
  220. _update_cache_to_call_python(), but to avoid the extra dict
  221. lookups, we cache in (reserved1, reserved2) the last seen pair
  222. (interp->modules, infotuple). The first item in this tuple is
  223. a random PyObject that identifies the subinterpreter.
  224. */
  225. if (externpy->reserved1 == NULL) {
  226. /* Not initialized! We didn't call @ffi.def_extern() on this
  227. externpy object from any subinterpreter at all. */
  228. err = 1;
  229. }
  230. else {
  231. PyGILState_STATE state = gil_ensure();
  232. if (externpy->reserved1 != _current_interp_key()) {
  233. /* Update the (reserved1, reserved2) cache. This will fail
  234. if we didn't call @ffi.def_extern() in this particular
  235. subinterpreter. */
  236. err = _update_cache_to_call_python(externpy);
  237. }
  238. if (!err) {
  239. general_invoke_callback(0, args, args, externpy->reserved2);
  240. }
  241. gil_release(state);
  242. }
  243. if (err) {
  244. static const char *msg[] = {
  245. "no code was attached to it yet with @ffi.def_extern()",
  246. "got internal exception (out of memory?)",
  247. "@ffi.def_extern() was not called in the current subinterpreter",
  248. "got internal exception (shutdown issue?)",
  249. };
  250. fprintf(stderr, "extern \"Python\": function %s() called, "
  251. "but %s. Returning 0.\n", externpy->name, msg[err-1]);
  252. memset(args, 0, externpy->size_of_result);
  253. }
  254. restore_errno();
  255. }