0
  7   ˆl–Ým_J
j"TýÆß¸ÛJbÑ¿�þ\Œ�¬Ù
ÀVÄðžóÉ„­¼ÿÎÄÂË ?÷     # pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable
# pylint: disable=no-member
from __future__ import absolute_import, print_function

import functools
import sys

from gevent.libuv import _corecffi # pylint:disable=no-name-in-module,import-error

# Nothing public here
__all__ = []

ffi = _corecffi.ffi
libuv = _corecffi.lib

from gevent._ffi import watcher as _base
from gevent._ffi import _dbg

# A set of uv_handle_t* CFFI objects. Kept around
# to keep the memory alive until libuv is done with them.
class _ClosingWatchers(dict):
    __slots__ = ()

    def remove(self, obj):
        try:
            del self[obj]
        except KeyError: # pragma: no cover
            # This has been seen to happen if the module is executed twice
            # and so the callback doesn't match the storage seen by watcher objects.
            print(
                'gevent error: Unable to remove closing watcher from keepaliveset. '
                'Has the module state been corrupted or executed more than once?',
                file=sys.stderr
            )

_closing_watchers = _ClosingWatchers()


# In debug mode, it would be nice to be able to clear the memory of
# the watcher (its size determined by
# libuv.uv_handle_size(ffi_watcher.type)) using memset so that if we
# are using it after it's supposedly been closed and deleted, we'd
# catch it sooner. BUT doing so breaks test__threadpool. We get errors
# about `pthread_mutex_lock[3]: Invalid argument` (and sometimes we
# crash) suggesting either that we're writing on memory that doesn't
# belong to us, somehow, or that we haven't actually lost all
# references...
_uv_close_callback = ffi.def_extern(name='_uv_close_callback')(
    _closing_watchers.remove
)


_events = [(libuv.UV_READABLE, "READ"),
           (libuv.UV_WRITABLE, "WRITE")]

def _events_to_str(events): # export
    return _base.events_to_str(events, _events)

class UVFuncallError(ValueError):
    pass

class libuv_error_wrapper(object):
    # Makes sure that everything stored as a function
    # on the wrapper instances (classes, actually,
    # because this is used by the metaclass)
    # checks its return value and raises an error.
    # This expects that everything we call has an int
    # or void return value and follows the conventions
    # of error handling (that negative values are errors)
    def __init__(self, uv):
        self._libuv = uv

    def __getattr__(self, name):
        libuv_func = getattr(self._libuv, name)

        @functools.wraps(libuv_func)
        def wrap(*args, **kwargs):
            if args and isinstance(args[0], watcher):
                args = args[1:]
            res = libuv_func(*args, **kwargs)
            if res is not None and res < 0:
                raise UVFuncallError(
                    str(ffi.string(libuv.uv_err_name(res)).decode('ascii')
                        + ' '
                        + ffi.string(libuv.uv_strerror(res)).decode('ascii'))
                    + " Args: " + repr(args) + " KWARGS: " + repr(kwargs)
                )
            return res

        setattr(self, name, wrap)

        return wrap


class ffi_unwrapper(object):
    # undoes the wrapping of libuv_error_wrapper for
    # the methods used by the metaclass that care

    def __init__(self, ff):
        self._ffi = ff

    def __getattr__(self, name):
        return getattr(self._ffi, name)

    def addressof(self, lib, name):
        assert isinstance(lib, libuv_error_wrapper)
        return self._ffi.addressof(libuv, name)


class watcher(_base.watcher):
    _FFI = ffi_unwrapper(ffi)
    _LIB = libuv_error_wrapper(libuv)

    _watcher_prefix = 'uv'
    _watcher_struct_pattern = '%s_t'

    @classmethod
    def _watcher_ffi_close(cls, ffi_watcher):
        # Managing the lifetime of _watcher is tricky.
        # They have to be uv_close()'d, but that only
        # queues them to be closed in the *next* loop iteration.
        # The memory must stay valid for at least that long,
       