Esempio n. 1
0
 def flag(self, name, values=None):
     if values is None:
         flag = name
     else:
         flag = enum.Flag(name, values)
     self._model.append(flag)
     return flag
def _create_flag(data):
    try:
        obj = enum.Flag(data[0], data[2])
    except AttributeError:
        # If the Flag class doesn't exist we fall back our own flag class
        from .flag import create_flag
        obj = create_flag(data[0], data[2])
    if data[1]:
        setattr(obj, '__doc__', data[1])
    return obj
Esempio n. 3
0
def test_resolves_flag_enum(resolver):
    # Storing all combinations takes O(2^n) memory.  Using an enum of 52
    # members in this test ensures that we won't try!
    F = enum.Flag('F', ' '.join(string.ascii_letters))
    # Filter to check that we can generate compound members of enum.Flags

    @given(resolver(F).filter(lambda ex: ex not in tuple(F)))
    def inner(ex):
        assert isinstance(ex, F)

    inner()
Esempio n. 4
0
class Endpoint(V.String):
    Side = enum.Flag("Side", "BIND CONNECT")

    name = "endpoint"

    def __init__(self, side=Side.BIND | Side.CONNECT, **kwargs):
        super().__init__(**kwargs)
        self.side = side

    def validate(self, value, adapt=True):
        super().validate(value, adapt=adapt)
        transports = {
            "tcp": self._validate_tcp,
            "ipc": self._validate_ipc,
            "inproc": self._validate_inproc,
            "pgm": self._validate_pgm,
            "epgm": self._validate_pgm,
            "vmci": self._validate_vmci,
        }
        transport, sep, endpoint = value.partition("://")
        if not sep:
            raise V.ValidationError("missing transport://")
        if transport not in transports:
            raise V.ValidationError(f"invalid transport {transport!r}")
        transports[transport](endpoint)
        return value

    def _validate_tcp(self, endpoint):
        source_endpoint, sep, endpoint = endpoint.rpartition(";")
        if sep:
            if self.side is not self.Side.CONNECT:
                raise V.ValidationError(
                    "must not specify source in bindable endpoint")
            self._validate_tcp_endpoint(source_endpoint, wildcard_ok=True)

        self._validate_tcp_endpoint(endpoint,
                                    wildcard_ok=self.side is self.Side.BIND)

    def _validate_tcp_endpoint(self, endpoint, wildcard_ok=False):
        host, port = self._validate_port_pair(endpoint,
                                              "host",
                                              wildcard_ok=wildcard_ok)
        if host == "*":
            if not wildcard_ok:
                raise V.ValidationError(
                    "wildcard host not valid in this context")
        elif not DNS_OR_IP_REGEX.match(host):
            raise V.ValidationError(f"host {host!r} does not look like a "
                                    "valid hostname nor an IP address")

    def _validate_ipc(self, endpoint):
        if "\0" in endpoint:
            raise V.ValidationError("paths must not contain NUL bytes")

    def _validate_inproc(self, endpoint):
        if not endpoint:
            raise V.ValidationError("inproc name must not be empty")
        if len(endpoint) > 256:
            raise V.ValidationError("inproc name must not be longer than 256 "
                                    "characters")

    def _validate_pgm(self, endpoint):
        rest, port = self._validate_port_pair(endpoint, "interface;multicast")
        iface, sep, multicast = rest.rpartition(";")
        if not sep:
            raise V.ValidationError("missing semicolon separator")
        # XXX: is it worth validating iface?
        try:
            multicast = ipaddress.IPv4Address(multicast)
        except ipaddress.AddressValueError as e:
            # XXX: what address is causing the error?
            raise V.ValidationError(str(e)) from None
        if not multicast.is_multicast:
            raise V.ValidationError(f"{str(multicast)!r} is not a multicast "
                                    "address")

    def _validate_vmci(self, endpoint):
        iface, port = self._validate_port_pair(
            endpoint, "interface", wildcard_ok=self.side is self.Side.BIND)
        if iface == "*":
            if self.side is not self.Side.BIND:
                raise V.ValidationError(
                    "wildcard interface not valid in this context")
        elif not iface.isdigit():
            raise V.ValidationError(f"interface {iface!r} must be an integer")

    def _validate_port_pair(self, endpoint, rest_name, wildcard_ok=False):
        rest, sep, port = endpoint.rpartition(":")
        if not sep:
            raise V.ValidationError(f"endpoint {endpoint} does not follow the "
                                    f"format of {rest_name}:port")
        if port == "*":
            if not wildcard_ok:
                # XXX: what context?
                raise V.ValidationError(
                    "wildcard port not valid in this context")
        elif not port.isdigit():
            raise V.ValidationError(f"port {port!r} must be an integer")
        return rest, port
Esempio n. 5
0
except ImportError:
    dataclasses = None  # type: ignore

MyNamedTuple = collections.namedtuple('A', ['x', 'y'])
MyTypedNamedTuple = NamedTuple('MyTypedNamedTuple', [('f1', int), ('f2', str)])


class MyEnum(enum.Enum):
    E1 = 5
    E2 = enum.auto()
    E3 = 'abc'


MyIntEnum = enum.IntEnum('MyIntEnum', 'I1 I2 I3')
MyIntFlag = enum.IntFlag('MyIntFlag', 'F1 F2 F3')
MyFlag = enum.Flag('MyFlag', 'F1 F2 F3')  # pylint: disable=too-many-function-args


class DefinesGetState:
    def __init__(self, value):
        self.value = value

    def __getstate__(self):
        return self.value

    def __eq__(self, other):
        return type(other) is type(self) and other.value == self.value


class DefinesGetAndSetState(DefinesGetState):
    def __setstate__(self, value):
Esempio n. 6
0
                                pad=1,
                                handle_mouse=_handle_lb_mouse,
                                handle_itemclick=None):
    listBox = create_listbox(posX, posY, sizeX, sizeY, orientation, iD, pad,
                             handle_mouse, handle_itemclick)
    i = 0
    for imageFile in imageFiles:
        btn = create_imagebutton(imageFile, IGNORE, IGNORE, btnSizeX, btnSizeY,
                                 "{}.{}".format(iD, i))
        listbox_append_child(listBox, btnSizeX, btnSizeY, btn,
                             handle_itemclick)
        i += 1
    return listBox


AnimOrientation = enum.Flag("AnimOrientation", "BOTH HORIZONTAL VERTICAL")
SelectOffsetType = enum.Flag("SelectOffsetType", "START CUR")


def listbox_select(lb,
                   offset,
                   offsetType=SelectOffsetType.START,
                   animOrientation=None,
                   colorizeEffect=None,
                   scrollToView=True):
    cnt = lb.get_n_children()
    aID = lb.get_id()
    curIndex = gActors[aID]['curIndex']
    if offsetType == SelectOffsetType.CUR:
        nxtIndex = (curIndex + offset) % cnt
    elif offsetType == SelectOffsetType.START:
Esempio n. 7
0
def sys_ioctl(kernel: Kernel, fd: Int, request: Uint, data_addr: Uint):
    """
    Arguments: (int fd, unsigned long request, ...)
    """

    # SOURCE: http://man7.org/linux/man-pages/man2/ioctl_list.2.html
    # < include / asm - i386 / termios.h >
    #
    # 0x00005401 TCGETS struct termios *
    # 0x00005402 TCSETS const struct termios *
    # 0x00005403 TCSETSW const struct termios *
    # 0x00005404 TCSETSF const struct termios *
    # 0x00005405 TCGETA struct termio *
    # 0x00005406 TCSETA const struct termio *
    # 0x00005407 TCSETAW const struct termio *
    # 0x00005408 TCSETAF const struct termio *
    # 0x00005409 TCSBRK int
    # 0x0000540A TCXONC int
    # 0x0000540B TCFLSH int
    # 0x0000540C TIOCEXCL void
    # 0x0000540D TIOCNXCL void
    # 0x0000540E TIOCSCTTY int
    # 0x0000540F TIOCGPGRP pid_t *
    # 0x00005410 TIOCSPGRP const pid_t *
    # 0x00005411 TIOCOUTQ int *
    # 0x00005412 TIOCSTI const char *
    # 0x00005413 TIOCGWINSZ struct winsize *
    # 0x00005414 TIOCSWINSZ const struct winsize *
    # 0x00005415 TIOCMGET int *
    # 0x00005416 TIOCMBIS const int *
    # 0x00005417 TIOCMBIC const int *
    # 0x00005418 TIOCMSET const int *
    # 0x00005419 TIOCGSOFTCAR int *
    # 0x0000541A TIOCSSOFTCAR const int *
    # 0x0000541B FIONREAD int *
    # 0x0000541B TIOCINQ int *
    # 0x0000541C TIOCLINUX const char * // MORE
    # 0x0000541D TIOCCONS void
    # 0x0000541E TIOCGSERIAL struct serial_struct *
    # 0x0000541F TIOCSSERIAL const struct serial_struct *
    # 0x00005420 TIOCPKT const int *
    # 0x00005421 FIONBIO const int *
    # 0x00005422 TIOCNOTTY void
    # 0x00005423 TIOCSETD const int *
    # 0x00005424 TIOCGETD int *
    # 0x00005425 TCSBRKP int
    # 0x00005426 TIOCTTYGSTRUCT struct tty_struct *
    # 0x00005450 FIONCLEX void
    # 0x00005451 FIOCLEX void
    # 0x00005452 FIOASYNC const int *
    # 0x00005453 TIOCSERCONFIG void
    # 0x00005454 TIOCSERGWILD int *
    # 0x00005455 TIOCSERSWILD const int *
    # 0x00005456 TIOCGLCKTRMIOS struct termios *
    # 0x00005457 TIOCSLCKTRMIOS const struct termios *
    # 0x00005458 TIOCSERGSTRUCT struct async_struct *
    # 0x00005459 TIOCSERGETLSR int *
    # 0x0000545A TIOCSERGETMULTI struct serial_multiport_struct *
    # 0x0000545B TIOCSERSETMULTI const struct serial_multiport_struct *

    import enum
    directions = enum.Flag('directions',
                           '_IOC_NONE _IOC_READ _IOC_WRITE',
                           start=0)

    # TAKEN FROM: https://elixir.bootlin.com/linux/v5.0.8/source/include/uapi/asm-generic/ioctl.h
    _IOC_NRBITS = 8
    _IOC_TYPEBITS = 8
    _IOC_SIZEBITS = 14
    _IOC_DIRBITS = 2

    _IOC_NRMASK = ((1 << _IOC_NRBITS) - 1)
    _IOC_TYPEMASK = ((1 << _IOC_TYPEBITS) - 1)
    _IOC_SIZEMASK = ((1 << _IOC_SIZEBITS) - 1)
    _IOC_DIRMASK = ((1 << _IOC_DIRBITS) - 1)

    _IOC_NRSHIFT = 0
    _IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS
    _IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS
    _IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS

    _IOC_NONE = 0
    _IOC_WRITE = 1
    _IOC_READ = 2

    _IOC_DIR = lambda nr: (((nr) >> _IOC_DIRSHIFT) & _IOC_DIRMASK)
    _IOC_TYPE = lambda nr: (((nr) >> _IOC_TYPESHIFT) & _IOC_TYPEMASK)
    _IOC_NR = lambda nr: (((nr) >> _IOC_NRSHIFT) & _IOC_NRMASK)
    _IOC_SIZE = lambda nr: (((nr) >> _IOC_SIZESHIFT) & _IOC_SIZEMASK)

    IOC_IN = (_IOC_WRITE << _IOC_DIRSHIFT)
    IOC_OUT = (_IOC_READ << _IOC_DIRSHIFT)
    IOC_INOUT = ((_IOC_WRITE | _IOC_READ) << _IOC_DIRSHIFT)
    IOCSIZE_MASK = (_IOC_SIZEMASK << _IOC_SIZESHIFT)
    IOCSIZE_SHIFT = (_IOC_SIZESHIFT)

    request_type = bytes([_IOC_TYPE(request)])
    request_number = _IOC_NR(request)
    request_direction = directions(_IOC_DIR(request))
    request_size = _IOC_SIZE(request)

    logger.info(
        f'ioctl(fd={fd},request={request:09_x} (type={request_type}, number={request_number}, direction={request_direction}, size={request_size}))'
    )

    if request_type == b'T':
        if request_number == 19 and request_direction == directions._IOC_NONE:
            try:
                kernel.cpu.descriptors[fd]
            except IndexError:
                return kernel.cpu.__return(-1)

            # TAKEN FROM: http://man7.org/linux/man-pages/man4/tty_ioctl.4.html
            #
            # struct winsize
            # {
            #     unsigned short ws_row;
            #     unsigned short ws_col;
            #     unsigned short ws_xpixel; / *unused * /
            #     unsigned short ws_ypixel; / *unused * /
            # };
            struct_winsize = struct.Struct('<HHHH')

            kernel.cpu.mem.set_bytes(data_addr, struct_winsize.size,
                                     struct_winsize.pack(256, 256, 0, 0))

            return 0

    return -1