You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

962 line
41 KiB

  1. import sys, types
  2. from .lock import allocate_lock
  3. from .error import CDefError
  4. from . import model
  5. try:
  6. callable
  7. except NameError:
  8. # Python 3.1
  9. from collections import Callable
  10. callable = lambda x: isinstance(x, Callable)
  11. try:
  12. basestring
  13. except NameError:
  14. # Python 3.x
  15. basestring = str
  16. _unspecified = object()
  17. class FFI(object):
  18. r'''
  19. The main top-level class that you instantiate once, or once per module.
  20. Example usage:
  21. ffi = FFI()
  22. ffi.cdef("""
  23. int printf(const char *, ...);
  24. """)
  25. C = ffi.dlopen(None) # standard library
  26. -or-
  27. C = ffi.verify() # use a C compiler: verify the decl above is right
  28. C.printf("hello, %s!\n", ffi.new("char[]", "world"))
  29. '''
  30. def __init__(self, backend=None):
  31. """Create an FFI instance. The 'backend' argument is used to
  32. select a non-default backend, mostly for tests.
  33. """
  34. if backend is None:
  35. # You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with
  36. # _cffi_backend.so compiled.
  37. import _cffi_backend as backend
  38. from . import __version__
  39. if backend.__version__ != __version__:
  40. # bad version! Try to be as explicit as possible.
  41. if hasattr(backend, '__file__'):
  42. # CPython
  43. 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." % (
  44. __version__, __file__,
  45. backend.__version__, backend.__file__))
  46. else:
  47. # PyPy
  48. 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." % (
  49. __version__, __file__, backend.__version__))
  50. # (If you insist you can also try to pass the option
  51. # 'backend=backend_ctypes.CTypesBackend()', but don't
  52. # rely on it! It's probably not going to work well.)
  53. from . import cparser
  54. self._backend = backend
  55. self._lock = allocate_lock()
  56. self._parser = cparser.Parser()
  57. self._cached_btypes = {}
  58. self._parsed_types = types.ModuleType('parsed_types').__dict__
  59. self._new_types = types.ModuleType('new_types').__dict__
  60. self._function_caches = []
  61. self._libraries = []
  62. self._cdefsources = []
  63. self._included_ffis = []
  64. self._windows_unicode = None
  65. self._init_once_cache = {}
  66. self._cdef_version = None
  67. self._embedding = None
  68. self._typecache = model.get_typecache(backend)
  69. if hasattr(backend, 'set_ffi'):
  70. backend.set_ffi(self)
  71. for name in list(backend.__dict__):
  72. if name.startswith('RTLD_'):
  73. setattr(self, name, getattr(backend, name))
  74. #
  75. with self._lock:
  76. self.BVoidP = self._get_cached_btype(model.voidp_type)
  77. self.BCharA = self._get_cached_btype(model.char_array_type)
  78. if isinstance(backend, types.ModuleType):
  79. # _cffi_backend: attach these constants to the class
  80. if not hasattr(FFI, 'NULL'):
  81. FFI.NULL = self.cast(self.BVoidP, 0)
  82. FFI.CData, FFI.CType = backend._get_types()
  83. else:
  84. # ctypes backend: attach these constants to the instance
  85. self.NULL = self.cast(self.BVoidP, 0)
  86. self.CData, self.CType = backend._get_types()
  87. self.buffer = backend.buffer
  88. def cdef(self, csource, override=False, packed=False, pack=None):
  89. """Parse the given C source. This registers all declared functions,
  90. types, and global variables. The functions and global variables can
  91. then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'.
  92. The types can be used in 'ffi.new()' and other functions.
  93. If 'packed' is specified as True, all structs declared inside this
  94. cdef are packed, i.e. laid out without any field alignment at all.
  95. Alternatively, 'pack' can be a small integer, and requests for
  96. alignment greater than that are ignored (pack=1 is equivalent to
  97. packed=True).
  98. """
  99. self._cdef(csource, override=override, packed=packed, pack=pack)
  100. def embedding_api(self, csource, packed=False, pack=None):
  101. self._cdef(csource, packed=packed, pack=pack, dllexport=True)
  102. if self._embedding is None:
  103. self._embedding = ''
  104. def _cdef(self, csource, override=False, **options):
  105. if not isinstance(csource, str): # unicode, on Python 2
  106. if not isinstance(csource, basestring):
  107. raise TypeError("cdef() argument must be a string")
  108. csource = csource.encode('ascii')
  109. with self._lock:
  110. self._cdef_version = object()
  111. self._parser.parse(csource, override=override, **options)
  112. self._cdefsources.append(csource)
  113. if override:
  114. for cache in self._function_caches:
  115. cache.clear()
  116. finishlist = self._parser._recomplete
  117. if finishlist:
  118. self._parser._recomplete = []
  119. for tp in finishlist:
  120. tp.finish_backend_type(self, finishlist)
  121. def dlopen(self, name, flags=0):
  122. """Load and return a dynamic library identified by 'name'.
  123. The standard C library can be loaded by passing None.
  124. Note that functions and types declared by 'ffi.cdef()' are not
  125. linked to a particular library, just like C headers; in the
  126. library we only look for the actual (untyped) symbols.
  127. """
  128. assert isinstance(name, basestring) or name is None
  129. with self._lock:
  130. lib, function_cache = _make_ffi_library(self, name, flags)
  131. self._function_caches.append(function_cache)
  132. self._libraries.append(lib)
  133. return lib
  134. def dlclose(self, lib):
  135. """Close a library obtained with ffi.dlopen(). After this call,
  136. access to functions or variables from the library will fail
  137. (possibly with a segmentation fault).
  138. """
  139. type(lib).__cffi_close__(lib)
  140. def _typeof_locked(self, cdecl):
  141. # call me with the lock!
  142. key = cdecl
  143. if key in self._parsed_types:
  144. return self._parsed_types[key]
  145. #
  146. if not isinstance(cdecl, str): # unicode, on Python 2
  147. cdecl = cdecl.encode('ascii')
  148. #
  149. type = self._parser.parse_type(cdecl)
  150. really_a_function_type = type.is_raw_function
  151. if really_a_function_type:
  152. type = type.as_function_pointer()
  153. btype = self._get_cached_btype(type)
  154. result = btype, really_a_function_type
  155. self._parsed_types[key] = result
  156. return result
  157. def _typeof(self, cdecl, consider_function_as_funcptr=False):
  158. # string -> ctype object
  159. try:
  160. result = self._parsed_types[cdecl]
  161. except KeyError:
  162. with self._lock:
  163. result = self._typeof_locked(cdecl)
  164. #
  165. btype, really_a_function_type = result
  166. if really_a_function_type and not consider_function_as_funcptr:
  167. raise CDefError("the type %r is a function type, not a "
  168. "pointer-to-function type" % (cdecl,))
  169. return btype
  170. def typeof(self, cdecl):
  171. """Parse the C type given as a string and return the
  172. corresponding <ctype> object.
  173. It can also be used on 'cdata' instance to get its C type.
  174. """
  175. if isinstance(cdecl, basestring):
  176. return self._typeof(cdecl)
  177. if isinstance(cdecl, self.CData):
  178. return self._backend.typeof(cdecl)
  179. if isinstance(cdecl, types.BuiltinFunctionType):
  180. res = _builtin_function_type(cdecl)
  181. if res is not None:
  182. return res
  183. if (isinstance(cdecl, types.FunctionType)
  184. and hasattr(cdecl, '_cffi_base_type')):
  185. with self._lock:
  186. return self._get_cached_btype(cdecl._cffi_base_type)
  187. raise TypeError(type(cdecl))
  188. def sizeof(self, cdecl):
  189. """Return the size in bytes of the argument. It can be a
  190. string naming a C type, or a 'cdata' instance.
  191. """
  192. if isinstance(cdecl, basestring):
  193. BType = self._typeof(cdecl)
  194. return self._backend.sizeof(BType)
  195. else:
  196. return self._backend.sizeof(cdecl)
  197. def alignof(self, cdecl):
  198. """Return the natural alignment size in bytes of the C type
  199. given as a string.
  200. """
  201. if isinstance(cdecl, basestring):
  202. cdecl = self._typeof(cdecl)
  203. return self._backend.alignof(cdecl)
  204. def offsetof(self, cdecl, *fields_or_indexes):
  205. """Return the offset of the named field inside the given
  206. structure or array, which must be given as a C type name.
  207. You can give several field names in case of nested structures.
  208. You can also give numeric values which correspond to array
  209. items, in case of an array type.
  210. """
  211. if isinstance(cdecl, basestring):
  212. cdecl = self._typeof(cdecl)
  213. return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
  214. def new(self, cdecl, init=None):
  215. """Allocate an instance according to the specified C type and
  216. return a pointer to it. The specified C type must be either a
  217. pointer or an array: ``new('X *')`` allocates an X and returns
  218. a pointer to it, whereas ``new('X[n]')`` allocates an array of
  219. n X'es and returns an array referencing it (which works
  220. mostly like a pointer, like in C). You can also use
  221. ``new('X[]', n)`` to allocate an array of a non-constant
  222. length n.
  223. The memory is initialized following the rules of declaring a
  224. global variable in C: by default it is zero-initialized, but
  225. an explicit initializer can be given which can be used to
  226. fill all or part of the memory.
  227. When the returned <cdata> object goes out of scope, the memory
  228. is freed. In other words the returned <cdata> object has
  229. ownership of the value of type 'cdecl' that it points to. This
  230. means that the raw data can be used as long as this object is
  231. kept alive, but must not be used for a longer time. Be careful
  232. about that when copying the pointer to the memory somewhere
  233. else, e.g. into another structure.
  234. """
  235. if isinstance(cdecl, basestring):
  236. cdecl = self._typeof(cdecl)
  237. return self._backend.newp(cdecl, init)
  238. def new_allocator(self, alloc=None, free=None,
  239. should_clear_after_alloc=True):
  240. """Return a new allocator, i.e. a function that behaves like ffi.new()
  241. but uses the provided low-level 'alloc' and 'free' functions.
  242. 'alloc' is called with the size as argument. If it returns NULL, a
  243. MemoryError is raised. 'free' is called with the result of 'alloc'
  244. as argument. Both can be either Python function or directly C
  245. functions. If 'free' is None, then no free function is called.
  246. If both 'alloc' and 'free' are None, the default is used.
  247. If 'should_clear_after_alloc' is set to False, then the memory
  248. returned by 'alloc' is assumed to be already cleared (or you are
  249. fine with garbage); otherwise CFFI will clear it.
  250. """
  251. compiled_ffi = self._backend.FFI()
  252. allocator = compiled_ffi.new_allocator(alloc, free,
  253. should_clear_after_alloc)
  254. def allocate(cdecl, init=None):
  255. if isinstance(cdecl, basestring):
  256. cdecl = self._typeof(cdecl)
  257. return allocator(cdecl, init)
  258. return allocate
  259. def cast(self, cdecl, source):
  260. """Similar to a C cast: returns an instance of the named C
  261. type initialized with the given 'source'. The source is
  262. casted between integers or pointers of any type.
  263. """
  264. if isinstance(cdecl, basestring):
  265. cdecl = self._typeof(cdecl)
  266. return self._backend.cast(cdecl, source)
  267. def string(self, cdata, maxlen=-1):
  268. """Return a Python string (or unicode string) from the 'cdata'.
  269. If 'cdata' is a pointer or array of characters or bytes, returns
  270. the null-terminated string. The returned string extends until
  271. the first null character, or at most 'maxlen' characters. If
  272. 'cdata' is an array then 'maxlen' defaults to its length.
  273. If 'cdata' is a pointer or array of wchar_t, returns a unicode
  274. string following the same rules.
  275. If 'cdata' is a single character or byte or a wchar_t, returns
  276. it as a string or unicode string.
  277. If 'cdata' is an enum, returns the value of the enumerator as a
  278. string, or 'NUMBER' if the value is out of range.
  279. """
  280. return self._backend.string(cdata, maxlen)
  281. def unpack(self, cdata, length):
  282. """Unpack an array of C data of the given length,
  283. returning a Python string/unicode/list.
  284. If 'cdata' is a pointer to 'char', returns a byte string.
  285. It does not stop at the first null. This is equivalent to:
  286. ffi.buffer(cdata, length)[:]
  287. If 'cdata' is a pointer to 'wchar_t', returns a unicode string.
  288. 'length' is measured in wchar_t's; it is not the size in bytes.
  289. If 'cdata' is a pointer to anything else, returns a list of
  290. 'length' items. This is a faster equivalent to:
  291. [cdata[i] for i in range(length)]
  292. """
  293. return self._backend.unpack(cdata, length)
  294. #def buffer(self, cdata, size=-1):
  295. # """Return a read-write buffer object that references the raw C data
  296. # pointed to by the given 'cdata'. The 'cdata' must be a pointer or
  297. # an array. Can be passed to functions expecting a buffer, or directly
  298. # manipulated with:
  299. #
  300. # buf[:] get a copy of it in a regular string, or
  301. # buf[idx] as a single character
  302. # buf[:] = ...
  303. # buf[idx] = ... change the content
  304. # """
  305. # note that 'buffer' is a type, set on this instance by __init__
  306. def from_buffer(self, cdecl, python_buffer=_unspecified,
  307. require_writable=False):
  308. """Return a cdata of the given type pointing to the data of the
  309. given Python object, which must support the buffer interface.
  310. Note that this is not meant to be used on the built-in types
  311. str or unicode (you can build 'char[]' arrays explicitly)
  312. but only on objects containing large quantities of raw data
  313. in some other format, like 'array.array' or numpy arrays.
  314. The first argument is optional and default to 'char[]'.
  315. """
  316. if python_buffer is _unspecified:
  317. cdecl, python_buffer = self.BCharA, cdecl
  318. elif isinstance(cdecl, basestring):
  319. cdecl = self._typeof(cdecl)
  320. return self._backend.from_buffer(cdecl, python_buffer,
  321. require_writable)
  322. def memmove(self, dest, src, n):
  323. """ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.
  324. Like the C function memmove(), the memory areas may overlap;
  325. apart from that it behaves like the C function memcpy().
  326. 'src' can be any cdata ptr or array, or any Python buffer object.
  327. 'dest' can be any cdata ptr or array, or a writable Python buffer
  328. object. The size to copy, 'n', is always measured in bytes.
  329. Unlike other methods, this one supports all Python buffer including
  330. byte strings and bytearrays---but it still does not support
  331. non-contiguous buffers.
  332. """
  333. return self._backend.memmove(dest, src, n)
  334. def callback(self, cdecl, python_callable=None, error=None, onerror=None):
  335. """Return a callback object or a decorator making such a
  336. callback object. 'cdecl' must name a C function pointer type.
  337. The callback invokes the specified 'python_callable' (which may
  338. be provided either directly or via a decorator). Important: the
  339. callback object must be manually kept alive for as long as the
  340. callback may be invoked from the C level.
  341. """
  342. def callback_decorator_wrap(python_callable):
  343. if not callable(python_callable):
  344. raise TypeError("the 'python_callable' argument "
  345. "is not callable")
  346. return self._backend.callback(cdecl, python_callable,
  347. error, onerror)
  348. if isinstance(cdecl, basestring):
  349. cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
  350. if python_callable is None:
  351. return callback_decorator_wrap # decorator mode
  352. else:
  353. return callback_decorator_wrap(python_callable) # direct mode
  354. def getctype(self, cdecl, replace_with=''):
  355. """Return a string giving the C type 'cdecl', which may be itself
  356. a string or a <ctype> object. If 'replace_with' is given, it gives
  357. extra text to append (or insert for more complicated C types), like
  358. a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
  359. """
  360. if isinstance(cdecl, basestring):
  361. cdecl = self._typeof(cdecl)
  362. replace_with = replace_with.strip()
  363. if (replace_with.startswith('*')
  364. and '&[' in self._backend.getcname(cdecl, '&')):
  365. replace_with = '(%s)' % replace_with
  366. elif replace_with and not replace_with[0] in '[(':
  367. replace_with = ' ' + replace_with
  368. return self._backend.getcname(cdecl, replace_with)
  369. def gc(self, cdata, destructor, size=0):
  370. """Return a new cdata object that points to the same
  371. data. Later, when this new cdata object is garbage-collected,
  372. 'destructor(old_cdata_object)' will be called.
  373. The optional 'size' gives an estimate of the size, used to
  374. trigger the garbage collection more eagerly. So far only used
  375. on PyPy. It tells the GC that the returned object keeps alive
  376. roughly 'size' bytes of external memory.
  377. """
  378. return self._backend.gcp(cdata, destructor, size)
  379. def _get_cached_btype(self, type):
  380. assert self._lock.acquire(False) is False
  381. # call me with the lock!
  382. try:
  383. BType = self._cached_btypes[type]
  384. except KeyError:
  385. finishlist = []
  386. BType = type.get_cached_btype(self, finishlist)
  387. for type in finishlist:
  388. type.finish_backend_type(self, finishlist)
  389. return BType
  390. def verify(self, source='', tmpdir=None, **kwargs):
  391. """Verify that the current ffi signatures compile on this
  392. machine, and return a dynamic library object. The dynamic
  393. library can be used to call functions and access global
  394. variables declared in this 'ffi'. The library is compiled
  395. by the C compiler: it gives you C-level API compatibility
  396. (including calling macros). This is unlike 'ffi.dlopen()',
  397. which requires binary compatibility in the signatures.
  398. """
  399. from .verifier import Verifier, _caller_dir_pycache
  400. #
  401. # If set_unicode(True) was called, insert the UNICODE and
  402. # _UNICODE macro declarations
  403. if self._windows_unicode:
  404. self._apply_windows_unicode(kwargs)
  405. #
  406. # Set the tmpdir here, and not in Verifier.__init__: it picks
  407. # up the caller's directory, which we want to be the caller of
  408. # ffi.verify(), as opposed to the caller of Veritier().
  409. tmpdir = tmpdir or _caller_dir_pycache()
  410. #
  411. # Make a Verifier() and use it to load the library.
  412. self.verifier = Verifier(self, source, tmpdir, **kwargs)
  413. lib = self.verifier.load_library()
  414. #
  415. # Save the loaded library for keep-alive purposes, even
  416. # if the caller doesn't keep it alive itself (it should).
  417. self._libraries.append(lib)
  418. return lib
  419. def _get_errno(self):
  420. return self._backend.get_errno()
  421. def _set_errno(self, errno):
  422. self._backend.set_errno(errno)
  423. errno = property(_get_errno, _set_errno, None,
  424. "the value of 'errno' from/to the C calls")
  425. def getwinerror(self, code=-1):
  426. return self._backend.getwinerror(code)
  427. def _pointer_to(self, ctype):
  428. with self._lock:
  429. return model.pointer_cache(self, ctype)
  430. def addressof(self, cdata, *fields_or_indexes):
  431. """Return the address of a <cdata 'struct-or-union'>.
  432. If 'fields_or_indexes' are given, returns the address of that
  433. field or array item in the structure or array, recursively in
  434. case of nested structures.
  435. """
  436. try:
  437. ctype = self._backend.typeof(cdata)
  438. except TypeError:
  439. if '__addressof__' in type(cdata).__dict__:
  440. return type(cdata).__addressof__(cdata, *fields_or_indexes)
  441. raise
  442. if fields_or_indexes:
  443. ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes)
  444. else:
  445. if ctype.kind == "pointer":
  446. raise TypeError("addressof(pointer)")
  447. offset = 0
  448. ctypeptr = self._pointer_to(ctype)
  449. return self._backend.rawaddressof(ctypeptr, cdata, offset)
  450. def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes):
  451. ctype, offset = self._backend.typeoffsetof(ctype, field_or_index)
  452. for field1 in fields_or_indexes:
  453. ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1)
  454. offset += offset1
  455. return ctype, offset
  456. def include(self, ffi_to_include):
  457. """Includes the typedefs, structs, unions and enums defined
  458. in another FFI instance. Usage is similar to a #include in C,
  459. where a part of the program might include types defined in
  460. another part for its own usage. Note that the include()
  461. method has no effect on functions, constants and global
  462. variables, which must anyway be accessed directly from the
  463. lib object returned by the original FFI instance.
  464. """
  465. if not isinstance(ffi_to_include, FFI):
  466. raise TypeError("ffi.include() expects an argument that is also of"
  467. " type cffi.FFI, not %r" % (
  468. type(ffi_to_include).__name__,))
  469. if ffi_to_include is self:
  470. raise ValueError("self.include(self)")
  471. with ffi_to_include._lock:
  472. with self._lock:
  473. self._parser.include(ffi_to_include._parser)
  474. self._cdefsources.append('[')
  475. self._cdefsources.extend(ffi_to_include._cdefsources)
  476. self._cdefsources.append(']')
  477. self._included_ffis.append(ffi_to_include)
  478. def new_handle(self, x):
  479. return self._backend.newp_handle(self.BVoidP, x)
  480. def from_handle(self, x):
  481. return self._backend.from_handle(x)
  482. def release(self, x):
  483. self._backend.release(x)
  484. def set_unicode(self, enabled_flag):
  485. """Windows: if 'enabled_flag' is True, enable the UNICODE and
  486. _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR
  487. to be (pointers to) wchar_t. If 'enabled_flag' is False,
  488. declare these types to be (pointers to) plain 8-bit characters.
  489. This is mostly for backward compatibility; you usually want True.
  490. """
  491. if self._windows_unicode is not None:
  492. raise ValueError("set_unicode() can only be called once")
  493. enabled_flag = bool(enabled_flag)
  494. if enabled_flag:
  495. self.cdef("typedef wchar_t TBYTE;"
  496. "typedef wchar_t TCHAR;"
  497. "typedef const wchar_t *LPCTSTR;"
  498. "typedef const wchar_t *PCTSTR;"
  499. "typedef wchar_t *LPTSTR;"
  500. "typedef wchar_t *PTSTR;"
  501. "typedef TBYTE *PTBYTE;"
  502. "typedef TCHAR *PTCHAR;")
  503. else:
  504. self.cdef("typedef char TBYTE;"
  505. "typedef char TCHAR;"
  506. "typedef const char *LPCTSTR;"
  507. "typedef const char *PCTSTR;"
  508. "typedef char *LPTSTR;"
  509. "typedef char *PTSTR;"
  510. "typedef TBYTE *PTBYTE;"
  511. "typedef TCHAR *PTCHAR;")
  512. self._windows_unicode = enabled_flag
  513. def _apply_windows_unicode(self, kwds):
  514. defmacros = kwds.get('define_macros', ())
  515. if not isinstance(defmacros, (list, tuple)):
  516. raise TypeError("'define_macros' must be a list or tuple")
  517. defmacros = list(defmacros) + [('UNICODE', '1'),
  518. ('_UNICODE', '1')]
  519. kwds['define_macros'] = defmacros
  520. def _apply_embedding_fix(self, kwds):
  521. # must include an argument like "-lpython2.7" for the compiler
  522. def ensure(key, value):
  523. lst = kwds.setdefault(key, [])
  524. if value not in lst:
  525. lst.append(value)
  526. #
  527. if '__pypy__' in sys.builtin_module_names:
  528. import os
  529. if sys.platform == "win32":
  530. # we need 'libpypy-c.lib'. Current distributions of
  531. # pypy (>= 4.1) contain it as 'libs/python27.lib'.
  532. pythonlib = "python{0[0]}{0[1]}".format(sys.version_info)
  533. if hasattr(sys, 'prefix'):
  534. ensure('library_dirs', os.path.join(sys.prefix, 'libs'))
  535. else:
  536. # we need 'libpypy-c.{so,dylib}', which should be by
  537. # default located in 'sys.prefix/bin' for installed
  538. # systems.
  539. if sys.version_info < (3,):
  540. pythonlib = "pypy-c"
  541. else:
  542. pythonlib = "pypy3-c"
  543. if hasattr(sys, 'prefix'):
  544. ensure('library_dirs', os.path.join(sys.prefix, 'bin'))
  545. # On uninstalled pypy's, the libpypy-c is typically found in
  546. # .../pypy/goal/.
  547. if hasattr(sys, 'prefix'):
  548. ensure('library_dirs', os.path.join(sys.prefix, 'pypy', 'goal'))
  549. else:
  550. if sys.platform == "win32":
  551. template = "python%d%d"
  552. if hasattr(sys, 'gettotalrefcount'):
  553. template += '_d'
  554. else:
  555. try:
  556. import sysconfig
  557. except ImportError: # 2.6
  558. from distutils import sysconfig
  559. template = "python%d.%d"
  560. if sysconfig.get_config_var('DEBUG_EXT'):
  561. template += sysconfig.get_config_var('DEBUG_EXT')
  562. pythonlib = (template %
  563. (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  564. if hasattr(sys, 'abiflags'):
  565. pythonlib += sys.abiflags
  566. ensure('libraries', pythonlib)
  567. if sys.platform == "win32":
  568. ensure('extra_link_args', '/MANIFEST')
  569. def set_source(self, module_name, source, source_extension='.c', **kwds):
  570. import os
  571. if hasattr(self, '_assigned_source'):
  572. raise ValueError("set_source() cannot be called several times "
  573. "per ffi object")
  574. if not isinstance(module_name, basestring):
  575. raise TypeError("'module_name' must be a string")
  576. if os.sep in module_name or (os.altsep and os.altsep in module_name):
  577. raise ValueError("'module_name' must not contain '/': use a dotted "
  578. "name to make a 'package.module' location")
  579. self._assigned_source = (str(module_name), source,
  580. source_extension, kwds)
  581. def set_source_pkgconfig(self, module_name, pkgconfig_libs, source,
  582. source_extension='.c', **kwds):
  583. from . import pkgconfig
  584. if not isinstance(pkgconfig_libs, list):
  585. raise TypeError("the pkgconfig_libs argument must be a list "
  586. "of package names")
  587. kwds2 = pkgconfig.flags_from_pkgconfig(pkgconfig_libs)
  588. pkgconfig.merge_flags(kwds, kwds2)
  589. self.set_source(module_name, source, source_extension, **kwds)
  590. def distutils_extension(self, tmpdir='build', verbose=True):
  591. from distutils.dir_util import mkpath
  592. from .recompiler import recompile
  593. #
  594. if not hasattr(self, '_assigned_source'):
  595. if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored
  596. return self.verifier.get_extension()
  597. raise ValueError("set_source() must be called before"
  598. " distutils_extension()")
  599. module_name, source, source_extension, kwds = self._assigned_source
  600. if source is None:
  601. raise TypeError("distutils_extension() is only for C extension "
  602. "modules, not for dlopen()-style pure Python "
  603. "modules")
  604. mkpath(tmpdir)
  605. ext, updated = recompile(self, module_name,
  606. source, tmpdir=tmpdir, extradir=tmpdir,
  607. source_extension=source_extension,
  608. call_c_compiler=False, **kwds)
  609. if verbose:
  610. if updated:
  611. sys.stderr.write("regenerated: %r\n" % (ext.sources[0],))
  612. else:
  613. sys.stderr.write("not modified: %r\n" % (ext.sources[0],))
  614. return ext
  615. def emit_c_code(self, filename):
  616. from .recompiler import recompile
  617. #
  618. if not hasattr(self, '_assigned_source'):
  619. raise ValueError("set_source() must be called before emit_c_code()")
  620. module_name, source, source_extension, kwds = self._assigned_source
  621. if source is None:
  622. raise TypeError("emit_c_code() is only for C extension modules, "
  623. "not for dlopen()-style pure Python modules")
  624. recompile(self, module_name, source,
  625. c_file=filename, call_c_compiler=False, **kwds)
  626. def emit_python_code(self, filename):
  627. from .recompiler import recompile
  628. #
  629. if not hasattr(self, '_assigned_source'):
  630. raise ValueError("set_source() must be called before emit_c_code()")
  631. module_name, source, source_extension, kwds = self._assigned_source
  632. if source is not None:
  633. raise TypeError("emit_python_code() is only for dlopen()-style "
  634. "pure Python modules, not for C extension modules")
  635. recompile(self, module_name, source,
  636. c_file=filename, call_c_compiler=False, **kwds)
  637. def compile(self, tmpdir='.', verbose=0, target=None, debug=None):
  638. """The 'target' argument gives the final file name of the
  639. compiled DLL. Use '*' to force distutils' choice, suitable for
  640. regular CPython C API modules. Use a file name ending in '.*'
  641. to ask for the system's default extension for dynamic libraries
  642. (.so/.dll/.dylib).
  643. The default is '*' when building a non-embedded C API extension,
  644. and (module_name + '.*') when building an embedded library.
  645. """
  646. from .recompiler import recompile
  647. #
  648. if not hasattr(self, '_assigned_source'):
  649. raise ValueError("set_source() must be called before compile()")
  650. module_name, source, source_extension, kwds = self._assigned_source
  651. return recompile(self, module_name, source, tmpdir=tmpdir,
  652. target=target, source_extension=source_extension,
  653. compiler_verbose=verbose, debug=debug, **kwds)
  654. def init_once(self, func, tag):
  655. # Read _init_once_cache[tag], which is either (False, lock) if
  656. # we're calling the function now in some thread, or (True, result).
  657. # Don't call setdefault() in most cases, to avoid allocating and
  658. # immediately freeing a lock; but still use setdefaut() to avoid
  659. # races.
  660. try:
  661. x = self._init_once_cache[tag]
  662. except KeyError:
  663. x = self._init_once_cache.setdefault(tag, (False, allocate_lock()))
  664. # Common case: we got (True, result), so we return the result.
  665. if x[0]:
  666. return x[1]
  667. # Else, it's a lock. Acquire it to serialize the following tests.
  668. with x[1]:
  669. # Read again from _init_once_cache the current status.
  670. x = self._init_once_cache[tag]
  671. if x[0]:
  672. return x[1]
  673. # Call the function and store the result back.
  674. result = func()
  675. self._init_once_cache[tag] = (True, result)
  676. return result
  677. def embedding_init_code(self, pysource):
  678. if self._embedding:
  679. raise ValueError("embedding_init_code() can only be called once")
  680. # fix 'pysource' before it gets dumped into the C file:
  681. # - remove empty lines at the beginning, so it starts at "line 1"
  682. # - dedent, if all non-empty lines are indented
  683. # - check for SyntaxErrors
  684. import re
  685. match = re.match(r'\s*\n', pysource)
  686. if match:
  687. pysource = pysource[match.end():]
  688. lines = pysource.splitlines() or ['']
  689. prefix = re.match(r'\s*', lines[0]).group()
  690. for i in range(1, len(lines)):
  691. line = lines[i]
  692. if line.rstrip():
  693. while not line.startswith(prefix):
  694. prefix = prefix[:-1]
  695. i = len(prefix)
  696. lines = [line[i:]+'\n' for line in lines]
  697. pysource = ''.join(lines)
  698. #
  699. compile(pysource, "cffi_init", "exec")
  700. #
  701. self._embedding = pysource
  702. def def_extern(self, *args, **kwds):
  703. raise ValueError("ffi.def_extern() is only available on API-mode FFI "
  704. "objects")
  705. def list_types(self):
  706. """Returns the user type names known to this FFI instance.
  707. This returns a tuple containing three lists of names:
  708. (typedef_names, names_of_structs, names_of_unions)
  709. """
  710. typedefs = []
  711. structs = []
  712. unions = []
  713. for key in self._parser._declarations:
  714. if key.startswith('typedef '):
  715. typedefs.append(key[8:])
  716. elif key.startswith('struct '):
  717. structs.append(key[7:])
  718. elif key.startswith('union '):
  719. unions.append(key[6:])
  720. typedefs.sort()
  721. structs.sort()
  722. unions.sort()
  723. return (typedefs, structs, unions)
  724. def _load_backend_lib(backend, name, flags):
  725. import os
  726. if name is None:
  727. if sys.platform != "win32":
  728. return backend.load_library(None, flags)
  729. name = "c" # Windows: load_library(None) fails, but this works
  730. # on Python 2 (backward compatibility hack only)
  731. first_error = None
  732. if '.' in name or '/' in name or os.sep in name:
  733. try:
  734. return backend.load_library(name, flags)
  735. except OSError as e:
  736. first_error = e
  737. import ctypes.util
  738. path = ctypes.util.find_library(name)
  739. if path is None:
  740. if name == "c" and sys.platform == "win32" and sys.version_info >= (3,):
  741. raise OSError("dlopen(None) cannot work on Windows for Python 3 "
  742. "(see http://bugs.python.org/issue23606)")
  743. msg = ("ctypes.util.find_library() did not manage "
  744. "to locate a library called %r" % (name,))
  745. if first_error is not None:
  746. msg = "%s. Additionally, %s" % (first_error, msg)
  747. raise OSError(msg)
  748. return backend.load_library(path, flags)
  749. def _make_ffi_library(ffi, libname, flags):
  750. backend = ffi._backend
  751. backendlib = _load_backend_lib(backend, libname, flags)
  752. #
  753. def accessor_function(name):
  754. key = 'function ' + name
  755. tp, _ = ffi._parser._declarations[key]
  756. BType = ffi._get_cached_btype(tp)
  757. value = backendlib.load_function(BType, name)
  758. library.__dict__[name] = value
  759. #
  760. def accessor_variable(name):
  761. key = 'variable ' + name
  762. tp, _ = ffi._parser._declarations[key]
  763. BType = ffi._get_cached_btype(tp)
  764. read_variable = backendlib.read_variable
  765. write_variable = backendlib.write_variable
  766. setattr(FFILibrary, name, property(
  767. lambda self: read_variable(BType, name),
  768. lambda self, value: write_variable(BType, name, value)))
  769. #
  770. def addressof_var(name):
  771. try:
  772. return addr_variables[name]
  773. except KeyError:
  774. with ffi._lock:
  775. if name not in addr_variables:
  776. key = 'variable ' + name
  777. tp, _ = ffi._parser._declarations[key]
  778. BType = ffi._get_cached_btype(tp)
  779. if BType.kind != 'array':
  780. BType = model.pointer_cache(ffi, BType)
  781. p = backendlib.load_function(BType, name)
  782. addr_variables[name] = p
  783. return addr_variables[name]
  784. #
  785. def accessor_constant(name):
  786. raise NotImplementedError("non-integer constant '%s' cannot be "
  787. "accessed from a dlopen() library" % (name,))
  788. #
  789. def accessor_int_constant(name):
  790. library.__dict__[name] = ffi._parser._int_constants[name]
  791. #
  792. accessors = {}
  793. accessors_version = [False]
  794. addr_variables = {}
  795. #
  796. def update_accessors():
  797. if accessors_version[0] is ffi._cdef_version:
  798. return
  799. #
  800. for key, (tp, _) in ffi._parser._declarations.items():
  801. if not isinstance(tp, model.EnumType):
  802. tag, name = key.split(' ', 1)
  803. if tag == 'function':
  804. accessors[name] = accessor_function
  805. elif tag == 'variable':
  806. accessors[name] = accessor_variable
  807. elif tag == 'constant':
  808. accessors[name] = accessor_constant
  809. else:
  810. for i, enumname in enumerate(tp.enumerators):
  811. def accessor_enum(name, tp=tp, i=i):
  812. tp.check_not_partial()
  813. library.__dict__[name] = tp.enumvalues[i]
  814. accessors[enumname] = accessor_enum
  815. for name in ffi._parser._int_constants:
  816. accessors.setdefault(name, accessor_int_constant)
  817. accessors_version[0] = ffi._cdef_version
  818. #
  819. def make_accessor(name):
  820. with ffi._lock:
  821. if name in library.__dict__ or name in FFILibrary.__dict__:
  822. return # added by another thread while waiting for the lock
  823. if name not in accessors:
  824. update_accessors()
  825. if name not in accessors:
  826. raise AttributeError(name)
  827. accessors[name](name)
  828. #
  829. class FFILibrary(object):
  830. def __getattr__(self, name):
  831. make_accessor(name)
  832. return getattr(self, name)
  833. def __setattr__(self, name, value):
  834. try:
  835. property = getattr(self.__class__, name)
  836. except AttributeError:
  837. make_accessor(name)
  838. setattr(self, name, value)
  839. else:
  840. property.__set__(self, value)
  841. def __dir__(self):
  842. with ffi._lock:
  843. update_accessors()
  844. return accessors.keys()
  845. def __addressof__(self, name):
  846. if name in library.__dict__:
  847. return library.__dict__[name]
  848. if name in FFILibrary.__dict__:
  849. return addressof_var(name)
  850. make_accessor(name)
  851. if name in library.__dict__:
  852. return library.__dict__[name]
  853. if name in FFILibrary.__dict__:
  854. return addressof_var(name)
  855. raise AttributeError("cffi library has no function or "
  856. "global variable named '%s'" % (name,))
  857. def __cffi_close__(self):
  858. backendlib.close_lib()
  859. self.__dict__.clear()
  860. #
  861. if libname is not None:
  862. try:
  863. if not isinstance(libname, str): # unicode, on Python 2
  864. libname = libname.encode('utf-8')
  865. FFILibrary.__name__ = 'FFILibrary_%s' % libname
  866. except UnicodeError:
  867. pass
  868. library = FFILibrary()
  869. return library, library.__dict__
  870. def _builtin_function_type(func):
  871. # a hack to make at least ffi.typeof(builtin_function) work,
  872. # if the builtin function was obtained by 'vengine_cpy'.
  873. import sys
  874. try:
  875. module = sys.modules[func.__module__]
  876. ffi = module._cffi_original_ffi
  877. types_of_builtin_funcs = module._cffi_types_of_builtin_funcs
  878. tp = types_of_builtin_funcs[func]
  879. except (KeyError, AttributeError, TypeError):
  880. return None
  881. else:
  882. with ffi._lock:
  883. return ffi._get_cached_btype(tp)