| 1 |
import ctypes |
| 2 |
import sys, os |
| 3 |
from collections import defaultdict |
| 4 |
|
| 5 |
import py |
| 6 |
|
| 7 |
from pypy import pypydir |
| 8 |
from rpython.rtyper.lltypesystem import rffi, lltype |
| 9 |
from rpython.rtyper.tool import rffi_platform |
| 10 |
from rpython.rtyper.lltypesystem import ll2ctypes |
| 11 |
from rpython.rtyper.annlowlevel import llhelper |
| 12 |
from rpython.rlib.objectmodel import we_are_translated, keepalive_until_here |
| 13 |
from rpython.rlib.objectmodel import dont_inline |
| 14 |
from rpython.rlib.rfile import (FILEP, c_fread, c_fclose, c_fwrite, |
| 15 |
c_fdopen, c_fileno, c_ferror, |
| 16 |
c_fopen) |
| 17 |
from rpython.rlib import jit, rutf8 |
| 18 |
from rpython.rlib.rarithmetic import widen |
| 19 |
from rpython.translator import cdir |
| 20 |
from rpython.translator.tool.cbuild import ExternalCompilationInfo |
| 21 |
from rpython.translator.gensupp import NameManager |
| 22 |
from rpython.tool.udir import udir |
| 23 |
from pypy.module.cpyext.state import State |
| 24 |
from pypy.interpreter.error import OperationError, oefmt, raise_import_error |
| 25 |
from pypy.interpreter.baseobjspace import W_Root |
| 26 |
from pypy.interpreter.gateway import unwrap_spec |
| 27 |
from pypy.interpreter.nestedscope import Cell |
| 28 |
from pypy.interpreter.module import Module |
| 29 |
from pypy.interpreter.function import StaticMethod, ClassMethod |
| 30 |
from pypy.interpreter.pyframe import PyFrame |
| 31 |
from pypy.interpreter.pyparser import pygram |
| 32 |
from pypy.interpreter.typedef import Function, Method, PyTraceback |
| 33 |
from pypy.objspace.std.dictmultiobject import W_DictViewKeysObject, W_DictViewValuesObject |
| 34 |
from pypy.objspace.std.sliceobject import W_SliceObject |
| 35 |
from pypy.objspace.std.unicodeobject import encode_object |
| 36 |
from pypy.module.__builtin__.descriptor import W_Property |
| 37 |
from pypy.module.__builtin__.functional import W_ReversedIterator, W_Range |
| 38 |
|
| 39 |
from pypy.module.__pypy__.interp_buffer import W_Bufferable |
| 40 |
from pypy.objspace.std.capsuleobject import W_Capsule |
| 41 |
from rpython.rlib.entrypoint import entrypoint_lowlevel |
| 42 |
from rpython.rlib.rposix import SuppressIPH |
| 43 |
from rpython.rlib.unroll import unrolling_iterable |
| 44 |
from rpython.rlib.objectmodel import specialize |
| 45 |
from pypy.module.exceptions import interp_exceptions, interp_group |
| 46 |
from rpython.tool.sourcetools import func_with_new_name |
| 47 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 48 |
from rpython.rlib import rawrefcount |
| 49 |
from rpython.rlib import rthread |
| 50 |
from rpython.rlib.debug import fatalerror_notb |
| 51 |
from rpython.rlib import rstackovf |
| 52 |
from pypy.objspace.std.typeobject import W_TypeObject, find_best_base |
| 53 |
from rpython.tool.cparser import CTypeSpace |
| 54 |
|
| 55 |
DEBUG_WRAPPER = True |
| 56 |
if sys.platform == 'win32': |
| 57 |
dash = '_' |
| 58 |
WIN32 = True |
| 59 |
else: |
| 60 |
dash = '' |
| 61 |
WIN32 = False |
| 62 |
|
| 63 |
pypydir = py.path.local(pypydir) |
| 64 |
include_dir = pypydir / 'module' / 'cpyext' / 'include' |
| 65 |
pc_dir = pypydir / 'module' / 'cpyext' / 'PC' |
| 66 |
parse_dir = pypydir / 'module' / 'cpyext' / 'parse' |
| 67 |
source_dir = pypydir / 'module' / 'cpyext' / 'src' |
| 68 |
translator_c_dir = py.path.local(cdir) |
| 69 |
include_dirs = [ |
| 70 |
udir, |
| 71 |
include_dir, |
| 72 |
parse_dir, |
| 73 |
translator_c_dir, |
| 74 |
] |
| 75 |
if WIN32: |
| 76 |
include_dirs.insert(0, pc_dir) |
| 77 |
|
| 78 |
configure_eci = ExternalCompilationInfo( |
| 79 |
include_dirs=include_dirs, |
| 80 |
includes=['Python.h', 'stdarg.h', 'structmember.h', 'marshal.h'], |
| 81 |
compile_extra=['-DPy_BUILD_CORE']) |
| 82 |
|
| 83 |
class CConfig: |
| 84 |
_compilation_info_ = configure_eci |
| 85 |
|
| 86 |
class CConfig2: |
| 87 |
_compilation_info_ = configure_eci |
| 88 |
|
| 89 |
class CConfig_constants: |
| 90 |
_compilation_info_ = configure_eci |
| 91 |
|
| 92 |
CONST_STRING = lltype.Ptr(lltype.Array(lltype.Char, |
| 93 |
hints={'nolength': True}), |
| 94 |
use_cache=False) |
| 95 |
CONST_STRINGP = lltype.Ptr(lltype.Array(rffi.CCHARP, |
| 96 |
hints={'nolength': True}), |
| 97 |
use_cache=False) |
| 98 |
CONST_WSTRING = lltype.Ptr(lltype.Array(lltype.UniChar, |
| 99 |
hints={'nolength': True}), |
| 100 |
use_cache=False) |
| 101 |
assert CONST_STRING is not rffi.CCHARP |
| 102 |
assert CONST_STRING == rffi.CCHARP |
| 103 |
assert CONST_STRINGP is not rffi.CCHARPP |
| 104 |
assert CONST_STRINGP == rffi.CCHARPP |
| 105 |
assert CONST_WSTRING is not rffi.CWCHARP |
| 106 |
assert CONST_WSTRING == rffi.CWCHARP |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
def fclose(fp): |
| 111 |
try: |
| 112 |
with SuppressIPH(): |
| 113 |
return c_fclose(fp) |
| 114 |
except IOError: |
| 115 |
return -1 |
| 116 |
|
| 117 |
def fwrite(buf, sz, n, fp): |
| 118 |
with SuppressIPH(): |
| 119 |
return c_fwrite(buf, sz, n, fp) |
| 120 |
|
| 121 |
def fread(buf, sz, n, fp): |
| 122 |
with SuppressIPH(): |
| 123 |
return c_fread(buf, sz, n, fp) |
| 124 |
|
| 125 |
_feof = rffi.llexternal('feof', [FILEP], rffi.INT) |
| 126 |
def feof(fp): |
| 127 |
with SuppressIPH(): |
| 128 |
return _feof(fp) |
| 129 |
|
| 130 |
_ferror = rffi.llexternal('ferror', [FILEP], rffi.INT) |
| 131 |
def ferror(fp): |
| 132 |
with SuppressIPH(): |
| 133 |
return _ferror(fp) |
| 134 |
|
| 135 |
pypy_decl = 'pypy_decl.h' |
| 136 |
udir.join(pypy_decl).write("/* Will be filled later */\n") |
| 137 |
udir.join('pypy_structmember_decl.h').write("/* Will be filled later */\n") |
| 138 |
udir.join('pypy_marshal_decl.h').write("/* Will be filled later */\n") |
| 139 |
udir.join('pypy_macros.h').write("/* Will be filled later */\n") |
| 140 |
udir.join('genericaliasobject.h').write("/* Will be filled later */\n") |
| 141 |
|
| 142 |
constant_names = """ |
| 143 |
Py_TPFLAGS_READY Py_TPFLAGS_READYING Py_TPFLAGS_MANAGED_DICT Py_TPFLAGS_MANAGED_WEAKREF |
| 144 |
METH_COEXIST METH_STATIC METH_CLASS Py_TPFLAGS_BASETYPE |
| 145 |
METH_NOARGS METH_VARARGS METH_KEYWORDS METH_FASTCALL METH_O |
| 146 |
Py_TPFLAGS_HEAPTYPE Py_TPFLAGS_DISALLOW_INSTANTIATION METH_METHOD |
| 147 |
Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_METHOD_DESCRIPTOR |
| 148 |
Py_LT Py_LE Py_EQ Py_NE Py_GT Py_GE PyBUF_MAX_NDIM |
| 149 |
Py_CLEANUP_SUPPORTED PyBUF_READ |
| 150 |
PyBUF_FORMAT PyBUF_ND PyBUF_STRIDES PyBUF_WRITABLE PyBUF_SIMPLE PyBUF_WRITE |
| 151 |
PY_SSIZE_T_MAX PY_SSIZE_T_MIN PYTHON_API_VERSION PYTHON_ABI_VERSION |
| 152 |
""".split() |
| 153 |
|
| 154 |
for name in ('LONG', 'LIST', 'TUPLE', 'UNICODE', 'DICT', 'BASE_EXC', |
| 155 |
'TYPE', 'BYTES'): |
| 156 |
constant_names.append('Py_TPFLAGS_%s_SUBCLASS' % name) |
| 157 |
|
| 158 |
|
| 159 |
for name in ('SIGN', 'ADD_DOT_0', 'ALT'): |
| 160 |
constant_names.append('Py_DTSF_%s' % name) |
| 161 |
|
| 162 |
for name in constant_names: |
| 163 |
setattr(CConfig_constants, name, rffi_platform.ConstantInteger(name)) |
| 164 |
globals().update(rffi_platform.configure(CConfig_constants)) |
| 165 |
|
| 166 |
def _copy_header_files(headers, dstdir): |
| 167 |
for header in headers: |
| 168 |
target = dstdir.join(header.basename) |
| 169 |
try: |
| 170 |
header.copy(dstdir) |
| 171 |
except py.error.EACCES: |
| 172 |
target.remove() |
| 173 |
header.copy(dstdir) |
| 174 |
target.chmod(0444) |
| 175 |
|
| 176 |
|
| 177 |
def copy_header_files(cts, dstdir, copy_numpy_headers): |
| 178 |
|
| 179 |
assert dstdir.check(dir=True) |
| 180 |
headers = include_dir.listdir('*.h') + include_dir.listdir('*.inl') |
| 181 |
for name in ["pypy_macros.h"] + FUNCTIONS_BY_HEADER.keys(): |
| 182 |
headers.append(udir.join(name)) |
| 183 |
for path in cts.parsed_headers: |
| 184 |
headers.append(path) |
| 185 |
_copy_header_files(headers, dstdir) |
| 186 |
|
| 187 |
if copy_numpy_headers: |
| 188 |
try: |
| 189 |
dstdir.mkdir('_numpypy') |
| 190 |
dstdir.mkdir('_numpypy/numpy') |
| 191 |
except py.error.EEXIST: |
| 192 |
pass |
| 193 |
numpy_dstdir = dstdir / '_numpypy' / 'numpy' |
| 194 |
|
| 195 |
numpy_include_dir = include_dir / '_numpypy' / 'numpy' |
| 196 |
numpy_headers = numpy_include_dir.listdir('*.h') + numpy_include_dir.listdir('*.inl') |
| 197 |
_copy_header_files(numpy_headers, numpy_dstdir) |
| 198 |
if WIN32: |
| 199 |
|
| 200 |
PC_dir = pypydir / 'module' / 'cpyext' / 'PC' |
| 201 |
headers = PC_dir.listdir('*.h') |
| 202 |
_copy_header_files(headers, dstdir) |
| 203 |
|
| 204 |
|
| 205 |
class NotSpecified(object): |
| 206 |
pass |
| 207 |
_NOT_SPECIFIED = NotSpecified() |
| 208 |
class CannotFail(object): |
| 209 |
pass |
| 210 |
CANNOT_FAIL = CannotFail() |
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
cpyext_namespace = NameManager('cpyext_') |
| 267 |
|
| 268 |
class BaseApiFunction(object): |
| 269 |
def __init__(self, argtypes, restype, callable): |
| 270 |
self.argtypes = argtypes |
| 271 |
self.restype = restype |
| 272 |
self.functype = lltype.Ptr(lltype.FuncType(argtypes, restype)) |
| 273 |
self.callable = callable |
| 274 |
self.cdecl = None |
| 275 |
|
| 276 |
def get_llhelper(space): |
| 277 |
return llhelper(self.functype, self.get_wrapper(space)) |
| 278 |
self.get_llhelper = get_llhelper |
| 279 |
|
| 280 |
def get_api_decl(self, name, c_writer): |
| 281 |
restype = self.get_c_restype(c_writer) |
| 282 |
args = self.get_c_args(c_writer) |
| 283 |
res = self.API_VISIBILITY % (restype,) |
| 284 |
return "{res} {name}({args});".format(**locals()) |
| 285 |
|
| 286 |
def get_c_restype(self, c_writer): |
| 287 |
if self.cdecl: |
| 288 |
return self.cdecl.tp.result.get_c_name() |
| 289 |
return c_writer.gettype(self.restype).replace('@', '').strip() |
| 290 |
|
| 291 |
def get_c_args(self, c_writer): |
| 292 |
if self.cdecl: |
| 293 |
args = [tp.get_c_name('arg%d' % i) for i, tp in |
| 294 |
enumerate(self.cdecl.tp.args)] |
| 295 |
return ', '.join(args) or "void" |
| 296 |
args = [] |
| 297 |
for i, argtype in enumerate(self.argtypes): |
| 298 |
if argtype is CONST_STRING: |
| 299 |
arg = 'const char *@' |
| 300 |
elif argtype is CONST_STRINGP: |
| 301 |
arg = 'const char **@' |
| 302 |
elif argtype is CONST_WSTRING: |
| 303 |
arg = 'const wchar_t *@' |
| 304 |
else: |
| 305 |
arg = c_writer.gettype(argtype) |
| 306 |
arg = arg.replace('@', 'arg%d' % (i,)).strip() |
| 307 |
args.append(arg) |
| 308 |
args = ', '.join(args) or "void" |
| 309 |
return args |
| 310 |
|
| 311 |
def get_ptr_decl(self, name, c_writer): |
| 312 |
restype = self.get_c_restype(c_writer) |
| 313 |
args = self.get_c_args(c_writer) |
| 314 |
return "{restype} (*{name})({args});".format(**locals()) |
| 315 |
|
| 316 |
def get_ctypes_impl(self, name, c_writer): |
| 317 |
restype = self.get_c_restype(c_writer) |
| 318 |
args = self.get_c_args(c_writer) |
| 319 |
callargs = ', '.join('arg%d' % (i,) |
| 320 |
for i in range(len(self.argtypes))) |
| 321 |
if self.restype is lltype.Void: |
| 322 |
body = "{ _pypyAPI.%s(%s); }" % (name, callargs) |
| 323 |
else: |
| 324 |
body = "{ return _pypyAPI.%s(%s); }" % (name, callargs) |
| 325 |
return '%s %s(%s)\n%s' % (restype, name, args, body) |
| 326 |
|
| 327 |
|
| 328 |
class ApiFunction(BaseApiFunction): |
| 329 |
API_VISIBILITY = "PyAPI_FUNC(%s)" |
| 330 |
|
| 331 |
def __init__(self, argtypes, restype, callable, error=CANNOT_FAIL, |
| 332 |
c_name=None, cdecl=None, gil=None, |
| 333 |
result_borrowed=False, result_is_ll=False): |
| 334 |
from rpython.flowspace.bytecode import cpython_code_signature |
| 335 |
BaseApiFunction.__init__(self, argtypes, restype, callable) |
| 336 |
self.error_value = error |
| 337 |
self.c_name = c_name |
| 338 |
self.cdecl = cdecl |
| 339 |
|
| 340 |
|
| 341 |
sig = cpython_code_signature(callable.func_code) |
| 342 |
assert sig.argnames[0] == 'space' |
| 343 |
self.argnames = sig.argnames[1:] |
| 344 |
if gil == 'pygilstate_ensure': |
| 345 |
assert self.argnames[-1] == 'previous_state' |
| 346 |
del self.argnames[-1] |
| 347 |
assert len(self.argnames) == len(self.argtypes) |
| 348 |
|
| 349 |
self.gil = gil |
| 350 |
self.result_borrowed = result_borrowed |
| 351 |
self.result_is_ll = result_is_ll |
| 352 |
|
| 353 |
def __repr__(self): |
| 354 |
return "<cpyext function %s>" % (self.callable.__name__,) |
| 355 |
|
| 356 |
def _freeze_(self): |
| 357 |
return True |
| 358 |
|
| 359 |
@specialize.memo() |
| 360 |
def get_wrapper(self, space): |
| 361 |
wrapper = getattr(self, '_wrapper', None) |
| 362 |
if wrapper is None: |
| 363 |
wrapper = self._wrapper = self._make_wrapper(space) |
| 364 |
return wrapper |
| 365 |
|
| 366 |
|
| 367 |
def _make_wrapper(self, space): |
| 368 |
"NOT_RPYTHON" |
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
argtypesw = zip(self.argtypes, |
| 374 |
[_name.startswith("w_") for _name in self.argnames]) |
| 375 |
error_value = self.error_value |
| 376 |
if (isinstance(self.restype, lltype.Ptr) |
| 377 |
and error_value is not CANNOT_FAIL): |
| 378 |
assert lltype.typeOf(error_value) == self.restype |
| 379 |
assert not error_value |
| 380 |
error_value = 0 |
| 381 |
|
| 382 |
if self.result_is_ll: |
| 383 |
result_kind = "L" |
| 384 |
elif self.result_borrowed: |
| 385 |
result_kind = "B" |
| 386 |
else: |
| 387 |
result_kind = "." |
| 388 |
|
| 389 |
signature = (tuple(argtypesw), |
| 390 |
self.restype, |
| 391 |
result_kind, |
| 392 |
error_value, |
| 393 |
self.gil) |
| 394 |
|
| 395 |
cache = space.fromcache(WrapperCache) |
| 396 |
try: |
| 397 |
wrapper_gen = cache.wrapper_gens[signature] |
| 398 |
except KeyError: |
| 399 |
wrapper_gen = WrapperGen(space, signature) |
| 400 |
cache.wrapper_gens[signature] = wrapper_gen |
| 401 |
wrapper = wrapper_gen.make_wrapper(self.callable) |
| 402 |
wrapper.relax_sig_check = True |
| 403 |
if self.c_name is not None: |
| 404 |
wrapper.c_name = cpyext_namespace.uniquename(self.c_name) |
| 405 |
return wrapper |
| 406 |
|
| 407 |
def get_unwrapper(self): |
| 408 |
names = self.argnames |
| 409 |
argtypesw = zip(self.argtypes, |
| 410 |
[_name.startswith("w_") for _name in self.argnames]) |
| 411 |
types_names_enum_ui = unrolling_iterable(enumerate(argtypesw)) |
| 412 |
|
| 413 |
@specialize.ll() |
| 414 |
def unwrapper(space, *args): |
| 415 |
from pypy.module.cpyext.pyobject import is_pyobj |
| 416 |
from pypy.module.cpyext.pyobject import from_ref, as_pyobj |
| 417 |
newargs = () |
| 418 |
keepalives = () |
| 419 |
assert len(args) == len(self.argtypes) |
| 420 |
for i, (ARG, is_wrapped) in types_names_enum_ui: |
| 421 |
input_arg = args[i] |
| 422 |
if is_PyObject(ARG) and not is_wrapped: |
| 423 |
|
| 424 |
if not is_pyobj(input_arg): |
| 425 |
keepalives += (input_arg,) |
| 426 |
arg = rffi.cast(ARG, as_pyobj(space, input_arg)) |
| 427 |
else: |
| 428 |
arg = rffi.cast(ARG, input_arg) |
| 429 |
elif ARG == rffi.VOIDP and not is_wrapped: |
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
if input_arg is None or isinstance(input_arg, W_Root): |
| 434 |
keepalives += (input_arg,) |
| 435 |
arg = rffi.cast(ARG, as_pyobj(space, input_arg)) |
| 436 |
else: |
| 437 |
arg = rffi.cast(ARG, input_arg) |
| 438 |
elif (is_PyObject(ARG) or ARG == rffi.VOIDP) and is_wrapped: |
| 439 |
|
| 440 |
if is_pyobj(input_arg): |
| 441 |
arg = from_ref(space, input_arg) |
| 442 |
else: |
| 443 |
arg = input_arg |
| 444 |
else: |
| 445 |
|
| 446 |
arg = input_arg |
| 447 |
newargs += (arg, ) |
| 448 |
try: |
| 449 |
result = self.callable(space, *newargs) |
| 450 |
finally: |
| 451 |
keepalive_until_here(*keepalives) |
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
if self.restype == PyObject: |
| 456 |
assert self.result_is_ll == is_pyobj(result) |
| 457 |
return result |
| 458 |
return unwrapper |
| 459 |
|
| 460 |
|
| 461 |
DEFAULT_HEADER = 'pypy_decl.h' |
| 462 |
def cpython_api(argtypes, restype, error=_NOT_SPECIFIED, header=DEFAULT_HEADER, |
| 463 |
gil=None, result_borrowed=False, result_is_ll=False): |
| 464 |
""" |
| 465 |
Declares a function to be exported. |
| 466 |
- `argtypes`, `restype` are lltypes and describe the function signature. |
| 467 |
- `error` is the value returned when an applevel exception is raised. The |
| 468 |
special value 'CANNOT_FAIL' (also when restype is Void) turns an eventual |
| 469 |
exception into a wrapped SystemError. Unwrapped exceptions also cause a |
| 470 |
SytemError. |
| 471 |
- `header` is the header file to export the function in. |
| 472 |
- set `gil` to "acquire", "release" or "around" to acquire the GIL, |
| 473 |
release the GIL, or both |
| 474 |
""" |
| 475 |
assert header is not None |
| 476 |
def decorate(func): |
| 477 |
if func.__name__ in FUNCTIONS_BY_HEADER[header]: |
| 478 |
raise ValueError("%s already registered" % func.__name__) |
| 479 |
func._always_inline_ = 'try' |
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
func._jit_look_inside_ = False |
| 484 |
|
| 485 |
api_function = ApiFunction( |
| 486 |
argtypes, restype, func, |
| 487 |
error=_compute_error(error, restype), gil=gil, |
| 488 |
result_borrowed=result_borrowed, result_is_ll=result_is_ll) |
| 489 |
FUNCTIONS_BY_HEADER[header][func.__name__] = api_function |
| 490 |
unwrapper = api_function.get_unwrapper() |
| 491 |
unwrapper.func = func |
| 492 |
unwrapper.api_func = api_function |
| 493 |
INTERPLEVEL_API[func.__name__] = unwrapper |
| 494 |
return unwrapper |
| 495 |
return decorate |
| 496 |
|
| 497 |
class COnlyApiFunction(BaseApiFunction): |
| 498 |
API_VISIBILITY = "extern %s" |
| 499 |
|
| 500 |
def get_wrapper(self, space): |
| 501 |
return self.callable |
| 502 |
|
| 503 |
def __call__(self, *args): |
| 504 |
raise TypeError("the function %s should not be directly " |
| 505 |
"called from RPython, but only from C" % (self.func,)) |
| 506 |
|
| 507 |
def c_only(argtypes, restype): |
| 508 |
def decorate(func): |
| 509 |
header = DEFAULT_HEADER |
| 510 |
if func.__name__ in FUNCTIONS_BY_HEADER[header]: |
| 511 |
raise ValueError("%s already registered" % func.__name__) |
| 512 |
func._revdb_c_only_ = True |
| 513 |
api_function = COnlyApiFunction(argtypes, restype, func) |
| 514 |
FUNCTIONS_BY_HEADER[header][func.__name__] = api_function |
| 515 |
return api_function |
| 516 |
return decorate |
| 517 |
|
| 518 |
def api_func_from_cdef(func, cdef, cts, |
| 519 |
error=_NOT_SPECIFIED, header=DEFAULT_HEADER, |
| 520 |
result_is_ll=False): |
| 521 |
func._always_inline_ = 'try' |
| 522 |
cdecl = cts.parse_func(cdef) |
| 523 |
RESULT = cdecl.get_llresult(cts) |
| 524 |
api_function = ApiFunction( |
| 525 |
cdecl.get_llargs(cts), RESULT, func, |
| 526 |
error=_compute_error(error, RESULT), cdecl=cdecl, |
| 527 |
result_is_ll=result_is_ll) |
| 528 |
FUNCTIONS_BY_HEADER[header][cdecl.name] = api_function |
| 529 |
unwrapper = api_function.get_unwrapper() |
| 530 |
unwrapper.func = func |
| 531 |
unwrapper.api_func = api_function |
| 532 |
return unwrapper |
| 533 |
|
| 534 |
def api_decl(cdef, cts, error=_NOT_SPECIFIED, header=DEFAULT_HEADER): |
| 535 |
def decorate(func): |
| 536 |
return api_func_from_cdef(func, cdef, cts, error=error, header=header) |
| 537 |
return decorate |
| 538 |
|
| 539 |
def slot_function(argtypes, restype, error=_NOT_SPECIFIED): |
| 540 |
def decorate(func): |
| 541 |
func._always_inline_ = 'try' |
| 542 |
api_function = ApiFunction( |
| 543 |
argtypes, restype, func, |
| 544 |
error=_compute_error(error, restype), |
| 545 |
c_name=func.__name__) |
| 546 |
unwrapper = api_function.get_unwrapper() |
| 547 |
unwrapper.func = func |
| 548 |
unwrapper.api_func = api_function |
| 549 |
return unwrapper |
| 550 |
return decorate |
| 551 |
|
| 552 |
def _compute_error(error, restype): |
| 553 |
"""Convert error specification to actual error value of type restype.""" |
| 554 |
if isinstance(restype, lltype.Typedef): |
| 555 |
real_restype = restype.OF |
| 556 |
else: |
| 557 |
real_restype = restype |
| 558 |
if error is _NOT_SPECIFIED: |
| 559 |
if isinstance(real_restype, lltype.Ptr): |
| 560 |
error = lltype.nullptr(real_restype.TO) |
| 561 |
elif real_restype is lltype.Void: |
| 562 |
error = CANNOT_FAIL |
| 563 |
if type(error) is int: |
| 564 |
error = rffi.cast(real_restype, error) |
| 565 |
return error |
| 566 |
|
| 567 |
|
| 568 |
def cpython_struct(name, fields, forward=None, level=1): |
| 569 |
configname = name.replace(' ', '__') |
| 570 |
if level == 1: |
| 571 |
config = CConfig |
| 572 |
else: |
| 573 |
config = CConfig2 |
| 574 |
setattr(config, configname, rffi_platform.Struct(name, fields)) |
| 575 |
if forward is None: |
| 576 |
forward = lltype.ForwardReference() |
| 577 |
TYPES[configname] = forward |
| 578 |
return forward |
| 579 |
|
| 580 |
GLOBALS = {} |
| 581 |
def register_global(name, typ, expr, header=None): |
| 582 |
|
| 583 |
|
| 584 |
|
| 585 |
|
| 586 |
if header is not None: |
| 587 |
name = '%s#%s' % (name, header) |
| 588 |
GLOBALS[name] = (typ, expr) |
| 589 |
|
| 590 |
INTERPLEVEL_API = {} |
| 591 |
FUNCTIONS_BY_HEADER = defaultdict(dict) |
| 592 |
|
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
SYMBOLS_C = [ |
| 597 |
'_Py_FatalErrorFunc', 'PyOS_snprintf', 'PyOS_vsnprintf', 'PyArg_Parse', |
| 598 |
'PyArg_ParseTuple', 'PyArg_UnpackTuple', 'PyArg_ParseTupleAndKeywords', |
| 599 |
'PyArg_VaParse', 'PyArg_VaParseTupleAndKeywords', '_PyArg_NoKeywords', |
| 600 |
'PyUnicode_FromFormat', 'PyUnicode_FromFormatV', 'PyUnicode_AsWideCharString', |
| 601 |
'PyUnicode_GetSize', 'PyUnicode_GetLength', 'PyUnicode_FromWideChar', |
| 602 |
'PyUnicode_AsUnicode', 'PyUnicode_AppendAndDel', |
| 603 |
'PyModule_AddObject', 'PyModule_AddIntConstant', 'PyModule_AddStringConstant', |
| 604 |
'PyModule_GetDef', 'PyModuleDef_Init', 'PyModule_GetState', 'PyModule_AddObjectRef', |
| 605 |
'Py_BuildValue', 'Py_VaBuildValue', 'PyTuple_Pack', |
| 606 |
'_PyArg_Parse_SizeT', '_PyArg_ParseTuple_SizeT', |
| 607 |
'_PyArg_ParseTupleAndKeywords_SizeT', '_PyArg_VaParse_SizeT', |
| 608 |
'_PyArg_VaParseTupleAndKeywords_SizeT', |
| 609 |
'_Py_BuildValue_SizeT', '_Py_VaBuildValue_SizeT', |
| 610 |
|
| 611 |
'PyErr_Format', 'PyErr_NewException', 'PyErr_NewExceptionWithDoc', |
| 612 |
'PyErr_WarnFormat', '_PyErr_FormatFromCause', 'PyErr_FormatV', |
| 613 |
'PySys_WriteStdout', 'PySys_WriteStderr', |
| 614 |
|
| 615 |
'PyEval_CallFunction', 'PyEval_CallMethod', 'PyObject_CallFunction', |
| 616 |
'PyEval_GetFuncDesc', |
| 617 |
'PyObject_CallMethod', 'PyObject_CallFunctionObjArgs', 'PyObject_CallMethodObjArgs', |
| 618 |
'_PyObject_CallFunction_SizeT', '_PyObject_CallMethod_SizeT', |
| 619 |
|
| 620 |
'PyObject_DelItemString', 'PyObject_GetBuffer', 'PyBuffer_Release', |
| 621 |
'_Py_setfilesystemdefaultencoding', |
| 622 |
|
| 623 |
'PyCapsule_IsValid', 'PyCapsule_GetPointer', |
| 624 |
'PyCapsule_GetName', 'PyCapsule_GetDestructor', 'PyCapsule_GetContext', |
| 625 |
'PyCapsule_SetPointer', 'PyCapsule_SetName', 'PyCapsule_SetDestructor', |
| 626 |
'PyCapsule_SetContext', 'PyCapsule_Import', '_Py_get_capsule_type', |
| 627 |
|
| 628 |
'PyComplex_AsCComplex', 'PyComplex_FromCComplex', 'PyNumber_Check', 'PyIndex_Check', |
| 629 |
|
| 630 |
'PyObject_AsReadBuffer', 'PyObject_AsWriteBuffer', 'PyObject_CheckReadBuffer', |
| 631 |
'PyBuffer_GetPointer', 'PyBuffer_ToContiguous', 'PyBuffer_FromContiguous', |
| 632 |
|
| 633 |
'PyImport_ImportModuleLevel', '_PyType_Name', 'PyType_GetModuleByDef', |
| 634 |
|
| 635 |
'PyOS_getsig', 'PyOS_setsig', 'PyType_GetName', 'PyType_GetQualName', |
| 636 |
'_Py_RestoreSignals', |
| 637 |
'PyThread_get_thread_ident', 'PyThread_allocate_lock', 'PyThread_free_lock', |
| 638 |
'PyThread_acquire_lock', 'PyThread_acquire_lock_timed', 'PyThread_release_lock', |
| 639 |
'PyThread_create_key', 'PyThread_delete_key', 'PyThread_set_key_value', |
| 640 |
'PyThread_get_key_value', 'PyThread_delete_key_value', |
| 641 |
'PyThread_ReInitTLS', 'PyThread_init_thread', |
| 642 |
'PyThread_start_new_thread', |
| 643 |
|
| 644 |
'PyStructSequence_InitType', 'PyStructSequence_InitType2', |
| 645 |
'PyStructSequence_New', 'PyStructSequence_UnnamedField', |
| 646 |
'PyStructSequence_NewType', 'PyStructSequence_GetItem', |
| 647 |
'PyStructSequence_SetItem', |
| 648 |
|
| 649 |
'PyFunction_Type', 'PyMethod_Type', 'PyRange_Type', 'PyTraceBack_Type', |
| 650 |
'PyCapsule_Type', |
| 651 |
|
| 652 |
'Py_FrozenFlag', |
| 653 |
'Py_UnbufferedStdioFlag', |
| 654 |
'_Py_PackageContext', 'PyOS_InputHook', 'Py_Version', |
| 655 |
'_Py_PackageContext', 'PyErr_SetInterrupt','PyErr_SetInterruptEx', |
| 656 |
|
| 657 |
'PyMem_RawMalloc', 'PyMem_RawCalloc', 'PyMem_RawRealloc', 'PyMem_RawFree', |
| 658 |
'PyMem_Malloc', 'PyMem_Calloc', 'PyMem_Realloc', 'PyMem_Free', |
| 659 |
'PyObject_CallFinalizerFromDealloc', |
| 660 |
'PyTraceMalloc_Track', 'PyTraceMalloc_Untrack', |
| 661 |
'PyBytes_FromFormat', 'PyBytes_FromFormatV', |
| 662 |
|
| 663 |
'PyType_FromSpec', 'PyType_GetModule', 'PyType_GetModuleState', 'PyType_IsSubtype', |
| 664 |
'Py_IncRef', 'Py_DecRef', 'PyObject_Free', 'PyObject_GC_Del', 'PyType_GenericAlloc', |
| 665 |
'_PyObject_New', '_PyObject_NewVar', 'PyType_GenericNew', |
| 666 |
'_PyObject_GC_Malloc', '_PyObject_GC_New', '_PyObject_GC_NewVar', |
| 667 |
'PyObject_Init', 'PyObject_InitVar', |
| 668 |
'PyTuple_New', '_Py_Dealloc', '_Py_object_dealloc', |
| 669 |
'PyVectorcall_Call', 'PyState_FindModule', 'PySlice_AdjustIndices', |
| 670 |
'PyFloat_Pack2', 'PyFloat_Pack4', 'PyFloat_Pack8', 'PyFloat_Unpack2', |
| 671 |
'PyFloat_Unpack4', 'PyFloat_Unpack8', '_PyFloat_InitState', |
| 672 |
] |
| 673 |
if sys.platform == "win32": |
| 674 |
SYMBOLS_C.append('Py_LegacyWindowsStdioFlag') |
| 675 |
TYPES = {} |
| 676 |
FORWARD_DECLS = [] |
| 677 |
INIT_FUNCTIONS = [] |
| 678 |
BOOTSTRAP_FUNCTIONS = [] |
| 679 |
SKIP_GLOBAL = [] |
| 680 |
|
| 681 |
|
| 682 |
|
| 683 |
_flags = [ |
| 684 |
|
| 685 |
('Py_DebugFlag', 'debug'), |
| 686 |
('Py_InspectFlag', 'inspect'), |
| 687 |
('Py_InteractiveFlag', 'interactive'), |
| 688 |
('Py_OptimizeFlag', 'optimize'), |
| 689 |
('Py_DontWriteBytecodeFlag', 'dont_write_bytecode'), |
| 690 |
('Py_NoUserSiteDirectory', 'no_user_site'), |
| 691 |
('Py_NoSiteFlag', 'no_site'), |
| 692 |
('Py_IgnoreEnvironmentFlag', 'ignore_environment'), |
| 693 |
('Py_VerboseFlag', 'verbose'), |
| 694 |
('Py_BytesWarningFlag', 'bytes_warning'), |
| 695 |
('Py_QuietFlag', 'quiet'), |
| 696 |
('Py_HashRandomizationFlag', 'hash_randomization'), |
| 697 |
('Py_IsolatedFlag', 'isolated'), |
| 698 |
] |
| 699 |
|
| 700 |
SYMBOLS_C += [c_name for c_name, _ in _flags] |
| 701 |
|
| 702 |
|
| 703 |
|
| 704 |
MANGLE_NAMES = ['PyType_Type', 'PyType_HasFeature'] |
| 705 |
SYMBOLS_C += MANGLE_NAMES |
| 706 |
SKIP_GLOBAL += MANGLE_NAMES |
| 707 |
|
| 708 |
|
| 709 |
register_global('_Py_NoneStruct', |
| 710 |
'PyObject*', 'space.w_None', header=pypy_decl) |
| 711 |
register_global('_Py_TrueStruct', |
| 712 |
'PyObject*', 'space.w_True', header=pypy_decl) |
| 713 |
register_global('_Py_FalseStruct', |
| 714 |
'PyObject*', 'space.w_False', header=pypy_decl) |
| 715 |
register_global('_Py_NotImplementedStruct', |
| 716 |
'PyObject*', 'space.w_NotImplemented', header=pypy_decl) |
| 717 |
register_global('_Py_EllipsisObject', |
| 718 |
'PyObject*', 'space.w_Ellipsis', header=pypy_decl) |
| 719 |
register_global('PyDateTimeAPI', 'PyDateTime_CAPI*', 'None') |
| 720 |
register_global('Py_GenericAliasType', 'PyTypeObject*', |
| 721 |
'''space.appexec([], """(): |
| 722 |
return type(tuple[int]) |
| 723 |
""")''', header=pypy_decl) |
| 724 |
|
| 725 |
|
| 726 |
def build_exported_objects(): |
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
from pypy.module.exceptions.moduledef import Module as ExcModule |
| 734 |
all_exceptions = list(ExcModule.interpleveldefs) |
| 735 |
for exc_name in all_exceptions: |
| 736 |
if exc_name in ('EnvironmentError', 'IOError', 'WindowsError') or exc_name.startswith("_"): |
| 737 |
|
| 738 |
|
| 739 |
continue |
| 740 |
register_global('PyExc_' + exc_name, |
| 741 |
'PyTypeObject*', |
| 742 |
'space.gettypeobject(%s.typedef)'% (ExcModule.interpleveldefs[exc_name], )) |
| 743 |
|
| 744 |
|
| 745 |
for cpyname, pypyexpr in { |
| 746 |
"PyType_Type": "space.w_type", |
| 747 |
"PyBytes_Type": "space.w_bytes", |
| 748 |
"PyUnicode_Type": "space.w_unicode", |
| 749 |
"PyDict_Type": "space.w_dict", |
| 750 |
"PyDictProxy_Type": 'space.gettypeobject(cpyext.dictproxyobject.W_DictProxyObject.typedef)', |
| 751 |
"PyDictValues_Type": "space.gettypeobject(W_DictViewValuesObject.typedef)", |
| 752 |
"PyDictKeys_Type": "space.gettypeobject(W_DictViewKeysObject.typedef)", |
| 753 |
"PyTuple_Type": "space.w_tuple", |
| 754 |
"PyList_Type": "space.w_list", |
| 755 |
"PySet_Type": "space.w_set", |
| 756 |
"PyFrozenSet_Type": "space.w_frozenset", |
| 757 |
"PyBool_Type": "space.w_bool", |
| 758 |
"PyFloat_Type": "space.w_float", |
| 759 |
"PyLong_Type": "space.w_int", |
| 760 |
"PyComplex_Type": "space.w_complex", |
| 761 |
"PyByteArray_Type": "space.w_bytearray", |
| 762 |
"PyMemoryView_Type": "space.w_memoryview", |
| 763 |
"PyBaseObject_Type": "space.w_object", |
| 764 |
'_PyNone_Type': 'space.type(space.w_None)', |
| 765 |
'_PyNotImplemented_Type': 'space.type(space.w_NotImplemented)', |
| 766 |
'PyCell_Type': 'space.gettypeobject(Cell.typedef)', |
| 767 |
'PyModule_Type': 'space.gettypeobject(Module.typedef)', |
| 768 |
'PyProperty_Type': 'space.gettypeobject(W_Property.typedef)', |
| 769 |
'PySlice_Type': 'space.gettypeobject(W_SliceObject.typedef)', |
| 770 |
'PyStaticMethod_Type': 'space.gettypeobject(StaticMethod.typedef)', |
| 771 |
'PyClassMethod_Type': 'space.gettypeobject(ClassMethod.typedef)', |
| 772 |
'PyCFunction_Type': 'space.gettypeobject(cpyext.methodobject.W_PyCFunctionObject.typedef)', |
| 773 |
'PyClassMethodDescr_Type': 'space.gettypeobject(cpyext.methodobject.W_PyCClassMethodObject.typedef)', |
| 774 |
'PyGetSetDescr_Type': 'space.gettypeobject(cpyext.typeobject.W_GetSetPropertyEx.typedef)', |
| 775 |
'PyMemberDescr_Type': 'space.gettypeobject(cpyext.typeobject.W_MemberDescr.typedef)', |
| 776 |
'PyMethodDescr_Type': 'space.gettypeobject(cpyext.methodobject.W_PyCMethodObject.typedef)', |
| 777 |
'PyWrapperDescr_Type': 'space.gettypeobject(cpyext.methodobject.W_PyCWrapperObject.typedef)', |
| 778 |
'PyInstanceMethod_Type': 'space.gettypeobject(cpyext.classobject.InstanceMethod.typedef)', |
| 779 |
'PyBufferable_Type': 'space.gettypeobject(W_Bufferable.typedef)', |
| 780 |
'PyReversed_Type': 'space.gettypeobject(W_ReversedIterator.typedef)', |
| 781 |
'PyRange_Type': 'space.gettypeobject(W_Range.typedef)', |
| 782 |
'PyFunction_Type': 'space.gettypeobject(Function.typedef)', |
| 783 |
'PyMethod_Type': 'space.gettypeobject(Method.typedef)', |
| 784 |
'PyTraceBack_Type': 'space.gettypeobject(PyTraceback.typedef)', |
| 785 |
'PyCapsule_Type': 'space.gettypeobject(W_Capsule.typedef)', |
| 786 |
'PyFrame_Type': 'space.gettypeobject(PyFrame.typedef)', |
| 787 |
}.items(): |
| 788 |
register_global(cpyname, 'PyTypeObject*', pypyexpr, header=pypy_decl) |
| 789 |
|
| 790 |
for cpyname in '''PyMethodObject PyListObject PyLongObject |
| 791 |
PyBaseExceptionObject'''.split(): |
| 792 |
FORWARD_DECLS.append('typedef struct { PyObject_HEAD } %s' |
| 793 |
% (cpyname, )) |
| 794 |
build_exported_objects() |
| 795 |
|
| 796 |
|
| 797 |
class CpyextTypeSpace(CTypeSpace): |
| 798 |
def decl(self, cdef, error=_NOT_SPECIFIED, header=DEFAULT_HEADER, |
| 799 |
result_is_ll=False): |
| 800 |
def decorate(func): |
| 801 |
return api_func_from_cdef( |
| 802 |
func, cdef, self, error=error, header=header, |
| 803 |
result_is_ll=result_is_ll) |
| 804 |
return decorate |
| 805 |
|
| 806 |
|
| 807 |
CPYEXT_BASE_HEADERS = ['sys/types.h', 'stdarg.h', 'stdio.h', |
| 808 |
'stddef.h', 'pyport.h'] |
| 809 |
|
| 810 |
|
| 811 |
|
| 812 |
|
| 813 |
|
| 814 |
|
| 815 |
|
| 816 |
cts = CpyextTypeSpace(headers=CPYEXT_BASE_HEADERS, include_dirs = [include_dir]) |
| 817 |
|
| 818 |
cts.parse_source(""" |
| 819 |
#ifdef _WIN64 |
| 820 |
typedef long long Py_ssize_t; |
| 821 |
typedef long long Py_hash_t; |
| 822 |
#else |
| 823 |
typedef long Py_ssize_t; |
| 824 |
typedef long Py_hash_t; |
| 825 |
#endif |
| 826 |
""", configure=False) |
| 827 |
cts.parse_header(parse_dir / 'cpyext_object.h', configure=False) |
| 828 |
cts.parse_header(parse_dir / 'cpyext_descrobject.h', configure=False) |
| 829 |
cts.configure_types() |
| 830 |
|
| 831 |
Py_ssize_t = cts.gettype('Py_ssize_t') |
| 832 |
Py_ssize_tP = cts.gettype('Py_ssize_t *') |
| 833 |
size_t = lltype.Unsigned |
| 834 |
ADDR = lltype.Signed |
| 835 |
|
| 836 |
|
| 837 |
|
| 838 |
|
| 839 |
PyTypeObject = cts.gettype('PyTypeObject') |
| 840 |
PyTypeObjectPtr = cts.gettype('PyTypeObject *') |
| 841 |
PyObjectStruct = cts.gettype('PyObject') |
| 842 |
PyObject = cts.gettype('PyObject *') |
| 843 |
PyObjectC = cts.gettype('PyObject const *') |
| 844 |
PyObjectFields = (("ob_base", PyObjectStruct),) |
| 845 |
PyVarObjectStruct = cts.gettype('PyVarObject') |
| 846 |
PyVarObjectFields = (("ob_base", PyVarObjectStruct),) |
| 847 |
PyVarObject = cts.gettype('PyVarObject *') |
| 848 |
|
| 849 |
Py_buffer = cts.gettype('Py_buffer') |
| 850 |
Py_bufferP = cts.gettype('Py_buffer *') |
| 851 |
|
| 852 |
|
| 853 |
@specialize.memo() |
| 854 |
def is_PyObject(TYPE): |
| 855 |
if not isinstance(TYPE, lltype.Ptr): |
| 856 |
return False |
| 857 |
if TYPE == PyObject: |
| 858 |
return True |
| 859 |
assert not isinstance(TYPE.TO, lltype.ForwardReference) |
| 860 |
base = getattr(TYPE.TO, 'c_ob_base', None) |
| 861 |
if not base: |
| 862 |
return False |
| 863 |
|
| 864 |
base = getattr(base, 'c_ob_base', base) |
| 865 |
return hasattr(base, 'c_ob_refcnt') and hasattr(base, 'c_ob_type') |
| 866 |
|
| 867 |
|
| 868 |
PyObjectP = rffi.CArrayPtr(PyObject) |
| 869 |
|
| 870 |
|
| 871 |
INTP_real = rffi.CArrayPtr(rffi.INT_real) |
| 872 |
|
| 873 |
def configure_types(): |
| 874 |
for config in (CConfig, CConfig2): |
| 875 |
for name, TYPE in rffi_platform.configure(config).iteritems(): |
| 876 |
if name in TYPES: |
| 877 |
TYPES[name].become(TYPE) |
| 878 |
|
| 879 |
def build_type_checkers(type_name, cls=None): |
| 880 |
""" |
| 881 |
Builds two api functions: Py_XxxCheck() and Py_XxxCheckExact(). |
| 882 |
- if `cls` is None, the type is space.w_[type]. |
| 883 |
- if `cls` is a string, it is the name of a space attribute, e.g. 'w_str'. |
| 884 |
- else `cls` must be a W_Class with a typedef. |
| 885 |
""" |
| 886 |
if cls is None: |
| 887 |
attrname = "w_" + type_name.lower() |
| 888 |
def get_w_type(space): |
| 889 |
return getattr(space, attrname) |
| 890 |
elif isinstance(cls, str): |
| 891 |
def get_w_type(space): |
| 892 |
return getattr(space, cls) |
| 893 |
else: |
| 894 |
def get_w_type(space): |
| 895 |
return space.gettypeobject(cls.typedef) |
| 896 |
check_name = "Py" + type_name + "_Check" |
| 897 |
|
| 898 |
@cts.decl("int %s(void * obj)" % check_name, error=CANNOT_FAIL) |
| 899 |
def check(space, w_obj): |
| 900 |
"Implements the Py_Xxx_Check function" |
| 901 |
w_obj_type = space.type(w_obj) |
| 902 |
w_type = get_w_type(space) |
| 903 |
return (space.is_w(w_obj_type, w_type) or |
| 904 |
space.issubtype_w(w_obj_type, w_type)) |
| 905 |
|
| 906 |
@cts.decl("int %sExact(void * obj)" % check_name, error=CANNOT_FAIL) |
| 907 |
def check_exact(space, w_obj): |
| 908 |
"Implements the Py_Xxx_CheckExact function" |
| 909 |
w_obj_type = space.type(w_obj) |
| 910 |
w_type = get_w_type(space) |
| 911 |
return space.is_w(w_obj_type, w_type) |
| 912 |
|
| 913 |
return check, check_exact |
| 914 |
|
| 915 |
def build_type_checkers_flags(type_name, cls=None, flagsubstr=None): |
| 916 |
""" |
| 917 |
Builds two api functions: Py_XxxCheck() and Py_XxxCheckExact() |
| 918 |
Does not export the functions, assumes they are macros in the *. files |
| 919 |
check will try a fast path via pto flags |
| 920 |
""" |
| 921 |
if cls is None: |
| 922 |
attrname = "w_" + type_name.lower() |
| 923 |
def get_w_type(space): |
| 924 |
return getattr(space, attrname) |
| 925 |
else: |
| 926 |
def get_w_type(space): |
| 927 |
return getattr(space, cls) |
| 928 |
if flagsubstr is None: |
| 929 |
tp_flag_str = 'Py_TPFLAGS_%s_SUBCLASS' % type_name.upper() |
| 930 |
else: |
| 931 |
tp_flag_str = 'Py_TPFLAGS_%s_SUBCLASS' % flagsubstr |
| 932 |
check_name = "Py" + type_name + "_Check" |
| 933 |
tp_flag = globals()[tp_flag_str] |
| 934 |
|
| 935 |
@specialize.argtype(1) |
| 936 |
def check(space, pto): |
| 937 |
from pypy.module.cpyext.pyobject import is_pyobj, as_pyobj |
| 938 |
"Implements the Py_Xxx_Check function" |
| 939 |
if is_pyobj(pto): |
| 940 |
return (widen(pto.c_ob_type.c_tp_flags) & tp_flag) == tp_flag |
| 941 |
w_obj_type = space.type(pto) |
| 942 |
w_type = get_w_type(space) |
| 943 |
return (space.is_w(w_obj_type, w_type) or |
| 944 |
space.issubtype_w(w_obj_type, w_type)) |
| 945 |
|
| 946 |
def check_exact(space, w_obj): |
| 947 |
"Implements the Py_Xxx_CheckExact function" |
| 948 |
w_obj_type = space.type(w_obj) |
| 949 |
w_type = get_w_type(space) |
| 950 |
return space.is_w(w_obj_type, w_type) |
| 951 |
|
| 952 |
return check, check_exact |
| 953 |
|
| 954 |
pypy_debug_catch_fatal_exception = rffi.llexternal('pypy_debug_catch_fatal_exception', [], lltype.Void) |
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
class WrapperCache(object): |
| 961 |
def __init__(self, space): |
| 962 |
self.space = space |
| 963 |
self.wrapper_gens = {} |
| 964 |
|
| 965 |
class WrapperGen(object): |
| 966 |
wrapper_second_level = None |
| 967 |
A = lltype.Array(lltype.Char) |
| 968 |
|
| 969 |
def __init__(self, space, signature): |
| 970 |
self.space = space |
| 971 |
self.signature = signature |
| 972 |
|
| 973 |
def make_wrapper(self, callable): |
| 974 |
if self.wrapper_second_level is None: |
| 975 |
self.wrapper_second_level = make_wrapper_second_level( |
| 976 |
self.space, *self.signature) |
| 977 |
wrapper_second_level = self.wrapper_second_level |
| 978 |
|
| 979 |
name = callable.__name__ |
| 980 |
pname = lltype.malloc(self.A, len(name), flavor='raw', immortal=True) |
| 981 |
for i in range(len(name)): |
| 982 |
pname[i] = name[i] |
| 983 |
|
| 984 |
def wrapper(*args): |
| 985 |
|
| 986 |
return wrapper_second_level(callable, pname, *args) |
| 987 |
|
| 988 |
wrapper.__name__ = "wrapper for %r" % (callable, ) |
| 989 |
return wrapper |
| 990 |
|
| 991 |
|
| 992 |
|
| 993 |
@dont_inline |
| 994 |
def _unpack_name(pname): |
| 995 |
return ''.join([pname[i] for i in range(len(pname))]) |
| 996 |
|
| 997 |
@dont_inline |
| 998 |
def deadlock_error(funcname): |
| 999 |
funcname = _unpack_name(funcname) |
| 1000 |
fatalerror_notb("GIL deadlock detected when a CPython C extension " |
| 1001 |
"module calls '%s'" % (funcname,)) |
| 1002 |
|
| 1003 |
@dont_inline |
| 1004 |
def no_gil_error(funcname): |
| 1005 |
funcname = _unpack_name(funcname) |
| 1006 |
fatalerror_notb("GIL not held when a CPython C extension " |
| 1007 |
"module calls '%s'" % (funcname,)) |
| 1008 |
|
| 1009 |
@dont_inline |
| 1010 |
def not_supposed_to_fail(funcname): |
| 1011 |
funcname = _unpack_name(funcname) |
| 1012 |
print "Error in cpyext, CPython compatibility layer:" |
| 1013 |
print "The function", funcname, "was not supposed to fail" |
| 1014 |
raise SystemError |
| 1015 |
|
| 1016 |
@dont_inline |
| 1017 |
def unexpected_exception(funcname, e, tb): |
| 1018 |
funcname = _unpack_name(funcname) |
| 1019 |
print 'Fatal error in cpyext, CPython compatibility layer, calling',funcname |
| 1020 |
print 'Either report a bug or consider not using this particular extension' |
| 1021 |
if not we_are_translated(): |
| 1022 |
if tb is None: |
| 1023 |
tb = sys.exc_info()[2] |
| 1024 |
import traceback |
| 1025 |
traceback.print_exc() |
| 1026 |
if sys.stdout == sys.__stdout__: |
| 1027 |
import pdb; pdb.post_mortem(tb) |
| 1028 |
|
| 1029 |
else: |
| 1030 |
print str(e) |
| 1031 |
pypy_debug_catch_fatal_exception() |
| 1032 |
assert False |
| 1033 |
|
| 1034 |
def _restore_gil_state(pygilstate_release, gilstate, gil_release, _gil_auto): |
| 1035 |
from rpython.rlib import rgil |
| 1036 |
|
| 1037 |
if pygilstate_release: |
| 1038 |
from pypy.module.cpyext import pystate |
| 1039 |
unlock = (gilstate == pystate.PyGILState_UNLOCKED) |
| 1040 |
else: |
| 1041 |
unlock = gil_release or _gil_auto |
| 1042 |
if unlock: |
| 1043 |
rgil.release() |
| 1044 |
|
| 1045 |
|
| 1046 |
def make_wrapper_second_level(space, argtypesw, restype, |
| 1047 |
result_kind, error_value, gil): |
| 1048 |
from rpython.rlib import rgil |
| 1049 |
argtypes_enum_ui = unrolling_iterable(enumerate(argtypesw)) |
| 1050 |
fatal_value = restype._defl() |
| 1051 |
gil_auto_workaround = (gil is None) |
| 1052 |
|
| 1053 |
gil_acquire = (gil == "acquire" or gil == "around") |
| 1054 |
gil_release = (gil == "release" or gil == "around") |
| 1055 |
pygilstate_ensure = (gil == "pygilstate_ensure") |
| 1056 |
pygilstate_release = (gil == "pygilstate_release") |
| 1057 |
pygilstate_check = (gil == "pygilstate_check") |
| 1058 |
assert (gil is None or gil_acquire or gil_release |
| 1059 |
or pygilstate_ensure or pygilstate_release or pygilstate_check) |
| 1060 |
expected_nb_args = len(argtypesw) + pygilstate_ensure |
| 1061 |
|
| 1062 |
if isinstance(restype, lltype.Ptr) and error_value == 0: |
| 1063 |
error_value = lltype.nullptr(restype.TO) |
| 1064 |
if error_value is not CANNOT_FAIL: |
| 1065 |
assert lltype.typeOf(error_value) == lltype.typeOf(fatal_value) |
| 1066 |
|
| 1067 |
def invalid(err): |
| 1068 |
"NOT_RPYTHON: translation-time crash if this ends up being called" |
| 1069 |
raise ValueError(err) |
| 1070 |
|
| 1071 |
def wrapper_second_level(callable, pname, *args): |
| 1072 |
from pypy.module.cpyext.pyobject import make_ref, from_ref, is_pyobj |
| 1073 |
from pypy.module.cpyext.pyobject import as_pyobj |
| 1074 |
from pypy.module.cpyext import pystate |
| 1075 |
|
| 1076 |
|
| 1077 |
|
| 1078 |
|
| 1079 |
_gil_auto = False |
| 1080 |
if gil_auto_workaround and not rgil.am_I_holding_the_GIL(): |
| 1081 |
_gil_auto = True |
| 1082 |
if _gil_auto or gil_acquire: |
| 1083 |
if gil_acquire and rgil.am_I_holding_the_GIL(): |
| 1084 |
deadlock_error(pname) |
| 1085 |
rgil.acquire() |
| 1086 |
if gil_auto_workaround: |
| 1087 |
|
| 1088 |
|
| 1089 |
|
| 1090 |
|
| 1091 |
space.fromcache(State).make_sure_cpyext_is_imported() |
| 1092 |
elif pygilstate_ensure: |
| 1093 |
if rgil.am_I_holding_the_GIL(): |
| 1094 |
args += (pystate.PyGILState_LOCKED,) |
| 1095 |
else: |
| 1096 |
rgil.acquire() |
| 1097 |
args += (pystate.PyGILState_UNLOCKED,) |
| 1098 |
elif pygilstate_check: |
| 1099 |
result = rgil.am_I_holding_the_GIL() |
| 1100 |
return rffi.cast(restype, result) |
| 1101 |
else: |
| 1102 |
if not rgil.am_I_holding_the_GIL(): |
| 1103 |
no_gil_error(pname) |
| 1104 |
if pygilstate_release: |
| 1105 |
gilstate = rffi.cast(lltype.Signed, args[-1]) |
| 1106 |
else: |
| 1107 |
gilstate = pystate.PyGILState_IGNORE |
| 1108 |
|
| 1109 |
llop.gc_stack_bottom(lltype.Void) |
| 1110 |
retval = fatal_value |
| 1111 |
boxed_args = () |
| 1112 |
tb = None |
| 1113 |
state = space.fromcache(State) |
| 1114 |
try: |
| 1115 |
if not we_are_translated() and DEBUG_WRAPPER: |
| 1116 |
print >>sys.stderr, callable, |
| 1117 |
assert len(args) == expected_nb_args |
| 1118 |
for i, (typ, is_wrapped) in argtypes_enum_ui: |
| 1119 |
arg = args[i] |
| 1120 |
if is_PyObject(typ) and is_wrapped: |
| 1121 |
assert is_pyobj(arg) |
| 1122 |
arg_conv = from_ref(space, rffi.cast(PyObject, arg)) |
| 1123 |
elif typ == rffi.VOIDP and is_wrapped: |
| 1124 |
|
| 1125 |
|
| 1126 |
arg_conv = from_ref(space, rffi.cast(PyObject, arg)) |
| 1127 |
else: |
| 1128 |
arg_conv = arg |
| 1129 |
boxed_args += (arg_conv, ) |
| 1130 |
if pygilstate_ensure: |
| 1131 |
boxed_args += (args[-1], ) |
| 1132 |
try: |
| 1133 |
result = callable(space, *boxed_args) |
| 1134 |
if not we_are_translated() and DEBUG_WRAPPER: |
| 1135 |
print >>sys.stderr, " DONE" |
| 1136 |
except OperationError as e: |
| 1137 |
failed = True |
| 1138 |
state.set_exception(e) |
| 1139 |
except BaseException as e: |
| 1140 |
failed = True |
| 1141 |
if not we_are_translated(): |
| 1142 |
tb = sys.exc_info()[2] |
| 1143 |
message = repr(e) |
| 1144 |
import traceback |
| 1145 |
traceback.print_exc() |
| 1146 |
else: |
| 1147 |
message = str(e) |
| 1148 |
state.set_exception(OperationError(space.w_SystemError, |
| 1149 |
space.newtext(message))) |
| 1150 |
except rstackovf.StackOverflow as e: |
| 1151 |
rstackovf.check_stack_overflow() |
| 1152 |
failed = True |
| 1153 |
state.set_exception(OperationError(space.w_RuntimeError, |
| 1154 |
space.newtext("maximum recursion depth exceeded"))) |
| 1155 |
else: |
| 1156 |
failed = False |
| 1157 |
|
| 1158 |
if failed: |
| 1159 |
if error_value is CANNOT_FAIL: |
| 1160 |
raise not_supposed_to_fail(pname) |
| 1161 |
retval = error_value |
| 1162 |
|
| 1163 |
elif is_PyObject(restype): |
| 1164 |
if is_pyobj(result): |
| 1165 |
if result_kind != "L": |
| 1166 |
raise invalid("missing result_is_ll=True") |
| 1167 |
else: |
| 1168 |
if result_kind == "L": |
| 1169 |
raise invalid("result_is_ll=True but not ll PyObject") |
| 1170 |
if result_kind == "B": |
| 1171 |
result = as_pyobj(space, result) |
| 1172 |
else: |
| 1173 |
result = make_ref(space, result) |
| 1174 |
retval = rffi.cast(restype, result) |
| 1175 |
|
| 1176 |
elif restype is not lltype.Void: |
| 1177 |
retval = rffi.cast(restype, result) |
| 1178 |
|
| 1179 |
except Exception as e: |
| 1180 |
unexpected_exception(pname, e, tb) |
| 1181 |
_restore_gil_state(pygilstate_release, gilstate, gil_release, _gil_auto) |
| 1182 |
state.check_and_raise_exception(always=True) |
| 1183 |
return fatal_value |
| 1184 |
|
| 1185 |
assert lltype.typeOf(retval) == restype |
| 1186 |
|
| 1187 |
_restore_gil_state(pygilstate_release, gilstate, gil_release, _gil_auto) |
| 1188 |
return retval |
| 1189 |
|
| 1190 |
wrapper_second_level._dont_inline_ = True |
| 1191 |
return wrapper_second_level |
| 1192 |
|
| 1193 |
|
| 1194 |
def setup_init_functions(eci, prefix): |
| 1195 |
|
| 1196 |
|
| 1197 |
|
| 1198 |
|
| 1199 |
get_capsule_type = rffi.llexternal('_%s_get_capsule_type' % prefix, |
| 1200 |
[], PyTypeObjectPtr, |
| 1201 |
compilation_info=eci, _nowrapper=True) |
| 1202 |
setdefenc = rffi.llexternal('_%s_setfilesystemdefaultencoding' % prefix, |
| 1203 |
[rffi.CCHARP], lltype.Void, |
| 1204 |
compilation_info=eci, _nowrapper=True) |
| 1205 |
@init_function |
| 1206 |
def init_types(space): |
| 1207 |
from pypy.module.cpyext.typeobject import py_type_ready |
| 1208 |
from pypy.module.sys.interp_encoding import getfilesystemencoding |
| 1209 |
py_type_ready(space, get_capsule_type()) |
| 1210 |
s = space.text_w(getfilesystemencoding(space)) |
| 1211 |
setdefenc(rffi.str2charp(s, track_allocation=False)) |
| 1212 |
|
| 1213 |
from pypy.module.posix.interp_posix import add_fork_hook |
| 1214 |
global py_fatalerrorfunc |
| 1215 |
py_fatalerrorfunc = rffi.llexternal('_%s_FatalErrorFunc' % prefix, |
| 1216 |
[CONST_STRING, CONST_STRING], lltype.Void, |
| 1217 |
compilation_info=eci) |
| 1218 |
_reinit_tls = rffi.llexternal('%sThread_ReInitTLS' % prefix, [], |
| 1219 |
lltype.Void, compilation_info=eci) |
| 1220 |
def reinit_tls(space): |
| 1221 |
_reinit_tls() |
| 1222 |
add_fork_hook('child', reinit_tls) |
| 1223 |
|
| 1224 |
|
| 1225 |
def attach_c_functions(space, eci, prefix): |
| 1226 |
state = space.fromcache(State) |
| 1227 |
state.C._Py_Dealloc = rffi.llexternal( |
| 1228 |
mangle_name(prefix, '_Py_Dealloc'), |
| 1229 |
[PyObject], lltype.Void, |
| 1230 |
compilation_info=eci, |
| 1231 |
_nowrapper=True) |
| 1232 |
state.C.PyObject_Free = rffi.llexternal( |
| 1233 |
mangle_name(prefix, 'PyObject_Free'), |
| 1234 |
[rffi.VOIDP], lltype.Void, |
| 1235 |
compilation_info=eci, |
| 1236 |
_nowrapper=True) |
| 1237 |
state.C.PyType_GenericAlloc = rffi.llexternal( |
| 1238 |
mangle_name(prefix, 'PyType_GenericAlloc'), |
| 1239 |
[PyTypeObjectPtr, Py_ssize_t], PyObject, |
| 1240 |
compilation_info=eci, |
| 1241 |
_nowrapper=True) |
| 1242 |
state.C._PyPy_int_dealloc = rffi.llexternal( |
| 1243 |
mangle_name(prefix, '_Py_int_dealloc'), [PyObject], lltype.Void, |
| 1244 |
compilation_info=eci, _nowrapper=True) |
| 1245 |
state.C.PyTuple_New = rffi.llexternal( |
| 1246 |
mangle_name(prefix, 'PyTuple_New'), |
| 1247 |
[Py_ssize_t], PyObject, |
| 1248 |
compilation_info=eci, |
| 1249 |
_nowrapper=True) |
| 1250 |
state.C._PyPy_tuple_dealloc = rffi.llexternal( |
| 1251 |
mangle_name(prefix, '_Py_tuple_dealloc'), [PyObject], lltype.Void, |
| 1252 |
compilation_info=eci, _nowrapper=True) |
| 1253 |
_, state.C.set_marker = rffi.CExternVariable( |
| 1254 |
rffi.VOIDP, '_pypy_rawrefcount_w_marker_deallocating', |
| 1255 |
eci, _nowrapper=True, c_type='void *', declare_as_extern=True) |
| 1256 |
state.C._PyPy_subtype_dealloc = rffi.llexternal( |
| 1257 |
mangle_name(prefix, '_Py_subtype_dealloc'), |
| 1258 |
[PyObject], lltype.Void, |
| 1259 |
compilation_info=eci, _nowrapper=True) |
| 1260 |
state.C._PyPy_object_dealloc = rffi.llexternal( |
| 1261 |
mangle_name(prefix, '_Py_object_dealloc'), |
| 1262 |
[PyObject], lltype.Void, |
| 1263 |
compilation_info=eci, _nowrapper=True) |
| 1264 |
FUNCPTR = lltype.Ptr(lltype.FuncType([], rffi.INT_real)) |
| 1265 |
state.C.get_pyos_inputhook = rffi.llexternal( |
| 1266 |
mangle_name(prefix, '_Py_get_PyOS_InputHook'), [], FUNCPTR, |
| 1267 |
compilation_info=eci, _nowrapper=True) |
| 1268 |
state.C.tuple_new = rffi.llexternal( |
| 1269 |
mangle_name(prefix, '_Py_tuple_new'), |
| 1270 |
[PyTypeObjectPtr, PyObject, PyObject], PyObject, |
| 1271 |
compilation_info=eci, _nowrapper=True) |
| 1272 |
state.C.PyType_GenericNew = rffi.llexternal( |
| 1273 |
mangle_name(prefix, 'PyType_GenericNew'), |
| 1274 |
[PyTypeObjectPtr, PyObject, PyObject], PyObject, |
| 1275 |
compilation_info=eci, _nowrapper=True) |
| 1276 |
state.C.tuple_new = rffi.llexternal( |
| 1277 |
mangle_name(prefix, '_Py_tuple_new'), |
| 1278 |
[PyTypeObjectPtr, PyObject, PyObject], PyObject, |
| 1279 |
compilation_info=eci, _nowrapper=True) |
| 1280 |
state.C.float_init = rffi.llexternal( |
| 1281 |
mangle_name(prefix, '_PyFloat_InitState'), |
| 1282 |
[], lltype.Void, |
| 1283 |
compilation_info=eci, _nowrapper=True) |
| 1284 |
|
| 1285 |
if we_are_translated(): |
| 1286 |
eci_flags = eci |
| 1287 |
else: |
| 1288 |
|
| 1289 |
|
| 1290 |
|
| 1291 |
|
| 1292 |
library_dirs = eci.library_dirs |
| 1293 |
link_extra = list(eci.link_extra) |
| 1294 |
link_files = eci.link_files |
| 1295 |
if sys.platform == "win32": |
| 1296 |
|
| 1297 |
|
| 1298 |
from pypy.module.sys import version |
| 1299 |
ver = version.CPYTHON_VERSION[:2] |
| 1300 |
link_extra.append("/NODEFAULTLIB:Python%d%d.lib" % ver) |
| 1301 |
|
| 1302 |
link_extra += [x.replace('dll', 'lib') for x in eci.libraries] |
| 1303 |
eci_flags = ExternalCompilationInfo( |
| 1304 |
include_dirs=include_dirs, |
| 1305 |
includes=['Python.h'], |
| 1306 |
link_extra = link_extra, |
| 1307 |
link_files = link_files, |
| 1308 |
library_dirs = library_dirs, |
| 1309 |
) |
| 1310 |
flag_setters = {} |
| 1311 |
for c_name, attr in _flags: |
| 1312 |
_, setter = rffi.CExternVariable(rffi.INT_real, c_name, eci_flags, |
| 1313 |
_nowrapper=True, c_type='int') |
| 1314 |
flag_setters[attr] = setter |
| 1315 |
unroll_flag_setters = unrolling_iterable(flag_setters.items()) |
| 1316 |
def init_flags(space): |
| 1317 |
for attr, setter in unroll_flag_setters: |
| 1318 |
setter(rffi.cast(rffi.INT_real, space.sys.get_flag(attr))) |
| 1319 |
state.C.init_flags = init_flags |
| 1320 |
|
| 1321 |
|
| 1322 |
def init_function(func): |
| 1323 |
INIT_FUNCTIONS.append(func) |
| 1324 |
return func |
| 1325 |
|
| 1326 |
def bootstrap_function(func): |
| 1327 |
BOOTSTRAP_FUNCTIONS.append(func) |
| 1328 |
return func |
| 1329 |
|
| 1330 |
def run_bootstrap_functions(space): |
| 1331 |
for func in BOOTSTRAP_FUNCTIONS: |
| 1332 |
func(space) |
| 1333 |
|
| 1334 |
@init_function |
| 1335 |
def call_init_flags(space): |
| 1336 |
state = space.fromcache(State) |
| 1337 |
state.C.init_flags(space) |
| 1338 |
|
| 1339 |
|
| 1340 |
|
| 1341 |
|
| 1342 |
|
| 1343 |
|
| 1344 |
def build_bridge(space): |
| 1345 |
"NOT_RPYTHON" |
| 1346 |
from rpython.translator.c.database import LowLevelDatabase |
| 1347 |
use_micronumpy = setup_micronumpy(space) |
| 1348 |
db = LowLevelDatabase() |
| 1349 |
prefix = 'cpyexttest' |
| 1350 |
|
| 1351 |
generate_decls_and_callbacks(db, prefix=prefix) |
| 1352 |
|
| 1353 |
|
| 1354 |
functions = [] |
| 1355 |
members = [] |
| 1356 |
structindex = {} |
| 1357 |
for header, header_functions in FUNCTIONS_BY_HEADER.iteritems(): |
| 1358 |
for name, func in header_functions.iteritems(): |
| 1359 |
functions.append(func.get_ctypes_impl(name, db)) |
| 1360 |
members.append(func.get_ptr_decl(name, db)) |
| 1361 |
structindex[name] = len(structindex) |
| 1362 |
structmembers = '\n'.join(members) |
| 1363 |
struct_declaration_code = """\ |
| 1364 |
struct PyPyAPI { |
| 1365 |
%(members)s |
| 1366 |
} _pypyAPI; |
| 1367 |
RPY_EXTERN struct PyPyAPI* pypyAPI; |
| 1368 |
struct PyPyAPI* pypyAPI = &_pypyAPI; |
| 1369 |
""" % dict(members=structmembers) |
| 1370 |
|
| 1371 |
prologue = ("#include <Python.h>\n" + |
| 1372 |
"#include <structmember.h>\n" + |
| 1373 |
"#include <marshal.h>\n" + |
| 1374 |
("#include <pypy_numpy.h>\n" if use_micronumpy else "") + |
| 1375 |
"#include <src/thread.c>\n") |
| 1376 |
code = (prologue + |
| 1377 |
struct_declaration_code + |
| 1378 |
'\n' + |
| 1379 |
'\n'.join(functions)) |
| 1380 |
|
| 1381 |
eci = build_eci(code, use_micronumpy, translating=False) |
| 1382 |
eci = eci.compile_shared_lib( |
| 1383 |
outputfilename=str(udir / "module_cache" / "pypyapi"), |
| 1384 |
symbolic=True) |
| 1385 |
space.fromcache(State).install_dll(eci) |
| 1386 |
modulename = py.path.local(eci.libraries[-1]) |
| 1387 |
|
| 1388 |
attach_c_functions(space, eci, prefix) |
| 1389 |
run_bootstrap_functions(space) |
| 1390 |
|
| 1391 |
|
| 1392 |
bridge = ctypes.CDLL(str(modulename), mode=ctypes.RTLD_GLOBAL) |
| 1393 |
|
| 1394 |
|
| 1395 |
builder = space.fromcache(State).builder = TestingObjBuilder() |
| 1396 |
from pypy.module import cpyext |
| 1397 |
for name, (typ, expr) in GLOBALS.iteritems(): |
| 1398 |
if '#' in name: |
| 1399 |
name, header = name.split('#') |
| 1400 |
assert typ in ('PyObject*', 'PyTypeObject*', 'PyIntObject*') |
| 1401 |
isptr = False |
| 1402 |
elif name.startswith('PyExc_'): |
| 1403 |
isptr = False |
| 1404 |
elif typ == 'PyDateTime_CAPI*': |
| 1405 |
isptr = True |
| 1406 |
else: |
| 1407 |
raise ValueError("Unknown static data: %s %s" % (typ, name)) |
| 1408 |
|
| 1409 |
w_obj = eval(expr) |
| 1410 |
INTERPLEVEL_API[name] = w_obj |
| 1411 |
|
| 1412 |
mname = mangle_name(prefix, name) |
| 1413 |
if isptr: |
| 1414 |
assert typ == 'PyDateTime_CAPI*' |
| 1415 |
value = w_obj |
| 1416 |
ptr = ctypes.c_void_p.in_dll(bridge, mname) |
| 1417 |
ptr.value = ctypes.cast(ll2ctypes.lltype2ctypes(value), |
| 1418 |
ctypes.c_void_p).value |
| 1419 |
elif typ in ('PyObject*', 'PyTypeObject*'): |
| 1420 |
if name.startswith('PyExc_'): |
| 1421 |
|
| 1422 |
in_dll = ll2ctypes.get_ctypes_type(PyObject).in_dll(bridge, mname) |
| 1423 |
py_obj = ll2ctypes.ctypes2lltype(PyObject, in_dll) |
| 1424 |
else: |
| 1425 |
|
| 1426 |
in_dll = ll2ctypes.get_ctypes_type(PyObject.TO).in_dll(bridge, mname) |
| 1427 |
py_obj = ll2ctypes.ctypes2lltype(PyObject, ctypes.pointer(in_dll)) |
| 1428 |
builder.prepare(py_obj, w_obj) |
| 1429 |
|
| 1430 |
pypyAPI = ctypes.POINTER(ctypes.c_void_p).in_dll(bridge, 'pypyAPI') |
| 1431 |
|
| 1432 |
|
| 1433 |
for header, header_functions in FUNCTIONS_BY_HEADER.iteritems(): |
| 1434 |
for name, func in header_functions.iteritems(): |
| 1435 |
pypyAPI[structindex[name]] = ctypes.cast( |
| 1436 |
ll2ctypes.lltype2ctypes(func.get_llhelper(space)), |
| 1437 |
ctypes.c_void_p) |
| 1438 |
|
| 1439 |
|
| 1440 |
|
| 1441 |
|
| 1442 |
|
| 1443 |
builder.attach_all(space) |
| 1444 |
|
| 1445 |
setup_init_functions(eci, prefix) |
| 1446 |
return modulename.new(ext='') |
| 1447 |
|
| 1448 |
def attach_recursively(space, static_pyobjs, static_objs_w, attached_objs, i): |
| 1449 |
|
| 1450 |
from pypy.module.cpyext.pyobject import get_typedescr, make_ref |
| 1451 |
if i in attached_objs: |
| 1452 |
return |
| 1453 |
py_obj = static_pyobjs[i] |
| 1454 |
w_obj = static_objs_w[i] |
| 1455 |
w_base = None |
| 1456 |
|
| 1457 |
if isinstance(w_obj, W_TypeObject): |
| 1458 |
bases_w = w_obj.bases_w |
| 1459 |
if bases_w: |
| 1460 |
w_base = find_best_base(bases_w) |
| 1461 |
if w_base: |
| 1462 |
try: |
| 1463 |
j = static_objs_w.index(w_base) |
| 1464 |
except ValueError: |
| 1465 |
j = -1 |
| 1466 |
if j >=0 and j not in attached_objs: |
| 1467 |
attach_recursively(space, static_pyobjs, static_objs_w, |
| 1468 |
attached_objs, j) |
| 1469 |
w_type = space.type(w_obj) |
| 1470 |
typedescr = get_typedescr(w_type.layout.typedef) |
| 1471 |
py_obj.c_ob_type = rffi.cast(PyTypeObjectPtr, |
| 1472 |
make_ref(space, w_type)) |
| 1473 |
typedescr.attach(space, py_obj, w_obj) |
| 1474 |
attached_objs.append(i) |
| 1475 |
|
| 1476 |
|
| 1477 |
class StaticObjectBuilder(object): |
| 1478 |
def __init__(self): |
| 1479 |
self.static_pyobjs = [] |
| 1480 |
self.static_objs_w = [] |
| 1481 |
self.cpyext_type_init = None |
| 1482 |
|
| 1483 |
|
| 1484 |
|
| 1485 |
self.get_static_pyobjs = lambda: self.static_pyobjs |
| 1486 |
|
| 1487 |
def prepare(self, py_obj, w_obj): |
| 1488 |
"NOT_RPYTHON" |
| 1489 |
if py_obj: |
| 1490 |
py_obj.c_ob_refcnt = 1 |
| 1491 |
self.static_pyobjs.append(py_obj) |
| 1492 |
self.static_objs_w.append(w_obj) |
| 1493 |
|
| 1494 |
def attach_all(self, space): |
| 1495 |
|
| 1496 |
from pypy.module.cpyext.typeobject import finish_type_1, finish_type_2 |
| 1497 |
from pypy.module.cpyext.pyobject import track_reference |
| 1498 |
|
| 1499 |
static_pyobjs = self.get_static_pyobjs() |
| 1500 |
static_objs_w = self.static_objs_w |
| 1501 |
for i in range(len(static_objs_w)): |
| 1502 |
track_reference(space, static_pyobjs[i], static_objs_w[i]) |
| 1503 |
|
| 1504 |
self.cpyext_type_init = [] |
| 1505 |
attached_objs = [] |
| 1506 |
for i in range(len(static_objs_w)): |
| 1507 |
attach_recursively(space, static_pyobjs, static_objs_w, attached_objs, i) |
| 1508 |
cpyext_type_init = self.cpyext_type_init |
| 1509 |
self.cpyext_type_init = None |
| 1510 |
for pto, w_type in cpyext_type_init: |
| 1511 |
finish_type_1(space, pto) |
| 1512 |
finish_type_2(space, pto, w_type) |
| 1513 |
|
| 1514 |
class TestingObjBuilder(StaticObjectBuilder): |
| 1515 |
"""The StaticObjectBuilder used in tests.""" |
| 1516 |
|
| 1517 |
class TranslationObjBuilder(StaticObjectBuilder): |
| 1518 |
"""The StaticObjectBuilder used during translation.""" |
| 1519 |
|
| 1520 |
|
| 1521 |
def mangle_name(prefix, name): |
| 1522 |
if name.startswith('PyPyUnicode'): |
| 1523 |
|
| 1524 |
return name |
| 1525 |
elif name.startswith('Py'): |
| 1526 |
return prefix + name[2:] |
| 1527 |
elif name.startswith('_Py'): |
| 1528 |
return '_' + prefix + name[3:] |
| 1529 |
else: |
| 1530 |
raise ValueError("Error converting '%s'" % name) |
| 1531 |
|
| 1532 |
def write_header(header_name, decls, needs_signed=True, add_guards=False): |
| 1533 |
decl_h = udir.join(header_name) |
| 1534 |
lines = [] |
| 1535 |
if add_guards: |
| 1536 |
guard = 'Py_' + header_name.replace('.', '_').upper() |
| 1537 |
lines += ['#ifndef ' + guard, |
| 1538 |
'#define ' + guard, |
| 1539 |
'#ifdef __cplusplus', |
| 1540 |
'extern "C" {', |
| 1541 |
'#endif', '' |
| 1542 |
] |
| 1543 |
if needs_signed: |
| 1544 |
lines += [ |
| 1545 |
'', |
| 1546 |
'#include "cpyext_object.h"', |
| 1547 |
'', |
| 1548 |
'#ifdef _WIN64', |
| 1549 |
'#define Signed Py_ssize_t /* xxx temporary fix */', |
| 1550 |
'#define Unsigned unsigned long long /* xxx temporary fix */', |
| 1551 |
'#else', |
| 1552 |
'#define Signed Py_ssize_t /* xxx temporary fix */', |
| 1553 |
'#define Unsigned unsigned long /* xxx temporary fix */', |
| 1554 |
'#endif', |
| 1555 |
] + decls + [ |
| 1556 |
'', |
| 1557 |
'#undef Signed /* xxx temporary fix */', |
| 1558 |
'#undef Unsigned /* xxx temporary fix */', |
| 1559 |
''] |
| 1560 |
else: |
| 1561 |
lines += decls |
| 1562 |
if add_guards: |
| 1563 |
lines += ['#ifdef __cplusplus', |
| 1564 |
'}', |
| 1565 |
'#endif', |
| 1566 |
'#endif /* !' + guard + ' */', |
| 1567 |
] |
| 1568 |
decl_h.write('\n'.join(lines) + '\n') |
| 1569 |
|
| 1570 |
def generate_decls_and_callbacks(db, prefix=''): |
| 1571 |
"NOT_RPYTHON" |
| 1572 |
pypy_macros = [] |
| 1573 |
for name in SYMBOLS_C: |
| 1574 |
newname = mangle_name(prefix, name) |
| 1575 |
pypy_macros.append('#define %s %s' % (name, newname)) |
| 1576 |
|
| 1577 |
|
| 1578 |
for macro_name, size in [ |
| 1579 |
("SIZEOF_LONG_LONG", rffi.LONGLONG), |
| 1580 |
("SIZEOF_VOID_P", rffi.VOIDP), |
| 1581 |
("SIZEOF_SIZE_T", rffi.SIZE_T), |
| 1582 |
("SIZEOF_TIME_T", rffi.TIME_T), |
| 1583 |
("SIZEOF_LONG", rffi.LONG), |
| 1584 |
("SIZEOF_SHORT", rffi.SHORT), |
| 1585 |
("SIZEOF_INT", rffi.INT), |
| 1586 |
("SIZEOF_FLOAT", rffi.FLOAT), |
| 1587 |
("SIZEOF_DOUBLE", rffi.DOUBLE), |
| 1588 |
]: |
| 1589 |
pypy_macros.append("#define %s %s" % (macro_name, rffi.sizeof(size))) |
| 1590 |
pypy_macros.append('') |
| 1591 |
|
| 1592 |
pypy_macros_h = udir.join('pypy_macros.h') |
| 1593 |
pypy_macros_h.write('\n'.join(pypy_macros)) |
| 1594 |
|
| 1595 |
|
| 1596 |
decls = defaultdict(list) |
| 1597 |
for decl in FORWARD_DECLS: |
| 1598 |
decls[pypy_decl].append("%s;" % (decl,)) |
| 1599 |
for header_name, header_functions in FUNCTIONS_BY_HEADER.iteritems(): |
| 1600 |
header = decls[header_name] |
| 1601 |
for name, func in sorted(header_functions.iteritems()): |
| 1602 |
_name = mangle_name(prefix, name) |
| 1603 |
header.append("#define %s %s" % (name, _name)) |
| 1604 |
header.append(func.get_api_decl(name, db)) |
| 1605 |
|
| 1606 |
for name, (typ, expr) in GLOBALS.iteritems(): |
| 1607 |
if '#' in name: |
| 1608 |
name, header = name.split("#") |
| 1609 |
typ = typ.replace("*", "") |
| 1610 |
elif name.startswith('PyExc_'): |
| 1611 |
typ = 'PyObject*' |
| 1612 |
header = pypy_decl |
| 1613 |
if name not in SKIP_GLOBAL: |
| 1614 |
decls[header].append('#define %s %s' % (name, mangle_name(prefix, name))) |
| 1615 |
decls[header].append('PyAPI_DATA(%s) %s;' % (typ, name)) |
| 1616 |
|
| 1617 |
for header_name, header_decls in decls.iteritems(): |
| 1618 |
|
| 1619 |
if header_name in ('genericaliasobject.h',): |
| 1620 |
write_header(header_name, header_decls, |
| 1621 |
needs_signed=False, add_guards=True) |
| 1622 |
else: |
| 1623 |
write_header(header_name, header_decls) |
| 1624 |
|
| 1625 |
|
| 1626 |
separate_module_files = [source_dir / "varargwrapper.c", |
| 1627 |
source_dir / "pyerrors.c", |
| 1628 |
source_dir / "modsupport.c", |
| 1629 |
source_dir / "getargs.c", |
| 1630 |
source_dir / "abstract.c", |
| 1631 |
source_dir / "unicodeobject.c", |
| 1632 |
source_dir / "mysnprintf.c", |
| 1633 |
source_dir / "pythonrun.c", |
| 1634 |
source_dir / "sysmodule.c", |
| 1635 |
source_dir / "complexobject.c", |
| 1636 |
source_dir / "structseq.c", |
| 1637 |
source_dir / "capsule.c", |
| 1638 |
source_dir / "pysignals.c", |
| 1639 |
source_dir / "pythread.c", |
| 1640 |
source_dir / "missing.c", |
| 1641 |
source_dir / "pymem.c", |
| 1642 |
source_dir / "pytime.c", |
| 1643 |
source_dir / "bytesobject.c", |
| 1644 |
source_dir / "import.c", |
| 1645 |
source_dir / "_warnings.c", |
| 1646 |
source_dir / "pylifecycle.c", |
| 1647 |
source_dir / "object.c", |
| 1648 |
source_dir / "typeobject.c", |
| 1649 |
source_dir / "tupleobject.c", |
| 1650 |
source_dir / "sliceobject.c", |
| 1651 |
source_dir / "call.c", |
| 1652 |
source_dir / "ceval.c", |
| 1653 |
source_dir / "floatobject.c", |
| 1654 |
|
| 1655 |
translator_c_dir / "src" / "signals.c", |
| 1656 |
] |
| 1657 |
if WIN32: |
| 1658 |
separate_module_files.append(source_dir / "pythread_nt.c") |
| 1659 |
else: |
| 1660 |
separate_module_files.append(source_dir / "pythread_posix.c") |
| 1661 |
|
| 1662 |
|
| 1663 |
def build_eci(code, use_micronumpy=False, translating=False): |
| 1664 |
"NOT_RPYTHON" |
| 1665 |
|
| 1666 |
kwds = {} |
| 1667 |
|
| 1668 |
compile_extra=['-DPy_BUILD_CORE'] |
| 1669 |
|
| 1670 |
if translating: |
| 1671 |
kwds["includes"] = ['Python.h'] |
| 1672 |
else: |
| 1673 |
if sys.platform == "win32": |
| 1674 |
|
| 1675 |
compile_extra.append("/we4013") |
| 1676 |
|
| 1677 |
|
| 1678 |
kwds["link_extra"] = ["msvcrt.lib"] |
| 1679 |
elif sys.platform.startswith('linux'): |
| 1680 |
compile_extra.append("-Werror=implicit-function-declaration") |
| 1681 |
compile_extra.append('-g') |
| 1682 |
compile_extra.append( |
| 1683 |
'-DCPYEXT_TESTS') |
| 1684 |
|
| 1685 |
|
| 1686 |
structs = ["#include <Python.h>"] |
| 1687 |
if use_micronumpy: |
| 1688 |
structs.append('#include <pypy_numpy.h> /* api.py line 1223 */') |
| 1689 |
for name, (typ, expr) in GLOBALS.iteritems(): |
| 1690 |
if '#' in name: |
| 1691 |
structs.append('%s %s;' % (typ[:-1], name.split('#')[0])) |
| 1692 |
elif name.startswith('PyExc_'): |
| 1693 |
structs.append('PyTypeObject _%s;' % (name,)) |
| 1694 |
structs.append('PyObject* %s = (PyObject*)&_%s;' % (name, name)) |
| 1695 |
elif typ == 'PyDateTime_CAPI*': |
| 1696 |
structs.append('%s %s = NULL;' % (typ, name)) |
| 1697 |
struct_source = '\n'.join(structs) |
| 1698 |
|
| 1699 |
separate_module_sources = [code, struct_source] |
| 1700 |
|
| 1701 |
if sys.platform == 'win32': |
| 1702 |
get_pythonapi_source = ''' |
| 1703 |
RPY_EXTERN |
| 1704 |
HANDLE pypy_get_pythonapi_handle() { |
| 1705 |
MEMORY_BASIC_INFORMATION mi; |
| 1706 |
memset(&mi, 0, sizeof(mi)); |
| 1707 |
|
| 1708 |
if( !VirtualQueryEx(GetCurrentProcess(), &pypy_get_pythonapi_handle, |
| 1709 |
&mi, sizeof(mi)) ) |
| 1710 |
return 0; |
| 1711 |
|
| 1712 |
return (HMODULE)mi.AllocationBase; |
| 1713 |
} |
| 1714 |
''' |
| 1715 |
separate_module_sources.append(get_pythonapi_source) |
| 1716 |
kwds['post_include_bits'] = ['#include <windows.h>', |
| 1717 |
'RPY_EXTERN HANDLE pypy_get_pythonapi_handle();', |
| 1718 |
] |
| 1719 |
|
| 1720 |
eci = ExternalCompilationInfo( |
| 1721 |
include_dirs=include_dirs, |
| 1722 |
separate_module_files= separate_module_files, |
| 1723 |
separate_module_sources=separate_module_sources, |
| 1724 |
compile_extra=compile_extra, |
| 1725 |
**kwds |
| 1726 |
) |
| 1727 |
|
| 1728 |
return eci |
| 1729 |
|
| 1730 |
def setup_micronumpy(space): |
| 1731 |
|
| 1732 |
return False |
| 1733 |
|
| 1734 |
use_micronumpy = space.config.objspace.usemodules.micronumpy |
| 1735 |
if not use_micronumpy: |
| 1736 |
return use_micronumpy |
| 1737 |
|
| 1738 |
from pypy.module.cpyext.ndarrayobject import HEADER |
| 1739 |
register_global("PyArray_Type", |
| 1740 |
'PyTypeObject*', "space.gettypeobject(W_NDimArray.typedef)", |
| 1741 |
header=HEADER) |
| 1742 |
separate_module_files.append(source_dir / "ndarrayobject.c") |
| 1743 |
return use_micronumpy |
| 1744 |
|
| 1745 |
def setup_library(space): |
| 1746 |
"NOT_RPYTHON" |
| 1747 |
from rpython.translator.c.database import LowLevelDatabase |
| 1748 |
use_micronumpy = setup_micronumpy(space) |
| 1749 |
db = LowLevelDatabase() |
| 1750 |
prefix = 'PyPy' |
| 1751 |
|
| 1752 |
generate_decls_and_callbacks(db, prefix=prefix) |
| 1753 |
|
| 1754 |
code = "#include <Python.h>\n" |
| 1755 |
if use_micronumpy: |
| 1756 |
code += "#include <pypy_numpy.h> /* api.py line 1290 */\n" |
| 1757 |
|
| 1758 |
eci = build_eci(code, use_micronumpy, translating=True) |
| 1759 |
space.fromcache(State).install_dll(eci) |
| 1760 |
|
| 1761 |
attach_c_functions(space, eci, prefix) |
| 1762 |
run_bootstrap_functions(space) |
| 1763 |
|
| 1764 |
|
| 1765 |
builder = space.fromcache(State).builder = TranslationObjBuilder() |
| 1766 |
lines = ['PyObject *pypy_static_pyobjs[] = {\n'] |
| 1767 |
include_lines = ['RPY_EXTERN PyObject *pypy_static_pyobjs[];\n'] |
| 1768 |
from pypy.module import cpyext |
| 1769 |
for name, (typ, expr) in sorted(GLOBALS.items()): |
| 1770 |
if '#' in name: |
| 1771 |
name, header = name.split('#') |
| 1772 |
assert typ in ('PyObject*', 'PyTypeObject*') |
| 1773 |
typ = typ[:-1] |
| 1774 |
mname = mangle_name(prefix, name) |
| 1775 |
include_lines.append('#define %s %s\n' % (name, mname)) |
| 1776 |
elif name.startswith('PyExc_'): |
| 1777 |
typ = 'PyTypeObject' |
| 1778 |
name = '_' + name |
| 1779 |
elif typ == 'PyDateTime_CAPI*': |
| 1780 |
continue |
| 1781 |
else: |
| 1782 |
raise ValueError("Unknown static data: %s %s" % (typ, name)) |
| 1783 |
|
| 1784 |
w_obj = eval(expr) |
| 1785 |
builder.prepare(None, w_obj) |
| 1786 |
lines.append('\t(PyObject *)&%s,\n' % (name,)) |
| 1787 |
include_lines.append('RPY_EXPORTED %s %s;\n' % (typ, name)) |
| 1788 |
|
| 1789 |
lines.append('};\n') |
| 1790 |
eci2 = configure_eci.merge(ExternalCompilationInfo( |
| 1791 |
separate_module_sources = [''.join(lines)], |
| 1792 |
post_include_bits = [''.join(include_lines)], |
| 1793 |
)) |
| 1794 |
|
| 1795 |
builder.get_static_pyobjs = rffi.CExternVariable( |
| 1796 |
PyObjectP, 'pypy_static_pyobjs', eci2, c_type='PyObject **', |
| 1797 |
getter_only=True, declare_as_extern=False) |
| 1798 |
|
| 1799 |
for header, header_functions in FUNCTIONS_BY_HEADER.iteritems(): |
| 1800 |
for name, func in header_functions.iteritems(): |
| 1801 |
newname = mangle_name(prefix, name) |
| 1802 |
deco = entrypoint_lowlevel("cpyext", func.argtypes, newname, |
| 1803 |
relax=True) |
| 1804 |
deco(func.get_wrapper(space)) |
| 1805 |
|
| 1806 |
setup_init_functions(eci, prefix) |
| 1807 |
if sys.platform == "win32": |
| 1808 |
trunk_include = pypydir.dirpath() / 'include' |
| 1809 |
else: |
| 1810 |
from pypy.module.sys import version |
| 1811 |
ver = version.CPYTHON_VERSION[:2] |
| 1812 |
trunk_include = pypydir.dirpath() / 'include' / 'pypy{}.{}'.format(*ver) |
| 1813 |
trunk_include.ensure(dir=True) |
| 1814 |
copy_header_files(cts, trunk_include, use_micronumpy) |
| 1815 |
|
| 1816 |
|
| 1817 |
def create_extension_module(space, w_spec): |
| 1818 |
|
| 1819 |
|
| 1820 |
|
| 1821 |
|
| 1822 |
|
| 1823 |
from rpython.rlib import rdynload |
| 1824 |
|
| 1825 |
w_name = space.getattr(w_spec, space.newtext("name")) |
| 1826 |
w_path = space.getattr(w_spec, space.newtext("origin")) |
| 1827 |
name = space.text_w(w_name) |
| 1828 |
path = space.text_w(w_path) |
| 1829 |
|
| 1830 |
if os.sep not in path: |
| 1831 |
path = os.curdir + os.sep + path |
| 1832 |
try: |
| 1833 |
if WIN32: |
| 1834 |
from rpython.rlib import rwin32 |
| 1835 |
|
| 1836 |
|
| 1837 |
flags = (rwin32.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | |
| 1838 |
rwin32.LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR) |
| 1839 |
dll = rdynload.dlopenex(path, space.sys.dlopenflags | flags) |
| 1840 |
else: |
| 1841 |
dll = rdynload.dlopen(path, space.sys.dlopenflags) |
| 1842 |
except rdynload.DLOpenError as e: |
| 1843 |
raise raise_import_error(space, |
| 1844 |
space.newfilename(e.msg), w_name, w_path) |
| 1845 |
look_for = None |
| 1846 |
|
| 1847 |
if space.config.objspace.usemodules._cffi_backend: |
| 1848 |
basename = name.split('.')[-1] |
| 1849 |
look_for = '_cffi_pypyinit_%s' % (basename,) |
| 1850 |
try: |
| 1851 |
initptr = rdynload.dlsym(dll, look_for) |
| 1852 |
except KeyError: |
| 1853 |
pass |
| 1854 |
else: |
| 1855 |
try: |
| 1856 |
from pypy.module._cffi_backend import cffi1_module |
| 1857 |
return cffi1_module.load_cffi1_module(space, name, path, initptr) |
| 1858 |
except: |
| 1859 |
rdynload.dlclose(dll) |
| 1860 |
raise |
| 1861 |
|
| 1862 |
if space.config.objspace.usemodules.cpyext: |
| 1863 |
also_look_for = get_init_name(space, w_name) |
| 1864 |
try: |
| 1865 |
initptr = rdynload.dlsym(dll, also_look_for) |
| 1866 |
except KeyError: |
| 1867 |
pass |
| 1868 |
else: |
| 1869 |
return create_cpyext_module(space, w_spec, name, path, dll, initptr) |
| 1870 |
if look_for is not None: |
| 1871 |
look_for += ' or ' + also_look_for |
| 1872 |
else: |
| 1873 |
look_for = also_look_for |
| 1874 |
assert look_for is not None |
| 1875 |
msg = b"function %s not found in library %s" % ( |
| 1876 |
look_for, space.utf8_w(space.newfilename(path))) |
| 1877 |
w_path = space.newfilename(path) |
| 1878 |
raise_import_error(space, space.newtext(msg), w_name, w_path) |
| 1879 |
|
| 1880 |
def get_init_name(space, w_name): |
| 1881 |
name = space.utf8_w(w_name) |
| 1882 |
basename = name.split('.')[-1] |
| 1883 |
if rutf8.first_non_ascii_char(basename) == -1: |
| 1884 |
return 'PyInit_%s' % (basename,) |
| 1885 |
basename = space.bytes_w(encode_object( |
| 1886 |
space, space.newtext(basename), 'punycode', None)) |
| 1887 |
basename = basename.replace('-', '_') |
| 1888 |
return 'PyInitU_%s' % (basename,) |
| 1889 |
|
| 1890 |
initfunctype = lltype.Ptr(lltype.FuncType([], PyObject)) |
| 1891 |
|
| 1892 |
def create_cpyext_module(space, w_spec, name, path, dll, initptr): |
| 1893 |
from rpython.rlib import rdynload |
| 1894 |
from pypy.module.cpyext.pyobject import get_w_obj_and_decref |
| 1895 |
from pypy.module.cpyext.modsupport import PyModuleDef |
| 1896 |
|
| 1897 |
state = space.fromcache(State) |
| 1898 |
state.make_sure_cpyext_is_imported() |
| 1899 |
w_mod = state.find_extension(name, path) |
| 1900 |
if w_mod is not None: |
| 1901 |
rdynload.dlclose(dll) |
| 1902 |
return w_mod |
| 1903 |
old_context = state.package_context |
| 1904 |
state.package_context = name, path |
| 1905 |
try: |
| 1906 |
if state.clear_exception(): |
| 1907 |
raise oefmt(space.w_SystemError, "error before call to initialization of %s", name) |
| 1908 |
initfunc = rffi.cast(initfunctype, initptr) |
| 1909 |
initret = generic_cpy_call_dont_convert_result(space, initfunc) |
| 1910 |
if not initret: |
| 1911 |
state.check_and_raise_exception() |
| 1912 |
raise oefmt(space.w_SystemError, |
| 1913 |
"initialization of %s failed without raising an exception", |
| 1914 |
name) |
| 1915 |
else: |
| 1916 |
if state.clear_exception(): |
| 1917 |
raise oefmt(space.w_SystemError, |
| 1918 |
"initialization of %s raised unreported exception", |
| 1919 |
name) |
| 1920 |
if not initret.c_ob_type: |
| 1921 |
raise oefmt(space.w_SystemError, |
| 1922 |
"init function of %s returned uninitialized object", |
| 1923 |
name) |
| 1924 |
|
| 1925 |
|
| 1926 |
tp_name_nonconst = rffi.cast(rffi.CCHARP, initret.c_ob_type.c_tp_name) |
| 1927 |
if rffi.charp2str(tp_name_nonconst) == "moduledef": |
| 1928 |
from pypy.module.cpyext.modsupport import \ |
| 1929 |
create_module_from_def_and_spec |
| 1930 |
moddef = rffi.cast(PyModuleDef, initret) |
| 1931 |
return create_module_from_def_and_spec(space, moddef, w_spec, |
| 1932 |
name) |
| 1933 |
finally: |
| 1934 |
state.package_context = old_context |
| 1935 |
|
| 1936 |
w_mod = get_w_obj_and_decref(space, initret) |
| 1937 |
state.fixup_extension(w_mod, name, path) |
| 1938 |
return w_mod |
| 1939 |
|
| 1940 |
@jit.dont_look_inside |
| 1941 |
def exec_extension_module(space, w_mod): |
| 1942 |
from pypy.module.cpyext.modsupport import exec_def, PyModuleObject |
| 1943 |
if not space.config.objspace.usemodules.cpyext: |
| 1944 |
return |
| 1945 |
if not isinstance(w_mod, Module): |
| 1946 |
return |
| 1947 |
space.getbuiltinmodule("cpyext") |
| 1948 |
mod = cts.cast('PyModuleObject*', rawrefcount.from_obj(PyObject, w_mod)) |
| 1949 |
if mod: |
| 1950 |
if mod.c_md_state: |
| 1951 |
|
| 1952 |
return |
| 1953 |
moddef = mod.c_md_def |
| 1954 |
return exec_def(space, mod, moddef) |
| 1955 |
|
| 1956 |
def invoke_pyos_inputhook(space): |
| 1957 |
state = space.fromcache(State) |
| 1958 |
c_inputhook = state.C.get_pyos_inputhook() |
| 1959 |
if c_inputhook: |
| 1960 |
generic_cpy_call(space, c_inputhook) |
| 1961 |
|
| 1962 |
@specialize.ll() |
| 1963 |
def generic_cpy_call(space, func, *args): |
| 1964 |
FT = lltype.typeOf(func).TO |
| 1965 |
return make_generic_cpy_call(FT, False, True)(space, func, *args) |
| 1966 |
|
| 1967 |
@specialize.ll() |
| 1968 |
def generic_cpy_call_expect_null(space, func, *args): |
| 1969 |
FT = lltype.typeOf(func).TO |
| 1970 |
return make_generic_cpy_call(FT, True, True)(space, func, *args) |
| 1971 |
|
| 1972 |
@specialize.ll() |
| 1973 |
def generic_cpy_call_dont_convert_result(space, func, *args): |
| 1974 |
FT = lltype.typeOf(func).TO |
| 1975 |
return make_generic_cpy_call(FT, False, False)(space, func, *args) |
| 1976 |
|
| 1977 |
@specialize.memo() |
| 1978 |
def make_generic_cpy_call(FT, expect_null, convert_result): |
| 1979 |
from pypy.module.cpyext.pyobject import is_pyobj, make_ref, decref |
| 1980 |
from pypy.module.cpyext.pyobject import get_w_obj_and_decref |
| 1981 |
from pypy.module.cpyext.pyerrors import PyErr_Occurred |
| 1982 |
unrolling_arg_types = unrolling_iterable(enumerate(FT.ARGS)) |
| 1983 |
RESULT_TYPE = FT.RESULT |
| 1984 |
|
| 1985 |
|
| 1986 |
|
| 1987 |
|
| 1988 |
argnames = ', '.join(['a%d' % i for i in range(len(FT.ARGS))]) |
| 1989 |
source = py.code.Source(""" |
| 1990 |
def cpy_call_external(funcptr, %(argnames)s): |
| 1991 |
# NB. it is essential that no exception checking occurs here! |
| 1992 |
res = funcptr(%(argnames)s) |
| 1993 |
return res |
| 1994 |
""" % locals()) |
| 1995 |
miniglobals = {'__name__': __name__, |
| 1996 |
} |
| 1997 |
exec source.compile() in miniglobals |
| 1998 |
call_external_function = specialize.ll()(miniglobals['cpy_call_external']) |
| 1999 |
call_external_function._dont_inline_ = True |
| 2000 |
call_external_function._gctransformer_hint_close_stack_ = True |
| 2001 |
|
| 2002 |
|
| 2003 |
|
| 2004 |
@specialize.ll() |
| 2005 |
def generic_cpy_call(space, func, *args): |
| 2006 |
boxed_args = () |
| 2007 |
to_decref = () |
| 2008 |
assert len(args) == len(FT.ARGS) |
| 2009 |
for i, ARG in unrolling_arg_types: |
| 2010 |
arg = args[i] |
| 2011 |
_pyobj = None |
| 2012 |
if is_PyObject(ARG): |
| 2013 |
if not is_pyobj(arg): |
| 2014 |
arg = make_ref(space, arg) |
| 2015 |
_pyobj = arg |
| 2016 |
boxed_args += (arg,) |
| 2017 |
to_decref += (_pyobj,) |
| 2018 |
|
| 2019 |
if is_PyObject(RESULT_TYPE): |
| 2020 |
preexist_error = PyErr_Occurred(space) |
| 2021 |
else: |
| 2022 |
preexist_error = "this is not used" |
| 2023 |
try: |
| 2024 |
|
| 2025 |
result = call_external_function(func, *boxed_args) |
| 2026 |
finally: |
| 2027 |
for i, ARG in unrolling_arg_types: |
| 2028 |
|
| 2029 |
_pyobj = to_decref[i] |
| 2030 |
if _pyobj is not None: |
| 2031 |
decref(space, _pyobj) |
| 2032 |
|
| 2033 |
if convert_result and is_PyObject(RESULT_TYPE): |
| 2034 |
if not is_pyobj(result): |
| 2035 |
ret = result |
| 2036 |
else: |
| 2037 |
|
| 2038 |
|
| 2039 |
|
| 2040 |
if result: |
| 2041 |
ret = get_w_obj_and_decref(space, result) |
| 2042 |
else: |
| 2043 |
ret = None |
| 2044 |
|
| 2045 |
|
| 2046 |
|
| 2047 |
|
| 2048 |
error = PyErr_Occurred(space) |
| 2049 |
has_new_error = (error is not None) and (error is not preexist_error) |
| 2050 |
has_result = ret is not None |
| 2051 |
if not expect_null and has_new_error and has_result: |
| 2052 |
state = space.fromcache(State) |
| 2053 |
state.clear_exception() |
| 2054 |
raise oefmt(space.w_SystemError, |
| 2055 |
"c function call returned a result with an exception set") |
| 2056 |
elif not expect_null and not has_new_error and not has_result: |
| 2057 |
state = space.fromcache(State) |
| 2058 |
state.clear_exception() |
| 2059 |
raise oefmt(space.w_SystemError, |
| 2060 |
"c function call returned NULL without setting an exception") |
| 2061 |
elif has_new_error: |
| 2062 |
state = space.fromcache(State) |
| 2063 |
state.check_and_raise_exception() |
| 2064 |
|
| 2065 |
return ret |
| 2066 |
return result |
| 2067 |
|
| 2068 |
return generic_cpy_call |