Example #1
0
 def string(self, cdataobj, maxlen):
     space = self.space
     if isinstance(self.ctitem, ctypeprim.W_CTypePrimitive):
         cdata = cdataobj._cdata
         if not cdata:
             raise operationerrfmt(space.w_RuntimeError,
                                   "cannot use string() on %s",
                                   space.str_w(cdataobj.repr()))
         #
         from pypy.module._cffi_backend import ctypearray
         length = maxlen
         if length < 0 and isinstance(self, ctypearray.W_CTypeArray):
             length = cdataobj.get_array_length()
         #
         # pointer to a primitive type of size 1: builds and returns a str
         if self.ctitem.size == rffi.sizeof(lltype.Char):
             if length < 0:
                 s = rffi.charp2str(cdata)
             else:
                 s = rffi.charp2strn(cdata, length)
             keepalive_until_here(cdataobj)
             return space.wrap(s)
         #
         # pointer to a wchar_t: builds and returns a unicode
         if self.is_unichar_ptr_or_array():
             cdata = rffi.cast(rffi.CWCHARP, cdata)
             if length < 0:
                 u = rffi.wcharp2unicode(cdata)
             else:
                 u = rffi.wcharp2unicoden(cdata, length)
             keepalive_until_here(cdataobj)
             return space.wrap(u)
     #
     return W_CType.string(self, cdataobj, maxlen)
Example #2
0
 def string(self, cdataobj, maxlen):
     space = self.space
     if isinstance(self.ctitem, ctypeprim.W_CTypePrimitive):
         cdata = cdataobj._cdata
         if not cdata:
             raise oefmt(space.w_RuntimeError, "cannot use string() on %s",
                         space.str_w(cdataobj.repr()))
         #
         from pypy.module._cffi_backend import ctypearray
         length = maxlen
         if length < 0 and isinstance(self, ctypearray.W_CTypeArray):
             length = cdataobj.get_array_length()
         #
         # pointer to a primitive type of size 1: builds and returns a str
         if self.ctitem.size == rffi.sizeof(lltype.Char):
             if length < 0:
                 s = rffi.charp2str(cdata)
             else:
                 s = rffi.charp2strn(cdata, length)
             keepalive_until_here(cdataobj)
             return space.wrap(s)
         #
         # pointer to a wchar_t: builds and returns a unicode
         if self.is_unichar_ptr_or_array():
             cdata = rffi.cast(rffi.CWCHARP, cdata)
             if length < 0:
                 u = rffi.wcharp2unicode(cdata)
             else:
                 u = rffi.wcharp2unicoden(cdata, length)
             keepalive_until_here(cdataobj)
             return space.wrap(u)
     #
     return W_CType.string(self, cdataobj, maxlen)
Example #3
0
def convert_from_regdata(space, buf, buflen, typ):
    if typ == rwinreg.REG_DWORD:
        if not buflen:
            return space.wrap(0)
        d = rffi.cast(rwin32.LPDWORD, buf)[0]
        return space.wrap(d)

    elif typ == rwinreg.REG_SZ or typ == rwinreg.REG_EXPAND_SZ:
        if not buflen:
            return space.wrap("")
        s = rffi.charp2strn(rffi.cast(rffi.CCHARP, buf), buflen)
        return space.wrap(s)

    elif typ == rwinreg.REG_MULTI_SZ:
        if not buflen:
            return space.newlist([])
        i = 0
        l = []
        while i < buflen and buf[i]:
            s = []
            while i < buflen and buf[i] != '\0':
                s.append(buf[i])
                i += 1
            if len(s) == 0:
                break
            s = ''.join(s)
            l.append(space.wrap(s))
            i += 1
        return space.newlist(l)

    else: # REG_BINARY and all other types
        return space.wrap(rffi.charpsize2str(buf, buflen))
Example #4
0
    def execute(self, space, sql, args=None):
        if self.column_count > 0:
            raise PrimitiveFailedError(
                'execute() cannot be called twice on same cursor')
            # otherwise we can't assume that column_{count,names} are immutable

        jit.promote(self.connection)
        jit.promote(self.statement)
        cache = self.connection.statement_cache
        self.statement = cache.get_or_make(sql)
        query = self.statement.query

        if args is not None:
            if len(args) != query.bind_parameter_count():
                raise PrimitiveFailedError('wrong # of arguments for query')
            for i, w_value in enumerate(args):
                self.bind_query_argument(space, w_value, query, i + 1)

        self._step()

        self.column_count = query.data_count()
        self.column_names = [rffi.charp2strn(query.column_name(i), 255)
                             for i in range(self.column_count)]

        return self
Example #5
0
def convert_from_regdata(space, buf, buflen, typ):
    if typ == rwinreg.REG_DWORD:
        if not buflen:
            return space.wrap(0)
        d = rffi.cast(rwin32.LPDWORD, buf)[0]
        return space.wrap(d)

    elif typ == rwinreg.REG_SZ or typ == rwinreg.REG_EXPAND_SZ:
        if not buflen:
            return space.wrap("")
        s = rffi.charp2strn(rffi.cast(rffi.CCHARP, buf), buflen)
        return space.wrap(s)

    elif typ == rwinreg.REG_MULTI_SZ:
        if not buflen:
            return space.newlist([])
        i = 0
        l = []
        while i < buflen and buf[i]:
            s = []
            while i < buflen and buf[i] != '\0':
                s.append(buf[i])
                i += 1
            if len(s) == 0:
                break
            s = ''.join(s)
            l.append(space.wrap(s))
            i += 1
        return space.newlist(l)

    else:  # REG_BINARY and all other types
        return space.wrap(rffi.charpsize2str(buf, buflen))
Example #6
0
 def string(self, cdataobj, maxlen):
     space = self.space
     if (isinstance(self.ctitem, ctypeprim.W_CTypePrimitive) and
             not isinstance(self.ctitem, ctypeprim.W_CTypePrimitiveBool)):
         with cdataobj as ptr:
             if not ptr:
                 raise oefmt(space.w_RuntimeError,
                             "cannot use string() on %R", cdataobj)
             #
             from pypy.module._cffi_backend import ctypearray
             length = maxlen
             if length < 0 and isinstance(self, ctypearray.W_CTypeArray):
                 length = cdataobj.get_array_length()
             #
             # pointer to a primitive type of size 1: builds and returns a str
             if self.ctitem.size == rffi.sizeof(lltype.Char):
                 if length < 0:
                     s = rffi.charp2str(ptr)
                 else:
                     s = rffi.charp2strn(ptr, length)
                 return space.newbytes(s)
             #
             # pointer to a wchar_t: builds and returns a unicode
             if self.is_unichar_ptr_or_array():
                 from pypy.module._cffi_backend import wchar_helper
                 if self.ctitem.size == 2:
                     length = wchar_helper.measure_length_16(ptr, length)
                 else:
                     length = wchar_helper.measure_length_32(ptr, length)
                 return self.ctitem.unpack_ptr(self, ptr, length)
     #
     return W_CType.string(self, cdataobj, maxlen)
Example #7
0
 def on_getattr(self, mem, name):
     if name == u"str" and self.ctype.size == 1:
         if self.length != 0:
             s = rffi.charp2strn(rffi.cast(rffi.CCHARP, mem.pointer), int(self.length))
         else:
             s = rffi.charp2str(rffi.cast(rffi.CCHARP, mem.pointer))
         return String(s.decode('utf-8'))
     raise Object.getattr(mem, name)
Example #8
0
 def on_getattr(self, mem, name):
     if name == u"str" and self.ctype.size == 1:
         if self.length != 0:
             s = rffi.charp2strn(rffi.cast(rffi.CCHARP, mem.pointer), int(self.length))
         else:
             s = rffi.charp2str(rffi.cast(rffi.CCHARP, mem.pointer))
         return String(s.decode('utf-8'))
     raise Object.getattr(mem, name)
Example #9
0
def strftime(space, format, w_tup=None):
    """strftime(format[, tuple]) -> string

    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used."""
    buf_value = _gettmarg(space, w_tup)

    # Checks added to make sure strftime() does not crash Python by
    # indexing blindly into some array for a textual representation
    # by some bad index (fixes bug #897625).
    # No check for year since handled in gettmarg().
    if rffi.getintfield(buf_value, 'c_tm_mon') < 0 or rffi.getintfield(buf_value, 'c_tm_mon') > 11:
        raise oefmt(space.w_ValueError, "month out of range")
    if rffi.getintfield(buf_value, 'c_tm_mday') < 1 or rffi.getintfield(buf_value, 'c_tm_mday') > 31:
        raise oefmt(space.w_ValueError, "day of month out of range")
    if rffi.getintfield(buf_value, 'c_tm_hour') < 0 or rffi.getintfield(buf_value, 'c_tm_hour') > 23:
        raise oefmt(space.w_ValueError, "hour out of range")
    if rffi.getintfield(buf_value, 'c_tm_min') < 0 or rffi.getintfield(buf_value, 'c_tm_min') > 59:
        raise oefmt(space.w_ValueError, "minute out of range")
    if rffi.getintfield(buf_value, 'c_tm_sec') < 0 or rffi.getintfield(buf_value, 'c_tm_sec') > 61:
        raise oefmt(space.w_ValueError, "seconds out of range")
    if rffi.getintfield(buf_value, 'c_tm_yday') < 0 or rffi.getintfield(buf_value, 'c_tm_yday') > 365:
        raise oefmt(space.w_ValueError, "day of year out of range")
    if rffi.getintfield(buf_value, 'c_tm_isdst') < -1 or rffi.getintfield(buf_value, 'c_tm_isdst') > 1:
        raise oefmt(space.w_ValueError, "daylight savings flag out of range")

    if _WIN:
        # check that the format string contains only valid directives
        length = len(format)
        i = 0
        while i < length:
            if format[i] == '%':
                i += 1
                if i < length and format[i] == '#':
                    # not documented by python
                    i += 1
                if i >= length or format[i] not in "aAbBcdHIjmMpSUwWxXyYzZ%":
                    raise oefmt(space.w_ValueError, "invalid format string")
            i += 1

    i = 1024
    while True:
        outbuf = lltype.malloc(rffi.CCHARP.TO, i, flavor='raw')
        try:
            buflen = c_strftime(outbuf, i, format, buf_value)
            if buflen > 0 or i >= 256 * len(format):
                # if the buffer is 256 times as long as the format,
                # it's probably not failing for lack of room!
                # More likely, the format yields an empty result,
                # e.g. an empty format, or %Z when the timezone
                # is unknown.
                result = rffi.charp2strn(outbuf, intmask(buflen))
                return space.wrap(result)
        finally:
            lltype.free(outbuf, flavor='raw')
        i += i
Example #10
0
def charp2string(space, address, maxlength=-1):
    if address == 0:
        return space.w_None
    charp_addr = rffi.cast(rffi.CCHARP, address)
    if maxlength == -1:
        s = rffi.charp2str(charp_addr)
    else:
        s = rffi.charp2strn(charp_addr, maxlength)
    return space.wrap(s)
Example #11
0
def charp2string(space, address, maxlength=-1):
    if address == 0:
        return space.w_None
    charp_addr = rffi.cast(rffi.CCHARP, address)
    if maxlength == -1:
        s = rffi.charp2str(charp_addr)
    else:
        s = rffi.charp2strn(charp_addr, maxlength)
    return space.newbytes(s)
Example #12
0
def gethostname():
    size = 1024
    buf = lltype.malloc(rffi.CCHARP.TO, size, flavor='raw')
    try:
        res = _c.gethostname(buf, size)
        if res < 0:
            raise last_error()
        return rffi.charp2strn(buf, size)
    finally:
        lltype.free(buf, flavor='raw')
Example #13
0
def gethostname():
    size = 1024
    buf = lltype.malloc(rffi.CCHARP.TO, size, flavor='raw')
    try:
        res = _c.gethostname(buf, size)
        if res < 0:
            raise last_error()
        return rffi.charp2strn(buf, size)
    finally:
        lltype.free(buf, flavor='raw')
Example #14
0
def _strftime(interp, is_gmt, format_string, timestamp):
    offset = lltype.nullptr(timelib.timelib_time_offset.TO)
    ta = lltype.malloc(timelib.tm, flavor='raw', zero=True)

    timelib_time = timelib.timelib_time_ctor()
    if is_gmt:
        timelib_timezone = lltype.nullptr(timelib.timelib_tzinfo.TO)
        timelib.timelib_unixtime2gmt(timelib_time, timestamp)
    else:
        timelib_timezone = interp.get_default_timezone(
            "getdate").timelib_timezone
        timelib_time.c_tz_info = timelib_timezone
        timelib_time.c_zone_type = timelib.TIMELIB_ZONETYPE_ID
        timelib.timelib_unixtime2local(timelib_time, timestamp)

    ta.c_tm_sec = rffi.cast(rffi.INT, timelib_time.c_s)
    ta.c_tm_min = rffi.cast(rffi.INT, timelib_time.c_i)
    ta.c_tm_hour = rffi.cast(rffi.INT, timelib_time.c_h)
    ta.c_tm_mday = rffi.cast(rffi.INT, timelib_time.c_d)
    ta.c_tm_mon = rffi.cast(rffi.INT, timelib_time.c_m - 1)
    ta.c_tm_year = rffi.cast(rffi.INT, timelib_time.c_y - 1900)
    ta.c_tm_wday = rffi.cast(
        rffi.INT,
        timelib.timelib_day_of_week(timelib_time.c_y, timelib_time.c_m,
                                    timelib_time.c_d))
    ta.c_tm_yday = rffi.cast(
        rffi.INT,
        timelib.timelib_day_of_year(timelib_time.c_y, timelib_time.c_m,
                                    timelib_time.c_d))

    if is_gmt:
        ta.c_tm_isdst = rffi.cast(rffi.INT, 0)
        ta.c_tm_gmtoff = rffi.cast(lltype.Signed, 0)
        ta.c_tm_zone = rffi.str2charp("GMT")
    else:
        offset = timelib.timelib_get_time_zone_info(timestamp,
                                                    timelib_timezone)
        ta.c_tm_isdst = rffi.cast(rffi.INT, offset.c_is_dst)
        ta.c_tm_gmtoff = rffi.cast(lltype.Signed, offset.c_offset)
        ta.c_tm_zone = offset.c_abbr

    # stolen from PyPy
    i = 1024
    while True:
        outbuf = lltype.malloc(rffi.CCHARP.TO, i, flavor='raw')
        try:
            buflen = timelib.c_strftime(outbuf, i, format_string, ta)
            if buflen > 0 or i >= 256 * len(format_string):
                return rffi.charp2strn(outbuf, intmask(buflen))
        finally:
            timelib.timelib_time_dtor(timelib_time)
            lltype.free(outbuf, flavor='raw')
            if offset:
                timelib.timelib_time_offset_dtor(offset)
        i += i
Example #15
0
def _strftime(interp, is_gmt, format_string, timestamp):
    offset = lltype.nullptr(timelib.timelib_time_offset.TO)
    ta = lltype.malloc(timelib.tm, flavor='raw', zero=True)

    timelib_time = timelib.timelib_time_ctor()
    if is_gmt:
        timelib_timezone = lltype.nullptr(timelib.timelib_tzinfo.TO)
        timelib.timelib_unixtime2gmt(timelib_time, timestamp)
    else:
        timelib_timezone = interp.get_default_timezone("getdate").timelib_timezone
        timelib_time.c_tz_info = timelib_timezone
        timelib_time.c_zone_type = timelib.TIMELIB_ZONETYPE_ID
        timelib.timelib_unixtime2local(timelib_time, timestamp)

    ta.c_tm_sec   = rffi.cast(rffi.INT, timelib_time.c_s)
    ta.c_tm_min   = rffi.cast(rffi.INT, timelib_time.c_i)
    ta.c_tm_hour  = rffi.cast(rffi.INT, timelib_time.c_h)
    ta.c_tm_mday  = rffi.cast(rffi.INT, timelib_time.c_d)
    ta.c_tm_mon   = rffi.cast(rffi.INT, timelib_time.c_m - 1)
    ta.c_tm_year  = rffi.cast(rffi.INT, timelib_time.c_y - 1900)
    ta.c_tm_wday  = rffi.cast(rffi.INT, timelib.timelib_day_of_week(
        timelib_time.c_y,
        timelib_time.c_m,
        timelib_time.c_d
    ))
    ta.c_tm_yday  = rffi.cast(rffi.INT, timelib.timelib_day_of_year(
        timelib_time.c_y,
        timelib_time.c_m,
        timelib_time.c_d
    ))

    if is_gmt:
        ta.c_tm_isdst = rffi.cast(rffi.INT, 0)
        ta.c_tm_gmtoff = rffi.cast(lltype.Signed, 0)
        ta.c_tm_zone = rffi.str2charp("GMT")
    else:
        offset = timelib.timelib_get_time_zone_info(timestamp, timelib_timezone)
        ta.c_tm_isdst = rffi.cast(rffi.INT, offset.c_is_dst)
        ta.c_tm_gmtoff = rffi.cast(lltype.Signed, offset.c_offset)
        ta.c_tm_zone = offset.c_abbr

    # stolen from PyPy
    i = 1024
    while True:
        outbuf = lltype.malloc(rffi.CCHARP.TO, i, flavor='raw')
        try:
            buflen = timelib.c_strftime(outbuf, i, format_string, ta)
            if buflen > 0 or i >= 256 * len(format_string):
                return rffi.charp2strn(outbuf, intmask(buflen))
        finally:
            timelib.timelib_time_dtor(timelib_time)
            lltype.free(outbuf, flavor='raw')
            if offset:
                timelib.timelib_time_offset_dtor(offset)
        i += i
Example #16
0
 def get_ifname(self, fd):
     ifname = ""
     a = self.lock(_c.sockaddr_ll)
     ifindex = rffi.getintfield(a, "c_sll_ifindex")
     if ifindex:
         p = lltype.malloc(_c.ifreq, flavor="raw")
         rffi.setintfield(p, "c_ifr_ifindex", ifindex)
         if _c.ioctl(fd, _c.SIOCGIFNAME, p) == 0:
             ifname = rffi.charp2strn(rffi.cast(rffi.CCHARP, p.c_ifr_name), PacketAddress.ifr_name_size)
         lltype.free(p, flavor="raw")
     self.unlock()
     return ifname
Example #17
0
    def set_error(self, space, code):
        err = rffi.charp2strn(XML_ErrorString(code), 200)
        lineno = XML_GetCurrentLineNumber(self.itself)
        colno = XML_GetCurrentColumnNumber(self.itself)
        msg = "%s: line %d, column %d" % (err, lineno, colno)
        w_errorcls = space.fromcache(Cache).w_error
        w_error = space.call_function(w_errorcls, space.wrap(msg))
        space.setattr(w_error, space.wrap("code"), space.wrap(code))
        space.setattr(w_error, space.wrap("offset"), space.wrap(colno))
        space.setattr(w_error, space.wrap("lineno"), space.wrap(lineno))

        self.w_error = w_error
        return OperationError(w_errorcls, w_error)
Example #18
0
    def set_error(self, space, code):
        err = rffi.charp2strn(XML_ErrorString(code), 200)
        lineno = XML_GetCurrentLineNumber(self.itself)
        colno = XML_GetCurrentColumnNumber(self.itself)
        msg = "%s: line %d, column %d" % (err, lineno, colno)
        w_errorcls = space.fromcache(Cache).w_error
        w_error = space.call_function(w_errorcls, space.newtext(msg))
        space.setattr(w_error, space.newtext("code"), space.newint(code))
        space.setattr(w_error, space.newtext("offset"), space.newint(colno))
        space.setattr(w_error, space.newtext("lineno"), space.newint(lineno))

        self.w_error = w_error
        return OperationError(w_errorcls, w_error)
Example #19
0
def strftime(format, seconds):
    i = 1024
    while i < (256 * len(format)):
        # if the buffer is 256 times as long as the format, we're not failing
        # for lack of room (see pypy)
        with lltype.scoped_alloc(rffi.TIME_TP.TO, 1) as t_ref:
            t_ref[0] = int(seconds)
            p = c_gmtime(t_ref)
            with lltype.scoped_alloc(rffi.CCHARP.TO, i) as outbuf:
                buflen = c_strftime(outbuf, i, format, p)
                if buflen > 0:
                    return rffi.charp2strn(outbuf, intmask(buflen))
        i += i
    return ""
Example #20
0
def strftime(format, seconds):
    i = 1024
    while i < (256 * len(format)):
        # if the buffer is 256 times as long as the format, we're not failing
        # for lack of room (see pypy)
        with lltype.scoped_alloc(rffi.TIME_TP.TO, 1) as t_ref:
            t_ref[0] = int(seconds)
            p = c_gmtime(t_ref)
            with lltype.scoped_alloc(rffi.CCHARP.TO, i) as outbuf:
                buflen = c_strftime(outbuf, i, format, p)
                if buflen > 0:
                    return rffi.charp2strn(outbuf, intmask(buflen))
        i += i
    return ""
def strftime(space, format, w_tup=None):
    """strftime(format[, tuple]) -> string

    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used."""
    buf_value = _gettmarg(space, w_tup)
    _checktm(space, buf_value)

    # Normalize tm_isdst just in case someone foolishly implements %Z
    # based on the assumption that tm_isdst falls within the range of
    # [-1, 1]
    if rffi.getintfield(buf_value, 'c_tm_isdst') < -1:
        rffi.setintfield(buf_value, 'c_tm_isdst', -1)
    elif rffi.getintfield(buf_value, 'c_tm_isdst') > 1:
        rffi.setintfield(buf_value, 'c_tm_isdst', 1)
    rffi.setintfield(buf_value, "c_tm_year",
                     rffi.getintfield(buf_value, "c_tm_year") - 1900)

    if _WIN:
        # check that the format string contains only valid directives
        length = len(format)
        i = 0
        while i < length:
            if format[i] == '%':
                i += 1
                if i < length and format[i] == '#':
                    # not documented by python
                    i += 1
                if i >= length or format[i] not in "aAbBcdHIjmMpSUwWxXyYzZ%":
                    raise oefmt(space.w_ValueError, "invalid format string")
            i += 1

    i = 1024
    while True:
        outbuf = lltype.malloc(rffi.CCHARP.TO, i, flavor='raw')
        try:
            buflen = c_strftime(outbuf, i, format, buf_value)
            if buflen > 0 or i >= 256 * len(format):
                # if the buffer is 256 times as long as the format,
                # it's probably not failing for lack of room!
                # More likely, the format yields an empty result,
                # e.g. an empty format, or %Z when the timezone
                # is unknown.
                result = rffi.charp2strn(outbuf, intmask(buflen))
                return space.newtext(result)
        finally:
            lltype.free(outbuf, flavor='raw')
        i += i
Example #22
0
def strftime(space, format, w_tup=None):
    """strftime(format[, tuple]) -> string

    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used."""
    buf_value = _gettmarg(space, w_tup)
    _checktm(space, buf_value)

    # Normalize tm_isdst just in case someone foolishly implements %Z
    # based on the assumption that tm_isdst falls within the range of
    # [-1, 1]
    if rffi.getintfield(buf_value, 'c_tm_isdst') < -1:
        rffi.setintfield(buf_value, 'c_tm_isdst', -1)
    elif rffi.getintfield(buf_value, 'c_tm_isdst') > 1:
        rffi.setintfield(buf_value, 'c_tm_isdst', 1)

    if _WIN:
        # check that the format string contains only valid directives
        length = len(format)
        i = 0
        while i < length:
            if format[i] == '%':
                i += 1
                if i < length and format[i] == '#':
                    # not documented by python
                    i += 1
                if i >= length or format[i] not in "aAbBcdHIjmMpSUwWxXyYzZ%":
                    raise OperationError(space.w_ValueError,
                                         space.wrap("invalid format string"))
            i += 1

    i = 1024
    while True:
        outbuf = lltype.malloc(rffi.CCHARP.TO, i, flavor='raw')
        try:
            buflen = c_strftime(outbuf, i, format, buf_value)
            if buflen > 0 or i >= 256 * len(format):
                # if the buffer is 256 times as long as the format,
                # it's probably not failing for lack of room!
                # More likely, the format yields an empty result,
                # e.g. an empty format, or %Z when the timezone
                # is unknown.
                result = rffi.charp2strn(outbuf, intmask(buflen))
                return space.wrap(result)
        finally:
            lltype.free(outbuf, flavor='raw')
        i += i
Example #23
0
def convert_from_regdata(space, buf, buflen, typ):
    if typ == rwinreg.REG_DWORD:
        if not buflen:
            return space.newint(0)
        d = rffi.cast(rwin32.LPDWORD, buf)[0]
        return space.newint(d)

    elif typ == rwinreg.REG_SZ or typ == rwinreg.REG_EXPAND_SZ:
        if not buflen:
            s = ""
        else:
            # may or may not have a trailing NULL in the buffer.
            buf = rffi.cast(rffi.CCHARP, buf)
            if buf[buflen - 1] == '\x00':
                buflen -= 1
            s = rffi.charp2strn(buf, buflen)
        w_s = space.newbytes(s)
        return space.call_method(w_s, 'decode', space.newtext('mbcs'))

    elif typ == rwinreg.REG_MULTI_SZ:
        if not buflen:
            return space.newlist([])
        i = 0
        l = []
        while i < buflen and buf[i]:
            s = []
            while i < buflen and buf[i] != '\0':
                s.append(buf[i])
                i += 1
            if len(s) == 0:
                break
            s = ''.join(s)
            l.append(space.newtext(s))
            i += 1
        return space.newlist(l)

    else:  # REG_BINARY and all other types
        if buflen == 0:
            return space.w_None
        else:
            return space.newbytes(rffi.charpsize2str(buf, buflen))
Example #24
0
def QueryValue(space, w_hkey, w_subkey):
    """string = QueryValue(key, sub_key) - retrieves the unnamed value for a key.

key is an already open key, or any one of the predefined HKEY_* constants.
sub_key is a string that holds the name of the subkey with which the value
 is associated.  If this parameter is None or empty, the function retrieves
 the value set by the SetValue() method for the key identified by key.

Values in the registry have name, type, and data components. This method
retrieves the data for a key's first value that has a NULL name.
But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!"""
    hkey = hkey_w(w_hkey, space)
    if space.is_w(w_subkey, space.w_None):
        subkey = None
    else:
        subkey = space.text_w(w_subkey)
    with lltype.scoped_alloc(rwin32.PLONG.TO, 1) as bufsize_p:
        ret = rwinreg.RegQueryValueA(hkey, subkey, None, bufsize_p)
        bufSize = intmask(bufsize_p[0])
        if ret == rwinreg.ERROR_MORE_DATA:
            bufSize = 256
        elif ret != 0:
            raiseWindowsError(space, ret, 'RegQueryValue')

        while True:
            with lltype.scoped_alloc(rffi.CCHARP.TO, bufSize) as buf:
                ret = rwinreg.RegQueryValueA(hkey, subkey, buf, bufsize_p)
                if ret == rwinreg.ERROR_MORE_DATA:
                    # Resize and retry
                    bufSize *= 2
                    bufsize_p[0] = rffi.cast(rwin32.LONG, bufSize)
                    continue

                if ret != 0:
                    raiseWindowsError(space, ret, 'RegQueryValue')
                length = intmask(bufsize_p[0])
                if length == 0:
                    return space.w_None
                return space.newtext(rffi.charp2strn(buf, length - 1))
Example #25
0
def convert_from_regdata(space, buf, buflen, typ):
    if typ == rwinreg.REG_DWORD:
        if not buflen:
            return space.wrap(0)
        d = rffi.cast(rwin32.LPDWORD, buf)[0]
        return space.wrap(d)

    elif typ == rwinreg.REG_SZ or typ == rwinreg.REG_EXPAND_SZ:
        if not buflen:
            s = ""
        else:
            # may or may not have a trailing NULL in the buffer.
            buf = rffi.cast(rffi.CCHARP, buf)
            if buf[buflen - 1] == '\x00':
                buflen -= 1
            s = rffi.charp2strn(buf, buflen)
        w_s = space.wrap(s)
        return space.call_method(w_s, 'decode', space.wrap('mbcs'))

    elif typ == rwinreg.REG_MULTI_SZ:
        if not buflen:
            return space.newlist([])
        i = 0
        l = []
        while i < buflen and buf[i]:
            s = []
            while i < buflen and buf[i] != '\0':
                s.append(buf[i])
                i += 1
            if len(s) == 0:
                break
            s = ''.join(s)
            l.append(space.wrap(s))
            i += 1
        return space.newlist(l)

    else: # REG_BINARY and all other types
        return space.newbytes(rffi.charpsize2str(buf, buflen))
Example #26
0
def QueryValue(space, w_hkey, w_subkey):
    """string = QueryValue(key, sub_key) - retrieves the unnamed value for a key.

key is an already open key, or any one of the predefined HKEY_* constants.
sub_key is a string that holds the name of the subkey with which the value
 is associated.  If this parameter is None or empty, the function retrieves
 the value set by the SetValue() method for the key identified by key.

Values in the registry have name, type, and data components. This method
retrieves the data for a key's first value that has a NULL name.
But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!"""
    hkey = hkey_w(w_hkey, space)
    if space.is_w(w_subkey, space.w_None):
        subkey = None
    else:
        subkey = space.str_w(w_subkey)
    with lltype.scoped_alloc(rwin32.PLONG.TO, 1) as bufsize_p:
        ret = rwinreg.RegQueryValue(hkey, subkey, None, bufsize_p)
        bufSize = intmask(bufsize_p[0])
        if ret == rwinreg.ERROR_MORE_DATA:
            bufSize = 256
        elif ret != 0:
            raiseWindowsError(space, ret, 'RegQueryValue')

        while True:
            with lltype.scoped_alloc(rffi.CCHARP.TO, bufSize) as buf:
                ret = rwinreg.RegQueryValue(hkey, subkey, buf, bufsize_p)
                if ret == rwinreg.ERROR_MORE_DATA:
                    # Resize and retry
                    bufSize *= 2
                    bufsize_p[0] = bufSize
                    continue

                if ret != 0:
                    raiseWindowsError(space, ret, 'RegQueryValue')
                length = intmask(bufsize_p[0] - 1)
                return space.wrap(rffi.charp2strn(buf, length))
Example #27
0
 def w_convert_charp_n(self, space, data, length):
     ll_length = rffi.cast(lltype.Signed, length)
     if data:
         return self.w_convert(space, rffi.charp2strn(data, ll_length))
     else:
         return space.w_None
Example #28
0
def strftime(space, format, w_tup=None):
    """strftime(format[, tuple]) -> string

    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used."""
    buf_value = _gettmarg(space, w_tup)

    # Checks added to make sure strftime() does not crash Python by
    # indexing blindly into some array for a textual representation
    # by some bad index (fixes bug #897625).
    # No check for year since handled in gettmarg().
    if rffi.getintfield(buf_value, 'c_tm_mon') < 0 or rffi.getintfield(
            buf_value, 'c_tm_mon') > 11:
        raise oefmt(space.w_ValueError, "month out of range")
    if rffi.getintfield(buf_value, 'c_tm_mday') < 1 or rffi.getintfield(
            buf_value, 'c_tm_mday') > 31:
        raise oefmt(space.w_ValueError, "day of month out of range")
    if rffi.getintfield(buf_value, 'c_tm_hour') < 0 or rffi.getintfield(
            buf_value, 'c_tm_hour') > 23:
        raise oefmt(space.w_ValueError, "hour out of range")
    if rffi.getintfield(buf_value, 'c_tm_min') < 0 or rffi.getintfield(
            buf_value, 'c_tm_min') > 59:
        raise oefmt(space.w_ValueError, "minute out of range")
    if rffi.getintfield(buf_value, 'c_tm_sec') < 0 or rffi.getintfield(
            buf_value, 'c_tm_sec') > 61:
        raise oefmt(space.w_ValueError, "seconds out of range")
    if rffi.getintfield(buf_value, 'c_tm_yday') < 0 or rffi.getintfield(
            buf_value, 'c_tm_yday') > 365:
        raise oefmt(space.w_ValueError, "day of year out of range")
    if rffi.getintfield(buf_value, 'c_tm_isdst') < -1 or rffi.getintfield(
            buf_value, 'c_tm_isdst') > 1:
        raise oefmt(space.w_ValueError, "daylight savings flag out of range")

    if _WIN:
        # check that the format string contains only valid directives
        length = len(format)
        i = 0
        while i < length:
            if format[i] == '%':
                i += 1
                if i < length and format[i] == '#':
                    # not documented by python
                    i += 1
                if i >= length or format[i] not in "aAbBcdHIjmMpSUwWxXyYzZ%":
                    raise oefmt(space.w_ValueError, "invalid format string")
            i += 1

    i = 1024
    while True:
        outbuf = lltype.malloc(rffi.CCHARP.TO, i, flavor='raw')
        try:
            buflen = c_strftime(outbuf, i, format, buf_value)
            if buflen > 0 or i >= 256 * len(format):
                # if the buffer is 256 times as long as the format,
                # it's probably not failing for lack of room!
                # More likely, the format yields an empty result,
                # e.g. an empty format, or %Z when the timezone
                # is unknown.
                result = rffi.charp2strn(outbuf, intmask(buflen))
                return space.newtext(result)
        finally:
            lltype.free(outbuf, flavor='raw')
        i += i
Example #29
0
 def w_convert_charp_n(self, space, data, length):
     ll_length = rffi.cast(lltype.Signed, length)
     if data:
         return self.w_convert(space, rffi.charp2strn(data, ll_length))
     else:
         return space.w_None
Example #30
0
def tokenize(regex_list, input_bytes, input_len):
    input_string = rffi.charp2strn(input_bytes, input_len)
    return run_several(unpack_regex_list(regex_list), input_string)