lib_obj.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /* A Lib object is what is in the "lib" attribute of a C extension
  2. module originally created by recompile().
  3. A Lib object is special in the sense that it has a custom
  4. __getattr__ which returns C globals, functions and constants. The
  5. original idea was to raise AttributeError for anything else, even
  6. attrs like '__class__', but it breaks various things; now, standard
  7. attrs are returned, but in the unlikely case where a user cdef()s
  8. the same name, then the standard attr is hidden (and the various
  9. things like introspection might break).
  10. A Lib object has got a reference to the _cffi_type_context_s
  11. structure, which is used to create lazily the objects returned by
  12. __getattr__.
  13. */
  14. #if defined(_asan_enabled_)
  15. void __lsan_ignore_object(const void* p);
  16. #endif
  17. inline static void MarkAsIntentionallyLeaked(const void* ptr) {
  18. #if defined(_asan_enabled_)
  19. __lsan_ignore_object(ptr);
  20. #else
  21. (void)ptr;
  22. #endif
  23. }
  24. struct CPyExtFunc_s {
  25. PyMethodDef md;
  26. void *direct_fn;
  27. int type_index;
  28. char doc[1];
  29. };
  30. struct LibObject_s {
  31. PyObject_HEAD
  32. builder_c_t *l_types_builder; /* same as the one on the ffi object */
  33. PyObject *l_dict; /* content, built lazily */
  34. PyObject *l_libname; /* some string that gives the name of the lib */
  35. FFIObject *l_ffi; /* reference back to the ffi object */
  36. void *l_libhandle; /* the dlopen()ed handle, if any */
  37. int l_auto_close; /* if we must dlclose() this handle */
  38. };
  39. static struct CPyExtFunc_s *_cpyextfunc_get(PyObject *x)
  40. {
  41. PyObject *y;
  42. LibObject *lo;
  43. PyCFunctionObject *fo;
  44. if (!PyCFunction_Check(x))
  45. return NULL;
  46. y = PyCFunction_GET_SELF(x);
  47. if (!LibObject_Check(y))
  48. return NULL;
  49. fo = (PyCFunctionObject *)x;
  50. lo = (LibObject *)y;
  51. if (lo->l_libname != fo->m_module)
  52. return NULL;
  53. return (struct CPyExtFunc_s *)(fo->m_ml);
  54. }
  55. static PyObject *_cpyextfunc_type(LibObject *lib, struct CPyExtFunc_s *exf)
  56. {
  57. PyObject *tuple, *result;
  58. tuple = realize_c_type_or_func(lib->l_types_builder,
  59. lib->l_types_builder->ctx.types,
  60. exf->type_index);
  61. if (tuple == NULL)
  62. return NULL;
  63. /* 'tuple' is a tuple of length 1 containing the real CT_FUNCTIONPTR
  64. object */
  65. result = PyTuple_GetItem(tuple, 0);
  66. Py_XINCREF(result);
  67. Py_DECREF(tuple);
  68. return result;
  69. }
  70. static PyObject *_cpyextfunc_type_index(PyObject *x)
  71. {
  72. struct CPyExtFunc_s *exf;
  73. LibObject *lib;
  74. assert(PyErr_Occurred());
  75. exf = _cpyextfunc_get(x);
  76. if (exf == NULL)
  77. return NULL; /* still the same exception is set */
  78. PyErr_Clear();
  79. lib = (LibObject *)PyCFunction_GET_SELF(x);
  80. return _cpyextfunc_type(lib, exf);
  81. }
  82. static void cdlopen_close_ignore_errors(void *libhandle); /* forward */
  83. static void *cdlopen_fetch(PyObject *libname, void *libhandle,
  84. const char *symbol);
  85. static void lib_dealloc(LibObject *lib)
  86. {
  87. PyObject_GC_UnTrack(lib);
  88. if (lib->l_auto_close)
  89. cdlopen_close_ignore_errors(lib->l_libhandle);
  90. Py_DECREF(lib->l_dict);
  91. Py_DECREF(lib->l_libname);
  92. Py_DECREF(lib->l_ffi);
  93. PyObject_GC_Del(lib);
  94. }
  95. static int lib_traverse(LibObject *lib, visitproc visit, void *arg)
  96. {
  97. Py_VISIT(lib->l_dict);
  98. Py_VISIT(lib->l_libname);
  99. Py_VISIT(lib->l_ffi);
  100. return 0;
  101. }
  102. static PyObject *lib_repr(LibObject *lib)
  103. {
  104. return PyText_FromFormat("<Lib object for '%.200s'>",
  105. PyText_AS_UTF8(lib->l_libname));
  106. }
  107. static PyObject *lib_build_cpython_func(LibObject *lib,
  108. const struct _cffi_global_s *g,
  109. const char *s, int flags)
  110. {
  111. /* First make sure the argument types and return type are really
  112. built. The C extension code can then assume that they are,
  113. by calling _cffi_type().
  114. */
  115. PyObject *result = NULL;
  116. CTypeDescrObject **pfargs = NULL;
  117. CTypeDescrObject *fresult;
  118. Py_ssize_t nargs = 0;
  119. struct CPyExtFunc_s *xfunc;
  120. int i, type_index = _CFFI_GETARG(g->type_op);
  121. _cffi_opcode_t *opcodes = lib->l_types_builder->ctx.types;
  122. static const char *const format = ";\n\nCFFI C function from %s.lib";
  123. const char *libname = PyText_AS_UTF8(lib->l_libname);
  124. struct funcbuilder_s funcbuilder;
  125. /* return type: */
  126. fresult = realize_c_func_return_type(lib->l_types_builder, opcodes,
  127. type_index);
  128. if (fresult == NULL)
  129. goto error;
  130. /* argument types: */
  131. /* note that if the arguments are already built, they have a
  132. pointer in the 'opcodes' array, and GETOP() returns a
  133. random even value. But OP_FUNCTION_END is odd, so the
  134. condition below still works correctly. */
  135. i = type_index + 1;
  136. while (_CFFI_GETOP(opcodes[i]) != _CFFI_OP_FUNCTION_END)
  137. i++;
  138. pfargs = alloca(sizeof(CTypeDescrObject *) * (i - type_index - 1));
  139. i = type_index + 1;
  140. while (_CFFI_GETOP(opcodes[i]) != _CFFI_OP_FUNCTION_END) {
  141. CTypeDescrObject *ct = realize_c_type(lib->l_types_builder, opcodes, i);
  142. if (ct == NULL)
  143. goto error;
  144. pfargs[nargs++] = ct;
  145. i++;
  146. }
  147. memset(&funcbuilder, 0, sizeof(funcbuilder));
  148. if (fb_build_name(&funcbuilder, g->name, pfargs, nargs, fresult, 0) < 0)
  149. goto error;
  150. /* The few bytes of memory we allocate here appear to leak, but
  151. this is not a real leak. Indeed, CPython never unloads its C
  152. extension modules. There is only one PyMem_Malloc() per real
  153. C function in a CFFI C extension module. That means that this
  154. PyMem_Malloc() could also have been written with a static
  155. global variable generated for each CPYTHON_BLTN defined in the
  156. C extension, and the effect would be the same (but a bit more
  157. complicated).
  158. */
  159. xfunc = PyMem_Malloc(sizeof(struct CPyExtFunc_s) +
  160. funcbuilder.nb_bytes +
  161. strlen(format) + strlen(libname));
  162. if (xfunc == NULL) {
  163. PyErr_NoMemory();
  164. goto error;
  165. }
  166. memset((char *)xfunc, 0, sizeof(struct CPyExtFunc_s));
  167. assert(g->address);
  168. xfunc->md.ml_meth = (PyCFunction)g->address;
  169. xfunc->md.ml_flags = flags;
  170. xfunc->md.ml_name = g->name;
  171. xfunc->md.ml_doc = xfunc->doc;
  172. xfunc->direct_fn = g->size_or_direct_fn;
  173. xfunc->type_index = type_index;
  174. /* build the docstring */
  175. funcbuilder.bufferp = xfunc->doc;
  176. if (fb_build_name(&funcbuilder, g->name, pfargs, nargs, fresult, 0) < 0)
  177. goto error;
  178. sprintf(funcbuilder.bufferp - 1, format, libname);
  179. /* done building the docstring */
  180. result = PyCFunction_NewEx(&xfunc->md, (PyObject *)lib, lib->l_libname);
  181. /* fall-through */
  182. error:
  183. Py_XDECREF(fresult);
  184. while (nargs > 0) {
  185. --nargs;
  186. Py_DECREF(pfargs[nargs]);
  187. }
  188. return result;
  189. }
  190. static PyObject *lib_build_and_cache_attr(LibObject *lib, PyObject *name,
  191. int recursion)
  192. {
  193. /* does not return a new reference! */
  194. PyObject *x;
  195. int index;
  196. const struct _cffi_global_s *g;
  197. CTypeDescrObject *ct;
  198. builder_c_t *types_builder = lib->l_types_builder;
  199. const char *s = PyText_AsUTF8(name);
  200. if (s == NULL)
  201. return NULL;
  202. index = search_in_globals(&types_builder->ctx, s, strlen(s));
  203. if (index < 0) {
  204. if (types_builder->included_libs != NULL) {
  205. Py_ssize_t i;
  206. PyObject *included_ffis = types_builder->included_ffis;
  207. PyObject *included_libs = types_builder->included_libs;
  208. if (recursion > 100) {
  209. PyErr_SetString(PyExc_RuntimeError,
  210. "recursion overflow in ffi.include() delegations");
  211. return NULL;
  212. }
  213. for (i = 0; i < PyTuple_GET_SIZE(included_libs); i++) {
  214. LibObject *lib1;
  215. lib1 = (LibObject *)PyTuple_GET_ITEM(included_libs, i);
  216. if (lib1 != NULL) {
  217. x = PyDict_GetItem(lib1->l_dict, name);
  218. if (x != NULL) {
  219. Py_INCREF(x);
  220. goto found;
  221. }
  222. x = lib_build_and_cache_attr(lib1, name, recursion + 1);
  223. if (x != NULL) {
  224. Py_INCREF(x);
  225. goto found;
  226. }
  227. }
  228. else {
  229. FFIObject *ffi1;
  230. ffi1 = (FFIObject *)PyTuple_GetItem(included_ffis, i);
  231. if (ffi1 == NULL)
  232. return NULL;
  233. x = ffi_fetch_int_constant(ffi1, s, recursion + 1);
  234. if (x != NULL)
  235. goto found;
  236. }
  237. if (PyErr_Occurred())
  238. return NULL;
  239. }
  240. }
  241. if (recursion > 0)
  242. return NULL; /* no error set, continue looking elsewhere */
  243. PyErr_Format(PyExc_AttributeError,
  244. "cffi library '%.200s' has no function, constant "
  245. "or global variable named '%.200s'",
  246. PyText_AS_UTF8(lib->l_libname), s);
  247. return NULL;
  248. }
  249. g = &types_builder->ctx.globals[index];
  250. switch (_CFFI_GETOP(g->type_op)) {
  251. case _CFFI_OP_CPYTHON_BLTN_V:
  252. x = lib_build_cpython_func(lib, g, s, METH_VARARGS);
  253. break;
  254. case _CFFI_OP_CPYTHON_BLTN_N:
  255. x = lib_build_cpython_func(lib, g, s, METH_NOARGS);
  256. break;
  257. case _CFFI_OP_CPYTHON_BLTN_O:
  258. x = lib_build_cpython_func(lib, g, s, METH_O);
  259. break;
  260. case _CFFI_OP_CONSTANT_INT:
  261. case _CFFI_OP_ENUM:
  262. {
  263. /* a constant integer whose value, in an "unsigned long long",
  264. is obtained by calling the function at g->address */
  265. x = realize_global_int(types_builder, index);
  266. break;
  267. }
  268. case _CFFI_OP_CONSTANT:
  269. case _CFFI_OP_DLOPEN_CONST:
  270. {
  271. /* a constant which is not of integer type */
  272. char *data;
  273. ct = realize_c_type(types_builder, types_builder->ctx.types,
  274. _CFFI_GETARG(g->type_op));
  275. if (ct == NULL)
  276. return NULL;
  277. if (ct->ct_size <= 0) {
  278. PyErr_Format(FFIError, "constant '%s' is of type '%s', "
  279. "whose size is not known", s, ct->ct_name);
  280. return NULL;
  281. }
  282. if (g->address == NULL) {
  283. /* for dlopen() style */
  284. assert(_CFFI_GETOP(g->type_op) == _CFFI_OP_DLOPEN_CONST);
  285. data = cdlopen_fetch(lib->l_libname, lib->l_libhandle, s);
  286. if (data == NULL)
  287. return NULL;
  288. }
  289. else {
  290. /* The few bytes of memory we allocate here appear to leak, but
  291. this is not a real leak. Indeed, CPython never unloads its C
  292. extension modules. There is only one PyMem_Malloc() per real
  293. non-integer C constant in a CFFI C extension module. That
  294. means that this PyMem_Malloc() could also have been written
  295. with a static global variable generated for each OP_CONSTANT
  296. defined in the C extension, and the effect would be the same
  297. (but a bit more complicated).
  298. Note that we used to do alloca(), but see issue #198. We
  299. could still do alloca(), or explicit PyMem_Free(), in some
  300. cases; but there is no point and it only makes the remaining
  301. less-common cases more suspicious.
  302. */
  303. assert(_CFFI_GETOP(g->type_op) == _CFFI_OP_CONSTANT);
  304. data = PyMem_Malloc(ct->ct_size);
  305. if (data == NULL) {
  306. PyErr_NoMemory();
  307. return NULL;
  308. }
  309. MarkAsIntentionallyLeaked(data);
  310. ((void(*)(char*))g->address)(data);
  311. }
  312. x = convert_to_object(data, ct);
  313. Py_DECREF(ct);
  314. break;
  315. }
  316. case _CFFI_OP_GLOBAL_VAR:
  317. {
  318. /* global variable of the exact type specified here
  319. (nowadays, only used by the ABI mode or backward
  320. compatibility; see _CFFI_OP_GLOBAL_VAR_F for the API mode)
  321. */
  322. Py_ssize_t g_size = (Py_ssize_t)g->size_or_direct_fn;
  323. ct = realize_c_type(types_builder, types_builder->ctx.types,
  324. _CFFI_GETARG(g->type_op));
  325. if (ct == NULL)
  326. return NULL;
  327. if (g_size != ct->ct_size && g_size != 0 && ct->ct_size > 0) {
  328. PyErr_Format(FFIError,
  329. "global variable '%.200s' should be %zd bytes "
  330. "according to the cdef, but is actually %zd",
  331. s, ct->ct_size, g_size);
  332. x = NULL;
  333. }
  334. else {
  335. void *address = g->address;
  336. if (address == NULL) {
  337. /* for dlopen() style */
  338. address = cdlopen_fetch(lib->l_libname, lib->l_libhandle, s);
  339. if (address == NULL)
  340. return NULL;
  341. }
  342. x = make_global_var(name, ct, address, NULL);
  343. }
  344. Py_DECREF(ct);
  345. break;
  346. }
  347. case _CFFI_OP_GLOBAL_VAR_F:
  348. ct = realize_c_type(types_builder, types_builder->ctx.types,
  349. _CFFI_GETARG(g->type_op));
  350. if (ct == NULL)
  351. return NULL;
  352. x = make_global_var(name, ct, NULL, (gs_fetch_addr_fn)g->address);
  353. Py_DECREF(ct);
  354. break;
  355. case _CFFI_OP_DLOPEN_FUNC:
  356. {
  357. /* For dlopen(): the function of the given 'name'. We use
  358. dlsym() to get the address of something in the dynamic
  359. library, which we interpret as being exactly a function of
  360. the specified type.
  361. */
  362. PyObject *ct1;
  363. void *address = cdlopen_fetch(lib->l_libname, lib->l_libhandle, s);
  364. if (address == NULL)
  365. return NULL;
  366. ct1 = realize_c_type_or_func(types_builder,
  367. types_builder->ctx.types,
  368. _CFFI_GETARG(g->type_op));
  369. if (ct1 == NULL)
  370. return NULL;
  371. assert(!CTypeDescr_Check(ct1)); /* must be a function */
  372. x = new_simple_cdata(address, unwrap_fn_as_fnptr(ct1));
  373. Py_DECREF(ct1);
  374. break;
  375. }
  376. case _CFFI_OP_EXTERN_PYTHON:
  377. /* for reading 'lib.bar' where bar is declared with extern "Python" */
  378. ct = realize_c_type(types_builder, types_builder->ctx.types,
  379. _CFFI_GETARG(g->type_op));
  380. if (ct == NULL)
  381. return NULL;
  382. x = convert_to_object((char *)&g->size_or_direct_fn, ct);
  383. Py_DECREF(ct);
  384. break;
  385. default:
  386. PyErr_Format(PyExc_NotImplementedError, "in lib_build_attr: op=%d",
  387. (int)_CFFI_GETOP(g->type_op));
  388. return NULL;
  389. }
  390. found:
  391. if (x != NULL) {
  392. int err = PyDict_SetItem(lib->l_dict, name, x);
  393. Py_DECREF(x);
  394. if (err < 0) /* else there is still one ref left in the dict */
  395. return NULL;
  396. }
  397. return x;
  398. }
  399. #define LIB_GET_OR_CACHE_ADDR(x, lib, name, error) \
  400. do { \
  401. x = PyDict_GetItem(lib->l_dict, name); \
  402. if (x == NULL) { \
  403. x = lib_build_and_cache_attr(lib, name, 0); \
  404. if (x == NULL) { \
  405. error; \
  406. } \
  407. } \
  408. } while (0)
  409. static PyObject *_lib_dir1(LibObject *lib, int ignore_global_vars)
  410. {
  411. const struct _cffi_global_s *g = lib->l_types_builder->ctx.globals;
  412. int i, count = 0, total = lib->l_types_builder->ctx.num_globals;
  413. PyObject *s, *lst = PyList_New(total);
  414. if (lst == NULL)
  415. return NULL;
  416. for (i = 0; i < total; i++) {
  417. if (ignore_global_vars) {
  418. int op = _CFFI_GETOP(g[i].type_op);
  419. if (op == _CFFI_OP_GLOBAL_VAR || op == _CFFI_OP_GLOBAL_VAR_F)
  420. continue;
  421. }
  422. s = PyText_FromString(g[i].name);
  423. if (s == NULL)
  424. goto error;
  425. PyList_SET_ITEM(lst, count, s);
  426. count++;
  427. }
  428. if (PyList_SetSlice(lst, count, total, NULL) < 0)
  429. goto error;
  430. return lst;
  431. error:
  432. Py_DECREF(lst);
  433. return NULL;
  434. }
  435. static PyObject *_lib_dict(LibObject *lib)
  436. {
  437. const struct _cffi_global_s *g = lib->l_types_builder->ctx.globals;
  438. int i, total = lib->l_types_builder->ctx.num_globals;
  439. PyObject *name, *x, *d = PyDict_New();
  440. if (d == NULL)
  441. return NULL;
  442. for (i = 0; i < total; i++) {
  443. name = PyText_FromString(g[i].name);
  444. if (name == NULL)
  445. goto error;
  446. LIB_GET_OR_CACHE_ADDR(x, lib, name, goto error);
  447. if (PyDict_SetItem(d, name, x) < 0)
  448. goto error;
  449. Py_DECREF(name);
  450. }
  451. return d;
  452. error:
  453. Py_XDECREF(name);
  454. Py_DECREF(d);
  455. return NULL;
  456. }
  457. static PyObject *lib_getattr(LibObject *lib, PyObject *name)
  458. {
  459. const char *p;
  460. PyObject *x;
  461. LIB_GET_OR_CACHE_ADDR(x, lib, name, goto missing);
  462. if (GlobSupport_Check(x)) {
  463. return read_global_var((GlobSupportObject *)x);
  464. }
  465. Py_INCREF(x);
  466. return x;
  467. missing:
  468. /*** ATTRIBUTEERROR IS SET HERE ***/
  469. p = PyText_AsUTF8(name);
  470. if (p == NULL)
  471. return NULL;
  472. if (strcmp(p, "__all__") == 0) {
  473. PyErr_Clear();
  474. return _lib_dir1(lib, 1);
  475. }
  476. if (strcmp(p, "__dict__") == 0) {
  477. PyErr_Clear();
  478. return _lib_dict(lib);
  479. }
  480. if (strcmp(p, "__class__") == 0) {
  481. PyErr_Clear();
  482. x = (PyObject *)&PyModule_Type;
  483. /* ^^^ used to be Py_TYPE(lib). But HAAAAAACK! That makes
  484. help() behave correctly. I couldn't find a more reasonable
  485. way. Urgh. */
  486. Py_INCREF(x);
  487. return x;
  488. }
  489. /* this hack is for Python 3.5, and also to give a more
  490. module-like behavior */
  491. if (strcmp(p, "__name__") == 0) {
  492. PyErr_Clear();
  493. return PyText_FromFormat("%s.lib", PyText_AS_UTF8(lib->l_libname));
  494. }
  495. #if PY_MAJOR_VERSION >= 3
  496. if (strcmp(p, "__loader__") == 0 || strcmp(p, "__spec__") == 0) {
  497. /* some more module-like behavior hacks */
  498. PyErr_Clear();
  499. Py_INCREF(Py_None);
  500. return Py_None;
  501. }
  502. #endif
  503. return NULL;
  504. }
  505. static int lib_setattr(LibObject *lib, PyObject *name, PyObject *val)
  506. {
  507. PyObject *x;
  508. LIB_GET_OR_CACHE_ADDR(x, lib, name, return -1);
  509. if (val == NULL) {
  510. PyErr_SetString(PyExc_AttributeError, "C attribute cannot be deleted");
  511. return -1;
  512. }
  513. if (GlobSupport_Check(x)) {
  514. return write_global_var((GlobSupportObject *)x, val);
  515. }
  516. PyErr_Format(PyExc_AttributeError,
  517. "cannot write to function or constant '%.200s'",
  518. PyText_Check(name) ? PyText_AS_UTF8(name) : "?");
  519. return -1;
  520. }
  521. static PyObject *lib_dir(PyObject *self, PyObject *noarg)
  522. {
  523. return _lib_dir1((LibObject *)self, 0);
  524. }
  525. static PyMethodDef lib_methods[] = {
  526. {"__dir__", lib_dir, METH_NOARGS},
  527. {NULL, NULL} /* sentinel */
  528. };
  529. static PyTypeObject Lib_Type = {
  530. PyVarObject_HEAD_INIT(NULL, 0)
  531. "_cffi_backend.Lib",
  532. sizeof(LibObject),
  533. 0,
  534. (destructor)lib_dealloc, /* tp_dealloc */
  535. 0, /* tp_print */
  536. 0, /* tp_getattr */
  537. 0, /* tp_setattr */
  538. 0, /* tp_compare */
  539. (reprfunc)lib_repr, /* tp_repr */
  540. 0, /* tp_as_number */
  541. 0, /* tp_as_sequence */
  542. 0, /* tp_as_mapping */
  543. 0, /* tp_hash */
  544. 0, /* tp_call */
  545. 0, /* tp_str */
  546. (getattrofunc)lib_getattr, /* tp_getattro */
  547. (setattrofunc)lib_setattr, /* tp_setattro */
  548. 0, /* tp_as_buffer */
  549. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  550. 0, /* tp_doc */
  551. (traverseproc)lib_traverse, /* tp_traverse */
  552. 0, /* tp_clear */
  553. 0, /* tp_richcompare */
  554. 0, /* tp_weaklistoffset */
  555. 0, /* tp_iter */
  556. 0, /* tp_iternext */
  557. lib_methods, /* tp_methods */
  558. 0, /* tp_members */
  559. 0, /* tp_getset */
  560. 0, /* tp_base */
  561. 0, /* tp_dict */
  562. 0, /* tp_descr_get */
  563. 0, /* tp_descr_set */
  564. offsetof(LibObject, l_dict), /* tp_dictoffset */
  565. };
  566. static LibObject *lib_internal_new(FFIObject *ffi, const char *module_name,
  567. void *dlopen_libhandle, int auto_close)
  568. {
  569. LibObject *lib;
  570. PyObject *libname, *dict;
  571. libname = PyText_FromString(module_name);
  572. if (libname == NULL)
  573. goto err1;
  574. dict = PyDict_New();
  575. if (dict == NULL)
  576. goto err2;
  577. lib = (LibObject *)PyType_GenericAlloc(&Lib_Type, 0);
  578. if (lib == NULL)
  579. goto err3;
  580. lib->l_types_builder = &ffi->types_builder;
  581. lib->l_dict = dict;
  582. lib->l_libname = libname;
  583. Py_INCREF(ffi);
  584. lib->l_ffi = ffi;
  585. lib->l_libhandle = dlopen_libhandle;
  586. lib->l_auto_close = auto_close;
  587. return lib;
  588. err3:
  589. Py_DECREF(dict);
  590. err2:
  591. Py_DECREF(libname);
  592. err1:
  593. if (auto_close)
  594. cdlopen_close_ignore_errors(dlopen_libhandle);
  595. return NULL;
  596. }
  597. static PyObject *address_of_global_var(PyObject *args)
  598. {
  599. LibObject *lib;
  600. PyObject *x, *o_varname;
  601. char *varname;
  602. if (!PyArg_ParseTuple(args, "O!s", &Lib_Type, &lib, &varname))
  603. return NULL;
  604. /* rebuild a string from 'varname', to do typechecks and to force
  605. a unicode back to a plain string (on python 2) */
  606. o_varname = PyText_FromString(varname);
  607. if (o_varname == NULL)
  608. return NULL;
  609. LIB_GET_OR_CACHE_ADDR(x, lib, o_varname, goto error);
  610. Py_DECREF(o_varname);
  611. if (GlobSupport_Check(x)) {
  612. return cg_addressof_global_var((GlobSupportObject *)x);
  613. }
  614. else {
  615. struct CPyExtFunc_s *exf = _cpyextfunc_get(x);
  616. if (exf != NULL) { /* an OP_CPYTHON_BLTN: '&func' returns a cdata */
  617. PyObject *ct;
  618. if (exf->direct_fn == NULL) {
  619. Py_INCREF(x); /* backward compatibility */
  620. return x;
  621. }
  622. ct = _cpyextfunc_type(lib, exf);
  623. if (ct == NULL)
  624. return NULL;
  625. x = new_simple_cdata(exf->direct_fn, (CTypeDescrObject *)ct);
  626. Py_DECREF(ct);
  627. return x;
  628. }
  629. if (CData_Check(x) && /* a constant functionptr cdata: 'f == &f' */
  630. (((CDataObject *)x)->c_type->ct_flags & CT_FUNCTIONPTR) != 0) {
  631. Py_INCREF(x);
  632. return x;
  633. }
  634. else {
  635. PyErr_Format(PyExc_AttributeError,
  636. "cannot take the address of the constant '%.200s'",
  637. varname);
  638. return NULL;
  639. }
  640. }
  641. error:
  642. Py_DECREF(o_varname);
  643. return NULL;
  644. }