3 '+e@sddlZddlZddlmZddlmZddlmZyeWn(e k rdddl m Z ddZYnXye Wne k re Z YnXGd d d eZd d Zd dZddZdS)N) allocate_lock) CDefError)model)CallablecCs t|tS)N) isinstancer)xr /usr/lib64/python3.6/api.py sr c@seZdZdZdfddZdgddZdhdd Zdid d Zdjd dZddZ ddZ dkddZ ddZ ddZ ddZddZdlddZdmd d!Zd"d#Zdod%d&Zd'd(Zdpd)d*Zd+d,Zdqd-d.Zdrd0d1Zdsd2d3Zd4d5Zdtd6d7Zd8d9Zd:d;Zeeedd<Zdvd=d>Z d?d@Z!dAdBZ"dCdDZ#dEdFZ$dGdHZ%dIdJZ&dKdLZ'dMdNZ(dOdPZ)dwdRdSZ*dxdUdVZ+dWdXZ,dYdZZ-dyd\d]Z.d^d_Z/d`daZ0dbdcZ1dddeZ2dS)zFFIa The main top-level class that you instantiate once, or once per module. Example usage: ffi = FFI() ffi.cdef(""" int printf(const char *, ...); """) C = ffi.dlopen(None) # standard library -or- C = ffi.verify() # use a C compiler: verify the decl above is right C.printf("hello, %s!\n", ffi.new("char[]", "world")) Nc Cs|dkr^ddl}ddlm}|j|kr^t|drJtd|t|j|jfntd|t|jfddlm}||_t|_ |j |_ i|_ t jd j|_t jd j|_g|_g|_g|_g|_d|_i|_d|_d|_tj||_t|d r|j|x2t|jD]$}|jd rt ||t!||qW|j "|j"tj#|_$|j"tj%|_&WdQRXt'|t jrtt(d s|j)|j$dt(_*|j+\t(_,t(_-n |j)|j$d|_*|j+\|_,|_-|j.|_.dS)z{Create an FFI instance. The 'backend' argument is used to select a non-default backend, mostly for tests. Nrr) __version____file__zVersion 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.zVersion 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.)cparserZ parsed_typesZ new_typesset_ffiZRTLD_NULL)/Z _cffi_backendr hasattr Exceptionrr_backendr_lockZParser_parser_cached_btypestypes ModuleType__dict__ _parsed_typesZ _new_types_function_caches _libraries _cdefsources_included_ffis_windows_unicode_init_once_cache _cdef_version _embeddingrZ get_typecacheZ _typecacherlist startswithsetattrgetattr_get_cached_btypeZ voidp_typeBVoidPZchar_array_typeBCharArr castrZ _get_typesCDataZCTypebuffer)selfbackendr rnamer r r __init__'sR          z FFI.__init__FcCs|j|||ddS)aParse the given C source. This registers all declared functions, types, and global variables. The functions and global variables can then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'. The types can be used in 'ffi.new()' and other functions. If 'packed' is specified as True, all structs declared inside this cdef are packed, i.e. laid out without any field alignment at all. )overridepackedN)_cdef)r/csourcer3r4r r r cdefcszFFI.cdefcCs$|j||dd|jdkr d|_dS)NT)r4Z dllexportr)r5r$)r/r6r4r r r embedding_apims zFFI.embedding_apic Kst|ts&t|tstd|jd}|j|t|_|jj |fd|i||j j ||rvx|j D] }|j qfW|jj}|rg|j_x|D]}|j||qWWdQRXdS)Nz cdef() argument must be a stringasciir3)rstr basestring TypeErrorencoderobjectr#rparserappendrclearZ _recompletefinish_backend_type)r/r6r3Zoptionscache finishlisttpr r r r5rs        z FFI._cdefrc Cs>|j.t|||\}}|jj||jj|WdQRX|S)aHLoad and return a dynamic library identified by 'name'. The standard C library can be loaded by passing None. Note that functions and types declared by 'ffi.cdef()' are not linked to a particular library, just like C headers; in the library we only look for the actual (untyped) symbols. N)r_make_ffi_libraryrr@r)r/r1flagslibZfunction_cacher r r dlopens  z FFI.dlopencCst|j|dS)zClose a library obtained with ffi.dlopen(). After this call, access to functions or variables from the library will fail (possibly with a segmentation fault). N)type__cffi_close__)r/rHr r r dlclosesz FFI.dlclosecCsj|}||jkr|j|St|ts,|jd}|jj|}|j}|rJ|j}|j|}||f}||j|<|S)Nr9) rrr:r=rZ parse_typeZis_raw_functionZas_function_pointerr))r/cdeclkeyrJreally_a_function_typebtyperesultr r r _typeof_lockeds       zFFI._typeof_lockedcCsdy|j|}Wn0tk r>|j|j|}WdQRXYnX|\}}|r`| r`td|f|S)Nz>the type %r is a function type, not a pointer-to-function type)rKeyErrorrrRr)r/rMconsider_function_as_funcptrrQrPrOr r r _typeofs  z FFI._typeofc Cst|tr|j|St||jr,|jj|St|tjrLt|}|dk rL|St|tj r|t |dr||j |j |j SQRXtt|dS)zParse the C type given as a string and return the corresponding object. It can also be used on 'cdata' instance to get its C type. N_cffi_base_type)rr;rUr-rtypeofrBuiltinFunctionType_builtin_function_type FunctionTyperrr)rVr<rJ)r/rMresr r r rWs       z FFI.typeofcCs0t|tr |j|}|jj|S|jj|SdS)zvReturn the size in bytes of the argument. It can be a string naming a C type, or a 'cdata' instance. N)rr;rUrsizeof)r/rMBTyper r r r\s   z FFI.sizeofcCs t|tr|j|}|jj|S)z\Return the natural alignment size in bytes of the C type given as a string. )rr;rUralignof)r/rMr r r r^s  z FFI.alignofcGs(t|tr|j|}|j|f|dS)a3Return the offset of the named field inside the given structure or array, which must be given as a C type name. You can give several field names in case of nested structures. You can also give numeric values which correspond to array items, in case of an array type. r)rr;rU _typeoffsetof)r/rMfields_or_indexesr r r offsetofs  z FFI.offsetofcCs"t|tr|j|}|jj||S)aAllocate an instance according to the specified C type and return a pointer to it. The specified C type must be either a pointer or an array: ``new('X *')`` allocates an X and returns a pointer to it, whereas ``new('X[n]')`` allocates an array of n X'es and returns an array referencing it (which works mostly like a pointer, like in C). You can also use ``new('X[]', n)`` to allocate an array of a non-constant length n. The memory is initialized following the rules of declaring a global variable in C: by default it is zero-initialized, but an explicit initializer can be given which can be used to fill all or part of the memory. When the returned object goes out of scope, the memory is freed. In other words the returned object has ownership of the value of type 'cdecl' that it points to. This means that the raw data can be used as long as this object is kept alive, but must not be used for a longer time. Be careful about that when copying the pointer to the memory somewhere else, e.g. into another structure. )rr;rUrZnewp)r/rMinitr r r news  zFFI.newTcs,jj}|j|||dfdd }|S)aReturn a new allocator, i.e. a function that behaves like ffi.new() but uses the provided low-level 'alloc' and 'free' functions. 'alloc' is called with the size as argument. If it returns NULL, a MemoryError is raised. 'free' is called with the result of 'alloc' as argument. Both can be either Python function or directly C functions. If 'free' is None, then no free function is called. If both 'alloc' and 'free' are None, the default is used. If 'should_clear_after_alloc' is set to False, then the memory returned by 'alloc' is assumed to be already cleared (or you are fine with garbage); otherwise CFFI will clear it. Ncst|trj|}||S)N)rr;rU)rMrb) allocatorr/r r allocates  z#FFI.new_allocator..allocate)N)rr new_allocator)r/ZallocZfreeZshould_clear_after_allocZ compiled_ffirer )rdr/r rfs  zFFI.new_allocatorcCs"t|tr|j|}|jj||S)zSimilar to a C cast: returns an instance of the named C type initialized with the given 'source'. The source is casted between integers or pointers of any type. )rr;rUrr,)r/rMsourcer r r r,s  zFFI.castrcCs|jj||S)aReturn a Python string (or unicode string) from the 'cdata'. If 'cdata' is a pointer or array of characters or bytes, returns the null-terminated string. The returned string extends until the first null character, or at most 'maxlen' characters. If 'cdata' is an array then 'maxlen' defaults to its length. If 'cdata' is a pointer or array of wchar_t, returns a unicode string following the same rules. If 'cdata' is a single character or byte or a wchar_t, returns it as a string or unicode string. If 'cdata' is an enum, returns the value of the enumerator as a string, or 'NUMBER' if the value is out of range. )rstring)r/cdatamaxlenr r r rh%sz FFI.stringcCs|jj||S)aLUnpack an array of C data of the given length, returning a Python string/unicode/list. If 'cdata' is a pointer to 'char', returns a byte string. It does not stop at the first null. This is equivalent to: ffi.buffer(cdata, length)[:] If 'cdata' is a pointer to 'wchar_t', returns a unicode string. 'length' is measured in wchar_t's; it is not the size in bytes. If 'cdata' is a pointer to anything else, returns a list of 'length' items. This is a faster equivalent to: [cdata[i] for i in range(length)] )runpack)r/riZlengthr r r rk7sz FFI.unpackcCs|jj|j||S)aReturn a that points to the data of the given Python object, which must support the buffer interface. Note that this is not meant to be used on the built-in types str or unicode (you can build 'char[]' arrays explicitly) but only on objects containing large quantities of raw data in some other format, like 'array.array' or numpy arrays. )r from_bufferr+)r/Z python_bufferZrequire_writabler r r rlUs zFFI.from_buffercCs|jj|||S)a_ffi.memmove(dest, src, n) copies n bytes of memory from src to dest. Like the C function memmove(), the memory areas may overlap; apart from that it behaves like the C function memcpy(). 'src' can be any cdata ptr or array, or any Python buffer object. 'dest' can be any cdata ptr or array, or a writable Python buffer object. The size to copy, 'n', is always measured in bytes. Unlike other methods, this one supports all Python buffer including byte strings and bytearrays---but it still does not support non-contiguous buffers. )rmemmove)r/destsrcnr r r rm`sz FFI.memmovecsBfdd}ttr*jdd|dkr6|S||SdS)aReturn a callback object or a decorator making such a callback object. 'cdecl' must name a C function pointer type. The callback invokes the specified 'python_callable' (which may be provided either directly or via a decorator). Important: the callback object must be manually kept alive for as long as the callback may be invoked from the C level. cs"t|stdjj|S)Nz.the 'python_callable' argument is not callable)callabler<rcallback)python_callable)rMerroronerrorr/r r callback_decorator_wrapxs z-FFI.callback..callback_decorator_wrapT)rTN)rr;rU)r/rMrsrtrurvr )rMrtrur/r rrps  z FFI.callbackrcCsht|tr|j|}|j}|jdrBd|jj|dkrBd|}n|rZ|ddkrZd|}|jj||S)a.Return a string giving the C type 'cdecl', which may be itself a string or a object. If 'replace_with' is given, it gives extra text to append (or insert for more complicated C types), like a variable name, or '*' to get actually the C type 'pointer-to-cdecl'. *z&[&z(%s)rz[( )rr;rUstripr&rZgetcname)r/rMZ replace_withr r r getctypes    z FFI.getctypecCs|jj|||S)aReturn a new cdata object that points to the same data. Later, when this new cdata object is garbage-collected, 'destructor(old_cdata_object)' will be called. The optional 'size' gives an estimate of the size, used to trigger the garbage collection more eagerly. So far only used on PyPy. It tells the GC that the returned object keeps alive roughly 'size' bytes of external memory. )rZgcp)r/riZ destructorsizer r r gcs zFFI.gcc CsRy|j|}Wn>tk rLg}|j||}x|D]}|j||q4WYnX|S)N)rrSZget_cached_btyperB)r/rJr]rDr r r r)s  zFFI._get_cached_btypecKsVddlm}m}|jr |j||p(|}||||f||_|jj}|jj||S)aVerify that the current ffi signatures compile on this machine, and return a dynamic library object. The dynamic library can be used to call functions and access global variables declared in this 'ffi'. The library is compiled by the C compiler: it gives you C-level API compatibility (including calling macros). This is unlike 'ffi.dlopen()', which requires binary compatibility in the signatures. r)Verifier_caller_dir_pycache)verifierr~rr!_apply_windows_unicode load_libraryrr@)r/rgtmpdirkwargsr~rrHr r r verifys     z FFI.verifycCs |jjS)N)rZ get_errno)r/r r r _get_errnoszFFI._get_errnocCs|jj|dS)N)rZ set_errno)r/errnor r r _set_errnoszFFI._set_errnoz(the value of 'errno' from/to the C callscCs |jj|S)N)r getwinerror)r/coder r r rszFFI.getwinerrorc Cs|jtj||SQRXdS)N)rr pointer_cache)r/ctyper r r _pointer_toszFFI._pointer_toc Gsy|jj|}Wn8tk rHdt|jkrBt|j|f|SYnX|rd|j|f|\}}n|jdkrvtdd}|j|}|jj |||S)zReturn the address of a . If 'fields_or_indexes' are given, returns the address of that field or array item in the structure or array, recursively in case of nested structures. __addressof__Zpointerzaddressof(pointer)r) rrWr<rJrrr_kindrZ rawaddressof)r/rir`roffsetZctypeptrr r r addressofs  z FFI.addressofcGsD|jj||\}}x(|D] }|jj||d\}}||7}qW||fS)Nr)rZ typeoffsetof)r/rZfield_or_indexr`rZfield1Zoffset1r r r r_s   zFFI._typeoffsetofcCst|tstdt|jf||kr.td|jX|jF|jj|j|j j d|j j |j |j j d|j j |WdQRXWdQRXdS)aIncludes the typedefs, structs, unions and enums defined in another FFI instance. Usage is similar to a #include in C, where a part of the program might include types defined in another part for its own usage. Note that the include() method has no effect on functions, constants and global variables, which must anyway be accessed directly from the lib object returned by the original FFI instance. zGffi.include() expects an argument that is also of type cffi.FFI, not %rzself.include(self)[]N) rr r<rJ__name__ ValueErrorrrincluderr@extendr )r/Zffi_to_includer r r rs   z FFI.includecCs|jj|j|S)N)rZ newp_handler*)r/rr r r new_handle szFFI.new_handlecCs |jj|S)N)r from_handle)r/rr r r rszFFI.from_handlecCs>|jdk rtdt|}|r*|jdn |jd||_dS)acWindows: if 'enabled_flag' is True, enable the UNICODE and _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR to be (pointers to) wchar_t. If 'enabled_flag' is False, declare these types to be (pointers to) plain 8-bit characters. This is mostly for backward compatibility; you usually want True. Nz%set_unicode() can only be called onceztypedef wchar_t TBYTE;typedef wchar_t TCHAR;typedef const wchar_t *LPCTSTR;typedef const wchar_t *PCTSTR;typedef wchar_t *LPTSTR;typedef wchar_t *PTSTR;typedef TBYTE *PTBYTE;typedef TCHAR *PTCHAR;ztypedef char TBYTE;typedef char TCHAR;typedef const char *LPCTSTR;typedef const char *PCTSTR;typedef char *LPTSTR;typedef char *PTSTR;typedef TBYTE *PTBYTE;typedef TCHAR *PTCHAR;)r!rboolr7)r/Z enabled_flagr r r set_unicodes  zFFI.set_unicodecCs>|jdf}t|ttfs"tdt|ddg}||d<dS)NZ define_macrosz''define_macros' must be a list or tupleUNICODE1_UNICODE)rr)rr)getrr%tupler<)r/kwdsZ defmacrosr r r r0s  zFFI._apply_windows_unicodec sjfdd}dtjkrddl}tjdkrNd}ttdr|d|jjtjd n4tjdkr^d }nd }ttdr|d|jjtjd ttdr|d|jjtjddntjdkrd}ttdr|d7}nLy ddl }Wn t k rddl m }YnXd}|j dr||j d7}|tj d?tj d?d@f}ttdrF|tj7}|d|tjdkrf|dddS)Ncs"j|g}||kr|j|dS)N) setdefaultr@)rNvalueZlst)rr r ensure:s z(FFI._apply_embedding_fix..ensureZ__pypy__rwin32Zpython27prefixZ library_dirsZlibszpypy-czpypy3-cbinZpypyZgoalz python%d%dgettotalrefcountZ_d) sysconfigz python%d.%dZ DEBUG_EXTabiflagsZ librariesZextra_link_argsz /MANIFEST)r)sysbuiltin_module_namesosplatformrpathjoinr version_infor ImportErrorZ distutilsget_config_var hexversionr)r/rrrZ pythonlibtemplaterr )rr _apply_embedding_fix8s@                zFFI._apply_embedding_fix.ccKsdddl}t|drtdt|ts,td|j|ksF|jrN|j|krNtdt||||f|_ dS)Nr_assigned_sourcez:set_source() cannot be called several times per ffi objectz'module_name' must be a stringzY'module_name' must not contain '/': use a dotted name to make a 'package.module' location) rrrrr;r<sepaltsepr:r)r/ module_namergsource_extensionrrr r r set_sourcejs  zFFI.set_sourcebuildc Csddlm}ddlm}t|ds>t|dr6|jjStd|j\}}}}|dkr\t d||||||f|||d d |\} } |r| rt j j d | j dfnt j j d | j df| S) Nr)mkpathr) recompilerrz8set_source() must be called before distutils_extension()zadistutils_extension() is only for C extension modules, not for dlopen()-style pure Python modulesF)rZextradirrcall_c_compilerzregenerated: %r znot modified: %r )Zdistutils.dir_utilr recompilerrrrZ get_extensionrrr<rstderrwriteZsources) r/rverboserrrrgrrZextupdatedr r r distutils_extensionws&     zFFI.distutils_extensioncCsZddlm}t|dstd|j\}}}}|dkrsz+FFI.embedding_init_code..Z cffi_initexec) r$rrematchend splitlinesgrouprangelenrstripr&rr)r/Zpysourcerrlinesrrr )rr embedding_init_codes$    zFFI.embedding_init_codecOs tddS)Nz:ffi.def_extern() is only available on API-mode FFI objects)r)r/argsrr r r def_externszFFI.def_externcCsg}g}g}xh|jjD]\}|jdr8|j|ddq|jdrV|j|ddq|jdr|j|ddqW|j|j|j|||fS)zReturns the user type names known to this FFI instance. This returns a tuple containing three lists of names: (typedef_names, names_of_structs, names_of_unions) ztypedef Nzstruct zunion )r _declarationsr&r@sort)r/ZtypedefsZstructsZunionsrNr r r list_typess   zFFI.list_types)N)FF)F)F)r)F)N)NNTr)r)F)NNN)r)r)rNr)r)r)rT)rrNN)3r __module__ __qualname____doc__r2r7r8r5rIrLrRrUrWr\r^rarcrfr,rhrkrlrmrrr{r}r)rrrpropertyrrrrr_rrrrrrrrrrrrrrrr r r r r sb <              2   r c Csddl}|dkr*tjdkr&|jd|Sd}d}d|ksHd|ksH|j|kr|y |j||Stk rz}z |}WYdd}~XnXddl}|jj|}|dkr|dkrtjdkrtj d krtdd|f}|dk rd ||f}t||j||S) Nrrcr/rzXdlopen(None) cannot work on Windows for Python 3 (see http://bugs.python.org/issue23606)zGctypes.util.find_library() did not manage to locate a library called %rz%s. Additionally, %s)r) rrrrrOSErrorZ ctypes.utilutilZ find_libraryr) r0r1rGrZ first_erroreZctypesrmsgr r r _load_backend_libs,     rc s j}t||| fdd fdd fdddd fd d id gi fd d   fdd G fdddt|dk ry"t|ts|jd}d|_Wntk rYnX jfS)Ncs<d|}jj|\}}j|}j||}|j|<dS)Nz function )rrr) load_functionr)r1rNrE_r]r) backendlibffilibraryr r accessor_function%s   z,_make_ffi_library..accessor_functioncs\d}jj|\}}j|jjttfddfdddS)Nz variable cs S)Nr )r/)r]r1 read_variabler r r 3sz>_make_ffi_library..accessor_variable..cs |S)Nr )r/r)r]r1write_variabler r r 4s)rrr)rrr'r)r1rNrEr) FFILibraryrr)r]r1rrr accessor_variable,s z,_make_ffi_library..accessor_variablecsy|Stk rjZ|krtd|}jj|\}}j|}|jdkr`tj|}j||}||<WdQRX|SXdS)Nz variable Zarray) rSrrrr)rrrr)r1rNrErr]p)addr_variablesrrr r addressof_var6s    z(_make_ffi_library..addressof_varcSstd|fdS)NzDnon-integer constant '%s' cannot be accessed from a dlopen() library)NotImplementedError)r1r r r accessor_constantEsz,_make_ffi_library..accessor_constantcsjj|j|<dS)N)r_int_constantsr)r1)rrr r accessor_int_constantIsz0_make_ffi_library..accessor_int_constantFcsdjkrdSxjjjD]\}\}}t|tjs~|jdd\}}|dkrZ|<q|dkrl|<q|dkr|<q x0t|j D]"\}}||ffdd }||<qWq Wxjj D]}j |qWjd<dS) NrryrZfunctionZvariableZconstantcs|j|j|j|<dS)N)Zcheck_not_partialZ enumvaluesr)r1rEr)rr r accessor_enum_szB_make_ffi_library..update_accessors..accessor_enum) r#rritemsrrZEnumTypesplit enumerateZ enumeratorsr r)rNrErrr1rZenumnamer )r rr r accessorsaccessors_versionrrr r update_accessorsPs"    z+_make_ffi_library..update_accessorsc sXjH|jks|jkr dS|kr>|kr>t|||WdQRXdS)N)rrAttributeError)r1)rrrrrr r make_accessorgsz(_make_ffi_library..make_accessorcsReZdZfddZfddZfddZfddZfd d Zd S) z%_make_ffi_library..FFILibrarycs|t||S)N)r()r/r1)rr r __getattr__rsz1_make_ffi_library..FFILibrary.__getattr__c sJyt|j|}Wn(tk r8|t|||YnX|j||dS)N)r( __class__rr'__set__)r/r1rr)rr r __setattr__us z1_make_ffi_library..FFILibrary.__setattr__c s jjSQRXdS)N)rkeys)r/)rrrr r __dir__}sz-_make_ffi_library..FFILibrary.__dir__csf|jkrj|S|jkr&|S||jkrBj|S|jkrT|Std|fdS)Nz:cffi library has no function or global variable named '%s')rr)r/r1)rrrrr r rs      z3_make_ffi_library..FFILibrary.__addressof__csj|jjdS)N)Z close_librrA)r/)rr r rKsz4_make_ffi_library..FFILibrary.__cffi_close__N)rrrrrrrrKr )rrrrrrrrr r rqs    rzutf-8z FFILibrary_%s) rrr>rr:r=r UnicodeErrorr)rZlibnamerGr0r )rr rr rrrrrrrrrrr rF!s,   "   rFcCsdddl}y$|j|j}|j}|j}||}Wntttfk rFdSX|j |j |SQRXdS)Nr) rmodulesrZ_cffi_original_ffiZ_cffi_types_of_builtin_funcsrSrr<rr))rrmodulerZtypes_of_builtin_funcsrEr r r rYs  rY)rrlockrrtrrrrq NameError collectionsrr;r:r>r rrFrYr r r r s*     wz