Python ctypes.get_errno() Examples

The following are 30 code examples of ctypes.get_errno(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ctypes , or try the search function .
Example #1
Source File: filesystems.py    From core with GNU General Public License v3.0 6 votes vote down vote up
def umount(self):
        """Unmount disk."""
        if not self.mountpoint:
            return
        signals.emit("filesystems", "pre_umount", self)
        loops = losetup.get_loop_devices()
        for l in loops:
            if loops[l].is_used() and loops[l].get_filename() == self.path:
                dev = loops[l]
                break
        s = libc.umount2(ctypes.c_char_p(b(self.mountpoint)), 0)
        if s == -1:
            excmsg = "Failed to unmount {0}: {1}"
            raise errors.OperationFailedError(
                excmsg.format(self.id, os.strerror(ctypes.get_errno())))
        if self.crypt:
            crypto.luks_close(self.id)
        if dev:
            dev.unmount()
        signals.emit("filesystems", "post_umount", self)
        self.mountpoint = None 
Example #2
Source File: semlock.py    From loky with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _sem_open(name, value=None):
    """ Construct or retrieve a semaphore with the given name

    If value is None, try to retrieve an existing named semaphore.
    Else create a new semaphore with the given value
    """
    if value is None:
        handle = pthread.sem_open(ctypes.c_char_p(name), 0)
    else:
        handle = pthread.sem_open(ctypes.c_char_p(name), SEM_OFLAG, SEM_PERM,
                                  ctypes.c_int(value))

    if handle == SEM_FAILURE:
        e = ctypes.get_errno()
        if e == errno.EEXIST:
            raise FileExistsError("a semaphore named %s already exists" % name)
        elif e == errno.ENOENT:
            raise FileNotFoundError('cannot find semaphore named %s' % name)
        elif e == errno.ENOSYS:
            raise NotImplementedError('No semaphore implementation on this '
                                      'system')
        else:
            raiseFromErrno()

    return handle 
Example #3
Source File: semlock.py    From loky with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def acquire(self, block=True, timeout=None):
        if self.kind == RECURSIVE_MUTEX and self._is_mine():
            self.count += 1
            return True

        if block and timeout is None:
            res = pthread.sem_wait(self.handle)
        elif not block or timeout <= 0:
            res = pthread.sem_trywait(self.handle)
        else:
            res = _sem_timedwait(self.handle, timeout)
        if res < 0:
            e = ctypes.get_errno()
            if e == errno.EINTR:
                return None
            elif e in [errno.EAGAIN, errno.ETIMEDOUT]:
                return False
            raiseFromErrno()
        self.count += 1
        self.ident = get_ident()
        return True 
Example #4
Source File: libc.py    From benchexec with Apache License 2.0 6 votes vote down vote up
def _check_errno(result, func, arguments):
    assert func.restype in [c_int, c_void_p]
    if (func.restype == c_int and result == -1) or (
        func.restype == c_void_p and c_void_p(result).value == c_void_p(-1).value
    ):
        errno = _ctypes.get_errno()
        try:
            func_name = func.__name__
        except AttributeError:
            func_name = "__unknown__"
        msg = (
            func_name
            + "("
            + ", ".join(map(str, arguments))
            + ") failed: "
            + _os.strerror(errno)
        )
        raise OSError(errno, msg)
    return result


# off_t is a signed integer type required for mmap.
# In my tests it is equal to long on both 32bit and 64bit x86 Linux. 
Example #5
Source File: rmTimeUtils.py    From rainmachine-developer-resources with GNU General Public License v3.0 6 votes vote down vote up
def monotonicTime(self, asSeconds = True):
        t = timespec()
        if self.clock_gettime(rmMonotonicTime.CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
            errno_ = ctypes.get_errno()
            if self.fallback:
                log.info("Monotonic Clock Error ! Reverting to time.time() fallback")
                return self.monotonicFallback(asSeconds)
            else:
                raise OSError(errno_, os.strerror(errno_))

        if asSeconds:
            return t.tv_sec

        return t.tv_sec + t.tv_nsec * 1e-9


#-----------------------------------------------------------------------------------------------
#
#
# 
Example #6
Source File: inotify_file_watcher.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def _remove_watch_for_path(self, path):
    logging.debug('_remove_watch_for_path(%r)', path)
    wd = self._directory_to_watch_descriptor[path]

    if InotifyFileWatcher._libc.inotify_rm_watch(self._inotify_fd, wd) < 0:
      # If the directory is deleted then the watch will removed automatically
      # and inotify_rm_watch will fail. Just log the error.
      logging.debug('inotify_rm_watch failed for %r: %d [%r]',
                    path,
                    ctypes.get_errno(),
                    errno.errorcode[ctypes.get_errno()])

    parent_path = os.path.dirname(path)
    if parent_path in self._directory_to_subdirs:
      self._directory_to_subdirs[parent_path].remove(path)

    # _directory_to_subdirs must be copied because it is mutated in the
    # recursive call.
    for subdir in frozenset(self._directory_to_subdirs[path]):
      self._remove_watch_for_path(subdir)

    del self._watch_to_directory[wd]
    del self._directory_to_watch_descriptor[path]
    del self._directory_to_subdirs[path] 
Example #7
Source File: freebsd.py    From beacontools with MIT License 6 votes vote down vote up
def open_dev(bt_device_id):
    """Open hci device socket."""
    # pylint: disable=no-member
    sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI)

    # Unlike Linux, FreeBSD has separate numbering depending on hardware
    # (ubt - USB bluetooth - is the most common, so convert numbers to that)
    if not isinstance(bt_device_id, str):
        bt_device_id = 'ubt{}hci'.format(bt_device_id)

    # Python's BTPROTO_HCI address parsing is busted: https://bugs.python.org/issue41130
    adr = SockaddrHci(ctypes.sizeof(SockaddrHci), socket.AF_BLUETOOTH, bt_device_id.ljust(32, '\0').encode('utf-8'))
    if libc.bind(sock.fileno(), ctypes.pointer(adr), ctypes.sizeof(SockaddrHci)) != 0:
        raise ConnectionError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
    if libc.connect(sock.fileno(), ctypes.pointer(adr), ctypes.sizeof(SockaddrHci)) != 0:
        raise ConnectionError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
    # pylint: enable=no-member

    fltr = HciRawFilter(0, NG_HCI_EVENT_MASK_LE)
    if libc.setsockopt(sock.fileno(),
                       SOL_HCI_RAW, SOL_HCI_RAW_FILTER,
                       ctypes.pointer(fltr), ctypes.sizeof(HciRawFilter)) != 0:
        raise ConnectionError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))

    return sock 
Example #8
Source File: LinProcess.py    From memorpy with GNU General Public License v3.0 6 votes vote down vote up
def _ptrace(self, attach):
        op = ctypes.c_int(PTRACE_ATTACH if attach else PTRACE_DETACH)
        c_pid = c_pid_t(self.pid)
        null = ctypes.c_void_p()

        if not attach:
            os.kill(self.pid, signal.SIGSTOP)
            os.waitpid(self.pid, 0)

        err = c_ptrace(op, c_pid, null, null)

        if not attach:
            os.kill(self.pid, signal.SIGCONT)

        if err != 0:
            raise OSError("%s: %s"%(
                'PTRACE_ATTACH' if attach else 'PTRACE_DETACH',
                errno.errorcode.get(ctypes.get_errno(), 'UNKNOWN')
            )) 
Example #9
Source File: semlock.py    From loky with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _is_zero(self):
        if sys.platform == 'darwin':
            # Handle broken get_value for mac ==> only Lock will work
            # as sem_get_value do not work properly
            if pthread.sem_trywait(self.handle) < 0:
                e = ctypes.get_errno()
                if e == errno.EAGAIN:
                    return True
                raise OSError(e, errno.errorcode[e])
            else:
                if pthread.sem_post(self.handle) < 0:
                    raiseFromErrno()
                return False
        else:
            value = ctypes.pointer(ctypes.c_int(-1))
            if pthread.sem_getvalue(self.handle, value) < 0:
                raiseFromErrno()
            return value.contents.value == 0 
Example #10
Source File: perf.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
def _create_file_from_fd(pfd):
    """Validates file description and creates a file-like object"""
    # -1 is returned on error: http://man7.org/linux/man-pages/man2/open.2.html#RETURN_VALUE
    if pfd == -1:
        INVALID_ARG_ERRNO = 22
        errno = ctypes.get_errno()
        if errno == INVALID_ARG_ERRNO:
            raise UnableToOpenPerfEvents('Invalid perf event file descriptor: {}, {}. '
                                         'For cgroup based perf counters it may indicate there is '
                                         'no enough hardware counters for measure all metrics!'
                                         'If traceback shows problem in perf_uncore '
                                         'it could be problem with PERF_FORMAT_GROUP in'
                                         'perf_event_attr structure for perf_event_open syscall.'
                                         'Older kernel cannot handle with extended format group.'
                                         'Kernel cannot be 3.10.0-862.el7.x86_64 or lower.'
                                         ''.format(errno, os.strerror(errno)))
        else:
            raise UnableToOpenPerfEvents('Invalid perf event file descriptor: {}, {}.'
                                         .format(errno, os.strerror(errno)))
    return os.fdopen(pfd, 'rb') 
Example #11
Source File: cgroups_allocations.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
def _migrate_page_call(pid, max_node, old_nodes, new_node) -> int:
    """Wrapper on migrate_pages function using libc syscall"""

    pid = int(pid)
    max = ctypes.c_ulong(max_node + 1)
    old = ctypes.pointer(ctypes.c_ulong(old_nodes))
    new = ctypes.pointer(ctypes.c_ulong(new_node))

    # Example memory_migrate(256, pid, 5, 13 -> b'1101', 2 -> b'0010')
    result = LIBC.syscall(NR_MIGRATE_PAGES, pid, max, old, new)

    if result == -1:
        errno = ctypes.get_errno()
        raise UnableToMigratePages('Unable to migrate pages: {}, {}.'
                                   .format(errno, os.strerror(errno)))
    log.log(TRACE, 'Number of not moved pages (return from migrate_pages syscall): %d', result)
    return result 
Example #12
Source File: uid.py    From mock with GNU General Public License v2.0 5 votes vote down vote up
def getresgid():
    rgid = ctypes.c_long()
    egid = ctypes.c_long()
    sgid = ctypes.c_long()
    res = _libc.getresgid(ctypes.byref(rgid), ctypes.byref(egid), ctypes.byref(sgid))
    if res:
        raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
    return (rgid.value, egid.value, sgid.value) 
Example #13
Source File: uid.py    From mock with GNU General Public License v2.0 5 votes vote down vote up
def getresuid():
    ruid = ctypes.c_long()
    euid = ctypes.c_long()
    suid = ctypes.c_long()
    res = _libc.getresuid(ctypes.byref(ruid), ctypes.byref(euid), ctypes.byref(suid))
    if res:
        raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
    return (ruid.value, euid.value, suid.value) 
Example #14
Source File: _sendfile.py    From Flask-P2P with MIT License 5 votes vote down vote up
def sendfile(fdout, fdin, offset, nbytes):
    if sys.platform == 'darwin':
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
                              ctypes.POINTER(ctypes.c_uint64), ctypes.c_voidp,
                              ctypes.c_int]
        _nbytes = ctypes.c_uint64(nbytes)
        result = _sendfile(fdin, fdout, offset, _nbytes, None, 0)

        if result == -1:
            e = ctypes.get_errno()
            if e == errno.EAGAIN and _nbytes.value is not None:
                return _nbytes.value
            raise OSError(e, os.strerror(e))
        return _nbytes.value
    elif sys.platform in ('freebsd', 'dragonfly',):
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
                              ctypes.c_uint64, ctypes.c_voidp,
                              ctypes.POINTER(ctypes.c_uint64), ctypes.c_int]
        _sbytes = ctypes.c_uint64()
        result = _sendfile(fdin, fdout, offset, nbytes, None, _sbytes, 0)
        if result == -1:
            e = ctypes.get_errno()
            if e == errno.EAGAIN and _sbytes.value is not None:
                return _sbytes.value
            raise OSError(e, os.strerror(e))
        return _sbytes.value

    else:
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int,
                ctypes.POINTER(ctypes.c_uint64), ctypes.c_size_t]

        _offset = ctypes.c_uint64(offset)
        sent = _sendfile(fdout, fdin, _offset, nbytes)
        if sent == -1:
            e = ctypes.get_errno()
            raise OSError(e, os.strerror(e))
        return sent 
Example #15
Source File: clip.py    From pappy-proxy with MIT License 5 votes vote down vote up
def __call__(self, *args):
        ret = self.f(*args)
        if not ret and get_errno():
            raise PyperclipWindowsException("Error calling " + self.f.__name__)
        return ret 
Example #16
Source File: usb1.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_errno():
        raise NotImplementedError(
            'Your python version does not support errno/last_error'
        ) 
Example #17
Source File: inotify_c.py    From script.service.kodi.callbacks with GNU General Public License v3.0 5 votes vote down vote up
def _raise_error():
        """
        Raises errors for inotify failures.
        """
        err = ctypes.get_errno()
        if err == errno.ENOSPC:
            raise OSError("inotify watch limit reached")
        elif err == errno.EMFILE:
            raise OSError("inotify instance limit reached")
        else:
            raise OSError(os.strerror(err)) 
Example #18
Source File: monotonic.py    From owasp-pysec with Apache License 2.0 5 votes vote down vote up
def monotonic():
    t = timespec()
    if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(t)) != 0:
        errno_ = ctypes.get_errno()
        raise OSError(errno_, os.strerror(errno_))
    return t.tv_sec * 1000000000 + t.tv_nsec 
Example #19
Source File: windows.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, *args):
        ret = self.f(*args)
        if not ret and get_errno():
            raise PyperclipWindowsException("Error calling " + self.f.__name__)
        return ret 
Example #20
Source File: calls.py    From PyInotify with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, message, *args, **kwargs):
        self.errno = ctypes.get_errno()
        message += " ERRNO=(%d)" % (self.errno,)

        super(InotifyError, self).__init__(message, *args, **kwargs) 
Example #21
Source File: uid.py    From mock with GNU General Public License v2.0 5 votes vote down vote up
def setresuid(ruid=-1, euid=-1, suid=-1):
    ruid = ctypes.c_long(ruid)
    euid = ctypes.c_long(euid)
    suid = ctypes.c_long(suid)
    res = _libc.setresuid(ruid, euid, suid)
    if res:
        raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno())) 
Example #22
Source File: Pyperclip.py    From MIA-Japanese-Add-on with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, *args):
        ret = self.f(*args)
        if not ret and get_errno():
            raise PyperclipWindowsException("Error calling " + self.f.__name__)
        return ret 
Example #23
Source File: util.py    From mock with GNU General Public License v2.0 5 votes vote down vote up
def condPersonality(per=None):
    if per is None or per in ('noarch',):
        return
    if personality_defs.get(per, None) is None:
        return
    res = _libc.personality(personality_defs[per])
    if res == -1:
        raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno())) 
Example #24
Source File: util.py    From mock with GNU General Public License v2.0 5 votes vote down vote up
def unshare(flags):
    getLog().debug("Unsharing. Flags: %s", flags)
    try:
        res = _libc.unshare(flags)
        if res:
            raise exception.UnshareFailed(os.strerror(ctypes.get_errno()))
    except AttributeError:
        pass 
Example #25
Source File: _ffi.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def errno():
        return ctypes.get_errno() 
Example #26
Source File: backend_ctypes.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def get_errno(self):
        return ctypes.get_errno() 
Example #27
Source File: time_utils.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def clock_gettime(clk_id):
    tp = timespec()
    if _clock_gettime(clk_id, ctypes.byref(tp)) < 0:
        err = ctypes.get_errno()
        msg = errno.errorcode[err]
        if err == errno.EINVAL:
            msg += (
                " The clk_id specified is not supported on this system" " clk_id=%r"
            ) % (clk_id,)
        raise OSError(err, msg)
    return tp.tv_sec + tp.tv_nsec * 1e-9 
Example #28
Source File: monotonic.py    From PySyncObj with MIT License 5 votes vote down vote up
def monotonic():
                """Monotonic clock, cannot go backward."""
                ts = timespec()
                if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(ts)):
                    errno = ctypes.get_errno()
                    raise OSError(errno, os.strerror(errno))
                return ts.tv_sec + ts.tv_nsec / 1.0e9

        # Perform a sanity-check. 
Example #29
Source File: backend_ctypes.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def get_errno(self):
        return ctypes.get_errno() 
Example #30
Source File: backend_ctypes.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def get_errno(self):
        return ctypes.get_errno()