Ejemplo n.º 1
0
class CConfig:
    _compilation_info_ = eci

    loop_t = rffi_platform.Struct("uv_loop_t", [("data", rffi.VOIDP)])
    handle_t = rffi_platform.Struct("uv_handle_t", [("data", rffi.VOIDP)])
    timer_t = rffi_platform.Struct("uv_timer_t", [("data", rffi.VOIDP)])
    prepare_t = rffi_platform.Struct("uv_prepare_t", [("data", rffi.VOIDP)])
    idle_t = rffi_platform.Struct("uv_idle_t", [("data", rffi.VOIDP)])
    process_options_t = rffi_platform.Struct("uv_process_options_t",
                                             [("file", rffi.CCHARP),
                                              ("args", rffi.CCHARPP),
                                              ("env", rffi.CCHARPP),
                                              ("cwd", rffi.CCHARP),
                                              ("flags", rffi.UINT),
                                              ("stdio_count", rffi.INT)])
    process_t = rffi_platform.Struct("uv_process_t", [("data", rffi.VOIDP),
                                                      ("pid", rffi.INT)])
    stream_t = rffi_platform.Struct("uv_stream_t", [("data", rffi.VOIDP)])
    connect_t = rffi_platform.Struct(
        "uv_connect_t", [("handle", lltype.Ptr(lltype.ForwardReference()))])
    shutdown_t = rffi_platform.Struct("uv_shutdown_t", [])
    write_t = rffi_platform.Struct("uv_write_t", [])
    tcp_t = rffi_platform.Struct("uv_tcp_t", [("data", rffi.VOIDP)])
    tty_t = rffi_platform.Struct("uv_tty_t", [("data", rffi.VOIDP)])
    fs_t = rffi_platform.Struct("uv_fs_t", [("data", rffi.VOIDP),
                                            ("path", rffi.CONST_CCHARP),
                                            ("result", rffi.SSIZE_T),
                                            ("ptr", rffi.VOIDP)])
    getaddrinfo_t = rffi_platform.Struct("uv_getaddrinfo_t",
                                         [("data", rffi.VOIDP)])
    buf_t = rffi_platform.Struct("uv_buf_t", [("base", rffi.CCHARP),
                                              ("len", rffi.SIZE_T)])
Ejemplo n.º 2
0
 def __init__(self, rtyper, classdef):
     AbstractClassRepr.__init__(self, rtyper, classdef)
     if classdef is None:
         # 'object' root type
         self.vtable_type = OBJECT_VTABLE
     else:
         self.vtable_type = lltype.ForwardReference()
     self.lowleveltype = Ptr(self.vtable_type)
Ejemplo n.º 3
0
def test_recursive_llhelper():
    from rpython.rtyper.annlowlevel import llhelper
    from rpython.rtyper.lltypesystem import lltype
    from rpython.rlib.objectmodel import specialize
    FT = lltype.ForwardReference()
    FTPTR = lltype.Ptr(FT)
    STRUCT = lltype.Struct("foo", ("bar", FTPTR))
    FT.become(lltype.FuncType([lltype.Ptr(STRUCT)], lltype.Signed))

    class A:
        def __init__(self, func, name):
            self.func = func
            self.name = name

        def _freeze_(self):
            return True

        @specialize.memo()
        def make_func(self):
            f = getattr(self, "_f", None)
            if f is not None:
                return f
            f = lambda *args: self.func(*args)
            f.c_name = self.name
            f.relax_sig_check = True
            f.__name__ = "WRAP%s" % (self.name, )
            self._f = f
            return f

        def get_llhelper(self):
            return llhelper(FTPTR, self.make_func())

    def f(s):
        if s.bar == t.bar:
            lltype.free(s, flavor="raw")
            return 1
        lltype.free(s, flavor="raw")
        return 0

    def g(x):
        return 42

    def chooser(x):
        s = lltype.malloc(STRUCT, flavor="raw")
        if x:
            s.bar = llhelper(FTPTR, a_f.make_func())
        else:
            s.bar = llhelper(FTPTR, a_g.make_func())
        return f(s)

    a_f = A(f, "f")
    a_g = A(g, "g")
    t = lltype.malloc(STRUCT, flavor="raw", immortal=True)
    t.bar = llhelper(FTPTR, a_f.make_func())
    fn = compile(chooser, [bool])
    assert fn(True)
Ejemplo n.º 4
0
 def graph2delayed(self, graph, FUNCTYPE=None):
     if FUNCTYPE is None:
         FUNCTYPE = lltype.ForwardReference()
     # obscure hack: embed the name of the function in the string, so
     # that the genc database can get it even before the delayedptr
     # is really computed
     name = "delayed!%s" % (graph.name, )
     delayedptr = lltype._ptr(lltype.Ptr(FUNCTYPE), name, solid=True)
     self.delayedfuncs.append((delayedptr, graph))
     return delayedptr
Ejemplo n.º 5
0
Archivo: api.py Proyecto: juokaz/pypy
def cpython_struct(name, fields, forward=None, level=1):
    configname = name.replace(' ', '__')
    if level == 1:
        config = CConfig
    else:
        config = CConfig2
    setattr(config, configname, rffi_platform.Struct(name, fields))
    if forward is None:
        forward = lltype.ForwardReference()
    TYPES[configname] = forward
    return forward
Ejemplo n.º 6
0
 def new_struct(self, obj):
     if obj.name == '_IO_FILE':  # cffi weirdness
         return cname_to_lltype('FILE')
     struct = DelayedStruct(obj.name, None, lltype.ForwardReference())
     # Cache it early, to avoid infinite recursion
     self.structs[obj] = struct
     if obj.fldtypes is not None:
         struct.fields = zip(
             obj.fldnames,
             [self.convert_field(field) for field in obj.fldtypes])
     return struct
Ejemplo n.º 7
0
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (PyObjectFields, bootstrap_function,
                                    cpython_struct, CANNOT_FAIL, cpython_api,
                                    PyObject, build_type_checkers,
                                    CONST_STRING)
from pypy.module.cpyext.pyobject import (make_typedescr, track_reference,
                                         from_ref)
from pypy.interpreter.error import OperationError
from rpython.rlib.rstruct import runpack
from pypy.objspace.std.floatobject import W_FloatObject

PyFloatObjectStruct = lltype.ForwardReference()
PyFloatObject = lltype.Ptr(PyFloatObjectStruct)
PyFloatObjectFields = PyObjectFields + \
    (("ob_fval", rffi.DOUBLE),)
cpython_struct("PyFloatObject", PyFloatObjectFields, PyFloatObjectStruct)


@bootstrap_function
def init_floatobject(space):
    "Type description of PyFloatObject"
    make_typedescr(space.w_float.layout.typedef,
                   basestruct=PyFloatObject.TO,
                   attach=float_attach,
                   realize=float_realize)


def float_attach(space, py_obj, w_obj, w_userdata=None):
    """
    Fills a newly allocated PyFloatObject with the given float object. The
    value must not be modified.
Ejemplo n.º 8
0
Archivo: clibffi.py Proyecto: Mu-L/pypy
        post_include_bits=post_include_bits,
    )

    eci = rffi_platform.configure_external_library('ffi-5', eci, [
        dict(prefix='libffi-', include_dir='include', library_dir='.libs'),
        dict(prefix=r'c:\\mingw64', include_dir='include', library_dir='lib'),
    ])
else:
    eci = ExternalCompilationInfo(
        includes=['ffi.h', 'windows.h'],
        libraries=['kernel32', 'libffi-8'],
        separate_module_sources=separate_module_sources,
        post_include_bits=post_include_bits,
    )

FFI_TYPE_P = lltype.Ptr(lltype.ForwardReference())
FFI_TYPE_PP = rffi.CArrayPtr(FFI_TYPE_P)
FFI_TYPE_NULL = lltype.nullptr(FFI_TYPE_P.TO)


class CConfig:
    _compilation_info_ = eci

    FFI_OK = rffi_platform.ConstantInteger('FFI_OK')
    FFI_BAD_TYPEDEF = rffi_platform.ConstantInteger('FFI_BAD_TYPEDEF')
    FFI_DEFAULT_ABI = rffi_platform.ConstantInteger('FFI_DEFAULT_ABI')
    if _WIN32 and not _WIN64:
        FFI_STDCALL = rffi_platform.ConstantInteger('FFI_STDCALL')

    if _ARM:
        FFI_SYSV = rffi_platform.ConstantInteger('FFI_SYSV')
Ejemplo n.º 9
0
else:
    libname = 'expat'
    pre_include_bits = []
eci = ExternalCompilationInfo(
    libraries=[libname],
    library_dirs=platform.preprocess_library_dirs([]),
    includes=['expat.h'],
    include_dirs=platform.preprocess_include_dirs([]),
    pre_include_bits=pre_include_bits,
)

eci = rffi_platform.configure_external_library(libname, eci, [
    dict(prefix='expat-', include_dir='lib', library_dir='win32/bin/release'),
])

XML_Content_Ptr = lltype.Ptr(lltype.ForwardReference())
XML_Parser = rffi.COpaquePtr(typedef='XML_Parser')

xml_error_list = [
    "XML_ERROR_NO_MEMORY",
    "XML_ERROR_SYNTAX",
    "XML_ERROR_NO_ELEMENTS",
    "XML_ERROR_INVALID_TOKEN",
    "XML_ERROR_UNCLOSED_TOKEN",
    "XML_ERROR_PARTIAL_CHAR",
    "XML_ERROR_TAG_MISMATCH",
    "XML_ERROR_DUPLICATE_ATTRIBUTE",
    "XML_ERROR_JUNK_AFTER_DOC_ELEMENT",
    "XML_ERROR_PARAM_ENTITY_REF",
    "XML_ERROR_UNDEFINED_ENTITY",
    "XML_ERROR_RECURSIVE_ENTITY_REF",
Ejemplo n.º 10
0
def get_chunk_manager(chunk_size=DEFAULT_CHUNK_SIZE, cache={}):
    try:
        return cache[chunk_size]
    except KeyError:
        pass

    CHUNK = lltype.ForwardReference()
    CHUNK.become(
        lltype.Struct(
            'AddressChunk', ('next', lltype.Ptr(CHUNK)),
            ('items', lltype.FixedSizeArray(llmemory.Address, chunk_size))))
    null_chunk = lltype.nullptr(CHUNK)

    class FreeList(object):
        _alloc_flavor_ = "raw"

        def __init__(self):
            self.free_list = null_chunk

        def get(self):
            if not self.free_list:
                # we zero-initialize the chunks to make the translation
                # backends happy, but we don't need to do it at run-time.
                zero = not we_are_translated()
                return lltype.malloc(CHUNK,
                                     flavor="raw",
                                     zero=zero,
                                     track_allocation=False)

            result = self.free_list
            self.free_list = result.next
            return result

        def put(self, chunk):
            if we_are_translated():
                chunk.next = self.free_list
                self.free_list = chunk
            else:
                # Don't cache the old chunks but free them immediately.
                # Helps debugging, and avoids that old chunks full of
                # addresses left behind by a test end up in genc...
                lltype.free(chunk, flavor="raw", track_allocation=False)

    unused_chunks = FreeList()
    cache[chunk_size] = unused_chunks, null_chunk

    def partition(array, left, right):
        last_item = array[right]
        pivot = last_item
        storeindex = left
        for i in range(left, right):
            if array[i] >= pivot:
                array[i], array[storeindex] = array[storeindex], array[i]
                storeindex += 1
        # Move pivot to its final place
        array[storeindex], array[right] = last_item, array[storeindex]
        return storeindex

    def quicksort(array, left, right):
        # sort array[left:right+1] (i.e. bounds included)
        if right > left:
            pivotnewindex = partition(array, left, right)
            quicksort(array, left, pivotnewindex - 1)
            quicksort(array, pivotnewindex + 1, right)

    def sort_chunk(chunk, size):
        quicksort(chunk.items, 0, size - 1)

    return unused_chunks, null_chunk, sort_chunk
Ejemplo n.º 11
0
ASM_CALLBACK_PTR = lltype.Ptr(lltype.FuncType([], lltype.Void))

# used internally by walk_stack_from()
WALKFRAME = lltype.Struct(
    'WALKFRAME',
    (
        'regs_stored_at',  # address of where the registers have been saved
        lltype.FixedSizeArray(llmemory.Address, CALLEE_SAVED_REGS)),
    ('frame_address', llmemory.Address),
)

# We have a circular doubly-linked list of all the ASM_FRAMEDATAs currently
# alive.  The list's starting point is given by 'gcrootanchor', which is not
# a full ASM_FRAMEDATA but only contains the prev/next pointers:
ASM_FRAMEDATA_HEAD_PTR = lltype.Ptr(lltype.ForwardReference())
ASM_FRAMEDATA_HEAD_PTR.TO.become(
    lltype.Struct('ASM_FRAMEDATA_HEAD', ('prev', ASM_FRAMEDATA_HEAD_PTR),
                  ('next', ASM_FRAMEDATA_HEAD_PTR)))
gcrootanchor = lltype.malloc(ASM_FRAMEDATA_HEAD_PTR.TO, immortal=True)
gcrootanchor.prev = gcrootanchor
gcrootanchor.next = gcrootanchor
c_gcrootanchor = Constant(gcrootanchor, ASM_FRAMEDATA_HEAD_PTR)

eci = ExternalCompilationInfo(compile_extra=['-DPYPY_USE_ASMGCC'],
                              post_include_bits=[
                                  """
static int pypy_compare_gcmap_entries(const void *addr1, const void *addr2)
{
    char *key1 = * (char * const *) addr1;
    char *key2 = * (char * const *) addr2;
Ejemplo n.º 12
0
from pypy.module.cpyext.api import (cpython_api, generic_cpy_call, CANNOT_FAIL,
                                    CConfig, cpython_struct)
from pypy.module.cpyext.pyobject import PyObject, Py_DecRef, make_ref, from_ref
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rlib import rthread

PyInterpreterStateStruct = lltype.ForwardReference()
PyInterpreterState = lltype.Ptr(PyInterpreterStateStruct)
cpython_struct("PyInterpreterState", [('next', PyInterpreterState)],
               PyInterpreterStateStruct)
PyThreadState = lltype.Ptr(
    cpython_struct("PyThreadState", [
        ('interp', PyInterpreterState),
        ('dict', PyObject),
    ]))


class NoThreads(Exception):
    pass


@cpython_api([], PyThreadState, error=CANNOT_FAIL, gil="release")
def PyEval_SaveThread(space):
    """Release the global interpreter lock (if it has been created and thread
    support is enabled) and reset the thread state to NULL, returning the
    previous thread state.  If the lock has been created,
    the current thread must have acquired it.  (This function is available even
    when thread support is disabled at compile time.)"""
    state = space.fromcache(InterpreterState)
    tstate = state.swap_thread_state(space, lltype.nullptr(PyThreadState.TO))
    return tstate
Ejemplo n.º 13
0
# change the typedef name
W_MemberDescr.typedef = TypeDef(
    "member_descriptor",
    __get__ = interp2app(GetSetProperty.descr_property_get),
    __set__ = interp2app(GetSetProperty.descr_property_set),
    __delete__ = interp2app(GetSetProperty.descr_property_del),
    __name__ = interp_attrproperty('name', cls=GetSetProperty,
        wrapfn="newtext_or_none"),
    __objclass__ = GetSetProperty(GetSetProperty.descr_get_objclass),
    __doc__ = interp_attrproperty('doc', cls=GetSetProperty,
        wrapfn="newtext_or_none"),
    )
assert not W_MemberDescr.typedef.acceptable_as_base_class  # no __new__

PyDescrObject = lltype.ForwardReference()
PyDescrObjectPtr = lltype.Ptr(PyDescrObject)
PyDescrObjectFields = PyObjectFields + (
    ("d_type", PyTypeObjectPtr),
    ("d_name", PyObject),
    )
cpython_struct("PyDescrObject", PyDescrObjectFields,
               PyDescrObject)

PyMemberDescrObjectStruct = lltype.ForwardReference()
PyMemberDescrObject = lltype.Ptr(PyMemberDescrObjectStruct)
PyMemberDescrObjectFields = PyDescrObjectFields + (
    ("d_member", lltype.Ptr(PyMemberDef)),
    )
cpython_struct("PyMemberDescrObject", PyMemberDescrObjectFields,
               PyMemberDescrObjectStruct, level=2)
Ejemplo n.º 14
0
from pypy.interpreter.error import OperationError
from pypy.objspace.std.classdict import ClassDictStrategy
from pypy.objspace.std.dictmultiobject import W_DictMultiObject
from pypy.interpreter.typedef import GetSetProperty
from pypy.module.cpyext.api import (cpython_api, CANNOT_FAIL,
                                    build_type_checkers_flags, Py_ssize_t,
                                    Py_ssize_tP, CONST_STRING, PyObjectFields,
                                    cpython_struct, bootstrap_function,
                                    slot_function)
from pypy.module.cpyext.pyobject import (PyObject, PyObjectP, as_pyobj,
                                         make_typedescr, track_reference,
                                         create_ref, from_ref, decref, incref)
from pypy.module.cpyext.object import _dealloc
from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall

PyDictObjectStruct = lltype.ForwardReference()
PyDictObject = lltype.Ptr(PyDictObjectStruct)
PyDictObjectFields = PyObjectFields + \
    (("_tmpkeys", PyObject),)
cpython_struct("PyDictObject", PyDictObjectFields, PyDictObjectStruct)


@bootstrap_function
def init_dictobject(space):
    "Type description of PyDictObject"
    make_typedescr(space.w_dict.layout.typedef,
                   basestruct=PyDictObject.TO,
                   attach=dict_attach,
                   dealloc=dict_dealloc,
                   realize=dict_realize)
Ejemplo n.º 15
0
 def __init__(self, rtyper, classdef):
     self.rtyper = rtyper
     self.classdef = classdef
     self.vtable_type = lltype.ForwardReference()
     self.lowleveltype = Ptr(self.vtable_type)
Ejemplo n.º 16
0
##   allocate a PyStringObject structure, and a buffer with the specified
##   size, but the reference won't be stored in the global map; there is no
##   corresponding object in pypy.  When from_ref() or Py_INCREF() is called,
##   the pypy string is created, and added to the global map of tracked
##   objects.  The buffer is then supposed to be immutable.
##
## - _PyString_Resize() works only on not-yet-pypy'd strings, and returns a
##   similar object.
##
## - PyString_Size() doesn't need to force the object.
##
## - There could be an (expensive!) check in from_ref() that the buffer still
##   corresponds to the pypy gc-managed string.
##

PyStringObjectStruct = lltype.ForwardReference()
PyStringObject = lltype.Ptr(PyStringObjectStruct)
PyStringObjectFields = PyObjectFields + \
    (("buffer", rffi.CCHARP), ("size", Py_ssize_t))
cpython_struct("PyStringObject", PyStringObjectFields, PyStringObjectStruct)

@bootstrap_function
def init_stringobject(space):
    "Type description of PyStringObject"
    make_typedescr(space.w_str.instancetypedef,
                   basestruct=PyStringObject.TO,
                   attach=string_attach,
                   dealloc=string_dealloc,
                   realize=string_realize)

PyString_Check, PyString_CheckExact = build_type_checkers("String", "w_str")
Ejemplo n.º 17
0
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (cpython_api, bootstrap_function,
                                    PyObjectFields, cpython_struct,
                                    CANNOT_FAIL)
from pypy.module.cpyext.pyobject import (PyObject, Py_DecRef, make_ref,
                                         from_ref, track_reference,
                                         make_typedescr, get_typedescr)
from pypy.module.cpyext.state import State
from pypy.module.cpyext.pystate import PyThreadState
from pypy.module.cpyext.funcobject import PyCodeObject
from pypy.interpreter.pyframe import PyFrame
from pypy.interpreter.pycode import PyCode
from pypy.interpreter.pytraceback import PyTraceback

PyFrameObjectStruct = lltype.ForwardReference()
PyFrameObject = lltype.Ptr(PyFrameObjectStruct)
PyFrameObjectFields = (PyObjectFields + (
    ("f_code", PyCodeObject),
    ("f_globals", PyObject),
    ("f_lineno", rffi.INT),
))
cpython_struct("PyFrameObject", PyFrameObjectFields, PyFrameObjectStruct)


@bootstrap_function
def init_frameobject(space):
    make_typedescr(PyFrame.typedef,
                   basestruct=PyFrameObject.TO,
                   attach=frame_attach,
                   dealloc=frame_dealloc,
                   realize=frame_realize)
Ejemplo n.º 18
0
                                    build_type_checkers, Py_ssize_tP,
                                    PyObjectFields, cpython_struct,
                                    bootstrap_function, Py_bufferP,
                                    slot_function, generic_cpy_call)
from pypy.module.cpyext.pyobject import (PyObject, make_ref, as_pyobj, decref,
                                         from_ref, make_typedescr,
                                         get_typedescr, track_reference)
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rlib.rarithmetic import widen
from pypy.objspace.std.memoryobject import W_MemoryView
from pypy.module.cpyext.object import _dealloc
from pypy.module.cpyext.import_ import PyImport_Import

PyMemoryView_Check, PyMemoryView_CheckExact = build_type_checkers("MemoryView")

PyMemoryViewObjectStruct = lltype.ForwardReference()
PyMemoryViewObject = lltype.Ptr(PyMemoryViewObjectStruct)
PyMemoryViewObjectFields = PyObjectFields + \
    (("view", Py_buffer),)
cpython_struct("PyMemoryViewObject",
               PyMemoryViewObjectFields,
               PyMemoryViewObjectStruct,
               level=2)


@bootstrap_function
def init_memoryobject(space):
    "Type description of PyDictObject"
    make_typedescr(
        W_MemoryView.typedef,
        basestruct=PyMemoryViewObject.TO,
Ejemplo n.º 19
0
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (PyObjectFields, generic_cpy_call,
                                    CONST_STRING, CANNOT_FAIL, Py_ssize_t,
                                    cpython_api, bootstrap_function,
                                    cpython_struct, slot_function)
from pypy.module.cpyext.pyobject import (PyObject, make_ref, from_ref, decref,
                                         make_typedescr)
from pypy.module.cpyext.frameobject import PyFrameObject
from pypy.interpreter.error import OperationError
from pypy.interpreter.pytraceback import PyTraceback
from pypy.interpreter import pycode

PyTracebackObjectStruct = lltype.ForwardReference()
PyTracebackObject = lltype.Ptr(PyTracebackObjectStruct)
PyTracebackObjectFields = PyObjectFields + (
    ("tb_next", PyTracebackObject),
    ("tb_frame", PyFrameObject),
    ("tb_lasti", rffi.INT),
    ("tb_lineno", rffi.INT),
)
cpython_struct("PyTracebackObject", PyTracebackObjectFields,
               PyTracebackObjectStruct)


@bootstrap_function
def init_traceback(space):
    make_typedescr(PyTraceback.typedef,
                   basestruct=PyTracebackObject.TO,
                   attach=traceback_attach,
                   dealloc=traceback_dealloc)
Ejemplo n.º 20
0
                                    CONST_WSTRING)
from pypy.module.cpyext.pyerrors import PyErr_BadArgument
from pypy.module.cpyext.pyobject import (PyObject, PyObjectP, Py_DecRef,
                                         make_ref, from_ref, track_reference,
                                         make_typedescr, get_typedescr)
from pypy.module.cpyext.stringobject import PyString_Check
from pypy.module.sys.interp_encoding import setdefaultencoding
from pypy.module._codecs.interp_codecs import CodecState
from pypy.objspace.std import unicodeobject
from rpython.rlib import rstring, runicode
from rpython.tool.sourcetools import func_renamer
import sys

## See comment in stringobject.py.

PyUnicodeObjectStruct = lltype.ForwardReference()
PyUnicodeObject = lltype.Ptr(PyUnicodeObjectStruct)
PyUnicodeObjectFields = (PyObjectFields + (("buffer", rffi.CWCHARP),
                                           ("size", Py_ssize_t)))
cpython_struct("PyUnicodeObject", PyUnicodeObjectFields, PyUnicodeObjectStruct)


@bootstrap_function
def init_unicodeobject(space):
    make_typedescr(space.w_unicode.instancetypedef,
                   basestruct=PyUnicodeObject.TO,
                   attach=unicode_attach,
                   dealloc=unicode_dealloc,
                   realize=unicode_realize)

Ejemplo n.º 21
0
#      }

# The type of the instances is:
#
#     struct object {       // for the root class
#         struct object_vtable* typeptr;
#     }
#
#     struct X {
#         struct Y super;   // inlined
#         ...               // extra instance attributes
#     }
#
# there's also a nongcobject

OBJECT_VTABLE = lltype.ForwardReference()
CLASSTYPE = Ptr(OBJECT_VTABLE)
OBJECT = GcStruct('object', ('typeptr', CLASSTYPE),
                  hints={
                      'immutable': True,
                      'shouldntbenull': True,
                      'typeptr': True
                  },
                  rtti=True)
OBJECTPTR = Ptr(OBJECT)
OBJECT_VTABLE.become(
    Struct(
        'object_vtable',
        #('parenttypeptr', CLASSTYPE),
        ('subclassrange_min', Signed),
        ('subclassrange_max', Signed),
Ejemplo n.º 22
0
    post_include_bits=[
        # Unnamed structures are not supported by rffi_platform.
        # So we replace an attribute access with a macro call.
        '#define pypy_GENERAL_NAME_dirn(name) (name->d.dirn)',
        '#define pypy_GENERAL_NAME_uri(name) (name->d.uniformResourceIdentifier)',
        '#define pypy_GENERAL_NAME_pop_free(names) (sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free))',
        '#define pypy_X509_OBJECT_data_x509(obj) (obj->data.x509)',
        '#define pypy_DIST_POINT_fullname(obj) (obj->distpoint->name.fullname)',
    ],
)

eci = rffi_platform.configure_external_library('openssl', eci, [
    dict(prefix='openssl-', include_dir='inc32', library_dir='out32'),
])

ASN1_STRING = lltype.Ptr(lltype.ForwardReference())
ASN1_IA5STRING = ASN1_STRING
ASN1_ITEM = rffi.COpaquePtr('ASN1_ITEM')
ASN1_OBJECT = rffi.COpaquePtr('ASN1_OBJECT')
X509_NAME = rffi.COpaquePtr('X509_NAME')
X509_VERIFY_PARAM = rffi.COpaquePtr('X509_VERIFY_PARAM')
stack_st_X509_OBJECT = rffi.COpaquePtr('STACK_OF(X509_OBJECT)')
DIST_POINT = rffi.COpaquePtr('DIST_POINT')
stack_st_DIST_POINT = rffi.COpaquePtr('STACK_OF(X509_OBJECT)')
DH = rffi.COpaquePtr('DH')
EC_KEY = rffi.COpaquePtr('EC_KEY')
AUTHORITY_INFO_ACCESS = rffi.COpaquePtr('AUTHORITY_INFO_ACCESS')
GENERAL_NAME = lltype.Ptr(lltype.ForwardReference())


class CConfigBootstrap:
Ejemplo n.º 23
0
eci = ExternalCompilationInfo(
    libraries=libraries,
    includes=includes,
    post_include_bits=[
        # Unnamed structures are not supported by rffi_platform.
        # So we replace an attribute access with a macro call.
        '#define pypy_GENERAL_NAME_dirn(name) (name->d.dirn)',
    ],
)

eci = rffi_platform.configure_external_library('openssl', eci, [
    dict(prefix='openssl-', include_dir='inc32', library_dir='out32'),
])

ASN1_STRING = lltype.Ptr(lltype.ForwardReference())
ASN1_ITEM = rffi.COpaquePtr('ASN1_ITEM')
X509_NAME = rffi.COpaquePtr('X509_NAME')


class CConfigBootstrap:
    _compilation_info_ = eci
    OPENSSL_EXPORT_VAR_AS_FUNCTION = rffi_platform.Defined(
        "OPENSSL_EXPORT_VAR_AS_FUNCTION")


if rffi_platform.configure(CConfigBootstrap)["OPENSSL_EXPORT_VAR_AS_FUNCTION"]:
    ASN1_ITEM_EXP = lltype.Ptr(lltype.FuncType([], ASN1_ITEM))
else:
    ASN1_ITEM_EXP = ASN1_ITEM
Ejemplo n.º 24
0
    w_type = space.getattr(w_datetime, space.wrap("time"))
    datetimeAPI.c_TimeType = rffi.cast(PyTypeObjectPtr,
                                       make_ref(space, w_type))

    w_type = space.getattr(w_datetime, space.wrap("timedelta"))
    datetimeAPI.c_DeltaType = rffi.cast(PyTypeObjectPtr,
                                        make_ref(space, w_type))

    return datetimeAPI


PyDateTime_Date = PyObject
PyDateTime_Time = PyObject
PyDateTime_DateTime = PyObject

PyDeltaObjectStruct = lltype.ForwardReference()
cpython_struct("PyDateTime_Delta", PyObjectFields, PyDeltaObjectStruct)
PyDateTime_Delta = lltype.Ptr(PyDeltaObjectStruct)

# Check functions


def make_check_function(func_name, type_name):
    @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
    @func_renamer(func_name)
    def check(space, w_obj):
        try:
            return space.is_true(
                space.appexec([w_obj], """(obj):
                    from datetime import %s as datatype
                    return isinstance(obj, datatype)
Ejemplo n.º 25
0
from rpython.rlib.rarithmetic import LONG_BIT, r_uint
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.debug import ll_assert, fatalerror

WORD = LONG_BIT // 8
NULL = llmemory.NULL
WORD_POWER_2 = {32: 2, 64: 3}[LONG_BIT]
assert 1 << WORD_POWER_2 == WORD

# Terminology: the memory is subdivided into "arenas" containing "pages".
# A page contains a number of allocated objects, called "blocks".

# The actual allocation occurs in whole arenas, which are then subdivided
# into pages.  For each arena we allocate one of the following structures:

ARENA_PTR = lltype.Ptr(lltype.ForwardReference())
ARENA = lltype.Struct(
    'ArenaReference',
    # -- The address of the arena, as returned by malloc()
    ('base', llmemory.Address),
    # -- The number of free and the total number of pages in the arena
    ('nfreepages', lltype.Signed),
    ('totalpages', lltype.Signed),
    # -- A chained list of free pages in the arena.  Ends with NULL.
    ('freepages', llmemory.Address),
    # -- A linked list of arenas.  See below.
    ('nextarena', ARENA_PTR),
)
ARENA_PTR.TO.become(ARENA)
ARENA_NULL = lltype.nullptr(ARENA)
Ejemplo n.º 26
0
## if they are called with a non-forced PyBytesObject, they will not
## unintentionally force the creation of a RPython object. As long as only these
## are used, the ob_sval buffer is still modifiable:
##
## PyBytes_AsString / PyString_AsString
## PyBytes_AS_STRING / PyString_AS_STRING
## PyBytes_AsStringAndSize / PyString_AsStringAndSize
## PyBytes_Size / PyString_Size
## PyBytes_Resize / PyString_Resize
## _PyBytes_Resize / _PyString_Resize (raises if called with a forced object)
##
## - There could be an (expensive!) check in from_ref() that the buffer still
##   corresponds to the pypy gc-managed string,
##

PyBytesObjectStruct = lltype.ForwardReference()
PyBytesObject = lltype.Ptr(PyBytesObjectStruct)
PyBytesObjectFields = PyVarObjectFields + \
    (("ob_shash", rffi.LONG), ("ob_sstate", rffi.INT), ("ob_sval", rffi.CArray(lltype.Char)))
cpython_struct("PyBytesObject", PyBytesObjectFields, PyBytesObjectStruct)


@bootstrap_function
def init_bytesobject(space):
    "Type description of PyBytesObject"
    make_typedescr(space.w_bytes.layout.typedef,
                   basestruct=PyBytesObject.TO,
                   attach=bytes_attach,
                   dealloc=bytes_dealloc,
                   realize=bytes_realize)
Ejemplo n.º 27
0

class CInterface(object):
    def __init__(self, namespace):
        for k, v in namespace.iteritems():
            setattr(self, k, v)

    def _freeze_(self):
        return True


# --- copy a few declarations from src/vmprof_stack.h ---

VMPROF_CODE_TAG = 1

VMPROFSTACK = lltype.ForwardReference()
PVMPROFSTACK = lltype.Ptr(VMPROFSTACK)
VMPROFSTACK.become(
    rffi.CStruct("vmprof_stack_s", ('next', PVMPROFSTACK),
                 ('value', lltype.Signed), ('kind', lltype.Signed)))
# ----------

vmprof_tl_stack = rthread.ThreadLocalField(PVMPROFSTACK, "vmprof_tl_stack")
do_use_eci = rffi.llexternal_use_eci(
    ExternalCompilationInfo(includes=['vmprof_stack.h'], include_dirs=[SRC]))


def enter_code(unique_id):
    do_use_eci()
    s = lltype.malloc(VMPROFSTACK, flavor='raw')
    s.c_next = vmprof_tl_stack.get_or_make_raw()
Ejemplo n.º 28
0
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (
    cpython_api, cpython_struct, bootstrap_function, build_type_checkers,
    CANNOT_FAIL, Py_ssize_t, Py_ssize_tP, PyObjectFields, slot_function)
from pypy.module.cpyext.pyobject import (
    decref, PyObject, make_ref, make_typedescr)
from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall
from pypy.interpreter.error import OperationError
from pypy.objspace.std.sliceobject import W_SliceObject

# Slice objects directly expose their members as PyObject.
# Don't change them!

PySliceObjectStruct = lltype.ForwardReference()
PySliceObject = lltype.Ptr(PySliceObjectStruct)
PySliceObjectFields = PyObjectFields + \
    (("start", PyObject), ("step", PyObject), ("stop", PyObject), )
cpython_struct("PySliceObject", PySliceObjectFields, PySliceObjectStruct)

@bootstrap_function
def init_sliceobject(space):
    "Type description of PySliceObject"
    make_typedescr(W_SliceObject.typedef,
                   basestruct=PySliceObject.TO,
                   attach=slice_attach,
                   dealloc=slice_dealloc)

def slice_attach(space, py_obj, w_obj, w_userdata=None):
    """
    Fills a newly allocated PySliceObject with the given slice object. The
    fields must not be modified.
Ejemplo n.º 29
0
from pypy.interpreter.error import OperationError
from pypy.interpreter.function import Function, Method
from pypy.interpreter.pycode import PyCode
from pypy.interpreter import pycode

CODE_FLAGS = dict(
    CO_OPTIMIZED=0x0001,
    CO_NEWLOCALS=0x0002,
    CO_VARARGS=0x0004,
    CO_VARKEYWORDS=0x0008,
    CO_NESTED=0x0010,
    CO_GENERATOR=0x0020,
)
ALL_CODE_FLAGS = unrolling_iterable(CODE_FLAGS.items())

PyFunctionObjectStruct = lltype.ForwardReference()
PyFunctionObject = lltype.Ptr(PyFunctionObjectStruct)
PyFunctionObjectFields = PyObjectFields + \
    (("func_name", PyObject),)
cpython_struct("PyFunctionObject", PyFunctionObjectFields,
               PyFunctionObjectStruct)

PyCodeObjectStruct = lltype.ForwardReference()
PyCodeObject = lltype.Ptr(PyCodeObjectStruct)
PyCodeObjectFields = PyObjectFields + \
    (("co_name", PyObject),
     ("co_filename", PyObject),
     ("co_flags", rffi.INT),
     ("co_argcount", rffi.INT),
    )
cpython_struct("PyCodeObject", PyCodeObjectFields, PyCodeObjectStruct)
Ejemplo n.º 30
0
## Implementation of PyTupleObject
## ===============================
##
## Similar to stringobject.py.  The reason is only the existance of
## W_SpecialisedTupleObject_ii and W_SpecialisedTupleObject_ff.
## These two PyPy classes implement getitem() by returning a freshly
## constructed W_IntObject or W_FloatObject.  This is not compatible
## with PyTuple_GetItem, which returns a borrowed reference.
##
## So we use this more advanced (but also likely faster) solution:
## tuple_attach makes a real PyTupleObject with an array of N
## 'PyObject *', which are created immediately and own a reference.
## Then the macro PyTuple_GET_ITEM can be implemented like CPython.
##

PyTupleObjectStruct = lltype.ForwardReference()
PyTupleObject = lltype.Ptr(PyTupleObjectStruct)
ObjectItems = rffi.CArray(PyObject)
PyTupleObjectFields = PyVarObjectFields + \
    (("ob_item", ObjectItems),)
cpython_struct("PyTupleObject", PyTupleObjectFields, PyTupleObjectStruct)

@bootstrap_function
def init_stringobject(space):
    "Type description of PyTupleObject"
    make_typedescr(space.w_tuple.layout.typedef,
                   basestruct=PyTupleObject.TO,
                   attach=tuple_attach,
                   dealloc=tuple_dealloc,
                   realize=tuple_realize)