diff --git a/qiling/os/freebsd/syscall.py b/qiling/os/freebsd/syscall.py index fc03d524a..37eef7bc8 100644 --- a/qiling/os/freebsd/syscall.py +++ b/qiling/os/freebsd/syscall.py @@ -10,7 +10,7 @@ from qiling import Qiling from qiling.arch.x86_const import * from qiling.os.freebsd.const import * -from qiling.os.posix.const import ENOENT +from qiling.os.posix.const_mapping import get_errno_class from qiling.os.posix.syscall.unistd import ql_syscall_getcwd from qiling.os.posix.syscall.stat import ql_syscall_newfstatat @@ -89,7 +89,7 @@ def ql_syscall___sysctl(ql: Qiling, name: int, namelen: int, old: int, oldlenp: ql.mem.write_ptr(oldlenp, out_len, 4, signed=True) - return -ENOENT + return -get_errno_class(ql.arch.type, ql.os.type).ENOENT.value if vecs[0] == CTL_KERN: if vecs[1] == KERN_OSRELDATE: diff --git a/qiling/os/linux/futex.py b/qiling/os/linux/futex.py index ef78db4f3..ab8382158 100644 --- a/qiling/os/linux/futex.py +++ b/qiling/os/linux/futex.py @@ -9,6 +9,8 @@ from gevent.event import Event from queue import Queue +from qiling.os.posix.const_mapping import get_errno_class + class QlLinuxFutexManagement: FUTEX_BITSET_MATCH_ANY = 0xffffffff @@ -21,14 +23,13 @@ def wait_list(self): return self._wait_list def futex_wait(self, ql, uaddr, t, val, bitset=FUTEX_BITSET_MATCH_ANY): - EAGAIN = 11 def _sched_wait_event(cur_thread): ql.log.debug(f"Wait for notifications.") event.wait() uaddr_value = ql.unpack32(ql.mem.read(uaddr, 4)) if uaddr_value != val: ql.log.debug(f"uaddr: {hex(uaddr_value)} != {hex(val)}") - return -EAGAIN + return -get_errno_class(ql.arch.type, ql.os.type).EAGAIN.value ql.emu_stop() if uaddr not in self.wait_list.keys(): self.wait_list[uaddr] = Queue() diff --git a/qiling/os/posix/const.py b/qiling/os/posix/const.py index 535cf6d79..2ca291fe3 100644 --- a/qiling/os/posix/const.py +++ b/qiling/os/posix/const.py @@ -762,270 +762,641 @@ class qnx_mmap_prot_flags(QlPrettyFlag): AT_FDCWD = -100 AT_EMPTY_PATH = 0x1000 -# error code -EPERM = 1 -ENOENT = 2 -ESRCH = 3 -EINTR = 4 -EIO = 5 -ENXIO = 6 -E2BIG = 7 -ENOEXEC = 8 -EBADF = 9 -ECHILD = 10 -EAGAIN = 11 -EWOULDBLOCK = 11 -ENOMEM = 12 -EACCES = 13 -EFAULT = 14 -ENOTBLK = 15 -EBUSY = 16 -EEXIST = 17 -EXDEV = 18 -ENODEV = 19 -ENOTDIR = 20 -EISDIR = 21 -EINVAL = 22 -ENFILE = 23 -EMFILE = 24 -ENOTTY = 25 -ETXTBSY = 26 -EFBIG = 27 -ENOSPC = 28 -ESPIPE = 29 -EROFS = 30 -EMLINK = 31 -EPIPE = 32 -EDOM = 33 -ERANGE = 34 -EDEADLK = 35 -ENAMETOOLONG = 36 -ENOLCK = 37 -ENOSYS = 38 -ENOTEMPTY = 39 -ELOOP = 40 -ENOMSG = 42 -EIDRM = 43 -ECHRNG = 44 -EL2NSYNC = 45 -EL3HLT = 46 -EL3RST = 47 -ELNRNG = 48 -EUNATCH = 49 -ENOCSI = 50 -EL2HLT = 51 -EBADE = 52 -EBADR = 53 -EXFULL = 54 -ENOANO = 55 -EBADRQC = 56 -EBADSLT = 57 -EBFONT = 59 -ENOSTR = 60 -ENODATA = 61 -ETIME = 62 -ENOSR = 63 -ENONET = 64 -ENOPKG = 65 -EREMOTE = 66 -ENOLINK = 67 -EADV = 68 -ESRMNT = 69 -ECOMM = 70 -EPROTO = 71 -EMULTIHOP = 72 -EDOTDOT = 73 -EBADMSG = 74 -EOVERFLOW = 75 -ENOTUNIQ = 76 -EBADFD = 77 -EREMCHG = 78 -ELIBACC = 79 -ELIBBAD = 80 -ELIBSCN = 81 -ELIBMAX = 82 -ELIBEXEC = 83 -EILSEQ = 84 -ERESTART = 85 -ESTRPIPE = 86 -EUSERS = 87 -ENOTSOCK = 88 -EDESTADDRREQ = 89 -EMSGSIZE = 90 -EPROTOTYPE = 91 -ENOPROTOOPT = 92 -EPROTONOSUPPORT = 93 -ESOCKTNOSUPPORT = 94 -EOPNOTSUPP = 95 -EPFNOSUPPORT = 96 -EAFNOSUPPORT = 97 -EADDRINUSE = 98 -EADDRNOTAVAIL = 99 -ENETDOWN = 100 -ENETUNREACH = 101 -ENETRESET = 102 -ECONNABORTED = 103 -ECONNRESET = 104 -ENOBUFS = 105 -EISCONN = 106 -ENOTCONN = 107 -ESHUTDOWN = 108 -ETOOMANYREFS = 109 -ETIMEDOUT = 110 -ECONNREFUSED = 111 -EHOSTDOWN = 112 -EHOSTUNREACH = 113 -EALREADY = 114 -EINPROGRESS = 115 -ESTALE = 116 -EUCLEAN = 117 -ENOTNAM = 118 -ENAVAIL = 119 -EISNAM = 120 -EREMOTEIO = 121 -EDQUOT = 122 -ENOMEDIUM = 123 -EMEDIUMTYPE = 124 -ECANCELED = 125 -ENOKEY = 126 -EKEYEXPIRED = 127 -EKEYREVOKED = 128 -EKEYREJECTED = 129 -EOWNERDEAD = 130 -ENOTRECOVERABLE = 131 - - -errors = { - 1: 'EPERM', - 2: 'ENOENT', - 3: 'ESRCH', - 4: 'EINTR', - 5: 'EIO', - 6: 'ENXIO', - 7: 'E2BIG', - 8: 'ENOEXEC', - 9: 'EBADF', - 10: 'ECHILD', - 11: 'EAGAIN/EWOULDBLOCK', - 12: 'ENOMEM', - 13: 'EACCES', - 14: 'EFAULT', - 15: 'ENOTBLK', - 16: 'EBUSY', - 17: 'EEXIST', - 18: 'EXDEV', - 19: 'ENODEV', - 20: 'ENOTDIR', - 21: 'EISDIR', - 22: 'EINVAL', - 23: 'ENFILE', - 24: 'EMFILE', - 25: 'ENOTTY', - 26: 'ETXTBSY', - 27: 'EFBIG', - 28: 'ENOSPC', - 29: 'ESPIPE', - 30: 'EROFS', - 31: 'EMLINK', - 32: 'EPIPE', - 33: 'EDOM', - 34: 'ERANGE', - 35: 'EDEADLK', - 36: 'ENAMETOOLONG', - 37: 'ENOLCK', - 38: 'ENOSYS', - 39: 'ENOTEMPTY', - 40: 'ELOOP', - 42: 'ENOMSG', - 43: 'EIDRM', - 44: 'ECHRNG', - 45: 'EL2NSYNC', - 46: 'EL3HLT', - 47: 'EL3RST', - 48: 'ELNRNG', - 49: 'EUNATCH', - 50: 'ENOCSI', - 51: 'EL2HLT', - 52: 'EBADE', - 53: 'EBADR', - 54: 'EXFULL', - 55: 'ENOANO', - 56: 'EBADRQC', - 57: 'EBADSLT', - 59: 'EBFONT', - 60: 'ENOSTR', - 61: 'ENODATA', - 62: 'ETIME', - 63: 'ENOSR', - 64: 'ENONET', - 65: 'ENOPKG', - 66: 'EREMOTE', - 67: 'ENOLINK', - 68: 'EADV', - 69: 'ESRMNT', - 70: 'ECOMM', - 71: 'EPROTO', - 72: 'EMULTIHOP', - 73: 'EDOTDOT', - 74: 'EBADMSG', - 75: 'EOVERFLOW', - 76: 'ENOTUNIQ', - 77: 'EBADFD', - 78: 'EREMCHG', - 79: 'ELIBACC', - 80: 'ELIBBAD', - 81: 'ELIBSCN', - 82: 'ELIBMAX', - 83: 'ELIBEXEC', - 84: 'EILSEQ', - 85: 'ERESTART', - 86: 'ESTRPIPE', - 87: 'EUSERS', - 88: 'ENOTSOCK', - 89: 'EDESTADDRREQ', - 90: 'EMSGSIZE', - 91: 'EPROTOTYPE', - 92: 'ENOPROTOOPT', - 93: 'EPROTONOSUPPORT', - 94: 'ESOCKTNOSUPPORT', - 95: 'EOPNOTSUPP', - 96: 'EPFNOSUPPORT', - 97: 'EAFNOSUPPORT', - 98: 'EADDRINUSE', - 99: 'EADDRNOTAVAIL', - 100: 'ENETDOWN', - 101: 'ENETUNREACH', - 102: 'ENETRESET', - 103: 'ECONNABORTED', - 104: 'ECONNRESET', - 105: 'ENOBUFS', - 106: 'EISCONN', - 107: 'ENOTCONN', - 108: 'ESHUTDOWN', - 109: 'ETOOMANYREFS', - 110: 'ETIMEDOUT', - 111: 'ECONNREFUSED', - 112: 'EHOSTDOWN', - 113: 'EHOSTUNREACH', - 114: 'EALREADY', - 115: 'EINPROGRESS', - 116: 'ESTALE', - 117: 'EUCLEAN', - 118: 'ENOTNAM', - 119: 'ENAVAIL', - 120: 'EISNAM', - 121: 'EREMOTEIO', - 122: 'EDQUOT', - 123: 'ENOMEDIUM', - 124: 'EMEDIUMTYPE', - 125: 'ECANCELED', - 126: 'ENOKEY', - 127: 'EKEYEXPIRED', - 128: 'EKEYREVOKED', - 129: 'EKEYREJECTED', - 130: 'EOWNERDEAD', - 131: 'ENOTRECOVERABLE', -} + +# see: https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/errno.h +class linux_errno(Enum): + EPERM = 1 + ENOENT = 2 + ESRCH = 3 + EINTR = 4 + EIO = 5 + ENXIO = 6 + E2BIG = 7 + ENOEXEC = 8 + EBADF = 9 + ECHILD = 10 + EAGAIN = 11 + EWOULDBLOCK = 11 + ENOMEM = 12 + EACCES = 13 + EFAULT = 14 + ENOTBLK = 15 + EBUSY = 16 + EEXIST = 17 + EXDEV = 18 + ENODEV = 19 + ENOTDIR = 20 + EISDIR = 21 + EINVAL = 22 + ENFILE = 23 + EMFILE = 24 + ENOTTY = 25 + ETXTBSY = 26 + EFBIG = 27 + ENOSPC = 28 + ESPIPE = 29 + EROFS = 30 + EMLINK = 31 + EPIPE = 32 + EDOM = 33 + ERANGE = 34 + EDEADLK = 35 + EDEADLOCK = 35 + ENAMETOOLONG = 36 + ENOLCK = 37 + ENOSYS = 38 + ENOTEMPTY = 39 + ELOOP = 40 + ENOMSG = 42 + EIDRM = 43 + ECHRNG = 44 + EL2NSYNC = 45 + EL3HLT = 46 + EL3RST = 47 + ELNRNG = 48 + EUNATCH = 49 + ENOCSI = 50 + EL2HLT = 51 + EBADE = 52 + EBADR = 53 + EXFULL = 54 + ENOANO = 55 + EBADRQC = 56 + EBADSLT = 57 + EBFONT = 59 + ENOSTR = 60 + ENODATA = 61 + ETIME = 62 + ENOSR = 63 + ENONET = 64 + ENOPKG = 65 + EREMOTE = 66 + ENOLINK = 67 + EADV = 68 + ESRMNT = 69 + ECOMM = 70 + EPROTO = 71 + EMULTIHOP = 72 + EDOTDOT = 73 + EBADMSG = 74 + EFSBADCRC = 74 + EOVERFLOW = 75 + ENOTUNIQ = 76 + EBADFD = 77 + EREMCHG = 78 + ELIBACC = 79 + ELIBBAD = 80 + ELIBSCN = 81 + ELIBMAX = 82 + ELIBEXEC = 83 + EILSEQ = 84 + ERESTART = 85 + ESTRPIPE = 86 + EUSERS = 87 + ENOTSOCK = 88 + EDESTADDRREQ = 89 + EMSGSIZE = 90 + EPROTOTYPE = 91 + ENOPROTOOPT = 92 + EPROTONOSUPPORT = 93 + ESOCKTNOSUPPORT = 94 + EOPNOTSUPP = 95 + ENOTSUP = 95 + EPFNOSUPPORT = 96 + EAFNOSUPPORT = 97 + EADDRINUSE = 98 + EADDRNOTAVAIL = 99 + ENETDOWN = 100 + ENETUNREACH = 101 + ENETRESET = 102 + ECONNABORTED = 103 + ECONNRESET = 104 + ENOBUFS = 105 + EISCONN = 106 + ENOTCONN = 107 + ESHUTDOWN = 108 + ETOOMANYREFS = 109 + ETIMEDOUT = 110 + ECONNREFUSED = 111 + EHOSTDOWN = 112 + EHOSTUNREACH = 113 + EALREADY = 114 + EINPROGRESS = 115 + ESTALE = 116 + EUCLEAN = 117 + EFSCORRUPTED = 117 + ENOTNAM = 118 + ENAVAIL = 119 + EISNAM = 120 + EREMOTEIO = 121 + EDQUOT = 122 + ENOMEDIUM = 123 + EMEDIUMTYPE = 124 + ECANCELED = 125 + ENOKEY = 126 + EKEYEXPIRED = 127 + EKEYREVOKED = 128 + EKEYREJECTED = 129 + EOWNERDEAD = 130 + ENOTRECOVERABLE = 131 + ERFKILL = 132 + EHWPOISON = 133 + EFTYPE = 134 + + +# see: https://github.com/torvalds/linux/blob/master/arch/mips/include/uapi/asm/errno.h +class linux_mips_errno(Enum): + EPERM = 1 + ENOENT = 2 + ESRCH = 3 + EINTR = 4 + EIO = 5 + ENXIO = 6 + E2BIG = 7 + ENOEXEC = 8 + EBADF = 9 + ECHILD = 10 + EAGAIN = 11 + EWOULDBLOCK = 11 + ENOMEM = 12 + EACCES = 13 + EFAULT = 14 + ENOTBLK = 15 + EBUSY = 16 + EEXIST = 17 + EXDEV = 18 + ENODEV = 19 + ENOTDIR = 20 + EISDIR = 21 + EINVAL = 22 + ENFILE = 23 + EMFILE = 24 + ENOTTY = 25 + ETXTBSY = 26 + EFBIG = 27 + ENOSPC = 28 + ESPIPE = 29 + EROFS = 30 + EMLINK = 31 + EPIPE = 32 + EDOM = 33 + ERANGE = 34 + ENOMSG = 35 + EIDRM = 36 + ECHRNG = 37 + EL2NSYNC = 38 + EL3HLT = 39 + EL3RST = 40 + ELNRNG = 41 + EUNATCH = 42 + ENOCSI = 43 + EL2HLT = 44 + EDEADLK = 45 + ENOLCK = 46 + EBADE = 50 + EBADR = 51 + EXFULL = 52 + ENOANO = 53 + EBADRQC = 54 + EBADSLT = 55 + EDEADLOCK = 56 + EBFONT = 59 + ENOSTR = 60 + ENODATA = 61 + ETIME = 62 + ENOSR = 63 + ENONET = 64 + ENOPKG = 65 + EREMOTE = 66 + ENOLINK = 67 + EADV = 68 + ESRMNT = 69 + ECOMM = 70 + EPROTO = 71 + EDOTDOT = 73 + EMULTIHOP = 74 + EBADMSG = 77 + EFSBADCRC = 77 + ENAMETOOLONG = 78 + EOVERFLOW = 79 + ENOTUNIQ = 80 + EBADFD = 81 + EREMCHG = 82 + ELIBACC = 83 + ELIBBAD = 84 + ELIBSCN = 85 + ELIBMAX = 86 + ELIBEXEC = 87 + EILSEQ = 88 + ENOSYS = 89 + ELOOP = 90 + ERESTART = 91 + ESTRPIPE = 92 + ENOTEMPTY = 93 + EUSERS = 94 + ENOTSOCK = 95 + EDESTADDRREQ = 96 + EMSGSIZE = 97 + EPROTOTYPE = 98 + ENOPROTOOPT = 99 + EPROTONOSUPPORT = 120 + ESOCKTNOSUPPORT = 121 + EOPNOTSUPP = 122 + ENOTSUP = 122 + EPFNOSUPPORT = 123 + EAFNOSUPPORT = 124 + EADDRINUSE = 125 + EADDRNOTAVAIL = 126 + ENETDOWN = 127 + ENETUNREACH = 128 + ENETRESET = 129 + ECONNABORTED = 130 + ECONNRESET = 131 + ENOBUFS = 132 + EISCONN = 133 + ENOTCONN = 134 + EUCLEAN = 135 + EFSCORRUPTED = 135 + ENOTNAM = 137 + ENAVAIL = 138 + EISNAM = 139 + EREMOTEIO = 140 + EINIT = 141 + EREMDEV = 142 + ESHUTDOWN = 143 + ETOOMANYREFS = 144 + ETIMEDOUT = 145 + ECONNREFUSED = 146 + EHOSTDOWN = 147 + EHOSTUNREACH = 148 + EALREADY = 149 + EINPROGRESS = 150 + ESTALE = 151 + ECANCELED = 158 + ENOMEDIUM = 159 + EMEDIUMTYPE = 160 + ENOKEY = 161 + EKEYEXPIRED = 162 + EKEYREVOKED = 163 + EKEYREJECTED = 164 + EOWNERDEAD = 165 + ENOTRECOVERABLE = 166 + ERFKILL = 167 + EHWPOISON = 168 + EFTYPE = 169 + EDQUOT = 1133 + + +# see: https://github.com/apple/darwin-xnu/blob/main/bsd/sys/errno.h +class macos_errno(Enum): + EPERM = 1 + ENOENT = 2 + ESRCH = 3 + EINTR = 4 + EIO = 5 + ENXIO = 6 + E2BIG = 7 + ENOEXEC = 8 + EBADF = 9 + ECHILD = 10 + EDEADLK = 11 + ENOMEM = 12 + EACCES = 13 + EFAULT = 14 + ENOTBLK = 15 + EBUSY = 16 + EEXIST = 17 + EXDEV = 18 + ENODEV = 19 + ENOTDIR = 20 + EISDIR = 21 + EINVAL = 22 + ENFILE = 23 + EMFILE = 24 + ENOTTY = 25 + ETXTBSY = 26 + EFBIG = 27 + ENOSPC = 28 + ESPIPE = 29 + EROFS = 30 + EMLINK = 31 + EPIPE = 32 + EDOM = 33 + ERANGE = 34 + EAGAIN = 35 + EWOULDBLOCK = 35 + EINPROGRESS = 36 + EALREADY = 37 + ENOTSOCK = 38 + EDESTADDRREQ = 39 + EMSGSIZE = 40 + EPROTOTYPE = 41 + ENOPROTOOPT = 42 + EPROTONOSUPPORT = 43 + ESOCKTNOSUPPORT = 44 + ENOTSUP = 45 + EPFNOSUPPORT = 46 + EAFNOSUPPORT = 47 + EADDRINUSE = 48 + EADDRNOTAVAIL = 49 + ENETDOWN = 50 + ENETUNREACH = 51 + ENETRESET = 52 + ECONNABORTED = 53 + ECONNRESET = 54 + ENOBUFS = 55 + EISCONN = 56 + ENOTCONN = 57 + ESHUTDOWN = 58 + ETOOMANYREFS = 59 + ETIMEDOUT = 60 + ECONNREFUSED = 61 + ELOOP = 62 + ENAMETOOLONG = 63 + EHOSTDOWN = 64 + EHOSTUNREACH = 65 + ENOTEMPTY = 66 + EPROCLIM = 67 + EUSERS = 68 + EDQUOT = 69 + ESTALE = 70 + EREMOTE = 71 + EBADRPC = 72 + ERPCMISMATCH = 73 + EPROGUNAVAIL = 74 + EPROGMISMATCH = 75 + EPROCUNAVAIL = 76 + ENOLCK = 77 + ENOSYS = 78 + EFTYPE = 79 + EAUTH = 80 + ENEEDAUTH = 81 + EPWROFF = 82 + EDEVERR = 83 + EOVERFLOW = 84 + EBADEXEC = 85 + EBADARCH = 86 + ESHLIBVERS = 87 + EBADMACHO = 88 + ECANCELED = 89 + EIDRM = 90 + ENOMSG = 91 + EILSEQ = 92 + ENOATTR = 93 + EBADMSG = 94 + EMULTIHOP = 95 + ENODATA = 96 + ENOLINK = 97 + ENOSR = 98 + ENOSTR = 99 + EPROTO = 100 + ETIME = 101 + EOPNOTSUPP = 102 + ENOPOLICY = 103 + ENOTRECOVERABLE = 104 + EOWNERDEAD = 105 + EQFULL = 106 + + +# see: https://github.com/freebsd/freebsd-src/blob/main/sys/sys/errno.h +class freebsd_errno(Enum): + EPERM = 1 + ENOENT = 2 + ESRCH = 3 + EINTR = 4 + EIO = 5 + ENXIO = 6 + E2BIG = 7 + ENOEXEC = 8 + EBADF = 9 + ECHILD = 10 + EDEADLK = 11 + ENOMEM = 12 + EACCES = 13 + EFAULT = 14 + ENOTBLK = 15 + EBUSY = 16 + EEXIST = 17 + EXDEV = 18 + ENODEV = 19 + ENOTDIR = 20 + EISDIR = 21 + EINVAL = 22 + ENFILE = 23 + EMFILE = 24 + ENOTTY = 25 + ETXTBSY = 26 + EFBIG = 27 + ENOSPC = 28 + ESPIPE = 29 + EROFS = 30 + EMLINK = 31 + EPIPE = 32 + EDOM = 33 + ERANGE = 34 + EAGAIN = 35 + EWOULDBLOCK = 35 + EINPROGRESS = 36 + EALREADY = 37 + ENOTSOCK = 38 + EDESTADDRREQ = 39 + EMSGSIZE = 40 + EPROTOTYPE = 41 + ENOPROTOOPT = 42 + EPROTONOSUPPORT = 43 + ESOCKTNOSUPPORT = 44 + EOPNOTSUPP = 45 + ENOTSUP = 45 + EPFNOSUPPORT = 46 + EAFNOSUPPORT = 47 + EADDRINUSE = 48 + EADDRNOTAVAIL = 49 + ENETDOWN = 50 + ENETUNREACH = 51 + ENETRESET = 52 + ECONNABORTED = 53 + ECONNRESET = 54 + ENOBUFS = 55 + EISCONN = 56 + ENOTCONN = 57 + ESHUTDOWN = 58 + ETOOMANYREFS = 59 + ETIMEDOUT = 60 + ECONNREFUSED = 61 + ELOOP = 62 + ENAMETOOLONG = 63 + EHOSTDOWN = 64 + EHOSTUNREACH = 65 + ENOTEMPTY = 66 + EPROCLIM = 67 + EUSERS = 68 + EDQUOT = 69 + ESTALE = 70 + EREMOTE = 71 + EBADRPC = 72 + ERPCMISMATCH = 73 + EPROGUNAVAIL = 74 + EPROGMISMATCH = 75 + EPROCUNAVAIL = 76 + ENOLCK = 77 + ENOSYS = 78 + EFTYPE = 79 + EAUTH = 80 + ENEEDAUTH = 81 + EIDRM = 82 + ENOMSG = 83 + EOVERFLOW = 84 + ECANCELED = 85 + EILSEQ = 86 + ENOATTR = 87 + EDOOFUS = 88 + EBADMSG = 89 + EMULTIHOP = 90 + ENOLINK = 91 + EPROTO = 92 + ENOTCAPABLE = 93 + ECAPMODE = 94 + ENOTRECOVERABLE = 95 + EOWNERDEAD = 96 + EINTEGRITY = 97 + + +# see: https://github.com/vocho/openqnx/blob/master/trunk/lib/c/public/errno.h +class qnx_errno(Enum): + EPERM = 1 + ENOENT = 2 + ESRCH = 3 + EINTR = 4 + EIO = 5 + ENXIO = 6 + E2BIG = 7 + ENOEXEC = 8 + EBADF = 9 + ECHILD = 10 + EAGAIN = 11 + EWOULDBLOCK = 11 + ENOMEM = 12 + EACCES = 13 + EFAULT = 14 + ENOTBLK = 15 + EBUSY = 16 + EALREADY = 16 + EEXIST = 17 + EXDEV = 18 + ENODEV = 19 + ENOTDIR = 20 + EISDIR = 21 + EINVAL = 22 + ENFILE = 23 + EMFILE = 24 + ENOTTY = 25 + ETXTBSY = 26 + EFBIG = 27 + ENOSPC = 28 + ESPIPE = 29 + EROFS = 30 + EMLINK = 31 + EPIPE = 32 + EDOM = 33 + ERANGE = 34 + ENOMSG = 35 + EIDRM = 36 + ECHRNG = 37 + EL2NSYNC = 38 + EL3HLT = 39 + EL3RST = 40 + ELNRNG = 41 + EUNATCH = 42 + ENOCSI = 43 + EL2HLT = 44 + EDEADLK = 45 + ENOLCK = 46 + ECANCELED = 47 + ENOTSUP = 48 + EDQUOT = 49 + EBADE = 50 + EBADR = 51 + EXFULL = 52 + ENOANO = 53 + EBADRQC = 54 + EBADSLT = 55 + EDEADLOCK = 56 + EBFONT = 57 + EOWNERDEAD = 58 + ENOSTR = 60 + ENODATA = 61 + ETIME = 62 + ENOSR = 63 + ENONET = 64 + ENOPKG = 65 + EREMOTE = 66 + ENOLINK = 67 + EADV = 68 + ESRMNT = 69 + ECOMM = 70 + EPROTO = 71 + EMULTIHOP = 74 + EBADMSG = 77 + ENAMETOOLONG = 78 + EOVERFLOW = 79 + ENOTUNIQ = 80 + EBADFD = 81 + EREMCHG = 82 + ELIBACC = 83 + ELIBBAD = 84 + ELIBSCN = 85 + ELIBMAX = 86 + ELIBEXEC = 87 + EILSEQ = 88 + ENOSYS = 89 + ELOOP = 90 + ERESTART = 91 + ESTRPIPE = 92 + ENOTEMPTY = 93 + EUSERS = 94 + EOPNOTSUPP = 103 + EFPOS = 110 + ESTALE = 122 + EINPROGRESS = 236 + ENOTSOCK = 238 + EDESTADDRREQ = 239 + EMSGSIZE = 240 + EPROTOTYPE = 241 + ENOPROTOOPT = 242 + EPROTONOSUPPORT = 243 + ESOCKTNOSUPPORT = 244 + EPFNOSUPPORT = 246 + EAFNOSUPPORT = 247 + EADDRINUSE = 248 + EADDRNOTAVAIL = 249 + ENETDOWN = 250 + ENETUNREACH = 251 + ENETRESET = 252 + ECONNABORTED = 253 + ECONNRESET = 254 + ENOBUFS = 255 + EISCONN = 256 + ENOTCONN = 257 + ESHUTDOWN = 258 + ETOOMANYREFS = 259 + ETIMEDOUT = 260 + ECONNREFUSED = 261 + EHOSTDOWN = 264 + EHOSTUNREACH = 265 + EBADRPC = 272 + ERPCMISMATCH = 273 + EPROGUNAVAIL = 274 + EPROGMISMATCH = 275 + EPROCUNAVAIL = 276 + ENOREMOTE = 300 + ENONDP = 301 + EBADFSYS = 302 + EMORE = 309 + ECTRLTERM = 310 + ENOLIC = 311 + ESRVRFAULT = 312 + EENDIAN = 313 + # shm syscall IPC_PRIVATE = 0 diff --git a/qiling/os/posix/const_mapping.py b/qiling/os/posix/const_mapping.py index dd95f717e..a1558a56d 100644 --- a/qiling/os/posix/const_mapping.py +++ b/qiling/os/posix/const_mapping.py @@ -4,6 +4,8 @@ # from __future__ import annotations + +import errno from typing import TYPE_CHECKING, Dict, Mapping, Type, Union from qiling.const import QL_ARCH, QL_OS @@ -202,7 +204,95 @@ def socket_option_mapping(value: int, archtype: QL_ARCH) -> str: return socket_option(value).name +def get_errno_class(archtype: QL_ARCH, ostype: QL_OS) -> Union[Type[Enum], None]: + """Retrieve the appropriate errno class for given architecture and OS. + + Args: + archtype: architecture type + ostype: operating system type + + Returns: appropriate errno class, or `None` if the specified arch and OS combination + is not supported + """ + + errno_by_os: Dict[QL_OS, Dict[QL_ARCH, Type[Enum]]] = { + QL_OS.LINUX: { + QL_ARCH.X86: linux_errno, + QL_ARCH.X8664: linux_errno, + QL_ARCH.ARM: linux_errno, + QL_ARCH.ARM64: linux_errno, + QL_ARCH.MIPS: linux_mips_errno, + QL_ARCH.RISCV: linux_errno, + QL_ARCH.RISCV64: linux_errno, + QL_ARCH.PPC: linux_errno + }, + + QL_OS.FREEBSD: { + QL_ARCH.X86: freebsd_errno, + QL_ARCH.X8664: freebsd_errno + }, + + QL_OS.MACOS: { + QL_ARCH.X86: macos_errno, + QL_ARCH.X8664: macos_errno, + QL_ARCH.ARM64: macos_errno + }, + + QL_OS.QNX: { + QL_ARCH.ARM: qnx_errno, + QL_ARCH.ARM64: qnx_errno + } + } + + cls = None + + if ostype in errno_by_os: + errno_by_arch = errno_by_os[ostype] + + if archtype in errno_by_arch: + cls = errno_by_arch[archtype] + + return cls + + +def ql_errno_mapping(ql: Qiling, err: int) -> int: + """Convert a hosting OS errno to the emulated OS errno. + + Errors are matched by name. Hosting errors that have no equivalent on the emulated OS + are reported as the emulated OS `EIO`. + + Args: + ql: qiling instance + err: positive hosting OS errno + + Returns: positive emulated OS errno + """ + + # the host may give one errno several names; prefer the canonical one + name = next((n for n in ('EAGAIN', 'EDEADLK', 'EOPNOTSUPP') if getattr(errno, n, None) == err), None) + + if name is None: + name = errno.errorcode.get(err, '').replace('WSAE', 'E', 1) + + archtype = ql.arch.type + ostype = ql.os.type + + emul_errno = get_errno_class(archtype, ostype) + + if emul_errno is None: + raise NotImplementedError(f'errno was not defined for emulated {archtype.name} {ostype.name}') + + members = emul_errno.__members__ + + # linux spells the missing extended attribute error ENODATA, bsd systems spell it ENOATTR + if name not in members: + name = {'ENODATA': 'ENOATTR', 'ENOATTR': 'ENODATA'}.get(name, name) + + return members.get(name, members['EIO']).value + + __all__ = [ 'flags_mapping', 'get_open_flags_class', 'ql_open_flag_mapping', 'socket_type_mapping', 'socket_domain_mapping', - 'socket_tcp_option_mapping', 'socket_level_mapping', 'socket_ip_option_mapping', 'socket_option_mapping' + 'socket_tcp_option_mapping', 'socket_level_mapping', 'socket_ip_option_mapping', 'socket_option_mapping', + 'get_errno_class', 'ql_errno_mapping' ] diff --git a/qiling/os/posix/posix.py b/qiling/os/posix/posix.py index a0a7b6290..c8e73488b 100644 --- a/qiling/os/posix/posix.py +++ b/qiling/os/posix/posix.py @@ -10,7 +10,8 @@ from qiling.const import QL_ARCH, QL_INTERCEPT from qiling.exception import QlErrorSyscallNotFound from qiling.os.os import QlOs -from qiling.os.posix.const import NR_OPEN, NSIG, errors +from qiling.os.posix.const import NR_OPEN, NSIG +from qiling.os.posix.const_mapping import get_errno_class from qiling.os.posix.msq import QlMsq from qiling.os.posix.shm import QlShm from qiling.os.posix.syscall.abi import QlSyscallABI, arm, intel, mips, ppc, riscv @@ -80,6 +81,9 @@ def __init__(self, ql: Qiling): # select syscall mapping function based on emulated OS and architecture self.syscall_mapper = self.__get_syscall_mapper(self.ql.arch.type) + # emulated errno names, used to annotate failed syscalls in the log + self._errno_names = {e.value: e.name for e in get_errno_class(self.ql.arch.type, self.type)} + self._fd = QlFileDes() # the QlOs constructor cannot assign the standard streams using their designated properties since @@ -152,8 +156,7 @@ def set_api(self, target: str, handler: Callable, intercept: QL_INTERCEPT = QL_I else: self.function_hook.add_function_hook(target, handler, intercept) - @staticmethod - def getNameFromErrorCode(ret: int) -> str: + def getNameFromErrorCode(self, ret: int) -> str: """Return the hex representation of a return value and if possible add the corresponding error name to it. @@ -165,7 +168,10 @@ def getNameFromErrorCode(ret: int) -> str: if type(ret) is not int: return '?' - return f'{ret:#x}{f" ({errors[-ret]})" if -ret in errors else f""}' + name = self._errno_names.get(-ret) + name = f' ({name})' if name else '' + + return f'{ret:#x}{name}' def load_syscall(self): syscall_id = self.syscall_abi.get_id() @@ -246,7 +252,7 @@ def __get_os_module(osname: str): args.append((name, f'{value:#x}')) - sret = QlOsPosix.getNameFromErrorCode(retval) + sret = self.getNameFromErrorCode(retval) self.utils.print_function(self.ql.arch.regs.arch_pc, syscall_basename, args, sret, False) # record syscall statistics diff --git a/qiling/os/posix/syscall/epoll.py b/qiling/os/posix/syscall/epoll.py index 669ce17b6..eccec68b2 100644 --- a/qiling/os/posix/syscall/epoll.py +++ b/qiling/os/posix/syscall/epoll.py @@ -7,6 +7,7 @@ from qiling.os import struct from qiling.os.posix.const import * +from qiling.os.posix.const_mapping import get_errno_class from qiling.os.filestruct import PersistentQlFile, ql_file @@ -114,28 +115,30 @@ def ql_syscall_epoll_ctl(ql: Qiling, epfd: int, op: int, fd: int, event: int): """Modify an existing epoll. """ + errno_class = get_errno_class(ql.arch.type, ql.os.type) + # not clear from man page, but to be safe don't support 'undefined' ops. if op not in (EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD): - return -EINVAL + return -errno_class.EINVAL.value if epfd == fd: - return -EINVAL + return -errno_class.EINVAL.value if epfd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value epoll_parent_obj = ql.os.fd[epfd] if not isinstance(epoll_parent_obj, QlEpollObj): - return -EINVAL + return -errno_class.EINVAL.value epoll_obj = epoll_parent_obj.epoll_instance if epoll_obj is None: - return -EBADF + return -errno_class.EBADF.value if epoll_obj.fileno() == fd: - return -ELOOP + return -errno_class.ELOOP.value # Qiling doesn't check process capabilities right now, so this case isn't explicitly handled yet # EPOLLWAKEUP (since Linux 3.5) @@ -144,7 +147,7 @@ def ql_syscall_epoll_ctl(ql: Qiling, epfd: int, op: int, fd: int, event: int): fd_obj = ql.os.fd[fd] if fd_obj is None: - return -EBADF + return -errno_class.EBADF.value # TODO: not sure if qiling supports a way to determine if the target file descriptor is a # directory. Here, check against PersistentQlFile is to ensure that polling stdin, stdout, @@ -153,13 +156,13 @@ def ql_syscall_epoll_ctl(ql: Qiling, epfd: int, op: int, fd: int, event: int): # The target file fd does not support epoll. This error can occur if fd refers to, for # example, a regular file or a directory. if isinstance(fd_obj, ql_file) and not isinstance(fd_obj, PersistentQlFile): - return -EPERM + return -errno_class.EPERM.value # EPOLLEXCLUSIVE was specified in event and fd refers to an epoll instance if isinstance(fd_obj, QlEpollObj) and (op & EPOLLEXCLUSIVE): - return -EINVAL + return -errno_class.EINVAL.value # Necessary to iterate over all possible qiling fds to determine if we have a chain of more # than five epolls monitoring each other This may be removed in the future if the QlOsLinux @@ -169,15 +172,15 @@ def ql_syscall_epoll_ctl(ql: Qiling, epfd: int, op: int, fd: int, event: int): try: check_epoll_depth(ql.os.fd) except RecursionError: - return -ELOOP + return -errno_class.ELOOP.value if op == EPOLL_CTL_ADD: # can't add an fd that's already being waited on if fd in epoll_parent_obj: - return -EEXIST + return -errno_class.EEXIST.value if not event: - return -EINVAL + return -errno_class.EINVAL.value # dereference the event pointer to get structure fields epoll_event_cls = __make_epoll_event(ql.arch) @@ -185,7 +188,7 @@ def ql_syscall_epoll_ctl(ql: Qiling, epfd: int, op: int, fd: int, event: int): # EPOLLEXCLUSIVE was specified in event and fd refers to an epoll instance if isinstance(fd_obj, QlEpollObj) and (epoll_event.events & EPOLLEXCLUSIVE): - return -EINVAL + return -errno_class.EINVAL.value epoll_parent_obj[fd] = QlEpollEntry( epoll_event.events, @@ -194,17 +197,17 @@ def ql_syscall_epoll_ctl(ql: Qiling, epfd: int, op: int, fd: int, event: int): elif op == EPOLL_CTL_DEL: if fd not in epoll_parent_obj: - return -ENOENT + return -errno_class.ENOENT.value # remove from fds list and do so in the underlying epoll instance del epoll_parent_obj[fd] elif op == EPOLL_CTL_MOD: if fd not in epoll_parent_obj: - return -ENOENT + return -errno_class.ENOENT.value if not event: - return -EINVAL + return -errno_class.EINVAL.value # dereference the event pointer to get structure fields epoll_event_cls = __make_epoll_event(ql.arch) @@ -212,7 +215,7 @@ def ql_syscall_epoll_ctl(ql: Qiling, epfd: int, op: int, fd: int, event: int): # EPOLLEXCLUSIVE cannot be set on MOD operation, only on ADD if epoll_event.events & EPOLLEXCLUSIVE: - return -EINVAL + return -errno_class.EINVAL.value epoll_parent_obj[fd] = QlEpollEntry( epoll_event.events, @@ -226,25 +229,27 @@ def ql_syscall_epoll_wait(ql: Qiling, epfd: int, epoll_events: int, maxevents: i """Wait on an existing epoll for specific events. """ + errno_class = get_errno_class(ql.arch.type, ql.os.type) + if maxevents <= 0: - return -EINVAL + return -errno_class.EINVAL.value # default value is 0xffffffff, but this fails when passing to epoll.poll() if timeout == 0xFFFFFFFF: timeout = None if epfd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value epoll_parent_obj = ql.os.fd[epfd] if not isinstance(epoll_parent_obj, QlEpollObj): - return -EINVAL + return -errno_class.EINVAL.value epoll_obj = epoll_parent_obj.epoll_instance if epoll_obj is None: - return -EBADF + return -errno_class.EBADF.value ready_fds = epoll_obj.poll(timeout, maxevents) @@ -282,13 +287,13 @@ def __epoll_create(ql: Qiling, sizehint: int, flags: int) -> int: def ql_syscall_epoll_create1(ql: Qiling, flags: int): if flags != select.EPOLL_CLOEXEC and flags != 0: - return -EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value return __epoll_create(ql, -1, flags) def ql_syscall_epoll_create(ql: Qiling, size: int): if size < 0: - return -EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value return __epoll_create(ql, size, 0) diff --git a/qiling/os/posix/syscall/fcntl.py b/qiling/os/posix/syscall/fcntl.py index 13d60701e..247263abb 100644 --- a/qiling/os/posix/syscall/fcntl.py +++ b/qiling/os/posix/syscall/fcntl.py @@ -8,13 +8,15 @@ from qiling import Qiling from qiling.const import QL_OS, QL_ARCH from qiling.os.posix.const import * -from qiling.os.posix.const_mapping import ql_open_flag_mapping, get_open_flags_class +from qiling.os.posix.const_mapping import ql_open_flag_mapping, get_open_flags_class, ql_errno_mapping, get_errno_class from qiling.os.posix.filestruct import ql_socket from .unistd import virtual_abspath_at, get_opened_fd def __do_open(ql: Qiling, absvpath: str, flags: int, mode: int) -> int: + errno_class = get_errno_class(ql.arch.type, ql.os.type) + flags &= 0xffffffff mode &= 0xffffffff @@ -22,7 +24,7 @@ def __do_open(ql: Qiling, absvpath: str, flags: int, mode: int) -> int: idx = next((i for i in range(NR_OPEN) if ql.os.fd[i] is None), -1) if idx == -1: - return -EMFILE + return -errno_class.EMFILE.value if ql.arch.type is QL_ARCH.ARM and ql.os.type is not QL_OS.QNX: mode = 0 @@ -33,13 +35,13 @@ def __do_open(ql: Qiling, absvpath: str, flags: int, mode: int) -> int: try: ql.os.fd[idx] = ql.os.fs_mapper.open_ql_file(absvpath, flags, mode) except FileNotFoundError: - return -ENOENT + return -errno_class.ENOENT.value except FileExistsError: - return -EEXIST + return -errno_class.EEXIST.value except IsADirectoryError: - return -EISDIR + return -errno_class.EISDIR.value except PermissionError: - return -EACCES + return -errno_class.EACCES.value return idx @@ -81,14 +83,16 @@ def ql_syscall_creat(ql: Qiling, filename: int, mode: int): def ql_syscall_fcntl(ql: Qiling, fd: int, cmd: int, arg: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + f = get_opened_fd(ql.os, fd) if f is None: - return -EBADF + return -errno_class.EBADF.value if cmd == F_DUPFD: if arg not in range(NR_OPEN): - regreturn = -EINVAL + regreturn = -errno_class.EINVAL.value for idx in range(arg, len(ql.os.fd)): if ql.os.fd[idx] is None: @@ -96,7 +100,7 @@ def ql_syscall_fcntl(ql: Qiling, fd: int, cmd: int, arg: int): regreturn = idx break else: - regreturn = -EMFILE + regreturn = -errno_class.EMFILE.value elif cmd == F_GETFD: regreturn = int(getattr(f, "close_on_exec", False)) @@ -114,24 +118,23 @@ def ql_syscall_fcntl(ql: Qiling, fd: int, cmd: int, arg: int): regreturn = 0 else: - regreturn = -EINVAL + regreturn = -errno_class.EINVAL.value return regreturn def ql_syscall_fcntl64(ql: Qiling, fd: int, cmd: int, arg: int): - if fd not in range(NR_OPEN): - return -1 + errno_class = get_errno_class(ql.arch.type, ql.os.type) - f = ql.os.fd[fd] + f = get_opened_fd(ql.os, fd) if f is None: - return -1 + return -errno_class.EBADF.value # https://linux.die.net/man/2/fcntl64 if cmd == F_DUPFD: if arg not in range(NR_OPEN): - regreturn = -1 + regreturn = -errno_class.EINVAL.value for idx in range(arg, len(ql.os.fd)): if ql.os.fd[idx] is None: @@ -139,7 +142,7 @@ def ql_syscall_fcntl64(ql: Qiling, fd: int, cmd: int, arg: int): regreturn = idx break else: - regreturn = -1 + regreturn = -errno_class.EMFILE.value elif cmd == F_GETFL: regreturn = 2 @@ -178,7 +181,7 @@ def ql_syscall_rename(ql: Qiling, oldname_buf: int, newname_buf: int): try: ql.os.fs_mapper.rename_mapping(old_vpath, new_vpath) except KeyError: - regreturn = -1 + regreturn = -get_errno_class(ql.arch.type, ql.os.type).ENOENT.value else: regreturn = 0 @@ -193,8 +196,8 @@ def ql_syscall_rename(ql: Qiling, oldname_buf: int, newname_buf: int): try: os.rename(old_hpath, new_hpath) - except OSError: - regreturn = -1 + except OSError as ex: + regreturn = -ql_errno_mapping(ql, ex.errno) else: regreturn = 0 diff --git a/qiling/os/posix/syscall/ioctl.py b/qiling/os/posix/syscall/ioctl.py index d87a8e2fd..82aba8bb0 100644 --- a/qiling/os/posix/syscall/ioctl.py +++ b/qiling/os/posix/syscall/ioctl.py @@ -5,10 +5,15 @@ import struct +from unicorn import UcError + from qiling import Qiling from qiling.os.posix.filestruct import ql_socket +from qiling.os.posix.const_mapping import ql_errno_mapping, get_errno_class def ql_syscall_ioctl(ql: Qiling, fd: int, cmd: int, arg: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + TCGETS = 0x5401 TIOCGWINSZ = 0x5413 TIOCSWINSZ = 0x5414 @@ -94,7 +99,7 @@ def ioctl(_fd: int, _cmd: int, _arg: int): data = ql.os.fd[fd].ioctl(cmd, bytes(data)) except OSError as ex: ql.log.debug(f'the underlying ioctl raised an exception: {ex.strerror}') - regreturn = -1 + regreturn = -ql_errno_mapping(ql, ex.errno) else: ql.mem.write(arg, data) regreturn = 0 @@ -111,8 +116,10 @@ def ioctl(_fd: int, _cmd: int, _arg: int): elif cmd == TIOCGWINSZ: data = struct.pack("HHHH", *info) ql.mem.write(arg, data) - except: - regreturn = -1 + except (KeyError, ValueError, NotImplementedError): + regreturn = -errno_class.ENOTTY.value + except UcError: + regreturn = -errno_class.EFAULT.value else: regreturn = 0 diff --git a/qiling/os/posix/syscall/mman.py b/qiling/os/posix/syscall/mman.py index a89f98d39..03def9665 100755 --- a/qiling/os/posix/syscall/mman.py +++ b/qiling/os/posix/syscall/mman.py @@ -13,6 +13,7 @@ from qiling.exception import QlMemoryMappedError from qiling.os.filestruct import ql_file from qiling.os.posix.const import * +from qiling.os.posix.const_mapping import get_errno_class def ql_syscall_munmap(ql: Qiling, addr: int, length: int): @@ -74,6 +75,8 @@ def ql_syscall_mprotect(ql: Qiling, start: int, mlen: int, prot: int): def syscall_mmap_impl(ql: Qiling, addr: int, length: int, prot: int, flags: int, fd: int, pgoffset: int, ver: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + def __select_mmap_flags(archtype: QL_ARCH, ostype: QL_OS): """The mmap flags definitions differ between operating systems and architectures. This method provides the apropriate flags set based on those properties. @@ -130,7 +133,7 @@ class mmap_flags(IntFlag): if flags & (mmap_flags.MAP_FIXED | mmap_flags.MAP_FIXED_NOREPLACE): # on non-QNX systems, base must be aligned to page boundary if addr & (pagesize - 1) and ql.os.type != QL_OS.QNX: - return -EINVAL + return -errno_class.EINVAL.value # if not, use the base address as a hint but always above or equal to # the value specified in /proc/sys/vm/mmap_min_addr (here: mmap_address) @@ -147,7 +150,7 @@ class mmap_flags(IntFlag): if flags & mmap_flags.MAP_FIXED_NOREPLACE: if not ql.mem.is_available(lbound, mapping_size): - return -EEXIST + return -errno_class.EEXIST.value elif flags & mmap_flags.MAP_FIXED: ql.log.debug(f'{api_name}: unmapping memory between {lbound:#x}-{ubound:#x} to make room for fixed mapping') @@ -165,12 +168,12 @@ class mmap_flags(IntFlag): fd = ql.os.utils.as_signed(fd, 32) if fd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value f: Optional[ql_file] = ql.os.fd[fd] if f is None: - return -EBADF + return -errno_class.EBADF.value # set mapping properties for future unmap f._is_map_shared = bool(flags & mmap_flags.MAP_SHARED) @@ -194,7 +197,7 @@ class mmap_flags(IntFlag): ql.mem.map(lbound, mapping_size, info=label) except QlMemoryMappedError: ql.log.debug(f'{api_name}: out of memory') - return -ENOMEM + return -errno_class.ENOMEM.value else: if data: ql.mem.write(addr, data) diff --git a/qiling/os/posix/syscall/msg.py b/qiling/os/posix/syscall/msg.py index 5bfe71fa2..12fbc8ecf 100644 --- a/qiling/os/posix/syscall/msg.py +++ b/qiling/os/posix/syscall/msg.py @@ -2,6 +2,7 @@ from qiling import Qiling from qiling.os.posix.const import * from qiling.os.posix.msq import QlMsqId, QlMsgBuf +from qiling.os.posix.const_mapping import get_errno_class def __find_msg(msq: QlMsqId, msgtyp: int, msgflg: int) -> Optional[QlMsgBuf]: @@ -40,12 +41,14 @@ def __perms(ql: Qiling, msq: QlMsqId, flag: int) -> int: # is there some bit set in requested_mode but not in granted_mode? if request_mode & ~granted_mode & 0o007: - return -EACCES + return -get_errno_class(ql.arch.type, ql.os.type).EACCES.value return 0 def ql_syscall_msgget(ql: Qiling, key: int, msgflg: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + def __create_msq(key: int, flags: int) -> int: """Create a new message queue for the specified key. @@ -53,7 +56,7 @@ def __create_msq(key: int, flags: int) -> int: """ if len(ql.os.msq) >= MSGMNI: - return -ENOSPC + return -errno_class.ENOSPC.value mode = flags & ((1 << 9) - 1) @@ -77,29 +80,31 @@ def __create_msq(key: int, flags: int) -> int: msqid = __create_msq(key, msgflg) else: - return -ENOENT + return -errno_class.ENOENT.value # a message queue with the specified key exists else: # the user asked to create a new one? if msgflg & (IPC_CREAT | IPC_EXCL): - return -EEXIST + return -errno_class.EEXIST.value if __perms(ql, msq, msgflg): - return -EACCES + return -errno_class.EACCES.value return msqid def ql_syscall_msgsnd(ql: Qiling, msqid: int, msgp: int, msgsz: int, msgflg: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + msq = ql.os.msq.get_by_id(msqid) if msq is None: - return -EINVAL + return -errno_class.EINVAL.value # Check if the user has write permissions for the message queue if __perms(ql, msq, 0o222): # S_IWUGO - return -EACCES + return -errno_class.EACCES.value msg_type = ql.mem.read_ptr(msgp) msg_text = ql.mem.read(msgp + ql.arch.pointersize, msgsz) @@ -109,7 +114,7 @@ def ql_syscall_msgsnd(ql: Qiling, msqid: int, msgp: int, msgsz: int, msgflg: int break if msgflg & IPC_NOWAIT: - return -EAGAIN + return -errno_class.EAGAIN.value msq.queue.append(QlMsgBuf(msg_type, bytes(msg_text))) @@ -117,18 +122,20 @@ def ql_syscall_msgsnd(ql: Qiling, msqid: int, msgp: int, msgsz: int, msgflg: int def ql_syscall_msgrcv(ql: Qiling, msqid: int, msgp: int, msgsz: int, msgtyp: int, msgflg: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + msq = ql.os.msq.get_by_id(msqid) if msq is None: - return -EINVAL + return -errno_class.EINVAL.value if msgflg & MSG_COPY: if msgflg & MSG_EXCEPT or not (msgflg & IPC_NOWAIT): - return -EINVAL + return -errno_class.EINVAL.value # Check if the user has read permissions for the message queue if __perms(ql, msq, 0o444): # S_IRUGO - return -EACCES + return -errno_class.EACCES.value while True: msg = __find_msg(msq, msgtyp, msgflg) @@ -137,17 +144,17 @@ def ql_syscall_msgrcv(ql: Qiling, msqid: int, msgp: int, msgsz: int, msgtyp: int break if msgflg & MSG_COPY: - return -ENOMSG + return -errno_class.ENOMSG.value if msgflg & IPC_NOWAIT: - return -ENOMSG + return -errno_class.ENOMSG.value if not (msgflg & MSG_COPY): msq.queue.remove(msg) if msgsz < len(msg.mtext): if not (msgflg & MSG_NOERROR): - return -E2BIG + return -errno_class.E2BIG.value else: sz = msgsz else: diff --git a/qiling/os/posix/syscall/prctl.py b/qiling/os/posix/syscall/prctl.py index 6f515d38a..b2ffa3485 100644 --- a/qiling/os/posix/syscall/prctl.py +++ b/qiling/os/posix/syscall/prctl.py @@ -5,7 +5,7 @@ from qiling import Qiling from qiling.arch.x86_const import IA32_FS_BASE_MSR, IA32_GS_BASE_MSR -from qiling.os.posix.const import EINVAL +from qiling.os.posix.const_mapping import get_errno_class def ql_syscall_arch_prctl(ql: Qiling, code: int, addr: int): @@ -30,7 +30,7 @@ def ql_syscall_arch_prctl(ql: Qiling, code: int, addr: int): if code not in handlers: ql.log.debug(f'prctl code {code:#x} not implemented') - return -EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value handlers[code]() diff --git a/qiling/os/posix/syscall/random.py b/qiling/os/posix/syscall/random.py index f0f5cc0a0..35b848fb6 100644 --- a/qiling/os/posix/syscall/random.py +++ b/qiling/os/posix/syscall/random.py @@ -6,11 +6,11 @@ import os from qiling import Qiling -from qiling.os.posix.const import EFAULT +from qiling.os.posix.const_mapping import get_errno_class def ql_syscall_getrandom(ql: Qiling, buf: int, buflen: int, flags: int): if not ql.mem.is_mapped(buf, buflen): - return -EFAULT + return -get_errno_class(ql.arch.type, ql.os.type).EFAULT.value data = os.urandom(buflen) ql.mem.write(buf, data) diff --git a/qiling/os/posix/syscall/resource.py b/qiling/os/posix/syscall/resource.py index 4841758d7..5b451e63d 100644 --- a/qiling/os/posix/syscall/resource.py +++ b/qiling/os/posix/syscall/resource.py @@ -8,6 +8,8 @@ except ImportError: # The library 'resource' does not exist on windows, so provide a dummy shim class DummyResource: + RLIM_INFINITY = -1 + def getrlimit(self, resource): return (-1, -1) def setrlimit(self, resource, rlim): @@ -16,7 +18,10 @@ def setrlimit(self, resource, rlim): import os +from unicorn import UcError + from qiling import Qiling +from qiling.os.posix.const_mapping import ql_errno_mapping, get_errno_class def __getrlimit_common(ql: Qiling, res: int, rlim: int) -> int: RLIMIT_STACK = 3 @@ -51,24 +56,43 @@ def ql_syscall_setrlimit(ql: Qiling, res: int, rlim: int): return 0 def ql_syscall_prlimit64(ql: Qiling, pid: int, res: int, new_limit: int, old_limit: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + # setrlimit() and getrlimit() if pid == 0 and new_limit == 0: try: rlim = resource.getrlimit(res) + except (ValueError, OverflowError): + return -errno_class.EINVAL.value + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) + + # struct rlimit64 holds two 64-bit fields; the guest expects all ones for unlimited + rlim = [-1 if v == resource.RLIM_INFINITY else v for v in rlim] - ql.mem.write_ptr(old_limit + 0 * ql.arch.pointersize, rlim[0], signed=True) - ql.mem.write_ptr(old_limit + 1 * ql.arch.pointersize, rlim[1], signed=True) + try: + ql.mem.write_ptr(old_limit + 0, rlim[0], 8, signed=True) + ql.mem.write_ptr(old_limit + 8, rlim[1], 8, signed=True) + except UcError: + return -errno_class.EFAULT.value - return 0 - except: - return -1 + return 0 # set other process which pid != 0 return -1 def ql_syscall_getpriority(ql: Qiling, which: int, who: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + + # not available on all hosting platforms (e.g. Windows) + if not hasattr(os, 'getpriority'): + return -errno_class.EOPNOTSUPP.value + try: regreturn = os.getpriority(which, who) - except: - regreturn = -1 + except OverflowError: + regreturn = -errno_class.EINVAL.value + except OSError as ex: + regreturn = -ql_errno_mapping(ql, ex.errno) + return regreturn diff --git a/qiling/os/posix/syscall/sendfile.py b/qiling/os/posix/syscall/sendfile.py index fa8656e1c..c3d59e5f8 100644 --- a/qiling/os/posix/syscall/sendfile.py +++ b/qiling/os/posix/syscall/sendfile.py @@ -6,7 +6,8 @@ from __future__ import annotations from typing import TYPE_CHECKING, IO, Optional -from qiling.os.posix.const import EBADF, NR_OPEN +from qiling.os.posix.const import NR_OPEN +from qiling.os.posix.const_mapping import get_errno_class if TYPE_CHECKING: @@ -21,14 +22,16 @@ def ql_syscall_sendfile64(ql: Qiling, out_fd: int, in_fd: int, offset: int, coun def ql_syscall_sendfile(ql: Qiling, out_fd: int, in_fd: int, offset: int, count: int): # https://man7.org/linux/man-pages/man2/sendfile.2.html + errno_class = get_errno_class(ql.arch.type, ql.os.type) + if in_fd not in range(NR_OPEN) or out_fd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value ifile: Optional[IO] = ql.os.fd[in_fd] ofile: Optional[IO] = ql.os.fd[out_fd] if ifile is None or ofile is None: - return -EBADF + return -errno_class.EBADF.value if offset: ifile_pos = ifile.tell() diff --git a/qiling/os/posix/syscall/shm.py b/qiling/os/posix/syscall/shm.py index 5578feeae..ec198fad8 100644 --- a/qiling/os/posix/syscall/shm.py +++ b/qiling/os/posix/syscall/shm.py @@ -9,10 +9,12 @@ from qiling.const import QL_ARCH from qiling.exception import QlMemoryMappedError from qiling.os.posix.const import * +from qiling.os.posix.const_mapping import get_errno_class from qiling.os.posix.shm import QlShmId def ql_syscall_shmget(ql: Qiling, key: int, size: int, shmflg: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) def __create_shm(key: int, size: int, flags: int) -> int: """Create a new shared memory segment for the specified key. @@ -21,7 +23,7 @@ def __create_shm(key: int, size: int, flags: int) -> int: """ if len(ql.os.shm) >= SHMMNI: - return -ENOSPC + return -errno_class.ENOSPC.value mode = flags & ((1 << 9) - 1) @@ -54,13 +56,13 @@ def __create_shm(key: int, size: int, flags: int) -> int: shmid = __create_shm(key, size, shmflg) else: - return -ENOENT + return -errno_class.ENOENT.value # a shm with the specified key exists else: # the user asked to create a new one? if shmflg & (IPC_CREAT | IPC_EXCL): - return -EEXIST + return -errno_class.EEXIST.value # check whether the user has permissions to access this shm # FIXME: should probably use ql.os.cuid instead, but we don't support it yet @@ -68,17 +70,19 @@ def __create_shm(key: int, size: int, flags: int) -> int: return shmid else: - return -EACCES + return -errno_class.EACCES.value return shmid def ql_syscall_shmat(ql: Qiling, shmid: int, shmaddr: int, shmflg: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + shm = ql.os.shm.get_by_id(shmid) # a shm with the specified key does not exist if shm is None: - return -EINVAL + return -errno_class.EINVAL.value if shmaddr == 0: # system may choose any suitable page-aligned address @@ -100,7 +104,7 @@ def ql_syscall_shmat(ql: Qiling, shmid: int, shmaddr: int, shmflg: int): else: # shmaddr is expected to be aligned if shmaddr & (ql.mem.pagesize - 1): - return -EINVAL + return -errno_class.EINVAL.value attaddr = shmaddr @@ -114,11 +118,11 @@ def ql_syscall_shmat(ql: Qiling, shmid: int, shmaddr: int, shmflg: int): # user asked to attached the seg as readable; is it allowed? if (perms & UC_PROT_READ) and not (shm.mode & SHM_R): - return -EACCES + return -errno_class.EACCES.value # user asked to attached the seg as writable; is it allowed? if (perms & UC_PROT_WRITE) and not (shm.mode & SHM_W): - return -EACCES + return -errno_class.EACCES.value # TODO: if segment is already attached, there is no need to map another memory for it. # if we do, data changes will not be reflected between the segment attachments. we could @@ -129,7 +133,7 @@ def ql_syscall_shmat(ql: Qiling, shmid: int, shmaddr: int, shmflg: int): # attach the segment at shmaddr ql.mem.map(attaddr, shm.segsz, perms, '[shm]') except QlMemoryMappedError: - return -EINVAL + return -errno_class.EINVAL.value # track attachment shm.attach.append(attaddr) @@ -143,7 +147,7 @@ def ql_syscall_shmdt(ql: Qiling, shmaddr: int): shm = ql.os.shm.get_by_attaddr(shmaddr) if shm is None: - return -EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value shm.attach.remove(shmaddr) diff --git a/qiling/os/posix/syscall/signal.py b/qiling/os/posix/syscall/signal.py index 1591cb558..aca117252 100644 --- a/qiling/os/posix/syscall/signal.py +++ b/qiling/os/posix/syscall/signal.py @@ -11,6 +11,7 @@ from qiling.const import QL_ARCH from qiling.os import struct from qiling.os.posix.const import NSIG +from qiling.os.posix.const_mapping import get_errno_class # TODO: MIPS differs in too many details around signals; MIPS implementation is better extracted out @@ -122,7 +123,7 @@ def ql_syscall_rt_sigaction(ql: Qiling, signum: int, act: int, oldact: int): SIGSTOP = 23 if ql.arch.type is QL_ARCH.MIPS else 19 if signum not in range(NSIG) or signum in (SIGKILL, SIGSTOP): - return -1 # EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value sigaction = __make_sigaction(ql.arch) @@ -161,7 +162,7 @@ def __sigprocmask(ql: Qiling, how: int, newset: int, oldset: int): ql.os.blocked_signals = set_mask else: - return -1 # EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value # silently drop attempts to block SIGKILL and SIGSTOP ql.os.blocked_signals &= ~((1 << SIGKILL) | (1 << SIGSTOP)) diff --git a/qiling/os/posix/syscall/socket.py b/qiling/os/posix/syscall/socket.py index ea6ee93ba..4349fe929 100644 --- a/qiling/os/posix/syscall/socket.py +++ b/qiling/os/posix/syscall/socket.py @@ -10,8 +10,8 @@ from typing import TYPE_CHECKING, Tuple, Union from qiling.const import QL_ARCH, QL_OS, QL_VERBOSE -from qiling.os.posix.const_mapping import socket_type_mapping, socket_level_mapping, socket_domain_mapping, socket_ip_option_mapping, socket_tcp_option_mapping, socket_option_mapping -from qiling.os.posix.const import NR_OPEN, EMFILE, EBADF, EAFNOSUPPORT, EINVAL, ENOTSOCK +from qiling.os.posix.const_mapping import socket_type_mapping, socket_level_mapping, socket_domain_mapping, socket_ip_option_mapping, socket_tcp_option_mapping, socket_option_mapping, get_errno_class, ql_errno_mapping +from qiling.os.posix.const import NR_OPEN from qiling.os.posix.filestruct import ql_socket from qiling.os.posix.structs import * @@ -166,19 +166,21 @@ def get_opened_socket(os: QlOsPosix, fd: int) -> Union[ql_socket, int]: appropriate error number is returned. """ + errno_class = get_errno_class(os.ql.arch.type, os.type) + # fd out of range? if fd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value sock = os.fd[fd] # not an opened file? if sock is None: - return -EBADF + return -errno_class.EBADF.value # not a socket? if not isinstance(sock, ql_socket): - return -ENOTSOCK + return -errno_class.ENOTSOCK.value return sock @@ -203,9 +205,11 @@ def ql_syscall_socket(ql: Qiling, domain: int, socktype: int, protocol: int): # May raise error: Protocol not supported except OSError as e: ql.log.debug(f'Error opening socket: {e}') - idx = -1 + idx = -ql_errno_mapping(ql, e.errno) else: ql.os.fd[idx] = sock + else: + idx = -get_errno_class(ql.arch.type, ql.os.type).EMFILE.value s_domain = socket_domain_mapping(domain, ql.arch.type, ql.os.type) s_socktype = socket_type_mapping(socktype, ql.arch.type) @@ -220,7 +224,7 @@ def ql_syscall_socketpair(ql: Qiling, domain: int, socktype: int, protocol: int, idx1 = next(unpopulated_fd, -1) idx2 = next(unpopulated_fd, -1) - regreturn = -EMFILE + regreturn = -get_errno_class(ql.arch.type, ql.os.type).EMFILE.value if (idx1 != -1) and (idx2 != -1): # ql_socket.socketpair should use host platform based socket type @@ -235,7 +239,7 @@ def ql_syscall_socketpair(ql: Qiling, domain: int, socktype: int, protocol: int, # May raise error: Protocol not supported except OSError as e: ql.log.debug(f'{e}: {domain=}, {socktype=}, {protocol=}, {sv=}') - regreturn = -1 + regreturn = -ql_errno_mapping(ql, e.errno) else: ql.os.fd[idx1] = sock1 @@ -255,6 +259,8 @@ def ql_syscall_socketpair(ql: Qiling, domain: int, socktype: int, protocol: int, def ql_syscall_connect(ql: Qiling, sockfd: int, addr: int, addrlen: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + sock = get_opened_socket(ql.os, sockfd) if isinstance(sock, int): @@ -269,7 +275,7 @@ def ql_syscall_connect(ql: Qiling, sockfd: int, addr: int, addrlen: int): sockaddr_obj = sockaddr.from_buffer(data) if sock.family != sockaddr_obj.sa_family: - return -1 + return -errno_class.EAFNOSUPPORT.value if sock.family == AF_UNIX: hpath, vpath = ql_unix_socket_path(ql, data[2:]) @@ -299,12 +305,12 @@ def ql_syscall_connect(ql: Qiling, sockfd: int, addr: int, addrlen: int): dest = (host, port) else: - return -EAFNOSUPPORT + return -errno_class.EAFNOSUPPORT.value try: sock.connect(dest) - except (ConnectionError, FileNotFoundError) as ex: - return -ex.errno + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) return 0 @@ -328,12 +334,12 @@ def ql_syscall_getsockopt(ql: Qiling, sockfd: int, level: int, optname: int, opt optlen = min(ql.mem.read_ptr(optlen_addr, 4, signed=True), 1024) if optlen < 0: - return -EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value try: optval = sock.getsockopt(hsock_level, hsock_opt, optlen) except (ConnectionError, OSError) as ex: - return -ex.errno + return -ql_errno_mapping(ql, ex.errno) ql.mem.write(optval_addr, optval) @@ -365,7 +371,7 @@ def ql_syscall_setsockopt(ql: Qiling, sockfd: int, level: int, optname: int, opt try: sock.setsockopt(hsock_level, hsock_opt, optval) except (ConnectionError, OSError) as ex: - return -ex.errno + return -ql_errno_mapping(ql, ex.errno) return 0 @@ -378,8 +384,8 @@ def ql_syscall_shutdown(ql: Qiling, sockfd: int, how: int): try: sock.shutdown(how) - except ConnectionError: - return -1 + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) return 0 @@ -439,12 +445,12 @@ def ql_syscall_bind(ql: Qiling, sockfd: int, addr: int, addrlen: int): dest = (host, port) else: - return -EAFNOSUPPORT + return -get_errno_class(ql.arch.type, ql.os.type).EAFNOSUPPORT.value try: sock.bind(dest) - except (OSError, ConnectionError, FileNotFoundError) as ex: - return -ex.errno + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) return 0 @@ -581,13 +587,15 @@ def ql_syscall_listen(ql: Qiling, sockfd: int, backlog: int): try: sock.listen(backlog) - except ConnectionError as ex: - return -ex.errno + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) return 0 def ql_syscall_accept(ql: Qiling, sockfd: int, addr: int, addrlenptr: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + sock = get_opened_socket(ql.os, sockfd) if isinstance(sock, int): @@ -595,16 +603,16 @@ def ql_syscall_accept(ql: Qiling, sockfd: int, addr: int, addrlenptr: int): try: conn, address = sock.accept() - except ConnectionError: - return -1 + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) if (conn is None) or (address is None): - return -1 + return -errno_class.EAGAIN.value idx = next((i for i in range(NR_OPEN) if ql.os.fd[i] is None), -1) if idx == -1: - return -EMFILE + return -errno_class.EMFILE.value ql.os.fd[idx] = conn @@ -710,8 +718,8 @@ def ql_syscall_recvmsg(ql: Qiling, sockfd: int, msg_addr: int, flags: int): try: # TODO: handle the addr data, ancdata, mflags, addr = sock.recvmsg(msg.msg_namelen, msg.msg_controllen, flags) - except ConnectionError: - return -1 + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) iovec = make_iovec(abits, endian) iovec_addr = msg.msg_iov diff --git a/qiling/os/posix/syscall/stat.py b/qiling/os/posix/syscall/stat.py index 87530d50b..4fd7a7d9c 100644 --- a/qiling/os/posix/syscall/stat.py +++ b/qiling/os/posix/syscall/stat.py @@ -8,9 +8,12 @@ import struct from typing import Callable +from unicorn import UcError + from qiling import Qiling from qiling.const import QL_OS, QL_ARCH, QL_ENDIAN -from qiling.os.posix.const import EIO, NR_OPEN, EBADF, AT_FDCWD, AT_EMPTY_PATH +from qiling.os.posix.const import NR_OPEN, AT_FDCWD, AT_EMPTY_PATH +from qiling.os.posix.const_mapping import ql_errno_mapping, get_errno_class from qiling.os.posix.stat import Stat, Lstat # Caveat: Never use types like ctypes.c_long whose size differs across platforms. @@ -1182,7 +1185,7 @@ def statFamily(ql: Qiling, path: int, ptr: int, name: str, stat_func, struct_fun info = stat_func(real_path) except OSError as e: ql.log.debug(f'{name}("{file_path}", {ptr:#x}) read/write fail') - return -e.errno + return -ql_errno_mapping(ql, e.errno) else: buf = struct_func(ql, info) ql.mem.write(ptr, buf) @@ -1234,7 +1237,7 @@ def ql_syscall_chmod(ql: Qiling, filename: int, mode: int): try: os.chmod(hpath, mode) except OSError as ex: - ret = -ex.errno + ret = -ql_errno_mapping(ql, ex.errno) else: ret = 0 @@ -1244,18 +1247,20 @@ def ql_syscall_chmod(ql: Qiling, filename: int, mode: int): def ql_syscall_fchmod(ql: Qiling, fd: int, mode: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + if fd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value f = ql.os.fd[fd] if f is None: - return -EBADF + return -errno_class.EBADF.value try: os.fchmod(f.fileno(), mode) except OSError as ex: - ret = -ex.errno + ret = -ql_errno_mapping(ql, ex.errno) else: ret = 0 @@ -1270,7 +1275,7 @@ def ql_syscall_fstatat64(ql: Qiling, dirfd: int, path: int, buf_ptr: int, flags: try: stat = Stat(real_path, dirfd) except OSError as ex: - ret = -ex.errno + ret = -ql_errno_mapping(ql, ex.errno) else: buf = pack_stat64_struct(ql, stat) ql.mem.write(buf_ptr, buf) @@ -1285,7 +1290,7 @@ def ql_syscall_newfstatat(ql: Qiling, dirfd: int, path: int, buf: int, flags: in try: stat = Stat(real_path, dirfd) except OSError as ex: - ret = -ex.errno + ret = -ql_errno_mapping(ql, ex.errno) else: data = pack_stat_struct(ql, stat) ql.mem.write(buf, data) @@ -1296,18 +1301,20 @@ def ql_syscall_newfstatat(ql: Qiling, dirfd: int, path: int, buf: int, flags: in def __do_fstat(ql: Qiling, fd: int, buf: int, method: Callable) -> int: + errno_class = get_errno_class(ql.arch.type, ql.os.type) + if fd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value f = ql.os.fd[fd] if f is None or not hasattr(f, "fstat"): - return -EBADF + return -errno_class.EBADF.value try: fstat = f.fstat() - except OSError: - return -EIO + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) if fstat != -1: data = method(ql, fstat) @@ -1440,6 +1447,8 @@ class Statx64EB(ctypes.BigEndianStructure): # int statx(int dirfd, const char *restrict pathname, int flags, # unsigned int mask, struct statx *restrict statxbuf); def ql_syscall_statx(ql: Qiling, dirfd: int, path: int, flags: int, mask: int, buf_ptr: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + is_eb = ql.arch.endian == QL_ENDIAN.EB def statx_convert_timestamp(tv_sec, tv_nsec): @@ -1493,8 +1502,13 @@ def minor(dev): regreturn = 0 - except Exception as e: - regreturn = -1 + except OSError as ex: + regreturn = -ql_errno_mapping(ql, ex.errno) + except UcError: + regreturn = -errno_class.EFAULT.value + except NotImplementedError: + # dir_fd is not supported on all hosting platforms (e.g. Windows) + regreturn = -errno_class.EOPNOTSUPP.value return regreturn @@ -1512,7 +1526,7 @@ def ql_syscall_mknodat(ql: Qiling, dirfd: int, path: int, mode: int, dev: int): try: os.mknod(real_path, mode, dev, dir_fd=dirfd) except OSError as ex: - ret = -ex.errno + ret = -ql_errno_mapping(ql, ex.errno) else: ret = 0 @@ -1531,7 +1545,7 @@ def ql_syscall_mkdir(ql: Qiling, pathname: int, mode: int): try: os.mkdir(hpath, mode) except OSError as ex: - ret = -ex.errno + ret = -ql_errno_mapping(ql, ex.errno) else: ret = 0 @@ -1550,7 +1564,7 @@ def ql_syscall_rmdir(ql: Qiling, pathname: int): try: os.rmdir(hpath) except OSError as ex: - ret = -ex.errno + ret = -ql_errno_mapping(ql, ex.errno) else: ret = 0 @@ -1565,8 +1579,8 @@ def ql_syscall_fstatfs(ql: Qiling, fd: int, buf: int): try: ql.mem.write(buf, data) - except: - regreturn = -1 + except UcError: + regreturn = -get_errno_class(ql.arch.type, ql.os.type).EFAULT.value return regreturn @@ -1576,8 +1590,8 @@ def ql_syscall_statfs(ql: Qiling, path: int, buf: int): try: ql.mem.write(buf, data) - except: - regreturn = -1 + except UcError: + regreturn = -get_errno_class(ql.arch.type, ql.os.type).EFAULT.value return regreturn diff --git a/qiling/os/posix/syscall/syscall.py b/qiling/os/posix/syscall/syscall.py index d269df3bd..4f665b73b 100644 --- a/qiling/os/posix/syscall/syscall.py +++ b/qiling/os/posix/syscall/syscall.py @@ -5,6 +5,7 @@ from qiling import Qiling from qiling.os.posix.const import * +from qiling.os.posix.const_mapping import get_errno_class from .shm import * from .msg import * @@ -19,7 +20,7 @@ def ql_syscall_ipc(ql: Qiling, call: int, first: int, second: int, third: int, p def __call_shmat(*args: int) -> int: if version == 1: - return -EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value return ql_syscall_shmat(ql, args[0], args[3], args[1]) @@ -38,7 +39,7 @@ def __call_msgsnd(*args: int) -> int: def __call_msgrcv(*args: int) -> int: if version == 0: if args[3] == 0: - return -EINVAL + return -get_errno_class(ql.arch.type, ql.os.type).EINVAL.value msgp = ql.mem.read_ptr(args[3]) msgtyp = ql.mem.read_ptr(args[3] + ql.arch.pointersize) @@ -59,7 +60,7 @@ def __call_msgrcv(*args: int) -> int: } if call not in ipc_call: - return -ENOSYS + return -get_errno_class(ql.arch.type, ql.os.type).ENOSYS.value return ipc_call[call](first, second, third, ptr, fifth) diff --git a/qiling/os/posix/syscall/unistd.py b/qiling/os/posix/syscall/unistd.py index 62cb6f61a..464ef1ede 100644 --- a/qiling/os/posix/syscall/unistd.py +++ b/qiling/os/posix/syscall/unistd.py @@ -8,6 +8,7 @@ import os import itertools import pathlib +from stat import S_ISREG from typing import TYPE_CHECKING, IO, Iterator, Optional, Union @@ -15,6 +16,7 @@ from qiling.const import QL_ARCH, QL_OS from qiling.os.posix.filestruct import ql_pipe from qiling.os.posix.const import * +from qiling.os.posix.const_mapping import ql_errno_mapping, get_errno_class from qiling.core_hooks import QlCoreHooks if TYPE_CHECKING: @@ -152,11 +154,13 @@ def ql_syscall_capset(ql: Qiling, hdrp: int, datap: int): def ql_syscall_kill(ql: Qiling, pid: int, sig: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + if sig not in range(NSIG): - return -1 # EINVAL + return -errno_class.EINVAL.value if pid > 0 and pid != ql.os.pid: - return -1 # ESRCH + return -errno_class.ESRCH.value sigaction = ql.os.sig[sig] @@ -190,13 +194,13 @@ def ql_syscall_fsync(ql: Qiling, fd: int): f = get_opened_fd(ql.os, fd) if f is None: - regreturn = -EBADF + regreturn = -get_errno_class(ql.arch.type, ql.os.type).EBADF.value else: try: os.fsync(f.fileno()) - except OSError: - regreturn = -1 + except OSError as ex: + regreturn = -ql_errno_mapping(ql, ex.errno) else: regreturn = 0 @@ -208,8 +212,8 @@ def ql_syscall_fsync(ql: Qiling, fd: int): def ql_syscall_fdatasync(ql: Qiling, fd: int): try: os.fdatasync(ql.os.fd[fd].fileno()) - except OSError: - regreturn = -1 + except OSError as ex: + regreturn = -ql_errno_mapping(ql, ex.errno) else: regreturn = 0 @@ -228,6 +232,8 @@ def virtual_abspath_at(ql: Qiling, vpath: str, dirfd: int) -> Union[int, str]: Returns: the resolved absolute path, or an error code if could not resolve it """ + errno_class = get_errno_class(ql.arch.type, ql.os.type) + if ql.os.path.is_virtual_abspath(vpath): return vpath @@ -249,12 +255,12 @@ def __as_signed(value: int, nbits: int) -> int: f = get_opened_fd(ql.os, dirfd) if f is None or not hasattr(f, 'name'): - return -EBADF + return -errno_class.EBADF.value hpath = f.name if not os.path.isdir(hpath): - return -ENOTDIR + return -errno_class.ENOTDIR.value basedir = ql.os.path.host_to_virtual_path(hpath) @@ -274,7 +280,7 @@ def ql_syscall_faccessat(ql: Qiling, dirfd: int, filename: int, mode: int): if not ql.os.path.is_safe_host_path(hpath): raise PermissionError(f'unsafe path: {hpath}') - regreturn = 0 if os.path.exists(hpath) else -ENOENT + regreturn = 0 if os.path.exists(hpath) else -get_errno_class(ql.arch.type, ql.os.type).ENOENT.value ql.log.debug(f'faccessat({dirfd:d}, "{vpath}", {mode:d}) = {regreturn}') @@ -287,13 +293,13 @@ def ql_syscall_lseek(ql: Qiling, fd: int, offset: int, origin: int): f = get_opened_fd(ql.os, fd) if f is None: - regreturn = -EBADF + regreturn = -get_errno_class(ql.arch.type, ql.os.type).EBADF.value else: try: regreturn = f.seek(offset, origin) - except OSError: - regreturn = -1 + except OSError as ex: + regreturn = -ql_errno_mapping(ql, ex.errno) ql.log.debug(f'lseek({fd:d}, {offset:#x}, {origin}) = {regreturn}') @@ -306,13 +312,13 @@ def ql_syscall__llseek(ql: Qiling, fd: int, offset_high: int, offset_low: int, r f = get_opened_fd(ql.os, fd) if f is None: - regreturn = -EBADF + regreturn = -get_errno_class(ql.arch.type, ql.os.type).EBADF.value else: try: ret = f.seek(offset, whence) - except OSError: - regreturn = -1 + except OSError as ex: + regreturn = -ql_errno_mapping(ql, ex.errno) else: ql.mem.write_ptr(result, ret, 8) regreturn = 0 @@ -347,7 +353,7 @@ def ql_syscall_access(ql: Qiling, path: int, mode: int): if not ql.os.path.is_safe_host_path(hpath): raise PermissionError(f'unsafe path: {hpath}') - regreturn = 0 if os.path.exists(hpath) else -ENOENT + regreturn = 0 if os.path.exists(hpath) else -get_errno_class(ql.arch.type, ql.os.type).ENOENT.value ql.log.debug(f'access("{vpath}", 0{mode:o}) = {regreturn}') @@ -358,7 +364,7 @@ def ql_syscall_close(ql: Qiling, fd: int): f = get_opened_fd(ql.os, fd) if f is None: - regreturn = -EBADF + regreturn = -get_errno_class(ql.arch.type, ql.os.type).EBADF.value else: f.close() @@ -371,13 +377,15 @@ def ql_syscall_close(ql: Qiling, fd: int): def ql_syscall_pread64(ql: Qiling, fd: int, buf: int, length: int, offt: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + f = get_opened_fd(ql.os, fd) if f is None: - return -EBADF + return -errno_class.EBADF.value if not ql.mem.is_mapped(buf, length): - return -EFAULT + return -errno_class.EFAULT.value # https://chromium.googlesource.com/linux-syscall-support/+/2c73abf02fd8af961e38024882b9ce0df6b4d19b # https://chromiumcodereview.appspot.com/10910222 @@ -390,8 +398,8 @@ def ql_syscall_pread64(ql: Qiling, fd: int, buf: int, length: int, offt: int): data = f.read(length) f.seek(pos) - except OSError: - regreturn = -1 + except OSError as ex: + regreturn = -ql_errno_mapping(ql, ex.errno) else: ql.mem.write(buf, data) @@ -401,25 +409,27 @@ def ql_syscall_pread64(ql: Qiling, fd: int, buf: int, length: int, offt: int): def ql_syscall_read(ql: Qiling, fd: int, buf: int, length: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + f = get_opened_fd(ql.os, fd) if f is None: - return -EBADF + return -errno_class.EBADF.value if not ql.mem.is_mapped(buf, length): - return -EFAULT + return -errno_class.EFAULT.value if not hasattr(f, 'read'): ql.log.debug(f'read failed since fd {fd:d} does not have a read method') - return -EBADF + return -errno_class.EBADF.value try: data = f.read(length) except IsADirectoryError: - return -EISDIR + return -errno_class.EISDIR.value except ConnectionError: ql.log.debug('read failed due to a connection error') - return -EIO + return -errno_class.EIO.value ql.mem.write(buf, data) ql.log.debug(f'read() CONTENT: {bytes(data)}') @@ -428,17 +438,19 @@ def ql_syscall_read(ql: Qiling, fd: int, buf: int, length: int): def ql_syscall_write(ql: Qiling, fd: int, buf: int, count: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + f = get_opened_fd(ql.os, fd) if f is None: - return -EBADF + return -errno_class.EBADF.value if not ql.mem.is_mapped(buf, count): - return -EFAULT + return -errno_class.EFAULT.value if not hasattr(f, 'write'): ql.log.debug(f'write failed since fd {fd:d} does not have a write method') - return -EBADF + return -errno_class.EBADF.value data = ql.mem.read(buf, count) @@ -446,7 +458,7 @@ def ql_syscall_write(ql: Qiling, fd: int, buf: int, count: int): f.write(data) except ConnectionError: ql.log.debug('write failed due to a connection error') - return -EIO + return -errno_class.EIO.value ql.log.debug(f'write() CONTENT: {bytes(data)}') @@ -478,7 +490,7 @@ def __do_readlink(ql: Qiling, absvpath: str, outbuf: int) -> int: target = '' if target is None: - return -ENOENT + return -get_errno_class(ql.arch.type, ql.os.type).ENOENT.value cstr = target.encode('utf-8') @@ -536,7 +548,7 @@ def ql_syscall_chdir(ql: Qiling, path_name: int): regreturn = 0 else: - regreturn = -ENOENT + regreturn = -get_errno_class(ql.arch.type, ql.os.type).ENOENT.value ql.log.debug(f'chdir("{absvpath}") = {regreturn}') @@ -585,16 +597,22 @@ def ql_syscall_setsid(ql: Qiling): def ql_syscall_execve(ql: Qiling, pathname: int, argv: int, envp: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + vpath = ql.os.utils.read_cstring(pathname) hpath = ql.os.path.virtual_to_host_path(vpath) # is it safe to run? if not ql.os.path.is_safe_host_path(hpath): - return -1 # EACCES + return -errno_class.EACCES.value + + try: + mode = os.stat(hpath).st_mode + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) - # is it a file? does it exist? - if not os.path.isfile(hpath): - return -1 # EACCES + if not S_ISREG(mode): + return -errno_class.EACCES.value def __read_ptr_array(addr: int) -> Iterator[int]: if addr: @@ -660,15 +678,17 @@ def __read_str_array(addr: int) -> Iterator[str]: def ql_syscall_dup(ql: Qiling, oldfd: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + f = get_opened_fd(ql.os, oldfd) if f is None: - return -EBADF + return -errno_class.EBADF.value newfd = next((i for i in range(NR_OPEN) if ql.os.fd[i] is None), -1) if newfd == -1: - return -EMFILE + return -errno_class.EMFILE.value ql.os.fd[newfd] = f.dup() @@ -678,13 +698,15 @@ def ql_syscall_dup(ql: Qiling, oldfd: int): def ql_syscall_dup2(ql: Qiling, oldfd: int, newfd: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + f = get_opened_fd(ql.os, oldfd) if f is None: - return -EBADF + return -errno_class.EBADF.value if newfd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value newslot = ql.os.fd[newfd] @@ -699,18 +721,20 @@ def ql_syscall_dup2(ql: Qiling, oldfd: int, newfd: int): def ql_syscall_dup3(ql: Qiling, oldfd: int, newfd: int, flags: int): + errno_class = get_errno_class(ql.arch.type, ql.os.type) + O_CLOEXEC = 0o2000000 if oldfd == newfd: - return -EINVAL + return -errno_class.EINVAL.value f = get_opened_fd(ql.os, oldfd) if f is None: - return -EBADF + return -errno_class.EBADF.value if newfd not in range(NR_OPEN): - return -EBADF + return -errno_class.EBADF.value newslot = ql.os.fd[newfd] @@ -746,7 +770,7 @@ def ql_syscall_pipe(ql: Qiling, pipefd: int): idx2 = next(unpopulated_fd, -1) if (idx1 == -1) or (idx2 == -1): - return -EMFILE + return -get_errno_class(ql.arch.type, ql.os.type).EMFILE.value ql.os.fd[idx1] = rd ql.os.fd[idx2] = wd @@ -781,8 +805,8 @@ def __do_truncate(ql: Qiling, hpath: str, length: int) -> int: with open(hpath, 'a+b') as ofile: ofile.write(b'\x00' * padding) - except OSError: - return -1 + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) else: return 0 @@ -801,7 +825,11 @@ def ql_syscall_truncate(ql: Qiling, path: int, length: int): def ql_syscall_ftruncate(ql: Qiling, fd: int, length: int): f = get_opened_fd(ql.os, fd) - regreturn = -EBADF if f is None else __do_truncate(ql, f.name, length) + if f is None: + regreturn = -get_errno_class(ql.arch.type, ql.os.type).EBADF.value + + else: + regreturn = __do_truncate(ql, f.name, length) ql.log.debug(f'ftruncate({fd}, {length:#x}) = {regreturn}') @@ -809,6 +837,7 @@ def ql_syscall_ftruncate(ql: Qiling, fd: int, length: int): def __do_unlink(ql: Qiling, absvpath: str) -> int: + errno_class = get_errno_class(ql.arch.type, ql.os.type) def __has_opened_fd(hpath: str) -> bool: opened_fds = (ql.os.fd[i] for i in range(NR_OPEN) if ql.os.fd[i] is not None) @@ -820,7 +849,7 @@ def __has_opened_fd(hpath: str) -> bool: if ql.os.fs_mapper.has_mapping(absvpath): if __has_opened_fd(hpath): - return -1 + return -errno_class.EBUSY.value ql.os.fs_mapper.remove_mapping(absvpath) @@ -835,12 +864,12 @@ def __ok_to_remove(hpath: str) -> bool: return any((path.is_block_device(), path.is_fifo(), path.is_socket(), path.is_symlink())) if __has_opened_fd(hpath) and not __ok_to_remove(hpath): - return -1 + return -errno_class.EBUSY.value try: os.unlink(hpath) - except OSError: - return -1 + except OSError as ex: + return -ql_errno_mapping(ql, ex.errno) return 0 diff --git a/qiling/os/posix/syscall/wait.py b/qiling/os/posix/syscall/wait.py index a936e3b54..0af1e2c0a 100644 --- a/qiling/os/posix/syscall/wait.py +++ b/qiling/os/posix/syscall/wait.py @@ -6,7 +6,7 @@ import os from qiling import Qiling -from qiling.os.posix.const import ECHILD +from qiling.os.posix.const_mapping import get_errno_class def ql_syscall_wait4(ql: Qiling, pid: int, wstatus: int, options: int, rusage: int): pid = ql.os.utils.as_signed(pid, 32) @@ -15,7 +15,7 @@ def ql_syscall_wait4(ql: Qiling, pid: int, wstatus: int, options: int, rusage: i try: spid, status, _ = os.wait4(pid, options) except ChildProcessError: - return -ECHILD + return -get_errno_class(ql.arch.type, ql.os.type).ECHILD.value if wstatus: ql.mem.write_ptr(wstatus, status, 4) diff --git a/tests/test_elf.py b/tests/test_elf.py index 26f453a5c..a2e8891c9 100644 --- a/tests/test_elf.py +++ b/tests/test_elf.py @@ -867,6 +867,45 @@ def test_linux_statx_bigendian(self): del ql + # Regression for failed syscalls reporting EPERM: a handler that fails on the + # host must return the matching emulated errno rather than a bare -1, which + # libc reads as EPERM (e.g. musl gives up searching its library paths unless + # open fails with ENOENT). + def test_linux_errno_from_host_error(self): + import tempfile + from qiling.os.posix.syscall.unistd import ql_syscall_unlink + + with tempfile.TemporaryDirectory() as rootfs: + ql = Qiling(code=b"\xCC", archtype=QL_ARCH.X8664, ostype=QL_OS.LINUX, + rootfs=rootfs, verbose=QL_VERBOSE.OFF) + + base = 0x100000 + ql.mem.map(base, 0x1000) + ql.mem.write(base, b"/missing\x00") + + ENOENT = 2 + self.assertEqual(ql_syscall_unlink(ql, base), -ENOENT) + + del ql + + # Errno values are not the same on all architectures: MIPS uses its own + # numbering (ENOSYS = 89, not the generic 38). Handlers used to return the + # generic value to every guest. + def test_linux_errno_mips(self): + from qiling.const import QL_ENDIAN + from qiling.os.posix.syscall.syscall import ql_syscall_ipc + + ENOSYS = {QL_ARCH.X8664: 38, QL_ARCH.MIPS: 89} + + for archtype, endian in ((QL_ARCH.X8664, QL_ENDIAN.EL), (QL_ARCH.MIPS, QL_ENDIAN.EB)): + ql = Qiling(code=b"\x00\x00\x00\x00", archtype=archtype, ostype=QL_OS.LINUX, + endian=endian, verbose=QL_VERBOSE.OFF) + + # an unknown ipc call is not implemented + self.assertEqual(ql_syscall_ipc(ql, 0xffff, 0, 0, 0, 0, 0), -ENOSYS[archtype]) + + del ql + def test_memory_search(self): ql = Qiling(code=b"\xCC", archtype=QL_ARCH.X8664, ostype=QL_OS.LINUX, verbose=QL_VERBOSE.DEBUG)