path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/third_party/python/Python/mysnprintf.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/fmt/fmt.h" #include "third_party/python/Include/pyerrors.h" /* clang-format off */ /* snprintf() wrappers. If the platform has vsnprintf, we use it, else we emulate it in a half-hearted way. Even if the platform has it, we wrap it because platforms differ in what vsnprintf does in case the buffer is too small: C99 behavior is to return the number of characters that would have been written had the buffer not been too small, and to set the last byte of the buffer to \0. At least MS _vsnprintf returns a negative value instead, and fills the entire buffer with non-\0 data. The wrappers ensure that str[size-1] is always \0 upon return. PyOS_snprintf and PyOS_vsnprintf never write more than size bytes (including the trailing '\0') into str. If the platform doesn't have vsnprintf, and the buffer size needed to avoid truncation exceeds size by more than 512, Python aborts with a Py_FatalError. Return value (rv): When 0 <= rv < size, the output conversion was unexceptional, and rv characters were written to str (excluding a trailing \0 byte at str[rv]). When rv >= size, output conversion was truncated, and a buffer of size rv+1 would have been needed to avoid truncation. str[size-1] is \0 in this case. When rv < 0, "something bad happened". str[size-1] is \0 in this case too, but the rest of str is unreliable. It could be that an error in format codes was detected by libc, or on platforms with a non-C99 vsnprintf simply that the buffer wasn't big enough to avoid truncation, or on platforms without any vsnprintf that PyMem_Malloc couldn't obtain space for a temp buffer. CAUTION: Unlike C99, str != NULL and size > 0 are required. */ int PyOS_snprintf(char *str, size_t size, const char *format, ...) { int rc; va_list va; va_start(va, format); rc = PyOS_vsnprintf(str, size, format, va); va_end(va); return rc; } int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) { int len; /* # bytes written, excluding \0 */ #ifdef HAVE_SNPRINTF #define _PyOS_vsnprintf_EXTRA_SPACE 1 #else #define _PyOS_vsnprintf_EXTRA_SPACE 512 char *buffer; #endif assert(str != NULL); assert(size > 0); assert(format != NULL); /* We take a size_t as input but return an int. Sanity check * our input so that it won't cause an overflow in the * vsnprintf return value or the buffer malloc size. */ if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) { len = -666; goto Done; } #ifdef HAVE_SNPRINTF len = vsnprintf(str, size, format, va); #else /* Emulate it. */ buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE); if (buffer == NULL) { len = -666; goto Done; } len = vsprintf(buffer, format, va); if (len < 0) /* ignore the error */; else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE) Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf"); else { const size_t to_copy = (size_t)len < size ? (size_t)len : size - 1; assert(to_copy < size); memcpy(str, buffer, to_copy); str[to_copy] = '\0'; } PyMem_FREE(buffer); #endif Done: if (size > 0) str[size-1] = '\0'; return len; #undef _PyOS_vsnprintf_EXTRA_SPACE }
4,259
113
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/fileutils.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/nt/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/fio.h" #include "libc/sysv/consts/o.h" #include "libc/str/locale.h" #include "libc/str/unicode.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/osdefs.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ wchar_t* _Py_DecodeUTF8_surrogateescape(const char *, Py_ssize_t); int _Py_open_cloexec_works = 1; PyObject * _Py_device_encoding(int fd) { #if defined(MS_WINDOWS) UINT cp; #endif int valid; _Py_BEGIN_SUPPRESS_IPH valid = isatty(fd); _Py_END_SUPPRESS_IPH if (!valid) Py_RETURN_NONE; #if defined(MS_WINDOWS) if (fd == 0) cp = GetConsoleCP(); else if (fd == 1 || fd == 2) cp = GetConsoleOutputCP(); else cp = 0; /* GetConsoleCP() and GetConsoleOutputCP() return 0 if the application has no console */ if (cp != 0) return PyUnicode_FromFormat("cp%u", (unsigned int)cp); #elif defined(CODESET) { char *codeset = nl_langinfo(CODESET); if (codeset != NULL && codeset[0] != 0) return PyUnicode_FromString(codeset); } #endif Py_RETURN_NONE; } static wchar_t* decode_current_locale(const char* arg, size_t *size) { wchar_t *res; size_t argsize; size_t count; unsigned char *in; wchar_t *out; mbstate_t mbs; argsize = mbstowcs(NULL, arg, 0); if (argsize != (size_t)-1) { if (argsize == PY_SSIZE_T_MAX) goto oom; argsize += 1; if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t)) goto oom; res = (wchar_t *)PyMem_RawMalloc(argsize*sizeof(wchar_t)); if (!res) goto oom; count = mbstowcs(res, arg, argsize); if (count != (size_t)-1) { wchar_t *tmp; /* Only use the result if it contains no surrogate characters. */ for (tmp = res; *tmp != 0 && !Py_UNICODE_IS_SURROGATE(*tmp); tmp++) ; if (*tmp == 0) { if (size != NULL) *size = count; return res; } } PyMem_RawFree(res); } /* Conversion failed. Fall back to escaping with surrogateescape. */ /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ /* Overallocate; as multi-byte characters are in the argument, the actual output could use less memory. */ argsize = strlen(arg) + 1; if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t)) goto oom; res = (wchar_t*)PyMem_RawMalloc(argsize*sizeof(wchar_t)); if (!res) goto oom; in = (unsigned char*)arg; out = res; bzero(&mbs, sizeof mbs); while (argsize) { size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); if (converted == 0) /* Reached end of string; null char stored. */ break; if (converted == (size_t)-2) { /* Incomplete character. This should never happen, since we provide everything that we have - unless there is a bug in the C library, or I misunderstood how mbrtowc works. */ PyMem_RawFree(res); if (size != NULL) *size = (size_t)-2; return NULL; } if (converted == (size_t)-1) { /* Conversion error. Escape as UTF-8b, and start over in the initial shift state. */ *out++ = 0xdc00 + *in++; argsize--; bzero(&mbs, sizeof mbs); continue; } if (Py_UNICODE_IS_SURROGATE(*out)) { /* Surrogate character. Escape the original byte sequence with surrogateescape. */ argsize -= converted; while (converted--) *out++ = 0xdc00 + *in++; continue; } /* successfully converted some bytes */ in += converted; argsize -= converted; out++; } if (size != NULL) *size = out - res; return res; oom: if (size != NULL) *size = (size_t)-1; return NULL; } static wchar_t* decode_locale(const char* arg, size_t *size, int current_locale) { if (current_locale) { return decode_current_locale(arg, size); } wchar_t *wstr; wstr = _Py_DecodeUTF8_surrogateescape(arg, strlen(arg)); if (size != NULL) { if (wstr != NULL) *size = wcslen(wstr); else *size = (size_t)-1; } return wstr; } /* Decode a byte string from the locale encoding with the surrogateescape error handler: undecodable bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate character, escape the bytes using the surrogateescape error handler instead of decoding them. Return a pointer to a newly allocated wide character string, use PyMem_RawFree() to free the memory. If size is not NULL, write the number of wide characters excluding the null character into *size Return NULL on decoding error or memory allocation error. If *size* is not NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on decoding error. Decoding errors should never happen, unless there is a bug in the C library. Use the Py_EncodeLocale() function to encode the character string back to a byte string. */ wchar_t* Py_DecodeLocale(const char* arg, size_t *size) { return decode_locale(arg, size, 0); } wchar_t* _Py_DecodeLocaleEx(const char* arg, size_t *size, int current_locale) { return decode_locale(arg, size, current_locale); } static char* encode_current_locale(const wchar_t *text, size_t *error_pos) { const size_t len = wcslen(text); char *result = NULL, *bytes = NULL; size_t i, size, converted; wchar_t c, buf[2]; /* The function works in two steps: 1. compute the length of the output buffer in bytes (size) 2. outputs the bytes */ size = 0; buf[1] = 0; while (1) { for (i=0; i < len; i++) { c = text[i]; if (c >= 0xdc80 && c <= 0xdcff) { /* UTF-8b surrogate */ if (bytes != NULL) { *bytes++ = c - 0xdc00; size--; } else size++; continue; } else { buf[0] = c; if (bytes != NULL) converted = wcstombs(bytes, buf, size); else converted = wcstombs(NULL, buf, 0); if (converted == (size_t)-1) { if (result != NULL) PyMem_Free(result); if (error_pos != NULL) *error_pos = i; return NULL; } if (bytes != NULL) { bytes += converted; size -= converted; } else size += converted; } } if (result != NULL) { *bytes = '\0'; break; } size += 1; /* nul byte at the end */ result = PyMem_Malloc(size); if (result == NULL) { if (error_pos != NULL) *error_pos = (size_t)-1; return NULL; } bytes = result; } return result; } static char* encode_locale(const wchar_t *text, size_t *error_pos, int current_locale) { if (current_locale) { return encode_current_locale(text, error_pos); } Py_ssize_t len; PyObject *unicode, *bytes = NULL; char *cpath; unicode = PyUnicode_FromWideChar(text, wcslen(text)); if (unicode == NULL) return NULL; bytes = _PyUnicode_AsUTF8String(unicode, "surrogateescape"); Py_DECREF(unicode); if (bytes == NULL) { PyErr_Clear(); if (error_pos != NULL) *error_pos = (size_t)-1; return NULL; } len = PyBytes_GET_SIZE(bytes); cpath = PyMem_Malloc(len+1); if (cpath == NULL) { PyErr_Clear(); Py_DECREF(bytes); if (error_pos != NULL) *error_pos = (size_t)-1; return NULL; } memcpy(cpath, PyBytes_AsString(bytes), len + 1); Py_DECREF(bytes); return cpath; } /* Encode a wide character string to the locale encoding with the surrogateescape error handler: surrogate characters in the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF. Return a pointer to a newly allocated byte string, use PyMem_Free() to free the memory. Return NULL on encoding or memory allocation error. If error_pos is not NULL, *error_pos is set to the index of the invalid character on encoding error, or set to (size_t)-1 otherwise. Use the Py_DecodeLocale() function to decode the bytes string back to a wide character string. */ char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos) { return encode_locale(text, error_pos, 0); } char* _Py_EncodeLocaleEx(const wchar_t *text, size_t *error_pos, int current_locale) { return encode_locale(text, error_pos, current_locale); } /* Return information about a file. On POSIX, use fstat(). On Windows, use GetFileType() and GetFileInformationByHandle() which support files larger than 2 GB. fstat() may fail with EOVERFLOW on files larger than 2 GB because the file size type is a signed 32-bit integer: see issue #23152. On Windows, set the last Windows error and return nonzero on error. On POSIX, set errno and return nonzero on error. Fill status and return 0 on success. */ int _Py_fstat_noraise(int fd, struct _Py_stat_struct *status) { return fstat(fd, status); } /* Return information about a file. On POSIX, use fstat(). On Windows, use GetFileType() and GetFileInformationByHandle() which support files larger than 2 GB. fstat() may fail with EOVERFLOW on files larger than 2 GB because the file size type is a signed 32-bit integer: see issue #23152. Raise an exception and return -1 on error. On Windows, set the last Windows error on error. On POSIX, set errno on error. Fill status and return 0 on success. Release the GIL to call GetFileType() and GetFileInformationByHandle(), or to call fstat(). The caller must hold the GIL. */ int _Py_fstat(int fd, struct _Py_stat_struct *status) { int res; #ifdef WITH_THREAD assert(PyGILState_Check()); #endif Py_BEGIN_ALLOW_THREADS res = _Py_fstat_noraise(fd, status); Py_END_ALLOW_THREADS if (res != 0) { PyErr_SetFromErrno(PyExc_OSError); return -1; } return 0; } /* Call _wstat() on Windows, or encode the path to the filesystem encoding and call stat() otherwise. Only fill st_mode attribute on Windows. Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was raised. */ int _Py_stat(PyObject *path, struct stat *statbuf) { int ret; PyObject *bytes; char *cpath; bytes = PyUnicode_EncodeFSDefault(path); if (bytes == NULL) return -2; /* check for embedded null bytes */ if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) { Py_DECREF(bytes); return -2; } ret = stat(cpath, statbuf); Py_DECREF(bytes); return ret; } /* This function MUST be kept async-signal-safe on POSIX when raise=0. */ static int get_inheritable(int fd, int raise) { int flags; flags = fcntl(fd, F_GETFD, 0); if (flags == -1) { if (raise) PyErr_SetFromErrno(PyExc_OSError); return -1; } return !(flags & FD_CLOEXEC); } /* Get the inheritable flag of the specified file descriptor. Return 1 if the file descriptor can be inherited, 0 if it cannot, raise an exception and return -1 on error. */ int _Py_get_inheritable(int fd) { return get_inheritable(fd, 1); } /* This function MUST be kept async-signal-safe on POSIX when raise=0. */ static int set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works) { static int ioctl_works = -1; int res, err, flags, new_flags; /* atomic_flag_works can only be used to make the file descriptor non-inheritable */ assert(!(atomic_flag_works != NULL && inheritable)); if (atomic_flag_works != NULL && !inheritable) { if (*atomic_flag_works == -1) { int isInheritable = get_inheritable(fd, raise); if (isInheritable == -1) return -1; *atomic_flag_works = !isInheritable; } if (*atomic_flag_works) return 0; } if (ioctl_works != 0 && raise != 0) { /* fast-path: ioctl() only requires one syscall */ /* caveat: raise=0 is an indicator that we must be async-signal-safe * thus avoid using ioctl() so we skip the fast-path. */ if (inheritable) err = ioctl(fd, FIONCLEX, NULL); else err = ioctl(fd, FIOCLEX, NULL); if (!err) { ioctl_works = 1; return 0; } if (errno != ENOTTY && errno != EACCES) { if (raise) PyErr_SetFromErrno(PyExc_OSError); return -1; } else { /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for device". The ioctl is declared but not supported by the kernel. Remember that ioctl() doesn't work. It is the case on Illumos-based OS for example. Issue #27057: When SELinux policy disallows ioctl it will fail with EACCES. While FIOCLEX is safe operation it may be unavailable because ioctl was denied altogether. This can be the case on Android. */ ioctl_works = 0; } /* fallback to fcntl() if ioctl() does not work */ } /* slow-path: fcntl() requires two syscalls */ flags = fcntl(fd, F_GETFD); if (flags < 0) { if (raise) PyErr_SetFromErrno(PyExc_OSError); return -1; } if (inheritable) { new_flags = flags & ~FD_CLOEXEC; } else { new_flags = flags | FD_CLOEXEC; } if (new_flags == flags) { /* FD_CLOEXEC flag already set/cleared: nothing to do */ return 0; } res = fcntl(fd, F_SETFD, new_flags); if (res < 0) { if (raise) PyErr_SetFromErrno(PyExc_OSError); return -1; } return 0; } /* Make the file descriptor non-inheritable. Return 0 on success, set errno and return -1 on error. */ static int make_non_inheritable(int fd) { return set_inheritable(fd, 0, 0, NULL); } /* Set the inheritable flag of the specified file descriptor. On success: return 0, on error: raise an exception and return -1. If atomic_flag_works is not NULL: * if *atomic_flag_works==-1, check if the inheritable is set on the file descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and set the inheritable flag * if *atomic_flag_works==1: do nothing * if *atomic_flag_works==0: set inheritable flag to False Set atomic_flag_works to NULL if no atomic flag was used to create the file descriptor. atomic_flag_works can only be used to make a file descriptor non-inheritable: atomic_flag_works must be NULL if inheritable=1. */ int _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works) { return set_inheritable(fd, inheritable, 1, atomic_flag_works); } /* Same as _Py_set_inheritable() but on error, set errno and don't raise an exception. This function is async-signal-safe. */ int _Py_set_inheritable_async_safe(int fd, int inheritable, int *atomic_flag_works) { return set_inheritable(fd, inheritable, 0, atomic_flag_works); } static int _Py_open_impl(const char *pathname, int flags, int gil_held) { int fd; int async_err = 0; int *atomic_flag_works; atomic_flag_works = &_Py_open_cloexec_works; flags |= O_CLOEXEC; if (gil_held) { do { Py_BEGIN_ALLOW_THREADS fd = open(pathname, flags); Py_END_ALLOW_THREADS } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals())); if (async_err) return -1; if (fd < 0) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname); return -1; } } else { fd = open(pathname, flags); if (fd < 0) return -1; } if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) { close(fd); return -1; } return fd; } /* Open a file with the specified flags (wrapper to open() function). Return a file descriptor on success. Raise an exception and return -1 on error. The file descriptor is created non-inheritable. When interrupted by a signal (open() fails with EINTR), retry the syscall, except if the Python signal handler raises an exception. Release the GIL to call open(). The caller must hold the GIL. */ int _Py_open(const char *pathname, int flags) { #ifdef WITH_THREAD /* _Py_open() must be called with the GIL held. */ assert(PyGILState_Check()); #endif return _Py_open_impl(pathname, flags, 1); } /* Open a file with the specified flags (wrapper to open() function). Return a file descriptor on success. Set errno and return -1 on error. The file descriptor is created non-inheritable. If interrupted by a signal, fail with EINTR. */ int _Py_open_noraise(const char *pathname, int flags) { return _Py_open_impl(pathname, flags, 0); } /* Open a file. Use _wfopen() on Windows, encode the path to the locale encoding and use fopen() otherwise. The file descriptor is created non-inheritable. If interrupted by a signal, fail with EINTR. */ FILE * _Py_wfopen(const wchar_t *path, const wchar_t *mode) { FILE *f; char *cpath; char cmode[10]; size_t r; r = wcstombs(cmode, mode, 10); if (r == (size_t)-1 || r >= 10) { errno = EINVAL; return NULL; } cpath = Py_EncodeLocale(path, NULL); if (cpath == NULL) return NULL; f = fopen(cpath, cmode); PyMem_Free(cpath); if (f == NULL) return NULL; if (make_non_inheritable(fileno(f)) < 0) { fclose(f); return NULL; } return f; } /* Wrapper to fopen(). The file descriptor is created non-inheritable. If interrupted by a signal, fail with EINTR. */ FILE* _Py_fopen(const char *pathname, const char *mode) { FILE *f = fopen(pathname, mode); if (f == NULL) return NULL; if (make_non_inheritable(fileno(f)) < 0) { fclose(f); return NULL; } return f; } /* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem encoding and call fopen() otherwise. Return the new file object on success. Raise an exception and return NULL on error. The file descriptor is created non-inheritable. When interrupted by a signal (open() fails with EINTR), retry the syscall, except if the Python signal handler raises an exception. Release the GIL to call _wfopen() or fopen(). The caller must hold the GIL. */ FILE* _Py_fopen_obj(PyObject *path, const char *mode) { FILE *f; int async_err = 0; PyObject *bytes; char *path_bytes; #ifdef WITH_THREAD assert(PyGILState_Check()); #endif if (!PyUnicode_FSConverter(path, &bytes)) return NULL; path_bytes = PyBytes_AS_STRING(bytes); do { Py_BEGIN_ALLOW_THREADS f = fopen(path_bytes, mode); Py_END_ALLOW_THREADS } while (f == NULL && errno == EINTR && !(async_err = PyErr_CheckSignals())); Py_DECREF(bytes); if (async_err) return NULL; if (f == NULL) { PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path); return NULL; } if (set_inheritable(fileno(f), 0, 1, NULL) < 0) { fclose(f); return NULL; } return f; } /* Read count bytes from fd into buf. On success, return the number of read bytes, it can be lower than count. If the current file offset is at or past the end of file, no bytes are read, and read() returns zero. On error, raise an exception, set errno and return -1. When interrupted by a signal (read() fails with EINTR), retry the syscall. If the Python signal handler raises an exception, the function returns -1 (the syscall is not retried). Release the GIL to call read(). The caller must hold the GIL. */ Py_ssize_t _Py_read(int fd, void *buf, size_t count) { Py_ssize_t n; int err; int async_err = 0; #ifdef WITH_THREAD assert(PyGILState_Check()); #endif /* _Py_read() must not be called with an exception set, otherwise the * caller may think that read() was interrupted by a signal and the signal * handler raised an exception. */ assert(!PyErr_Occurred()); if (count > _PY_READ_MAX) { count = _PY_READ_MAX; } _Py_BEGIN_SUPPRESS_IPH do { Py_BEGIN_ALLOW_THREADS errno = 0; n = read(fd, buf, count); /* save/restore errno because PyErr_CheckSignals() * and PyErr_SetFromErrno() can modify it */ err = errno; Py_END_ALLOW_THREADS } while (n < 0 && err == EINTR && !(async_err = PyErr_CheckSignals())); _Py_END_SUPPRESS_IPH if (async_err) { /* read() was interrupted by a signal (failed with EINTR) * and the Python signal handler raised an exception */ errno = err; assert(errno == EINTR && PyErr_Occurred()); return -1; } if (n < 0) { PyErr_SetFromErrno(PyExc_OSError); errno = err; return -1; } return n; } static Py_ssize_t _Py_write_impl(int fd, const void *buf, size_t count, int gil_held) { Py_ssize_t n; int err; int async_err = 0; _Py_BEGIN_SUPPRESS_IPH if (IsWindows() && count > 32767 && isatty(fd)) { /* Issue #11395: the Windows console returns an error (12: not enough space error) on writing into stdout if stdout mode is binary and the length is greater than 66,000 bytes (or less, depending on heap usage). */ count = 32767; } if (count > _PY_WRITE_MAX) { count = _PY_WRITE_MAX; } if (gil_held) { do { Py_BEGIN_ALLOW_THREADS errno = 0; n = write(fd, buf, count); /* save/restore errno because PyErr_CheckSignals() * and PyErr_SetFromErrno() can modify it */ err = errno; Py_END_ALLOW_THREADS } while (n < 0 && err == EINTR && !(async_err = PyErr_CheckSignals())); } else { do { errno = 0; n = write(fd, buf, count); err = errno; } while (n < 0 && err == EINTR); } _Py_END_SUPPRESS_IPH if (async_err) { /* write() was interrupted by a signal (failed with EINTR) and the Python signal handler raised an exception (if gil_held is nonzero). */ errno = err; assert(errno == EINTR && (!gil_held || PyErr_Occurred())); return -1; } if (n < 0) { if (gil_held) PyErr_SetFromErrno(PyExc_OSError); errno = err; return -1; } return n; } /* Write count bytes of buf into fd. On success, return the number of written bytes, it can be lower than count including 0. On error, raise an exception, set errno and return -1. When interrupted by a signal (write() fails with EINTR), retry the syscall. If the Python signal handler raises an exception, the function returns -1 (the syscall is not retried). Release the GIL to call write(). The caller must hold the GIL. */ Py_ssize_t _Py_write(int fd, const void *buf, size_t count) { #ifdef WITH_THREAD assert(PyGILState_Check()); #endif /* _Py_write() must not be called with an exception set, otherwise the * caller may think that write() was interrupted by a signal and the signal * handler raised an exception. */ assert(!PyErr_Occurred()); return _Py_write_impl(fd, buf, count, 1); } /* Write count bytes of buf into fd. * * On success, return the number of written bytes, it can be lower than count * including 0. On error, set errno and return -1. * * When interrupted by a signal (write() fails with EINTR), retry the syscall * without calling the Python signal handler. */ Py_ssize_t _Py_write_noraise(int fd, const void *buf, size_t count) { return _Py_write_impl(fd, buf, count, 0); } #ifdef HAVE_READLINK /* Read value of symbolic link. Encode the path to the locale encoding, decode the result from the locale encoding. Return -1 on error. */ int _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz) { char *cpath; char cbuf[MAXPATHLEN]; wchar_t *wbuf; int res; size_t r1; cpath = Py_EncodeLocale(path, NULL); if (cpath == NULL) { errno = EINVAL; return -1; } res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf)); PyMem_Free(cpath); if (res == -1) return -1; if (res == Py_ARRAY_LENGTH(cbuf)) { errno = EINVAL; return -1; } cbuf[res] = '\0'; /* buf will be null terminated */ wbuf = Py_DecodeLocale(cbuf, &r1); if (wbuf == NULL) { errno = EINVAL; return -1; } if (bufsiz <= r1) { PyMem_RawFree(wbuf); errno = EINVAL; return -1; } wcsncpy(buf, wbuf, bufsiz); PyMem_RawFree(wbuf); return (int)r1; } #endif /* Return the canonicalized absolute pathname. Encode path to the locale encoding, decode the result from the locale encoding. Return NULL on error. */ wchar_t* _Py_wrealpath(const wchar_t *path, wchar_t *resolved_path, size_t resolved_path_size) { char *cpath; char cresolved_path[MAXPATHLEN]; wchar_t *wresolved_path; char *res; size_t r; cpath = Py_EncodeLocale(path, NULL); if (cpath == NULL) { errno = EINVAL; return NULL; } res = realpath(cpath, cresolved_path); PyMem_Free(cpath); if (res == NULL) return NULL; wresolved_path = Py_DecodeLocale(cresolved_path, &r); if (wresolved_path == NULL) { errno = EINVAL; return NULL; } if (resolved_path_size <= r) { PyMem_RawFree(wresolved_path); errno = EINVAL; return NULL; } wcsncpy(resolved_path, wresolved_path, resolved_path_size); PyMem_RawFree(wresolved_path); return resolved_path; } /* Get the current directory. size is the buffer size in wide characters including the null character. Decode the path from the locale encoding. Return NULL on error. */ wchar_t* _Py_wgetcwd(wchar_t *buf, size_t size) { char fname[MAXPATHLEN]; wchar_t *wname; size_t len; if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL) return NULL; wname = Py_DecodeLocale(fname, &len); if (wname == NULL) return NULL; if (size <= len) { PyMem_RawFree(wname); return NULL; } wcsncpy(buf, wname, size); PyMem_RawFree(wname); return buf; } /* Duplicate a file descriptor. The new file descriptor is created as non-inheritable. Return a new file descriptor on success, raise an OSError exception and return -1 on error. The GIL is released to call dup(). The caller must hold the GIL. */ int _Py_dup(int fd) { #ifdef WITH_THREAD assert(PyGILState_Check()); #endif Py_BEGIN_ALLOW_THREADS _Py_BEGIN_SUPPRESS_IPH fd = fcntl(fd, F_DUPFD_CLOEXEC, 0); _Py_END_SUPPRESS_IPH Py_END_ALLOW_THREADS if (fd < 0) { PyErr_SetFromErrno(PyExc_OSError); return -1; } return fd; } /* Get the blocking mode of the file descriptor. Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared, raise an exception and return -1 on error. */ int _Py_get_blocking(int fd) { int flags; _Py_BEGIN_SUPPRESS_IPH flags = fcntl(fd, F_GETFL, 0); _Py_END_SUPPRESS_IPH if (flags < 0) { PyErr_SetFromErrno(PyExc_OSError); return -1; } return !(flags & O_NONBLOCK); } /* Set the blocking mode of the specified file descriptor. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag otherwise. Return 0 on success, raise an exception and return -1 on error. */ int _Py_set_blocking(int fd, int blocking) { int flags, res; _Py_BEGIN_SUPPRESS_IPH flags = fcntl(fd, F_GETFL, 0); if (flags >= 0) { if (blocking) flags = flags & (~O_NONBLOCK); else flags = flags | O_NONBLOCK; res = fcntl(fd, F_SETFL, flags); } else { res = -1; } _Py_END_SUPPRESS_IPH if (res < 0) goto error; return 0; error: PyErr_SetFromErrno(PyExc_OSError); return -1; } int _Py_GetLocaleconvNumeric(PyObject **decimal_point, PyObject **thousands_sep, const char **grouping) { int res = -1; struct lconv *lc = localeconv(); int change_locale = 0; if (decimal_point != NULL && (strlen(lc->decimal_point) > 1 || ((unsigned char)lc->decimal_point[0]) > 127)) { change_locale = 1; } if (thousands_sep != NULL && (strlen(lc->thousands_sep) > 1 || ((unsigned char)lc->thousands_sep[0]) > 127)) { change_locale = 1; } /* Keep a copy of the LC_CTYPE locale */ char *oldloc = NULL, *loc = NULL; if (change_locale) { oldloc = setlocale(LC_CTYPE, NULL); if (!oldloc) { PyErr_SetString(PyExc_RuntimeWarning, "failed to get LC_CTYPE locale"); return -1; } oldloc = _PyMem_Strdup(oldloc); if (!oldloc) { PyErr_NoMemory(); return -1; } loc = setlocale(LC_NUMERIC, NULL); if (loc != NULL && strcmp(loc, oldloc) == 0) { loc = NULL; } if (loc != NULL) { /* Only set the locale temporarily the LC_CTYPE locale if LC_NUMERIC locale is different than LC_CTYPE locale and decimal_point and/or thousands_sep are non-ASCII or longer than 1 byte */ setlocale(LC_CTYPE, loc); } } if (decimal_point != NULL) { *decimal_point = PyUnicode_DecodeLocale(lc->decimal_point, NULL); if (*decimal_point == NULL) { goto error; } } if (thousands_sep != NULL) { *thousands_sep = PyUnicode_DecodeLocale(lc->thousands_sep, NULL); if (*thousands_sep == NULL) { goto error; } } if (grouping != NULL) { *grouping = lc->grouping; } res = 0; error: if (loc != NULL) { setlocale(LC_CTYPE, oldloc); } PyMem_Free(oldloc); return res; }
32,539
1,145
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/getversion.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/patchlevel.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ /* Return the full version string. */ const char * Py_GetVersion(void) { static char version[250]; PyOS_snprintf(version, sizeof(version), "%.80s (%.80s) %.80s", PY_VERSION, Py_GetBuildInfo(), Py_GetCompiler()); return version; }
1,234
22
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/progname.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ #ifdef MS_WINDOWS static wchar_t *progname = L"python"; #else static wchar_t *progname = L"python3"; #endif void Py_SetProgramName(wchar_t *pn) { if (pn && *pn) progname = pn; } wchar_t * Py_GetProgramName(void) { return progname; }
1,143
28
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/flags.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ /* Global configuration variable declarations are in pydebug.h */ /* XXX (ncoghlan): move those declarations to pylifecycle.h? */ int Py_DebugFlag; /* Needed by parser.c */ int Py_VerboseFlag; /* Needed by import.c */ int Py_QuietFlag; /* Needed by sysmodule.c */ int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */ int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */ int Py_OptimizeFlag; /* Needed by compile.c */ int Py_NoSiteFlag; /* Suppress 'import site' */ int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */ int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */ int Py_FrozenFlag; /* Needed by getpath.c */ int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */ int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */ int Py_NoUserSiteDirectory; /* for -s and site.py */ int Py_UnbufferedStdioFlag; /* Unbuffered binary std{in,out,err} */ int Py_HashRandomizationFlag; /* for -R and PYTHONHASHSEED */ int Py_IsolatedFlag; /* for -I, isolate from user's env */ #ifdef MS_WINDOWS int Py_LegacyWindowsFSEncodingFlag; /* Uses mbcs instead of utf-8 */ int Py_LegacyWindowsStdioFlag; /* Uses FileIO instead of WindowsConsoleIO */ #endif PyThreadState *_Py_Finalizing;
2,215
35
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/initstdio.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/struct/stat.h" #include "libc/str/locale.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ /* PYTHON_YOINK("io"); */ /* PYTHON_YOINK("encodings.aliases"); */ /* PYTHON_YOINK("encodings.latin_1"); */ /* PYTHON_YOINK("encodings.utf_8"); */ _Py_IDENTIFIER(name); _Py_IDENTIFIER(stdin); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); char *_Py_StandardStreamEncoding; char *_Py_StandardStreamErrors; /* Check if a file descriptor is valid or not. Return 0 if the file descriptor is invalid, return non-zero otherwise. */ static int is_valid_fd(int fd) { if (IsWindows()) { return __isfdopen(fd); } if (IsXnu()) { /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect such error. */ struct stat st; return fstat(fd, &st) == 0; } int fd2; if (fd < 0) return 0; _Py_BEGIN_SUPPRESS_IPH /* Prefer dup() over fstat(). fstat() can require input/output whereas dup() doesn't, there is a low risk of EMFILE/ENFILE at Python startup. */ fd2 = dup(fd); if (fd2 >= 0) close(fd2); _Py_END_SUPPRESS_IPH return fd2 >= 0; } /* returns Py_None if the fd is not valid */ static PyObject* create_stdio(PyObject* io, int fd, int write_mode, const char* name, const char* encoding, const char* errors) { PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; const char* mode; const char* newline; PyObject *line_buffering; int buffering, isatty; _Py_IDENTIFIER(open); _Py_IDENTIFIER(isatty); _Py_IDENTIFIER(TextIOWrapper); _Py_IDENTIFIER(mode); if (!is_valid_fd(fd)) Py_RETURN_NONE; /* stdin is always opened in buffered mode, first because it shouldn't make a difference in common use cases, second because TextIOWrapper depends on the presence of a read1() method which only exists on buffered streams. */ if (Py_UnbufferedStdioFlag && write_mode) buffering = 0; else buffering = -1; if (write_mode) mode = "wb"; else mode = "rb"; buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi", fd, mode, buffering, Py_None, Py_None, /* encoding, errors */ Py_None, 0); /* newline, closefd */ if (buf == NULL) goto error; if (buffering) { _Py_IDENTIFIER(raw); raw = _PyObject_GetAttrId(buf, &PyId_raw); if (raw == NULL) goto error; } else { raw = buf; Py_INCREF(raw); } #ifdef MS_WINDOWS /* Windows console IO is always UTF-8 encoded */ if (PyWindowsConsoleIO_Check(raw)) encoding = "utf-8"; #endif text = PyUnicode_FromString(name); if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0) goto error; res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL); if (res == NULL) goto error; isatty = PyObject_IsTrue(res); Py_DECREF(res); if (isatty == -1) goto error; if (isatty || Py_UnbufferedStdioFlag) line_buffering = Py_True; else line_buffering = Py_False; Py_CLEAR(raw); Py_CLEAR(text); #ifdef MS_WINDOWS /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r" newlines to "\n". sys.stdout and sys.stderr: translate "\n" to "\r\n". */ newline = NULL; #else /* sys.stdin: split lines at "\n". sys.stdout and sys.stderr: don't translate newlines (use "\n"). */ newline = "\n"; #endif stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO", buf, encoding, errors, newline, line_buffering); Py_CLEAR(buf); if (stream == NULL) goto error; if (write_mode) mode = "w"; else mode = "r"; text = PyUnicode_FromString(mode); if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0) goto error; Py_CLEAR(text); return stream; error: Py_XDECREF(buf); Py_XDECREF(stream); Py_XDECREF(text); Py_XDECREF(raw); if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) { /* Issue #24891: the file descriptor was closed after the first is_valid_fd() check was called. Ignore the OSError and set the stream to None. */ PyErr_Clear(); Py_RETURN_NONE; } return NULL; } /* Initialize sys.stdin, stdout, stderr and builtins.open */ int _Py_InitStdio(void) { PyObject *iomod = NULL, *wrapper; PyObject *bimod = NULL; PyObject *m; PyObject *std = NULL; int status = 0, fd; PyObject * encoding_attr; char *pythonioencoding = NULL, *encoding, *errors; /* Hack to avoid a nasty recursion issue when Python is invoked in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { goto error; } Py_DECREF(m); if (!(m = PyImport_ImportModule("encodings.latin_1"))) { goto error; } Py_DECREF(m); if (!(bimod = PyImport_ImportModule("builtins"))) { goto error; } if (!(iomod = PyImport_ImportModule("io"))) { goto error; } if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { goto error; } /* Set builtins.open */ if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { Py_DECREF(wrapper); goto error; } Py_DECREF(wrapper); encoding = _Py_StandardStreamEncoding; errors = _Py_StandardStreamErrors; if (!encoding || !errors) { pythonioencoding = Py_GETENV("PYTHONIOENCODING"); if (pythonioencoding) { char *err; pythonioencoding = _PyMem_Strdup(pythonioencoding); if (pythonioencoding == NULL) { PyErr_NoMemory(); goto error; } err = strchr(pythonioencoding, ':'); if (err) { *err = '\0'; err++; if (*err && !errors) { errors = err; } } if (*pythonioencoding && !encoding) { encoding = pythonioencoding; } } if (!errors && !(pythonioencoding && *pythonioencoding)) { /* When the LC_CTYPE locale is the POSIX locale ("C locale"), stdin and stdout use the surrogateescape error handler by default, instead of the strict error handler. */ char *loc = setlocale(LC_CTYPE, NULL); if (loc != NULL && strcmp(loc, "C") == 0) errors = "surrogateescape"; } } /* Set sys.stdin */ fd = fileno(stdin); /* Under some conditions stdin, stdout and stderr may not be connected * and fileno() may point to an invalid file descriptor. For example * GUI apps don't have valid standard streams by default. */ std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors); if (std == NULL) goto error; PySys_SetObject("__stdin__", std); _PySys_SetObjectId(&PyId_stdin, std); Py_DECREF(std); /* Set sys.stdout */ fd = fileno(stdout); std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors); if (std == NULL) goto error; PySys_SetObject("__stdout__", std); _PySys_SetObjectId(&PyId_stdout, std); Py_DECREF(std); #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ /* Set sys.stderr, replaces the preliminary stderr */ fd = fileno(stderr); std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace"); if (std == NULL) goto error; /* Same as hack above, pre-import stderr's codec to avoid recursion when import.c tries to write to stderr in verbose mode. */ encoding_attr = PyObject_GetAttrString(std, "encoding"); if (encoding_attr != NULL) { const char * std_encoding; std_encoding = PyUnicode_AsUTF8(encoding_attr); if (std_encoding != NULL) { PyObject *codec_info = _PyCodec_Lookup(std_encoding); Py_XDECREF(codec_info); } Py_DECREF(encoding_attr); } PyErr_Clear(); /* Not a fatal error if codec isn't available */ if (PySys_SetObject("__stderr__", std) < 0) { Py_DECREF(std); goto error; } if (_PySys_SetObjectId(&PyId_stderr, std) < 0) { Py_DECREF(std); goto error; } Py_DECREF(std); #endif if (0) { error: status = -1; } /* We won't need them anymore. */ if (_Py_StandardStreamEncoding) { PyMem_RawFree(_Py_StandardStreamEncoding); _Py_StandardStreamEncoding = NULL; } if (_Py_StandardStreamErrors) { PyMem_RawFree(_Py_StandardStreamErrors); _Py_StandardStreamErrors = NULL; } PyMem_Free(pythonioencoding); Py_XDECREF(bimod); Py_XDECREF(iomod); return status; }
10,591
332
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/importdl.h
#ifndef Py_IMPORTDL_H #define Py_IMPORTDL_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ extern const char *_PyImport_DynLoadFiletab[]; extern PyObject *_PyImport_LoadDynamicModuleWithSpec(PyObject *spec, FILE *); /* Max length of module suffix searched for -- accommodates "module.slb" */ #define MAXSUFFIXSIZE 12 typedef void (*dl_funcptr)(void); COSMOPOLITAN_C_END_ #endif /* !Py_IMPORTDL_H */
426
17
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/thread_pthread.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/thread/semaphore.h" /* clang-format off */ /* Posix threads interface */ /* The POSIX spec requires that use of pthread_attr_setstacksize be conditional on _POSIX_THREAD_ATTR_STACKSIZE being defined. */ #ifdef _POSIX_THREAD_ATTR_STACKSIZE #ifndef THREAD_STACK_SIZE #define THREAD_STACK_SIZE 0 /* use default stack size */ #endif /* The default stack size for new threads on OSX and BSD is small enough that * we'll get hard crashes instead of 'maximum recursion depth exceeded' * exceptions. * * The default stack sizes below are the empirically determined minimal stack * sizes where a simple recursive function doesn't cause a hard crash. */ #if defined(__APPLE__) && defined(THREAD_STACK_SIZE) && THREAD_STACK_SIZE == 0 #undef THREAD_STACK_SIZE #define THREAD_STACK_SIZE 0x500000 #endif #if defined(__FreeBSD__) && defined(THREAD_STACK_SIZE) && THREAD_STACK_SIZE == 0 #undef THREAD_STACK_SIZE #define THREAD_STACK_SIZE 0x400000 #endif /* for safety, ensure a viable minimum stacksize */ #define THREAD_STACK_MIN 0x8000 /* 32kB */ #else /* !_POSIX_THREAD_ATTR_STACKSIZE */ #ifdef THREAD_STACK_SIZE #error "THREAD_STACK_SIZE defined but _POSIX_THREAD_ATTR_STACKSIZE undefined" #endif #endif #if !defined(pthread_attr_default) # define pthread_attr_default ((pthread_attr_t *)NULL) #endif #if !defined(pthread_mutexattr_default) # define pthread_mutexattr_default ((pthread_mutexattr_t *)NULL) #endif #if !defined(pthread_condattr_default) # define pthread_condattr_default ((pthread_condattr_t *)NULL) #endif /* Whether or not to use semaphores directly rather than emulating them with * mutexes and condition variables: */ #if (defined(_POSIX_SEMAPHORES) && !defined(HAVE_BROKEN_POSIX_SEMAPHORES) && \ defined(HAVE_SEM_TIMEDWAIT)) # define USE_SEMAPHORES #else # undef USE_SEMAPHORES #endif /* On platforms that don't use standard POSIX threads pthread_sigmask() * isn't present. DEC threads uses sigprocmask() instead as do most * other UNIX International compliant systems that don't have the full * pthread implementation. */ #if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK) # define SET_THREAD_SIGMASK pthread_sigmask #else # define SET_THREAD_SIGMASK sigprocmask #endif /* We assume all modern POSIX systems have gettimeofday() */ #ifdef GETTIMEOFDAY_NO_TZ #define GETTIMEOFDAY(ptv) gettimeofday(ptv) #else #define GETTIMEOFDAY(ptv) gettimeofday(ptv, (struct timezone *)NULL) #endif #define MICROSECONDS_TO_TIMESPEC(microseconds, ts) \ do { \ struct timeval tv; \ GETTIMEOFDAY(&tv); \ tv.tv_usec += microseconds % 1000000; \ tv.tv_sec += microseconds / 1000000; \ tv.tv_sec += tv.tv_usec / 1000000; \ tv.tv_usec %= 1000000; \ ts.tv_sec = tv.tv_sec; \ ts.tv_nsec = tv.tv_usec * 1000; \ } while(0) /* A pthread mutex isn't sufficient to model the Python lock type * because, according to Draft 5 of the docs (P1003.4a/D5), both of the * following are undefined: * -> a thread tries to lock a mutex it already has locked * -> a thread tries to unlock a mutex locked by a different thread * pthread mutexes are designed for serializing threads over short pieces * of code anyway, so wouldn't be an appropriate implementation of * Python's locks regardless. * * The pthread_lock struct implements a Python lock as a "locked?" bit * and a <condition, mutex> pair. In general, if the bit can be acquired * instantly, it is, else the pair is used to block the thread until the * bit is cleared. 9 May 1994 [email protected] */ typedef struct { char locked; /* 0=unlocked, 1=locked */ /* a <cond, mutex> pair to handle an acquire of a locked lock */ pthread_cond_t lock_released; pthread_mutex_t mut; } pthread_lock; #define CHECK_STATUS(name) if (status != 0) { perror(name); error = 1; } #define CHECK_STATUS_PTHREAD(name) if (status != 0) { fprintf(stderr, \ "%s: %s\n", name, strerror(status)); error = 1; } /* * Initialization. */ #if defined(_HAVE_BSDI) static void _noop(void) { } static void PyThread__init_thread(void) { /* DO AN INIT BY STARTING THE THREAD */ static int dummy = 0; pthread_t thread1; pthread_create(&thread1, NULL, (void *) _noop, &dummy); pthread_join(thread1, NULL); } #else /* !_HAVE_BSDI */ static void PyThread__init_thread(void) { #if defined(_AIX) && defined(__GNUC__) extern void pthread_init(void); pthread_init(); #endif } #endif /* !_HAVE_BSDI */ /* * Thread support. */ /* bpo-33015: pythread_callback struct and pythread_wrapper() cast "void func(void *)" to "void* func(void *)": always return NULL. PyThread_start_new_thread() uses "void func(void *)" type, whereas pthread_create() requires a void* return value. */ typedef struct { void (*func) (void *); void *arg; } pythread_callback; static void * pythread_wrapper(void *arg) { /* copy func and func_arg and free the temporary structure */ pythread_callback *callback = arg; void (*func)(void *) = callback->func; void *func_arg = callback->arg; PyMem_RawFree(arg); func(func_arg); return NULL; } long PyThread_start_new_thread(void (*func)(void *), void *arg) { pthread_t th; int status; #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) pthread_attr_t attrs; #endif #if defined(THREAD_STACK_SIZE) size_t tss; #endif dprintf(("PyThread_start_new_thread called\n")); if (!initialized) PyThread_init_thread(); #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) if (pthread_attr_init(&attrs) != 0) return -1; #endif #if defined(THREAD_STACK_SIZE) tss = (_pythread_stacksize != 0) ? _pythread_stacksize : THREAD_STACK_SIZE; if (tss != 0) { if (pthread_attr_setstacksize(&attrs, tss) != 0) { pthread_attr_destroy(&attrs); return -1; } } #endif #if defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); #endif pythread_callback *callback = PyMem_RawMalloc(sizeof(pythread_callback)); if (callback == NULL) { return -1; } callback->func = func; callback->arg = arg; status = pthread_create(&th, #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) &attrs, #else (pthread_attr_t*)NULL, #endif pythread_wrapper, callback); #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) pthread_attr_destroy(&attrs); #endif if (status != 0) { PyMem_RawFree(callback); return -1; } pthread_detach(th); #if SIZEOF_PTHREAD_T <= SIZEOF_LONG return (long) th; #else return (long) *(long *) &th; #endif } /* XXX This implementation is considered (to quote Tim Peters) "inherently hosed" because: - It does not guarantee the promise that a non-zero integer is returned. - The cast to long is inherently unsafe. - It is not clear that the 'volatile' (for AIX?) are any longer necessary. */ long PyThread_get_thread_ident(void) { volatile pthread_t threadid; if (!initialized) PyThread_init_thread(); threadid = pthread_self(); return (long) threadid; } void PyThread_exit_thread(void) { dprintf(("PyThread_exit_thread called\n")); if (!initialized) exit(0); pthread_exit(0); } #ifdef USE_SEMAPHORES /* * Lock support. */ PyThread_type_lock PyThread_allocate_lock(void) { sem_t *lock; int status, error = 0; dprintf(("PyThread_allocate_lock called\n")); if (!initialized) PyThread_init_thread(); lock = (sem_t *)PyMem_RawMalloc(sizeof(sem_t)); if (lock) { status = sem_init(lock,0,1); CHECK_STATUS("sem_init"); if (error) { PyMem_RawFree((void *)lock); lock = NULL; } } dprintf(("PyThread_allocate_lock() -> %p\n", lock)); return (PyThread_type_lock)lock; } void PyThread_free_lock(PyThread_type_lock lock) { sem_t *thelock = (sem_t *)lock; int status, error = 0; (void) error; /* silence unused-but-set-variable warning */ dprintf(("PyThread_free_lock(%p) called\n", lock)); if (!thelock) return; status = sem_destroy(thelock); CHECK_STATUS("sem_destroy"); PyMem_RawFree((void *)thelock); } /* * As of February 2002, Cygwin thread implementations mistakenly report error * codes in the return value of the sem_ calls (like the pthread_ functions). * Correct implementations return -1 and put the code in errno. This supports * either. */ static int fix_status(int status) { return (status == -1) ? errno : status; } PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds, int intr_flag) { PyLockStatus success; sem_t *thelock = (sem_t *)lock; int status, error = 0; struct timespec ts; (void) error; /* silence unused-but-set-variable warning */ dprintf(("PyThread_acquire_lock_timed(%p, %lld, %d) called\n", lock, microseconds, intr_flag)); if (microseconds > 0) MICROSECONDS_TO_TIMESPEC(microseconds, ts); do { if (microseconds > 0) status = fix_status(sem_timedwait(thelock, &ts)); else if (microseconds == 0) status = fix_status(sem_trywait(thelock)); else status = fix_status(sem_wait(thelock)); /* Retry if interrupted by a signal, unless the caller wants to be notified. */ } while (!intr_flag && status == EINTR); /* Don't check the status if we're stopping because of an interrupt. */ if (!(intr_flag && status == EINTR)) { if (microseconds > 0) { if (status != ETIMEDOUT) CHECK_STATUS("sem_timedwait"); } else if (microseconds == 0) { if (status != EAGAIN) CHECK_STATUS("sem_trywait"); } else { CHECK_STATUS("sem_wait"); } } if (status == 0) { success = PY_LOCK_ACQUIRED; } else if (intr_flag && status == EINTR) { success = PY_LOCK_INTR; } else { success = PY_LOCK_FAILURE; } dprintf(("PyThread_acquire_lock_timed(%p, %lld, %d) -> %d\n", lock, microseconds, intr_flag, success)); return success; } void PyThread_release_lock(PyThread_type_lock lock) { sem_t *thelock = (sem_t *)lock; int status, error = 0; (void) error; /* silence unused-but-set-variable warning */ dprintf(("PyThread_release_lock(%p) called\n", lock)); status = sem_post(thelock); CHECK_STATUS("sem_post"); } #else /* USE_SEMAPHORES */ /* * Lock support. */ PyThread_type_lock PyThread_allocate_lock(void) { pthread_lock *lock; int status, error = 0; dprintf(("PyThread_allocate_lock called\n")); if (!initialized) PyThread_init_thread(); lock = (pthread_lock *) PyMem_RawMalloc(sizeof(pthread_lock)); if (lock) { bzero((void *)lock, sizeof(pthread_lock)); lock->locked = 0; status = pthread_mutex_init(&lock->mut, pthread_mutexattr_default); CHECK_STATUS_PTHREAD("pthread_mutex_init"); /* Mark the pthread mutex underlying a Python mutex as pure happens-before. We can't simply mark the Python-level mutex as a mutex because it can be acquired and released in different threads, which will cause errors. */ _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(&lock->mut); status = pthread_cond_init(&lock->lock_released, pthread_condattr_default); CHECK_STATUS_PTHREAD("pthread_cond_init"); if (error) { PyMem_RawFree((void *)lock); lock = 0; } } dprintf(("PyThread_allocate_lock() -> %p\n", lock)); return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { pthread_lock *thelock = (pthread_lock *)lock; int status, error = 0; (void) error; /* silence unused-but-set-variable warning */ dprintf(("PyThread_free_lock(%p) called\n", lock)); /* some pthread-like implementations tie the mutex to the cond * and must have the cond destroyed first. */ status = pthread_cond_destroy( &thelock->lock_released ); CHECK_STATUS_PTHREAD("pthread_cond_destroy"); status = pthread_mutex_destroy( &thelock->mut ); CHECK_STATUS_PTHREAD("pthread_mutex_destroy"); PyMem_RawFree((void *)thelock); } PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds, int intr_flag) { PyLockStatus success = PY_LOCK_FAILURE; pthread_lock *thelock = (pthread_lock *)lock; int status, error = 0; dprintf(("PyThread_acquire_lock_timed(%p, %lld, %d) called\n", lock, microseconds, intr_flag)); if (microseconds == 0) { status = pthread_mutex_trylock( &thelock->mut ); if (status != EBUSY) CHECK_STATUS_PTHREAD("pthread_mutex_trylock[1]"); } else { status = pthread_mutex_lock( &thelock->mut ); CHECK_STATUS_PTHREAD("pthread_mutex_lock[1]"); } if (status == 0) { if (thelock->locked == 0) { success = PY_LOCK_ACQUIRED; } else if (microseconds != 0) { struct timespec ts; if (microseconds > 0) MICROSECONDS_TO_TIMESPEC(microseconds, ts); /* continue trying until we get the lock */ /* mut must be locked by me -- part of the condition * protocol */ while (success == PY_LOCK_FAILURE) { if (microseconds > 0) { status = pthread_cond_timedwait( &thelock->lock_released, &thelock->mut, &ts); if (status == ETIMEDOUT) break; CHECK_STATUS_PTHREAD("pthread_cond_timed_wait"); } else { status = pthread_cond_wait( &thelock->lock_released, &thelock->mut); CHECK_STATUS_PTHREAD("pthread_cond_wait"); } if (intr_flag && status == 0 && thelock->locked) { /* We were woken up, but didn't get the lock. We probably received * a signal. Return PY_LOCK_INTR to allow the caller to handle * it and retry. */ success = PY_LOCK_INTR; break; } else if (status == 0 && !thelock->locked) { success = PY_LOCK_ACQUIRED; } } } if (success == PY_LOCK_ACQUIRED) thelock->locked = 1; status = pthread_mutex_unlock( &thelock->mut ); CHECK_STATUS_PTHREAD("pthread_mutex_unlock[1]"); } if (error) success = PY_LOCK_FAILURE; dprintf(("PyThread_acquire_lock_timed(%p, %lld, %d) -> %d\n", lock, microseconds, intr_flag, success)); return success; } void PyThread_release_lock(PyThread_type_lock lock) { pthread_lock *thelock = (pthread_lock *)lock; int status, error = 0; (void) error; /* silence unused-but-set-variable warning */ dprintf(("PyThread_release_lock(%p) called\n", lock)); status = pthread_mutex_lock( &thelock->mut ); CHECK_STATUS_PTHREAD("pthread_mutex_lock[3]"); thelock->locked = 0; /* wake up someone (anyone, if any) waiting on the lock */ status = pthread_cond_signal( &thelock->lock_released ); CHECK_STATUS_PTHREAD("pthread_cond_signal"); status = pthread_mutex_unlock( &thelock->mut ); CHECK_STATUS_PTHREAD("pthread_mutex_unlock[3]"); } #endif /* USE_SEMAPHORES */ int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0, /*intr_flag=*/0); } /* set the thread stack size. * Return 0 if size is valid, -1 if size is invalid, * -2 if setting stack size is not supported. */ static int _pythread_pthread_set_stacksize(size_t size) { #if defined(THREAD_STACK_SIZE) pthread_attr_t attrs; size_t tss_min; int rc = 0; #endif /* set to default */ if (size == 0) { _pythread_stacksize = 0; return 0; } #if defined(THREAD_STACK_SIZE) #if defined(PTHREAD_STACK_MIN) tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN : THREAD_STACK_MIN; #else tss_min = THREAD_STACK_MIN; #endif if (size >= tss_min) { /* validate stack size by setting thread attribute */ if (pthread_attr_init(&attrs) == 0) { rc = pthread_attr_setstacksize(&attrs, size); pthread_attr_destroy(&attrs); if (rc == 0) { _pythread_stacksize = size; return 0; } } } return -1; #else return -2; #endif } #define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x) #define Py_HAVE_NATIVE_TLS int PyThread_create_key(void) { pthread_key_t key; int fail = pthread_key_create(&key, NULL); if (fail) return -1; if (key > INT_MAX) { /* Issue #22206: handle integer overflow */ pthread_key_delete(key); errno = ENOMEM; return -1; } return (int)key; } void PyThread_delete_key(int key) { pthread_key_delete(key); } void PyThread_delete_key_value(int key) { pthread_setspecific(key, NULL); } int PyThread_set_key_value(int key, void *value) { int fail; fail = pthread_setspecific(key, value); return fail ? -1 : 0; } void * PyThread_get_key_value(int key) { return pthread_getspecific(key); } void PyThread_ReInitTLS(void) {}
18,922
663
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/traceback.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/weirdtypes.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/osdefs.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/traceback.h" /* clang-format off */ #define OFF(x) offsetof(PyTracebackObject, x) #define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str)) #define MAX_STRING_LENGTH 500 #define MAX_FRAME_DEPTH 100 #define MAX_NTHREADS 100 /* Function from Parser/tokenizer.c */ extern char * PyTokenizer_FindEncodingFilename(int, PyObject *); _Py_IDENTIFIER(TextIOWrapper); _Py_IDENTIFIER(close); _Py_IDENTIFIER(open); _Py_IDENTIFIER(path); static PyObject * tb_dir(PyTracebackObject *self) { return Py_BuildValue("[ssss]", "tb_frame", "tb_next", "tb_lasti", "tb_lineno"); } static PyMethodDef tb_methods[] = { {"__dir__", (PyCFunction)tb_dir, METH_NOARGS}, {NULL, NULL, 0, NULL}, }; static PyMemberDef tb_memberlist[] = { {"tb_next", T_OBJECT, OFF(tb_next), READONLY}, {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY}, {"tb_lasti", T_INT, OFF(tb_lasti), READONLY}, {"tb_lineno", T_INT, OFF(tb_lineno), READONLY}, {NULL} /* Sentinel */ }; static void tb_dealloc(PyTracebackObject *tb) { PyObject_GC_UnTrack(tb); Py_TRASHCAN_SAFE_BEGIN(tb) Py_XDECREF(tb->tb_next); Py_XDECREF(tb->tb_frame); PyObject_GC_Del(tb); Py_TRASHCAN_SAFE_END(tb) } static int tb_traverse(PyTracebackObject *tb, visitproc visit, void *arg) { Py_VISIT(tb->tb_next); Py_VISIT(tb->tb_frame); return 0; } static int tb_clear(PyTracebackObject *tb) { Py_CLEAR(tb->tb_next); Py_CLEAR(tb->tb_frame); return 0; } PyTypeObject PyTraceBack_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "traceback", sizeof(PyTracebackObject), 0, (destructor)tb_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)tb_traverse, /* tp_traverse */ (inquiry)tb_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ tb_methods, /* tp_methods */ tb_memberlist, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ }; static PyTracebackObject * newtracebackobject(PyTracebackObject *next, PyFrameObject *frame) { PyTracebackObject *tb; if ((next != NULL && !PyTraceBack_Check(next)) || frame == NULL || !PyFrame_Check(frame)) { PyErr_BadInternalCall(); return NULL; } tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type); if (tb != NULL) { Py_XINCREF(next); tb->tb_next = next; Py_XINCREF(frame); tb->tb_frame = frame; tb->tb_lasti = frame->f_lasti; tb->tb_lineno = PyFrame_GetLineNumber(frame); PyObject_GC_Track(tb); } return tb; } int PyTraceBack_Here(PyFrameObject *frame) { PyObject *exc, *val, *tb, *newtb; PyErr_Fetch(&exc, &val, &tb); newtb = (PyObject *)newtracebackobject((PyTracebackObject *)tb, frame); if (newtb == NULL) { _PyErr_ChainExceptions(exc, val, tb); return -1; } PyErr_Restore(exc, val, newtb); Py_XDECREF(tb); return 0; } /* Insert a frame into the traceback for (funcname, filename, lineno). */ void _PyTraceback_Add(const char *funcname, const char *filename, int lineno) { PyObject *globals; PyCodeObject *code; PyFrameObject *frame; PyObject *exc, *val, *tb; /* Save and clear the current exception. Python functions must not be called with an exception set. Calling Python functions happens when the codec of the filesystem encoding is implemented in pure Python. */ PyErr_Fetch(&exc, &val, &tb); globals = PyDict_New(); if (!globals) goto error; code = PyCode_NewEmpty(filename, funcname, lineno); if (!code) { Py_DECREF(globals); goto error; } frame = PyFrame_New(PyThreadState_Get(), code, globals, NULL); Py_DECREF(globals); Py_DECREF(code); if (!frame) goto error; frame->f_lineno = lineno; PyErr_Restore(exc, val, tb); PyTraceBack_Here(frame); Py_DECREF(frame); return; error: _PyErr_ChainExceptions(exc, val, tb); } static PyObject * _Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io) { Py_ssize_t i; PyObject *binary; PyObject *v; Py_ssize_t npath; size_t taillen; PyObject *syspath; PyObject *path; const char* tail; PyObject *filebytes; const char* filepath; Py_ssize_t len; PyObject* result; filebytes = PyUnicode_EncodeFSDefault(filename); if (filebytes == NULL) { PyErr_Clear(); return NULL; } filepath = PyBytes_AS_STRING(filebytes); /* Search tail of filename in sys.path before giving up */ tail = strrchr(filepath, SEP); if (tail == NULL) tail = filepath; else tail++; taillen = strlen(tail); syspath = _PySys_GetObjectId(&PyId_path); if (syspath == NULL || !PyList_Check(syspath)) goto error; npath = PyList_Size(syspath); for (i = 0; i < npath; i++) { v = PyList_GetItem(syspath, i); if (v == NULL) { PyErr_Clear(); break; } if (!PyUnicode_Check(v)) continue; path = PyUnicode_EncodeFSDefault(v); if (path == NULL) { PyErr_Clear(); continue; } len = PyBytes_GET_SIZE(path); if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) { Py_DECREF(path); continue; /* Too long */ } strcpy(namebuf, PyBytes_AS_STRING(path)); Py_DECREF(path); if (strlen(namebuf) != (size_t)len) continue; /* v contains '\0' */ if (len > 0 && namebuf[len-1] != SEP) namebuf[len++] = SEP; strcpy(namebuf+len, tail); binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb"); if (binary != NULL) { result = binary; goto finally; } PyErr_Clear(); } goto error; error: result = NULL; finally: Py_DECREF(filebytes); return result; } int _Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent) { int err = 0; int fd; int i; char *found_encoding; char *encoding; PyObject *io; PyObject *binary; PyObject *fob = NULL; PyObject *lineobj = NULL; PyObject *res; char buf[MAXPATHLEN+1]; int kind; void *data; /* open the file */ if (filename == NULL) return 0; io = PyImport_ImportModuleNoBlock("io"); if (io == NULL) return -1; binary = _PyObject_CallMethodId(io, &PyId_open, "Os", filename, "rb"); if (binary == NULL) { PyErr_Clear(); binary = _Py_FindSourceFile(filename, buf, sizeof(buf), io); if (binary == NULL) { Py_DECREF(io); return -1; } } /* use the right encoding to decode the file as unicode */ fd = PyObject_AsFileDescriptor(binary); if (fd < 0) { Py_DECREF(io); Py_DECREF(binary); return 0; } found_encoding = PyTokenizer_FindEncodingFilename(fd, filename); if (found_encoding == NULL) PyErr_Clear(); encoding = (found_encoding != NULL) ? found_encoding : "utf-8"; /* Reset position */ if (lseek(fd, 0, SEEK_SET) == (off_t)-1) { Py_DECREF(io); Py_DECREF(binary); PyMem_FREE(found_encoding); return 0; } fob = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "Os", binary, encoding); Py_DECREF(io); PyMem_FREE(found_encoding); if (fob == NULL) { PyErr_Clear(); res = _PyObject_CallMethodId(binary, &PyId_close, NULL); Py_DECREF(binary); if (res) Py_DECREF(res); else PyErr_Clear(); return 0; } Py_DECREF(binary); /* get the line number lineno */ for (i = 0; i < lineno; i++) { Py_XDECREF(lineobj); lineobj = PyFile_GetLine(fob, -1); if (!lineobj) { PyErr_Clear(); err = -1; break; } } res = _PyObject_CallMethodId(fob, &PyId_close, NULL); if (res) Py_DECREF(res); else PyErr_Clear(); Py_DECREF(fob); if (!lineobj || !PyUnicode_Check(lineobj)) { Py_XDECREF(lineobj); return err; } /* remove the indentation of the line */ kind = PyUnicode_KIND(lineobj); data = PyUnicode_DATA(lineobj); for (i=0; i < PyUnicode_GET_LENGTH(lineobj); i++) { Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (ch != ' ' && ch != '\t' && ch != '\014') break; } if (i) { PyObject *truncated; truncated = PyUnicode_Substring(lineobj, i, PyUnicode_GET_LENGTH(lineobj)); if (truncated) { Py_DECREF(lineobj); lineobj = truncated; } else { PyErr_Clear(); } } /* Write some spaces before the line */ strcpy(buf, " "); assert (strlen(buf) == 10); while (indent > 0) { if (indent < 10) buf[indent] = '\0'; err = PyFile_WriteString(buf, f); if (err != 0) break; indent -= 10; } /* finally display the line */ if (err == 0) err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW); Py_DECREF(lineobj); if (err == 0) err = PyFile_WriteString("\n", f); return err; } static int tb_displayline(PyObject *f, PyObject *filename, int lineno, PyObject *name) { int err; PyObject *line; if (filename == NULL || name == NULL) return -1; line = PyUnicode_FromFormat(" File \"%U\", line %d, in %U\n", filename, lineno, name); if (line == NULL) return -1; err = PyFile_WriteObject(line, f, Py_PRINT_RAW); Py_DECREF(line); if (err != 0) return err; /* ignore errors since we can't report them, can we? */ if (_Py_DisplaySourceLine(f, filename, lineno, 4)) PyErr_Clear(); return err; } static const int TB_RECURSIVE_CUTOFF = 3; // Also hardcoded in traceback.py. static int tb_print_line_repeated(PyObject *f, long cnt) { cnt -= TB_RECURSIVE_CUTOFF; PyObject *line = PyUnicode_FromFormat( (cnt > 1) ? " [Previous line repeated %ld more times]\n" : " [Previous line repeated %ld more time]\n", cnt); if (line == NULL) { return -1; } int err = PyFile_WriteObject(line, f, Py_PRINT_RAW); Py_DECREF(line); return err; } static int tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit) { int err = 0; Py_ssize_t depth = 0; PyObject *last_file = NULL; int last_line = -1; PyObject *last_name = NULL; long cnt = 0; PyTracebackObject *tb1 = tb; while (tb1 != NULL) { depth++; tb1 = tb1->tb_next; } while (tb != NULL && depth > limit) { depth--; tb = tb->tb_next; } while (tb != NULL && err == 0) { if (last_file == NULL || tb->tb_frame->f_code->co_filename != last_file || last_line == -1 || tb->tb_lineno != last_line || last_name == NULL || tb->tb_frame->f_code->co_name != last_name) { if (cnt > TB_RECURSIVE_CUTOFF) { err = tb_print_line_repeated(f, cnt); } last_file = tb->tb_frame->f_code->co_filename; last_line = tb->tb_lineno; last_name = tb->tb_frame->f_code->co_name; cnt = 0; } cnt++; if (err == 0 && cnt <= TB_RECURSIVE_CUTOFF) { err = tb_displayline(f, tb->tb_frame->f_code->co_filename, tb->tb_lineno, tb->tb_frame->f_code->co_name); if (err == 0) { err = PyErr_CheckSignals(); } } tb = tb->tb_next; } if (err == 0 && cnt > TB_RECURSIVE_CUTOFF) { err = tb_print_line_repeated(f, cnt); } return err; } #define PyTraceBack_LIMIT 1000 int PyTraceBack_Print(PyObject *v, PyObject *f) { int err; PyObject *limitv; long limit = PyTraceBack_LIMIT; if (v == NULL) return 0; if (!PyTraceBack_Check(v)) { PyErr_BadInternalCall(); return -1; } limitv = PySys_GetObject("tracebacklimit"); if (limitv && PyLong_Check(limitv)) { int overflow; limit = PyLong_AsLongAndOverflow(limitv, &overflow); if (overflow > 0) { limit = LONG_MAX; } else if (limit <= 0) { return 0; } } err = PyFile_WriteString("Traceback (most recent call last):\n", f); if (!err) err = tb_printinternal((PyTracebackObject *)v, f, limit); return err; } /* Reverse a string. For example, "abcd" becomes "dcba". This function is signal safe. */ void _Py_DumpDecimal(int fd, unsigned long value) { /* maximum number of characters required for output of %lld or %p. We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits, plus 1 for the null byte. 53/22 is an upper bound for log10(256). */ char buffer[1 + (sizeof(unsigned long)*53-1) / 22 + 1]; char *ptr, *end; end = &buffer[Py_ARRAY_LENGTH(buffer) - 1]; ptr = end; *ptr = '\0'; do { --ptr; assert(ptr >= buffer); *ptr = '0' + (value % 10); value /= 10; } while (value); _Py_write_noraise(fd, ptr, end - ptr); } /* Format an integer in range [0; 0xffffffff] to hexadecimal of 'width' digits, and write it into the file fd. This function is signal safe. */ void _Py_DumpHexadecimal(int fd, unsigned long value, Py_ssize_t width) { char buffer[sizeof(unsigned long) * 2 + 1], *ptr, *end; const Py_ssize_t size = Py_ARRAY_LENGTH(buffer) - 1; if (width > size) width = size; /* it's ok if width is negative */ end = &buffer[size]; ptr = end; *ptr = '\0'; do { --ptr; assert(ptr >= buffer); *ptr = Py_hexdigits[value & 15]; value >>= 4; } while ((end - ptr) < width || value); _Py_write_noraise(fd, ptr, end - ptr); } void _Py_DumpASCII(int fd, PyObject *text) { PyASCIIObject *ascii = (PyASCIIObject *)text; Py_ssize_t i, size; int truncated; int kind; void *data = NULL; wchar_t *wstr = NULL; Py_UCS4 ch; if (!PyUnicode_Check(text)) return; size = ascii->length; kind = ascii->state.kind; if (kind == PyUnicode_WCHAR_KIND) { wstr = ((PyASCIIObject *)text)->wstr; if (wstr == NULL) return; size = ((PyCompactUnicodeObject *)text)->wstr_length; } else if (ascii->state.compact) { if (ascii->state.ascii) data = ((PyASCIIObject*)text) + 1; else data = ((PyCompactUnicodeObject*)text) + 1; } else { data = ((PyUnicodeObject *)text)->data.any; if (data == NULL) return; } if (MAX_STRING_LENGTH < size) { size = MAX_STRING_LENGTH; truncated = 1; } else { truncated = 0; } for (i=0; i < size; i++) { if (kind != PyUnicode_WCHAR_KIND) ch = PyUnicode_READ(kind, data, i); else ch = wstr[i]; if (' ' <= ch && ch <= 126) { /* printable ASCII character */ char c = (char)ch; _Py_write_noraise(fd, &c, 1); } else if (ch <= 0xff) { PUTS(fd, "\\x"); _Py_DumpHexadecimal(fd, ch, 2); } else if (ch <= 0xffff) { PUTS(fd, "\\u"); _Py_DumpHexadecimal(fd, ch, 4); } else { PUTS(fd, "\\U"); _Py_DumpHexadecimal(fd, ch, 8); } } if (truncated) { PUTS(fd, "..."); } } /* Write a frame into the file fd: "File "xxx", line xxx in xxx". This function is signal safe. */ static void dump_frame(int fd, PyFrameObject *frame) { PyCodeObject *code; int lineno; code = frame->f_code; PUTS(fd, " File "); if (code != NULL && code->co_filename != NULL && PyUnicode_Check(code->co_filename)) { PUTS(fd, "\""); _Py_DumpASCII(fd, code->co_filename); PUTS(fd, "\""); } else { PUTS(fd, "???"); } /* PyFrame_GetLineNumber() was introduced in Python 2.7.0 and 3.2.0 */ lineno = PyCode_Addr2Line(code, frame->f_lasti); PUTS(fd, ", line "); if (lineno >= 0) { _Py_DumpDecimal(fd, (unsigned long)lineno); } else { PUTS(fd, "???"); } PUTS(fd, " in "); if (code != NULL && code->co_name != NULL && PyUnicode_Check(code->co_name)) { _Py_DumpASCII(fd, code->co_name); } else { PUTS(fd, "???"); } PUTS(fd, "\n"); } static void dump_traceback(int fd, PyThreadState *tstate, int write_header) { PyFrameObject *frame; unsigned int depth; if (write_header) PUTS(fd, "Stack (most recent call first):\n"); frame = _PyThreadState_GetFrame(tstate); if (frame == NULL) return; depth = 0; while (frame != NULL) { if (MAX_FRAME_DEPTH <= depth) { PUTS(fd, " ...\n"); break; } if (!PyFrame_Check(frame)) break; dump_frame(fd, frame); frame = frame->f_back; depth++; } } /* Dump the traceback of a Python thread into fd. Use write() to write the traceback and retry if write() is interrupted by a signal (failed with EINTR), but don't call the Python signal handler. The caller is responsible to call PyErr_CheckSignals() to call Python signal handlers if signals were received. */ void _Py_DumpTraceback(int fd, PyThreadState *tstate) { dump_traceback(fd, tstate, 1); } /* Write the thread identifier into the file 'fd': "Current thread 0xHHHH:\" if is_current is true, "Thread 0xHHHH:\n" otherwise. This function is signal safe. */ static void write_thread_id(int fd, PyThreadState *tstate, int is_current) { if (is_current) PUTS(fd, "Current thread 0x"); else PUTS(fd, "Thread 0x"); _Py_DumpHexadecimal(fd, (unsigned long)tstate->thread_id, sizeof(unsigned long) * 2); PUTS(fd, " (most recent call first):\n"); } /* Dump the traceback of all Python threads into fd. Use write() to write the traceback and retry if write() is interrupted by a signal (failed with EINTR), but don't call the Python signal handler. The caller is responsible to call PyErr_CheckSignals() to call Python signal handlers if signals were received. */ const char* _Py_DumpTracebackThreads(int fd, PyInterpreterState *interp, PyThreadState *current_tstate) { PyThreadState *tstate; unsigned int nthreads; #ifdef WITH_THREAD if (current_tstate == NULL) { /* _Py_DumpTracebackThreads() is called from signal handlers by faulthandler. SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and are thus delivered to the thread that caused the fault. Get the Python thread state of the current thread. PyThreadState_Get() doesn't give the state of the thread that caused the fault if the thread released the GIL, and so this function cannot be used. Read the thread local storage (TLS) instead: call PyGILState_GetThisThreadState(). */ current_tstate = PyGILState_GetThisThreadState(); } if (interp == NULL) { if (current_tstate == NULL) { interp = _PyGILState_GetInterpreterStateUnsafe(); if (interp == NULL) { /* We need the interpreter state to get Python threads */ return "unable to get the interpreter state"; } } else { interp = current_tstate->interp; } } #else if (current_tstate == NULL) { /* Call _PyThreadState_UncheckedGet() instead of PyThreadState_Get() to not fail with a fatal error if the thread state is NULL. */ current_tstate = _PyThreadState_UncheckedGet(); } if (interp == NULL) { if (current_tstate == NULL) { /* We need the interpreter state to get Python threads */ return "unable to get the interpreter state"; } interp = current_tstate->interp; } #endif assert(interp != NULL); /* Get the current interpreter from the current thread */ tstate = PyInterpreterState_ThreadHead(interp); if (tstate == NULL) return "unable to get the thread head state"; /* Dump the traceback of each thread */ tstate = PyInterpreterState_ThreadHead(interp); nthreads = 0; _Py_BEGIN_SUPPRESS_IPH do { if (nthreads != 0) PUTS(fd, "\n"); if (nthreads >= MAX_NTHREADS) { PUTS(fd, "...\n"); break; } write_thread_id(fd, tstate, tstate == current_tstate); dump_traceback(fd, tstate, 0); tstate = PyThreadState_Next(tstate); nthreads++; } while (tstate != NULL); _Py_END_SUPPRESS_IPH return NULL; }
24,223
842
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/opcode_targets.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ static void *const opcode_targets[256] = { &&_unknown_opcode, &&TARGET_POP_TOP, &&TARGET_ROT_TWO, &&TARGET_ROT_THREE, &&TARGET_DUP_TOP, &&TARGET_DUP_TOP_TWO, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&TARGET_NOP, &&TARGET_UNARY_POSITIVE, &&TARGET_UNARY_NEGATIVE, &&TARGET_UNARY_NOT, &&_unknown_opcode, &&_unknown_opcode, &&TARGET_UNARY_INVERT, &&TARGET_BINARY_MATRIX_MULTIPLY, &&TARGET_INPLACE_MATRIX_MULTIPLY, &&_unknown_opcode, &&TARGET_BINARY_POWER, &&TARGET_BINARY_MULTIPLY, &&_unknown_opcode, &&TARGET_BINARY_MODULO, &&TARGET_BINARY_ADD, &&TARGET_BINARY_SUBTRACT, &&TARGET_BINARY_SUBSCR, &&TARGET_BINARY_FLOOR_DIVIDE, &&TARGET_BINARY_TRUE_DIVIDE, &&TARGET_INPLACE_FLOOR_DIVIDE, &&TARGET_INPLACE_TRUE_DIVIDE, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&TARGET_GET_AITER, &&TARGET_GET_ANEXT, &&TARGET_BEFORE_ASYNC_WITH, &&_unknown_opcode, &&_unknown_opcode, &&TARGET_INPLACE_ADD, &&TARGET_INPLACE_SUBTRACT, &&TARGET_INPLACE_MULTIPLY, &&_unknown_opcode, &&TARGET_INPLACE_MODULO, &&TARGET_STORE_SUBSCR, &&TARGET_DELETE_SUBSCR, &&TARGET_BINARY_LSHIFT, &&TARGET_BINARY_RSHIFT, &&TARGET_BINARY_AND, &&TARGET_BINARY_XOR, &&TARGET_BINARY_OR, &&TARGET_INPLACE_POWER, &&TARGET_GET_ITER, &&TARGET_GET_YIELD_FROM_ITER, &&TARGET_PRINT_EXPR, &&TARGET_LOAD_BUILD_CLASS, &&TARGET_YIELD_FROM, &&TARGET_GET_AWAITABLE, &&_unknown_opcode, &&TARGET_INPLACE_LSHIFT, &&TARGET_INPLACE_RSHIFT, &&TARGET_INPLACE_AND, &&TARGET_INPLACE_XOR, &&TARGET_INPLACE_OR, &&TARGET_BREAK_LOOP, &&TARGET_WITH_CLEANUP_START, &&TARGET_WITH_CLEANUP_FINISH, &&TARGET_RETURN_VALUE, &&TARGET_IMPORT_STAR, &&TARGET_SETUP_ANNOTATIONS, &&TARGET_YIELD_VALUE, &&TARGET_POP_BLOCK, &&TARGET_END_FINALLY, &&TARGET_POP_EXCEPT, &&TARGET_STORE_NAME, &&TARGET_DELETE_NAME, &&TARGET_UNPACK_SEQUENCE, &&TARGET_FOR_ITER, &&TARGET_UNPACK_EX, &&TARGET_STORE_ATTR, &&TARGET_DELETE_ATTR, &&TARGET_STORE_GLOBAL, &&TARGET_DELETE_GLOBAL, &&_unknown_opcode, &&TARGET_LOAD_CONST, &&TARGET_LOAD_NAME, &&TARGET_BUILD_TUPLE, &&TARGET_BUILD_LIST, &&TARGET_BUILD_SET, &&TARGET_BUILD_MAP, &&TARGET_LOAD_ATTR, &&TARGET_COMPARE_OP, &&TARGET_IMPORT_NAME, &&TARGET_IMPORT_FROM, &&TARGET_JUMP_FORWARD, &&TARGET_JUMP_IF_FALSE_OR_POP, &&TARGET_JUMP_IF_TRUE_OR_POP, &&TARGET_JUMP_ABSOLUTE, &&TARGET_POP_JUMP_IF_FALSE, &&TARGET_POP_JUMP_IF_TRUE, &&TARGET_LOAD_GLOBAL, &&_unknown_opcode, &&_unknown_opcode, &&TARGET_CONTINUE_LOOP, &&TARGET_SETUP_LOOP, &&TARGET_SETUP_EXCEPT, &&TARGET_SETUP_FINALLY, &&_unknown_opcode, &&TARGET_LOAD_FAST, &&TARGET_STORE_FAST, &&TARGET_DELETE_FAST, &&TARGET_STORE_ANNOTATION, &&_unknown_opcode, &&_unknown_opcode, &&TARGET_RAISE_VARARGS, &&TARGET_CALL_FUNCTION, &&TARGET_MAKE_FUNCTION, &&TARGET_BUILD_SLICE, &&_unknown_opcode, &&TARGET_LOAD_CLOSURE, &&TARGET_LOAD_DEREF, &&TARGET_STORE_DEREF, &&TARGET_DELETE_DEREF, &&_unknown_opcode, &&_unknown_opcode, &&TARGET_CALL_FUNCTION_KW, &&TARGET_CALL_FUNCTION_EX, &&TARGET_SETUP_WITH, &&TARGET_EXTENDED_ARG, &&TARGET_LIST_APPEND, &&TARGET_SET_ADD, &&TARGET_MAP_ADD, &&TARGET_LOAD_CLASSDEREF, &&TARGET_BUILD_LIST_UNPACK, &&TARGET_BUILD_MAP_UNPACK, &&TARGET_BUILD_MAP_UNPACK_WITH_CALL, &&TARGET_BUILD_TUPLE_UNPACK, &&TARGET_BUILD_SET_UNPACK, &&TARGET_SETUP_ASYNC_WITH, &&TARGET_FORMAT_VALUE, &&TARGET_BUILD_CONST_KEY_MAP, &&TARGET_BUILD_STRING, &&TARGET_BUILD_TUPLE_UNPACK_WITH_CALL, &&_unknown_opcode, &&TARGET_LOAD_METHOD, &&TARGET_CALL_METHOD, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode };
7,345
267
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/xedmodule.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/yoink.h" #include "third_party/xed/x86.h" /* clang-format off */ PYTHON_PROVIDE("xed"); PYTHON_PROVIDE("xed.ild"); PyDoc_STRVAR(xed_doc, "Xed Module\n\ \n\ This module exposes low-level utilities for x86 encoding."); PyDoc_STRVAR(ild_doc, "ild($module, bytes)\n\ --\n\n\ Decodes byte-length of first machine instruction in byte sequence.\n\ \n\ This function makes it possible to tokenize raw x86 binary instructions.\n\ Return value is negative on error, where -1 is defined as buffer being\n\ too short, and lower numbers represent other errors."); static PyObject * xed_ild(PyObject *self, PyObject *args) { int e; Py_ssize_t n; const char *p; struct XedDecodedInst xedd; if (!PyArg_ParseTuple(args, "y#:ild", &p, &n)) return 0; xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64); e = xed_instruction_length_decode(&xedd, p, n); return PyLong_FromUnsignedLong(e ? -e : xedd.length); } static PyMethodDef xed_methods[] = { {"ild", xed_ild, METH_VARARGS, ild_doc}, {0}, }; static struct PyModuleDef xedmodule = { PyModuleDef_HEAD_INIT, "xed", xed_doc, -1, xed_methods, }; PyMODINIT_FUNC PyInit_xed(void) { return PyModule_Create(&xedmodule); } _Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_xed = { "xed", PyInit_xed, };
3,531
82
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pylifecycle.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/dce.h" #include "libc/fmt/conv.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/sig.h" #include "libc/str/locale.h" #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/ast.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/cosmo.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/errcode.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/intrcheck.h" #include "third_party/python/Include/marshal.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/osdefs.h" #include "third_party/python/Include/parsetok.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystrcmp.h" #include "third_party/python/Include/pytime.h" #include "third_party/python/Include/symtable.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/token.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Include/yoink.h" #include "third_party/python/pyconfig.h" /* clang-format off */ /* Python interpreter top-level routines, including init/exit */ _Py_IDENTIFIER(name); _Py_IDENTIFIER(flush); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); /* Forward */ void wait_for_thread_shutdown(void); #ifdef WITH_THREAD extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *); extern void _PyGILState_Fini(void); #endif /* WITH_THREAD */ /* Hack to force loading of object files */ int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \ PyOS_mystrnicmp; /* Python/pystrcmp.o */ /* Helper to allow an embedding application to override the normal * mechanism that attempts to figure out an appropriate IO encoding */ int Py_SetStandardStreamEncoding(const char *encoding, const char *errors) { if (Py_IsInitialized()) { /* This is too late to have any effect */ return -1; } /* Can't call PyErr_NoMemory() on errors, as Python hasn't been * initialised yet. * * However, the raw memory allocators are initialised appropriately * as C static variables, so _PyMem_RawStrdup is OK even though * Py_Initialize hasn't been called yet. */ if (encoding) { _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding); if (!_Py_StandardStreamEncoding) { return -2; } } if (errors) { _Py_StandardStreamErrors = _PyMem_RawStrdup(errors); if (!_Py_StandardStreamErrors) { if (_Py_StandardStreamEncoding) { PyMem_RawFree(_Py_StandardStreamEncoding); } return -3; } } #ifdef MS_WINDOWS if (_Py_StandardStreamEncoding) { /* Overriding the stream encoding implies legacy streams */ Py_LegacyWindowsStdioFlag = 1; } #endif return 0; } /* Global initializations. Can be undone by Py_FinalizeEx(). Don't call this twice without an intervening Py_FinalizeEx() call. When initializations fail, a fatal error is issued and the function does not return. On return, the first thread and interpreter state have been created. Locking: you must hold the interpreter lock while calling this. (If the lock has not yet been initialized, that's equivalent to having the lock, but you cannot use multiple threads.) */ static int add_flag(int flag, const char *envs) { int env = atoi(envs); if (flag < env) flag = env; if (flag < 1) flag = 1; return flag; } void _Py_InitializeEx_Private(int install_sigs, int install_importlib) { PyInterpreterState *interp; PyThreadState *tstate; PyObject *bimod, *sysmod, *pstderr; char *p; if (_Py_initialized) return; _Py_initialized = 1; _Py_Finalizing = NULL; #ifdef HAVE_SETLOCALE /* Set up the LC_CTYPE locale, so we can obtain the locale's charset without having to switch locales. */ setlocale(LC_CTYPE, ""); #endif if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') Py_DebugFlag = add_flag(Py_DebugFlag, p); if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') Py_VerboseFlag = add_flag(Py_VerboseFlag, p); if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); #ifdef MS_WINDOWS if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0') Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p); if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0') Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p); #endif _PyRandom_Init(); interp = PyInterpreterState_New(); if (interp == NULL) Py_FatalError("Py_Initialize: can't make first interpreter"); tstate = PyThreadState_New(interp); if (tstate == NULL) Py_FatalError("Py_Initialize: can't make first thread"); (void) PyThreadState_Swap(tstate); #ifdef WITH_THREAD /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because destroying the GIL might fail when it is being referenced from another running thread (see issue #9901). Instead we destroy the previously created GIL here, which ensures that we can call Py_Initialize / Py_FinalizeEx multiple times. */ _PyEval_FiniThreads(); /* Auto-thread-state API */ _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ _Py_ReadyTypes(); if (!_PyFrame_Init()) Py_FatalError("Py_Initialize: can't init frames"); if (!_PyLong_Init()) Py_FatalError("Py_Initialize: can't init longs"); if (!PyByteArray_Init()) Py_FatalError("Py_Initialize: can't init bytearray"); if (!_PyFloat_Init()) Py_FatalError("Py_Initialize: can't init float"); interp->modules = PyDict_New(); if (interp->modules == NULL) Py_FatalError("Py_Initialize: can't make modules dictionary"); /* Init Unicode implementation; relies on the codec registry */ if (_PyUnicode_Init() < 0) Py_FatalError("Py_Initialize: can't initialize unicode"); if (_PyStructSequence_Init() < 0) Py_FatalError("Py_Initialize: can't initialize structseq"); bimod = _PyBuiltin_Init(); if (bimod == NULL) Py_FatalError("Py_Initialize: can't initialize builtins modules"); _PyImport_FixupBuiltin(bimod, "builtins"); interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) Py_FatalError("Py_Initialize: can't initialize builtins dict"); Py_INCREF(interp->builtins); /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PySys_Init(); if (sysmod == NULL) Py_FatalError("Py_Initialize: can't initialize sys"); interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) Py_FatalError("Py_Initialize: can't initialize sys dict"); Py_INCREF(interp->sysdict); _PyImport_FixupBuiltin(sysmod, "sys"); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImportLookupTables_Init(); _PyImport_Init(); _PyImportHooks_Init(); /* Initialize _warnings. */ _PyWarnings_Init(); if (!install_importlib) return; if (_PyTime_Init() < 0) Py_FatalError("Py_Initialize: can't initialize time"); _Py_InitImport(interp, sysmod); /* initialize the faulthandler module */ if (_PyFaulthandler_Init()) Py_FatalError("Py_Initialize: can't initialize faulthandler"); if (_Py_InitFsEncoding(interp) < 0) Py_FatalError("Py_Initialize: unable to load the file system codec"); if (install_sigs) _Py_InitSigs(); /* Signal handling stuff, including initintr() */ #if IsModeDbg() if (_PyTraceMalloc_Init() < 0) Py_FatalError("Py_Initialize: can't initialize tracemalloc"); #endif _Py_InitMain(interp); /* Module __main__ */ if (_Py_InitStdio() < 0) { Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); } /* Initialize warnings. */ if (PySys_HasWarnOptions()) { PyObject *warnings_module = PyImport_ImportModule("warnings"); if (warnings_module == NULL) { fputs("'import warnings' failed; traceback:\n", stderr); PyErr_Print(); } Py_XDECREF(warnings_module); } _PyImportZip_Init(); if (!Py_NoSiteFlag) _Py_InitSite(); /* Module site */ } void Py_InitializeEx(int install_sigs) { _Py_InitializeEx_Private(install_sigs, 1); } void Py_Initialize(void) { Py_InitializeEx(1); } #ifdef COUNT_ALLOCS extern void dump_counts(FILE*); #endif /* Create and initialize a new interpreter and thread, and return the new thread. This requires that Py_Initialize() has been called first. Unsuccessful initialization yields a NULL pointer. Note that *no* exception information is available even in this case -- the exception information is held in the thread, and there is no thread. Locking: as above. */ PyThreadState * Py_NewInterpreter(void) { PyInterpreterState *interp; PyThreadState *tstate, *save_tstate; PyObject *bimod, *sysmod; if (!_Py_initialized) Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); #ifdef WITH_THREAD /* Issue #10915, #15751: The GIL API doesn't work with multiple interpreters: disable PyGILState_Check(). */ _PyGILState_check_enabled = 0; #endif interp = PyInterpreterState_New(); if (interp == NULL) return NULL; tstate = PyThreadState_New(interp); if (tstate == NULL) { PyInterpreterState_Delete(interp); return NULL; } save_tstate = PyThreadState_Swap(tstate); /* XXX The following is lax in error checking */ interp->modules = PyDict_New(); bimod = _PyImport_FindBuiltin("builtins"); if (bimod != NULL) { interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) goto handle_error; Py_INCREF(interp->builtins); } else if (PyErr_Occurred()) { goto handle_error; } /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PyImport_FindBuiltin("sys"); if (bimod != NULL && sysmod != NULL) { PyObject *pstderr; interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) goto handle_error; Py_INCREF(interp->sysdict); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImportHooks_Init(); _Py_InitImport(interp, sysmod); if (_Py_InitFsEncoding(interp) < 0) goto handle_error; if (_Py_InitStdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); _Py_InitMain(interp); if (!Py_NoSiteFlag) _Py_InitSite(); } if (!PyErr_Occurred()) return tstate; handle_error: /* Oops, it didn't work. Undo it all. */ PyErr_PrintEx(0); PyThreadState_Clear(tstate); PyThreadState_Swap(save_tstate); PyThreadState_Delete(tstate); PyInterpreterState_Delete(interp); return NULL; } /* Delete an interpreter and its last thread. This requires that the given thread state is current, that the thread has no remaining frames, and that it is its interpreter's only remaining thread. It is a fatal error to violate these constraints. (Py_FinalizeEx() doesn't have these constraints -- it zaps everything, regardless.) Locking: as above. */ void Py_EndInterpreter(PyThreadState *tstate) { PyInterpreterState *interp = tstate->interp; if (tstate != PyThreadState_GET()) Py_FatalError("Py_EndInterpreter: thread is not current"); if (tstate->frame != NULL) Py_FatalError("Py_EndInterpreter: thread still has a frame"); wait_for_thread_shutdown(); if (tstate != interp->tstate_head || tstate->next != NULL) Py_FatalError("Py_EndInterpreter: not the last thread"); PyImport_Cleanup(); PyInterpreterState_Clear(interp); PyThreadState_Swap(NULL); PyInterpreterState_Delete(interp); } /* Clean up and exit */ #ifdef WITH_THREAD #include "third_party/python/Include/pythread.h" #endif /* Wait until threading._shutdown completes, provided the threading module was imported in the first place. The shutdown routine will wait until all non-daemon "threading" threads have completed. */ void wait_for_thread_shutdown(void) { #ifdef WITH_THREAD _Py_IDENTIFIER(_shutdown); PyObject *result; PyThreadState *tstate = PyThreadState_GET(); PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, "threading"); if (threading == NULL) { /* threading not imported */ PyErr_Clear(); return; } result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL); if (result == NULL) { PyErr_WriteUnraisable(threading); } else { Py_DECREF(result); } Py_DECREF(threading); #endif } void Py_Exit(int sts) { if (Py_FinalizeEx() < 0) { sts = 120; } exit(sts); }
16,023
507
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/wordcode_helpers.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/code.h" /* clang-format off */ /* This file contains code shared by the compiler and the peephole optimizer. */ #ifdef WORDS_BIGENDIAN # define PACKOPARG(opcode, oparg) ((_Py_CODEUNIT)(((opcode) << 8) | (oparg))) #else # define PACKOPARG(opcode, oparg) ((_Py_CODEUNIT)(((oparg) << 8) | (opcode))) #endif /* Minimum number of code units necessary to encode instruction with EXTENDED_ARGs */ static int instrsize(unsigned int oparg) { return oparg <= 0xff ? 1 : oparg <= 0xffff ? 2 : oparg <= 0xffffff ? 3 : 4; } /* Spits out op/oparg pair using ilen bytes. codestr should be pointed at the desired location of the first EXTENDED_ARG */ static void write_op_arg(_Py_CODEUNIT *codestr, unsigned char opcode, unsigned int oparg, int ilen) { switch (ilen) { case 4: *codestr++ = PACKOPARG(EXTENDED_ARG, (oparg >> 24) & 0xff); /* fall through */ case 3: *codestr++ = PACKOPARG(EXTENDED_ARG, (oparg >> 16) & 0xff); /* fall through */ case 2: *codestr++ = PACKOPARG(EXTENDED_ARG, (oparg >> 8) & 0xff); /* fall through */ case 1: *codestr++ = PACKOPARG(opcode, oparg & 0xff); break; default: assert(0); } }
2,155
54
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/flushstdfiles.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/sysmodule.h" /* clang-format off */ _Py_IDENTIFIER(flush); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); static int file_is_closed(PyObject *fobj) { int r; PyObject *tmp = PyObject_GetAttrString(fobj, "closed"); if (tmp == NULL) { PyErr_Clear(); return 0; } r = PyObject_IsTrue(tmp); Py_DECREF(tmp); if (r < 0) PyErr_Clear(); return r > 0; } int _Py_FlushStdFiles(void) { PyObject *fout = _PySys_GetObjectId(&PyId_stdout); PyObject *ferr = _PySys_GetObjectId(&PyId_stderr); PyObject *tmp; int status = 0; if (fout != NULL && fout != Py_None && !file_is_closed(fout)) { tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL); if (tmp == NULL) { PyErr_WriteUnraisable(fout); status = -1; } else Py_DECREF(tmp); } if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) { tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL); if (tmp == NULL) { PyErr_Clear(); status = -1; } else Py_DECREF(tmp); } return status; }
2,201
61
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/initfsencoding.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ _Py_IDENTIFIER(name); static char * get_codec_name(const char *encoding) { char *name_utf8, *name_str; PyObject *codec, *name = NULL; codec = _PyCodec_Lookup(encoding); if (!codec) goto error; name = _PyObject_GetAttrId(codec, &PyId_name); Py_CLEAR(codec); if (!name) goto error; name_utf8 = PyUnicode_AsUTF8(name); if (name_utf8 == NULL) goto error; name_str = _PyMem_RawStrdup(name_utf8); Py_DECREF(name); if (name_str == NULL) { PyErr_NoMemory(); return NULL; } return name_str; error: Py_XDECREF(codec); Py_XDECREF(name); return NULL; } static char * get_locale_encoding(void) { #ifdef MS_WINDOWS char codepage[100]; PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP()); return get_codec_name(codepage); #elif defined(__ANDROID__) || defined(__COSMOPOLITAN__) return get_codec_name("UTF-8"); #elif defined(HAVE_LANGINFO_H) && defined(CODESET) char* codeset = nl_langinfo(CODESET); if (!codeset || codeset[0] == '\0') { PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty"); return NULL; } return get_codec_name(codeset); #else PyErr_SetNone(PyExc_NotImplementedError); return NULL; #endif } int _Py_InitFsEncoding(PyInterpreterState *interp) { PyObject *codec; #ifdef MS_WINDOWS if (Py_LegacyWindowsFSEncodingFlag) { Py_FileSystemDefaultEncoding = "mbcs"; Py_FileSystemDefaultEncodeErrors = "replace"; } else { Py_FileSystemDefaultEncoding = "utf-8"; Py_FileSystemDefaultEncodeErrors = "surrogatepass"; } #else if (Py_FileSystemDefaultEncoding == NULL) { Py_FileSystemDefaultEncoding = get_locale_encoding(); if (Py_FileSystemDefaultEncoding == NULL) Py_FatalError("Py_Initialize: Unable to get the locale encoding"); Py_HasFileSystemDefaultEncoding = 0; interp->fscodec_initialized = 1; return 0; } #endif /* the encoding is mbcs, utf-8 or ascii */ codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding); if (!codec) { /* Such error can only occurs in critical situations: no more * memory, import a module of the standard library failed, * etc. */ return -1; } Py_DECREF(codec); interp->fscodec_initialized = 1; return 0; }
3,583
108
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/asdl.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/asdl.h" #include "third_party/python/Include/pyerrors.h" /* clang-format off */ asdl_seq * _Py_asdl_seq_new(Py_ssize_t size, PyArena *arena) { asdl_seq *seq = NULL; size_t n; /* check size is sane */ if (size < 0 || (size && (((size_t)size - 1) > (SIZE_MAX / sizeof(void *))))) { PyErr_NoMemory(); return NULL; } n = (size ? (sizeof(void *) * (size - 1)) : 0); /* check if size can be added safely */ if (n > SIZE_MAX - sizeof(asdl_seq)) { PyErr_NoMemory(); return NULL; } n += sizeof(asdl_seq); seq = (asdl_seq *)PyArena_Malloc(arena, n); if (!seq) { PyErr_NoMemory(); return NULL; } bzero(seq, n); seq->size = size; return seq; } asdl_int_seq * _Py_asdl_int_seq_new(Py_ssize_t size, PyArena *arena) { asdl_int_seq *seq = NULL; size_t n; /* check size is sane */ if (size < 0 || (size && (((size_t)size - 1) > (SIZE_MAX / sizeof(void *))))) { PyErr_NoMemory(); return NULL; } n = (size ? (sizeof(void *) * (size - 1)) : 0); /* check if size can be added safely */ if (n > SIZE_MAX - sizeof(asdl_seq)) { PyErr_NoMemory(); return NULL; } n += sizeof(asdl_seq); seq = (asdl_int_seq *)PyArena_Malloc(arena, n); if (!seq) { PyErr_NoMemory(); return NULL; } bzero(seq, n); seq->size = size; return seq; }
2,309
72
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/dynload_shlib.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/weirdtypes.h" #include "libc/runtime/dlfcn.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Python/importdl.h" /* clang-format off */ #define SOABI "cpython36m-x86_64-cosmo" #if (defined(__OpenBSD__) || defined(__NetBSD__)) && !defined(__ELF__) #define LEAD_UNDERSCORE "_" #else #define LEAD_UNDERSCORE "" #endif /* The .so extension module ABI tag, supplied by the Makefile via Makefile.pre.in and configure. This is used to discriminate between incompatible .so files so that extensions for different Python builds can live in the same directory. E.g. foomodule.cpython-32.so */ const char *_PyImport_DynLoadFiletab[] = { #ifdef __CYGWIN__ ".dll", #else /* !__CYGWIN__ */ "." SOABI ".so", ".abi" PYTHON_ABI_STRING ".so", ".so", #endif /* __CYGWIN__ */ NULL, }; static struct { dev_t dev; ino_t ino; void *handle; } handles[128]; static int nhandles = 0; dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix, const char *shortname, const char *pathname, FILE *fp) { dl_funcptr p; void *handle; char funcname[258]; char pathbuf[260]; int dlopenflags=0; if (strchr(pathname, '/') == NULL) { /* Prefix bare filename with "./" */ PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname); pathname = pathbuf; } PyOS_snprintf(funcname, sizeof(funcname), LEAD_UNDERSCORE "%.20s_%.200s", prefix, shortname); if (fp != NULL) { int i; struct _Py_stat_struct status; if (_Py_fstat(fileno(fp), &status) == -1) return NULL; for (i = 0; i < nhandles; i++) { if (status.st_dev == handles[i].dev && status.st_ino == handles[i].ino) { p = (dl_funcptr) dlsym(handles[i].handle, funcname); return p; } } if (nhandles < 128) { handles[nhandles].dev = status.st_dev; handles[nhandles].ino = status.st_ino; } } dlopenflags = PyThreadState_GET()->interp->dlopenflags; handle = dlopen(pathname, dlopenflags); if (handle == NULL) { PyObject *mod_name; PyObject *path; PyObject *error_ob; const char *error = dlerror(); if (error == NULL) error = "unknown dlopen() error"; error_ob = PyUnicode_FromString(error); if (error_ob == NULL) return NULL; mod_name = PyUnicode_FromString(shortname); if (mod_name == NULL) { Py_DECREF(error_ob); return NULL; } path = PyUnicode_FromString(pathname); if (path == NULL) { Py_DECREF(error_ob); Py_DECREF(mod_name); return NULL; } PyErr_SetImportError(error_ob, mod_name, path); Py_DECREF(error_ob); Py_DECREF(mod_name); Py_DECREF(path); return NULL; } if (fp != NULL && nhandles < 128) handles[nhandles++].handle = handle; p = (dl_funcptr) dlsym(handle, funcname); return p; }
4,176
118
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pystrhex.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ /* bytes to hex implementation */ static PyObject *_Py_strhex_impl(const char* argbuf, const Py_ssize_t arglen, int return_bytes) { PyObject *retval; Py_UCS1* retbuf; Py_ssize_t i, j; assert(arglen >= 0); if (arglen > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); if (return_bytes) { /* If _PyBytes_FromSize() were public we could avoid malloc+copy. */ retbuf = (Py_UCS1*) PyMem_Malloc(arglen*2); if (!retbuf) return PyErr_NoMemory(); retval = NULL; /* silence a compiler warning, assigned later. */ } else { retval = PyUnicode_New(arglen*2, 127); if (!retval) return NULL; retbuf = PyUnicode_1BYTE_DATA(retval); } /* make hex version of string, taken from shamodule.c */ for (i=j=0; i < arglen; i++) { unsigned char c; c = (argbuf[i] >> 4) & 0xf; retbuf[j++] = Py_hexdigits[c]; c = argbuf[i] & 0xf; retbuf[j++] = Py_hexdigits[c]; } if (return_bytes) { retval = PyBytes_FromStringAndSize((const char *)retbuf, arglen*2); PyMem_Free(retbuf); } #ifdef Py_DEBUG else { assert(_PyUnicode_CheckConsistency(retval, 1)); } #endif return retval; } PyObject * _Py_strhex(const char* argbuf, const Py_ssize_t arglen) { return _Py_strhex_impl(argbuf, arglen, 0); } /* Same as above but returns a bytes() instead of str() to avoid the * need to decode the str() when bytes are needed. */ PyObject * _Py_strhex_bytes(const char* argbuf, const Py_ssize_t arglen) { return _Py_strhex_impl(argbuf, arglen, 1); }
2,780
75
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/Python-ast.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ PYTHON_PROVIDE("_ast"); /* File automatically generated by Parser/asdl_c.py. */ static PyTypeObject AST_type; static PyTypeObject *mod_type; static PyObject* ast2obj_mod(void*); static PyTypeObject *Module_type; _Py_IDENTIFIER(body); static char *Module_fields[]={ "body", }; static PyTypeObject *Interactive_type; static char *Interactive_fields[]={ "body", }; static PyTypeObject *Expression_type; static char *Expression_fields[]={ "body", }; static PyTypeObject *Suite_type; static char *Suite_fields[]={ "body", }; static PyTypeObject *stmt_type; _Py_IDENTIFIER(lineno); _Py_IDENTIFIER(col_offset); static char *stmt_attributes[] = { "lineno", "col_offset", }; static PyObject* ast2obj_stmt(void*); static PyTypeObject *FunctionDef_type; _Py_IDENTIFIER(name); _Py_IDENTIFIER(args); _Py_IDENTIFIER(decorator_list); _Py_IDENTIFIER(returns); static char *FunctionDef_fields[]={ "name", "args", "body", "decorator_list", "returns", }; static PyTypeObject *AsyncFunctionDef_type; static char *AsyncFunctionDef_fields[]={ "name", "args", "body", "decorator_list", "returns", }; static PyTypeObject *ClassDef_type; _Py_IDENTIFIER(bases); _Py_IDENTIFIER(keywords); static char *ClassDef_fields[]={ "name", "bases", "keywords", "body", "decorator_list", }; static PyTypeObject *Return_type; _Py_IDENTIFIER(value); static char *Return_fields[]={ "value", }; static PyTypeObject *Delete_type; _Py_IDENTIFIER(targets); static char *Delete_fields[]={ "targets", }; static PyTypeObject *Assign_type; static char *Assign_fields[]={ "targets", "value", }; static PyTypeObject *AugAssign_type; _Py_IDENTIFIER(target); _Py_IDENTIFIER(op); static char *AugAssign_fields[]={ "target", "op", "value", }; static PyTypeObject *AnnAssign_type; _Py_IDENTIFIER(annotation); _Py_IDENTIFIER(simple); static char *AnnAssign_fields[]={ "target", "annotation", "value", "simple", }; static PyTypeObject *For_type; _Py_IDENTIFIER(iter); _Py_IDENTIFIER(orelse); static char *For_fields[]={ "target", "iter", "body", "orelse", }; static PyTypeObject *AsyncFor_type; static char *AsyncFor_fields[]={ "target", "iter", "body", "orelse", }; static PyTypeObject *While_type; _Py_IDENTIFIER(test); static char *While_fields[]={ "test", "body", "orelse", }; static PyTypeObject *If_type; static char *If_fields[]={ "test", "body", "orelse", }; static PyTypeObject *With_type; _Py_IDENTIFIER(items); static char *With_fields[]={ "items", "body", }; static PyTypeObject *AsyncWith_type; static char *AsyncWith_fields[]={ "items", "body", }; static PyTypeObject *Raise_type; _Py_IDENTIFIER(exc); _Py_IDENTIFIER(cause); static char *Raise_fields[]={ "exc", "cause", }; static PyTypeObject *Try_type; _Py_IDENTIFIER(handlers); _Py_IDENTIFIER(finalbody); static char *Try_fields[]={ "body", "handlers", "orelse", "finalbody", }; static PyTypeObject *Assert_type; _Py_IDENTIFIER(msg); static char *Assert_fields[]={ "test", "msg", }; static PyTypeObject *Import_type; _Py_IDENTIFIER(names); static char *Import_fields[]={ "names", }; static PyTypeObject *ImportFrom_type; _Py_IDENTIFIER(module); _Py_IDENTIFIER(level); static char *ImportFrom_fields[]={ "module", "names", "level", }; static PyTypeObject *Global_type; static char *Global_fields[]={ "names", }; static PyTypeObject *Nonlocal_type; static char *Nonlocal_fields[]={ "names", }; static PyTypeObject *Expr_type; static char *Expr_fields[]={ "value", }; static PyTypeObject *Pass_type; static PyTypeObject *Break_type; static PyTypeObject *Continue_type; static PyTypeObject *expr_type; static char *expr_attributes[] = { "lineno", "col_offset", }; static PyObject* ast2obj_expr(void*); static PyTypeObject *BoolOp_type; _Py_IDENTIFIER(values); static char *BoolOp_fields[]={ "op", "values", }; static PyTypeObject *BinOp_type; _Py_IDENTIFIER(left); _Py_IDENTIFIER(right); static char *BinOp_fields[]={ "left", "op", "right", }; static PyTypeObject *UnaryOp_type; _Py_IDENTIFIER(operand); static char *UnaryOp_fields[]={ "op", "operand", }; static PyTypeObject *Lambda_type; static char *Lambda_fields[]={ "args", "body", }; static PyTypeObject *IfExp_type; static char *IfExp_fields[]={ "test", "body", "orelse", }; static PyTypeObject *Dict_type; _Py_IDENTIFIER(keys); static char *Dict_fields[]={ "keys", "values", }; static PyTypeObject *Set_type; _Py_IDENTIFIER(elts); static char *Set_fields[]={ "elts", }; static PyTypeObject *ListComp_type; _Py_IDENTIFIER(elt); _Py_IDENTIFIER(generators); static char *ListComp_fields[]={ "elt", "generators", }; static PyTypeObject *SetComp_type; static char *SetComp_fields[]={ "elt", "generators", }; static PyTypeObject *DictComp_type; _Py_IDENTIFIER(key); static char *DictComp_fields[]={ "key", "value", "generators", }; static PyTypeObject *GeneratorExp_type; static char *GeneratorExp_fields[]={ "elt", "generators", }; static PyTypeObject *Await_type; static char *Await_fields[]={ "value", }; static PyTypeObject *Yield_type; static char *Yield_fields[]={ "value", }; static PyTypeObject *YieldFrom_type; static char *YieldFrom_fields[]={ "value", }; static PyTypeObject *Compare_type; _Py_IDENTIFIER(ops); _Py_IDENTIFIER(comparators); static char *Compare_fields[]={ "left", "ops", "comparators", }; static PyTypeObject *Call_type; _Py_IDENTIFIER(func); static char *Call_fields[]={ "func", "args", "keywords", }; static PyTypeObject *Num_type; _Py_IDENTIFIER(n); static char *Num_fields[]={ "n", }; static PyTypeObject *Str_type; _Py_IDENTIFIER(s); static char *Str_fields[]={ "s", }; static PyTypeObject *FormattedValue_type; _Py_IDENTIFIER(conversion); _Py_IDENTIFIER(format_spec); static char *FormattedValue_fields[]={ "value", "conversion", "format_spec", }; static PyTypeObject *JoinedStr_type; static char *JoinedStr_fields[]={ "values", }; static PyTypeObject *Bytes_type; static char *Bytes_fields[]={ "s", }; static PyTypeObject *NameConstant_type; static char *NameConstant_fields[]={ "value", }; static PyTypeObject *Ellipsis_type; static PyTypeObject *Constant_type; static char *Constant_fields[]={ "value", }; static PyTypeObject *Attribute_type; _Py_IDENTIFIER(attr); _Py_IDENTIFIER(ctx); static char *Attribute_fields[]={ "value", "attr", "ctx", }; static PyTypeObject *Subscript_type; _Py_IDENTIFIER(slice); static char *Subscript_fields[]={ "value", "slice", "ctx", }; static PyTypeObject *Starred_type; static char *Starred_fields[]={ "value", "ctx", }; static PyTypeObject *Name_type; _Py_IDENTIFIER(id); static char *Name_fields[]={ "id", "ctx", }; static PyTypeObject *List_type; static char *List_fields[]={ "elts", "ctx", }; static PyTypeObject *Tuple_type; static char *Tuple_fields[]={ "elts", "ctx", }; static PyTypeObject *expr_context_type; static PyObject *Load_singleton, *Store_singleton, *Del_singleton, *AugLoad_singleton, *AugStore_singleton, *Param_singleton; static PyObject* ast2obj_expr_context(expr_context_ty); static PyTypeObject *Load_type; static PyTypeObject *Store_type; static PyTypeObject *Del_type; static PyTypeObject *AugLoad_type; static PyTypeObject *AugStore_type; static PyTypeObject *Param_type; static PyTypeObject *slice_type; static PyObject* ast2obj_slice(void*); static PyTypeObject *Slice_type; _Py_IDENTIFIER(lower); _Py_IDENTIFIER(upper); _Py_IDENTIFIER(step); static char *Slice_fields[]={ "lower", "upper", "step", }; static PyTypeObject *ExtSlice_type; _Py_IDENTIFIER(dims); static char *ExtSlice_fields[]={ "dims", }; static PyTypeObject *Index_type; static char *Index_fields[]={ "value", }; static PyTypeObject *boolop_type; static PyObject *And_singleton, *Or_singleton; static PyObject* ast2obj_boolop(boolop_ty); static PyTypeObject *And_type; static PyTypeObject *Or_type; static PyTypeObject *operator_type; static PyObject *Add_singleton, *Sub_singleton, *Mult_singleton, *MatMult_singleton, *Div_singleton, *Mod_singleton, *Pow_singleton, *LShift_singleton, *RShift_singleton, *BitOr_singleton, *BitXor_singleton, *BitAnd_singleton, *FloorDiv_singleton; static PyObject* ast2obj_operator(operator_ty); static PyTypeObject *Add_type; static PyTypeObject *Sub_type; static PyTypeObject *Mult_type; static PyTypeObject *MatMult_type; static PyTypeObject *Div_type; static PyTypeObject *Mod_type; static PyTypeObject *Pow_type; static PyTypeObject *LShift_type; static PyTypeObject *RShift_type; static PyTypeObject *BitOr_type; static PyTypeObject *BitXor_type; static PyTypeObject *BitAnd_type; static PyTypeObject *FloorDiv_type; static PyTypeObject *unaryop_type; static PyObject *Invert_singleton, *Not_singleton, *UAdd_singleton, *USub_singleton; static PyObject* ast2obj_unaryop(unaryop_ty); static PyTypeObject *Invert_type; static PyTypeObject *Not_type; static PyTypeObject *UAdd_type; static PyTypeObject *USub_type; static PyTypeObject *cmpop_type; static PyObject *Eq_singleton, *NotEq_singleton, *Lt_singleton, *LtE_singleton, *Gt_singleton, *GtE_singleton, *Is_singleton, *IsNot_singleton, *In_singleton, *NotIn_singleton; static PyObject* ast2obj_cmpop(cmpop_ty); static PyTypeObject *Eq_type; static PyTypeObject *NotEq_type; static PyTypeObject *Lt_type; static PyTypeObject *LtE_type; static PyTypeObject *Gt_type; static PyTypeObject *GtE_type; static PyTypeObject *Is_type; static PyTypeObject *IsNot_type; static PyTypeObject *In_type; static PyTypeObject *NotIn_type; static PyTypeObject *comprehension_type; static PyObject* ast2obj_comprehension(void*); _Py_IDENTIFIER(ifs); _Py_IDENTIFIER(is_async); static char *comprehension_fields[]={ "target", "iter", "ifs", "is_async", }; static PyTypeObject *excepthandler_type; static char *excepthandler_attributes[] = { "lineno", "col_offset", }; static PyObject* ast2obj_excepthandler(void*); static PyTypeObject *ExceptHandler_type; _Py_IDENTIFIER(type); static char *ExceptHandler_fields[]={ "type", "name", "body", }; static PyTypeObject *arguments_type; static PyObject* ast2obj_arguments(void*); _Py_IDENTIFIER(vararg); _Py_IDENTIFIER(kwonlyargs); _Py_IDENTIFIER(kw_defaults); _Py_IDENTIFIER(kwarg); _Py_IDENTIFIER(defaults); static char *arguments_fields[]={ "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults", }; static PyTypeObject *arg_type; static PyObject* ast2obj_arg(void*); static char *arg_attributes[] = { "lineno", "col_offset", }; _Py_IDENTIFIER(arg); static char *arg_fields[]={ "arg", "annotation", }; static PyTypeObject *keyword_type; static PyObject* ast2obj_keyword(void*); static char *keyword_fields[]={ "arg", "value", }; static PyTypeObject *alias_type; static PyObject* ast2obj_alias(void*); _Py_IDENTIFIER(asname); static char *alias_fields[]={ "name", "asname", }; static PyTypeObject *withitem_type; static PyObject* ast2obj_withitem(void*); _Py_IDENTIFIER(context_expr); _Py_IDENTIFIER(optional_vars); static char *withitem_fields[]={ "context_expr", "optional_vars", }; typedef struct { PyObject_HEAD PyObject *dict; } AST_object; static void ast_dealloc(AST_object *self) { /* bpo-31095: UnTrack is needed before calling any callbacks */ PyObject_GC_UnTrack(self); Py_CLEAR(self->dict); Py_TYPE(self)->tp_free(self); } static int ast_traverse(AST_object *self, visitproc visit, void *arg) { Py_VISIT(self->dict); return 0; } static int ast_clear(AST_object *self) { Py_CLEAR(self->dict); return 0; } static int ast_type_init(PyObject *self, PyObject *args, PyObject *kw) { _Py_IDENTIFIER(_fields); Py_ssize_t i, numfields = 0; int res = -1; PyObject *key, *value, *fields; fields = _PyObject_GetAttrId((PyObject*)Py_TYPE(self), &PyId__fields); if (!fields) PyErr_Clear(); if (fields) { numfields = PySequence_Size(fields); if (numfields == -1) goto cleanup; } res = 0; /* if no error occurs, this stays 0 to the end */ if (PyTuple_GET_SIZE(args) > 0) { if (numfields != PyTuple_GET_SIZE(args)) { PyErr_Format(PyExc_TypeError, "%.400s constructor takes %s" "%zd positional argument%s", Py_TYPE(self)->tp_name, numfields == 0 ? "" : "either 0 or ", numfields, numfields == 1 ? "" : "s"); res = -1; goto cleanup; } for (i = 0; i < PyTuple_GET_SIZE(args); i++) { /* cannot be reached when fields is NULL */ PyObject *name = PySequence_GetItem(fields, i); if (!name) { res = -1; goto cleanup; } res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i)); Py_DECREF(name); if (res < 0) goto cleanup; } } if (kw) { i = 0; /* needed by PyDict_Next */ while (PyDict_Next(kw, &i, &key, &value)) { res = PyObject_SetAttr(self, key, value); if (res < 0) goto cleanup; } } cleanup: Py_XDECREF(fields); return res; } /* Pickling support */ static PyObject * ast_type_reduce(PyObject *self, PyObject *unused) { PyObject *res; _Py_IDENTIFIER(__dict__); PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__); if (dict == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); else return NULL; } if (dict) { res = Py_BuildValue("O()O", Py_TYPE(self), dict); Py_DECREF(dict); return res; } return Py_BuildValue("O()", Py_TYPE(self)); } static PyMethodDef ast_type_methods[] = { {"__reduce__", ast_type_reduce, METH_NOARGS, NULL}, {NULL} }; static PyGetSetDef ast_type_getsets[] = { {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, {NULL} }; static PyTypeObject AST_type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "_ast.AST", sizeof(AST_object), 0, (destructor)ast_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)ast_traverse, /* tp_traverse */ (inquiry)ast_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ast_type_methods, /* tp_methods */ 0, /* tp_members */ ast_type_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(AST_object, dict),/* tp_dictoffset */ (initproc)ast_type_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields) { PyObject *fnames, *result; int i; fnames = PyTuple_New(num_fields); if (!fnames) return NULL; for (i = 0; i < num_fields; i++) { PyObject *field = PyUnicode_FromString(fields[i]); if (!field) { Py_DECREF(fnames); return NULL; } PyTuple_SET_ITEM(fnames, i, field); } result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){sOss}", type, base, "_fields", fnames, "__module__", "_ast"); Py_DECREF(fnames); return (PyTypeObject*)result; } static int add_attributes(PyTypeObject* type, char**attrs, int num_fields) { int i, result; _Py_IDENTIFIER(_attributes); PyObject *s, *l = PyTuple_New(num_fields); if (!l) return 0; for (i = 0; i < num_fields; i++) { s = PyUnicode_FromString(attrs[i]); if (!s) { Py_DECREF(l); return 0; } PyTuple_SET_ITEM(l, i, s); } result = _PyObject_SetAttrId((PyObject*)type, &PyId__attributes, l) >= 0; Py_DECREF(l); return result; } /* Conversion AST -> Python */ static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*)) { Py_ssize_t i, n = asdl_seq_LEN(seq); PyObject *result = PyList_New(n); PyObject *value; if (!result) return NULL; for (i = 0; i < n; i++) { value = func(asdl_seq_GET(seq, i)); if (!value) { Py_DECREF(result); return NULL; } PyList_SET_ITEM(result, i, value); } return result; } static PyObject* ast2obj_object(void *o) { if (!o) o = Py_None; Py_INCREF((PyObject*)o); return (PyObject*)o; } #define ast2obj_singleton ast2obj_object #define ast2obj_constant ast2obj_object #define ast2obj_identifier ast2obj_object #define ast2obj_string ast2obj_object #define ast2obj_bytes ast2obj_object static PyObject* ast2obj_int(long b) { return PyLong_FromLong(b); } /* Conversion Python -> AST */ static int obj2ast_singleton(PyObject *obj, PyObject** out, PyArena* arena) { if (obj != Py_None && obj != Py_True && obj != Py_False) { PyErr_SetString(PyExc_ValueError, "AST singleton must be True, False, or None"); return 1; } *out = obj; return 0; } static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena) { if (obj == Py_None) obj = NULL; if (obj) { if (PyArena_AddPyObject(arena, obj) < 0) { *out = NULL; return -1; } Py_INCREF(obj); } *out = obj; return 0; } static int obj2ast_constant(PyObject* obj, PyObject** out, PyArena* arena) { if (obj) { if (PyArena_AddPyObject(arena, obj) < 0) { *out = NULL; return -1; } Py_INCREF(obj); } *out = obj; return 0; } static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena) { if (!PyUnicode_CheckExact(obj) && obj != Py_None) { PyErr_SetString(PyExc_TypeError, "AST identifier must be of type str"); return 1; } return obj2ast_object(obj, out, arena); } static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena) { if (!PyUnicode_CheckExact(obj) && !PyBytes_CheckExact(obj)) { PyErr_SetString(PyExc_TypeError, "AST string must be of type str"); return 1; } return obj2ast_object(obj, out, arena); } static int obj2ast_bytes(PyObject* obj, PyObject** out, PyArena* arena) { if (!PyBytes_CheckExact(obj)) { PyErr_SetString(PyExc_TypeError, "AST bytes must be of type bytes"); return 1; } return obj2ast_object(obj, out, arena); } static int obj2ast_int(PyObject* obj, int* out, PyArena* arena) { int i; if (!PyLong_Check(obj)) { PyErr_Format(PyExc_ValueError, "invalid integer value: %R", obj); return 1; } i = _PyLong_AsInt(obj); if (i == -1 && PyErr_Occurred()) return 1; *out = i; return 0; } static int add_ast_fields(void) { PyObject *empty_tuple, *d; if (PyType_Ready(&AST_type) < 0) return -1; d = AST_type.tp_dict; empty_tuple = PyTuple_New(0); if (!empty_tuple || PyDict_SetItemString(d, "_fields", empty_tuple) < 0 || PyDict_SetItemString(d, "_attributes", empty_tuple) < 0) { Py_XDECREF(empty_tuple); return -1; } Py_DECREF(empty_tuple); return 0; } static int exists_not_none(PyObject *obj, _Py_Identifier *id) { int isnone; PyObject *attr = _PyObject_GetAttrId(obj, id); if (!attr) { PyErr_Clear(); return 0; } isnone = attr == Py_None; Py_DECREF(attr); return !isnone; } static int init_types(void) { static int initialized; if (initialized) return 1; if (add_ast_fields() < 0) return 0; mod_type = make_type("mod", &AST_type, NULL, 0); if (!mod_type) return 0; if (!add_attributes(mod_type, NULL, 0)) return 0; Module_type = make_type("Module", mod_type, Module_fields, 1); if (!Module_type) return 0; Interactive_type = make_type("Interactive", mod_type, Interactive_fields, 1); if (!Interactive_type) return 0; Expression_type = make_type("Expression", mod_type, Expression_fields, 1); if (!Expression_type) return 0; Suite_type = make_type("Suite", mod_type, Suite_fields, 1); if (!Suite_type) return 0; stmt_type = make_type("stmt", &AST_type, NULL, 0); if (!stmt_type) return 0; if (!add_attributes(stmt_type, stmt_attributes, 2)) return 0; FunctionDef_type = make_type("FunctionDef", stmt_type, FunctionDef_fields, 5); if (!FunctionDef_type) return 0; AsyncFunctionDef_type = make_type("AsyncFunctionDef", stmt_type, AsyncFunctionDef_fields, 5); if (!AsyncFunctionDef_type) return 0; ClassDef_type = make_type("ClassDef", stmt_type, ClassDef_fields, 5); if (!ClassDef_type) return 0; Return_type = make_type("Return", stmt_type, Return_fields, 1); if (!Return_type) return 0; Delete_type = make_type("Delete", stmt_type, Delete_fields, 1); if (!Delete_type) return 0; Assign_type = make_type("Assign", stmt_type, Assign_fields, 2); if (!Assign_type) return 0; AugAssign_type = make_type("AugAssign", stmt_type, AugAssign_fields, 3); if (!AugAssign_type) return 0; AnnAssign_type = make_type("AnnAssign", stmt_type, AnnAssign_fields, 4); if (!AnnAssign_type) return 0; For_type = make_type("For", stmt_type, For_fields, 4); if (!For_type) return 0; AsyncFor_type = make_type("AsyncFor", stmt_type, AsyncFor_fields, 4); if (!AsyncFor_type) return 0; While_type = make_type("While", stmt_type, While_fields, 3); if (!While_type) return 0; If_type = make_type("If", stmt_type, If_fields, 3); if (!If_type) return 0; With_type = make_type("With", stmt_type, With_fields, 2); if (!With_type) return 0; AsyncWith_type = make_type("AsyncWith", stmt_type, AsyncWith_fields, 2); if (!AsyncWith_type) return 0; Raise_type = make_type("Raise", stmt_type, Raise_fields, 2); if (!Raise_type) return 0; Try_type = make_type("Try", stmt_type, Try_fields, 4); if (!Try_type) return 0; Assert_type = make_type("Assert", stmt_type, Assert_fields, 2); if (!Assert_type) return 0; Import_type = make_type("Import", stmt_type, Import_fields, 1); if (!Import_type) return 0; ImportFrom_type = make_type("ImportFrom", stmt_type, ImportFrom_fields, 3); if (!ImportFrom_type) return 0; Global_type = make_type("Global", stmt_type, Global_fields, 1); if (!Global_type) return 0; Nonlocal_type = make_type("Nonlocal", stmt_type, Nonlocal_fields, 1); if (!Nonlocal_type) return 0; Expr_type = make_type("Expr", stmt_type, Expr_fields, 1); if (!Expr_type) return 0; Pass_type = make_type("Pass", stmt_type, NULL, 0); if (!Pass_type) return 0; Break_type = make_type("Break", stmt_type, NULL, 0); if (!Break_type) return 0; Continue_type = make_type("Continue", stmt_type, NULL, 0); if (!Continue_type) return 0; expr_type = make_type("expr", &AST_type, NULL, 0); if (!expr_type) return 0; if (!add_attributes(expr_type, expr_attributes, 2)) return 0; BoolOp_type = make_type("BoolOp", expr_type, BoolOp_fields, 2); if (!BoolOp_type) return 0; BinOp_type = make_type("BinOp", expr_type, BinOp_fields, 3); if (!BinOp_type) return 0; UnaryOp_type = make_type("UnaryOp", expr_type, UnaryOp_fields, 2); if (!UnaryOp_type) return 0; Lambda_type = make_type("Lambda", expr_type, Lambda_fields, 2); if (!Lambda_type) return 0; IfExp_type = make_type("IfExp", expr_type, IfExp_fields, 3); if (!IfExp_type) return 0; Dict_type = make_type("Dict", expr_type, Dict_fields, 2); if (!Dict_type) return 0; Set_type = make_type("Set", expr_type, Set_fields, 1); if (!Set_type) return 0; ListComp_type = make_type("ListComp", expr_type, ListComp_fields, 2); if (!ListComp_type) return 0; SetComp_type = make_type("SetComp", expr_type, SetComp_fields, 2); if (!SetComp_type) return 0; DictComp_type = make_type("DictComp", expr_type, DictComp_fields, 3); if (!DictComp_type) return 0; GeneratorExp_type = make_type("GeneratorExp", expr_type, GeneratorExp_fields, 2); if (!GeneratorExp_type) return 0; Await_type = make_type("Await", expr_type, Await_fields, 1); if (!Await_type) return 0; Yield_type = make_type("Yield", expr_type, Yield_fields, 1); if (!Yield_type) return 0; YieldFrom_type = make_type("YieldFrom", expr_type, YieldFrom_fields, 1); if (!YieldFrom_type) return 0; Compare_type = make_type("Compare", expr_type, Compare_fields, 3); if (!Compare_type) return 0; Call_type = make_type("Call", expr_type, Call_fields, 3); if (!Call_type) return 0; Num_type = make_type("Num", expr_type, Num_fields, 1); if (!Num_type) return 0; Str_type = make_type("Str", expr_type, Str_fields, 1); if (!Str_type) return 0; FormattedValue_type = make_type("FormattedValue", expr_type, FormattedValue_fields, 3); if (!FormattedValue_type) return 0; JoinedStr_type = make_type("JoinedStr", expr_type, JoinedStr_fields, 1); if (!JoinedStr_type) return 0; Bytes_type = make_type("Bytes", expr_type, Bytes_fields, 1); if (!Bytes_type) return 0; NameConstant_type = make_type("NameConstant", expr_type, NameConstant_fields, 1); if (!NameConstant_type) return 0; Ellipsis_type = make_type("Ellipsis", expr_type, NULL, 0); if (!Ellipsis_type) return 0; Constant_type = make_type("Constant", expr_type, Constant_fields, 1); if (!Constant_type) return 0; Attribute_type = make_type("Attribute", expr_type, Attribute_fields, 3); if (!Attribute_type) return 0; Subscript_type = make_type("Subscript", expr_type, Subscript_fields, 3); if (!Subscript_type) return 0; Starred_type = make_type("Starred", expr_type, Starred_fields, 2); if (!Starred_type) return 0; Name_type = make_type("Name", expr_type, Name_fields, 2); if (!Name_type) return 0; List_type = make_type("List", expr_type, List_fields, 2); if (!List_type) return 0; Tuple_type = make_type("Tuple", expr_type, Tuple_fields, 2); if (!Tuple_type) return 0; expr_context_type = make_type("expr_context", &AST_type, NULL, 0); if (!expr_context_type) return 0; if (!add_attributes(expr_context_type, NULL, 0)) return 0; Load_type = make_type("Load", expr_context_type, NULL, 0); if (!Load_type) return 0; Load_singleton = PyType_GenericNew(Load_type, NULL, NULL); if (!Load_singleton) return 0; Store_type = make_type("Store", expr_context_type, NULL, 0); if (!Store_type) return 0; Store_singleton = PyType_GenericNew(Store_type, NULL, NULL); if (!Store_singleton) return 0; Del_type = make_type("Del", expr_context_type, NULL, 0); if (!Del_type) return 0; Del_singleton = PyType_GenericNew(Del_type, NULL, NULL); if (!Del_singleton) return 0; AugLoad_type = make_type("AugLoad", expr_context_type, NULL, 0); if (!AugLoad_type) return 0; AugLoad_singleton = PyType_GenericNew(AugLoad_type, NULL, NULL); if (!AugLoad_singleton) return 0; AugStore_type = make_type("AugStore", expr_context_type, NULL, 0); if (!AugStore_type) return 0; AugStore_singleton = PyType_GenericNew(AugStore_type, NULL, NULL); if (!AugStore_singleton) return 0; Param_type = make_type("Param", expr_context_type, NULL, 0); if (!Param_type) return 0; Param_singleton = PyType_GenericNew(Param_type, NULL, NULL); if (!Param_singleton) return 0; slice_type = make_type("slice", &AST_type, NULL, 0); if (!slice_type) return 0; if (!add_attributes(slice_type, NULL, 0)) return 0; Slice_type = make_type("Slice", slice_type, Slice_fields, 3); if (!Slice_type) return 0; ExtSlice_type = make_type("ExtSlice", slice_type, ExtSlice_fields, 1); if (!ExtSlice_type) return 0; Index_type = make_type("Index", slice_type, Index_fields, 1); if (!Index_type) return 0; boolop_type = make_type("boolop", &AST_type, NULL, 0); if (!boolop_type) return 0; if (!add_attributes(boolop_type, NULL, 0)) return 0; And_type = make_type("And", boolop_type, NULL, 0); if (!And_type) return 0; And_singleton = PyType_GenericNew(And_type, NULL, NULL); if (!And_singleton) return 0; Or_type = make_type("Or", boolop_type, NULL, 0); if (!Or_type) return 0; Or_singleton = PyType_GenericNew(Or_type, NULL, NULL); if (!Or_singleton) return 0; operator_type = make_type("operator", &AST_type, NULL, 0); if (!operator_type) return 0; if (!add_attributes(operator_type, NULL, 0)) return 0; Add_type = make_type("Add", operator_type, NULL, 0); if (!Add_type) return 0; Add_singleton = PyType_GenericNew(Add_type, NULL, NULL); if (!Add_singleton) return 0; Sub_type = make_type("Sub", operator_type, NULL, 0); if (!Sub_type) return 0; Sub_singleton = PyType_GenericNew(Sub_type, NULL, NULL); if (!Sub_singleton) return 0; Mult_type = make_type("Mult", operator_type, NULL, 0); if (!Mult_type) return 0; Mult_singleton = PyType_GenericNew(Mult_type, NULL, NULL); if (!Mult_singleton) return 0; MatMult_type = make_type("MatMult", operator_type, NULL, 0); if (!MatMult_type) return 0; MatMult_singleton = PyType_GenericNew(MatMult_type, NULL, NULL); if (!MatMult_singleton) return 0; Div_type = make_type("Div", operator_type, NULL, 0); if (!Div_type) return 0; Div_singleton = PyType_GenericNew(Div_type, NULL, NULL); if (!Div_singleton) return 0; Mod_type = make_type("Mod", operator_type, NULL, 0); if (!Mod_type) return 0; Mod_singleton = PyType_GenericNew(Mod_type, NULL, NULL); if (!Mod_singleton) return 0; Pow_type = make_type("Pow", operator_type, NULL, 0); if (!Pow_type) return 0; Pow_singleton = PyType_GenericNew(Pow_type, NULL, NULL); if (!Pow_singleton) return 0; LShift_type = make_type("LShift", operator_type, NULL, 0); if (!LShift_type) return 0; LShift_singleton = PyType_GenericNew(LShift_type, NULL, NULL); if (!LShift_singleton) return 0; RShift_type = make_type("RShift", operator_type, NULL, 0); if (!RShift_type) return 0; RShift_singleton = PyType_GenericNew(RShift_type, NULL, NULL); if (!RShift_singleton) return 0; BitOr_type = make_type("BitOr", operator_type, NULL, 0); if (!BitOr_type) return 0; BitOr_singleton = PyType_GenericNew(BitOr_type, NULL, NULL); if (!BitOr_singleton) return 0; BitXor_type = make_type("BitXor", operator_type, NULL, 0); if (!BitXor_type) return 0; BitXor_singleton = PyType_GenericNew(BitXor_type, NULL, NULL); if (!BitXor_singleton) return 0; BitAnd_type = make_type("BitAnd", operator_type, NULL, 0); if (!BitAnd_type) return 0; BitAnd_singleton = PyType_GenericNew(BitAnd_type, NULL, NULL); if (!BitAnd_singleton) return 0; FloorDiv_type = make_type("FloorDiv", operator_type, NULL, 0); if (!FloorDiv_type) return 0; FloorDiv_singleton = PyType_GenericNew(FloorDiv_type, NULL, NULL); if (!FloorDiv_singleton) return 0; unaryop_type = make_type("unaryop", &AST_type, NULL, 0); if (!unaryop_type) return 0; if (!add_attributes(unaryop_type, NULL, 0)) return 0; Invert_type = make_type("Invert", unaryop_type, NULL, 0); if (!Invert_type) return 0; Invert_singleton = PyType_GenericNew(Invert_type, NULL, NULL); if (!Invert_singleton) return 0; Not_type = make_type("Not", unaryop_type, NULL, 0); if (!Not_type) return 0; Not_singleton = PyType_GenericNew(Not_type, NULL, NULL); if (!Not_singleton) return 0; UAdd_type = make_type("UAdd", unaryop_type, NULL, 0); if (!UAdd_type) return 0; UAdd_singleton = PyType_GenericNew(UAdd_type, NULL, NULL); if (!UAdd_singleton) return 0; USub_type = make_type("USub", unaryop_type, NULL, 0); if (!USub_type) return 0; USub_singleton = PyType_GenericNew(USub_type, NULL, NULL); if (!USub_singleton) return 0; cmpop_type = make_type("cmpop", &AST_type, NULL, 0); if (!cmpop_type) return 0; if (!add_attributes(cmpop_type, NULL, 0)) return 0; Eq_type = make_type("Eq", cmpop_type, NULL, 0); if (!Eq_type) return 0; Eq_singleton = PyType_GenericNew(Eq_type, NULL, NULL); if (!Eq_singleton) return 0; NotEq_type = make_type("NotEq", cmpop_type, NULL, 0); if (!NotEq_type) return 0; NotEq_singleton = PyType_GenericNew(NotEq_type, NULL, NULL); if (!NotEq_singleton) return 0; Lt_type = make_type("Lt", cmpop_type, NULL, 0); if (!Lt_type) return 0; Lt_singleton = PyType_GenericNew(Lt_type, NULL, NULL); if (!Lt_singleton) return 0; LtE_type = make_type("LtE", cmpop_type, NULL, 0); if (!LtE_type) return 0; LtE_singleton = PyType_GenericNew(LtE_type, NULL, NULL); if (!LtE_singleton) return 0; Gt_type = make_type("Gt", cmpop_type, NULL, 0); if (!Gt_type) return 0; Gt_singleton = PyType_GenericNew(Gt_type, NULL, NULL); if (!Gt_singleton) return 0; GtE_type = make_type("GtE", cmpop_type, NULL, 0); if (!GtE_type) return 0; GtE_singleton = PyType_GenericNew(GtE_type, NULL, NULL); if (!GtE_singleton) return 0; Is_type = make_type("Is", cmpop_type, NULL, 0); if (!Is_type) return 0; Is_singleton = PyType_GenericNew(Is_type, NULL, NULL); if (!Is_singleton) return 0; IsNot_type = make_type("IsNot", cmpop_type, NULL, 0); if (!IsNot_type) return 0; IsNot_singleton = PyType_GenericNew(IsNot_type, NULL, NULL); if (!IsNot_singleton) return 0; In_type = make_type("In", cmpop_type, NULL, 0); if (!In_type) return 0; In_singleton = PyType_GenericNew(In_type, NULL, NULL); if (!In_singleton) return 0; NotIn_type = make_type("NotIn", cmpop_type, NULL, 0); if (!NotIn_type) return 0; NotIn_singleton = PyType_GenericNew(NotIn_type, NULL, NULL); if (!NotIn_singleton) return 0; comprehension_type = make_type("comprehension", &AST_type, comprehension_fields, 4); if (!comprehension_type) return 0; if (!add_attributes(comprehension_type, NULL, 0)) return 0; excepthandler_type = make_type("excepthandler", &AST_type, NULL, 0); if (!excepthandler_type) return 0; if (!add_attributes(excepthandler_type, excepthandler_attributes, 2)) return 0; ExceptHandler_type = make_type("ExceptHandler", excepthandler_type, ExceptHandler_fields, 3); if (!ExceptHandler_type) return 0; arguments_type = make_type("arguments", &AST_type, arguments_fields, 6); if (!arguments_type) return 0; if (!add_attributes(arguments_type, NULL, 0)) return 0; arg_type = make_type("arg", &AST_type, arg_fields, 2); if (!arg_type) return 0; if (!add_attributes(arg_type, arg_attributes, 2)) return 0; keyword_type = make_type("keyword", &AST_type, keyword_fields, 2); if (!keyword_type) return 0; if (!add_attributes(keyword_type, NULL, 0)) return 0; alias_type = make_type("alias", &AST_type, alias_fields, 2); if (!alias_type) return 0; if (!add_attributes(alias_type, NULL, 0)) return 0; withitem_type = make_type("withitem", &AST_type, withitem_fields, 2); if (!withitem_type) return 0; if (!add_attributes(withitem_type, NULL, 0)) return 0; initialized = 1; return 1; } static int obj2ast_mod(PyObject* obj, mod_ty* out, PyArena* arena); static int obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena); static int obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena); static int obj2ast_expr_context(PyObject* obj, expr_context_ty* out, PyArena* arena); static int obj2ast_slice(PyObject* obj, slice_ty* out, PyArena* arena); static int obj2ast_boolop(PyObject* obj, boolop_ty* out, PyArena* arena); static int obj2ast_operator(PyObject* obj, operator_ty* out, PyArena* arena); static int obj2ast_unaryop(PyObject* obj, unaryop_ty* out, PyArena* arena); static int obj2ast_cmpop(PyObject* obj, cmpop_ty* out, PyArena* arena); static int obj2ast_comprehension(PyObject* obj, comprehension_ty* out, PyArena* arena); static int obj2ast_excepthandler(PyObject* obj, excepthandler_ty* out, PyArena* arena); static int obj2ast_arguments(PyObject* obj, arguments_ty* out, PyArena* arena); static int obj2ast_arg(PyObject* obj, arg_ty* out, PyArena* arena); static int obj2ast_keyword(PyObject* obj, keyword_ty* out, PyArena* arena); static int obj2ast_alias(PyObject* obj, alias_ty* out, PyArena* arena); static int obj2ast_withitem(PyObject* obj, withitem_ty* out, PyArena* arena); mod_ty Module(asdl_seq * body, PyArena *arena) { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Module_kind; p->v.Module.body = body; return p; } mod_ty Interactive(asdl_seq * body, PyArena *arena) { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Interactive_kind; p->v.Interactive.body = body; return p; } mod_ty Expression(expr_ty body, PyArena *arena) { mod_ty p; if (!body) { PyErr_SetString(PyExc_ValueError, "field body is required for Expression"); return NULL; } p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Expression_kind; p->v.Expression.body = body; return p; } mod_ty Suite(asdl_seq * body, PyArena *arena) { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Suite_kind; p->v.Suite.body = body; return p; } stmt_ty FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq * decorator_list, expr_ty returns, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!name) { PyErr_SetString(PyExc_ValueError, "field name is required for FunctionDef"); return NULL; } if (!args) { PyErr_SetString(PyExc_ValueError, "field args is required for FunctionDef"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = FunctionDef_kind; p->v.FunctionDef.name = name; p->v.FunctionDef.args = args; p->v.FunctionDef.body = body; p->v.FunctionDef.decorator_list = decorator_list; p->v.FunctionDef.returns = returns; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty AsyncFunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq * decorator_list, expr_ty returns, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!name) { PyErr_SetString(PyExc_ValueError, "field name is required for AsyncFunctionDef"); return NULL; } if (!args) { PyErr_SetString(PyExc_ValueError, "field args is required for AsyncFunctionDef"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = AsyncFunctionDef_kind; p->v.AsyncFunctionDef.name = name; p->v.AsyncFunctionDef.args = args; p->v.AsyncFunctionDef.body = body; p->v.AsyncFunctionDef.decorator_list = decorator_list; p->v.AsyncFunctionDef.returns = returns; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty ClassDef(identifier name, asdl_seq * bases, asdl_seq * keywords, asdl_seq * body, asdl_seq * decorator_list, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!name) { PyErr_SetString(PyExc_ValueError, "field name is required for ClassDef"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = ClassDef_kind; p->v.ClassDef.name = name; p->v.ClassDef.bases = bases; p->v.ClassDef.keywords = keywords; p->v.ClassDef.body = body; p->v.ClassDef.decorator_list = decorator_list; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Return(expr_ty value, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Return_kind; p->v.Return.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Delete(asdl_seq * targets, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Delete_kind; p->v.Delete.targets = targets; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Assign"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Assign_kind; p->v.Assign.targets = targets; p->v.Assign.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!target) { PyErr_SetString(PyExc_ValueError, "field target is required for AugAssign"); return NULL; } if (!op) { PyErr_SetString(PyExc_ValueError, "field op is required for AugAssign"); return NULL; } if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for AugAssign"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = AugAssign_kind; p->v.AugAssign.target = target; p->v.AugAssign.op = op; p->v.AugAssign.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty AnnAssign(expr_ty target, expr_ty annotation, expr_ty value, int simple, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!target) { PyErr_SetString(PyExc_ValueError, "field target is required for AnnAssign"); return NULL; } if (!annotation) { PyErr_SetString(PyExc_ValueError, "field annotation is required for AnnAssign"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = AnnAssign_kind; p->v.AnnAssign.target = target; p->v.AnnAssign.annotation = annotation; p->v.AnnAssign.value = value; p->v.AnnAssign.simple = simple; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!target) { PyErr_SetString(PyExc_ValueError, "field target is required for For"); return NULL; } if (!iter) { PyErr_SetString(PyExc_ValueError, "field iter is required for For"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = For_kind; p->v.For.target = target; p->v.For.iter = iter; p->v.For.body = body; p->v.For.orelse = orelse; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty AsyncFor(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!target) { PyErr_SetString(PyExc_ValueError, "field target is required for AsyncFor"); return NULL; } if (!iter) { PyErr_SetString(PyExc_ValueError, "field iter is required for AsyncFor"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = AsyncFor_kind; p->v.AsyncFor.target = target; p->v.AsyncFor.iter = iter; p->v.AsyncFor.body = body; p->v.AsyncFor.orelse = orelse; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!test) { PyErr_SetString(PyExc_ValueError, "field test is required for While"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = While_kind; p->v.While.test = test; p->v.While.body = body; p->v.While.orelse = orelse; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!test) { PyErr_SetString(PyExc_ValueError, "field test is required for If"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = If_kind; p->v.If.test = test; p->v.If.body = body; p->v.If.orelse = orelse; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty With(asdl_seq * items, asdl_seq * body, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = With_kind; p->v.With.items = items; p->v.With.body = body; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty AsyncWith(asdl_seq * items, asdl_seq * body, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = AsyncWith_kind; p->v.AsyncWith.items = items; p->v.AsyncWith.body = body; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Raise(expr_ty exc, expr_ty cause, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Raise_kind; p->v.Raise.exc = exc; p->v.Raise.cause = cause; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Try(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, asdl_seq * finalbody, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Try_kind; p->v.Try.body = body; p->v.Try.handlers = handlers; p->v.Try.orelse = orelse; p->v.Try.finalbody = finalbody; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!test) { PyErr_SetString(PyExc_ValueError, "field test is required for Assert"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Assert_kind; p->v.Assert.test = test; p->v.Assert.msg = msg; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Import(asdl_seq * names, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Import_kind; p->v.Import.names = names; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty ImportFrom(identifier module, asdl_seq * names, int level, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = ImportFrom_kind; p->v.ImportFrom.module = module; p->v.ImportFrom.names = names; p->v.ImportFrom.level = level; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Global_kind; p->v.Global.names = names; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Nonlocal(asdl_seq * names, int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Nonlocal_kind; p->v.Nonlocal.names = names; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Expr(expr_ty value, int lineno, int col_offset, PyArena *arena) { stmt_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Expr"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Expr_kind; p->v.Expr.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Pass(int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Pass_kind; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Break(int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Break_kind; p->lineno = lineno; p->col_offset = col_offset; return p; } stmt_ty Continue(int lineno, int col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Continue_kind; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!op) { PyErr_SetString(PyExc_ValueError, "field op is required for BoolOp"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = BoolOp_kind; p->v.BoolOp.op = op; p->v.BoolOp.values = values; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!left) { PyErr_SetString(PyExc_ValueError, "field left is required for BinOp"); return NULL; } if (!op) { PyErr_SetString(PyExc_ValueError, "field op is required for BinOp"); return NULL; } if (!right) { PyErr_SetString(PyExc_ValueError, "field right is required for BinOp"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = BinOp_kind; p->v.BinOp.left = left; p->v.BinOp.op = op; p->v.BinOp.right = right; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!op) { PyErr_SetString(PyExc_ValueError, "field op is required for UnaryOp"); return NULL; } if (!operand) { PyErr_SetString(PyExc_ValueError, "field operand is required for UnaryOp"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = UnaryOp_kind; p->v.UnaryOp.op = op; p->v.UnaryOp.operand = operand; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!args) { PyErr_SetString(PyExc_ValueError, "field args is required for Lambda"); return NULL; } if (!body) { PyErr_SetString(PyExc_ValueError, "field body is required for Lambda"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Lambda_kind; p->v.Lambda.args = args; p->v.Lambda.body = body; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!test) { PyErr_SetString(PyExc_ValueError, "field test is required for IfExp"); return NULL; } if (!body) { PyErr_SetString(PyExc_ValueError, "field body is required for IfExp"); return NULL; } if (!orelse) { PyErr_SetString(PyExc_ValueError, "field orelse is required for IfExp"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = IfExp_kind; p->v.IfExp.test = test; p->v.IfExp.body = body; p->v.IfExp.orelse = orelse; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, PyArena *arena) { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Dict_kind; p->v.Dict.keys = keys; p->v.Dict.values = values; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena) { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Set_kind; p->v.Set.elts = elts; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty ListComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!elt) { PyErr_SetString(PyExc_ValueError, "field elt is required for ListComp"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = ListComp_kind; p->v.ListComp.elt = elt; p->v.ListComp.generators = generators; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty SetComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!elt) { PyErr_SetString(PyExc_ValueError, "field elt is required for SetComp"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = SetComp_kind; p->v.SetComp.elt = elt; p->v.SetComp.generators = generators; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty DictComp(expr_ty key, expr_ty value, asdl_seq * generators, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!key) { PyErr_SetString(PyExc_ValueError, "field key is required for DictComp"); return NULL; } if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for DictComp"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = DictComp_kind; p->v.DictComp.key = key; p->v.DictComp.value = value; p->v.DictComp.generators = generators; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!elt) { PyErr_SetString(PyExc_ValueError, "field elt is required for GeneratorExp"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = GeneratorExp_kind; p->v.GeneratorExp.elt = elt; p->v.GeneratorExp.generators = generators; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Await(expr_ty value, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Await"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Await_kind; p->v.Await.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Yield(expr_ty value, int lineno, int col_offset, PyArena *arena) { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Yield_kind; p->v.Yield.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty YieldFrom(expr_ty value, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for YieldFrom"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = YieldFrom_kind; p->v.YieldFrom.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!left) { PyErr_SetString(PyExc_ValueError, "field left is required for Compare"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Compare_kind; p->v.Compare.left = left; p->v.Compare.ops = ops; p->v.Compare.comparators = comparators; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!func) { PyErr_SetString(PyExc_ValueError, "field func is required for Call"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Call_kind; p->v.Call.func = func; p->v.Call.args = args; p->v.Call.keywords = keywords; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Num(object n, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!n) { PyErr_SetString(PyExc_ValueError, "field n is required for Num"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Num_kind; p->v.Num.n = n; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Str(string s, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!s) { PyErr_SetString(PyExc_ValueError, "field s is required for Str"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Str_kind; p->v.Str.s = s; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty FormattedValue(expr_ty value, int conversion, expr_ty format_spec, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for FormattedValue"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = FormattedValue_kind; p->v.FormattedValue.value = value; p->v.FormattedValue.conversion = conversion; p->v.FormattedValue.format_spec = format_spec; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty JoinedStr(asdl_seq * values, int lineno, int col_offset, PyArena *arena) { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = JoinedStr_kind; p->v.JoinedStr.values = values; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Bytes(bytes s, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!s) { PyErr_SetString(PyExc_ValueError, "field s is required for Bytes"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Bytes_kind; p->v.Bytes.s = s; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty NameConstant(singleton value, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for NameConstant"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = NameConstant_kind; p->v.NameConstant.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Ellipsis(int lineno, int col_offset, PyArena *arena) { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Ellipsis_kind; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Constant(constant value, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Constant"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Constant_kind; p->v.Constant.value = value; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Attribute"); return NULL; } if (!attr) { PyErr_SetString(PyExc_ValueError, "field attr is required for Attribute"); return NULL; } if (!ctx) { PyErr_SetString(PyExc_ValueError, "field ctx is required for Attribute"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Attribute_kind; p->v.Attribute.value = value; p->v.Attribute.attr = attr; p->v.Attribute.ctx = ctx; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Subscript"); return NULL; } if (!slice) { PyErr_SetString(PyExc_ValueError, "field slice is required for Subscript"); return NULL; } if (!ctx) { PyErr_SetString(PyExc_ValueError, "field ctx is required for Subscript"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Subscript_kind; p->v.Subscript.value = value; p->v.Subscript.slice = slice; p->v.Subscript.ctx = ctx; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Starred(expr_ty value, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Starred"); return NULL; } if (!ctx) { PyErr_SetString(PyExc_ValueError, "field ctx is required for Starred"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Starred_kind; p->v.Starred.value = value; p->v.Starred.ctx = ctx; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Name(identifier id, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!id) { PyErr_SetString(PyExc_ValueError, "field id is required for Name"); return NULL; } if (!ctx) { PyErr_SetString(PyExc_ValueError, "field ctx is required for Name"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Name_kind; p->v.Name.id = id; p->v.Name.ctx = ctx; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty List(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!ctx) { PyErr_SetString(PyExc_ValueError, "field ctx is required for List"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = List_kind; p->v.List.elts = elts; p->v.List.ctx = ctx; p->lineno = lineno; p->col_offset = col_offset; return p; } expr_ty Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena) { expr_ty p; if (!ctx) { PyErr_SetString(PyExc_ValueError, "field ctx is required for Tuple"); return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Tuple_kind; p->v.Tuple.elts = elts; p->v.Tuple.ctx = ctx; p->lineno = lineno; p->col_offset = col_offset; return p; } slice_ty Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena) { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Slice_kind; p->v.Slice.lower = lower; p->v.Slice.upper = upper; p->v.Slice.step = step; return p; } slice_ty ExtSlice(asdl_seq * dims, PyArena *arena) { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = ExtSlice_kind; p->v.ExtSlice.dims = dims; return p; } slice_ty Index(expr_ty value, PyArena *arena) { slice_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Index"); return NULL; } p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Index_kind; p->v.Index.value = value; return p; } comprehension_ty comprehension(expr_ty target, expr_ty iter, asdl_seq * ifs, int is_async, PyArena *arena) { comprehension_ty p; if (!target) { PyErr_SetString(PyExc_ValueError, "field target is required for comprehension"); return NULL; } if (!iter) { PyErr_SetString(PyExc_ValueError, "field iter is required for comprehension"); return NULL; } p = (comprehension_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->target = target; p->iter = iter; p->ifs = ifs; p->is_async = is_async; return p; } excepthandler_ty ExceptHandler(expr_ty type, identifier name, asdl_seq * body, int lineno, int col_offset, PyArena *arena) { excepthandler_ty p; p = (excepthandler_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = ExceptHandler_kind; p->v.ExceptHandler.type = type; p->v.ExceptHandler.name = name; p->v.ExceptHandler.body = body; p->lineno = lineno; p->col_offset = col_offset; return p; } arguments_ty arguments(asdl_seq * args, arg_ty vararg, asdl_seq * kwonlyargs, asdl_seq * kw_defaults, arg_ty kwarg, asdl_seq * defaults, PyArena *arena) { arguments_ty p; p = (arguments_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->args = args; p->vararg = vararg; p->kwonlyargs = kwonlyargs; p->kw_defaults = kw_defaults; p->kwarg = kwarg; p->defaults = defaults; return p; } arg_ty arg(identifier arg, expr_ty annotation, int lineno, int col_offset, PyArena *arena) { arg_ty p; if (!arg) { PyErr_SetString(PyExc_ValueError, "field arg is required for arg"); return NULL; } p = (arg_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->arg = arg; p->annotation = annotation; p->lineno = lineno; p->col_offset = col_offset; return p; } keyword_ty keyword(identifier arg, expr_ty value, PyArena *arena) { keyword_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for keyword"); return NULL; } p = (keyword_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->arg = arg; p->value = value; return p; } alias_ty alias(identifier name, identifier asname, PyArena *arena) { alias_ty p; if (!name) { PyErr_SetString(PyExc_ValueError, "field name is required for alias"); return NULL; } p = (alias_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->name = name; p->asname = asname; return p; } withitem_ty withitem(expr_ty context_expr, expr_ty optional_vars, PyArena *arena) { withitem_ty p; if (!context_expr) { PyErr_SetString(PyExc_ValueError, "field context_expr is required for withitem"); return NULL; } p = (withitem_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->context_expr = context_expr; p->optional_vars = optional_vars; return p; } PyObject* ast2obj_mod(void* _o) { mod_ty o = (mod_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } switch (o->kind) { case Module_kind: result = PyType_GenericNew(Module_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Module.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case Interactive_kind: result = PyType_GenericNew(Interactive_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Interactive.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case Expression_kind: result = PyType_GenericNew(Expression_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Expression.body); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case Suite_kind: result = PyType_GenericNew(Suite_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Suite.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; } return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_stmt(void* _o) { stmt_ty o = (stmt_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } switch (o->kind) { case FunctionDef_kind: result = PyType_GenericNew(FunctionDef_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.FunctionDef.name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_arguments(o->v.FunctionDef.args); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_args, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.FunctionDef.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.FunctionDef.decorator_list, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_decorator_list, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.FunctionDef.returns); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_returns, value) == -1) goto failed; Py_DECREF(value); break; case AsyncFunctionDef_kind: result = PyType_GenericNew(AsyncFunctionDef_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.AsyncFunctionDef.name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_arguments(o->v.AsyncFunctionDef.args); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_args, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncFunctionDef.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncFunctionDef.decorator_list, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_decorator_list, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AsyncFunctionDef.returns); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_returns, value) == -1) goto failed; Py_DECREF(value); break; case ClassDef_kind: result = PyType_GenericNew(ClassDef_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.ClassDef.name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ClassDef.bases, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_bases, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ClassDef.keywords, ast2obj_keyword); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_keywords, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ClassDef.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ClassDef.decorator_list, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_decorator_list, value) == -1) goto failed; Py_DECREF(value); break; case Return_kind: result = PyType_GenericNew(Return_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Return.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case Delete_kind: result = PyType_GenericNew(Delete_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Delete.targets, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_targets, value) == -1) goto failed; Py_DECREF(value); break; case Assign_kind: result = PyType_GenericNew(Assign_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Assign.targets, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_targets, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Assign.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case AugAssign_kind: result = PyType_GenericNew(AugAssign_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.AugAssign.target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_operator(o->v.AugAssign.op); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_op, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AugAssign.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case AnnAssign_kind: result = PyType_GenericNew(AnnAssign_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.AnnAssign.target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AnnAssign.annotation); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_annotation, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AnnAssign.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_int(o->v.AnnAssign.simple); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_simple, value) == -1) goto failed; Py_DECREF(value); break; case For_kind: result = PyType_GenericNew(For_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.For.target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.For.iter); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_iter, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.For.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.For.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case AsyncFor_kind: result = PyType_GenericNew(AsyncFor_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.AsyncFor.target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AsyncFor.iter); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_iter, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncFor.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncFor.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case While_kind: result = PyType_GenericNew(While_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.While.test); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_test, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.While.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.While.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case If_kind: result = PyType_GenericNew(If_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.If.test); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_test, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.If.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.If.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case With_kind: result = PyType_GenericNew(With_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.With.items, ast2obj_withitem); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_items, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.With.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case AsyncWith_kind: result = PyType_GenericNew(AsyncWith_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.AsyncWith.items, ast2obj_withitem); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_items, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncWith.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case Raise_kind: result = PyType_GenericNew(Raise_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Raise.exc); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_exc, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Raise.cause); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_cause, value) == -1) goto failed; Py_DECREF(value); break; case Try_kind: result = PyType_GenericNew(Try_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Try.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Try.handlers, ast2obj_excepthandler); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_handlers, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Try.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Try.finalbody, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_finalbody, value) == -1) goto failed; Py_DECREF(value); break; case Assert_kind: result = PyType_GenericNew(Assert_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Assert.test); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_test, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Assert.msg); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_msg, value) == -1) goto failed; Py_DECREF(value); break; case Import_kind: result = PyType_GenericNew(Import_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Import.names, ast2obj_alias); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_names, value) == -1) goto failed; Py_DECREF(value); break; case ImportFrom_kind: result = PyType_GenericNew(ImportFrom_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.ImportFrom.module); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_module, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ImportFrom.names, ast2obj_alias); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_names, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_int(o->v.ImportFrom.level); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_level, value) == -1) goto failed; Py_DECREF(value); break; case Global_kind: result = PyType_GenericNew(Global_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Global.names, ast2obj_identifier); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_names, value) == -1) goto failed; Py_DECREF(value); break; case Nonlocal_kind: result = PyType_GenericNew(Nonlocal_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Nonlocal.names, ast2obj_identifier); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_names, value) == -1) goto failed; Py_DECREF(value); break; case Expr_kind: result = PyType_GenericNew(Expr_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Expr.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case Pass_kind: result = PyType_GenericNew(Pass_type, NULL, NULL); if (!result) goto failed; break; case Break_kind: result = PyType_GenericNew(Break_type, NULL, NULL); if (!result) goto failed; break; case Continue_kind: result = PyType_GenericNew(Continue_type, NULL, NULL); if (!result) goto failed; break; } value = ast2obj_int(o->lineno); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_lineno, value) < 0) goto failed; Py_DECREF(value); value = ast2obj_int(o->col_offset); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_col_offset, value) < 0) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_expr(void* _o) { expr_ty o = (expr_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } switch (o->kind) { case BoolOp_kind: result = PyType_GenericNew(BoolOp_type, NULL, NULL); if (!result) goto failed; value = ast2obj_boolop(o->v.BoolOp.op); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_op, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.BoolOp.values, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_values, value) == -1) goto failed; Py_DECREF(value); break; case BinOp_kind: result = PyType_GenericNew(BinOp_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.BinOp.left); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_left, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_operator(o->v.BinOp.op); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_op, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.BinOp.right); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_right, value) == -1) goto failed; Py_DECREF(value); break; case UnaryOp_kind: result = PyType_GenericNew(UnaryOp_type, NULL, NULL); if (!result) goto failed; value = ast2obj_unaryop(o->v.UnaryOp.op); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_op, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.UnaryOp.operand); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_operand, value) == -1) goto failed; Py_DECREF(value); break; case Lambda_kind: result = PyType_GenericNew(Lambda_type, NULL, NULL); if (!result) goto failed; value = ast2obj_arguments(o->v.Lambda.args); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_args, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Lambda.body); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case IfExp_kind: result = PyType_GenericNew(IfExp_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.IfExp.test); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_test, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.IfExp.body); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.IfExp.orelse); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case Dict_kind: result = PyType_GenericNew(Dict_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Dict.keys, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_keys, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Dict.values, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_values, value) == -1) goto failed; Py_DECREF(value); break; case Set_kind: result = PyType_GenericNew(Set_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Set.elts, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_elts, value) == -1) goto failed; Py_DECREF(value); break; case ListComp_kind: result = PyType_GenericNew(ListComp_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.ListComp.elt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_elt, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ListComp.generators, ast2obj_comprehension); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_generators, value) == -1) goto failed; Py_DECREF(value); break; case SetComp_kind: result = PyType_GenericNew(SetComp_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.SetComp.elt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_elt, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.SetComp.generators, ast2obj_comprehension); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_generators, value) == -1) goto failed; Py_DECREF(value); break; case DictComp_kind: result = PyType_GenericNew(DictComp_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.DictComp.key); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_key, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.DictComp.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.DictComp.generators, ast2obj_comprehension); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_generators, value) == -1) goto failed; Py_DECREF(value); break; case GeneratorExp_kind: result = PyType_GenericNew(GeneratorExp_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.GeneratorExp.elt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_elt, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.GeneratorExp.generators, ast2obj_comprehension); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_generators, value) == -1) goto failed; Py_DECREF(value); break; case Await_kind: result = PyType_GenericNew(Await_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Await.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case Yield_kind: result = PyType_GenericNew(Yield_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Yield.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case YieldFrom_kind: result = PyType_GenericNew(YieldFrom_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.YieldFrom.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case Compare_kind: result = PyType_GenericNew(Compare_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Compare.left); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_left, value) == -1) goto failed; Py_DECREF(value); { Py_ssize_t i, n = asdl_seq_LEN(o->v.Compare.ops); value = PyList_New(n); if (!value) goto failed; for(i = 0; i < n; i++) PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(o->v.Compare.ops, i))); } if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_ops, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Compare.comparators, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_comparators, value) == -1) goto failed; Py_DECREF(value); break; case Call_kind: result = PyType_GenericNew(Call_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Call.func); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_func, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Call.args, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_args, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Call.keywords, ast2obj_keyword); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_keywords, value) == -1) goto failed; Py_DECREF(value); break; case Num_kind: result = PyType_GenericNew(Num_type, NULL, NULL); if (!result) goto failed; value = ast2obj_object(o->v.Num.n); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_n, value) == -1) goto failed; Py_DECREF(value); break; case Str_kind: result = PyType_GenericNew(Str_type, NULL, NULL); if (!result) goto failed; value = ast2obj_string(o->v.Str.s); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_s, value) == -1) goto failed; Py_DECREF(value); break; case FormattedValue_kind: result = PyType_GenericNew(FormattedValue_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.FormattedValue.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_int(o->v.FormattedValue.conversion); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_conversion, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.FormattedValue.format_spec); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_format_spec, value) == -1) goto failed; Py_DECREF(value); break; case JoinedStr_kind: result = PyType_GenericNew(JoinedStr_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.JoinedStr.values, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_values, value) == -1) goto failed; Py_DECREF(value); break; case Bytes_kind: result = PyType_GenericNew(Bytes_type, NULL, NULL); if (!result) goto failed; value = ast2obj_bytes(o->v.Bytes.s); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_s, value) == -1) goto failed; Py_DECREF(value); break; case NameConstant_kind: result = PyType_GenericNew(NameConstant_type, NULL, NULL); if (!result) goto failed; value = ast2obj_singleton(o->v.NameConstant.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case Ellipsis_kind: result = PyType_GenericNew(Ellipsis_type, NULL, NULL); if (!result) goto failed; break; case Constant_kind: result = PyType_GenericNew(Constant_type, NULL, NULL); if (!result) goto failed; value = ast2obj_constant(o->v.Constant.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case Attribute_kind: result = PyType_GenericNew(Attribute_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Attribute.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_identifier(o->v.Attribute.attr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_attr, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr_context(o->v.Attribute.ctx); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_ctx, value) == -1) goto failed; Py_DECREF(value); break; case Subscript_kind: result = PyType_GenericNew(Subscript_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Subscript.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_slice(o->v.Subscript.slice); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_slice, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr_context(o->v.Subscript.ctx); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_ctx, value) == -1) goto failed; Py_DECREF(value); break; case Starred_kind: result = PyType_GenericNew(Starred_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Starred.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr_context(o->v.Starred.ctx); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_ctx, value) == -1) goto failed; Py_DECREF(value); break; case Name_kind: result = PyType_GenericNew(Name_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.Name.id); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_id, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr_context(o->v.Name.ctx); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_ctx, value) == -1) goto failed; Py_DECREF(value); break; case List_kind: result = PyType_GenericNew(List_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.List.elts, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_elts, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr_context(o->v.List.ctx); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_ctx, value) == -1) goto failed; Py_DECREF(value); break; case Tuple_kind: result = PyType_GenericNew(Tuple_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Tuple.elts, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_elts, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr_context(o->v.Tuple.ctx); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_ctx, value) == -1) goto failed; Py_DECREF(value); break; } value = ast2obj_int(o->lineno); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_lineno, value) < 0) goto failed; Py_DECREF(value); value = ast2obj_int(o->col_offset); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_col_offset, value) < 0) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_expr_context(expr_context_ty o) { switch(o) { case Load: Py_INCREF(Load_singleton); return Load_singleton; case Store: Py_INCREF(Store_singleton); return Store_singleton; case Del: Py_INCREF(Del_singleton); return Del_singleton; case AugLoad: Py_INCREF(AugLoad_singleton); return AugLoad_singleton; case AugStore: Py_INCREF(AugStore_singleton); return AugStore_singleton; case Param: Py_INCREF(Param_singleton); return Param_singleton; default: /* should never happen, but just in case ... */ PyErr_Format(PyExc_SystemError, "unknown expr_context found"); return NULL; } } PyObject* ast2obj_slice(void* _o) { slice_ty o = (slice_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } switch (o->kind) { case Slice_kind: result = PyType_GenericNew(Slice_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Slice.lower); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_lower, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Slice.upper); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_upper, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Slice.step); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_step, value) == -1) goto failed; Py_DECREF(value); break; case ExtSlice_kind: result = PyType_GenericNew(ExtSlice_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.ExtSlice.dims, ast2obj_slice); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_dims, value) == -1) goto failed; Py_DECREF(value); break; case Index_kind: result = PyType_GenericNew(Index_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Index.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; } return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_boolop(boolop_ty o) { switch(o) { case And: Py_INCREF(And_singleton); return And_singleton; case Or: Py_INCREF(Or_singleton); return Or_singleton; default: /* should never happen, but just in case ... */ PyErr_Format(PyExc_SystemError, "unknown boolop found"); return NULL; } } PyObject* ast2obj_operator(operator_ty o) { switch(o) { case Add: Py_INCREF(Add_singleton); return Add_singleton; case Sub: Py_INCREF(Sub_singleton); return Sub_singleton; case Mult: Py_INCREF(Mult_singleton); return Mult_singleton; case MatMult: Py_INCREF(MatMult_singleton); return MatMult_singleton; case Div: Py_INCREF(Div_singleton); return Div_singleton; case Mod: Py_INCREF(Mod_singleton); return Mod_singleton; case Pow: Py_INCREF(Pow_singleton); return Pow_singleton; case LShift: Py_INCREF(LShift_singleton); return LShift_singleton; case RShift: Py_INCREF(RShift_singleton); return RShift_singleton; case BitOr: Py_INCREF(BitOr_singleton); return BitOr_singleton; case BitXor: Py_INCREF(BitXor_singleton); return BitXor_singleton; case BitAnd: Py_INCREF(BitAnd_singleton); return BitAnd_singleton; case FloorDiv: Py_INCREF(FloorDiv_singleton); return FloorDiv_singleton; default: /* should never happen, but just in case ... */ PyErr_Format(PyExc_SystemError, "unknown operator found"); return NULL; } } PyObject* ast2obj_unaryop(unaryop_ty o) { switch(o) { case Invert: Py_INCREF(Invert_singleton); return Invert_singleton; case Not: Py_INCREF(Not_singleton); return Not_singleton; case UAdd: Py_INCREF(UAdd_singleton); return UAdd_singleton; case USub: Py_INCREF(USub_singleton); return USub_singleton; default: /* should never happen, but just in case ... */ PyErr_Format(PyExc_SystemError, "unknown unaryop found"); return NULL; } } PyObject* ast2obj_cmpop(cmpop_ty o) { switch(o) { case Eq: Py_INCREF(Eq_singleton); return Eq_singleton; case NotEq: Py_INCREF(NotEq_singleton); return NotEq_singleton; case Lt: Py_INCREF(Lt_singleton); return Lt_singleton; case LtE: Py_INCREF(LtE_singleton); return LtE_singleton; case Gt: Py_INCREF(Gt_singleton); return Gt_singleton; case GtE: Py_INCREF(GtE_singleton); return GtE_singleton; case Is: Py_INCREF(Is_singleton); return Is_singleton; case IsNot: Py_INCREF(IsNot_singleton); return IsNot_singleton; case In: Py_INCREF(In_singleton); return In_singleton; case NotIn: Py_INCREF(NotIn_singleton); return NotIn_singleton; default: /* should never happen, but just in case ... */ PyErr_Format(PyExc_SystemError, "unknown cmpop found"); return NULL; } } PyObject* ast2obj_comprehension(void* _o) { comprehension_ty o = (comprehension_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } result = PyType_GenericNew(comprehension_type, NULL, NULL); if (!result) return NULL; value = ast2obj_expr(o->target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->iter); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_iter, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->ifs, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_ifs, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_int(o->is_async); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_is_async, value) == -1) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_excepthandler(void* _o) { excepthandler_ty o = (excepthandler_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } switch (o->kind) { case ExceptHandler_kind: result = PyType_GenericNew(ExceptHandler_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.ExceptHandler.type); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_type, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_identifier(o->v.ExceptHandler.name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ExceptHandler.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; } value = ast2obj_int(o->lineno); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_lineno, value) < 0) goto failed; Py_DECREF(value); value = ast2obj_int(o->col_offset); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_col_offset, value) < 0) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_arguments(void* _o) { arguments_ty o = (arguments_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } result = PyType_GenericNew(arguments_type, NULL, NULL); if (!result) return NULL; value = ast2obj_list(o->args, ast2obj_arg); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_args, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_arg(o->vararg); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_vararg, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->kwonlyargs, ast2obj_arg); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_kwonlyargs, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->kw_defaults, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_kw_defaults, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_arg(o->kwarg); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_kwarg, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->defaults, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_defaults, value) == -1) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_arg(void* _o) { arg_ty o = (arg_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } result = PyType_GenericNew(arg_type, NULL, NULL); if (!result) return NULL; value = ast2obj_identifier(o->arg); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_arg, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->annotation); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_annotation, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_int(o->lineno); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_lineno, value) < 0) goto failed; Py_DECREF(value); value = ast2obj_int(o->col_offset); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_col_offset, value) < 0) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_keyword(void* _o) { keyword_ty o = (keyword_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } result = PyType_GenericNew(keyword_type, NULL, NULL); if (!result) return NULL; value = ast2obj_identifier(o->arg); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_arg, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_alias(void* _o) { alias_ty o = (alias_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } result = PyType_GenericNew(alias_type, NULL, NULL); if (!result) return NULL; value = ast2obj_identifier(o->name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_identifier(o->asname); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_asname, value) == -1) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } PyObject* ast2obj_withitem(void* _o) { withitem_ty o = (withitem_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_INCREF(Py_None); return Py_None; } result = PyType_GenericNew(withitem_type, NULL, NULL); if (!result) return NULL; value = ast2obj_expr(o->context_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_context_expr, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->optional_vars); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_optional_vars, value) == -1) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } int obj2ast_mod(PyObject* obj, mod_ty* out, PyArena* arena) { int isinstance; PyObject *tmp = NULL; if (obj == Py_None) { *out = NULL; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Module_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* body; if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Module field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Module field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Module"); return 1; } *out = Module(body, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Interactive_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* body; if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Interactive field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Interactive field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Interactive"); return 1; } *out = Interactive(body, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Expression_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty body; if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &body, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Expression"); return 1; } *out = Expression(body, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Suite_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* body; if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Suite field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Suite field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Suite"); return 1; } *out = Suite(body, arena); if (*out == NULL) goto failed; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of mod, but got %R", obj); failed: Py_XDECREF(tmp); return 1; } int obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena) { int isinstance; PyObject *tmp = NULL; int lineno; int col_offset; if (obj == Py_None) { *out = NULL; return 0; } if (_PyObject_HasAttrId(obj, &PyId_lineno)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_lineno); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &lineno, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from stmt"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_col_offset)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_col_offset); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &col_offset, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from stmt"); return 1; } isinstance = PyObject_IsInstance(obj, (PyObject*)FunctionDef_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier name; arguments_ty args; asdl_seq* body; asdl_seq* decorator_list; expr_ty returns; if (_PyObject_HasAttrId(obj, &PyId_name)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_name); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &name, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from FunctionDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_args)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_args); if (tmp == NULL) goto failed; res = obj2ast_arguments(tmp, &args, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from FunctionDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "FunctionDef field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "FunctionDef field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from FunctionDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_decorator_list)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_decorator_list); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "FunctionDef field \"decorator_list\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); decorator_list = _Py_asdl_seq_new(len, arena); if (decorator_list == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "FunctionDef field \"decorator_list\" changed size during iteration"); goto failed; } asdl_seq_SET(decorator_list, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"decorator_list\" missing from FunctionDef"); return 1; } if (exists_not_none(obj, &PyId_returns)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_returns); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &returns, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { returns = NULL; } *out = FunctionDef(name, args, body, decorator_list, returns, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AsyncFunctionDef_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier name; arguments_ty args; asdl_seq* body; asdl_seq* decorator_list; expr_ty returns; if (_PyObject_HasAttrId(obj, &PyId_name)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_name); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &name, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from AsyncFunctionDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_args)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_args); if (tmp == NULL) goto failed; res = obj2ast_arguments(tmp, &args, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from AsyncFunctionDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncFunctionDef field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncFunctionDef field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from AsyncFunctionDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_decorator_list)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_decorator_list); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncFunctionDef field \"decorator_list\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); decorator_list = _Py_asdl_seq_new(len, arena); if (decorator_list == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncFunctionDef field \"decorator_list\" changed size during iteration"); goto failed; } asdl_seq_SET(decorator_list, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"decorator_list\" missing from AsyncFunctionDef"); return 1; } if (exists_not_none(obj, &PyId_returns)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_returns); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &returns, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { returns = NULL; } *out = AsyncFunctionDef(name, args, body, decorator_list, returns, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)ClassDef_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier name; asdl_seq* bases; asdl_seq* keywords; asdl_seq* body; asdl_seq* decorator_list; if (_PyObject_HasAttrId(obj, &PyId_name)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_name); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &name, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from ClassDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_bases)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_bases); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ClassDef field \"bases\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); bases = _Py_asdl_seq_new(len, arena); if (bases == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"bases\" changed size during iteration"); goto failed; } asdl_seq_SET(bases, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"bases\" missing from ClassDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_keywords)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_keywords); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ClassDef field \"keywords\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); keywords = _Py_asdl_seq_new(len, arena); if (keywords == NULL) goto failed; for (i = 0; i < len; i++) { keyword_ty val; res = obj2ast_keyword(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"keywords\" changed size during iteration"); goto failed; } asdl_seq_SET(keywords, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"keywords\" missing from ClassDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ClassDef field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from ClassDef"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_decorator_list)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_decorator_list); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ClassDef field \"decorator_list\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); decorator_list = _Py_asdl_seq_new(len, arena); if (decorator_list == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"decorator_list\" changed size during iteration"); goto failed; } asdl_seq_SET(decorator_list, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"decorator_list\" missing from ClassDef"); return 1; } *out = ClassDef(name, bases, keywords, body, decorator_list, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Return_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; if (exists_not_none(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { value = NULL; } *out = Return(value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Delete_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* targets; if (_PyObject_HasAttrId(obj, &PyId_targets)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_targets); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Delete field \"targets\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); targets = _Py_asdl_seq_new(len, arena); if (targets == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Delete field \"targets\" changed size during iteration"); goto failed; } asdl_seq_SET(targets, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"targets\" missing from Delete"); return 1; } *out = Delete(targets, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Assign_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* targets; expr_ty value; if (_PyObject_HasAttrId(obj, &PyId_targets)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_targets); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Assign field \"targets\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); targets = _Py_asdl_seq_new(len, arena); if (targets == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Assign field \"targets\" changed size during iteration"); goto failed; } asdl_seq_SET(targets, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"targets\" missing from Assign"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Assign"); return 1; } *out = Assign(targets, value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AugAssign_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty target; operator_ty op; expr_ty value; if (_PyObject_HasAttrId(obj, &PyId_target)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_target); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from AugAssign"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_op)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_op); if (tmp == NULL) goto failed; res = obj2ast_operator(tmp, &op, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from AugAssign"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from AugAssign"); return 1; } *out = AugAssign(target, op, value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AnnAssign_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty target; expr_ty annotation; expr_ty value; int simple; if (_PyObject_HasAttrId(obj, &PyId_target)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_target); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from AnnAssign"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_annotation)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_annotation); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &annotation, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"annotation\" missing from AnnAssign"); return 1; } if (exists_not_none(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { value = NULL; } if (_PyObject_HasAttrId(obj, &PyId_simple)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_simple); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &simple, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"simple\" missing from AnnAssign"); return 1; } *out = AnnAssign(target, annotation, value, simple, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)For_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty target; expr_ty iter; asdl_seq* body; asdl_seq* orelse; if (_PyObject_HasAttrId(obj, &PyId_target)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_target); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from For"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_iter)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_iter); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &iter, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"iter\" missing from For"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "For field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "For field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from For"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_orelse)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_orelse); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "For field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "For field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from For"); return 1; } *out = For(target, iter, body, orelse, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AsyncFor_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty target; expr_ty iter; asdl_seq* body; asdl_seq* orelse; if (_PyObject_HasAttrId(obj, &PyId_target)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_target); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from AsyncFor"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_iter)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_iter); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &iter, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"iter\" missing from AsyncFor"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncFor field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncFor field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from AsyncFor"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_orelse)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_orelse); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncFor field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncFor field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from AsyncFor"); return 1; } *out = AsyncFor(target, iter, body, orelse, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)While_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty test; asdl_seq* body; asdl_seq* orelse; if (_PyObject_HasAttrId(obj, &PyId_test)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_test); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &test, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from While"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "While field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "While field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from While"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_orelse)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_orelse); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "While field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "While field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from While"); return 1; } *out = While(test, body, orelse, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)If_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty test; asdl_seq* body; asdl_seq* orelse; if (_PyObject_HasAttrId(obj, &PyId_test)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_test); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &test, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from If"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "If field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "If field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from If"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_orelse)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_orelse); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "If field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "If field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from If"); return 1; } *out = If(test, body, orelse, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)With_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* items; asdl_seq* body; if (_PyObject_HasAttrId(obj, &PyId_items)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_items); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "With field \"items\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); items = _Py_asdl_seq_new(len, arena); if (items == NULL) goto failed; for (i = 0; i < len; i++) { withitem_ty val; res = obj2ast_withitem(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "With field \"items\" changed size during iteration"); goto failed; } asdl_seq_SET(items, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"items\" missing from With"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "With field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "With field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from With"); return 1; } *out = With(items, body, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AsyncWith_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* items; asdl_seq* body; if (_PyObject_HasAttrId(obj, &PyId_items)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_items); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncWith field \"items\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); items = _Py_asdl_seq_new(len, arena); if (items == NULL) goto failed; for (i = 0; i < len; i++) { withitem_ty val; res = obj2ast_withitem(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncWith field \"items\" changed size during iteration"); goto failed; } asdl_seq_SET(items, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"items\" missing from AsyncWith"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncWith field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncWith field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from AsyncWith"); return 1; } *out = AsyncWith(items, body, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Raise_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty exc; expr_ty cause; if (exists_not_none(obj, &PyId_exc)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_exc); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &exc, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { exc = NULL; } if (exists_not_none(obj, &PyId_cause)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_cause); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &cause, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { cause = NULL; } *out = Raise(exc, cause, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Try_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* body; asdl_seq* handlers; asdl_seq* orelse; asdl_seq* finalbody; if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Try field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Try field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Try"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_handlers)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_handlers); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Try field \"handlers\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); handlers = _Py_asdl_seq_new(len, arena); if (handlers == NULL) goto failed; for (i = 0; i < len; i++) { excepthandler_ty val; res = obj2ast_excepthandler(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Try field \"handlers\" changed size during iteration"); goto failed; } asdl_seq_SET(handlers, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"handlers\" missing from Try"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_orelse)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_orelse); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Try field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Try field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from Try"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_finalbody)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_finalbody); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Try field \"finalbody\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); finalbody = _Py_asdl_seq_new(len, arena); if (finalbody == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Try field \"finalbody\" changed size during iteration"); goto failed; } asdl_seq_SET(finalbody, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"finalbody\" missing from Try"); return 1; } *out = Try(body, handlers, orelse, finalbody, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Assert_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty test; expr_ty msg; if (_PyObject_HasAttrId(obj, &PyId_test)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_test); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &test, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from Assert"); return 1; } if (exists_not_none(obj, &PyId_msg)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_msg); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &msg, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { msg = NULL; } *out = Assert(test, msg, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Import_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* names; if (_PyObject_HasAttrId(obj, &PyId_names)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_names); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Import field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); names = _Py_asdl_seq_new(len, arena); if (names == NULL) goto failed; for (i = 0; i < len; i++) { alias_ty val; res = obj2ast_alias(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Import field \"names\" changed size during iteration"); goto failed; } asdl_seq_SET(names, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Import"); return 1; } *out = Import(names, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)ImportFrom_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier module; asdl_seq* names; int level; if (exists_not_none(obj, &PyId_module)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_module); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &module, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { module = NULL; } if (_PyObject_HasAttrId(obj, &PyId_names)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_names); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ImportFrom field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); names = _Py_asdl_seq_new(len, arena); if (names == NULL) goto failed; for (i = 0; i < len; i++) { alias_ty val; res = obj2ast_alias(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ImportFrom field \"names\" changed size during iteration"); goto failed; } asdl_seq_SET(names, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from ImportFrom"); return 1; } if (exists_not_none(obj, &PyId_level)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_level); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &level, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { level = 0; } *out = ImportFrom(module, names, level, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Global_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* names; if (_PyObject_HasAttrId(obj, &PyId_names)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_names); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Global field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); names = _Py_asdl_seq_new(len, arena); if (names == NULL) goto failed; for (i = 0; i < len; i++) { identifier val; res = obj2ast_identifier(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Global field \"names\" changed size during iteration"); goto failed; } asdl_seq_SET(names, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Global"); return 1; } *out = Global(names, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Nonlocal_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* names; if (_PyObject_HasAttrId(obj, &PyId_names)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_names); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Nonlocal field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); names = _Py_asdl_seq_new(len, arena); if (names == NULL) goto failed; for (i = 0; i < len; i++) { identifier val; res = obj2ast_identifier(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Nonlocal field \"names\" changed size during iteration"); goto failed; } asdl_seq_SET(names, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Nonlocal"); return 1; } *out = Nonlocal(names, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Expr_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Expr"); return 1; } *out = Expr(value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Pass_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Pass(lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Break_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Break(lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Continue_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Continue(lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of stmt, but got %R", obj); failed: Py_XDECREF(tmp); return 1; } int obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena) { int isinstance; PyObject *tmp = NULL; int lineno; int col_offset; if (obj == Py_None) { *out = NULL; return 0; } if (_PyObject_HasAttrId(obj, &PyId_lineno)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_lineno); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &lineno, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from expr"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_col_offset)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_col_offset); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &col_offset, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from expr"); return 1; } isinstance = PyObject_IsInstance(obj, (PyObject*)BoolOp_type); if (isinstance == -1) { return 1; } if (isinstance) { boolop_ty op; asdl_seq* values; if (_PyObject_HasAttrId(obj, &PyId_op)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_op); if (tmp == NULL) goto failed; res = obj2ast_boolop(tmp, &op, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from BoolOp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_values)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_values); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "BoolOp field \"values\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); values = _Py_asdl_seq_new(len, arena); if (values == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "BoolOp field \"values\" changed size during iteration"); goto failed; } asdl_seq_SET(values, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"values\" missing from BoolOp"); return 1; } *out = BoolOp(op, values, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)BinOp_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty left; operator_ty op; expr_ty right; if (_PyObject_HasAttrId(obj, &PyId_left)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_left); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &left, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"left\" missing from BinOp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_op)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_op); if (tmp == NULL) goto failed; res = obj2ast_operator(tmp, &op, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from BinOp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_right)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_right); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &right, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"right\" missing from BinOp"); return 1; } *out = BinOp(left, op, right, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)UnaryOp_type); if (isinstance == -1) { return 1; } if (isinstance) { unaryop_ty op; expr_ty operand; if (_PyObject_HasAttrId(obj, &PyId_op)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_op); if (tmp == NULL) goto failed; res = obj2ast_unaryop(tmp, &op, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from UnaryOp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_operand)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_operand); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &operand, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"operand\" missing from UnaryOp"); return 1; } *out = UnaryOp(op, operand, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Lambda_type); if (isinstance == -1) { return 1; } if (isinstance) { arguments_ty args; expr_ty body; if (_PyObject_HasAttrId(obj, &PyId_args)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_args); if (tmp == NULL) goto failed; res = obj2ast_arguments(tmp, &args, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from Lambda"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &body, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Lambda"); return 1; } *out = Lambda(args, body, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)IfExp_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty test; expr_ty body; expr_ty orelse; if (_PyObject_HasAttrId(obj, &PyId_test)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_test); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &test, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from IfExp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &body, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from IfExp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_orelse)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_orelse); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &orelse, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from IfExp"); return 1; } *out = IfExp(test, body, orelse, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Dict_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* keys; asdl_seq* values; if (_PyObject_HasAttrId(obj, &PyId_keys)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_keys); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Dict field \"keys\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); keys = _Py_asdl_seq_new(len, arena); if (keys == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Dict field \"keys\" changed size during iteration"); goto failed; } asdl_seq_SET(keys, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"keys\" missing from Dict"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_values)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_values); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Dict field \"values\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); values = _Py_asdl_seq_new(len, arena); if (values == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Dict field \"values\" changed size during iteration"); goto failed; } asdl_seq_SET(values, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"values\" missing from Dict"); return 1; } *out = Dict(keys, values, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Set_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* elts; if (_PyObject_HasAttrId(obj, &PyId_elts)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_elts); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Set field \"elts\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); elts = _Py_asdl_seq_new(len, arena); if (elts == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Set field \"elts\" changed size during iteration"); goto failed; } asdl_seq_SET(elts, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"elts\" missing from Set"); return 1; } *out = Set(elts, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)ListComp_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty elt; asdl_seq* generators; if (_PyObject_HasAttrId(obj, &PyId_elt)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_elt); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &elt, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"elt\" missing from ListComp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_generators)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_generators); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ListComp field \"generators\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); generators = _Py_asdl_seq_new(len, arena); if (generators == NULL) goto failed; for (i = 0; i < len; i++) { comprehension_ty val; res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ListComp field \"generators\" changed size during iteration"); goto failed; } asdl_seq_SET(generators, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"generators\" missing from ListComp"); return 1; } *out = ListComp(elt, generators, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)SetComp_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty elt; asdl_seq* generators; if (_PyObject_HasAttrId(obj, &PyId_elt)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_elt); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &elt, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"elt\" missing from SetComp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_generators)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_generators); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "SetComp field \"generators\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); generators = _Py_asdl_seq_new(len, arena); if (generators == NULL) goto failed; for (i = 0; i < len; i++) { comprehension_ty val; res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "SetComp field \"generators\" changed size during iteration"); goto failed; } asdl_seq_SET(generators, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"generators\" missing from SetComp"); return 1; } *out = SetComp(elt, generators, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)DictComp_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty key; expr_ty value; asdl_seq* generators; if (_PyObject_HasAttrId(obj, &PyId_key)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_key); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &key, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"key\" missing from DictComp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from DictComp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_generators)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_generators); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "DictComp field \"generators\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); generators = _Py_asdl_seq_new(len, arena); if (generators == NULL) goto failed; for (i = 0; i < len; i++) { comprehension_ty val; res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "DictComp field \"generators\" changed size during iteration"); goto failed; } asdl_seq_SET(generators, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"generators\" missing from DictComp"); return 1; } *out = DictComp(key, value, generators, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)GeneratorExp_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty elt; asdl_seq* generators; if (_PyObject_HasAttrId(obj, &PyId_elt)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_elt); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &elt, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"elt\" missing from GeneratorExp"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_generators)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_generators); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "GeneratorExp field \"generators\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); generators = _Py_asdl_seq_new(len, arena); if (generators == NULL) goto failed; for (i = 0; i < len; i++) { comprehension_ty val; res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "GeneratorExp field \"generators\" changed size during iteration"); goto failed; } asdl_seq_SET(generators, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"generators\" missing from GeneratorExp"); return 1; } *out = GeneratorExp(elt, generators, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Await_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Await"); return 1; } *out = Await(value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Yield_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; if (exists_not_none(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { value = NULL; } *out = Yield(value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)YieldFrom_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from YieldFrom"); return 1; } *out = YieldFrom(value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Compare_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty left; asdl_int_seq* ops; asdl_seq* comparators; if (_PyObject_HasAttrId(obj, &PyId_left)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_left); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &left, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"left\" missing from Compare"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_ops)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_ops); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Compare field \"ops\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); ops = _Py_asdl_int_seq_new(len, arena); if (ops == NULL) goto failed; for (i = 0; i < len; i++) { cmpop_ty val; res = obj2ast_cmpop(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Compare field \"ops\" changed size during iteration"); goto failed; } asdl_seq_SET(ops, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"ops\" missing from Compare"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_comparators)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_comparators); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Compare field \"comparators\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); comparators = _Py_asdl_seq_new(len, arena); if (comparators == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Compare field \"comparators\" changed size during iteration"); goto failed; } asdl_seq_SET(comparators, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"comparators\" missing from Compare"); return 1; } *out = Compare(left, ops, comparators, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Call_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty func; asdl_seq* args; asdl_seq* keywords; if (_PyObject_HasAttrId(obj, &PyId_func)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_func); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &func, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"func\" missing from Call"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_args)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_args); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Call field \"args\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); args = _Py_asdl_seq_new(len, arena); if (args == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Call field \"args\" changed size during iteration"); goto failed; } asdl_seq_SET(args, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from Call"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_keywords)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_keywords); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Call field \"keywords\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); keywords = _Py_asdl_seq_new(len, arena); if (keywords == NULL) goto failed; for (i = 0; i < len; i++) { keyword_ty val; res = obj2ast_keyword(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Call field \"keywords\" changed size during iteration"); goto failed; } asdl_seq_SET(keywords, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"keywords\" missing from Call"); return 1; } *out = Call(func, args, keywords, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Num_type); if (isinstance == -1) { return 1; } if (isinstance) { object n; if (_PyObject_HasAttrId(obj, &PyId_n)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_n); if (tmp == NULL) goto failed; res = obj2ast_object(tmp, &n, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"n\" missing from Num"); return 1; } *out = Num(n, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Str_type); if (isinstance == -1) { return 1; } if (isinstance) { string s; if (_PyObject_HasAttrId(obj, &PyId_s)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_s); if (tmp == NULL) goto failed; res = obj2ast_string(tmp, &s, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"s\" missing from Str"); return 1; } *out = Str(s, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)FormattedValue_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; int conversion; expr_ty format_spec; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from FormattedValue"); return 1; } if (exists_not_none(obj, &PyId_conversion)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_conversion); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &conversion, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { conversion = 0; } if (exists_not_none(obj, &PyId_format_spec)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_format_spec); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &format_spec, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { format_spec = NULL; } *out = FormattedValue(value, conversion, format_spec, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)JoinedStr_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* values; if (_PyObject_HasAttrId(obj, &PyId_values)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_values); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "JoinedStr field \"values\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); values = _Py_asdl_seq_new(len, arena); if (values == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "JoinedStr field \"values\" changed size during iteration"); goto failed; } asdl_seq_SET(values, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"values\" missing from JoinedStr"); return 1; } *out = JoinedStr(values, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Bytes_type); if (isinstance == -1) { return 1; } if (isinstance) { bytes s; if (_PyObject_HasAttrId(obj, &PyId_s)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_s); if (tmp == NULL) goto failed; res = obj2ast_bytes(tmp, &s, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"s\" missing from Bytes"); return 1; } *out = Bytes(s, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)NameConstant_type); if (isinstance == -1) { return 1; } if (isinstance) { singleton value; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_singleton(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from NameConstant"); return 1; } *out = NameConstant(value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Ellipsis_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Ellipsis(lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Constant_type); if (isinstance == -1) { return 1; } if (isinstance) { constant value; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_constant(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Constant"); return 1; } *out = Constant(value, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Attribute_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; identifier attr; expr_context_ty ctx; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Attribute"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_attr)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_attr); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &attr, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"attr\" missing from Attribute"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_ctx)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_ctx); if (tmp == NULL) goto failed; res = obj2ast_expr_context(tmp, &ctx, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Attribute"); return 1; } *out = Attribute(value, attr, ctx, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Subscript_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; slice_ty slice; expr_context_ty ctx; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Subscript"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_slice)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_slice); if (tmp == NULL) goto failed; res = obj2ast_slice(tmp, &slice, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"slice\" missing from Subscript"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_ctx)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_ctx); if (tmp == NULL) goto failed; res = obj2ast_expr_context(tmp, &ctx, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Subscript"); return 1; } *out = Subscript(value, slice, ctx, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Starred_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; expr_context_ty ctx; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Starred"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_ctx)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_ctx); if (tmp == NULL) goto failed; res = obj2ast_expr_context(tmp, &ctx, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Starred"); return 1; } *out = Starred(value, ctx, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Name_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier id; expr_context_ty ctx; if (_PyObject_HasAttrId(obj, &PyId_id)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_id); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &id, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"id\" missing from Name"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_ctx)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_ctx); if (tmp == NULL) goto failed; res = obj2ast_expr_context(tmp, &ctx, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Name"); return 1; } *out = Name(id, ctx, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)List_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* elts; expr_context_ty ctx; if (_PyObject_HasAttrId(obj, &PyId_elts)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_elts); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "List field \"elts\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); elts = _Py_asdl_seq_new(len, arena); if (elts == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "List field \"elts\" changed size during iteration"); goto failed; } asdl_seq_SET(elts, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"elts\" missing from List"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_ctx)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_ctx); if (tmp == NULL) goto failed; res = obj2ast_expr_context(tmp, &ctx, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from List"); return 1; } *out = List(elts, ctx, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Tuple_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* elts; expr_context_ty ctx; if (_PyObject_HasAttrId(obj, &PyId_elts)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_elts); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Tuple field \"elts\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); elts = _Py_asdl_seq_new(len, arena); if (elts == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Tuple field \"elts\" changed size during iteration"); goto failed; } asdl_seq_SET(elts, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"elts\" missing from Tuple"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_ctx)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_ctx); if (tmp == NULL) goto failed; res = obj2ast_expr_context(tmp, &ctx, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"ctx\" missing from Tuple"); return 1; } *out = Tuple(elts, ctx, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of expr, but got %R", obj); failed: Py_XDECREF(tmp); return 1; } int obj2ast_expr_context(PyObject* obj, expr_context_ty* out, PyArena* arena) { int isinstance; isinstance = PyObject_IsInstance(obj, (PyObject *)Load_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Load; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Store_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Store; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Del_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Del; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)AugLoad_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = AugLoad; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)AugStore_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = AugStore; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Param_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Param; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of expr_context, but got %R", obj); return 1; } int obj2ast_slice(PyObject* obj, slice_ty* out, PyArena* arena) { int isinstance; PyObject *tmp = NULL; if (obj == Py_None) { *out = NULL; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Slice_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty lower; expr_ty upper; expr_ty step; if (exists_not_none(obj, &PyId_lower)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_lower); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &lower, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { lower = NULL; } if (exists_not_none(obj, &PyId_upper)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_upper); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &upper, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { upper = NULL; } if (exists_not_none(obj, &PyId_step)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_step); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &step, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { step = NULL; } *out = Slice(lower, upper, step, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)ExtSlice_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* dims; if (_PyObject_HasAttrId(obj, &PyId_dims)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_dims); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ExtSlice field \"dims\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); dims = _Py_asdl_seq_new(len, arena); if (dims == NULL) goto failed; for (i = 0; i < len; i++) { slice_ty val; res = obj2ast_slice(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ExtSlice field \"dims\" changed size during iteration"); goto failed; } asdl_seq_SET(dims, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"dims\" missing from ExtSlice"); return 1; } *out = ExtSlice(dims, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Index_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Index"); return 1; } *out = Index(value, arena); if (*out == NULL) goto failed; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of slice, but got %R", obj); failed: Py_XDECREF(tmp); return 1; } int obj2ast_boolop(PyObject* obj, boolop_ty* out, PyArena* arena) { int isinstance; isinstance = PyObject_IsInstance(obj, (PyObject *)And_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = And; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Or_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Or; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of boolop, but got %R", obj); return 1; } int obj2ast_operator(PyObject* obj, operator_ty* out, PyArena* arena) { int isinstance; isinstance = PyObject_IsInstance(obj, (PyObject *)Add_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Add; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Sub_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Sub; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Mult_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Mult; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)MatMult_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = MatMult; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Div_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Div; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Mod_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Mod; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Pow_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Pow; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)LShift_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = LShift; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)RShift_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = RShift; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)BitOr_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = BitOr; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)BitXor_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = BitXor; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)BitAnd_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = BitAnd; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)FloorDiv_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = FloorDiv; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of operator, but got %R", obj); return 1; } int obj2ast_unaryop(PyObject* obj, unaryop_ty* out, PyArena* arena) { int isinstance; isinstance = PyObject_IsInstance(obj, (PyObject *)Invert_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Invert; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Not_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Not; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)UAdd_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = UAdd; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)USub_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = USub; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of unaryop, but got %R", obj); return 1; } int obj2ast_cmpop(PyObject* obj, cmpop_ty* out, PyArena* arena) { int isinstance; isinstance = PyObject_IsInstance(obj, (PyObject *)Eq_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Eq; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)NotEq_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = NotEq; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Lt_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Lt; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)LtE_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = LtE; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Gt_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Gt; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)GtE_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = GtE; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)Is_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Is; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)IsNot_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = IsNot; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)In_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = In; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject *)NotIn_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = NotIn; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of cmpop, but got %R", obj); return 1; } int obj2ast_comprehension(PyObject* obj, comprehension_ty* out, PyArena* arena) { PyObject* tmp = NULL; expr_ty target; expr_ty iter; asdl_seq* ifs; int is_async; if (_PyObject_HasAttrId(obj, &PyId_target)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_target); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from comprehension"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_iter)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_iter); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &iter, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"iter\" missing from comprehension"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_ifs)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_ifs); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "comprehension field \"ifs\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); ifs = _Py_asdl_seq_new(len, arena); if (ifs == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "comprehension field \"ifs\" changed size during iteration"); goto failed; } asdl_seq_SET(ifs, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"ifs\" missing from comprehension"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_is_async)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_is_async); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &is_async, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"is_async\" missing from comprehension"); return 1; } *out = comprehension(target, iter, ifs, is_async, arena); return 0; failed: Py_XDECREF(tmp); return 1; } int obj2ast_excepthandler(PyObject* obj, excepthandler_ty* out, PyArena* arena) { int isinstance; PyObject *tmp = NULL; int lineno; int col_offset; if (obj == Py_None) { *out = NULL; return 0; } if (_PyObject_HasAttrId(obj, &PyId_lineno)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_lineno); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &lineno, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from excepthandler"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_col_offset)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_col_offset); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &col_offset, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from excepthandler"); return 1; } isinstance = PyObject_IsInstance(obj, (PyObject*)ExceptHandler_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty type; identifier name; asdl_seq* body; if (exists_not_none(obj, &PyId_type)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_type); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &type, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { type = NULL; } if (exists_not_none(obj, &PyId_name)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_name); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &name, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { name = NULL; } if (_PyObject_HasAttrId(obj, &PyId_body)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_body); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ExceptHandler field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ExceptHandler field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from ExceptHandler"); return 1; } *out = ExceptHandler(type, name, body, lineno, col_offset, arena); if (*out == NULL) goto failed; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of excepthandler, but got %R", obj); failed: Py_XDECREF(tmp); return 1; } int obj2ast_arguments(PyObject* obj, arguments_ty* out, PyArena* arena) { PyObject* tmp = NULL; asdl_seq* args; arg_ty vararg; asdl_seq* kwonlyargs; asdl_seq* kw_defaults; arg_ty kwarg; asdl_seq* defaults; if (_PyObject_HasAttrId(obj, &PyId_args)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_args); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "arguments field \"args\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); args = _Py_asdl_seq_new(len, arena); if (args == NULL) goto failed; for (i = 0; i < len; i++) { arg_ty val; res = obj2ast_arg(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "arguments field \"args\" changed size during iteration"); goto failed; } asdl_seq_SET(args, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from arguments"); return 1; } if (exists_not_none(obj, &PyId_vararg)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_vararg); if (tmp == NULL) goto failed; res = obj2ast_arg(tmp, &vararg, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { vararg = NULL; } if (_PyObject_HasAttrId(obj, &PyId_kwonlyargs)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_kwonlyargs); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "arguments field \"kwonlyargs\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); kwonlyargs = _Py_asdl_seq_new(len, arena); if (kwonlyargs == NULL) goto failed; for (i = 0; i < len; i++) { arg_ty val; res = obj2ast_arg(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "arguments field \"kwonlyargs\" changed size during iteration"); goto failed; } asdl_seq_SET(kwonlyargs, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"kwonlyargs\" missing from arguments"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_kw_defaults)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_kw_defaults); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "arguments field \"kw_defaults\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); kw_defaults = _Py_asdl_seq_new(len, arena); if (kw_defaults == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "arguments field \"kw_defaults\" changed size during iteration"); goto failed; } asdl_seq_SET(kw_defaults, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"kw_defaults\" missing from arguments"); return 1; } if (exists_not_none(obj, &PyId_kwarg)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_kwarg); if (tmp == NULL) goto failed; res = obj2ast_arg(tmp, &kwarg, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { kwarg = NULL; } if (_PyObject_HasAttrId(obj, &PyId_defaults)) { int res; Py_ssize_t len; Py_ssize_t i; tmp = _PyObject_GetAttrId(obj, &PyId_defaults); if (tmp == NULL) goto failed; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "arguments field \"defaults\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); defaults = _Py_asdl_seq_new(len, arena); if (defaults == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "arguments field \"defaults\" changed size during iteration"); goto failed; } asdl_seq_SET(defaults, i, val); } Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"defaults\" missing from arguments"); return 1; } *out = arguments(args, vararg, kwonlyargs, kw_defaults, kwarg, defaults, arena); return 0; failed: Py_XDECREF(tmp); return 1; } int obj2ast_arg(PyObject* obj, arg_ty* out, PyArena* arena) { PyObject* tmp = NULL; identifier arg; expr_ty annotation; int lineno; int col_offset; if (_PyObject_HasAttrId(obj, &PyId_arg)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_arg); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &arg, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"arg\" missing from arg"); return 1; } if (exists_not_none(obj, &PyId_annotation)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_annotation); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &annotation, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { annotation = NULL; } if (_PyObject_HasAttrId(obj, &PyId_lineno)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_lineno); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &lineno, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from arg"); return 1; } if (_PyObject_HasAttrId(obj, &PyId_col_offset)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_col_offset); if (tmp == NULL) goto failed; res = obj2ast_int(tmp, &col_offset, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from arg"); return 1; } *out = arg(arg, annotation, lineno, col_offset, arena); return 0; failed: Py_XDECREF(tmp); return 1; } int obj2ast_keyword(PyObject* obj, keyword_ty* out, PyArena* arena) { PyObject* tmp = NULL; identifier arg; expr_ty value; if (exists_not_none(obj, &PyId_arg)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_arg); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &arg, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { arg = NULL; } if (_PyObject_HasAttrId(obj, &PyId_value)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_value); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from keyword"); return 1; } *out = keyword(arg, value, arena); return 0; failed: Py_XDECREF(tmp); return 1; } int obj2ast_alias(PyObject* obj, alias_ty* out, PyArena* arena) { PyObject* tmp = NULL; identifier name; identifier asname; if (_PyObject_HasAttrId(obj, &PyId_name)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_name); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &name, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from alias"); return 1; } if (exists_not_none(obj, &PyId_asname)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_asname); if (tmp == NULL) goto failed; res = obj2ast_identifier(tmp, &asname, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { asname = NULL; } *out = alias(name, asname, arena); return 0; failed: Py_XDECREF(tmp); return 1; } int obj2ast_withitem(PyObject* obj, withitem_ty* out, PyArena* arena) { PyObject* tmp = NULL; expr_ty context_expr; expr_ty optional_vars; if (_PyObject_HasAttrId(obj, &PyId_context_expr)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_context_expr); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &context_expr, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { PyErr_SetString(PyExc_TypeError, "required field \"context_expr\" missing from withitem"); return 1; } if (exists_not_none(obj, &PyId_optional_vars)) { int res; tmp = _PyObject_GetAttrId(obj, &PyId_optional_vars); if (tmp == NULL) goto failed; res = obj2ast_expr(tmp, &optional_vars, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } else { optional_vars = NULL; } *out = withitem(context_expr, optional_vars, arena); return 0; failed: Py_XDECREF(tmp); return 1; } static struct PyModuleDef _astmodule = { PyModuleDef_HEAD_INIT, "_ast" }; PyMODINIT_FUNC PyInit__ast(void) { PyObject *m, *d; if (!init_types()) return NULL; m = PyModule_Create(&_astmodule); if (!m) return NULL; d = PyModule_GetDict(m); if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return NULL; if (PyModule_AddIntMacro(m, PyCF_ONLY_AST) < 0) return NULL; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return NULL; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) return NULL; if (PyDict_SetItemString(d, "Interactive", (PyObject*)Interactive_type) < 0) return NULL; if (PyDict_SetItemString(d, "Expression", (PyObject*)Expression_type) < 0) return NULL; if (PyDict_SetItemString(d, "Suite", (PyObject*)Suite_type) < 0) return NULL; if (PyDict_SetItemString(d, "stmt", (PyObject*)stmt_type) < 0) return NULL; if (PyDict_SetItemString(d, "FunctionDef", (PyObject*)FunctionDef_type) < 0) return NULL; if (PyDict_SetItemString(d, "AsyncFunctionDef", (PyObject*)AsyncFunctionDef_type) < 0) return NULL; if (PyDict_SetItemString(d, "ClassDef", (PyObject*)ClassDef_type) < 0) return NULL; if (PyDict_SetItemString(d, "Return", (PyObject*)Return_type) < 0) return NULL; if (PyDict_SetItemString(d, "Delete", (PyObject*)Delete_type) < 0) return NULL; if (PyDict_SetItemString(d, "Assign", (PyObject*)Assign_type) < 0) return NULL; if (PyDict_SetItemString(d, "AugAssign", (PyObject*)AugAssign_type) < 0) return NULL; if (PyDict_SetItemString(d, "AnnAssign", (PyObject*)AnnAssign_type) < 0) return NULL; if (PyDict_SetItemString(d, "For", (PyObject*)For_type) < 0) return NULL; if (PyDict_SetItemString(d, "AsyncFor", (PyObject*)AsyncFor_type) < 0) return NULL; if (PyDict_SetItemString(d, "While", (PyObject*)While_type) < 0) return NULL; if (PyDict_SetItemString(d, "If", (PyObject*)If_type) < 0) return NULL; if (PyDict_SetItemString(d, "With", (PyObject*)With_type) < 0) return NULL; if (PyDict_SetItemString(d, "AsyncWith", (PyObject*)AsyncWith_type) < 0) return NULL; if (PyDict_SetItemString(d, "Raise", (PyObject*)Raise_type) < 0) return NULL; if (PyDict_SetItemString(d, "Try", (PyObject*)Try_type) < 0) return NULL; if (PyDict_SetItemString(d, "Assert", (PyObject*)Assert_type) < 0) return NULL; if (PyDict_SetItemString(d, "Import", (PyObject*)Import_type) < 0) return NULL; if (PyDict_SetItemString(d, "ImportFrom", (PyObject*)ImportFrom_type) < 0) return NULL; if (PyDict_SetItemString(d, "Global", (PyObject*)Global_type) < 0) return NULL; if (PyDict_SetItemString(d, "Nonlocal", (PyObject*)Nonlocal_type) < 0) return NULL; if (PyDict_SetItemString(d, "Expr", (PyObject*)Expr_type) < 0) return NULL; if (PyDict_SetItemString(d, "Pass", (PyObject*)Pass_type) < 0) return NULL; if (PyDict_SetItemString(d, "Break", (PyObject*)Break_type) < 0) return NULL; if (PyDict_SetItemString(d, "Continue", (PyObject*)Continue_type) < 0) return NULL; if (PyDict_SetItemString(d, "expr", (PyObject*)expr_type) < 0) return NULL; if (PyDict_SetItemString(d, "BoolOp", (PyObject*)BoolOp_type) < 0) return NULL; if (PyDict_SetItemString(d, "BinOp", (PyObject*)BinOp_type) < 0) return NULL; if (PyDict_SetItemString(d, "UnaryOp", (PyObject*)UnaryOp_type) < 0) return NULL; if (PyDict_SetItemString(d, "Lambda", (PyObject*)Lambda_type) < 0) return NULL; if (PyDict_SetItemString(d, "IfExp", (PyObject*)IfExp_type) < 0) return NULL; if (PyDict_SetItemString(d, "Dict", (PyObject*)Dict_type) < 0) return NULL; if (PyDict_SetItemString(d, "Set", (PyObject*)Set_type) < 0) return NULL; if (PyDict_SetItemString(d, "ListComp", (PyObject*)ListComp_type) < 0) return NULL; if (PyDict_SetItemString(d, "SetComp", (PyObject*)SetComp_type) < 0) return NULL; if (PyDict_SetItemString(d, "DictComp", (PyObject*)DictComp_type) < 0) return NULL; if (PyDict_SetItemString(d, "GeneratorExp", (PyObject*)GeneratorExp_type) < 0) return NULL; if (PyDict_SetItemString(d, "Await", (PyObject*)Await_type) < 0) return NULL; if (PyDict_SetItemString(d, "Yield", (PyObject*)Yield_type) < 0) return NULL; if (PyDict_SetItemString(d, "YieldFrom", (PyObject*)YieldFrom_type) < 0) return NULL; if (PyDict_SetItemString(d, "Compare", (PyObject*)Compare_type) < 0) return NULL; if (PyDict_SetItemString(d, "Call", (PyObject*)Call_type) < 0) return NULL; if (PyDict_SetItemString(d, "Num", (PyObject*)Num_type) < 0) return NULL; if (PyDict_SetItemString(d, "Str", (PyObject*)Str_type) < 0) return NULL; if (PyDict_SetItemString(d, "FormattedValue", (PyObject*)FormattedValue_type) < 0) return NULL; if (PyDict_SetItemString(d, "JoinedStr", (PyObject*)JoinedStr_type) < 0) return NULL; if (PyDict_SetItemString(d, "Bytes", (PyObject*)Bytes_type) < 0) return NULL; if (PyDict_SetItemString(d, "NameConstant", (PyObject*)NameConstant_type) < 0) return NULL; if (PyDict_SetItemString(d, "Ellipsis", (PyObject*)Ellipsis_type) < 0) return NULL; if (PyDict_SetItemString(d, "Constant", (PyObject*)Constant_type) < 0) return NULL; if (PyDict_SetItemString(d, "Attribute", (PyObject*)Attribute_type) < 0) return NULL; if (PyDict_SetItemString(d, "Subscript", (PyObject*)Subscript_type) < 0) return NULL; if (PyDict_SetItemString(d, "Starred", (PyObject*)Starred_type) < 0) return NULL; if (PyDict_SetItemString(d, "Name", (PyObject*)Name_type) < 0) return NULL; if (PyDict_SetItemString(d, "List", (PyObject*)List_type) < 0) return NULL; if (PyDict_SetItemString(d, "Tuple", (PyObject*)Tuple_type) < 0) return NULL; if (PyDict_SetItemString(d, "expr_context", (PyObject*)expr_context_type) < 0) return NULL; if (PyDict_SetItemString(d, "Load", (PyObject*)Load_type) < 0) return NULL; if (PyDict_SetItemString(d, "Store", (PyObject*)Store_type) < 0) return NULL; if (PyDict_SetItemString(d, "Del", (PyObject*)Del_type) < 0) return NULL; if (PyDict_SetItemString(d, "AugLoad", (PyObject*)AugLoad_type) < 0) return NULL; if (PyDict_SetItemString(d, "AugStore", (PyObject*)AugStore_type) < 0) return NULL; if (PyDict_SetItemString(d, "Param", (PyObject*)Param_type) < 0) return NULL; if (PyDict_SetItemString(d, "slice", (PyObject*)slice_type) < 0) return NULL; if (PyDict_SetItemString(d, "Slice", (PyObject*)Slice_type) < 0) return NULL; if (PyDict_SetItemString(d, "ExtSlice", (PyObject*)ExtSlice_type) < 0) return NULL; if (PyDict_SetItemString(d, "Index", (PyObject*)Index_type) < 0) return NULL; if (PyDict_SetItemString(d, "boolop", (PyObject*)boolop_type) < 0) return NULL; if (PyDict_SetItemString(d, "And", (PyObject*)And_type) < 0) return NULL; if (PyDict_SetItemString(d, "Or", (PyObject*)Or_type) < 0) return NULL; if (PyDict_SetItemString(d, "operator", (PyObject*)operator_type) < 0) return NULL; if (PyDict_SetItemString(d, "Add", (PyObject*)Add_type) < 0) return NULL; if (PyDict_SetItemString(d, "Sub", (PyObject*)Sub_type) < 0) return NULL; if (PyDict_SetItemString(d, "Mult", (PyObject*)Mult_type) < 0) return NULL; if (PyDict_SetItemString(d, "MatMult", (PyObject*)MatMult_type) < 0) return NULL; if (PyDict_SetItemString(d, "Div", (PyObject*)Div_type) < 0) return NULL; if (PyDict_SetItemString(d, "Mod", (PyObject*)Mod_type) < 0) return NULL; if (PyDict_SetItemString(d, "Pow", (PyObject*)Pow_type) < 0) return NULL; if (PyDict_SetItemString(d, "LShift", (PyObject*)LShift_type) < 0) return NULL; if (PyDict_SetItemString(d, "RShift", (PyObject*)RShift_type) < 0) return NULL; if (PyDict_SetItemString(d, "BitOr", (PyObject*)BitOr_type) < 0) return NULL; if (PyDict_SetItemString(d, "BitXor", (PyObject*)BitXor_type) < 0) return NULL; if (PyDict_SetItemString(d, "BitAnd", (PyObject*)BitAnd_type) < 0) return NULL; if (PyDict_SetItemString(d, "FloorDiv", (PyObject*)FloorDiv_type) < 0) return NULL; if (PyDict_SetItemString(d, "unaryop", (PyObject*)unaryop_type) < 0) return NULL; if (PyDict_SetItemString(d, "Invert", (PyObject*)Invert_type) < 0) return NULL; if (PyDict_SetItemString(d, "Not", (PyObject*)Not_type) < 0) return NULL; if (PyDict_SetItemString(d, "UAdd", (PyObject*)UAdd_type) < 0) return NULL; if (PyDict_SetItemString(d, "USub", (PyObject*)USub_type) < 0) return NULL; if (PyDict_SetItemString(d, "cmpop", (PyObject*)cmpop_type) < 0) return NULL; if (PyDict_SetItemString(d, "Eq", (PyObject*)Eq_type) < 0) return NULL; if (PyDict_SetItemString(d, "NotEq", (PyObject*)NotEq_type) < 0) return NULL; if (PyDict_SetItemString(d, "Lt", (PyObject*)Lt_type) < 0) return NULL; if (PyDict_SetItemString(d, "LtE", (PyObject*)LtE_type) < 0) return NULL; if (PyDict_SetItemString(d, "Gt", (PyObject*)Gt_type) < 0) return NULL; if (PyDict_SetItemString(d, "GtE", (PyObject*)GtE_type) < 0) return NULL; if (PyDict_SetItemString(d, "Is", (PyObject*)Is_type) < 0) return NULL; if (PyDict_SetItemString(d, "IsNot", (PyObject*)IsNot_type) < 0) return NULL; if (PyDict_SetItemString(d, "In", (PyObject*)In_type) < 0) return NULL; if (PyDict_SetItemString(d, "NotIn", (PyObject*)NotIn_type) < 0) return NULL; if (PyDict_SetItemString(d, "comprehension", (PyObject*)comprehension_type) < 0) return NULL; if (PyDict_SetItemString(d, "excepthandler", (PyObject*)excepthandler_type) < 0) return NULL; if (PyDict_SetItemString(d, "ExceptHandler", (PyObject*)ExceptHandler_type) < 0) return NULL; if (PyDict_SetItemString(d, "arguments", (PyObject*)arguments_type) < 0) return NULL; if (PyDict_SetItemString(d, "arg", (PyObject*)arg_type) < 0) return NULL; if (PyDict_SetItemString(d, "keyword", (PyObject*)keyword_type) < 0) return NULL; if (PyDict_SetItemString(d, "alias", (PyObject*)alias_type) < 0) return NULL; if (PyDict_SetItemString(d, "withitem", (PyObject*)withitem_type) < 0) return NULL; return m; } PyObject* PyAST_mod2obj(mod_ty t) { if (!init_types()) return NULL; return ast2obj_mod(t); } /* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */ mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode) { mod_ty res; PyObject *req_type[3]; char *req_name[] = {"Module", "Expression", "Interactive"}; int isinstance; req_type[0] = (PyObject*)Module_type; req_type[1] = (PyObject*)Expression_type; req_type[2] = (PyObject*)Interactive_type; assert(0 <= mode && mode <= 2); if (!init_types()) return NULL; isinstance = PyObject_IsInstance(ast, req_type[mode]); if (isinstance == -1) return NULL; if (!isinstance) { PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s", req_name[mode], Py_TYPE(ast)->tp_name); return NULL; } if (obj2ast_mod(ast, &res, arena) != 0) return NULL; else return res; } int PyAST_Check(PyObject* obj) { if (!init_types()) return -1; return PyObject_IsInstance(obj, (PyObject*)&AST_type); }
270,763
8,119
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/ceval.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_LOCAL_AGGRESSIVE #include "libc/errno.h" #include "libc/intrin/likely.h" #include "libc/runtime/stack.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/cellobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/classobject.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/eval.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/genobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/opcode.h" #include "third_party/python/Include/pydtrace.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ /* Execute compiled code */ /* XXX TO DO: XXX speed up searching for keywords by using a dictionary XXX document it! */ /* Turn this on if your compiler chokes on the big switch: */ /* #define CASE_TOO_BIG 1 */ #ifdef Py_DEBUG /* For debugging the interpreter: */ #define LLTRACE 1 /* Low-level trace feature */ #define CHECKEXC 1 /* Double-check exception checking */ #endif extern int _PyObject_GetMethod(PyObject *, PyObject *, PyObject **); typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *); #ifdef LLTRACE static int lltrace; static int prtrace(PyObject *, const char *); #endif static PyObject *call_function(PyObject ***, Py_ssize_t, PyObject *); static PyObject *cmp_outcome(int, PyObject *, PyObject *); static PyObject *do_call_core(PyObject *, PyObject *, PyObject *); static PyObject *import_from(PyObject *, PyObject *); static PyObject *import_name(PyFrameObject *, PyObject *, PyObject *, PyObject *); static PyObject *special_lookup(PyObject *, _Py_Identifier *); static PyObject *unicode_concatenate(PyObject *, PyObject *, PyFrameObject *, const _Py_CODEUNIT *); static int call_trace(Py_tracefunc, PyObject *, PyThreadState *, PyFrameObject *, int, PyObject *); static int call_trace_protected(Py_tracefunc, PyObject *, PyThreadState *, PyFrameObject *, int, PyObject *); static int check_args_iterable(PyObject *, PyObject *); static int import_all_from(PyObject *, PyObject *); static int maybe_call_line_trace(Py_tracefunc, PyObject *, PyThreadState *, PyFrameObject *, int *, int *, int *); static void call_exc_trace(Py_tracefunc, PyObject *, PyThreadState *, PyFrameObject *); static void dtrace_function_entry(PyFrameObject *); static void dtrace_function_return(PyFrameObject *); static void format_awaitable_error(PyTypeObject *, int); static void format_exc_check_arg(PyObject *, const char *, PyObject *); static void format_exc_unbound(PyCodeObject *, int); static void format_kwargs_mapping_error(PyObject *, PyObject *); static void maybe_dtrace_line(PyFrameObject *, int *, int *, int *); #define NAME_ERROR_MSG \ "name '%.200s' is not defined" #define UNBOUNDLOCAL_ERROR_MSG \ "local variable '%.200s' referenced before assignment" #define UNBOUNDFREE_ERROR_MSG \ "free variable '%.200s' referenced before assignment" \ " in enclosing scope" /* Dynamic execution profile */ #ifdef DYNAMIC_EXECUTION_PROFILE #ifdef DXPAIRS static long dxpairs[257][256]; #define dxp dxpairs[256] #else static long dxp[256]; #endif #endif /* Function call profile */ #ifdef CALL_PROFILE #define PCALL_NUM 11 static int pcall[PCALL_NUM]; #define PCALL_ALL 0 #define PCALL_FUNCTION 1 #define PCALL_FAST_FUNCTION 2 #define PCALL_FASTER_FUNCTION 3 #define PCALL_METHOD 4 #define PCALL_BOUND_METHOD 5 #define PCALL_CFUNCTION 6 #define PCALL_TYPE 7 #define PCALL_GENERATOR 8 #define PCALL_OTHER 9 #define PCALL_POP 10 /* Notes about the statistics PCALL_FAST stats FAST_FUNCTION means no argument tuple needs to be created. FASTER_FUNCTION means that the fast-path frame setup code is used. If there is a method call where the call can be optimized by changing the argument tuple and calling the function directly, it gets recorded twice. As a result, the relationship among the statistics appears to be PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD + PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION PCALL_METHOD > PCALL_BOUND_METHOD */ #define PCALL(POS) pcall[POS]++ PyObject * PyEval_GetCallStats(PyObject *self) { return Py_BuildValue("iiiiiiiiiii", pcall[0], pcall[1], pcall[2], pcall[3], pcall[4], pcall[5], pcall[6], pcall[7], pcall[8], pcall[9], pcall[10]); } #else #define PCALL(O) PyObject * PyEval_GetCallStats(PyObject *self) { Py_INCREF(Py_None); return Py_None; } #endif #ifdef WITH_THREAD #define GIL_REQUEST _Py_atomic_load_relaxed(&gil_drop_request) #else #define GIL_REQUEST 0 #endif /* This can set eval_breaker to 0 even though gil_drop_request became 1. We believe this is all right because the eval loop will release the GIL eventually anyway. */ #define COMPUTE_EVAL_BREAKER() \ _Py_atomic_store_relaxed( \ &eval_breaker, \ GIL_REQUEST | \ _Py_atomic_load_relaxed(&pendingcalls_to_do) | \ pending_async_exc) #ifdef WITH_THREAD #define SET_GIL_DROP_REQUEST() \ do { \ _Py_atomic_store_relaxed(&gil_drop_request, 1); \ _Py_atomic_store_relaxed(&eval_breaker, 1); \ } while (0) #define RESET_GIL_DROP_REQUEST() \ do { \ _Py_atomic_store_relaxed(&gil_drop_request, 0); \ COMPUTE_EVAL_BREAKER(); \ } while (0) #endif /* Pending calls are only modified under pending_lock */ #define SIGNAL_PENDING_CALLS() \ do { \ _Py_atomic_store_relaxed(&pendingcalls_to_do, 1); \ _Py_atomic_store_relaxed(&eval_breaker, 1); \ } while (0) #define UNSIGNAL_PENDING_CALLS() \ do { \ _Py_atomic_store_relaxed(&pendingcalls_to_do, 0); \ COMPUTE_EVAL_BREAKER(); \ } while (0) #define SIGNAL_ASYNC_EXC() \ do { \ pending_async_exc = 1; \ _Py_atomic_store_relaxed(&eval_breaker, 1); \ } while (0) #define UNSIGNAL_ASYNC_EXC() \ do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0) /* This single variable consolidates all requests to break out of the fast path in the eval loop. */ static _Py_atomic_int eval_breaker = {0}; /* Request for running pending calls. */ static _Py_atomic_int pendingcalls_to_do = {0}; /* Request for looking at the `async_exc` field of the current thread state. Guarded by the GIL. */ static int pending_async_exc = 0; #ifdef WITH_THREAD #include "third_party/python/Include/pythread.h" static PyThread_type_lock pending_lock = 0; /* for pending calls */ static long main_thread = 0; /* Request for dropping the GIL */ static _Py_atomic_int gil_drop_request = {0}; #include "third_party/python/Python/ceval_gil.inc" int PyEval_ThreadsInitialized(void) { return gil_created(); } void PyEval_InitThreads(void) { if (gil_created()) return; create_gil(); take_gil(PyThreadState_GET()); main_thread = PyThread_get_thread_ident(); if (!pending_lock) pending_lock = PyThread_allocate_lock(); } void _PyEval_FiniThreads(void) { if (!gil_created()) return; destroy_gil(); assert(!gil_created()); } void PyEval_AcquireLock(void) { PyThreadState *tstate = PyThreadState_GET(); if (tstate == NULL) Py_FatalError("PyEval_AcquireLock: current thread state is NULL"); take_gil(tstate); } void PyEval_ReleaseLock(void) { /* This function must succeed when the current thread state is NULL. We therefore avoid PyThreadState_GET() which dumps a fatal error in debug mode. */ drop_gil((PyThreadState*)_Py_atomic_load_relaxed( &_PyThreadState_Current)); } void PyEval_AcquireThread(PyThreadState *tstate) { if (tstate == NULL) Py_FatalError("PyEval_AcquireThread: NULL new thread state"); /* Check someone has called PyEval_InitThreads() to create the lock */ assert(gil_created()); take_gil(tstate); if (PyThreadState_Swap(tstate) != NULL) Py_FatalError( "PyEval_AcquireThread: non-NULL old thread state"); } void PyEval_ReleaseThread(PyThreadState *tstate) { if (tstate == NULL) Py_FatalError("PyEval_ReleaseThread: NULL thread state"); if (PyThreadState_Swap(NULL) != tstate) Py_FatalError("PyEval_ReleaseThread: wrong thread state"); drop_gil(tstate); } /* This function is called from PyOS_AfterFork to destroy all threads which are * not running in the child process, and clear internal locks which might be * held by those threads. (This could also be done using pthread_atfork * mechanism, at least for the pthreads implementation.) */ void PyEval_ReInitThreads(void) { _Py_IDENTIFIER(_after_fork); PyObject *threading, *result; PyThreadState *current_tstate = PyThreadState_GET(); if (!gil_created()) return; recreate_gil(); pending_lock = PyThread_allocate_lock(); take_gil(current_tstate); main_thread = PyThread_get_thread_ident(); /* Update the threading module with the new state. */ threading = PyMapping_GetItemString(current_tstate->interp->modules, "threading"); if (threading == NULL) { /* threading not imported */ PyErr_Clear(); return; } result = _PyObject_CallMethodId(threading, &PyId__after_fork, NULL); if (result == NULL) PyErr_WriteUnraisable(threading); else Py_DECREF(result); Py_DECREF(threading); /* Destroy all threads except the current one */ _PyThreadState_DeleteExcept(current_tstate); } #endif /* WITH_THREAD */ /* This function is used to signal that async exceptions are waiting to be raised, therefore it is also useful in non-threaded builds. */ void _PyEval_SignalAsyncExc(void) { SIGNAL_ASYNC_EXC(); } /* Functions save_thread and restore_thread are always defined so dynamically loaded modules needn't be compiled separately for use with and without threads: */ PyThreadState * PyEval_SaveThread(void) { PyThreadState *tstate = PyThreadState_Swap(NULL); if (tstate == NULL) Py_FatalError("PyEval_SaveThread: NULL tstate"); #ifdef WITH_THREAD if (gil_created()) drop_gil(tstate); #endif return tstate; } void PyEval_RestoreThread(PyThreadState *tstate) { if (tstate == NULL) Py_FatalError("PyEval_RestoreThread: NULL tstate"); #ifdef WITH_THREAD if (gil_created()) { int err = errno; take_gil(tstate); /* _Py_Finalizing is protected by the GIL */ if (_Py_Finalizing && tstate != _Py_Finalizing) { drop_gil(tstate); PyThread_exit_thread(); assert(0); /* unreachable */ } errno = err; } #endif PyThreadState_Swap(tstate); } /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX signal handlers or Mac I/O completion routines) can schedule calls to a function to be called synchronously. The synchronous function is called with one void* argument. It should return 0 for success or -1 for failure -- failure should be accompanied by an exception. If registry succeeds, the registry function returns 0; if it fails (e.g. due to too many pending calls) it returns -1 (without setting an exception condition). Note that because registry may occur from within signal handlers, or other asynchronous events, calling malloc() is unsafe! #ifdef WITH_THREAD Any thread can schedule pending calls, but only the main thread will execute them. There is no facility to schedule calls to a particular thread, but that should be easy to change, should that ever be required. In that case, the static variables here should go into the python threadstate. #endif */ void _PyEval_SignalReceived(void) { /* bpo-30703: Function called when the C signal handler of Python gets a signal. We cannot queue a callback using Py_AddPendingCall() since that function is not async-signal-safe. */ SIGNAL_PENDING_CALLS(); } #ifdef WITH_THREAD /* The WITH_THREAD implementation is thread-safe. It allows scheduling to be made from any thread, and even from an executing callback. */ #define NPENDINGCALLS 32 static struct { int (*func)(void *); void *arg; } pendingcalls[NPENDINGCALLS]; static int pendingfirst = 0; static int pendinglast = 0; int Py_AddPendingCall(int (*func)(void *), void *arg) { int i, j, result=0; PyThread_type_lock lock = pending_lock; /* try a few times for the lock. Since this mechanism is used * for signal handling (on the main thread), there is a (slim) * chance that a signal is delivered on the same thread while we * hold the lock during the Py_MakePendingCalls() function. * This avoids a deadlock in that case. * Note that signals can be delivered on any thread. In particular, * on Windows, a SIGINT is delivered on a system-created worker * thread. * We also check for lock being NULL, in the unlikely case that * this function is called before any bytecode evaluation takes place. */ if (lock != NULL) { for (i = 0; i<100; i++) { if (PyThread_acquire_lock(lock, NOWAIT_LOCK)) break; } if (i == 100) return -1; } i = pendinglast; j = (i + 1) % NPENDINGCALLS; if (j == pendingfirst) { result = -1; /* Queue full */ } else { pendingcalls[i].func = func; pendingcalls[i].arg = arg; pendinglast = j; } /* signal main loop */ SIGNAL_PENDING_CALLS(); if (lock != NULL) PyThread_release_lock(lock); return result; } int Py_MakePendingCalls(void) { static int busy = 0; int i; int r = 0; assert(PyGILState_Check()); if (!pending_lock) { /* initial allocation of the lock */ pending_lock = PyThread_allocate_lock(); if (pending_lock == NULL) return -1; } /* only service pending calls on main thread */ if (main_thread && PyThread_get_thread_ident() != main_thread) return 0; /* don't perform recursive pending calls */ if (busy) return 0; busy = 1; /* unsignal before starting to call callbacks, so that any callback added in-between re-signals */ UNSIGNAL_PENDING_CALLS(); /* Python signal handler doesn't really queue a callback: it only signals that a signal was received, see _PyEval_SignalReceived(). */ if (PyErr_CheckSignals() < 0) { goto error; } /* perform a bounded number of calls, in case of recursion */ for (i=0; i<NPENDINGCALLS; i++) { int j; int (*func)(void *); void *arg = NULL; /* pop one item off the queue while holding the lock */ PyThread_acquire_lock(pending_lock, WAIT_LOCK); j = pendingfirst; if (j == pendinglast) { func = NULL; /* Queue empty */ } else { func = pendingcalls[j].func; arg = pendingcalls[j].arg; pendingfirst = (j + 1) % NPENDINGCALLS; } PyThread_release_lock(pending_lock); /* having released the lock, perform the callback */ if (func == NULL) break; r = func(arg); if (r) { goto error; } } busy = 0; return r; error: busy = 0; SIGNAL_PENDING_CALLS(); /* We're not done yet */ return -1; } #else /* if ! defined WITH_THREAD */ /* WARNING! ASYNCHRONOUSLY EXECUTING CODE! This code is used for signal handling in python that isn't built with WITH_THREAD. Don't use this implementation when Py_AddPendingCalls() can happen on a different thread! There are two possible race conditions: (1) nested asynchronous calls to Py_AddPendingCall() (2) AddPendingCall() calls made while pending calls are being processed. (1) is very unlikely because typically signal delivery is blocked during signal handling. So it should be impossible. (2) is a real possibility. The current code is safe against (2), but not against (1). The safety against (2) is derived from the fact that only one thread is present, interrupted by signals, and that the critical section is protected with the "busy" variable. On Windows, which delivers SIGINT on a system thread, this does not hold and therefore Windows really shouldn't use this version. The two threads could theoretically wiggle around the "busy" variable. */ #define NPENDINGCALLS 32 static struct { int (*func)(void *); void *arg; } pendingcalls[NPENDINGCALLS]; static volatile int pendingfirst = 0; static volatile int pendinglast = 0; int Py_AddPendingCall(int (*func)(void *), void *arg) { static volatile int busy = 0; int i, j; /* XXX Begin critical section */ if (busy) return -1; busy = 1; i = pendinglast; j = (i + 1) % NPENDINGCALLS; if (j == pendingfirst) { busy = 0; return -1; /* Queue full */ } pendingcalls[i].func = func; pendingcalls[i].arg = arg; pendinglast = j; SIGNAL_PENDING_CALLS(); busy = 0; /* XXX End critical section */ return 0; } int Py_MakePendingCalls(void) { static int busy = 0; if (busy) return 0; busy = 1; /* unsignal before starting to call callbacks, so that any callback added in-between re-signals */ UNSIGNAL_PENDING_CALLS(); /* Python signal handler doesn't really queue a callback: it only signals that a signal was received, see _PyEval_SignalReceived(). */ if (PyErr_CheckSignals() < 0) { goto error; } for (;;) { int i; int (*func)(void *); void *arg; i = pendingfirst; if (i == pendinglast) break; /* Queue empty */ func = pendingcalls[i].func; arg = pendingcalls[i].arg; pendingfirst = (i + 1) % NPENDINGCALLS; if (func(arg) < 0) { goto error; } } busy = 0; return 0; error: busy = 0; SIGNAL_PENDING_CALLS(); /* We're not done yet */ return -1; } #endif /* WITH_THREAD */ /* The interpreter's recursion limit */ #ifndef Py_DEFAULT_RECURSION_LIMIT #define Py_DEFAULT_RECURSION_LIMIT 1000 #endif static int recursion_limit = Py_DEFAULT_RECURSION_LIMIT; int _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT; int Py_GetRecursionLimit(void) { return recursion_limit; } void Py_SetRecursionLimit(int new_limit) { recursion_limit = new_limit; _Py_CheckRecursionLimit = recursion_limit; } int _Py_CheckRecursiveCall(const char *where) { PyThreadState *t; const char *rsp, *bot; rsp = __builtin_frame_address(0); bot = (const char *)GetStackAddr() + 32768; if (rsp > bot) { t = PyThreadState_GET(); _Py_CheckRecursionLimit = recursion_limit; if (t->recursion_depth > recursion_limit && !t->recursion_critical) { --t->recursion_depth; t->overflowed = 1; PyErr_Format(PyExc_RecursionError, "maximum recursion depth exceeded%s", where); return -1; } return 0; } else if (rsp > bot - 20480) { PyErr_Format(PyExc_MemoryError, "Stack overflow%s", where); return -1; } else { Py_FatalError("Cannot recover from stack overflow"); } } /* Status code for main loop (reason for stack unwind) */ enum why_code { WHY_NOT = 0x0001, /* No error */ WHY_EXCEPTION = 0x0002, /* Exception occurred */ WHY_RETURN = 0x0008, /* 'return' statement */ WHY_BREAK = 0x0010, /* 'break' statement */ WHY_CONTINUE = 0x0020, /* 'continue' statement */ WHY_YIELD = 0x0040, /* 'yield' operator */ WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */ }; static void save_exc_state(PyThreadState *, PyFrameObject *); static void swap_exc_state(PyThreadState *, PyFrameObject *); static void restore_and_clear_exc_state(PyThreadState *, PyFrameObject *); static int do_raise(PyObject *, PyObject *); static int unpack_iterable(PyObject *, int, int, PyObject **); /* Records whether tracing is on for any thread. Counts the number of threads for which tstate->c_tracefunc is non-NULL, so if the value is 0, we know we don't have to check this thread's c_tracefunc. This speeds up the if statement in PyEval_EvalFrameEx() after fast_next_opcode*/ static int _Py_TracingPossible = 0; PyObject * PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals) { return PyEval_EvalCodeEx(co, globals, locals, (PyObject **)NULL, 0, (PyObject **)NULL, 0, (PyObject **)NULL, 0, NULL, NULL); } /* Interpreter main loop */ PyObject * PyEval_EvalFrame(PyFrameObject *f) { /* This is for backward compatibility with extension modules that used this API; core interpreter code should call PyEval_EvalFrameEx() */ return PyEval_EvalFrameEx(f, 0); } PyObject * (PyEval_EvalFrameEx)(PyFrameObject *f, int throwflag) { PyThreadState *tstate = PyThreadState_GET(); return tstate->interp->eval_frame(f, throwflag); } PyObject * _Py_HOT_FUNCTION _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag) { #ifdef DXPAIRS int lastopcode = 0; #endif PyObject **stack_pointer; /* Next free slot in value stack */ const _Py_CODEUNIT *next_instr; int opcode; /* Current opcode */ int oparg; /* Current opcode argument, if any */ enum why_code why; /* Reason for block stack unwind */ PyObject **freevars; PyObject *retval = NULL; /* Return value */ PyThreadState *tstate = PyThreadState_GET(); PyCodeObject *co; /* when tracing we set things up so that not (instr_lb <= current_bytecode_offset < instr_ub) is true when the line being executed has changed. The initial values are such as to make this false the first time it is tested. */ int instr_ub = -1, instr_lb = 0, instr_prev = -1; const _Py_CODEUNIT *first_instr; PyObject *names; PyObject *consts; #ifdef LLTRACE _Py_IDENTIFIER(__ltrace__); #endif /* Computed GOTOs, or the-optimization-commonly-but-improperly-known-as-"threaded code" using gcc's labels-as-values extension (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html). The traditional bytecode evaluation loop uses a "switch" statement, which decent compilers will optimize as a single indirect branch instruction combined with a lookup table of jump addresses. However, since the indirect jump instruction is shared by all opcodes, the CPU will have a hard time making the right prediction for where to jump next (actually, it will be always wrong except in the uncommon case of a sequence of several identical opcodes). "Threaded code" in contrast, uses an explicit jump table and an explicit indirect jump instruction at the end of each opcode. Since the jump instruction is at a different address for each opcode, the CPU will make a separate prediction for each of these instructions, which is equivalent to predicting the second opcode of each opcode pair. These predictions have a much better chance to turn out valid, especially in small bytecode loops. A mispredicted branch on a modern CPU flushes the whole pipeline and can cost several CPU cycles (depending on the pipeline depth), and potentially many more instructions (depending on the pipeline width). A correctly predicted branch, however, is nearly free. At the time of this writing, the "threaded code" version is up to 15-20% faster than the normal "switch" version, depending on the compiler and the CPU architecture. We disable the optimization if DYNAMIC_EXECUTION_PROFILE is defined, because it would render the measurements invalid. NOTE: Care must be taken that the compiler doesn't try to "optimize" the indirect jumps by sharing them between all opcodes. Such optimizations can be disabled on gcc by using the -fno-gcse flag (or possibly -fno-crossjumping). */ #ifdef DYNAMIC_EXECUTION_PROFILE #undef USE_COMPUTED_GOTOS #define USE_COMPUTED_GOTOS 0 #endif #ifdef HAVE_COMPUTED_GOTOS #ifndef USE_COMPUTED_GOTOS #define USE_COMPUTED_GOTOS 1 #endif #else #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS #error "Computed gotos are not supported on this compiler." #endif #undef USE_COMPUTED_GOTOS #define USE_COMPUTED_GOTOS 0 #endif #if USE_COMPUTED_GOTOS /* Import the static jump table */ #include "third_party/python/Python/opcode_targets.inc" #if __GNUC__ + 0 >= 9 #define HOT_LABEL __attribute__((__hot__)) #define COLD_LABEL __attribute__((__cold__)) #else #define HOT_LABEL #define COLD_LABEL #endif #define TARGET(op) \ TARGET_##op: \ case op: #define LIKELY_TARGET(op) \ TARGET_##op: \ HOT_LABEL; \ case op: #define DISPATCH() \ { \ if (!_Py_atomic_load_relaxed(&eval_breaker)) { \ FAST_DISPATCH(); \ } \ continue; \ } #ifdef LLTRACE #define FAST_DISPATCH() \ { \ if (!lltrace && !_Py_TracingPossible && !PyDTrace_LINE_ENABLED()) { \ f->f_lasti = INSTR_OFFSET(); \ NEXTOPARG(); \ goto *opcode_targets[opcode]; \ } \ goto fast_next_opcode; \ } #else #define FAST_DISPATCH() \ { \ if (!_Py_TracingPossible && !PyDTrace_LINE_ENABLED()) { \ f->f_lasti = INSTR_OFFSET(); \ NEXTOPARG(); \ goto *opcode_targets[opcode]; \ } \ goto fast_next_opcode; \ } #endif #else #define TARGET(op) case op: #define LIKELY_TARGET(op) case op: #define DISPATCH() continue #define FAST_DISPATCH() goto fast_next_opcode #endif /* Tuple access macros */ #ifndef Py_DEBUG #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i)) #else #define GETITEM(v, i) PyTuple_GetItem((v), (i)) #endif /* Code access macros */ /* The integer overflow is checked by an assertion below. */ #define INSTR_OFFSET() ( (char*)next_instr - (char*)first_instr ) #define NEXTOPARG() do { \ _Py_CODEUNIT word = *next_instr; \ opcode = _Py_OPCODE(word); \ oparg = _Py_OPARG(word); \ next_instr++; \ } while (0) #define JUMPTO(x) (next_instr = first_instr + (x) / sizeof(_Py_CODEUNIT)) #define JUMPBY(x) (next_instr += (x) / sizeof(_Py_CODEUNIT)) /* OpCode prediction macros Some opcodes tend to come in pairs thus making it possible to predict the second code when the first is run. For example, COMPARE_OP is often followed by POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE. Verifying the prediction costs a single high-speed test of a register variable against a constant. If the pairing was good, then the processor's own internal branch predication has a high likelihood of success, resulting in a nearly zero-overhead transition to the next opcode. A successful prediction saves a trip through the eval-loop including its unpredictable switch-case branch. Combined with the processor's internal branch prediction, a successful PREDICT has the effect of making the two opcodes run as if they were a single new opcode with the bodies combined. If collecting opcode statistics, your choices are to either keep the predictions turned-on and interpret the results as if some opcodes had been combined or turn-off predictions so that the opcode frequency counter updates for both opcodes. Opcode prediction is disabled with threaded code, since the latter allows the CPU to record separate branch prediction information for each opcode. */ #if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS #define PREDICT(op) if (0) goto PRED_##op #else #define PREDICT(op) \ do{ \ _Py_CODEUNIT word = *next_instr; \ opcode = _Py_OPCODE(word); \ if (opcode == op){ \ oparg = _Py_OPARG(word); \ next_instr++; \ goto PRED_##op; \ } \ } while(0) #endif #define PREDICTED(op) PRED_##op: /* Stack manipulation macros */ /* The stack can grow at most MAXINT deep, as co_nlocals and co_stacksize are ints. */ #define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) #define EMPTY() (STACK_LEVEL() == 0) #define TOP() (stack_pointer[-1]) #define SECOND() (stack_pointer[-2]) #define THIRD() (stack_pointer[-3]) #define FOURTH() (stack_pointer[-4]) #define PEEK(n) (stack_pointer[-(n)]) #define SET_TOP(v) (stack_pointer[-1] = (v)) #define SET_SECOND(v) (stack_pointer[-2] = (v)) #define SET_THIRD(v) (stack_pointer[-3] = (v)) #define SET_FOURTH(v) (stack_pointer[-4] = (v)) #define SET_VALUE(n, v) (stack_pointer[-(n)] = (v)) #define BASIC_STACKADJ(n) (stack_pointer += n) #define BASIC_PUSH(v) (*stack_pointer++ = (v)) #define BASIC_POP() (*--stack_pointer) #ifdef LLTRACE #define PUSH(v) { (void)(BASIC_PUSH(v), \ lltrace && prtrace(TOP(), "push")); \ assert(STACK_LEVEL() <= co->co_stacksize); } #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ BASIC_POP()) #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ lltrace && prtrace(TOP(), "stackadj")); \ assert(STACK_LEVEL() <= co->co_stacksize); } #define EXT_POP(STACK_POINTER) ((void)(lltrace && \ prtrace((STACK_POINTER)[-1], "ext_pop")), \ *--(STACK_POINTER)) #else #define PUSH(v) BASIC_PUSH(v) #define POP() BASIC_POP() #define STACKADJ(n) BASIC_STACKADJ(n) #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER)) #endif /* Local variable macros */ #define GETLOCAL(i) (f->f_localsplus[i]) /* The SETLOCAL() macro must not DECREF the local variable in-place and then store the new value; it must copy the old value to a temporary value, then store the new value, and then DECREF the temporary value. This is because it is possible that during the DECREF the frame is accessed by other code (e.g. a __del__ method or gc.collect()) and the variable would be pointing to already-freed memory. */ #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ GETLOCAL(i) = value; \ Py_XDECREF(tmp); } while (0) #define UNWIND_BLOCK(b) \ while (STACK_LEVEL() > (b)->b_level) { \ PyObject *v = POP(); \ Py_XDECREF(v); \ } #define UNWIND_EXCEPT_HANDLER(b) \ do { \ PyObject *type, *value, *traceback; \ assert(STACK_LEVEL() >= (b)->b_level + 3); \ while (STACK_LEVEL() > (b)->b_level + 3) { \ value = POP(); \ Py_XDECREF(value); \ } \ type = tstate->exc_type; \ value = tstate->exc_value; \ traceback = tstate->exc_traceback; \ tstate->exc_type = POP(); \ tstate->exc_value = POP(); \ tstate->exc_traceback = POP(); \ Py_XDECREF(type); \ Py_XDECREF(value); \ Py_XDECREF(traceback); \ } while(0) /* Start of code */ /* push frame */ if (Py_EnterRecursiveCall("")) return NULL; tstate->frame = f; if (UNLIKELY(tstate->use_tracing)) { if (tstate->c_tracefunc != NULL) { /* tstate->c_tracefunc, if defined, is a function that will be called on *every* entry to a code block. Its return value, if not None, is a function that will be called at the start of each executed line of code. (Actually, the function must return itself in order to continue tracing.) The trace functions are called with three arguments: a pointer to the current frame, a string indicating why the function is called, and an argument which depends on the situation. The global trace function is also called whenever an exception is detected. */ if (call_trace_protected(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, PyTrace_CALL, Py_None)) { /* Trace function raised an error */ goto exit_eval_frame; } } if (tstate->c_profilefunc != NULL) { /* Similar for c_profilefunc, except it needn't return itself and isn't called for "line" events */ if (call_trace_protected(tstate->c_profilefunc, tstate->c_profileobj, tstate, f, PyTrace_CALL, Py_None)) { /* Profile function raised an error */ goto exit_eval_frame; } } } if (PyDTrace_FUNCTION_ENTRY_ENABLED()) dtrace_function_entry(f); co = f->f_code; names = co->co_names; consts = co->co_consts; freevars = f->f_localsplus + co->co_nlocals; assert(PyBytes_Check(co->co_code)); assert(PyBytes_GET_SIZE(co->co_code) <= INT_MAX); assert(PyBytes_GET_SIZE(co->co_code) % sizeof(_Py_CODEUNIT) == 0); assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(co->co_code), sizeof(_Py_CODEUNIT))); first_instr = (_Py_CODEUNIT *) PyBytes_AS_STRING(co->co_code); /* f->f_lasti refers to the index of the last instruction, unless it's -1 in which case next_instr should be first_instr. YIELD_FROM sets f_lasti to itself, in order to repeatedly yield multiple values. When the PREDICT() macros are enabled, some opcode pairs follow in direct succession without updating f->f_lasti. A successful prediction effectively links the two codes together as if they were a single new opcode; accordingly,f->f_lasti will point to the first code in the pair (for instance, GET_ITER followed by FOR_ITER is effectively a single opcode and f->f_lasti will point to the beginning of the combined pair.) */ assert(f->f_lasti >= -1); next_instr = first_instr; if (f->f_lasti >= 0) { assert(f->f_lasti % sizeof(_Py_CODEUNIT) == 0); next_instr += f->f_lasti / sizeof(_Py_CODEUNIT) + 1; } stack_pointer = f->f_stacktop; assert(stack_pointer != NULL); f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ f->f_executing = 1; if (co->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) { if (!throwflag && f->f_exc_type != NULL && f->f_exc_type != Py_None) { /* We were in an except handler when we left, restore the exception state which was put aside (see YIELD_VALUE). */ swap_exc_state(tstate, f); } else save_exc_state(tstate, f); } #ifdef LLTRACE lltrace = _PyDict_GetItemId(f->f_globals, &PyId___ltrace__) != NULL; #endif why = WHY_NOT; if (throwflag) /* support for generator.throw() */ goto error; #ifdef Py_DEBUG /* PyEval_EvalFrameEx() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); #endif for (;;) { assert(stack_pointer >= f->f_valuestack); /* else underflow */ assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ assert(!PyErr_Occurred()); /* Do periodic things. Doing this every time through the loop would add too much overhead, so we do it only every Nth instruction. We also do it if ``pendingcalls_to_do'' is set, i.e. when an asynchronous event needs attention (e.g. a signal handler or async I/O handler); see Py_AddPendingCall() and Py_MakePendingCalls() above. */ if (_Py_atomic_load_relaxed(&eval_breaker)) { opcode = _Py_OPCODE(*next_instr); if (opcode == SETUP_FINALLY || opcode == SETUP_WITH || opcode == BEFORE_ASYNC_WITH || opcode == YIELD_FROM) { /* Few cases where we skip running signal handlers and other pending calls: - If we're about to enter the 'with:'. It will prevent emitting a resource warning in the common idiom 'with open(path) as file:'. - If we're about to enter the 'async with:'. - If we're about to enter the 'try:' of a try/finally (not *very* useful, but might help in some cases and it's traditional) - If we're resuming a chain of nested 'yield from' or 'await' calls, then each frame is parked with YIELD_FROM as its next opcode. If the user hit control-C we want to wait until we've reached the innermost frame before running the signal handler and raising KeyboardInterrupt (see bpo-30039). */ goto fast_next_opcode; } if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) { if (Py_MakePendingCalls() < 0) goto error; } #ifdef WITH_THREAD if (_Py_atomic_load_relaxed(&gil_drop_request)) { /* Give another thread a chance */ if (PyThreadState_Swap(NULL) != tstate) Py_FatalError("ceval: tstate mix-up"); drop_gil(tstate); /* Other threads may run now */ take_gil(tstate); /* Check if we should make a quick exit. */ if (_Py_Finalizing && _Py_Finalizing != tstate) { drop_gil(tstate); PyThread_exit_thread(); } if (PyThreadState_Swap(tstate) != NULL) Py_FatalError("ceval: orphan tstate"); } #endif /* Check for asynchronous exceptions. */ if (UNLIKELY(tstate->async_exc != NULL)) { PyObject *exc = tstate->async_exc; tstate->async_exc = NULL; UNSIGNAL_ASYNC_EXC(); PyErr_SetNone(exc); Py_DECREF(exc); goto error; } } fast_next_opcode: f->f_lasti = INSTR_OFFSET(); if (PyDTrace_LINE_ENABLED()) maybe_dtrace_line(f, &instr_lb, &instr_ub, &instr_prev); /* line-by-line tracing support */ if (_Py_TracingPossible && tstate->c_tracefunc != NULL && !tstate->tracing) { int err; /* see maybe_call_line_trace for expository comments */ f->f_stacktop = stack_pointer; err = maybe_call_line_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, &instr_lb, &instr_ub, &instr_prev); /* Reload possibly changed frame fields */ JUMPTO(f->f_lasti); if (f->f_stacktop != NULL) { stack_pointer = f->f_stacktop; f->f_stacktop = NULL; } if (err) /* trace function raised an exception */ goto error; } /* Extract opcode and argument */ NEXTOPARG(); dispatch_opcode: #ifdef DYNAMIC_EXECUTION_PROFILE #ifdef DXPAIRS dxpairs[lastopcode][opcode]++; lastopcode = opcode; #endif dxp[opcode]++; #endif #ifdef LLTRACE /* Instruction tracing */ if (lltrace) { if (HAS_ARG(opcode)) { printf("%d: %d, %d\n", f->f_lasti, opcode, oparg); } else { printf("%d: %d\n", f->f_lasti, opcode); } } #endif switch (opcode) { /* BEWARE! It is essential that any operation that fails sets either x to NULL, err to nonzero, or why to anything but WHY_NOT, and that no operation that succeeds does this! */ TARGET(NOP) FAST_DISPATCH(); LIKELY_TARGET(LOAD_FAST) { PyObject *value = GETLOCAL(((unsigned)oparg)); if (UNLIKELY(value == NULL)) { format_exc_check_arg(PyExc_UnboundLocalError, UNBOUNDLOCAL_ERROR_MSG, PyTuple_GetItem(co->co_varnames, oparg)); goto error; } Py_INCREF(value); PUSH(value); FAST_DISPATCH(); } PREDICTED(LOAD_CONST); TARGET(LOAD_CONST) { PyObject *value = GETITEM(consts, ((unsigned)oparg)); Py_INCREF(value); PUSH(value); FAST_DISPATCH(); } PREDICTED(STORE_FAST); TARGET(STORE_FAST) { PyObject *value = POP(); SETLOCAL(((unsigned)oparg), value); FAST_DISPATCH(); } TARGET(POP_TOP) { PyObject *value = POP(); Py_DECREF(value); FAST_DISPATCH(); } TARGET(ROT_TWO) { PyObject *top = TOP(); PyObject *second = SECOND(); SET_TOP(second); SET_SECOND(top); FAST_DISPATCH(); } TARGET(ROT_THREE) { PyObject *top = TOP(); PyObject *second = SECOND(); PyObject *third = THIRD(); SET_TOP(second); SET_SECOND(third); SET_THIRD(top); FAST_DISPATCH(); } TARGET(DUP_TOP) { PyObject *top = TOP(); Py_INCREF(top); PUSH(top); FAST_DISPATCH(); } TARGET(DUP_TOP_TWO) { PyObject *top = TOP(); PyObject *second = SECOND(); Py_INCREF(top); Py_INCREF(second); STACKADJ(2); SET_TOP(top); SET_SECOND(second); FAST_DISPATCH(); } TARGET(UNARY_POSITIVE) { PyObject *value = TOP(); PyObject *res = PyNumber_Positive(value); Py_DECREF(value); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(UNARY_NEGATIVE) { PyObject *value = TOP(); PyObject *res = PyNumber_Negative(value); Py_DECREF(value); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(UNARY_NOT) { PyObject *value = TOP(); int err = PyObject_IsTrue(value); Py_DECREF(value); if (err == 0) { Py_INCREF(Py_True); SET_TOP(Py_True); DISPATCH(); } else if (err > 0) { Py_INCREF(Py_False); SET_TOP(Py_False); err = 0; DISPATCH(); } STACKADJ(-1); goto error; } TARGET(UNARY_INVERT) { PyObject *value = TOP(); PyObject *res = PyNumber_Invert(value); Py_DECREF(value); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_POWER) { PyObject *exp = POP(); PyObject *base = TOP(); PyObject *res = PyNumber_Power(base, exp, Py_None); Py_DECREF(base); Py_DECREF(exp); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_MULTIPLY) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_Multiply(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_MATRIX_MULTIPLY) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_MatrixMultiply(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_TRUE_DIVIDE) { PyObject *divisor = POP(); PyObject *dividend = TOP(); PyObject *quotient = PyNumber_TrueDivide(dividend, divisor); Py_DECREF(dividend); Py_DECREF(divisor); SET_TOP(quotient); if (quotient == NULL) goto error; DISPATCH(); } TARGET(BINARY_FLOOR_DIVIDE) { PyObject *divisor = POP(); PyObject *dividend = TOP(); PyObject *quotient = PyNumber_FloorDivide(dividend, divisor); Py_DECREF(dividend); Py_DECREF(divisor); SET_TOP(quotient); if (quotient == NULL) goto error; DISPATCH(); } TARGET(BINARY_MODULO) { PyObject *divisor = POP(); PyObject *dividend = TOP(); PyObject *res; if (PyUnicode_CheckExact(dividend) && ( !PyUnicode_Check(divisor) || PyUnicode_CheckExact(divisor))) { // fast path; string formatting, but not if the RHS is a str subclass // (see issue28598) res = PyUnicode_Format(dividend, divisor); } else { res = PyNumber_Remainder(dividend, divisor); } Py_DECREF(divisor); Py_DECREF(dividend); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_ADD) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *sum; if (PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)) { sum = unicode_concatenate(left, right, f, next_instr); /* unicode_concatenate consumed the ref to left */ } else { sum = PyNumber_Add(left, right); Py_DECREF(left); } Py_DECREF(right); SET_TOP(sum); if (sum == NULL) goto error; DISPATCH(); } TARGET(BINARY_SUBTRACT) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *diff = PyNumber_Subtract(left, right); Py_DECREF(right); Py_DECREF(left); SET_TOP(diff); if (diff == NULL) goto error; DISPATCH(); } TARGET(BINARY_SUBSCR) { PyObject *sub = POP(); PyObject *container = TOP(); PyObject *res = PyObject_GetItem(container, sub); Py_DECREF(container); Py_DECREF(sub); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_LSHIFT) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_Lshift(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_RSHIFT) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_Rshift(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_AND) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_And(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_XOR) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_Xor(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(BINARY_OR) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_Or(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(LIST_APPEND) { PyObject *v = POP(); PyObject *list = PEEK((size_t)(unsigned)oparg); int err; err = PyList_Append(list, v); Py_DECREF(v); if (err != 0) goto error; PREDICT(JUMP_ABSOLUTE); DISPATCH(); } TARGET(SET_ADD) { PyObject *v = POP(); PyObject *set = stack_pointer[-oparg]; int err; err = PySet_Add(set, v); Py_DECREF(v); if (err != 0) goto error; PREDICT(JUMP_ABSOLUTE); DISPATCH(); } TARGET(INPLACE_POWER) { PyObject *exp = POP(); PyObject *base = TOP(); PyObject *res = PyNumber_InPlacePower(base, exp, Py_None); Py_DECREF(base); Py_DECREF(exp); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(INPLACE_MULTIPLY) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_InPlaceMultiply(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(INPLACE_MATRIX_MULTIPLY) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_InPlaceMatrixMultiply(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(INPLACE_TRUE_DIVIDE) { PyObject *divisor = POP(); PyObject *dividend = TOP(); PyObject *quotient = PyNumber_InPlaceTrueDivide(dividend, divisor); Py_DECREF(dividend); Py_DECREF(divisor); SET_TOP(quotient); if (quotient == NULL) goto error; DISPATCH(); } TARGET(INPLACE_FLOOR_DIVIDE) { PyObject *divisor = POP(); PyObject *dividend = TOP(); PyObject *quotient = PyNumber_InPlaceFloorDivide(dividend, divisor); Py_DECREF(dividend); Py_DECREF(divisor); SET_TOP(quotient); if (quotient == NULL) goto error; DISPATCH(); } TARGET(INPLACE_MODULO) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *mod = PyNumber_InPlaceRemainder(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(mod); if (mod == NULL) goto error; DISPATCH(); } TARGET(INPLACE_ADD) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *sum; if (PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)) { sum = unicode_concatenate(left, right, f, next_instr); /* unicode_concatenate consumed the ref to left */ } else { sum = PyNumber_InPlaceAdd(left, right); Py_DECREF(left); } Py_DECREF(right); SET_TOP(sum); if (sum == NULL) goto error; DISPATCH(); } TARGET(INPLACE_SUBTRACT) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *diff = PyNumber_InPlaceSubtract(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(diff); if (diff == NULL) goto error; DISPATCH(); } TARGET(INPLACE_LSHIFT) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_InPlaceLshift(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(INPLACE_RSHIFT) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_InPlaceRshift(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(INPLACE_AND) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_InPlaceAnd(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(INPLACE_XOR) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_InPlaceXor(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(INPLACE_OR) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = PyNumber_InPlaceOr(left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(STORE_SUBSCR) { PyObject *sub = TOP(); PyObject *container = SECOND(); PyObject *v = THIRD(); int err; STACKADJ(-3); /* container[sub] = v */ err = PyObject_SetItem(container, sub, v); Py_DECREF(v); Py_DECREF(container); Py_DECREF(sub); if (err != 0) goto error; DISPATCH(); } TARGET(STORE_ANNOTATION) { _Py_IDENTIFIER(__annotations__); PyObject *ann_dict; PyObject *ann = POP(); PyObject *name = GETITEM(names, ((unsigned)oparg)); int err; if (f->f_locals == NULL) { PyErr_Format(PyExc_SystemError, "no locals found when storing annotation"); Py_DECREF(ann); goto error; } /* first try to get __annotations__ from locals... */ if (PyDict_CheckExact(f->f_locals)) { ann_dict = _PyDict_GetItemId(f->f_locals, &PyId___annotations__); if (ann_dict == NULL) { PyErr_SetString(PyExc_NameError, "__annotations__ not found"); Py_DECREF(ann); goto error; } Py_INCREF(ann_dict); } else { PyObject *ann_str = _PyUnicode_FromId(&PyId___annotations__); if (ann_str == NULL) { Py_DECREF(ann); goto error; } ann_dict = PyObject_GetItem(f->f_locals, ann_str); if (ann_dict == NULL) { if (PyErr_ExceptionMatches(PyExc_KeyError)) { PyErr_SetString(PyExc_NameError, "__annotations__ not found"); } Py_DECREF(ann); goto error; } } /* ...if succeeded, __annotations__[name] = ann */ if (PyDict_CheckExact(ann_dict)) { err = PyDict_SetItem(ann_dict, name, ann); } else { err = PyObject_SetItem(ann_dict, name, ann); } Py_DECREF(ann_dict); Py_DECREF(ann); if (err != 0) { goto error; } DISPATCH(); } TARGET(DELETE_SUBSCR) { PyObject *sub = TOP(); PyObject *container = SECOND(); int err; STACKADJ(-2); /* del container[sub] */ err = PyObject_DelItem(container, sub); Py_DECREF(container); Py_DECREF(sub); if (err != 0) goto error; DISPATCH(); } TARGET(PRINT_EXPR) { _Py_IDENTIFIER(displayhook); PyObject *value = POP(); PyObject *hook = _PySys_GetObjectId(&PyId_displayhook); PyObject *res; if (hook == NULL) { PyErr_SetString(PyExc_RuntimeError, "lost sys.displayhook"); Py_DECREF(value); goto error; } res = PyObject_CallFunctionObjArgs(hook, value, NULL); Py_DECREF(value); if (res == NULL) goto error; Py_DECREF(res); DISPATCH(); } #ifdef CASE_TOO_BIG default: switch (opcode) { #endif TARGET(RAISE_VARARGS) { PyObject *cause = NULL, *exc = NULL; switch (oparg) { case 2: cause = POP(); /* cause */ /* fall through */ case 1: exc = POP(); /* exc */ /* fall through */ case 0: if (do_raise(exc, cause)) { why = WHY_EXCEPTION; goto fast_block_end; } break; default: PyErr_SetString(PyExc_SystemError, "bad RAISE_VARARGS oparg"); break; } goto error; } TARGET(RETURN_VALUE) { retval = POP(); why = WHY_RETURN; goto fast_block_end; } TARGET(GET_AITER) { unaryfunc getter = NULL; PyObject *iter = NULL; PyObject *awaitable = NULL; PyObject *obj = TOP(); PyTypeObject *type = Py_TYPE(obj); if (type->tp_as_async != NULL) { getter = type->tp_as_async->am_aiter; } if (getter != NULL) { iter = (*getter)(obj); Py_DECREF(obj); if (iter == NULL) { SET_TOP(NULL); goto error; } } else { SET_TOP(NULL); PyErr_Format( PyExc_TypeError, "'async for' requires an object with " "__aiter__ method, got %.100s", type->tp_name); Py_DECREF(obj); goto error; } if (Py_TYPE(iter)->tp_as_async != NULL && Py_TYPE(iter)->tp_as_async->am_anext != NULL) { /* Starting with CPython 3.5.2 __aiter__ should return asynchronous iterators directly (not awaitables that resolve to asynchronous iterators.) Therefore, we check if the object that was returned from __aiter__ has an __anext__ method. If it does, we wrap it in an awaitable that resolves to `iter`. See http://bugs.python.org/issue27243 for more details. */ PyObject *wrapper = _PyAIterWrapper_New(iter); Py_DECREF(iter); SET_TOP(wrapper); DISPATCH(); } awaitable = _PyCoro_GetAwaitableIter(iter); if (awaitable == NULL) { _PyErr_FormatFromCause( PyExc_TypeError, "'async for' received an invalid object " "from __aiter__: %.100s", Py_TYPE(iter)->tp_name); SET_TOP(NULL); Py_DECREF(iter); goto error; } else { Py_DECREF(iter); if (PyErr_WarnFormat( PyExc_DeprecationWarning, 1, "'%.100s' implements legacy __aiter__ protocol; " "__aiter__ should return an asynchronous " "iterator, not awaitable", type->tp_name)) { /* Warning was converted to an error. */ Py_DECREF(awaitable); SET_TOP(NULL); goto error; } } SET_TOP(awaitable); PREDICT(LOAD_CONST); DISPATCH(); } TARGET(GET_ANEXT) { unaryfunc getter = NULL; PyObject *next_iter = NULL; PyObject *awaitable = NULL; PyObject *aiter = TOP(); PyTypeObject *type = Py_TYPE(aiter); if (PyAsyncGen_CheckExact(aiter)) { awaitable = type->tp_as_async->am_anext(aiter); if (awaitable == NULL) { goto error; } } else { if (type->tp_as_async != NULL){ getter = type->tp_as_async->am_anext; } if (getter != NULL) { next_iter = (*getter)(aiter); if (next_iter == NULL) { goto error; } } else { PyErr_Format( PyExc_TypeError, "'async for' requires an iterator with " "__anext__ method, got %.100s", type->tp_name); goto error; } awaitable = _PyCoro_GetAwaitableIter(next_iter); if (awaitable == NULL) { _PyErr_FormatFromCause( PyExc_TypeError, "'async for' received an invalid object " "from __anext__: %.100s", Py_TYPE(next_iter)->tp_name); Py_DECREF(next_iter); goto error; } else { Py_DECREF(next_iter); } } PUSH(awaitable); PREDICT(LOAD_CONST); DISPATCH(); } PREDICTED(GET_AWAITABLE); TARGET(GET_AWAITABLE) { PyObject *iterable = TOP(); PyObject *iter = _PyCoro_GetAwaitableIter(iterable); if (iter == NULL) { format_awaitable_error(Py_TYPE(iterable), _Py_OPCODE(next_instr[-2])); } Py_DECREF(iterable); if (iter != NULL && PyCoro_CheckExact(iter)) { PyObject *yf = _PyGen_yf((PyGenObject*)iter); if (yf != NULL) { /* `iter` is a coroutine object that is being awaited, `yf` is a pointer to the current awaitable being awaited on. */ Py_DECREF(yf); Py_CLEAR(iter); PyErr_SetString( PyExc_RuntimeError, "coroutine is being awaited already"); /* The code below jumps to `error` if `iter` is NULL. */ } } SET_TOP(iter); /* Even if it's NULL */ if (iter == NULL) { goto error; } PREDICT(LOAD_CONST); DISPATCH(); } TARGET(YIELD_FROM) { PyObject *v = POP(); PyObject *receiver = TOP(); int err; if (PyGen_CheckExact(receiver) || PyCoro_CheckExact(receiver)) { retval = _PyGen_Send((PyGenObject *)receiver, v); } else { _Py_IDENTIFIER(send); if (v == Py_None) retval = Py_TYPE(receiver)->tp_iternext(receiver); else retval = _PyObject_CallMethodIdObjArgs(receiver, &PyId_send, v, NULL); } Py_DECREF(v); if (retval == NULL) { PyObject *val; if (tstate->c_tracefunc != NULL && PyErr_ExceptionMatches(PyExc_StopIteration)) call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f); err = _PyGen_FetchStopIterationValue(&val); if (err < 0) goto error; Py_DECREF(receiver); SET_TOP(val); DISPATCH(); } /* receiver remains on stack, retval is value to be yielded */ f->f_stacktop = stack_pointer; why = WHY_YIELD; /* and repeat... */ assert(f->f_lasti >= (int)sizeof(_Py_CODEUNIT)); f->f_lasti -= sizeof(_Py_CODEUNIT); goto fast_yield; } TARGET(YIELD_VALUE) { retval = POP(); if (co->co_flags & CO_ASYNC_GENERATOR) { PyObject *w = _PyAsyncGenValueWrapperNew(retval); Py_DECREF(retval); if (w == NULL) { retval = NULL; goto error; } retval = w; } f->f_stacktop = stack_pointer; why = WHY_YIELD; goto fast_yield; } TARGET(POP_EXCEPT) { PyTryBlock *b = PyFrame_BlockPop(f); if (b->b_type != EXCEPT_HANDLER) { PyErr_SetString(PyExc_SystemError, "popped block is not an except handler"); goto error; } UNWIND_EXCEPT_HANDLER(b); DISPATCH(); } PREDICTED(POP_BLOCK); TARGET(POP_BLOCK) { PyTryBlock *b = PyFrame_BlockPop(f); UNWIND_BLOCK(b); DISPATCH(); } PREDICTED(END_FINALLY); TARGET(END_FINALLY) { PyObject *status = POP(); if (PyLong_Check(status)) { why = (enum why_code) PyLong_AS_LONG(status); assert(why != WHY_YIELD && why != WHY_EXCEPTION); if (why == WHY_RETURN || why == WHY_CONTINUE) retval = POP(); if (why == WHY_SILENCED) { /* An exception was silenced by 'with', we must manually unwind the EXCEPT_HANDLER block which was created when the exception was caught, otherwise the stack will be in an inconsistent state. */ PyTryBlock *b = PyFrame_BlockPop(f); assert(b->b_type == EXCEPT_HANDLER); UNWIND_EXCEPT_HANDLER(b); why = WHY_NOT; Py_DECREF(status); DISPATCH(); } Py_DECREF(status); goto fast_block_end; } else if (PyExceptionClass_Check(status)) { PyObject *exc = POP(); PyObject *tb = POP(); PyErr_Restore(status, exc, tb); why = WHY_EXCEPTION; goto fast_block_end; } else if (status != Py_None) { PyErr_SetString(PyExc_SystemError, "'finally' pops bad exception"); Py_DECREF(status); goto error; } Py_DECREF(status); DISPATCH(); } TARGET(LOAD_BUILD_CLASS) { _Py_IDENTIFIER(__build_class__); PyObject *bc; if (PyDict_CheckExact(f->f_builtins)) { bc = _PyDict_GetItemId(f->f_builtins, &PyId___build_class__); if (bc == NULL) { PyErr_SetString(PyExc_NameError, "__build_class__ not found"); goto error; } Py_INCREF(bc); } else { PyObject *build_class_str = _PyUnicode_FromId(&PyId___build_class__); if (build_class_str == NULL) goto error; bc = PyObject_GetItem(f->f_builtins, build_class_str); if (bc == NULL) { if (PyErr_ExceptionMatches(PyExc_KeyError)) PyErr_SetString(PyExc_NameError, "__build_class__ not found"); goto error; } } PUSH(bc); DISPATCH(); } TARGET(STORE_NAME) { PyObject *name = GETITEM(names, ((unsigned)oparg)); PyObject *v = POP(); PyObject *ns = f->f_locals; int err; if (ns == NULL) { PyErr_Format(PyExc_SystemError, "no locals found when storing %R", name); Py_DECREF(v); goto error; } if (PyDict_CheckExact(ns)) err = PyDict_SetItem(ns, name, v); else err = PyObject_SetItem(ns, name, v); Py_DECREF(v); if (err != 0) goto error; DISPATCH(); } TARGET(DELETE_NAME) { PyObject *name = GETITEM(names, ((unsigned)oparg)); PyObject *ns = f->f_locals; int err; if (ns == NULL) { PyErr_Format(PyExc_SystemError, "no locals when deleting %R", name); goto error; } err = PyObject_DelItem(ns, name); if (err != 0) { format_exc_check_arg(PyExc_NameError, NAME_ERROR_MSG, name); goto error; } DISPATCH(); } PREDICTED(UNPACK_SEQUENCE); TARGET(UNPACK_SEQUENCE) { PyObject *seq = POP(), *item, **items; if (PyTuple_CheckExact(seq) && PyTuple_GET_SIZE(seq) == ((unsigned)oparg)) { items = ((PyTupleObject *)seq)->ob_item; while (oparg--) { item = items[oparg]; Py_INCREF(item); PUSH(item); } } else if (PyList_CheckExact(seq) && PyList_GET_SIZE(seq) == (unsigned)oparg) { items = ((PyListObject *)seq)->ob_item; while (oparg--) { item = items[oparg]; Py_INCREF(item); PUSH(item); } } else if (unpack_iterable(seq, oparg, -1, stack_pointer + oparg)) { STACKADJ(((unsigned)oparg)); } else { /* unpack_iterable() raised an exception */ Py_DECREF(seq); goto error; } Py_DECREF(seq); DISPATCH(); } TARGET(UNPACK_EX) { int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8); PyObject *seq = POP(); if (unpack_iterable(seq, oparg & 0xFF, oparg >> 8, stack_pointer + totalargs)) { stack_pointer += totalargs; } else { Py_DECREF(seq); goto error; } Py_DECREF(seq); DISPATCH(); } TARGET(STORE_ATTR) { PyObject *name = GETITEM(names, ((unsigned)oparg)); PyObject *owner = TOP(); PyObject *v = SECOND(); int err; STACKADJ(-2); err = PyObject_SetAttr(owner, name, v); Py_DECREF(v); Py_DECREF(owner); if (err != 0) goto error; DISPATCH(); } TARGET(DELETE_ATTR) { PyObject *name = GETITEM(names, ((unsigned)oparg)); PyObject *owner = POP(); int err; err = PyObject_SetAttr(owner, name, (PyObject *)NULL); Py_DECREF(owner); if (err != 0) goto error; DISPATCH(); } TARGET(STORE_GLOBAL) { PyObject *name = GETITEM(names, ((unsigned)oparg)); PyObject *v = POP(); int err; err = PyDict_SetItem(f->f_globals, name, v); Py_DECREF(v); if (err != 0) goto error; DISPATCH(); } TARGET(DELETE_GLOBAL) { PyObject *name = GETITEM(names, ((unsigned)oparg)); int err; err = PyDict_DelItem(f->f_globals, name); if (err != 0) { format_exc_check_arg( PyExc_NameError, NAME_ERROR_MSG, name); goto error; } DISPATCH(); } TARGET(LOAD_NAME) { PyObject *name = GETITEM(names, ((unsigned)oparg)); PyObject *locals = f->f_locals; PyObject *v; if (locals == NULL) { PyErr_Format(PyExc_SystemError, "no locals when loading %R", name); goto error; } if (PyDict_CheckExact(locals)) { v = PyDict_GetItem(locals, name); Py_XINCREF(v); } else { v = PyObject_GetItem(locals, name); if (v == NULL) { if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error; PyErr_Clear(); } } if (v == NULL) { v = PyDict_GetItem(f->f_globals, name); Py_XINCREF(v); if (v == NULL) { if (PyDict_CheckExact(f->f_builtins)) { v = PyDict_GetItem(f->f_builtins, name); if (v == NULL) { format_exc_check_arg( PyExc_NameError, NAME_ERROR_MSG, name); goto error; } Py_INCREF(v); } else { v = PyObject_GetItem(f->f_builtins, name); if (v == NULL) { if (PyErr_ExceptionMatches(PyExc_KeyError)) format_exc_check_arg( PyExc_NameError, NAME_ERROR_MSG, name); goto error; } } } } PUSH(v); DISPATCH(); } TARGET(LOAD_GLOBAL) { PyObject *name = GETITEM(names, ((unsigned)oparg)); PyObject *v; if (PyDict_CheckExact(f->f_globals) && PyDict_CheckExact(f->f_builtins)) { v = _PyDict_LoadGlobal((PyDictObject *)f->f_globals, (PyDictObject *)f->f_builtins, name); if (v == NULL) { if (!_PyErr_OCCURRED()) { /* _PyDict_LoadGlobal() returns NULL without raising * an exception if the key doesn't exist */ format_exc_check_arg(PyExc_NameError, NAME_ERROR_MSG, name); } goto error; } Py_INCREF(v); } else { /* Slow-path if globals or builtins is not a dict */ /* namespace 1: globals */ v = PyObject_GetItem(f->f_globals, name); if (v == NULL) { if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error; PyErr_Clear(); /* namespace 2: builtins */ v = PyObject_GetItem(f->f_builtins, name); if (v == NULL) { if (PyErr_ExceptionMatches(PyExc_KeyError)) format_exc_check_arg( PyExc_NameError, NAME_ERROR_MSG, name); goto error; } } } PUSH(v); DISPATCH(); } TARGET(DELETE_FAST) { PyObject *v = GETLOCAL(((unsigned)oparg)); if (v != NULL) { SETLOCAL(((unsigned)oparg), NULL); DISPATCH(); } format_exc_check_arg( PyExc_UnboundLocalError, UNBOUNDLOCAL_ERROR_MSG, PyTuple_GetItem(co->co_varnames, oparg) ); goto error; } TARGET(DELETE_DEREF) { PyObject *cell = freevars[oparg]; if (PyCell_GET(cell) != NULL) { PyCell_Set(cell, NULL); DISPATCH(); } format_exc_unbound(co, oparg); goto error; } TARGET(LOAD_CLOSURE) { PyObject *cell = freevars[oparg]; Py_INCREF(cell); PUSH(cell); DISPATCH(); } TARGET(LOAD_CLASSDEREF) { PyObject *name, *value, *locals = f->f_locals; Py_ssize_t idx; assert(locals); assert(oparg >= PyTuple_GET_SIZE(co->co_cellvars)); idx = oparg - PyTuple_GET_SIZE(co->co_cellvars); assert(idx >= 0 && idx < PyTuple_GET_SIZE(co->co_freevars)); name = PyTuple_GET_ITEM(co->co_freevars, idx); if (PyDict_CheckExact(locals)) { value = PyDict_GetItem(locals, name); Py_XINCREF(value); } else { value = PyObject_GetItem(locals, name); if (value == NULL) { if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error; PyErr_Clear(); } } if (!value) { PyObject *cell = freevars[oparg]; value = PyCell_GET(cell); if (value == NULL) { format_exc_unbound(co, oparg); goto error; } Py_INCREF(value); } PUSH(value); DISPATCH(); } TARGET(LOAD_DEREF) { PyObject *cell = freevars[oparg]; PyObject *value = PyCell_GET(cell); if (value == NULL) { format_exc_unbound(co, oparg); goto error; } Py_INCREF(value); PUSH(value); DISPATCH(); } TARGET(STORE_DEREF) { PyObject *v = POP(); PyObject *cell = freevars[oparg]; PyObject *oldobj = PyCell_GET(cell); PyCell_SET(cell, v); Py_XDECREF(oldobj); DISPATCH(); } TARGET(BUILD_STRING) { PyObject *str; PyObject *empty = PyUnicode_New(0, 0); if (empty == NULL) { goto error; } str = _PyUnicode_JoinArray(empty, stack_pointer - oparg, oparg); Py_DECREF(empty); if (str == NULL) goto error; while (--oparg >= 0) { PyObject *item = POP(); Py_DECREF(item); } PUSH(str); DISPATCH(); } TARGET(BUILD_TUPLE) { PyObject *tup = PyTuple_New(((unsigned)oparg)); if (tup == NULL) goto error; while (--oparg >= 0) { PyObject *item = POP(); PyTuple_SET_ITEM(tup, oparg, item); } PUSH(tup); DISPATCH(); } TARGET(BUILD_LIST) { PyObject *list = PyList_New(((unsigned)oparg)); if (list == NULL) goto error; while (--oparg >= 0) { PyObject *item = POP(); PyList_SET_ITEM(list, oparg, item); } PUSH(list); DISPATCH(); } TARGET(BUILD_TUPLE_UNPACK_WITH_CALL) TARGET(BUILD_TUPLE_UNPACK) TARGET(BUILD_LIST_UNPACK) { int convert_to_tuple = opcode != BUILD_LIST_UNPACK; Py_ssize_t i; PyObject *sum = PyList_New(0); PyObject *return_value; if (sum == NULL) goto error; for (i = oparg; i > 0; i--) { PyObject *none_val; none_val = _PyList_Extend((PyListObject *)sum, PEEK(i)); if (none_val == NULL) { if (opcode == BUILD_TUPLE_UNPACK_WITH_CALL && PyErr_ExceptionMatches(PyExc_TypeError)) { check_args_iterable(PEEK(1 + oparg), PEEK(i)); } Py_DECREF(sum); goto error; } Py_DECREF(none_val); } if (convert_to_tuple) { return_value = PyList_AsTuple(sum); Py_DECREF(sum); if (return_value == NULL) goto error; } else { return_value = sum; } while (oparg--) Py_DECREF(POP()); PUSH(return_value); DISPATCH(); } TARGET(BUILD_SET) { PyObject *set = PySet_New(NULL); int err = 0; int i; if (set == NULL) goto error; for (i = oparg; i > 0; i--) { PyObject *item = PEEK(i); if (err == 0) err = PySet_Add(set, item); Py_DECREF(item); } STACKADJ(-(size_t)(unsigned)oparg); if (err != 0) { Py_DECREF(set); goto error; } PUSH(set); DISPATCH(); } TARGET(BUILD_SET_UNPACK) { Py_ssize_t i; PyObject *sum = PySet_New(NULL); if (sum == NULL) goto error; for (i = oparg; i > 0; i--) { if (_PySet_Update(sum, PEEK(i)) < 0) { Py_DECREF(sum); goto error; } } while (oparg--) Py_DECREF(POP()); PUSH(sum); DISPATCH(); } TARGET(BUILD_MAP) { Py_ssize_t i; PyObject *map = _PyDict_NewPresized((size_t)(unsigned)oparg); if (map == NULL) goto error; for (i = oparg; i > 0; i--) { int err; PyObject *key = PEEK(2*i); PyObject *value = PEEK(2*i - 1); err = PyDict_SetItem(map, key, value); if (err != 0) { Py_DECREF(map); goto error; } } while (oparg--) { Py_DECREF(POP()); Py_DECREF(POP()); } PUSH(map); DISPATCH(); } TARGET(SETUP_ANNOTATIONS) { _Py_IDENTIFIER(__annotations__); int err; PyObject *ann_dict; if (f->f_locals == NULL) { PyErr_Format(PyExc_SystemError, "no locals found when setting up annotations"); goto error; } /* check if __annotations__ in locals()... */ if (PyDict_CheckExact(f->f_locals)) { ann_dict = _PyDict_GetItemId(f->f_locals, &PyId___annotations__); if (ann_dict == NULL) { /* ...if not, create a new one */ ann_dict = PyDict_New(); if (ann_dict == NULL) { goto error; } err = _PyDict_SetItemId(f->f_locals, &PyId___annotations__, ann_dict); Py_DECREF(ann_dict); if (err != 0) { goto error; } } } else { /* do the same if locals() is not a dict */ PyObject *ann_str = _PyUnicode_FromId(&PyId___annotations__); if (ann_str == NULL) { goto error; } ann_dict = PyObject_GetItem(f->f_locals, ann_str); if (ann_dict == NULL) { if (!PyErr_ExceptionMatches(PyExc_KeyError)) { goto error; } PyErr_Clear(); ann_dict = PyDict_New(); if (ann_dict == NULL) { goto error; } err = PyObject_SetItem(f->f_locals, ann_str, ann_dict); Py_DECREF(ann_dict); if (err != 0) { goto error; } } else { Py_DECREF(ann_dict); } } DISPATCH(); } TARGET(BUILD_CONST_KEY_MAP) { Py_ssize_t i; PyObject *map; PyObject *keys = TOP(); if (!PyTuple_CheckExact(keys) || PyTuple_GET_SIZE(keys) != (Py_ssize_t)(size_t)(unsigned)oparg) { PyErr_SetString(PyExc_SystemError, "bad BUILD_CONST_KEY_MAP keys argument"); goto error; } map = _PyDict_NewPresized((size_t)(unsigned)oparg); if (map == NULL) { goto error; } for (i = oparg; i > 0; i--) { int err; PyObject *key = PyTuple_GET_ITEM(keys, oparg - i); PyObject *value = PEEK(i + 1); err = PyDict_SetItem(map, key, value); if (err != 0) { Py_DECREF(map); goto error; } } Py_DECREF(POP()); while (oparg--) { Py_DECREF(POP()); } PUSH(map); DISPATCH(); } TARGET(BUILD_MAP_UNPACK) { Py_ssize_t i; PyObject *sum = PyDict_New(); if (sum == NULL) goto error; for (i = oparg; i > 0; i--) { PyObject *arg = PEEK(i); if (PyDict_Update(sum, arg) < 0) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not a mapping", arg->ob_type->tp_name); } Py_DECREF(sum); goto error; } } while (oparg--) Py_DECREF(POP()); PUSH(sum); DISPATCH(); } TARGET(BUILD_MAP_UNPACK_WITH_CALL) { Py_ssize_t i; PyObject *sum = PyDict_New(); if (sum == NULL) goto error; for (i = oparg; i > 0; i--) { PyObject *arg = PEEK(i); if (_PyDict_MergeEx(sum, arg, 2) < 0) { PyObject *func = PEEK(2 + (size_t)(unsigned)oparg); if (PyErr_ExceptionMatches(PyExc_AttributeError)) { format_kwargs_mapping_error(func, arg); } else if (PyErr_ExceptionMatches(PyExc_KeyError)) { PyObject *exc, *val, *tb; PyErr_Fetch(&exc, &val, &tb); if (val && PyTuple_Check(val) && PyTuple_GET_SIZE(val) == 1) { PyObject *key = PyTuple_GET_ITEM(val, 0); if (!PyUnicode_Check(key)) { PyErr_Format(PyExc_TypeError, "%.200s%.200s keywords must be strings", PyEval_GetFuncName(func), PyEval_GetFuncDesc(func)); } else { PyErr_Format(PyExc_TypeError, "%.200s%.200s got multiple " "values for keyword argument '%U'", PyEval_GetFuncName(func), PyEval_GetFuncDesc(func), key); } Py_XDECREF(exc); Py_XDECREF(val); Py_XDECREF(tb); } else { PyErr_Restore(exc, val, tb); } } Py_DECREF(sum); goto error; } } while (oparg--) Py_DECREF(POP()); PUSH(sum); DISPATCH(); } TARGET(MAP_ADD) { PyObject *key = TOP(); PyObject *value = SECOND(); PyObject *map; int err; STACKADJ(-2); map = stack_pointer[-oparg]; /* dict */ assert(PyDict_CheckExact(map)); err = PyDict_SetItem(map, key, value); /* map[key] = value */ Py_DECREF(value); Py_DECREF(key); if (err != 0) goto error; PREDICT(JUMP_ABSOLUTE); DISPATCH(); } TARGET(LOAD_ATTR) { PyObject *name = GETITEM(names, (unsigned)oparg); PyObject *owner = TOP(); PyObject *res = PyObject_GetAttr(owner, name); Py_DECREF(owner); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(COMPARE_OP) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = cmp_outcome(oparg, left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; PREDICT(POP_JUMP_IF_FALSE); PREDICT(POP_JUMP_IF_TRUE); DISPATCH(); } TARGET(IMPORT_NAME) { PyObject *name = GETITEM(names, (unsigned)oparg); PyObject *fromlist = POP(); PyObject *level = TOP(); PyObject *res; res = import_name(f, name, fromlist, level); Py_DECREF(level); Py_DECREF(fromlist); SET_TOP(res); if (res == NULL) goto error; DISPATCH(); } TARGET(IMPORT_STAR) { PyObject *from = POP(), *locals; int err; if (PyFrame_FastToLocalsWithError(f) < 0) { Py_DECREF(from); goto error; } locals = f->f_locals; if (locals == NULL) { PyErr_SetString(PyExc_SystemError, "no locals found during 'import *'"); Py_DECREF(from); goto error; } err = import_all_from(locals, from); PyFrame_LocalsToFast(f, 0); Py_DECREF(from); if (err != 0) goto error; DISPATCH(); } TARGET(IMPORT_FROM) { PyObject *name = GETITEM(names, (unsigned)oparg); PyObject *from = TOP(); PyObject *res; res = import_from(from, name); PUSH(res); if (res == NULL) goto error; DISPATCH(); } TARGET(JUMP_FORWARD) { JUMPBY((unsigned)oparg); FAST_DISPATCH(); } PREDICTED(POP_JUMP_IF_FALSE); TARGET(POP_JUMP_IF_FALSE) { PyObject *cond = POP(); int err; if (cond == Py_True) { Py_DECREF(cond); FAST_DISPATCH(); } if (cond == Py_False) { Py_DECREF(cond); JUMPTO((unsigned)oparg); FAST_DISPATCH(); } err = PyObject_IsTrue(cond); Py_DECREF(cond); if (err > 0) err = 0; else if (err == 0) JUMPTO((unsigned)oparg); else goto error; DISPATCH(); } PREDICTED(POP_JUMP_IF_TRUE); TARGET(POP_JUMP_IF_TRUE) { PyObject *cond = POP(); int err; if (cond == Py_False) { Py_DECREF(cond); FAST_DISPATCH(); } if (cond == Py_True) { Py_DECREF(cond); JUMPTO((unsigned)oparg); FAST_DISPATCH(); } err = PyObject_IsTrue(cond); Py_DECREF(cond); if (err > 0) { err = 0; JUMPTO((unsigned)oparg); } else if (err == 0) ; else goto error; DISPATCH(); } TARGET(JUMP_IF_FALSE_OR_POP) { PyObject *cond = TOP(); int err; if (cond == Py_True) { STACKADJ(-1); Py_DECREF(cond); FAST_DISPATCH(); } if (cond == Py_False) { JUMPTO((unsigned)oparg); FAST_DISPATCH(); } err = PyObject_IsTrue(cond); if (err > 0) { STACKADJ(-1); Py_DECREF(cond); err = 0; } else if (err == 0) JUMPTO((unsigned)oparg); else goto error; DISPATCH(); } TARGET(JUMP_IF_TRUE_OR_POP) { PyObject *cond = TOP(); int err; if (cond == Py_False) { STACKADJ(-1); Py_DECREF(cond); FAST_DISPATCH(); } if (cond == Py_True) { JUMPTO((unsigned)oparg); FAST_DISPATCH(); } err = PyObject_IsTrue(cond); if (err > 0) { err = 0; JUMPTO((unsigned)oparg); } else if (err == 0) { STACKADJ(-1); Py_DECREF(cond); } else goto error; DISPATCH(); } PREDICTED(JUMP_ABSOLUTE); TARGET(JUMP_ABSOLUTE) { JUMPTO((unsigned)oparg); #if FAST_LOOPS /* Enabling this path speeds-up all while and for-loops by bypassing the per-loop checks for signals. By default, this should be turned-off because it prevents detection of a control-break in tight loops like "while 1: pass". Compile with this option turned-on when you need the speed-up and do not need break checking inside tight loops (ones that contain only instructions ending with FAST_DISPATCH). */ FAST_DISPATCH(); #else DISPATCH(); #endif } TARGET(GET_ITER) { /* before: [obj]; after [getiter(obj)] */ PyObject *iterable = TOP(); PyObject *iter = PyObject_GetIter(iterable); Py_DECREF(iterable); SET_TOP(iter); if (iter == NULL) goto error; PREDICT(FOR_ITER); PREDICT(CALL_FUNCTION); DISPATCH(); } TARGET(GET_YIELD_FROM_ITER) { /* before: [obj]; after [getiter(obj)] */ PyObject *iterable = TOP(); PyObject *iter; if (PyCoro_CheckExact(iterable)) { /* `iterable` is a coroutine */ if (!(co->co_flags & (CO_COROUTINE | CO_ITERABLE_COROUTINE))) { /* and it is used in a 'yield from' expression of a regular generator. */ Py_DECREF(iterable); SET_TOP(NULL); PyErr_SetString(PyExc_TypeError, "cannot 'yield from' a coroutine object " "in a non-coroutine generator"); goto error; } } else if (!PyGen_CheckExact(iterable)) { /* `iterable` is not a generator. */ iter = PyObject_GetIter(iterable); Py_DECREF(iterable); SET_TOP(iter); if (iter == NULL) goto error; } PREDICT(LOAD_CONST); DISPATCH(); } PREDICTED(FOR_ITER); TARGET(FOR_ITER) { /* before: [iter]; after: [iter, iter()] *or* [] */ PyObject *iter = TOP(); PyObject *next = (*iter->ob_type->tp_iternext)(iter); if (next != NULL) { PUSH(next); PREDICT(STORE_FAST); PREDICT(UNPACK_SEQUENCE); DISPATCH(); } if (PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_StopIteration)) goto error; else if (tstate->c_tracefunc != NULL) call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f); PyErr_Clear(); } /* iterator ended normally */ STACKADJ(-1); Py_DECREF(iter); JUMPBY((unsigned)oparg); PREDICT(POP_BLOCK); DISPATCH(); } TARGET(BREAK_LOOP) { why = WHY_BREAK; goto fast_block_end; } TARGET(CONTINUE_LOOP) { retval = PyLong_FromLong((unsigned)oparg); if (retval == NULL) goto error; why = WHY_CONTINUE; goto fast_block_end; } TARGET(SETUP_LOOP) TARGET(SETUP_EXCEPT) TARGET(SETUP_FINALLY) { /* NOTE: If you add any new block-setup opcodes that are not try/except/finally handlers, you may need to update the PyGen_NeedsFinalizing() function. */ PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL()); DISPATCH(); } TARGET(BEFORE_ASYNC_WITH) { _Py_IDENTIFIER(__aexit__); _Py_IDENTIFIER(__aenter__); PyObject *mgr = TOP(); PyObject *exit = special_lookup(mgr, &PyId___aexit__), *enter; PyObject *res; if (exit == NULL) goto error; SET_TOP(exit); enter = special_lookup(mgr, &PyId___aenter__); Py_DECREF(mgr); if (enter == NULL) goto error; res = PyObject_CallFunctionObjArgs(enter, NULL); Py_DECREF(enter); if (res == NULL) goto error; PUSH(res); PREDICT(GET_AWAITABLE); DISPATCH(); } TARGET(SETUP_ASYNC_WITH) { PyObject *res = POP(); /* Setup the finally block before pushing the result of __aenter__ on the stack. */ PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg, STACK_LEVEL()); PUSH(res); DISPATCH(); } TARGET(SETUP_WITH) { _Py_IDENTIFIER(__exit__); _Py_IDENTIFIER(__enter__); PyObject *mgr = TOP(); PyObject *enter = special_lookup(mgr, &PyId___enter__), *exit; PyObject *res; if (enter == NULL) goto error; exit = special_lookup(mgr, &PyId___exit__); if (exit == NULL) { Py_DECREF(enter); goto error; } SET_TOP(exit); Py_DECREF(mgr); res = PyObject_CallFunctionObjArgs(enter, NULL); Py_DECREF(enter); if (res == NULL) goto error; /* Setup the finally block before pushing the result of __enter__ on the stack. */ PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg, STACK_LEVEL()); PUSH(res); DISPATCH(); } TARGET(WITH_CLEANUP_START) { /* At the top of the stack are 1-6 values indicating how/why we entered the finally clause: - TOP = None - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval - TOP = WHY_*; no retval below it - (TOP, SECOND, THIRD) = exc_info() (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER Below them is EXIT, the context.__exit__ bound method. In the last case, we must call EXIT(TOP, SECOND, THIRD) otherwise we must call EXIT(None, None, None) In the first three cases, we remove EXIT from the stack, leaving the rest in the same order. In the fourth case, we shift the bottom 3 values of the stack down, and replace the empty spot with NULL. In addition, if the stack represents an exception, *and* the function call returns a 'true' value, we push WHY_SILENCED onto the stack. END_FINALLY will then not re-raise the exception. (But non-local gotos should still be resumed.) */ PyObject *exit_func; PyObject *exc = TOP(), *val = Py_None, *tb = Py_None, *res; if (exc == Py_None) { (void)POP(); exit_func = TOP(); SET_TOP(exc); } else if (PyLong_Check(exc)) { STACKADJ(-1); switch (PyLong_AsLong(exc)) { case WHY_RETURN: case WHY_CONTINUE: /* Retval in TOP. */ exit_func = SECOND(); SET_SECOND(TOP()); SET_TOP(exc); break; default: exit_func = TOP(); SET_TOP(exc); break; } exc = Py_None; } else { PyObject *tp2, *exc2, *tb2; PyTryBlock *block; val = SECOND(); tb = THIRD(); tp2 = FOURTH(); exc2 = PEEK(5); tb2 = PEEK(6); exit_func = PEEK(7); SET_VALUE(7, tb2); SET_VALUE(6, exc2); SET_VALUE(5, tp2); /* UNWIND_EXCEPT_HANDLER will pop this off. */ SET_FOURTH(NULL); /* We just shifted the stack down, so we have to tell the except handler block that the values are lower than it expects. */ block = &f->f_blockstack[f->f_iblock - 1]; assert(block->b_type == EXCEPT_HANDLER); block->b_level--; } /* XXX Not the fastest way to call it... */ res = PyObject_CallFunctionObjArgs(exit_func, exc, val, tb, NULL); Py_DECREF(exit_func); if (res == NULL) goto error; Py_INCREF(exc); /* Duplicating the exception on the stack */ PUSH(exc); PUSH(res); PREDICT(WITH_CLEANUP_FINISH); DISPATCH(); } PREDICTED(WITH_CLEANUP_FINISH); TARGET(WITH_CLEANUP_FINISH) { PyObject *res = POP(); PyObject *exc = POP(); int err; if (exc != Py_None) err = PyObject_IsTrue(res); else err = 0; Py_DECREF(res); Py_DECREF(exc); if (err < 0) goto error; else if (err > 0) { err = 0; /* There was an exception and a True return */ PUSH(PyLong_FromLong((long) WHY_SILENCED)); } PREDICT(END_FINALLY); DISPATCH(); } TARGET(LOAD_METHOD) { /* Designed to work in tamdem with CALL_METHOD. */ PyObject *name = GETITEM(names, oparg); PyObject *obj = TOP(); PyObject *meth = NULL; int meth_found = _PyObject_GetMethod(obj, name, &meth); if (meth == NULL) { /* Most likely attribute wasn't found. */ goto error; } if (meth_found) { /* We can bypass temporary bound method object. meth is unbound method and obj is self. meth | self | arg1 | ... | argN */ SET_TOP(meth); PUSH(obj); // self } else { /* meth is not an unbound method (but a regular attr, or something was returned by a descriptor protocol). Set the second element of the stack to NULL, to signal CALL_METHOD that it's not a method call. NULL | meth | arg1 | ... | argN */ SET_TOP(NULL); Py_DECREF(obj); PUSH(meth); } DISPATCH(); } TARGET(CALL_METHOD) { /* Designed to work in tamdem with LOAD_METHOD. */ PyObject **sp, *res, *meth; sp = stack_pointer; meth = PEEK(oparg + 2); if (meth == NULL) { /* `meth` is NULL when LOAD_METHOD thinks that it's not a method call. Stack layout: ... | NULL | callable | arg1 | ... | argN ^- TOP() ^- (-oparg) ^- (-oparg-1) ^- (-oparg-2) `callable` will be POPed by call_function. NULL will will be POPed manually later. */ res = call_function(&sp, oparg, NULL); stack_pointer = sp; (void)POP(); /* POP the NULL. */ } else { /* This is a method call. Stack layout: ... | method | self | arg1 | ... | argN ^- TOP() ^- (-oparg) ^- (-oparg-1) ^- (-oparg-2) `self` and `method` will be POPed by call_function. We'll be passing `oparg + 1` to call_function, to make it accept the `self` as a first argument. */ res = call_function(&sp, oparg + 1, NULL); stack_pointer = sp; } PUSH(res); if (res == NULL) goto error; DISPATCH(); } PREDICTED(CALL_FUNCTION); TARGET(CALL_FUNCTION) { PyObject **sp, *res; PCALL(PCALL_ALL); sp = stack_pointer; res = call_function(&sp, oparg, NULL); stack_pointer = sp; PUSH(res); if (res == NULL) { goto error; } DISPATCH(); } TARGET(CALL_FUNCTION_KW) { PyObject **sp, *res, *names; names = POP(); assert(PyTuple_CheckExact(names) && PyTuple_GET_SIZE(names) <= oparg); PCALL(PCALL_ALL); sp = stack_pointer; res = call_function(&sp, oparg, names); stack_pointer = sp; PUSH(res); Py_DECREF(names); if (res == NULL) { goto error; } DISPATCH(); } TARGET(CALL_FUNCTION_EX) { PyObject *func, *callargs, *kwargs = NULL, *result; PCALL(PCALL_ALL); if (oparg & 0x01) { kwargs = POP(); if (!PyDict_CheckExact(kwargs)) { PyObject *d = PyDict_New(); if (d == NULL) goto error; if (PyDict_Update(d, kwargs) != 0) { Py_DECREF(d); /* PyDict_Update raises attribute * error (percolated from an attempt * to get 'keys' attribute) instead of * a type error if its second argument * is not a mapping. */ if (PyErr_ExceptionMatches(PyExc_AttributeError)) { format_kwargs_mapping_error(SECOND(), kwargs); } Py_DECREF(kwargs); goto error; } Py_DECREF(kwargs); kwargs = d; } assert(PyDict_CheckExact(kwargs)); } callargs = POP(); func = TOP(); if (!PyTuple_CheckExact(callargs)) { if (check_args_iterable(func, callargs) < 0) { Py_DECREF(callargs); goto error; } Py_SETREF(callargs, PySequence_Tuple(callargs)); if (callargs == NULL) { goto error; } } assert(PyTuple_CheckExact(callargs)); result = do_call_core(func, callargs, kwargs); Py_DECREF(func); Py_DECREF(callargs); Py_XDECREF(kwargs); SET_TOP(result); if (result == NULL) { goto error; } DISPATCH(); } TARGET(MAKE_FUNCTION) { PyObject *qualname = POP(); PyObject *codeobj = POP(); PyFunctionObject *func = (PyFunctionObject *) PyFunction_NewWithQualName(codeobj, f->f_globals, qualname); Py_DECREF(codeobj); Py_DECREF(qualname); if (func == NULL) { goto error; } if (oparg & 0x08) { assert(PyTuple_CheckExact(TOP())); func ->func_closure = POP(); } if (oparg & 0x04) { assert(PyDict_CheckExact(TOP())); func->func_annotations = POP(); } if (oparg & 0x02) { assert(PyDict_CheckExact(TOP())); func->func_kwdefaults = POP(); } if (oparg & 0x01) { assert(PyTuple_CheckExact(TOP())); func->func_defaults = POP(); } PUSH((PyObject *)func); DISPATCH(); } TARGET(BUILD_SLICE) { PyObject *start, *stop, *step, *slice; if (oparg == 3) step = POP(); else step = NULL; stop = POP(); start = TOP(); slice = PySlice_New(start, stop, step); Py_DECREF(start); Py_DECREF(stop); Py_XDECREF(step); SET_TOP(slice); if (slice == NULL) goto error; DISPATCH(); } TARGET(FORMAT_VALUE) { /* Handles f-string value formatting. */ PyObject *result; PyObject *fmt_spec; PyObject *value; PyObject *(*conv_fn)(PyObject *); int which_conversion = oparg & FVC_MASK; int have_fmt_spec = (oparg & FVS_MASK) == FVS_HAVE_SPEC; fmt_spec = have_fmt_spec ? POP() : NULL; value = POP(); /* See if any conversion is specified. */ switch (which_conversion) { case FVC_STR: conv_fn = PyObject_Str; break; case FVC_REPR: conv_fn = PyObject_Repr; break; case FVC_ASCII: conv_fn = PyObject_ASCII; break; /* Must be 0 (meaning no conversion), since only four values are allowed by (oparg & FVC_MASK). */ default: conv_fn = NULL; break; } /* If there's a conversion function, call it and replace value with that result. Otherwise, just use value, without conversion. */ if (conv_fn != NULL) { result = conv_fn(value); Py_DECREF(value); if (result == NULL) { Py_XDECREF(fmt_spec); goto error; } value = result; } /* If value is a unicode object, and there's no fmt_spec, then we know the result of format(value) is value itself. In that case, skip calling format(). I plan to move this optimization in to PyObject_Format() itself. */ if (PyUnicode_CheckExact(value) && fmt_spec == NULL) { /* Do nothing, just transfer ownership to result. */ result = value; } else { /* Actually call format(). */ result = PyObject_Format(value, fmt_spec); Py_DECREF(value); Py_XDECREF(fmt_spec); if (result == NULL) { goto error; } } PUSH(result); DISPATCH(); } TARGET(EXTENDED_ARG) { int oldoparg = oparg; NEXTOPARG(); oparg |= oldoparg << 8; goto dispatch_opcode; } #if USE_COMPUTED_GOTOS _unknown_opcode: COLD_LABEL; #endif default: fprintf(stderr, "XXX lineno: %d, opcode: %d\n", PyFrame_GetLineNumber(f), opcode); PyErr_SetString(PyExc_SystemError, "unknown opcode"); goto error; #ifdef CASE_TOO_BIG } #endif } /* switch */ /* This should never be reached. Every opcode should end with DISPATCH() or goto error. */ unreachable; error: COLD_LABEL; assert(why == WHY_NOT); why = WHY_EXCEPTION; /* Double-check exception status. */ if (!PyErr_Occurred()) PyErr_SetString(PyExc_SystemError, "error return without exception set"); /* Log traceback info. */ PyTraceBack_Here(f); if (tstate->c_tracefunc != NULL) call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f); fast_block_end: assert(why != WHY_NOT); /* Unwind stacks if a (pseudo) exception occurred */ while (UNLIKELY(why != WHY_NOT && f->f_iblock > 0)) { /* Peek at the current block. */ PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1]; assert(why != WHY_YIELD); if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { why = WHY_NOT; JUMPTO(PyLong_AS_LONG(retval)); Py_DECREF(retval); break; } /* Now we have to pop the block. */ f->f_iblock--; if (b->b_type == EXCEPT_HANDLER) { UNWIND_EXCEPT_HANDLER(b); continue; } UNWIND_BLOCK(b); if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { why = WHY_NOT; JUMPTO(b->b_handler); break; } if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT || b->b_type == SETUP_FINALLY)) { PyObject *exc, *val, *tb; int handler = b->b_handler; /* Beware, this invalidates all b->b_* fields */ PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL()); PUSH(tstate->exc_traceback); PUSH(tstate->exc_value); if (tstate->exc_type != NULL) { PUSH(tstate->exc_type); } else { Py_INCREF(Py_None); PUSH(Py_None); } PyErr_Fetch(&exc, &val, &tb); /* Make the raw exception data available to the handler, so a program can emulate the Python main loop. */ PyErr_NormalizeException( &exc, &val, &tb); if (tb != NULL) PyException_SetTraceback(val, tb); else PyException_SetTraceback(val, Py_None); Py_INCREF(exc); tstate->exc_type = exc; Py_INCREF(val); tstate->exc_value = val; tstate->exc_traceback = tb; if (tb == NULL) tb = Py_None; Py_INCREF(tb); PUSH(tb); PUSH(val); PUSH(exc); why = WHY_NOT; JUMPTO(handler); break; } if (b->b_type == SETUP_FINALLY) { if (why & (WHY_RETURN | WHY_CONTINUE)) PUSH(retval); PUSH(PyLong_FromLong((long)why)); why = WHY_NOT; JUMPTO(b->b_handler); break; } } /* unwind stack */ /* End the loop if we still have an error (or return) */ if (why != WHY_NOT) break; assert(!PyErr_Occurred()); } /* main loop */ assert(why != WHY_YIELD); /* Pop remaining stack entries. */ while (!EMPTY()) { PyObject *o = POP(); Py_XDECREF(o); } if (why != WHY_RETURN) retval = NULL; assert((retval != NULL) ^ (PyErr_Occurred() != NULL)); fast_yield: if (co->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) { /* The purpose of this block is to put aside the generator's exception state and restore that of the calling frame. If the current exception state is from the caller, we clear the exception values on the generator frame, so they are not swapped back in latter. The origin of the current exception state is determined by checking for except handler blocks, which we must be in iff a new exception state came into existence in this frame. (An uncaught exception would have why == WHY_EXCEPTION, and we wouldn't be here). */ int i; for (i = 0; i < f->f_iblock; i++) { if (f->f_blockstack[i].b_type == EXCEPT_HANDLER) { break; } } if (i == f->f_iblock) /* We did not create this exception. */ restore_and_clear_exc_state(tstate, f); else swap_exc_state(tstate, f); } if (UNLIKELY(tstate->use_tracing)) { if (tstate->c_tracefunc) { if (why == WHY_RETURN || why == WHY_YIELD) { if (call_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, PyTrace_RETURN, retval)) { Py_CLEAR(retval); why = WHY_EXCEPTION; } } else if (why == WHY_EXCEPTION) { call_trace_protected(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, PyTrace_RETURN, NULL); } } if (tstate->c_profilefunc) { if (why == WHY_EXCEPTION) call_trace_protected(tstate->c_profilefunc, tstate->c_profileobj, tstate, f, PyTrace_RETURN, NULL); else if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, tstate, f, PyTrace_RETURN, retval)) { Py_CLEAR(retval); /* why = WHY_EXCEPTION; */ } } } /* pop frame */ exit_eval_frame: if (PyDTrace_FUNCTION_RETURN_ENABLED()) dtrace_function_return(f); Py_LeaveRecursiveCall(); f->f_executing = 0; tstate->frame = f->f_back; return _Py_CheckFunctionResult(NULL, retval, "PyEval_EvalFrameEx"); } static void format_missing(const char *kind, PyCodeObject *co, PyObject *names) { int err; Py_ssize_t len = PyList_GET_SIZE(names); PyObject *name_str, *comma, *tail, *tmp; assert(PyList_CheckExact(names)); assert(len >= 1); /* Deal with the joys of natural language. */ switch (len) { case 1: name_str = PyList_GET_ITEM(names, 0); Py_INCREF(name_str); break; case 2: name_str = PyUnicode_FromFormat("%U and %U", PyList_GET_ITEM(names, len - 2), PyList_GET_ITEM(names, len - 1)); break; default: tail = PyUnicode_FromFormat(", %U, and %U", PyList_GET_ITEM(names, len - 2), PyList_GET_ITEM(names, len - 1)); if (tail == NULL) return; /* Chop off the last two objects in the list. This shouldn't actually fail, but we can't be too careful. */ err = PyList_SetSlice(names, len - 2, len, NULL); if (err == -1) { Py_DECREF(tail); return; } /* Stitch everything up into a nice comma-separated list. */ comma = PyUnicode_FromString(", "); if (comma == NULL) { Py_DECREF(tail); return; } tmp = PyUnicode_Join(comma, names); Py_DECREF(comma); if (tmp == NULL) { Py_DECREF(tail); return; } name_str = PyUnicode_Concat(tmp, tail); Py_DECREF(tmp); Py_DECREF(tail); break; } if (name_str == NULL) return; PyErr_Format(PyExc_TypeError, "%U() missing %i required %s argument%s: %U", co->co_name, len, kind, len == 1 ? "" : "s", name_str); Py_DECREF(name_str); } static void missing_arguments(PyCodeObject *co, Py_ssize_t missing, Py_ssize_t defcount, PyFrameObject *f) { Py_ssize_t i, j = 0; Py_ssize_t start, end; int positional = (defcount != -1); const char *kind = positional ? "positional" : "keyword-only"; PyObject *missing_names; /* Compute the names of the arguments that are missing. */ missing_names = PyList_New(missing); if (missing_names == NULL) return; if (positional) { start = 0; end = co->co_argcount - defcount; } else { start = co->co_argcount; end = start + co->co_kwonlyargcount; } for (i = start; i < end; i++) { if (GETLOCAL(i) == NULL) { PyObject *raw = PyTuple_GET_ITEM(co->co_varnames, i); PyObject *name = PyObject_Repr(raw); if (name == NULL) { Py_DECREF(missing_names); return; } PyList_SET_ITEM(missing_names, j++, name); } } assert(j == missing); format_missing(kind, co, missing_names); Py_DECREF(missing_names); } static void too_many_positional(PyCodeObject *co, Py_ssize_t given, Py_ssize_t defcount, PyFrameObject *f) { int plural; Py_ssize_t kwonly_given = 0; Py_ssize_t i; PyObject *sig, *kwonly_sig; Py_ssize_t co_argcount = co->co_argcount; assert((co->co_flags & CO_VARARGS) == 0); /* Count missing keyword-only args. */ for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) { if (GETLOCAL(i) != NULL) { kwonly_given++; } } if (defcount) { Py_ssize_t atleast = co_argcount - defcount; plural = 1; sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount); } else { plural = (co_argcount != 1); sig = PyUnicode_FromFormat("%zd", co_argcount); } if (sig == NULL) return; if (kwonly_given) { const char *format = " positional argument%s (and %zd keyword-only argument%s)"; kwonly_sig = PyUnicode_FromFormat(format, given != 1 ? "s" : "", kwonly_given, kwonly_given != 1 ? "s" : ""); if (kwonly_sig == NULL) { Py_DECREF(sig); return; } } else { /* This will not fail. */ kwonly_sig = PyUnicode_FromString(""); assert(kwonly_sig != NULL); } PyErr_Format(PyExc_TypeError, "%U() takes %U positional argument%s but %zd%U %s given", co->co_name, sig, plural ? "s" : "", given, kwonly_sig, given == 1 && !kwonly_given ? "was" : "were"); Py_DECREF(sig); Py_DECREF(kwonly_sig); } /* This is gonna seem *real weird*, but if you put some other code between PyEval_EvalFrame() and _PyEval_EvalFrameDefault() you will need to adjust the test in the if statements in Misc/gdbinit (pystack and pystackv). */ PyObject * _PyEval_EvalCodeWithName(PyObject *_co, PyObject *globals, PyObject *locals, PyObject **args, Py_ssize_t argcount, PyObject **kwnames, PyObject **kwargs, Py_ssize_t kwcount, int kwstep, PyObject **defs, Py_ssize_t defcount, PyObject *kwdefs, PyObject *closure, PyObject *name, PyObject *qualname) { PyCodeObject* co = (PyCodeObject*)_co; PyFrameObject *f; PyObject *retval = NULL; PyObject **freevars; PyThreadState *tstate; PyObject *x, *u; const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount; Py_ssize_t i, n; PyObject *kwdict; if (globals == NULL) { PyErr_SetString(PyExc_SystemError, "PyEval_EvalCodeEx: NULL globals"); return NULL; } /* Create the frame */ tstate = PyThreadState_GET(); assert(tstate != NULL); f = _PyFrame_New_NoTrack(tstate, co, globals, locals); if (f == NULL) { return NULL; } freevars = f->f_localsplus + co->co_nlocals; /* Create a dictionary for keyword parameters (**kwags) */ if (co->co_flags & CO_VARKEYWORDS) { kwdict = PyDict_New(); if (kwdict == NULL) goto fail; i = total_args; if (co->co_flags & CO_VARARGS) { i++; } SETLOCAL(i, kwdict); } else { kwdict = NULL; } /* Copy positional arguments into local variables */ if (argcount > co->co_argcount) { n = co->co_argcount; } else { n = argcount; } for (i = 0; i < n; i++) { x = args[i]; Py_INCREF(x); SETLOCAL(i, x); } /* Pack other positional arguments into the *args argument */ if (co->co_flags & CO_VARARGS) { u = PyTuple_New(argcount - n); if (u == NULL) { goto fail; } SETLOCAL(total_args, u); for (i = n; i < argcount; i++) { x = args[i]; Py_INCREF(x); PyTuple_SET_ITEM(u, i-n, x); } } /* Handle keyword arguments passed as two strided arrays */ kwcount *= kwstep; for (i = 0; i < kwcount; i += kwstep) { PyObject **co_varnames; PyObject *keyword = kwnames[i]; PyObject *value = kwargs[i]; Py_ssize_t j; if (keyword == NULL || !PyUnicode_Check(keyword)) { PyErr_Format(PyExc_TypeError, "%U() keywords must be strings", co->co_name); goto fail; } /* Speed hack: do raw pointer compares. As names are normally interned this should almost always hit. */ co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item; for (j = 0; j < total_args; j++) { PyObject *name = co_varnames[j]; if (name == keyword) { goto kw_found; } } /* Slow fallback, just in case */ for (j = 0; j < total_args; j++) { PyObject *name = co_varnames[j]; int cmp = PyObject_RichCompareBool( keyword, name, Py_EQ); if (cmp > 0) { goto kw_found; } else if (cmp < 0) { goto fail; } } if (j >= total_args && kwdict == NULL) { PyErr_Format(PyExc_TypeError, "%U() got an unexpected keyword argument '%S'", co->co_name, keyword); goto fail; } if (PyDict_SetItem(kwdict, keyword, value) == -1) { goto fail; } continue; kw_found: if (GETLOCAL(j) != NULL) { PyErr_Format(PyExc_TypeError, "%U() got multiple values for argument '%S'", co->co_name, keyword); goto fail; } Py_INCREF(value); SETLOCAL(j, value); } /* Check the number of positional arguments */ if (argcount > co->co_argcount && !(co->co_flags & CO_VARARGS)) { too_many_positional(co, argcount, defcount, f); goto fail; } /* Add missing positional arguments (copy default values from defs) */ if (argcount < co->co_argcount) { Py_ssize_t m = co->co_argcount - defcount; Py_ssize_t missing = 0; for (i = argcount; i < m; i++) { if (GETLOCAL(i) == NULL) { missing++; } } if (missing) { missing_arguments(co, missing, defcount, f); goto fail; } if (n > m) i = n - m; else i = 0; for (; i < defcount; i++) { if (GETLOCAL(m+i) == NULL) { PyObject *def = defs[i]; Py_INCREF(def); SETLOCAL(m+i, def); } } } /* Add missing keyword arguments (copy default values from kwdefs) */ if (co->co_kwonlyargcount > 0) { Py_ssize_t missing = 0; for (i = co->co_argcount; i < total_args; i++) { PyObject *name; if (GETLOCAL(i) != NULL) continue; name = PyTuple_GET_ITEM(co->co_varnames, i); if (kwdefs != NULL) { PyObject *def = PyDict_GetItem(kwdefs, name); if (def) { Py_INCREF(def); SETLOCAL(i, def); continue; } } missing++; } if (missing) { missing_arguments(co, missing, -1, f); goto fail; } } /* Allocate and initialize storage for cell vars, and copy free vars into frame. */ for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { PyObject *c; int arg; /* Possibly account for the cell variable being an argument. */ if (co->co_cell2arg != NULL && (arg = co->co_cell2arg[i]) != CO_CELL_NOT_AN_ARG) { c = PyCell_New(GETLOCAL(arg)); /* Clear the local copy. */ SETLOCAL(arg, NULL); } else { c = PyCell_New(NULL); } if (c == NULL) goto fail; SETLOCAL(co->co_nlocals + i, c); } /* Copy closure variables to free variables */ for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { PyObject *o = PyTuple_GET_ITEM(closure, i); Py_INCREF(o); freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; } /* Handle generator/coroutine/asynchronous generator */ if (co->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) { PyObject *gen; PyObject *coro_wrapper = tstate->coroutine_wrapper; int is_coro = co->co_flags & CO_COROUTINE; if (is_coro && tstate->in_coroutine_wrapper) { assert(coro_wrapper != NULL); PyErr_Format(PyExc_RuntimeError, "coroutine wrapper %.200R attempted " "to recursively wrap %.200R", coro_wrapper, co); goto fail; } /* Don't need to keep the reference to f_back, it will be set * when the generator is resumed. */ Py_CLEAR(f->f_back); PCALL(PCALL_GENERATOR); /* Create a new generator that owns the ready to run frame * and return that as the value. */ if (is_coro) { gen = PyCoro_New(f, name, qualname); } else if (co->co_flags & CO_ASYNC_GENERATOR) { gen = PyAsyncGen_New(f, name, qualname); } else { gen = PyGen_NewWithQualName(f, name, qualname); } if (gen == NULL) return NULL; if (is_coro && coro_wrapper != NULL) { PyObject *wrapped; tstate->in_coroutine_wrapper = 1; wrapped = PyObject_CallFunction(coro_wrapper, "N", gen); tstate->in_coroutine_wrapper = 0; return wrapped; } return gen; } retval = PyEval_EvalFrameEx(f,0); fail: /* Jump here from prelude on failure */ /* decref'ing the frame can cause __del__ methods to get invoked, which can call back into Python. While we're done with the current Python frame (f), the associated C stack is still in use, so recursion_depth must be boosted for the duration. */ assert(tstate != NULL); if (Py_REFCNT(f) > 1) { Py_DECREF(f); _PyObject_GC_TRACK(f); } else { ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; } return retval; } PyObject * PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure) { return _PyEval_EvalCodeWithName(_co, globals, locals, args, argcount, kws, kws != NULL ? kws + 1 : NULL, kwcount, 2, defs, defcount, kwdefs, closure, NULL, NULL); } static PyObject * special_lookup(PyObject *o, _Py_Identifier *id) { PyObject *res; res = _PyObject_LookupSpecial(o, id); if (res == NULL && !PyErr_Occurred()) { PyErr_SetObject(PyExc_AttributeError, id->object); return NULL; } return res; } /* These 3 functions deal with the exception state of generators. */ static void save_exc_state(PyThreadState *tstate, PyFrameObject *f) { PyObject *type, *value, *traceback; Py_XINCREF(tstate->exc_type); Py_XINCREF(tstate->exc_value); Py_XINCREF(tstate->exc_traceback); type = f->f_exc_type; value = f->f_exc_value; traceback = f->f_exc_traceback; f->f_exc_type = tstate->exc_type; f->f_exc_value = tstate->exc_value; f->f_exc_traceback = tstate->exc_traceback; Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); } static void swap_exc_state(PyThreadState *tstate, PyFrameObject *f) { PyObject *tmp; tmp = tstate->exc_type; tstate->exc_type = f->f_exc_type; f->f_exc_type = tmp; tmp = tstate->exc_value; tstate->exc_value = f->f_exc_value; f->f_exc_value = tmp; tmp = tstate->exc_traceback; tstate->exc_traceback = f->f_exc_traceback; f->f_exc_traceback = tmp; } static void restore_and_clear_exc_state(PyThreadState *tstate, PyFrameObject *f) { PyObject *type, *value, *tb; type = tstate->exc_type; value = tstate->exc_value; tb = tstate->exc_traceback; tstate->exc_type = f->f_exc_type; tstate->exc_value = f->f_exc_value; tstate->exc_traceback = f->f_exc_traceback; f->f_exc_type = NULL; f->f_exc_value = NULL; f->f_exc_traceback = NULL; Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tb); } /* Logic for the raise statement (too complicated for inlining). This *consumes* a reference count to each of its arguments. */ static dontinline int do_raise(PyObject *exc, PyObject *cause) { PyObject *type = NULL, *value = NULL; if (exc == NULL) { /* Reraise */ PyThreadState *tstate = PyThreadState_GET(); PyObject *tb; type = tstate->exc_type; value = tstate->exc_value; tb = tstate->exc_traceback; if (type == Py_None || type == NULL) { PyErr_SetString(PyExc_RuntimeError, "No active exception to reraise"); return 0; } Py_XINCREF(type); Py_XINCREF(value); Py_XINCREF(tb); PyErr_Restore(type, value, tb); return 1; } /* We support the following forms of raise: raise raise <instance> raise <type> */ if (PyExceptionClass_Check(exc)) { type = exc; value = PyObject_CallObject(exc, NULL); if (value == NULL) goto raise_error; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto raise_error; } } else if (PyExceptionInstance_Check(exc)) { value = exc; type = PyExceptionInstance_Class(exc); Py_INCREF(type); } else { /* Not something you can raise. You get an exception anyway, just not what you specified :-) */ Py_DECREF(exc); PyErr_SetString(PyExc_TypeError, "exceptions must derive from BaseException"); goto raise_error; } if (cause) { PyObject *fixed_cause; if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto raise_error; Py_DECREF(cause); } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; } else if (cause == Py_None) { Py_DECREF(cause); fixed_cause = NULL; } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto raise_error; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); /* PyErr_SetObject incref's its arguments */ Py_XDECREF(value); Py_XDECREF(type); return 0; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(cause); return 0; } /* Iterate v argcnt times and store the results on the stack (via decreasing * sp). Return 1 for success, 0 if error. * * If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack * with a variable target. */ static int unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp) { int i = 0, j = 0; Py_ssize_t ll = 0; PyObject *it; /* iter(v) */ PyObject *w; PyObject *l = NULL; /* variable list */ assert(v != NULL); it = PyObject_GetIter(v); if (it == NULL) goto Error; for (; i < argcnt; i++) { w = PyIter_Next(it); if (w == NULL) { /* Iterator done, via error or exhaustion. */ if (!PyErr_Occurred()) { if (argcntafter == -1) { PyErr_Format(PyExc_ValueError, "not enough values to unpack (expected %d, got %d)", argcnt, i); } else { PyErr_Format(PyExc_ValueError, "not enough values to unpack " "(expected at least %d, got %d)", argcnt + argcntafter, i); } } goto Error; } *--sp = w; } if (argcntafter == -1) { /* We better have exhausted the iterator now. */ w = PyIter_Next(it); if (w == NULL) { if (PyErr_Occurred()) goto Error; Py_DECREF(it); return 1; } Py_DECREF(w); PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %d)", argcnt); goto Error; } l = PySequence_List(it); if (l == NULL) goto Error; *--sp = l; i++; ll = PyList_GET_SIZE(l); if (ll < argcntafter) { PyErr_Format(PyExc_ValueError, "not enough values to unpack (expected at least %d, got %zd)", argcnt + argcntafter, argcnt + ll); goto Error; } /* Pop the "after-variable" args off the list. */ for (j = argcntafter; j > 0; j--, i++) { *--sp = PyList_GET_ITEM(l, ll - j); } /* Resize the list. */ Py_SIZE(l) = ll - argcntafter; Py_DECREF(it); return 1; Error: for (; i > 0; i--, sp++) Py_DECREF(*sp); Py_XDECREF(it); return 0; } #ifdef LLTRACE static int prtrace(PyObject *v, const char *str) { printf("%s ", str); if (PyObject_Print(v, stdout, 0) != 0) PyErr_Clear(); /* Don't know what else to do */ printf("\n"); return 1; } #endif static void call_exc_trace(Py_tracefunc func, PyObject *self, PyThreadState *tstate, PyFrameObject *f) { PyObject *type, *value, *traceback, *orig_traceback, *arg; int err; PyErr_Fetch(&type, &value, &orig_traceback); if (value == NULL) { value = Py_None; Py_INCREF(value); } PyErr_NormalizeException(&type, &value, &orig_traceback); traceback = (orig_traceback != NULL) ? orig_traceback : Py_None; arg = PyTuple_Pack(3, type, value, traceback); if (arg == NULL) { PyErr_Restore(type, value, orig_traceback); return; } err = call_trace(func, self, tstate, f, PyTrace_EXCEPTION, arg); Py_DECREF(arg); if (err == 0) PyErr_Restore(type, value, orig_traceback); else { Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(orig_traceback); } } static int call_trace_protected(Py_tracefunc func, PyObject *obj, PyThreadState *tstate, PyFrameObject *frame, int what, PyObject *arg) { PyObject *type, *value, *traceback; int err; PyErr_Fetch(&type, &value, &traceback); err = call_trace(func, obj, tstate, frame, what, arg); if (err == 0) { PyErr_Restore(type, value, traceback); return 0; } else { Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); return -1; } } static int call_trace(Py_tracefunc func, PyObject *obj, PyThreadState *tstate, PyFrameObject *frame, int what, PyObject *arg) { int result; if (tstate->tracing) return 0; tstate->tracing++; tstate->use_tracing = 0; result = func(obj, frame, what, arg); tstate->use_tracing = ((tstate->c_tracefunc != NULL) || (tstate->c_profilefunc != NULL)); tstate->tracing--; return result; } PyObject * _PyEval_CallTracing(PyObject *func, PyObject *args) { PyThreadState *tstate = PyThreadState_GET(); int save_tracing = tstate->tracing; int save_use_tracing = tstate->use_tracing; PyObject *result; tstate->tracing = 0; tstate->use_tracing = ((tstate->c_tracefunc != NULL) || (tstate->c_profilefunc != NULL)); result = PyObject_Call(func, args, NULL); tstate->tracing = save_tracing; tstate->use_tracing = save_use_tracing; return result; } /* See Objects/lnotab_notes.txt for a description of how tracing works. */ static int maybe_call_line_trace(Py_tracefunc func, PyObject *obj, PyThreadState *tstate, PyFrameObject *frame, int *instr_lb, int *instr_ub, int *instr_prev) { int result = 0; int line = frame->f_lineno; /* If the last instruction executed isn't in the current instruction window, reset the window. */ if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) { PyAddrPair bounds; line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, &bounds); *instr_lb = bounds.ap_lower; *instr_ub = bounds.ap_upper; } /* If the last instruction falls at the start of a line or if it represents a jump backwards, update the frame's line number and call the trace function. */ if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) { frame->f_lineno = line; result = call_trace(func, obj, tstate, frame, PyTrace_LINE, Py_None); } *instr_prev = frame->f_lasti; return result; } void PyEval_SetProfile(Py_tracefunc func, PyObject *arg) { PyThreadState *tstate = PyThreadState_GET(); PyObject *temp = tstate->c_profileobj; Py_XINCREF(arg); tstate->c_profilefunc = NULL; tstate->c_profileobj = NULL; /* Must make sure that tracing is not ignored if 'temp' is freed */ tstate->use_tracing = tstate->c_tracefunc != NULL; Py_XDECREF(temp); tstate->c_profilefunc = func; tstate->c_profileobj = arg; /* Flag that tracing or profiling is turned on */ tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL); } void PyEval_SetTrace(Py_tracefunc func, PyObject *arg) { PyThreadState *tstate = PyThreadState_GET(); PyObject *temp = tstate->c_traceobj; _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); Py_XINCREF(arg); tstate->c_tracefunc = NULL; tstate->c_traceobj = NULL; /* Must make sure that profiling is not ignored if 'temp' is freed */ tstate->use_tracing = tstate->c_profilefunc != NULL; Py_XDECREF(temp); tstate->c_tracefunc = func; tstate->c_traceobj = arg; /* Flag that tracing or profiling is turned on */ tstate->use_tracing = ((func != NULL) || (tstate->c_profilefunc != NULL)); } void _PyEval_SetCoroutineWrapper(PyObject *wrapper) { PyThreadState *tstate = PyThreadState_GET(); Py_XINCREF(wrapper); Py_XSETREF(tstate->coroutine_wrapper, wrapper); } PyObject * _PyEval_GetCoroutineWrapper(void) { PyThreadState *tstate = PyThreadState_GET(); return tstate->coroutine_wrapper; } void _PyEval_SetAsyncGenFirstiter(PyObject *firstiter) { PyThreadState *tstate = PyThreadState_GET(); Py_XINCREF(firstiter); Py_XSETREF(tstate->async_gen_firstiter, firstiter); } PyObject * _PyEval_GetAsyncGenFirstiter(void) { PyThreadState *tstate = PyThreadState_GET(); return tstate->async_gen_firstiter; } void _PyEval_SetAsyncGenFinalizer(PyObject *finalizer) { PyThreadState *tstate = PyThreadState_GET(); Py_XINCREF(finalizer); Py_XSETREF(tstate->async_gen_finalizer, finalizer); } PyObject * _PyEval_GetAsyncGenFinalizer(void) { PyThreadState *tstate = PyThreadState_GET(); return tstate->async_gen_finalizer; } PyObject * PyEval_GetBuiltins(void) { PyFrameObject *current_frame = PyEval_GetFrame(); if (current_frame == NULL) return PyThreadState_GET()->interp->builtins; else return current_frame->f_builtins; } /* Convenience function to get a builtin from its name */ PyObject * _PyEval_GetBuiltinId(_Py_Identifier *name) { PyObject *attr = _PyDict_GetItemIdWithError(PyEval_GetBuiltins(), name); if (attr) { Py_INCREF(attr); } else if (!PyErr_Occurred()) { PyErr_SetObject(PyExc_AttributeError, _PyUnicode_FromId(name)); } return attr; } PyObject * PyEval_GetLocals(void) { PyFrameObject *current_frame = PyEval_GetFrame(); if (current_frame == NULL) { PyErr_SetString(PyExc_SystemError, "frame does not exist"); return NULL; } if (PyFrame_FastToLocalsWithError(current_frame) < 0) return NULL; assert(current_frame->f_locals != NULL); return current_frame->f_locals; } PyObject * PyEval_GetGlobals(void) { PyFrameObject *current_frame = PyEval_GetFrame(); if (current_frame == NULL) return NULL; assert(current_frame->f_globals != NULL); return current_frame->f_globals; } PyFrameObject * PyEval_GetFrame(void) { PyThreadState *tstate = PyThreadState_GET(); return _PyThreadState_GetFrame(tstate); } int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) { PyFrameObject *current_frame = PyEval_GetFrame(); int result = cf->cf_flags != 0; if (current_frame != NULL) { const int codeflags = current_frame->f_code->co_flags; const int compilerflags = codeflags & PyCF_MASK; if (compilerflags) { result = 1; cf->cf_flags |= compilerflags; } #if 0 /* future keyword */ if (codeflags & CO_GENERATOR_ALLOWED) { result = 1; cf->cf_flags |= CO_GENERATOR_ALLOWED; } #endif } return result; } const char * PyEval_GetFuncName(PyObject *func) { if (PyMethod_Check(func)) return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func)); else if (PyFunction_Check(func)) return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name); else if (PyCFunction_Check(func)) return ((PyCFunctionObject*)func)->m_ml->ml_name; else return func->ob_type->tp_name; } const char * PyEval_GetFuncDesc(PyObject *func) { if (PyMethod_Check(func)) return "()"; else if (PyFunction_Check(func)) return "()"; else if (PyCFunction_Check(func)) return "()"; else return " object"; } #define C_TRACE(x, call) \ if (tstate->use_tracing && tstate->c_profilefunc) { \ if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \ tstate, tstate->frame, \ PyTrace_C_CALL, func)) { \ x = NULL; \ } \ else { \ x = call; \ if (tstate->c_profilefunc != NULL) { \ if (x == NULL) { \ call_trace_protected(tstate->c_profilefunc, \ tstate->c_profileobj, \ tstate, tstate->frame, \ PyTrace_C_EXCEPTION, func); \ /* XXX should pass (type, value, tb) */ \ } else { \ if (call_trace(tstate->c_profilefunc, \ tstate->c_profileobj, \ tstate, tstate->frame, \ PyTrace_C_RETURN, func)) { \ Py_DECREF(x); \ x = NULL; \ } \ } \ } \ } \ } else { \ x = call; \ } forceinline PyObject * _Py_HOT_FUNCTION call_function(PyObject ***pp_stack, Py_ssize_t oparg, PyObject *kwnames) { PyObject **pfunc = (*pp_stack) - oparg - 1; PyObject *func = *pfunc; PyObject *x, *w; Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames); Py_ssize_t nargs = oparg - nkwargs; PyObject **stack = (*pp_stack) - nargs - nkwargs; /* Always dispatch PyCFunction first, because these are presumed to be the most frequent callable object. */ if (PyCFunction_Check(func)) { PyThreadState *tstate = PyThreadState_GET(); PCALL(PCALL_CFUNCTION); C_TRACE(x, _PyCFunction_FastCallKeywords(func, stack, nargs, kwnames)); } else if (Py_TYPE(func) == &PyMethodDescr_Type) { PyThreadState *tstate = PyThreadState_GET(); if (nargs > 0 && tstate->use_tracing) { /* We need to create a temporary bound method as argument for profiling. If nargs == 0, then this cannot work because we have no "self". In any case, the call itself would raise TypeError (foo needs an argument), so we just skip profiling. */ PyObject *self = stack[0]; func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self)); if (func != NULL) { C_TRACE(x, _PyCFunction_FastCallKeywords(func, stack+1, nargs-1, kwnames)); Py_DECREF(func); } else { x = NULL; } } else { x = _PyMethodDescr_FastCallKeywords(func, stack, nargs, kwnames); } } else { if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { /* optimize access to bound methods */ PyObject *self = PyMethod_GET_SELF(func); PCALL(PCALL_METHOD); PCALL(PCALL_BOUND_METHOD); Py_INCREF(self); func = PyMethod_GET_FUNCTION(func); Py_INCREF(func); Py_SETREF(*pfunc, self); nargs++; stack--; } else { Py_INCREF(func); } if (PyFunction_Check(func)) { x = _PyFunction_FastCallKeywords(func, stack, nargs, kwnames); } else { x = _PyObject_FastCallKeywords(func, stack, nargs, kwnames); } Py_DECREF(func); } assert((x != NULL) ^ (PyErr_Occurred() != NULL)); /* Clear the stack of the function object. */ while ((*pp_stack) > pfunc) { w = EXT_POP(*pp_stack); Py_DECREF(w); PCALL(PCALL_POP); } return x; } static PyObject * do_call_core(PyObject *func, PyObject *callargs, PyObject *kwdict) { #ifdef CALL_PROFILE /* At this point, we have to look at the type of func to update the call stats properly. Do it here so as to avoid exposing the call stats machinery outside ceval.c */ if (PyFunction_Check(func)) PCALL(PCALL_FUNCTION); else if (PyMethod_Check(func)) PCALL(PCALL_METHOD); else if (PyType_Check(func)) PCALL(PCALL_TYPE); else if (PyCFunction_Check(func)) PCALL(PCALL_CFUNCTION); else PCALL(PCALL_OTHER); #endif if (PyCFunction_Check(func)) { PyObject *result; PyThreadState *tstate = PyThreadState_GET(); C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); return result; } else { return PyObject_Call(func, callargs, kwdict); } } /* Extract a slice index from a PyLong or an object with the nb_index slot defined, and store in *pi. Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX, and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN. Return 0 on error, 1 on success. */ int _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi) { if (v != Py_None) { Py_ssize_t x; if (PyIndex_Check(v)) { x = PyNumber_AsSsize_t(v, NULL); if (x == -1 && PyErr_Occurred()) return 0; } else { PyErr_SetString(PyExc_TypeError, "slice indices must be integers or " "None or have an __index__ method"); return 0; } *pi = x; } return 1; } int _PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi) { Py_ssize_t x; if (PyIndex_Check(v)) { x = PyNumber_AsSsize_t(v, NULL); if (x == -1 && PyErr_Occurred()) return 0; } else { PyErr_SetString(PyExc_TypeError, "slice indices must be integers or " "have an __index__ method"); return 0; } *pi = x; return 1; } #define CANNOT_CATCH_MSG "catching classes that do not inherit from "\ "BaseException is not allowed" static PyObject * cmp_outcome(int op, PyObject *v, PyObject *w) { int res = 0; switch (op) { case PyCmp_IS: res = (v == w); break; case PyCmp_IS_NOT: res = (v != w); break; case PyCmp_IN: res = PySequence_Contains(w, v); if (res < 0) return NULL; break; case PyCmp_NOT_IN: res = PySequence_Contains(w, v); if (res < 0) return NULL; res = !res; break; case PyCmp_EXC_MATCH: if (PyTuple_Check(w)) { Py_ssize_t i, length; length = PyTuple_Size(w); for (i = 0; i < length; i += 1) { PyObject *exc = PyTuple_GET_ITEM(w, i); if (!PyExceptionClass_Check(exc)) { PyErr_SetString(PyExc_TypeError, CANNOT_CATCH_MSG); return NULL; } } } else { if (!PyExceptionClass_Check(w)) { PyErr_SetString(PyExc_TypeError, CANNOT_CATCH_MSG); return NULL; } } res = PyErr_GivenExceptionMatches(v, w); break; default: return PyObject_RichCompare(v, w, op); } v = res ? Py_True : Py_False; Py_INCREF(v); return v; } static PyObject * import_name(PyFrameObject *f, PyObject *name, PyObject *fromlist, PyObject *level) { _Py_IDENTIFIER(__import__); PyObject *import_func, *res; PyObject* stack[5]; import_func = _PyDict_GetItemId(f->f_builtins, &PyId___import__); if (import_func == NULL) { PyErr_SetString(PyExc_ImportError, "__import__ not found"); return NULL; } /* Fast path for not overloaded __import__. */ if (import_func == PyThreadState_GET()->interp->import_func) { int ilevel = _PyLong_AsInt(level); if (ilevel == -1 && PyErr_Occurred()) { return NULL; } res = PyImport_ImportModuleLevelObject( name, f->f_globals, f->f_locals == NULL ? Py_None : f->f_locals, fromlist, ilevel); return res; } Py_INCREF(import_func); stack[0] = name; stack[1] = f->f_globals; stack[2] = f->f_locals == NULL ? Py_None : f->f_locals; stack[3] = fromlist; stack[4] = level; res = _PyObject_FastCall(import_func, stack, 5); Py_DECREF(import_func); return res; } static PyObject * import_from(PyObject *v, PyObject *name) { PyObject *x; _Py_IDENTIFIER(__name__); PyObject *fullmodname, *pkgname; x = PyObject_GetAttr(v, name); if (x != NULL || !PyErr_ExceptionMatches(PyExc_AttributeError)) return x; /* Issue #17636: in case this failed because of a circular relative import, try to fallback on reading the module directly from sys.modules. */ PyErr_Clear(); pkgname = _PyObject_GetAttrId(v, &PyId___name__); if (pkgname == NULL) { goto error; } if (!PyUnicode_Check(pkgname)) { Py_CLEAR(pkgname); goto error; } fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name); Py_DECREF(pkgname); if (fullmodname == NULL) { return NULL; } x = PyDict_GetItem(PyImport_GetModuleDict(), fullmodname); Py_DECREF(fullmodname); if (x == NULL) { goto error; } Py_INCREF(x); return x; error: PyErr_Format(PyExc_ImportError, "cannot import name %R", name); return NULL; } static int import_all_from(PyObject *locals, PyObject *v) { _Py_IDENTIFIER(__all__); _Py_IDENTIFIER(__dict__); PyObject *all = _PyObject_GetAttrId(v, &PyId___all__); PyObject *dict, *name, *value; int skip_leading_underscores = 0; int pos, err; if (all == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return -1; /* Unexpected error */ PyErr_Clear(); dict = _PyObject_GetAttrId(v, &PyId___dict__); if (dict == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return -1; PyErr_SetString(PyExc_ImportError, "from-import-* object has no __dict__ and no __all__"); return -1; } all = PyMapping_Keys(dict); Py_DECREF(dict); if (all == NULL) return -1; skip_leading_underscores = 1; } for (pos = 0, err = 0; ; pos++) { name = PySequence_GetItem(all, pos); if (name == NULL) { if (!PyErr_ExceptionMatches(PyExc_IndexError)) err = -1; else PyErr_Clear(); break; } if (skip_leading_underscores && PyUnicode_Check(name)) { if (PyUnicode_READY(name) == -1) { Py_DECREF(name); err = -1; break; } if (PyUnicode_READ_CHAR(name, 0) == '_') { Py_DECREF(name); continue; } } value = PyObject_GetAttr(v, name); if (value == NULL) err = -1; else if (PyDict_CheckExact(locals)) err = PyDict_SetItem(locals, name, value); else err = PyObject_SetItem(locals, name, value); Py_DECREF(name); Py_XDECREF(value); if (err != 0) break; } Py_DECREF(all); return err; } static int check_args_iterable(PyObject *func, PyObject *args) { if (args->ob_type->tp_iter == NULL && !PySequence_Check(args)) { PyErr_Format(PyExc_TypeError, "%.200s%.200s argument after * " "must be an iterable, not %.200s", PyEval_GetFuncName(func), PyEval_GetFuncDesc(func), args->ob_type->tp_name); return -1; } return 0; } static void format_kwargs_mapping_error(PyObject *func, PyObject *kwargs) { PyErr_Format(PyExc_TypeError, "%.200s%.200s argument after ** " "must be a mapping, not %.200s", PyEval_GetFuncName(func), PyEval_GetFuncDesc(func), kwargs->ob_type->tp_name); } static void format_exc_check_arg(PyObject *exc, const char *format_str, PyObject *obj) { const char *obj_str; if (!obj) return; obj_str = PyUnicode_AsUTF8(obj); if (!obj_str) return; PyErr_Format(exc, format_str, obj_str); } static void format_exc_unbound(PyCodeObject *co, int oparg) { PyObject *name; /* Don't stomp existing exception */ if (PyErr_Occurred()) return; if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { name = PyTuple_GET_ITEM(co->co_cellvars, oparg); format_exc_check_arg( PyExc_UnboundLocalError, UNBOUNDLOCAL_ERROR_MSG, name); } else { name = PyTuple_GET_ITEM(co->co_freevars, oparg - PyTuple_GET_SIZE(co->co_cellvars)); format_exc_check_arg(PyExc_NameError, UNBOUNDFREE_ERROR_MSG, name); } } static void format_awaitable_error(PyTypeObject *type, int prevopcode) { if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) { if (prevopcode == BEFORE_ASYNC_WITH) { PyErr_Format(PyExc_TypeError, "'async with' received an object from __aenter__ " "that does not implement __await__: %.100s", type->tp_name); } else if (prevopcode == WITH_CLEANUP_START) { PyErr_Format(PyExc_TypeError, "'async with' received an object from __aexit__ " "that does not implement __await__: %.100s", type->tp_name); } } } static PyObject * unicode_concatenate(PyObject *v, PyObject *w, PyFrameObject *f, const _Py_CODEUNIT *next_instr) { PyObject *res; if (Py_REFCNT(v) == 2) { /* In the common case, there are 2 references to the value * stored in 'variable' when the += is performed: one on the * value stack (in 'v') and one still stored in the * 'variable'. We try to delete the variable now to reduce * the refcnt to 1. */ int opcode, oparg; NEXTOPARG(); switch (opcode) { case STORE_FAST: { if (GETLOCAL((unsigned)oparg) == v) SETLOCAL((unsigned)oparg, NULL); break; } case STORE_DEREF: { PyObject **freevars = (f->f_localsplus + f->f_code->co_nlocals); PyObject *c = freevars[oparg]; if (PyCell_GET(c) == v) PyCell_Set(c, NULL); break; } case STORE_NAME: { PyObject *names = f->f_code->co_names; PyObject *name = GETITEM(names, (unsigned)oparg); PyObject *locals = f->f_locals; if (locals && PyDict_CheckExact(locals) && PyDict_GetItem(locals, name) == v) { if (PyDict_DelItem(locals, name) != 0) { PyErr_Clear(); } } break; } } } res = v; PyUnicode_Append(&res, w); return res; } #ifdef DYNAMIC_EXECUTION_PROFILE static PyObject * getarray(long a[256]) { int i; PyObject *l = PyList_New(256); if (l == NULL) return NULL; for (i = 0; i < 256; i++) { PyObject *x = PyLong_FromLong(a[i]); if (x == NULL) { Py_DECREF(l); return NULL; } PyList_SET_ITEM(l, i, x); } for (i = 0; i < 256; i++) a[i] = 0; return l; } PyObject * _Py_GetDXProfile(PyObject *self, PyObject *args) { #ifndef DXPAIRS return getarray(dxp); #else int i; PyObject *l = PyList_New(257); if (l == NULL) return NULL; for (i = 0; i < 257; i++) { PyObject *x = getarray(dxpairs[i]); if (x == NULL) { Py_DECREF(l); return NULL; } PyList_SET_ITEM(l, i, x); } return l; #endif } #endif Py_ssize_t _PyEval_RequestCodeExtraIndex(freefunc free) { __PyCodeExtraState *state = __PyCodeExtraState_Get(); Py_ssize_t new_index; if (state->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) { return -1; } new_index = state->co_extra_user_count++; state->co_extra_freefuncs[new_index] = free; return new_index; } static void dtrace_function_entry(PyFrameObject *f) { char* filename; char* funcname; int lineno; filename = PyUnicode_AsUTF8(f->f_code->co_filename); funcname = PyUnicode_AsUTF8(f->f_code->co_name); lineno = PyCode_Addr2Line(f->f_code, f->f_lasti); PyDTrace_FUNCTION_ENTRY(filename, funcname, lineno); } static void dtrace_function_return(PyFrameObject *f) { char* filename; char* funcname; int lineno; filename = PyUnicode_AsUTF8(f->f_code->co_filename); funcname = PyUnicode_AsUTF8(f->f_code->co_name); lineno = PyCode_Addr2Line(f->f_code, f->f_lasti); PyDTrace_FUNCTION_RETURN(filename, funcname, lineno); } /* DTrace equivalent of maybe_call_line_trace. */ static void maybe_dtrace_line(PyFrameObject *frame, int *instr_lb, int *instr_ub, int *instr_prev) { int line = frame->f_lineno; char *co_filename, *co_name; /* If the last instruction executed isn't in the current instruction window, reset the window. */ if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) { PyAddrPair bounds; line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, &bounds); *instr_lb = bounds.ap_lower; *instr_ub = bounds.ap_upper; } /* If the last instruction falls at the start of a line or if it represents a jump backwards, update the frame's line number and call the trace function. */ if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) { frame->f_lineno = line; co_filename = PyUnicode_AsUTF8(frame->f_code->co_filename); if (!co_filename) co_filename = "?"; co_name = PyUnicode_AsUTF8(frame->f_code->co_name); if (!co_name) co_name = "?"; PyDTrace_LINE(co_filename, co_name, line); } *instr_prev = frame->f_lasti; }
174,719
5,406
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/inittab.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/import.h" static struct _inittab _PyImport_Inittab_Empty[1]; struct _inittab *PyImport_Inittab = _PyImport_Inittab_Empty;
1,996
23
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/getopt.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "third_party/python/Include/pygetopt.h" /* clang-format off */ asm(".ident\t\"\\n\\n\ python getopt (isc license)\\n\ Copyright 1992-1994 David Gottner\""); /* clang-format off */ /*---------------------------------------------------------------------------* * <RCS keywords> * * C++ Library * * Copyright 1992-1994, David Gottner * * All Rights Reserved * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice, this permission notice and * the following disclaimer notice appear unmodified in all copies. * * I DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL I * BE LIABLE FOR ANY SPECIAL, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Nevertheless, I would like to know about bugs in this library or * suggestions for improvment. Send bug reports and feedback to * [email protected]. *---------------------------------------------------------------------------*/ /* Modified to support --help and --version, as well as /? on Windows * by Georg Brandl. */ int _PyOS_opterr = 1; /* generate error messages */ int _PyOS_optind = 1; /* index into argv array */ wchar_t *_PyOS_optarg = NULL; /* optional argument */ static wchar_t *opt_ptr = L""; void _PyOS_ResetGetOpt(void) { _PyOS_opterr = 1; _PyOS_optind = 1; _PyOS_optarg = NULL; opt_ptr = L""; } int _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring) { wchar_t *ptr; wchar_t option; if (*opt_ptr == '\0') { if (_PyOS_optind >= argc) return -1; #ifdef MS_WINDOWS else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { ++_PyOS_optind; return 'h'; } #endif else if (argv[_PyOS_optind][0] != L'-' || argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) return -1; else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { ++_PyOS_optind; return -1; } else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { ++_PyOS_optind; return 'h'; } else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { ++_PyOS_optind; return 'V'; } opt_ptr = &argv[_PyOS_optind++][1]; } if ((option = *opt_ptr++) == L'\0') return -1; if (option == 'J') { if (_PyOS_opterr) fprintf(stderr, "-J is reserved for Jython\n"); return '_'; } if ((ptr = wcschr(optstring, option)) == NULL) { if (_PyOS_opterr) fprintf(stderr, "Unknown option: -%c\n", (char)option); return '_'; } if (*(ptr + 1) == L':') { if (*opt_ptr != L'\0') { _PyOS_optarg = opt_ptr; opt_ptr = L""; } else { if (_PyOS_optind >= argc) { if (_PyOS_opterr) fprintf(stderr, "Argument expected for the -%c option\n", (char)option); return '_'; } _PyOS_optarg = argv[_PyOS_optind++]; } } return option; }
4,409
119
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/dynload_win.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/patchlevel.h" #include "third_party/python/Python/importdl.h" /* clang-format off */ // "activation context" magic - see dl_nt.c... #if HAVE_SXS extern ULONG_PTR _Py_ActivateActCtx(); void _Py_DeactivateActCtx(ULONG_PTR cookie); #endif #ifdef _DEBUG #define PYD_DEBUG_SUFFIX "_d" #else #define PYD_DEBUG_SUFFIX "" #endif #ifdef PYD_PLATFORM_TAG #define PYD_TAGGED_SUFFIX PYD_DEBUG_SUFFIX ".cp" Py_STRINGIFY(PY_MAJOR_VERSION) Py_STRINGIFY(PY_MINOR_VERSION) "-" PYD_PLATFORM_TAG ".pyd" #else #define PYD_TAGGED_SUFFIX PYD_DEBUG_SUFFIX ".cp" Py_STRINGIFY(PY_MAJOR_VERSION) Py_STRINGIFY(PY_MINOR_VERSION) ".pyd" #endif #define PYD_UNTAGGED_SUFFIX PYD_DEBUG_SUFFIX ".pyd" const char *_PyImport_DynLoadFiletab[] = { PYD_TAGGED_SUFFIX, PYD_UNTAGGED_SUFFIX, NULL }; /* Case insensitive string compare, to avoid any dependencies on particular C RTL implementations */ static int strcasecmp (const char *string1, const char *string2) { int first, second; do { first = tolower(*string1); second = tolower(*string2); string1++; string2++; } while (first && first == second); return (first - second); } /* Function to return the name of the "python" DLL that the supplied module directly imports. Looks through the list of imported modules and returns the first entry that starts with "python" (case sensitive) and is followed by nothing but numbers until the separator (period). Returns a pointer to the import name, or NULL if no matching name was located. This function parses through the PE header for the module as loaded in memory by the system loader. The PE header is accessed as documented by Microsoft in the MSDN PE and COFF specification (2/99), and handles both PE32 and PE32+. It only worries about the direct import table and not the delay load import table since it's unlikely an extension is going to be delay loading Python (after all, it's already loaded). If any magic values are not found (e.g., the PE header or optional header magic), then this function simply returns NULL. */ #define DWORD_AT(mem) (*(DWORD *)(mem)) #define WORD_AT(mem) (*(WORD *)(mem)) static char *GetPythonImport (HINSTANCE hModule) { unsigned char *dllbase, *import_data, *import_name; DWORD pe_offset, opt_offset; WORD opt_magic; int num_dict_off, import_off; /* Safety check input */ if (hModule == NULL) { return NULL; } /* Module instance is also the base load address. First portion of memory is the MS-DOS loader, which holds the offset to the PE header (from the load base) at 0x3C */ dllbase = (unsigned char *)hModule; pe_offset = DWORD_AT(dllbase + 0x3C); /* The PE signature must be "PE\0\0" */ if (bcmp(dllbase+pe_offset,"PE\0\0",4)) { return NULL; } /* Following the PE signature is the standard COFF header (20 bytes) and then the optional header. The optional header starts with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ uses 64-bits for some fields). It might also be 0x107 for a ROM image, but we don't process that here. The optional header ends with a data dictionary that directly points to certain types of data, among them the import entries (in the second table entry). Based on the header type, we determine offsets for the data dictionary count and the entry within the dictionary pointing to the imports. */ opt_offset = pe_offset + 4 + 20; opt_magic = WORD_AT(dllbase+opt_offset); if (opt_magic == 0x10B) { /* PE32 */ num_dict_off = 92; import_off = 104; } else if (opt_magic == 0x20B) { /* PE32+ */ num_dict_off = 108; import_off = 120; } else { /* Unsupported */ return NULL; } /* Now if an import table exists, offset to it and walk the list of imports. The import table is an array (ending when an entry has empty values) of structures (20 bytes each), which contains (at offset 12) a relative address (to the module base) at which a string constant holding the import name is located. */ if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { /* We have at least 2 tables - the import table is the second one. But still it may be that the table size is zero */ if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) return NULL; import_data = dllbase + DWORD_AT(dllbase + opt_offset + import_off); while (DWORD_AT(import_data)) { import_name = dllbase + DWORD_AT(import_data+12); if (strlen(import_name) >= 6 && !strncmp(import_name,"python",6)) { char *pch; #ifndef _DEBUG /* In a release version, don't claim that python3.dll is a Python DLL. */ if (strcmp(import_name, "python3.dll") == 0) { import_data += 20; continue; } #endif /* Ensure python prefix is followed only by numbers to the end of the basename */ pch = import_name + 6; #ifdef _DEBUG while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { #else while (*pch && *pch != '.') { #endif if (*pch >= '0' && *pch <= '9') { pch++; } else { pch = NULL; break; } } if (pch) { /* Found it - return the name */ return import_name; } } import_data += 20; } } return NULL; } dl_funcptr _PyImport_FindSharedFuncptrWindows(const char *prefix, const char *shortname, PyObject *pathname, FILE *fp) { dl_funcptr p; char funcname[258], *import_python; const wchar_t *wpathname; _Py_CheckPython3(); wpathname = _PyUnicode_AsUnicode(pathname); if (wpathname == NULL) return NULL; PyOS_snprintf(funcname, sizeof(funcname), "%.20s_%.200s", prefix, shortname); { HINSTANCE hDLL = NULL; unsigned int old_mode; #if HAVE_SXS ULONG_PTR cookie = 0; #endif /* Don't display a message box when Python can't load a DLL */ old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); #if HAVE_SXS cookie = _Py_ActivateActCtx(); #endif /* We use LoadLibraryEx so Windows looks for dependent DLLs in directory of pathname first. */ /* XXX This call doesn't exist in Windows CE */ hDLL = LoadLibraryExW(wpathname, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); #if HAVE_SXS _Py_DeactivateActCtx(cookie); #endif /* restore old error mode settings */ SetErrorMode(old_mode); if (hDLL==NULL){ PyObject *message; unsigned int errorCode; /* Get an error string from Win32 error code */ wchar_t theInfo[256]; /* Pointer to error text from system */ int theLength; /* Length of error text */ errorCode = GetLastError(); theLength = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ NULL, /* message source */ errorCode, /* the message (error) ID */ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ theInfo, /* the buffer */ sizeof(theInfo) / sizeof(wchar_t), /* size in wchars */ NULL); /* no additional format args. */ /* Problem: could not get the error message. This should not happen if called correctly. */ if (theLength == 0) { message = PyUnicode_FromFormat( "DLL load failed with error code %d", errorCode); } else { /* For some reason a \r\n is appended to the text */ if (theLength >= 2 && theInfo[theLength-2] == '\r' && theInfo[theLength-1] == '\n') { theLength -= 2; theInfo[theLength] = '\0'; } message = PyUnicode_FromString( "DLL load failed: "); PyUnicode_AppendAndDel(&message, PyUnicode_FromWideChar( theInfo, theLength)); } if (message != NULL) { PyObject *shortname_obj = PyUnicode_FromString(shortname); PyErr_SetImportError(message, shortname_obj, pathname); Py_XDECREF(shortname_obj); Py_DECREF(message); } return NULL; } else { char buffer[256]; PyOS_snprintf(buffer, sizeof(buffer), #ifdef _DEBUG "python%d%d_d.dll", #else "python%d%d.dll", #endif PY_MAJOR_VERSION,PY_MINOR_VERSION); import_python = GetPythonImport(hDLL); if (import_python && strcasecmp(buffer,import_python)) { PyErr_Format(PyExc_ImportError, "Module use of %.150s conflicts " "with this version of Python.", import_python); FreeLibrary(hDLL); return NULL; } } p = GetProcAddress(hDLL, funcname); } return p; }
10,939
304
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/peephole.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/ast.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/opcode.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/symtable.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Python/wordcode_helpers.inc" #include "third_party/quickjs/internal.h" /* clang-format off */ /* Peephole optimizations for bytecode compiler. */ #define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) #define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \ || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP) #define GETJUMPTGT(arr, i) (get_arg(arr, i) / sizeof(_Py_CODEUNIT) + \ (ABSOLUTE_JUMP(_Py_OPCODE(arr[i])) ? 0 : i+1)) #define ISBASICBLOCK(blocks, start, end) \ (blocks[start]==blocks[end]) #define CONST_STACK_CREATE() { \ const_stack_size = 256; \ const_stack = PyMem_New(PyObject *, const_stack_size); \ if (!const_stack) { \ PyErr_NoMemory(); \ goto exitError; \ } \ } #define CONST_STACK_DELETE() do { \ if (const_stack) \ PyMem_Free(const_stack); \ } while(0) #define CONST_STACK_LEN() ((unsigned)(const_stack_top + 1)) #define CONST_STACK_PUSH_OP(i) do { \ PyObject *_x; \ assert(_Py_OPCODE(codestr[i]) == LOAD_CONST); \ assert(PyList_GET_SIZE(consts) > (Py_ssize_t)get_arg(codestr, i)); \ _x = PyList_GET_ITEM(consts, get_arg(codestr, i)); \ if (++const_stack_top >= const_stack_size) { \ const_stack_size *= 2; \ PyMem_Resize(const_stack, PyObject *, const_stack_size); \ if (!const_stack) { \ PyErr_NoMemory(); \ goto exitError; \ } \ } \ const_stack[const_stack_top] = _x; \ in_consts = 1; \ } while(0) #define CONST_STACK_RESET() do { \ const_stack_top = -1; \ } while(0) #define CONST_STACK_LASTN(i) \ &const_stack[CONST_STACK_LEN() - i] #define CONST_STACK_POP(i) do { \ assert(CONST_STACK_LEN() >= i); \ const_stack_top -= i; \ } while(0) /* Scans back N consecutive LOAD_CONST instructions, skipping NOPs, returns index of the Nth last's LOAD_CONST's EXTENDED_ARG prefix. Callers are responsible to check CONST_STACK_LEN beforehand. */ static Py_ssize_t lastn_const_start(const _Py_CODEUNIT *codestr, Py_ssize_t i, Py_ssize_t n) { assert(n > 0); for (;;) { i--; assert(i >= 0); if (_Py_OPCODE(codestr[i]) == LOAD_CONST) { if (!--n) { while (i > 0 && _Py_OPCODE(codestr[i-1]) == EXTENDED_ARG) { i--; } return i; } } else { assert(_Py_OPCODE(codestr[i]) == NOP || _Py_OPCODE(codestr[i]) == EXTENDED_ARG); } } } /* Scans through EXTENDED ARGs, seeking the index of the effective opcode */ static Py_ssize_t find_op(const _Py_CODEUNIT *codestr, Py_ssize_t codelen, Py_ssize_t i) { while (i < codelen && _Py_OPCODE(codestr[i]) == EXTENDED_ARG) { i++; } return i; } /* Given the index of the effective opcode, scan back to construct the oparg with EXTENDED_ARG */ static unsigned int get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i) { _Py_CODEUNIT word; unsigned int oparg = _Py_OPARG(codestr[i]); if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) { oparg |= _Py_OPARG(word) << 8; if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) { oparg |= _Py_OPARG(word) << 16; if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) { oparg |= _Py_OPARG(word) << 24; } } } return oparg; } /* Fill the region with NOPs. */ static void fill_nops(_Py_CODEUNIT *codestr, Py_ssize_t start, Py_ssize_t end) { memset(codestr + start, NOP, (end - start) * sizeof(_Py_CODEUNIT)); } /* Given the index of the effective opcode, attempt to replace the argument, taking into account EXTENDED_ARG. Returns -1 on failure, or the new op index on success */ static Py_ssize_t set_arg(_Py_CODEUNIT *codestr, Py_ssize_t i, unsigned int oparg) { unsigned int curarg = get_arg(codestr, i); int curilen, newilen; if (curarg == oparg) return i; curilen = instrsize(curarg); newilen = instrsize(oparg); if (curilen < newilen) { return -1; } write_op_arg(codestr + i + 1 - curilen, _Py_OPCODE(codestr[i]), oparg, newilen); fill_nops(codestr, i + 1 - curilen + newilen, i + 1); return i-curilen+newilen; } /* Attempt to write op/arg at end of specified region of memory. Preceding memory in the region is overwritten with NOPs. Returns -1 on failure, op index on success */ static Py_ssize_t copy_op_arg(_Py_CODEUNIT *codestr, Py_ssize_t i, unsigned char op, unsigned int oparg, Py_ssize_t maxi) { int ilen = instrsize(oparg); if (i + ilen > maxi) { return -1; } write_op_arg(codestr + maxi - ilen, op, oparg, ilen); fill_nops(codestr, i, maxi - ilen); return maxi - 1; } /* Check whether a collection doesn't containing too much items (including subcollections). This protects from creating a constant that needs too much time for calculating a hash. "limit" is the maximal number of items. Returns the negative number if the total number of items exceeds the limit. Otherwise returns the limit minus the total number of items. */ static Py_ssize_t check_complexity(PyObject *obj, Py_ssize_t limit) { if (PyTuple_Check(obj)) { Py_ssize_t i; limit -= PyTuple_GET_SIZE(obj); for (i = 0; limit >= 0 && i < PyTuple_GET_SIZE(obj); i++) { limit = check_complexity(PyTuple_GET_ITEM(obj, i), limit); } return limit; } else if (PyFrozenSet_Check(obj)) { Py_ssize_t i = 0; PyObject *item; Py_hash_t hash; limit -= PySet_GET_SIZE(obj); while (limit >= 0 && _PySet_NextEntry(obj, &i, &item, &hash)) { limit = check_complexity(item, limit); } } return limit; } /* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n with LOAD_CONST (c1, c2, ... cn). The consts table must still be in list form so that the new constant (c1, c2, ... cn) can be appended. Called with codestr pointing to the first LOAD_CONST. Bails out with no change if one or more of the LOAD_CONSTs is missing. Also works for BUILD_LIST and BUILT_SET when followed by an "in" or "not in" test; for BUILD_SET it assembles a frozenset rather than a tuple. */ static Py_ssize_t fold_tuple_on_constants(_Py_CODEUNIT *codestr, Py_ssize_t c_start, Py_ssize_t opcode_end, unsigned char opcode, PyObject *consts, PyObject **objs, int n) { PyObject *newconst, *constant; Py_ssize_t i, len_consts; /* Pre-conditions */ assert(PyList_CheckExact(consts)); /* Buildup new tuple of constants */ newconst = PyTuple_New(n); if (newconst == NULL) { return -1; } for (i=0 ; i<n ; i++) { constant = objs[i]; Py_INCREF(constant); PyTuple_SET_ITEM(newconst, i, constant); } /* If it's a BUILD_SET, use the PyTuple we just built to create a PyFrozenSet, and use that as the constant instead: */ if (opcode == BUILD_SET) { Py_SETREF(newconst, PyFrozenSet_New(newconst)); if (newconst == NULL) { return -1; } } /* Append folded constant onto consts */ len_consts = PyList_GET_SIZE(consts); if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return -1; } Py_DECREF(newconst); return copy_op_arg(codestr, c_start, LOAD_CONST, len_consts, opcode_end); } #define MAX_INT_SIZE 128 /* bits */ #define MAX_COLLECTION_SIZE 20 /* items */ #define MAX_STR_SIZE 20 /* characters */ #define MAX_TOTAL_ITEMS 1024 /* including nested collections */ static PyObject * safe_multiply(PyObject *v, PyObject *w) { if (PyLong_Check(v) && PyLong_Check(w) && Py_SIZE(v) && Py_SIZE(w)) { size_t vbits = _PyLong_NumBits(v); size_t wbits = _PyLong_NumBits(w); if (vbits == (size_t)-1 || wbits == (size_t)-1) { return NULL; } if (vbits + wbits > MAX_INT_SIZE) { return NULL; } } else if (PyLong_Check(v) && (PyTuple_Check(w) || PyFrozenSet_Check(w))) { Py_ssize_t size = PyTuple_Check(w) ? PyTuple_GET_SIZE(w) : PySet_GET_SIZE(w); if (size) { long n = PyLong_AsLong(v); if (n < 0 || n > MAX_COLLECTION_SIZE / size) { return NULL; } if (n && check_complexity(w, MAX_TOTAL_ITEMS / n) < 0) { return NULL; } } } else if (PyLong_Check(v) && (PyUnicode_Check(w) || PyBytes_Check(w))) { Py_ssize_t size = PyUnicode_Check(w) ? PyUnicode_GET_LENGTH(w) : PyBytes_GET_SIZE(w); if (size) { long n = PyLong_AsLong(v); if (n < 0 || n > MAX_STR_SIZE / size) { return NULL; } } } else if (PyLong_Check(w) && (PyTuple_Check(v) || PyFrozenSet_Check(v) || PyUnicode_Check(v) || PyBytes_Check(v))) { return safe_multiply(w, v); } return PyNumber_Multiply(v, w); } static PyObject * safe_power(PyObject *v, PyObject *w) { if (PyLong_Check(v) && PyLong_Check(w) && Py_SIZE(v) && Py_SIZE(w) > 0) { size_t vbits = _PyLong_NumBits(v); size_t wbits = PyLong_AsSize_t(w); if (vbits == (size_t)-1 || wbits == (size_t)-1) { return NULL; } if (vbits > MAX_INT_SIZE / wbits) { return NULL; } } return PyNumber_Power(v, w, Py_None); } static PyObject * safe_lshift(PyObject *v, PyObject *w) { if (PyLong_Check(v) && PyLong_Check(w) && Py_SIZE(v) && Py_SIZE(w)) { size_t vbits = _PyLong_NumBits(v); size_t wbits = PyLong_AsSize_t(w); if (vbits == (size_t)-1 || wbits == (size_t)-1) { return NULL; } if (wbits > MAX_INT_SIZE || vbits > MAX_INT_SIZE - wbits) { return NULL; } } return PyNumber_Lshift(v, w); } static PyObject * safe_mod(PyObject *v, PyObject *w) { if (PyUnicode_Check(v) || PyBytes_Check(v)) { return NULL; } return PyNumber_Remainder(v, w); } /* Replace LOAD_CONST c1, LOAD_CONST c2, BINOP with LOAD_CONST binop(c1,c2) The consts table must still be in list form so that the new constant can be appended. Called with codestr pointing to the BINOP. Abandons the transformation if the folding fails (i.e. 1+'a'). If the new constant is a sequence, only folds when the size is below a threshold value. That keeps pyc files from becoming large in the presence of code like: (None,)*1000. */ static Py_ssize_t fold_binops_on_constants(_Py_CODEUNIT *codestr, Py_ssize_t c_start, Py_ssize_t opcode_end, unsigned char opcode, PyObject *consts, PyObject **objs) { PyObject *newconst, *v, *w; Py_ssize_t len_consts; /* Pre-conditions */ assert(PyList_CheckExact(consts)); len_consts = PyList_GET_SIZE(consts); /* Create new constant */ v = objs[0]; w = objs[1]; switch (opcode) { case BINARY_POWER: newconst = safe_power(v, w); break; case BINARY_MULTIPLY: newconst = safe_multiply(v, w); break; case BINARY_TRUE_DIVIDE: newconst = PyNumber_TrueDivide(v, w); break; case BINARY_FLOOR_DIVIDE: newconst = PyNumber_FloorDivide(v, w); break; case BINARY_MODULO: newconst = safe_mod(v, w); break; case BINARY_ADD: newconst = PyNumber_Add(v, w); break; case BINARY_SUBTRACT: newconst = PyNumber_Subtract(v, w); break; case BINARY_SUBSCR: newconst = PyObject_GetItem(v, w); break; case BINARY_LSHIFT: newconst = safe_lshift(v, w); break; case BINARY_RSHIFT: newconst = PyNumber_Rshift(v, w); break; case BINARY_AND: newconst = PyNumber_And(v, w); break; case BINARY_XOR: newconst = PyNumber_Xor(v, w); break; case BINARY_OR: newconst = PyNumber_Or(v, w); break; default: /* Called with an unknown opcode */ PyErr_Format(PyExc_SystemError, "unexpected binary operation %d on a constant", opcode); return -1; } if (newconst == NULL) { if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) { PyErr_Clear(); } return -1; } /* Append folded constant into consts table */ if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return -1; } Py_DECREF(newconst); return copy_op_arg(codestr, c_start, LOAD_CONST, len_consts, opcode_end); } static Py_ssize_t fold_unaryops_on_constants(_Py_CODEUNIT *codestr, Py_ssize_t c_start, Py_ssize_t opcode_end, unsigned char opcode, PyObject *consts, PyObject *v) { PyObject *newconst; Py_ssize_t len_consts; /* Pre-conditions */ assert(PyList_CheckExact(consts)); len_consts = PyList_GET_SIZE(consts); /* Create new constant */ switch (opcode) { case UNARY_NEGATIVE: newconst = PyNumber_Negative(v); break; case UNARY_INVERT: newconst = PyNumber_Invert(v); break; case UNARY_POSITIVE: newconst = PyNumber_Positive(v); break; default: /* Called with an unknown opcode */ PyErr_Format(PyExc_SystemError, "unexpected unary operation %d on a constant", opcode); return -1; } if (newconst == NULL) { if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) { PyErr_Clear(); } return -1; } /* Append folded constant into consts table */ if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); PyErr_Clear(); return -1; } Py_DECREF(newconst); return copy_op_arg(codestr, c_start, LOAD_CONST, len_consts, opcode_end); } static unsigned int * markblocks(_Py_CODEUNIT *code, Py_ssize_t len) { unsigned int *blocks = PyMem_New(unsigned int, len); int i, j, opcode, blockcnt = 0; if (blocks == NULL) { PyErr_NoMemory(); return NULL; } bzero(blocks, len*sizeof(int)); /* Mark labels in the first pass */ for (i = 0; i < len; i++) { opcode = _Py_OPCODE(code[i]); switch (opcode) { case FOR_ITER: case JUMP_FORWARD: case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case JUMP_ABSOLUTE: case CONTINUE_LOOP: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: case SETUP_ASYNC_WITH: j = GETJUMPTGT(code, i); assert(j < len); blocks[j] = 1; break; } } /* Build block numbers in the second pass */ for (i = 0; i < len; i++) { blockcnt += blocks[i]; /* increment blockcnt over labels */ blocks[i] = blockcnt; } return blocks; } /* Perform basic peephole optimizations to components of a code object. The consts object should still be in list form to allow new constants to be appended. To keep the optimizer simple, it bails when the lineno table has complex encoding for gaps >= 255. Optimizations are restricted to simple transformations occurring within a single basic block. All transformations keep the code size the same or smaller. For those that reduce size, the gaps are initially filled with NOPs. Later those NOPs are removed and the jump addresses retargeted in a single pass. */ PyObject * PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names, PyObject *lnotab_obj) { Py_ssize_t h, i, nexti, op_start, codelen, tgt; unsigned int j, nops; unsigned char opcode, nextop; _Py_CODEUNIT *codestr = NULL; unsigned char *lnotab; unsigned int cum_orig_offset, last_offset; Py_ssize_t tabsiz; PyObject **const_stack = NULL; Py_ssize_t const_stack_top = -1; Py_ssize_t const_stack_size = 0; int in_consts = 0; /* whether we are in a LOAD_CONST sequence */ unsigned int *blocks = NULL; /* Bail out if an exception is set */ if (PyErr_Occurred()) goto exitError; /* Bypass optimization when the lnotab table is too complex */ assert(PyBytes_Check(lnotab_obj)); lnotab = (unsigned char*)PyBytes_AS_STRING(lnotab_obj); tabsiz = PyBytes_GET_SIZE(lnotab_obj); assert(tabsiz == 0 || Py_REFCNT(lnotab_obj) == 1); if (memchr(lnotab, 255, tabsiz) != NULL) { /* 255 value are used for multibyte bytecode instructions */ goto exitUnchanged; } /* Note: -128 and 127 special values for line number delta are ok, the peephole optimizer doesn't modify line numbers. */ assert(PyBytes_Check(code)); codelen = PyBytes_GET_SIZE(code); assert(codelen % sizeof(_Py_CODEUNIT) == 0); /* Make a modifiable copy of the code string */ codestr = (_Py_CODEUNIT *)PyMem_Malloc(codelen); if (codestr == NULL) { PyErr_NoMemory(); goto exitError; } memcpy(codestr, PyBytes_AS_STRING(code), codelen); codelen /= sizeof(_Py_CODEUNIT); blocks = markblocks(codestr, codelen); if (blocks == NULL) goto exitError; assert(PyList_Check(consts)); CONST_STACK_CREATE(); for (i=find_op(codestr, codelen, 0) ; i<codelen ; i=nexti) { opcode = _Py_OPCODE(codestr[i]); op_start = i; while (op_start >= 1 && _Py_OPCODE(codestr[op_start-1]) == EXTENDED_ARG) { op_start--; } nexti = i + 1; while (nexti < codelen && _Py_OPCODE(codestr[nexti]) == EXTENDED_ARG) nexti++; nextop = nexti < codelen ? _Py_OPCODE(codestr[nexti]) : 0; if (!in_consts) { CONST_STACK_RESET(); } in_consts = 0; switch (opcode) { /* Replace UNARY_NOT POP_JUMP_IF_FALSE with POP_JUMP_IF_TRUE */ case UNARY_NOT: if (nextop != POP_JUMP_IF_FALSE || !ISBASICBLOCK(blocks, op_start, i + 1)) break; fill_nops(codestr, op_start, i + 1); codestr[nexti] = PACKOPARG(POP_JUMP_IF_TRUE, _Py_OPARG(codestr[nexti])); break; /* not a is b --> a is not b not a in b --> a not in b not a is not b --> a is b not a not in b --> a in b */ case COMPARE_OP: j = get_arg(codestr, i); if (j < 6 || j > 9 || nextop != UNARY_NOT || !ISBASICBLOCK(blocks, op_start, i + 1)) break; codestr[i] = PACKOPARG(opcode, j^1); fill_nops(codestr, i + 1, nexti + 1); break; /* Skip over LOAD_CONST trueconst POP_JUMP_IF_FALSE xx. This improves "while 1" performance. */ case LOAD_CONST: CONST_STACK_PUSH_OP(i); if (nextop != POP_JUMP_IF_FALSE || !ISBASICBLOCK(blocks, op_start, i + 1) || !PyObject_IsTrue(PyList_GET_ITEM(consts, get_arg(codestr, i)))) break; fill_nops(codestr, op_start, nexti + 1); CONST_STACK_POP(1); break; /* Try to fold tuples of constants (includes a case for lists and sets which are only used for "in" and "not in" tests). Skip over BUILD_SEQN 1 UNPACK_SEQN 1. Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ case BUILD_TUPLE: case BUILD_LIST: case BUILD_SET: j = get_arg(codestr, i); if (j > 0 && CONST_STACK_LEN() >= j) { h = lastn_const_start(codestr, op_start, j); if ((opcode == BUILD_TUPLE && ISBASICBLOCK(blocks, h, op_start)) || ((opcode == BUILD_LIST || opcode == BUILD_SET) && ((nextop==COMPARE_OP && (_Py_OPARG(codestr[nexti]) == PyCmp_IN || _Py_OPARG(codestr[nexti]) == PyCmp_NOT_IN)) || nextop == GET_ITER) && ISBASICBLOCK(blocks, h, i + 1))) { h = fold_tuple_on_constants(codestr, h, i + 1, opcode, consts, CONST_STACK_LASTN(j), j); if (h >= 0) { CONST_STACK_POP(j); CONST_STACK_PUSH_OP(h); } break; } } if (nextop != UNPACK_SEQUENCE || !ISBASICBLOCK(blocks, op_start, i + 1) || j != get_arg(codestr, nexti) || opcode == BUILD_SET) break; if (j < 2) { fill_nops(codestr, op_start, nexti + 1); } else if (j == 2) { codestr[op_start] = PACKOPARG(ROT_TWO, 0); fill_nops(codestr, op_start + 1, nexti + 1); CONST_STACK_RESET(); } else if (j == 3) { codestr[op_start] = PACKOPARG(ROT_THREE, 0); codestr[op_start + 1] = PACKOPARG(ROT_TWO, 0); fill_nops(codestr, op_start + 2, nexti + 1); CONST_STACK_RESET(); } break; /* Fold binary ops on constants. LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ case BINARY_POWER: case BINARY_MULTIPLY: case BINARY_TRUE_DIVIDE: case BINARY_FLOOR_DIVIDE: case BINARY_MODULO: case BINARY_ADD: case BINARY_SUBTRACT: case BINARY_SUBSCR: case BINARY_LSHIFT: case BINARY_RSHIFT: case BINARY_AND: case BINARY_XOR: case BINARY_OR: if (CONST_STACK_LEN() < 2) break; h = lastn_const_start(codestr, op_start, 2); if (ISBASICBLOCK(blocks, h, op_start)) { h = fold_binops_on_constants(codestr, h, i + 1, opcode, consts, CONST_STACK_LASTN(2)); if (h >= 0) { CONST_STACK_POP(2); CONST_STACK_PUSH_OP(h); } } break; /* Fold unary ops on constants. LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ case UNARY_NEGATIVE: case UNARY_INVERT: case UNARY_POSITIVE: if (CONST_STACK_LEN() < 1) break; h = lastn_const_start(codestr, op_start, 1); if (ISBASICBLOCK(blocks, h, op_start)) { h = fold_unaryops_on_constants(codestr, h, i + 1, opcode, consts, *CONST_STACK_LASTN(1)); if (h >= 0) { CONST_STACK_POP(1); CONST_STACK_PUSH_OP(h); } } break; /* Simplify conditional jump to conditional jump where the result of the first test implies the success of a similar test or the failure of the opposite test. Arises in code like: "if a and b:" "if a or b:" "a and b or c" "(a and b) and c" x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z --> x:JUMP_IF_FALSE_OR_POP z x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z --> x:POP_JUMP_IF_FALSE y+1 where y+1 is the instruction following the second test. */ case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: h = get_arg(codestr, i) / sizeof(_Py_CODEUNIT); tgt = find_op(codestr, codelen, h); j = _Py_OPCODE(codestr[tgt]); if (CONDITIONAL_JUMP(j)) { /* NOTE: all possible jumps here are absolute. */ if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { /* The second jump will be taken iff the first is. The current opcode inherits its target's stack effect */ h = set_arg(codestr, i, get_arg(codestr, tgt)); } else { /* The second jump is not taken if the first is (so jump past it), and all conditional jumps pop their argument when they're not taken (so change the first jump to pop its argument when it's taken). */ h = set_arg(codestr, i, (tgt + 1) * sizeof(_Py_CODEUNIT)); j = opcode == JUMP_IF_TRUE_OR_POP ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE; } if (h >= 0) { nexti = h; codestr[nexti] = PACKOPARG(j, _Py_OPARG(codestr[nexti])); break; } } /* Intentional fallthrough */ /* Replace jumps to unconditional jumps */ case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case FOR_ITER: case JUMP_FORWARD: case JUMP_ABSOLUTE: case CONTINUE_LOOP: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: case SETUP_ASYNC_WITH: h = GETJUMPTGT(codestr, i); tgt = find_op(codestr, codelen, h); /* Replace JUMP_* to a RETURN into just a RETURN */ if (UNCONDITIONAL_JUMP(opcode) && _Py_OPCODE(codestr[tgt]) == RETURN_VALUE) { codestr[op_start] = PACKOPARG(RETURN_VALUE, 0); fill_nops(codestr, op_start + 1, i + 1); } else if (UNCONDITIONAL_JUMP(_Py_OPCODE(codestr[tgt]))) { j = GETJUMPTGT(codestr, tgt); if (opcode == JUMP_FORWARD) { /* JMP_ABS can go backwards */ opcode = JUMP_ABSOLUTE; } else if (!ABSOLUTE_JUMP(opcode)) { if ((Py_ssize_t)j < i + 1) { break; /* No backward relative jumps */ } j -= i + 1; /* Calc relative jump addr */ } j *= sizeof(_Py_CODEUNIT); copy_op_arg(codestr, op_start, opcode, j, i + 1); } break; /* Remove unreachable ops after RETURN */ case RETURN_VALUE: h = i + 1; while (h < codelen && ISBASICBLOCK(blocks, i, h)) { h++; } if (h > i + 1) { fill_nops(codestr, i + 1, h); nexti = find_op(codestr, codelen, h); } break; } } /* Fixup lnotab */ for (i = 0, nops = 0; i < codelen; i++) { assert(i - nops <= INT_MAX); /* original code offset => new code offset */ blocks[i] = i - nops; if (_Py_OPCODE(codestr[i]) == NOP) nops++; } cum_orig_offset = 0; last_offset = 0; for (i=0 ; i < tabsiz ; i+=2) { unsigned int offset_delta, new_offset; cum_orig_offset += lnotab[i]; assert(cum_orig_offset % sizeof(_Py_CODEUNIT) == 0); new_offset = blocks[cum_orig_offset / sizeof(_Py_CODEUNIT)] * sizeof(_Py_CODEUNIT); offset_delta = new_offset - last_offset; assert(offset_delta <= 255); lnotab[i] = (unsigned char)offset_delta; last_offset = new_offset; } /* Remove NOPs and fixup jump targets */ for (op_start = i = h = 0; i < codelen; i++, op_start = i) { j = _Py_OPARG(codestr[i]); while (_Py_OPCODE(codestr[i]) == EXTENDED_ARG) { i++; j = j<<8 | _Py_OPARG(codestr[i]); } opcode = _Py_OPCODE(codestr[i]); switch (opcode) { case NOP:continue; case JUMP_ABSOLUTE: case CONTINUE_LOOP: case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: j = blocks[j / sizeof(_Py_CODEUNIT)] * sizeof(_Py_CODEUNIT); break; case FOR_ITER: case JUMP_FORWARD: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: case SETUP_ASYNC_WITH: j = blocks[j / sizeof(_Py_CODEUNIT) + i + 1] - blocks[i] - 1; j *= sizeof(_Py_CODEUNIT); break; } nexti = i - op_start + 1; if (instrsize(j) > nexti) goto exitUnchanged; /* If instrsize(j) < nexti, we'll emit EXTENDED_ARG 0 */ write_op_arg(codestr + h, opcode, j, nexti); h += nexti; } assert(h + (Py_ssize_t)nops == codelen); CONST_STACK_DELETE(); PyMem_Free(blocks); code = PyBytes_FromStringAndSize((char *)codestr, h * sizeof(_Py_CODEUNIT)); PyMem_Free(codestr); return code; exitError: code = NULL; exitUnchanged: Py_XINCREF(code); CONST_STACK_DELETE(); PyMem_Free(blocks); PyMem_Free(codestr); return code; }
32,885
926
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/sigcheck.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/intrcheck.h" #include "third_party/python/Include/pyerrors.h" /* clang-format off */ /* Sigcheck is similar to intrcheck() but sets an exception when an interrupt occurs. It can't be in the intrcheck.c file since that file (and the whole directory it is in) doesn't know about objects or exceptions. It can't be in errors.c because it can be overridden (at link time) by a more powerful version implemented in signalmodule.c. */ #pragma weak PyErr_CheckSignals /* ARGSUSED */ int PyErr_CheckSignals(void) { if (!PyOS_InterruptOccurred()) return 0; PyErr_SetNone(PyExc_KeyboardInterrupt); return -1; }
1,479
29
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/xtermmodule.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ PYTHON_PROVIDE("xterm"); PYTHON_PROVIDE("xterm.rgb2xterm256"); PyDoc_STRVAR(xterm_doc, "Xterm Module\n\ \n\ This module exposes low-level utilities for xterm ansi encoding."); PyDoc_STRVAR(rgb2xterm256_doc, "rgb2xterm256($module, r, g, b)\n\ --\n\n\ Quantizes RGB to color to XTERM256 ANSI terminal code.\n\ \n\ This helps you print colors in the terminal faster. For example:\n\ \n\ print(\"\\x1b[38;5;%dmhello\\x1b[0m\" % (xterm.rgb2xterm256(255,0,0)))\n\ \n\ Will print red text to the terminal."); static PyObject * xterm_rgb2xterm256(PyObject *self, PyObject *args) { unsigned char r, g, b; int res, cerr, gerr, ir, ig, ib, gray, grai, cr, cg, cb, gv; const unsigned char kXtermCube[6] = {0, 0137, 0207, 0257, 0327, 0377}; if (!PyArg_ParseTuple(args, "BBB:rgb2xterm256", &r, &g, &b)) return 0; gray = round(r * .299 + g * .587 + b * .114); grai = gray > 238 ? 23 : (gray - 3) / 10; ir = r < 48 ? 0 : r < 115 ? 1 : (r - 35) / 40; ig = g < 48 ? 0 : g < 115 ? 1 : (g - 35) / 40; ib = b < 48 ? 0 : b < 115 ? 1 : (b - 35) / 40; cr = kXtermCube[ir]; cg = kXtermCube[ig]; cb = kXtermCube[ib]; gv = 8 + 10 * grai; cerr = (cr-r)*(cr-r) + (cg-g)*(cg-g) + (cb-b)*(cb-b); gerr = (gv-r)*(gv-r) + (gv-g)*(gv-g) + (gv-b)*(gv-b); if (cerr <= gerr) { res = 16 + 36 * ir + 6 * ig + ib; } else { res = 232 + grai; } return PyLong_FromUnsignedLong(res); } static PyMethodDef xterm_methods[] = { {"rgb2xterm256", xterm_rgb2xterm256, METH_VARARGS, rgb2xterm256_doc}, {0}, }; static struct PyModuleDef xtermmodule = { PyModuleDef_HEAD_INIT, "xterm", xterm_doc, -1, xterm_methods, }; PyMODINIT_FUNC PyInit_xterm(void) { return PyModule_Create(&xtermmodule); } _Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_xterm = { "xterm", PyInit_xterm, };
4,116
96
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/finalize.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/yoink.h" #include "third_party/python/pyconfig.h" /* clang-format off */ /* Undo the effect of Py_Initialize(). Beware: if multiple interpreter and/or thread states exist, these are not wiped out; only the current thread and interpreter state are deleted. But since everything else is deleted, those other interpreter and thread states should no longer be used. (XXX We should do better, e.g. wipe out all interpreters and threads.) Locking: as above. */ #ifdef WITH_THREAD extern void wait_for_thread_shutdown(void); extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *); extern void _PyGILState_Fini(void); #endif /* WITH_THREAD */ int Py_FinalizeEx(void) { PyInterpreterState *interp; PyThreadState *tstate; int status = 0; if (!_Py_initialized) return status; #ifdef WITH_THREAD wait_for_thread_shutdown(); #endif /* The interpreter is still entirely intact at this point, and the * exit funcs may be relying on that. In particular, if some thread * or exit func is still waiting to do an import, the import machinery * expects Py_IsInitialized() to return true. So don't say the * interpreter is uninitialized until after the exit funcs have run. * Note that Threading.py uses an exit func to do a join on all the * threads created thru it, so this also protects pending imports in * the threads created via Threading. */ _Py_CallExitFuncs(); /* Get current thread state and interpreter pointer */ tstate = PyThreadState_GET(); interp = tstate->interp; /* Remaining threads (e.g. daemon threads) will automatically exit after taking the GIL (in PyEval_RestoreThread()). */ _Py_Finalizing = tstate; _Py_initialized = 0; /* Flush sys.stdout and sys.stderr */ if (_Py_FlushStdFiles() < 0) { status = -1; } /* Disable signal handling */ PyOS_FiniInterrupts(); /* Collect garbage. This may call finalizers; it's nice to call these * before all modules are destroyed. * XXX If a __del__ or weakref callback is triggered here, and tries to * XXX import a module, bad things can happen, because Python no * XXX longer believes it's initialized. * XXX Fatal Python error: Interpreter not initialized (version mismatch?) * XXX is easy to provoke that way. I've also seen, e.g., * XXX Exception exceptions.ImportError: 'No module named sha' * XXX in <function callback at 0x008F5718> ignored * XXX but I'm unclear on exactly how that one happens. In any case, * XXX I haven't seen a real-life report of either of these. */ _PyGC_CollectIfEnabled(); #ifdef COUNT_ALLOCS /* With COUNT_ALLOCS, it helps to run GC multiple times: each collection might release some types from the type list, so they become garbage. */ while (_PyGC_CollectIfEnabled() > 0) /* nothing */; #endif /* Destroy all modules */ PyImport_Cleanup(); _PyImportLookupTables_Cleanup(); /* Flush sys.stdout and sys.stderr (again, in case more was printed) */ if (_Py_FlushStdFiles() < 0) { status = -1; } /* Collect final garbage. This disposes of cycles created by * class definitions, for example. * XXX This is disabled because it caused too many problems. If * XXX a __del__ or weakref callback triggers here, Python code has * XXX a hard time running, because even the sys module has been * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc). * XXX One symptom is a sequence of information-free messages * XXX coming from threads (if a __del__ or callback is invoked, * XXX other threads can execute too, and any exception they encounter * XXX triggers a comedy of errors as subsystem after subsystem * XXX fails to find what it *expects* to find in sys to help report * XXX the exception and consequent unexpected failures). I've also * XXX seen segfaults then, after adding print statements to the * XXX Python code getting called. */ #if 0 _PyGC_CollectIfEnabled(); #endif #if IsModeDbg() /* Disable tracemalloc after all Python objects have been destroyed, so it is possible to use tracemalloc in objects destructor. */ _PyTraceMalloc_Fini(); #endif /* Destroy the database used by _PyImport_{Fixup,Find}Extension */ _PyImport_Fini(); /* Cleanup typeobject.c's internal caches. */ _PyType_Fini(); /* unload faulthandler module */ _PyFaulthandler_Fini(); /* Debugging stuff */ #ifdef COUNT_ALLOCS dump_counts(stderr); #endif /* dump hash stats */ _PyHash_Fini(); _PY_DEBUG_PRINT_TOTAL_REFS(); #ifdef Py_TRACE_REFS /* Display all objects still alive -- this can invoke arbitrary * __repr__ overrides, so requires a mostly-intact interpreter. * Alas, a lot of stuff may still be alive now that will be cleaned * up later. */ if (Py_GETENV("PYTHONDUMPREFS")) _Py_PrintReferences(stderr); #endif /* Py_TRACE_REFS */ /* Clear interpreter state and all thread states. */ PyInterpreterState_Clear(interp); /* Now we decref the exception classes. After this point nothing can raise an exception. That's okay, because each Fini() method below has been checked to make sure no exceptions are ever raised. */ _PyExc_Fini(); /* Sundry finalizers */ PyMethod_Fini(); PyFrame_Fini(); PyCFunction_Fini(); PyTuple_Fini(); PyList_Fini(); PySet_Fini(); PyBytes_Fini(); PyByteArray_Fini(); PyLong_Fini(); PyFloat_Fini(); PyDict_Fini(); PySlice_Fini(); _PyGC_Fini(); _PyRandom_Fini(); _PyArg_Fini(); PyAsyncGen_Fini(); /* Cleanup Unicode implementation */ _PyUnicode_Fini(); /* reset file system default encoding */ if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) { PyMem_RawFree((char*)Py_FileSystemDefaultEncoding); Py_FileSystemDefaultEncoding = NULL; } /* XXX Still allocated: - various static ad-hoc pointers to interned strings - int and float free list blocks - whatever various modules and libraries allocate */ PyGrammar_RemoveAccelerators(&_PyParser_Grammar); /* Cleanup auto-thread-state */ #ifdef WITH_THREAD _PyGILState_Fini(); #endif /* WITH_THREAD */ /* Delete current thread. After this, many C API calls become crashy. */ PyThreadState_Swap(NULL); PyInterpreterState_Delete(interp); #ifdef Py_TRACE_REFS /* Display addresses (& refcnts) of all objects still alive. * An address can be used to find the repr of the object, printed * above by _Py_PrintReferences. */ if (Py_GETENV("PYTHONDUMPREFS")) _Py_PrintReferenceAddresses(stderr); #endif /* Py_TRACE_REFS */ #ifdef WITH_PYMALLOC #if IsModeDbg() if (_PyMem_PymallocEnabled()) { char *opt = Py_GETENV("PYTHONMALLOCSTATS"); if (opt != NULL && *opt != '\0') _PyObject_DebugMallocStats(stderr); } #endif #endif _Py_CallLlExitFuncs(); return status; } void Py_Finalize(void) { Py_FinalizeEx(); }
8,641
247
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/initsigs.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/sysv/consts/sig.h" #include "third_party/python/Include/intrcheck.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ void _Py_InitSigs(void) { #ifdef SIGPIPE PyOS_setsig(SIGPIPE, SIG_IGN); #endif #ifdef SIGXFZ PyOS_setsig(SIGXFZ, SIG_IGN); #endif #ifdef SIGXFSZ PyOS_setsig(SIGXFSZ, SIG_IGN); #endif PyOS_InitInterrupts(); /* May imply initsignal() */ if (PyErr_Occurred()) { Py_FatalError("Py_Initialize: can't import signal"); } }
1,403
31
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/import.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/stat.macros.h" #include "libc/fmt/conv.h" #include "libc/intrin/bits.h" #include "libc/macros.internal.h" #include "libc/mem/alg.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/s.h" #include "libc/x/x.h" #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bltinmodule.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/errcode.h" #include "third_party/python/Include/eval.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/marshal.h" #include "third_party/python/Include/memoryobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/osdefs.h" #include "third_party/python/Include/osmodule.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Include/weakrefobject.h" #include "third_party/python/Include/yoink.h" #include "third_party/python/Python/importdl.h" /* clang-format off */ PYTHON_PROVIDE("_imp"); PYTHON_PROVIDE("_imp.__doc__"); PYTHON_PROVIDE("_imp.__loader__"); PYTHON_PROVIDE("_imp.__name__"); PYTHON_PROVIDE("_imp.__package__"); PYTHON_PROVIDE("_imp.__spec__"); PYTHON_PROVIDE("_imp._fix_co_filename"); PYTHON_PROVIDE("_imp.acquire_lock"); PYTHON_PROVIDE("_imp.create_builtin"); PYTHON_PROVIDE("_imp.create_dynamic"); PYTHON_PROVIDE("_imp.exec_builtin"); PYTHON_PROVIDE("_imp.exec_dynamic"); PYTHON_PROVIDE("_imp.extension_suffixes"); PYTHON_PROVIDE("_imp.get_frozen_object"); PYTHON_PROVIDE("_imp.init_frozen"); PYTHON_PROVIDE("_imp.is_builtin"); PYTHON_PROVIDE("_imp.is_frozen"); PYTHON_PROVIDE("_imp.is_frozen_package"); PYTHON_PROVIDE("_imp.lock_held"); PYTHON_PROVIDE("_imp.release_lock"); PYTHON_PROVIDE("_imp._path_is_mode_type"); PYTHON_PROVIDE("_imp._path_isfile"); PYTHON_PROVIDE("_imp._path_isdir"); PYTHON_PROVIDE("_imp._calc_mode"); #define CACHEDIR "__pycache__" /* See _PyImport_FixupExtensionObject() below */ static PyObject *extensions = NULL; static PyObject *initstr = NULL; /*[clinic input] module _imp [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/ #include "third_party/python/Python/clinic/import.inc" /* Initialize things */ typedef struct { const char *name; union { const struct _inittab *tab; const struct _frozen *frz; }; } initentry; typedef struct { size_t n; initentry *entries; } Lookup; static Lookup Builtins_Lookup = {.n = 0, .entries = NULL}; static Lookup Frozens_Lookup = {.n = 0, .entries = NULL}; static int cmp_initentry(const void *_x, const void *_y) { const initentry *x = _x; const initentry *y = _y; return strcmp(x->name, y->name); } void _PyImport_Init(void) { PyInterpreterState *interp = PyThreadState_Get()->interp; initstr = PyUnicode_InternFromString("__init__"); if (initstr == NULL) Py_FatalError("Can't initialize import variables"); interp->builtins_copy = PyDict_Copy(interp->builtins); if (interp->builtins_copy == NULL) Py_FatalError("Can't backup builtins dict"); } void _PyImportLookupTables_Init(void) { size_t i, n; if (Builtins_Lookup.entries == NULL) { for(n=0; PyImport_Inittab[n].name; n++); Builtins_Lookup.n = n; Builtins_Lookup.entries = malloc(sizeof(initentry) * n); for(i=0; i < n; i++) { Builtins_Lookup.entries[i].name = PyImport_Inittab[i].name; Builtins_Lookup.entries[i].tab = &(PyImport_Inittab[i]); } qsort(Builtins_Lookup.entries, Builtins_Lookup.n, sizeof(initentry), cmp_initentry); } if (Frozens_Lookup.entries == NULL) { for(n=0; PyImport_FrozenModules[n].name; n++); Frozens_Lookup.n = n; Frozens_Lookup.entries = malloc(sizeof(initentry) * n); for(i=0; i<n; i++) { Frozens_Lookup.entries[i].name = PyImport_FrozenModules[i].name; Frozens_Lookup.entries[i].frz = &(PyImport_FrozenModules[i]); } qsort(Frozens_Lookup.entries, Frozens_Lookup.n, sizeof(initentry), cmp_initentry); } } void _PyImportLookupTables_Cleanup(void) { if (Builtins_Lookup.entries != NULL) { free(Builtins_Lookup.entries); Builtins_Lookup.entries = NULL; } if (Frozens_Lookup.entries != NULL) { free(Frozens_Lookup.entries); Frozens_Lookup.entries = NULL; } } void _PyImportHooks_Init(void) { PyObject *v, *path_hooks = NULL; int err = 0; /* adding sys.path_hooks and sys.path_importer_cache */ v = PyList_New(0); if (v == NULL) goto error; err = PySys_SetObject("meta_path", v); Py_DECREF(v); if (err) goto error; v = PyDict_New(); if (v == NULL) goto error; err = PySys_SetObject("path_importer_cache", v); Py_DECREF(v); if (err) goto error; path_hooks = PyList_New(0); if (path_hooks == NULL) goto error; err = PySys_SetObject("path_hooks", path_hooks); if (err) { error: PyErr_Print(); Py_FatalError("initializing sys.meta_path, sys.path_hooks, " "or path_importer_cache failed"); } Py_DECREF(path_hooks); } void _PyImportZip_Init(void) { PyObject *path_hooks, *zimpimport; int err = 0; path_hooks = PySys_GetObject("path_hooks"); if (path_hooks == NULL) { PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks"); goto error; } if (Py_VerboseFlag) PySys_WriteStderr("# installing zipimport hook\n"); zimpimport = PyImport_ImportModule("zipimport"); if (zimpimport == NULL) { PyErr_Clear(); /* No zip import module -- okay */ if (Py_VerboseFlag) PySys_WriteStderr("# can't import zipimport\n"); } else { _Py_IDENTIFIER(zipimporter); PyObject *zipimporter = _PyObject_GetAttrId(zimpimport, &PyId_zipimporter); Py_DECREF(zimpimport); if (zipimporter == NULL) { PyErr_Clear(); /* No zipimporter object -- okay */ if (Py_VerboseFlag) PySys_WriteStderr( "# can't import zipimport.zipimporter\n"); } else { /* sys.path_hooks.append(zipimporter) */ /* add this hook in case of import from external zip */ err = PyList_Append(path_hooks, zipimporter); Py_DECREF(zipimporter); if (err < 0) { goto error; } if (Py_VerboseFlag) PySys_WriteStderr( "# installed zipimport hook\n"); } } return; error: PyErr_Print(); Py_FatalError("initializing zipimport failed"); } /* Locking primitives to prevent parallel imports of the same module in different threads to return with a partially loaded module. These calls are serialized by the global interpreter lock. */ #ifdef WITH_THREAD #include "third_party/python/Include/pythread.h" static PyThread_type_lock import_lock = 0; static long import_lock_thread = -1; static int import_lock_level = 0; void _PyImport_AcquireLock(void) { long me = PyThread_get_thread_ident(); if (me == -1) return; /* Too bad */ if (import_lock == NULL) { import_lock = PyThread_allocate_lock(); if (import_lock == NULL) return; /* Nothing much we can do. */ } if (import_lock_thread == me) { import_lock_level++; return; } if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) { PyThreadState *tstate = PyEval_SaveThread(); PyThread_acquire_lock(import_lock, 1); PyEval_RestoreThread(tstate); } assert(import_lock_level == 0); import_lock_thread = me; import_lock_level = 1; } int _PyImport_ReleaseLock(void) { long me = PyThread_get_thread_ident(); if (me == -1 || import_lock == NULL) return 0; /* Too bad */ if (import_lock_thread != me) return -1; import_lock_level--; assert(import_lock_level >= 0); if (import_lock_level == 0) { import_lock_thread = -1; PyThread_release_lock(import_lock); } return 1; } /* This function is called from PyOS_AfterFork to ensure that newly created child processes do not share locks with the parent. We now acquire the import lock around fork() calls but on some platforms (Solaris 9 and earlier? see isue7242) that still left us with problems. */ void _PyImport_ReInitLock(void) { if (import_lock != NULL) { import_lock = PyThread_allocate_lock(); if (import_lock == NULL) { Py_FatalError("PyImport_ReInitLock failed to create a new lock"); } } if (import_lock_level > 1) { /* Forked as a side effect of import */ long me = PyThread_get_thread_ident(); /* The following could fail if the lock is already held, but forking as a side-effect of an import is a) rare, b) nuts, and c) difficult to do thanks to the lock only being held when doing individual module locks per import. */ PyThread_acquire_lock(import_lock, NOWAIT_LOCK); import_lock_thread = me; import_lock_level--; } else { import_lock_thread = -1; import_lock_level = 0; } } #endif /*[clinic input] _imp.lock_held Return True if the import lock is currently held, else False. On platforms without threads, return False. [clinic start generated code]*/ static PyObject * _imp_lock_held_impl(PyObject *module) /*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/ { #ifdef WITH_THREAD return PyBool_FromLong(import_lock_thread != -1); #else return PyBool_FromLong(0); #endif } /*[clinic input] _imp.acquire_lock Acquires the interpreter's import lock for the current thread. This lock should be used by import hooks to ensure thread-safety when importing modules. On platforms without threads, this function does nothing. [clinic start generated code]*/ static PyObject * _imp_acquire_lock_impl(PyObject *module) /*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/ { #ifdef WITH_THREAD _PyImport_AcquireLock(); #endif Py_INCREF(Py_None); return Py_None; } /*[clinic input] _imp.release_lock Release the interpreter's import lock. On platforms without threads, this function does nothing. [clinic start generated code]*/ static PyObject * _imp_release_lock_impl(PyObject *module) /*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/ { #ifdef WITH_THREAD if (_PyImport_ReleaseLock() < 0) { PyErr_SetString(PyExc_RuntimeError, "not holding the import lock"); return NULL; } #endif Py_INCREF(Py_None); return Py_None; } void _PyImport_Fini(void) { Py_CLEAR(extensions); #ifdef WITH_THREAD if (import_lock != NULL) { PyThread_free_lock(import_lock); import_lock = NULL; } #endif } /* Helper for sys */ PyObject * PyImport_GetModuleDict(void) { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->modules == NULL) Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); return interp->modules; } /* List of names to clear in sys */ static const char * const sys_deletes[] = { "path", "argv", "ps1", "ps2", "last_type", "last_value", "last_traceback", "path_hooks", "path_importer_cache", "meta_path", "__interactivehook__", /* misc stuff */ "flags", "float_info", NULL }; static const char * const sys_files[] = { "stdin", "__stdin__", "stdout", "__stdout__", "stderr", "__stderr__", NULL }; /* Un-initialize things, as good as we can */ void PyImport_Cleanup(void) { Py_ssize_t pos; PyObject *key, *value, *dict; PyInterpreterState *interp = PyThreadState_GET()->interp; PyObject *modules = interp->modules; PyObject *weaklist = NULL; const char * const *p; if (modules == NULL) return; /* Already done */ /* Delete some special variables first. These are common places where user values hide and people complain when their destructors fail. Since the modules containing them are deleted *last* of all, they would come too late in the normal destruction order. Sigh. */ /* XXX Perhaps these precautions are obsolete. Who knows? */ if (Py_VerboseFlag) PySys_WriteStderr("# clear builtins._\n"); if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) { PyErr_Clear(); } for (p = sys_deletes; *p != NULL; p++) { if (Py_VerboseFlag) PySys_WriteStderr("# clear sys.%s\n", *p); if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) { PyErr_Clear(); } } for (p = sys_files; *p != NULL; p+=2) { if (Py_VerboseFlag) PySys_WriteStderr("# restore sys.%s\n", *p); value = PyDict_GetItemString(interp->sysdict, *(p+1)); if (value == NULL) value = Py_None; if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) { PyErr_Clear(); } } /* We prepare a list which will receive (name, weakref) tuples of modules when they are removed from sys.modules. The name is used for diagnosis messages (in verbose mode), while the weakref helps detect those modules which have been held alive. */ weaklist = PyList_New(0); if (weaklist == NULL) PyErr_Clear(); #define STORE_MODULE_WEAKREF(name, mod) \ if (weaklist != NULL) { \ PyObject *wr = PyWeakref_NewRef(mod, NULL); \ if (wr) { \ PyObject *tup = PyTuple_Pack(2, name, wr); \ if (!tup || PyList_Append(weaklist, tup) < 0) { \ PyErr_Clear(); \ } \ Py_XDECREF(tup); \ Py_DECREF(wr); \ } \ else { \ PyErr_Clear(); \ } \ } /* Remove all modules from sys.modules, hoping that garbage collection can reclaim most of them. */ pos = 0; while (PyDict_Next(modules, &pos, &key, &value)) { if (PyModule_Check(value)) { if (Py_VerboseFlag && PyUnicode_Check(key)) PySys_FormatStderr("# cleanup[2] removing %U\n", key); STORE_MODULE_WEAKREF(key, value); if (PyDict_SetItem(modules, key, Py_None) < 0) { PyErr_Clear(); } } } /* Clear the modules dict. */ PyDict_Clear(modules); /* Restore the original builtins dict, to ensure that any user data gets cleared. */ dict = PyDict_Copy(interp->builtins); if (dict == NULL) PyErr_Clear(); PyDict_Clear(interp->builtins); if (PyDict_Update(interp->builtins, interp->builtins_copy)) PyErr_Clear(); Py_XDECREF(dict); /* Clear module dict copies stored in the interpreter state */ _PyState_ClearModules(); /* Collect references */ _PyGC_CollectNoFail(); /* Dump GC stats before it's too late, since it uses the warnings machinery. */ _PyGC_DumpShutdownStats(); /* Now, if there are any modules left alive, clear their globals to minimize potential leaks. All C extension modules actually end up here, since they are kept alive in the interpreter state. The special treatment of "builtins" here is because even when it's not referenced as a module, its dictionary is referenced by almost every module's __builtins__. Since deleting a module clears its dictionary (even if there are references left to it), we need to delete the "builtins" module last. Likewise, we don't delete sys until the very end because it is implicitly referenced (e.g. by print). */ if (weaklist != NULL) { Py_ssize_t i, n; n = PyList_GET_SIZE(weaklist); for (i = 0; i < n; i++) { PyObject *tup = PyList_GET_ITEM(weaklist, i); PyObject *name = PyTuple_GET_ITEM(tup, 0); PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1)); if (mod == Py_None) continue; assert(PyModule_Check(mod)); dict = PyModule_GetDict(mod); if (dict == interp->builtins || dict == interp->sysdict) continue; Py_INCREF(mod); if (Py_VerboseFlag && PyUnicode_Check(name)) PySys_FormatStderr("# cleanup[3] wiping %U\n", name); _PyModule_Clear(mod); Py_DECREF(mod); } Py_DECREF(weaklist); } /* Next, delete sys and builtins (in that order) */ if (Py_VerboseFlag) PySys_FormatStderr("# cleanup[3] wiping sys\n"); _PyModule_ClearDict(interp->sysdict); if (Py_VerboseFlag) PySys_FormatStderr("# cleanup[3] wiping builtins\n"); _PyModule_ClearDict(interp->builtins); /* Clear and delete the modules directory. Actual modules will still be there only if imported during the execution of some destructor. */ interp->modules = NULL; Py_DECREF(modules); /* Once more */ _PyGC_CollectNoFail(); #undef CLEAR_MODULE #undef STORE_MODULE_WEAKREF } /* Helper for pythonrun.c -- return magic number and tag. */ long PyImport_GetMagicNumber(void) { static char raw_magic_number[4] = {0, 0, '\r', '\n'}; WRITE16LE(raw_magic_number, 3390); /* so many indirections for a single constant */ /* PyInterpreterState *interp = PyThreadState_Get()->interp; PyObject *external, *pyc_magic; external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external"); if (external == NULL) return -1; pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER"); Py_DECREF(external); if (pyc_magic == NULL) return -1; res = PyLong_AsLong(pyc_magic); Py_DECREF(pyc_magic); */ return (long)READ32LE(raw_magic_number); } extern const char * _PySys_ImplCacheTag; const char * PyImport_GetMagicTag(void) { return _PySys_ImplCacheTag; } /* Magic for extension modules (built-in as well as dynamically loaded). To prevent initializing an extension module more than once, we keep a static dictionary 'extensions' keyed by the tuple (module name, module name) (for built-in modules) or by (filename, module name) (for dynamically loaded modules), containing these modules. A copy of the module's dictionary is stored by calling _PyImport_FixupExtensionObject() immediately after the module initialization function succeeds. A copy can be retrieved from there by calling _PyImport_FindExtensionObject(). Modules which do support multiple initialization set their m_size field to a non-negative number (indicating the size of the module-specific state). They are still recorded in the extensions dictionary, to avoid loading shared libraries twice. */ int _PyImport_FixupExtensionObject(PyObject *mod, PyObject *name, PyObject *filename) { PyObject *modules, *dict, *key; struct PyModuleDef *def; int res; if (extensions == NULL) { extensions = PyDict_New(); if (extensions == NULL) return -1; } if (mod == NULL || !PyModule_Check(mod)) { PyErr_BadInternalCall(); return -1; } def = PyModule_GetDef(mod); if (!def) { PyErr_BadInternalCall(); return -1; } modules = PyImport_GetModuleDict(); if (PyDict_SetItem(modules, name, mod) < 0) return -1; if (_PyState_AddModule(mod, def) < 0) { PyDict_DelItem(modules, name); return -1; } if (def->m_size == -1) { if (def->m_base.m_copy) { /* Somebody already imported the module, likely under a different name. XXX this should really not happen. */ Py_CLEAR(def->m_base.m_copy); } dict = PyModule_GetDict(mod); if (dict == NULL) return -1; def->m_base.m_copy = PyDict_Copy(dict); if (def->m_base.m_copy == NULL) return -1; } key = PyTuple_Pack(2, filename, name); if (key == NULL) return -1; res = PyDict_SetItem(extensions, key, (PyObject *)def); Py_DECREF(key); if (res < 0) return -1; return 0; } int _PyImport_FixupBuiltin(PyObject *mod, const char *name) { int res; PyObject *nameobj; nameobj = PyUnicode_InternFromString(name); if (nameobj == NULL) return -1; res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj); Py_DECREF(nameobj); return res; } PyObject * _PyImport_FindExtensionObject(PyObject *name, PyObject *filename) { PyObject *mod, *mdict, *key; PyModuleDef* def; if (extensions == NULL) return NULL; key = PyTuple_Pack(2, filename, name); if (key == NULL) return NULL; def = (PyModuleDef *)PyDict_GetItem(extensions, key); Py_DECREF(key); if (def == NULL) return NULL; if (def->m_size == -1) { /* Module does not support repeated initialization */ if (def->m_base.m_copy == NULL) return NULL; mod = PyImport_AddModuleObject(name); if (mod == NULL) return NULL; mdict = PyModule_GetDict(mod); if (mdict == NULL) return NULL; if (PyDict_Update(mdict, def->m_base.m_copy)) return NULL; } else { if (def->m_base.m_init == NULL) return NULL; mod = def->m_base.m_init(); if (mod == NULL) return NULL; if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) { Py_DECREF(mod); return NULL; } Py_DECREF(mod); } if (_PyState_AddModule(mod, def) < 0) { PyDict_DelItem(PyImport_GetModuleDict(), name); Py_DECREF(mod); return NULL; } if (Py_VerboseFlag) PySys_FormatStderr("import %U # previously loaded (%R)\n", name, filename); return mod; } PyObject * _PyImport_FindBuiltin(const char *name) { PyObject *res, *nameobj; nameobj = PyUnicode_InternFromString(name); if (nameobj == NULL) return NULL; res = _PyImport_FindExtensionObject(nameobj, nameobj); Py_DECREF(nameobj); return res; } /* Get the module object corresponding to a module name. First check the modules dictionary if there's one there, if not, create a new one and insert it in the modules dictionary. Because the former action is most common, THIS DOES NOT RETURN A 'NEW' REFERENCE! */ PyObject * PyImport_AddModuleObject(PyObject *name) { PyObject *modules = PyImport_GetModuleDict(); PyObject *m; if ((m = PyDict_GetItemWithError(modules, name)) != NULL && PyModule_Check(m)) { return m; } if (PyErr_Occurred()) { return NULL; } m = PyModule_NewObject(name); if (m == NULL) return NULL; if (PyDict_SetItem(modules, name, m) != 0) { Py_DECREF(m); return NULL; } Py_DECREF(m); /* Yes, it still exists, in modules! */ return m; } PyObject * PyImport_AddModule(const char *name) { PyObject *nameobj, *module; nameobj = PyUnicode_FromString(name); if (nameobj == NULL) return NULL; module = PyImport_AddModuleObject(nameobj); Py_DECREF(nameobj); return module; } /* Remove name from sys.modules, if it's there. */ static void remove_module(PyObject *name) { PyObject *modules = PyImport_GetModuleDict(); if (PyDict_GetItem(modules, name) == NULL) return; if (PyDict_DelItem(modules, name) < 0) Py_FatalError("import: deleting existing key in " "sys.modules failed"); } /* Execute a code object in a module and return the module object * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is * removed from sys.modules, to avoid leaving damaged module objects * in sys.modules. The caller may wish to restore the original * module object (if any) in this case; PyImport_ReloadModule is an * example. * * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer * interface. The other two exist primarily for backward compatibility. */ PyObject * PyImport_ExecCodeModule(const char *name, PyObject *co) { return PyImport_ExecCodeModuleWithPathnames( name, co, (char *)NULL, (char *)NULL); } PyObject * PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname) { return PyImport_ExecCodeModuleWithPathnames( name, co, pathname, (char *)NULL); } PyObject * PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char *pathname, const char *cpathname) { struct stat stinfo; PyObject *m = NULL; PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL; nameobj = PyUnicode_FromString(name); if (nameobj == NULL) return NULL; if (cpathname != NULL) { cpathobj = PyUnicode_DecodeFSDefault(cpathname); if (cpathobj == NULL) goto error; } else cpathobj = NULL; if (pathname != NULL) { pathobj = PyUnicode_DecodeFSDefault(pathname); if (pathobj == NULL) goto error; } else if (cpathobj != NULL) { // cpathobj != NULL means cpathname != NULL size_t cpathlen = strlen(cpathname); char *pathname2 = _gc(strdup(cpathname)); if (_endswith(pathname2, ".pyc")) { pathname2[cpathlen-2] = '\0'; // so now ends with .py if(!stat(pathname2, &stinfo) && (stinfo.st_mode & S_IFMT) == S_IFREG) pathobj = PyUnicode_FromStringAndSize(pathname2, cpathlen); } if (pathobj == NULL) PyErr_Clear(); } else pathobj = NULL; m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj); error: Py_DECREF(nameobj); Py_XDECREF(pathobj); Py_XDECREF(cpathobj); return m; } static PyObject * module_dict_for_exec(PyObject *name) { PyObject *m, *d = NULL; m = PyImport_AddModuleObject(name); if (m == NULL) return NULL; /* If the module is being reloaded, we get the old module back and re-use its dict to exec the new code. */ d = PyModule_GetDict(m); if (PyDict_GetItemString(d, "__builtins__") == NULL) { if (PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins()) != 0) { remove_module(name); return NULL; } } return d; /* Return a borrowed reference. */ } static PyObject * exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object) { PyObject *modules = PyImport_GetModuleDict(); PyObject *v, *m; v = PyEval_EvalCode(code_object, module_dict, module_dict); if (v == NULL) { remove_module(name); return NULL; } Py_DECREF(v); if ((m = PyDict_GetItem(modules, name)) == NULL) { PyErr_Format(PyExc_ImportError, "Loaded module %R not found in sys.modules", name); return NULL; } Py_INCREF(m); return m; } PyObject* PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname) { PyObject *d, *external, *res; PyInterpreterState *interp = PyThreadState_GET()->interp; _Py_IDENTIFIER(_fix_up_module); d = module_dict_for_exec(name); if (d == NULL) { return NULL; } if (pathname == NULL) { pathname = ((PyCodeObject *)co)->co_filename; } external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external"); if (external == NULL) return NULL; res = _PyObject_CallMethodIdObjArgs(external, &PyId__fix_up_module, d, name, pathname, cpathname, NULL); Py_DECREF(external); if (res != NULL) { Py_DECREF(res); res = exec_code_in_module(name, d, co); } return res; } static void update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname) { PyObject *constants, *tmp; Py_ssize_t i, n; if (PyUnicode_Compare(co->co_filename, oldname)) return; Py_INCREF(newname); Py_XSETREF(co->co_filename, newname); constants = co->co_consts; n = PyTuple_GET_SIZE(constants); for (i = 0; i < n; i++) { tmp = PyTuple_GET_ITEM(constants, i); if (PyCode_Check(tmp)) update_code_filenames((PyCodeObject *)tmp, oldname, newname); } } static void update_compiled_module(PyCodeObject *co, PyObject *newname) { PyObject *oldname; if (PyUnicode_Compare(co->co_filename, newname) == 0) return; oldname = co->co_filename; Py_INCREF(oldname); update_code_filenames(co, oldname, newname); Py_DECREF(oldname); } /*[clinic input] _imp._fix_co_filename code: object(type="PyCodeObject *", subclass_of="&PyCode_Type") Code object to change. path: unicode File path to use. / Changes code.co_filename to specify the passed-in file path. [clinic start generated code]*/ static PyObject * _imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code, PyObject *path) /*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/ { update_compiled_module(code, path); Py_RETURN_NONE; } /* Forward */ static const struct _frozen * find_frozen(PyObject *); /* Helper to test for built-in module */ static int is_builtin(PyObject *name) { initentry key; initentry *res; key.name = PyUnicode_AsUTF8(name); key.tab = NULL; if(!name || !key.name) return 0; res = bsearch(&key, Builtins_Lookup.entries, Builtins_Lookup.n, sizeof(initentry), cmp_initentry); if (res) { if (res->tab->initfunc == NULL) return -1; return 1; } return 0; } /* Return a finder object for a sys.path/pkg.__path__ item 'p', possibly by fetching it from the path_importer_cache dict. If it wasn't yet cached, traverse path_hooks until a hook is found that can handle the path item. Return None if no hook could; this tells our caller that the path based finder could not find a finder for this path item. Cache the result in path_importer_cache. Returns a borrowed reference. */ static PyObject * get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks, PyObject *p) { PyObject *importer; Py_ssize_t j, nhooks; /* These conditions are the caller's responsibility: */ assert(PyList_Check(path_hooks)); assert(PyDict_Check(path_importer_cache)); nhooks = PyList_Size(path_hooks); if (nhooks < 0) return NULL; /* Shouldn't happen */ importer = PyDict_GetItem(path_importer_cache, p); if (importer != NULL) return importer; /* set path_importer_cache[p] to None to avoid recursion */ if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0) return NULL; for (j = 0; j < nhooks; j++) { PyObject *hook = PyList_GetItem(path_hooks, j); if (hook == NULL) return NULL; importer = PyObject_CallFunctionObjArgs(hook, p, NULL); if (importer != NULL) break; if (!PyErr_ExceptionMatches(PyExc_ImportError)) { return NULL; } PyErr_Clear(); } if (importer == NULL) { return Py_None; } if (importer != NULL) { int err = PyDict_SetItem(path_importer_cache, p, importer); Py_DECREF(importer); if (err != 0) return NULL; } return importer; } PyObject * PyImport_GetImporter(PyObject *path) { PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL; path_importer_cache = PySys_GetObject("path_importer_cache"); path_hooks = PySys_GetObject("path_hooks"); if (path_importer_cache != NULL && path_hooks != NULL) { importer = get_path_importer(path_importer_cache, path_hooks, path); } Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */ return importer; } /*[clinic input] _imp.create_builtin spec: object / Create an extension module. [clinic start generated code]*/ static PyObject * _imp_create_builtin(PyObject *module, PyObject *spec) /*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/ { struct _inittab *p; initentry key; initentry *res; PyObject *name; char *namestr; PyObject *mod; name = PyObject_GetAttrString(spec, "name"); if (name == NULL) { return NULL; } mod = _PyImport_FindExtensionObject(name, name); if (mod || PyErr_Occurred()) { Py_DECREF(name); Py_XINCREF(mod); return mod; } namestr = PyUnicode_AsUTF8(name); if (namestr == NULL) { Py_DECREF(name); return NULL; } key.name = namestr; key.tab = NULL; res = bsearch(&key, Builtins_Lookup.entries, Builtins_Lookup.n, sizeof(initentry), cmp_initentry); if (res != NULL) { p = res->tab; PyModuleDef *def; if (p->initfunc == NULL) { /* Cannot re-init internal module ("sys" or "builtins") */ mod = PyImport_AddModule(namestr); Py_DECREF(name); return mod; } mod = (*p->initfunc)(); if (mod == NULL) { Py_DECREF(name); return NULL; } if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) { Py_DECREF(name); return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec); } else { /* Remember pointer to module init function. */ def = PyModule_GetDef(mod); if (def == NULL) { Py_DECREF(name); return NULL; } def->m_base.m_init = p->initfunc; if (_PyImport_FixupExtensionObject(mod, name, name) < 0) { Py_DECREF(name); return NULL; } Py_DECREF(name); return mod; } } Py_DECREF(name); Py_RETURN_NONE; } /* Frozen modules */ static const struct _frozen * find_frozen(PyObject *name) { initentry key; initentry *res; if (name == NULL) return NULL; key.name = PyUnicode_AsUTF8(name); key.frz = NULL; res = bsearch(&key, Frozens_Lookup.entries, Frozens_Lookup.n, sizeof(initentry), cmp_initentry); if (res && res->frz->name != NULL) { return res->frz; } return NULL; } static PyObject * get_frozen_object(PyObject *name) { const struct _frozen *p = find_frozen(name); int size; if (p == NULL) { PyErr_Format(PyExc_ImportError, "No such frozen object named %R", name); return NULL; } if (p->code == NULL) { PyErr_Format(PyExc_ImportError, "Excluded frozen object named %R", name); return NULL; } size = p->size; if (size < 0) size = -size; return PyMarshal_ReadObjectFromString((const char *)p->code, size); } static PyObject * is_frozen_package(PyObject *name) { const struct _frozen *p = find_frozen(name); int size; if (p == NULL) { PyErr_Format(PyExc_ImportError, "No such frozen object named %R", name); return NULL; } size = p->size; if (size < 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; } /* Initialize a frozen module. Return 1 for success, 0 if the module is not found, and -1 with an exception set if the initialization failed. This function is also used from frozenmain.c */ int PyImport_ImportFrozenModuleObject(PyObject *name) { const struct _frozen *p; PyObject *co, *m, *d; int ispackage; int size; p = find_frozen(name); if (p == NULL) return 0; if (p->code == NULL) { PyErr_Format(PyExc_ImportError, "Excluded frozen object named %R", name); return -1; } size = p->size; ispackage = (size < 0); if (ispackage) size = -size; co = PyMarshal_ReadObjectFromString((const char *)p->code, size); if (co == NULL) return -1; if (!PyCode_Check(co)) { PyErr_Format(PyExc_TypeError, "frozen object %R is not a code object", name); goto err_return; } if (ispackage) { /* Set __path__ to the empty list */ PyObject *l; int err; m = PyImport_AddModuleObject(name); if (m == NULL) goto err_return; d = PyModule_GetDict(m); l = PyList_New(0); if (l == NULL) { goto err_return; } err = PyDict_SetItemString(d, "__path__", l); Py_DECREF(l); if (err != 0) goto err_return; } d = module_dict_for_exec(name); if (d == NULL) { goto err_return; } m = exec_code_in_module(name, d, co); if (m == NULL) goto err_return; Py_DECREF(co); Py_DECREF(m); return 1; err_return: Py_DECREF(co); return -1; } int PyImport_ImportFrozenModule(const char *name) { PyObject *nameobj; int ret; nameobj = PyUnicode_InternFromString(name); if (nameobj == NULL) return -1; ret = PyImport_ImportFrozenModuleObject(nameobj); Py_DECREF(nameobj); return ret; } /* Import a module, either built-in, frozen, or external, and return its module object WITH INCREMENTED REFERENCE COUNT */ PyObject * PyImport_ImportModule(const char *name) { PyObject *pname; PyObject *result; pname = PyUnicode_FromString(name); if (pname == NULL) return NULL; result = PyImport_Import(pname); Py_DECREF(pname); return result; } /* Import a module without blocking * * At first it tries to fetch the module from sys.modules. If the module was * never loaded before it loads it with PyImport_ImportModule() unless another * thread holds the import lock. In the latter case the function raises an * ImportError instead of blocking. * * Returns the module object with incremented ref count. */ PyObject * PyImport_ImportModuleNoBlock(const char *name) { return PyImport_ImportModule(name); } /* Remove importlib frames from the traceback, * except in Verbose mode. */ static void remove_importlib_frames(void) { const char *importlib_filename = "<frozen importlib._bootstrap>"; const char *external_filename = "<frozen importlib._bootstrap_external>"; const char *remove_frames = "_call_with_frames_removed"; int always_trim = 0; int in_importlib = 0; PyObject *exception, *value, *base_tb, *tb; PyObject **prev_link, **outer_link = NULL; /* Synopsis: if it's an ImportError, we trim all importlib chunks from the traceback. We always trim chunks which end with a call to "_call_with_frames_removed". */ PyErr_Fetch(&exception, &value, &base_tb); if (!exception || Py_VerboseFlag) goto done; if (PyType_IsSubtype((PyTypeObject *) exception, (PyTypeObject *) PyExc_ImportError)) always_trim = 1; prev_link = &base_tb; tb = base_tb; while (tb != NULL) { PyTracebackObject *traceback = (PyTracebackObject *)tb; PyObject *next = (PyObject *) traceback->tb_next; PyFrameObject *frame = traceback->tb_frame; PyCodeObject *code = frame->f_code; int now_in_importlib; assert(PyTraceBack_Check(tb)); now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) || _PyUnicode_EqualToASCIIString(code->co_filename, external_filename); if (now_in_importlib && !in_importlib) { /* This is the link to this chunk of importlib tracebacks */ outer_link = prev_link; } in_importlib = now_in_importlib; if (in_importlib && (always_trim || _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) { Py_XINCREF(next); Py_XSETREF(*outer_link, next); prev_link = outer_link; } else { prev_link = (PyObject **) &traceback->tb_next; } tb = next; } done: PyErr_Restore(exception, value, base_tb); } static PyObject * resolve_name(PyObject *name, PyObject *globals, int level) { _Py_IDENTIFIER(__spec__); _Py_IDENTIFIER(__package__); _Py_IDENTIFIER(__path__); _Py_IDENTIFIER(__name__); _Py_IDENTIFIER(parent); PyObject *abs_name; PyObject *package = NULL; PyObject *spec; Py_ssize_t last_dot; PyObject *base; int level_up; if (globals == NULL) { PyErr_SetString(PyExc_KeyError, "'__name__' not in globals"); goto error; } if (!PyDict_Check(globals)) { PyErr_SetString(PyExc_TypeError, "globals must be a dict"); goto error; } package = _PyDict_GetItemId(globals, &PyId___package__); if (package == Py_None) { package = NULL; } spec = _PyDict_GetItemId(globals, &PyId___spec__); if (package != NULL) { Py_INCREF(package); if (!PyUnicode_Check(package)) { PyErr_SetString(PyExc_TypeError, "package must be a string"); goto error; } else if (spec != NULL && spec != Py_None) { int equal; PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent); if (parent == NULL) { goto error; } equal = PyObject_RichCompareBool(package, parent, Py_EQ); Py_DECREF(parent); if (equal < 0) { goto error; } else if (equal == 0) { if (PyErr_WarnEx(PyExc_ImportWarning, "__package__ != __spec__.parent", 1) < 0) { goto error; } } } } else if (spec != NULL && spec != Py_None) { package = _PyObject_GetAttrId(spec, &PyId_parent); if (package == NULL) { goto error; } else if (!PyUnicode_Check(package)) { PyErr_SetString(PyExc_TypeError, "__spec__.parent must be a string"); goto error; } } else { if (PyErr_WarnEx(PyExc_ImportWarning, "can't resolve package from __spec__ or __package__, " "falling back on __name__ and __path__", 1) < 0) { goto error; } package = _PyDict_GetItemId(globals, &PyId___name__); if (package == NULL) { PyErr_SetString(PyExc_KeyError, "'__name__' not in globals"); goto error; } Py_INCREF(package); if (!PyUnicode_Check(package)) { PyErr_SetString(PyExc_TypeError, "__name__ must be a string"); goto error; } if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) { Py_ssize_t dot; if (PyUnicode_READY(package) < 0) { goto error; } dot = PyUnicode_FindChar(package, '.', 0, PyUnicode_GET_LENGTH(package), -1); if (dot == -2) { goto error; } if (dot >= 0) { PyObject *substr = PyUnicode_Substring(package, 0, dot); if (substr == NULL) { goto error; } Py_SETREF(package, substr); } } } last_dot = PyUnicode_GET_LENGTH(package); if (last_dot == 0) { PyErr_SetString(PyExc_ImportError, "attempted relative import with no known parent package"); goto error; } for (level_up = 1; level_up < level; level_up += 1) { last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1); if (last_dot == -2) { goto error; } else if (last_dot == -1) { PyErr_SetString(PyExc_ValueError, "attempted relative import beyond top-level " "package"); goto error; } } base = PyUnicode_Substring(package, 0, last_dot); Py_DECREF(package); if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) { return base; } abs_name = PyUnicode_FromFormat("%U.%U", base, name); Py_DECREF(base); return abs_name; error: Py_XDECREF(package); return NULL; } PyObject * PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) { _Py_IDENTIFIER(_find_and_load); _Py_IDENTIFIER(_handle_fromlist); PyObject *abs_name = NULL; PyObject *final_mod = NULL; PyObject *mod = NULL; PyObject *package = NULL; PyInterpreterState *interp = PyThreadState_GET()->interp; int has_from; if (name == NULL) { PyErr_SetString(PyExc_ValueError, "Empty module name"); goto error; } /* The below code is importlib.__import__() & _gcd_import(), ported to C for added performance. */ if (!PyUnicode_Check(name)) { PyErr_SetString(PyExc_TypeError, "module name must be a string"); goto error; } if (PyUnicode_READY(name) < 0) { goto error; } if (level < 0) { PyErr_SetString(PyExc_ValueError, "level must be >= 0"); goto error; } if (level > 0) { abs_name = resolve_name(name, globals, level); if (abs_name == NULL) goto error; } else { /* level == 0 */ if (PyUnicode_GET_LENGTH(name) == 0) { PyErr_SetString(PyExc_ValueError, "Empty module name"); goto error; } abs_name = name; Py_INCREF(abs_name); } mod = PyDict_GetItem(interp->modules, abs_name); if (mod != NULL && mod != Py_None) { Py_INCREF(mod); } else { mod = _PyObject_CallMethodIdObjArgs(interp->importlib, &PyId__find_and_load, abs_name, interp->import_func, NULL); if (mod == NULL) { goto error; } } has_from = 0; if (fromlist != NULL && fromlist != Py_None) { has_from = PyObject_IsTrue(fromlist); if (has_from < 0) goto error; } if (!has_from) { Py_ssize_t len = PyUnicode_GET_LENGTH(name); if (level == 0 || len > 0) { Py_ssize_t dot; dot = PyUnicode_FindChar(name, '.', 0, len, 1); if (dot == -2) { goto error; } if (dot == -1) { /* No dot in module name, simple exit */ final_mod = mod; Py_INCREF(mod); goto error; } if (level == 0) { PyObject *front = PyUnicode_Substring(name, 0, dot); if (front == NULL) { goto error; } final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0); Py_DECREF(front); } else { Py_ssize_t cut_off = len - dot; Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name); PyObject *to_return = PyUnicode_Substring(abs_name, 0, abs_name_len - cut_off); if (to_return == NULL) { goto error; } final_mod = PyDict_GetItem(interp->modules, to_return); Py_DECREF(to_return); if (final_mod == NULL) { PyErr_Format(PyExc_KeyError, "%R not in sys.modules as expected", to_return); goto error; } Py_INCREF(final_mod); } } else { final_mod = mod; Py_INCREF(mod); } } else { final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib, &PyId__handle_fromlist, mod, fromlist, interp->import_func, NULL); } error: Py_XDECREF(abs_name); Py_XDECREF(mod); Py_XDECREF(package); if (final_mod == NULL) remove_importlib_frames(); return final_mod; } PyObject * PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) { PyObject *nameobj, *mod; nameobj = PyUnicode_FromString(name); if (nameobj == NULL) return NULL; mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals, fromlist, level); Py_DECREF(nameobj); return mod; } /* Re-import a module of any kind and return its module object, WITH INCREMENTED REFERENCE COUNT */ PyObject * PyImport_ReloadModule(PyObject *m) { _Py_IDENTIFIER(reload); PyObject *reloaded_module = NULL; PyObject *modules = PyImport_GetModuleDict(); PyObject *imp = PyDict_GetItemString(modules, "imp"); if (imp == NULL) { imp = PyImport_ImportModule("imp"); if (imp == NULL) { return NULL; } } else { Py_INCREF(imp); } reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m); Py_DECREF(imp); return reloaded_module; } /* Higher-level import emulator which emulates the "import" statement more accurately -- it invokes the __import__() function from the builtins of the current globals. This means that the import is done using whatever import hooks are installed in the current environment. A dummy list ["__doc__"] is passed as the 4th argument so that e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache")) will return <module "gencache"> instead of <module "win32com">. */ PyObject * PyImport_Import(PyObject *module_name) { static PyObject *silly_list = NULL; static PyObject *builtins_str = NULL; static PyObject *import_str = NULL; PyObject *globals = NULL; PyObject *import = NULL; PyObject *builtins = NULL; PyObject *modules = NULL; PyObject *r = NULL; /* Initialize constant string objects */ if (silly_list == NULL) { import_str = PyUnicode_InternFromString("__import__"); if (import_str == NULL) return NULL; builtins_str = PyUnicode_InternFromString("__builtins__"); if (builtins_str == NULL) return NULL; silly_list = PyList_New(0); if (silly_list == NULL) return NULL; } /* Get the builtins from current globals */ globals = PyEval_GetGlobals(); if (globals != NULL) { Py_INCREF(globals); builtins = PyObject_GetItem(globals, builtins_str); if (builtins == NULL) goto err; } else { /* No globals -- use standard builtins, and fake globals */ builtins = PyImport_ImportModuleLevel("builtins", NULL, NULL, NULL, 0); if (builtins == NULL) return NULL; globals = Py_BuildValue("{OO}", builtins_str, builtins); if (globals == NULL) goto err; } /* Get the __import__ function from the builtins */ if (PyDict_Check(builtins)) { import = PyObject_GetItem(builtins, import_str); if (import == NULL) PyErr_SetObject(PyExc_KeyError, import_str); } else import = PyObject_GetAttr(builtins, import_str); if (import == NULL) goto err; /* Call the __import__ function with the proper argument list Always use absolute import here. Calling for side-effect of import. */ r = PyObject_CallFunction(import, "OOOOi", module_name, globals, globals, silly_list, 0, NULL); if (r == NULL) goto err; Py_DECREF(r); modules = PyImport_GetModuleDict(); r = PyDict_GetItemWithError(modules, module_name); if (r != NULL) { Py_INCREF(r); } else if (!PyErr_Occurred()) { PyErr_SetObject(PyExc_KeyError, module_name); } err: Py_XDECREF(globals); Py_XDECREF(builtins); Py_XDECREF(import); return r; } /*[clinic input] _imp.extension_suffixes Returns the list of file suffixes used to identify extension modules. [clinic start generated code]*/ static PyObject * _imp_extension_suffixes_impl(PyObject *module) /*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/ { PyObject *list; const char *suffix; unsigned int index = 0; list = PyList_New(0); if (list == NULL) return NULL; #ifdef HAVE_DYNAMIC_LOADING while ((suffix = _PyImport_DynLoadFiletab[index])) { PyObject *item = PyUnicode_FromString(suffix); if (item == NULL) { Py_DECREF(list); return NULL; } if (PyList_Append(list, item) < 0) { Py_DECREF(list); Py_DECREF(item); return NULL; } Py_DECREF(item); index += 1; } #endif return list; } /*[clinic input] _imp.init_frozen name: unicode / Initializes a frozen module. [clinic start generated code]*/ static PyObject * _imp_init_frozen_impl(PyObject *module, PyObject *name) /*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/ { int ret; PyObject *m; ret = PyImport_ImportFrozenModuleObject(name); if (ret < 0) return NULL; if (ret == 0) { Py_INCREF(Py_None); return Py_None; } m = PyImport_AddModuleObject(name); Py_XINCREF(m); return m; } /*[clinic input] _imp.get_frozen_object name: unicode / Create a code object for a frozen module. [clinic start generated code]*/ static PyObject * _imp_get_frozen_object_impl(PyObject *module, PyObject *name) /*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/ { return get_frozen_object(name); } /*[clinic input] _imp.is_frozen_package name: unicode / Returns True if the module name is of a frozen package. [clinic start generated code]*/ static PyObject * _imp_is_frozen_package_impl(PyObject *module, PyObject *name) /*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/ { return is_frozen_package(name); } /*[clinic input] _imp.is_builtin name: unicode / Returns True if the module name corresponds to a built-in module. [clinic start generated code]*/ static PyObject * _imp_is_builtin_impl(PyObject *module, PyObject *name) /*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/ { return PyLong_FromLong(is_builtin(name)); } /*[clinic input] _imp.is_frozen name: unicode / Returns True if the module name corresponds to a frozen module. [clinic start generated code]*/ static PyObject * _imp_is_frozen_impl(PyObject *module, PyObject *name) /*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/ { const struct _frozen *p; p = find_frozen(name); return PyBool_FromLong((long) (p == NULL ? 0 : p->size)); } /* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */ static int exec_builtin_or_dynamic(PyObject *mod) { PyModuleDef *def; void *state; if (!PyModule_Check(mod)) { return 0; } def = PyModule_GetDef(mod); if (def == NULL) { return 0; } state = PyModule_GetState(mod); if (state) { /* Already initialized; skip reload */ return 0; } return PyModule_ExecDef(mod, def); } #ifdef HAVE_DYNAMIC_LOADING /*[clinic input] _imp.create_dynamic spec: object file: object = NULL / Create an extension module. [clinic start generated code]*/ static PyObject * _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file) /*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/ { PyObject *mod, *name, *path; FILE *fp; name = PyObject_GetAttrString(spec, "name"); if (name == NULL) { return NULL; } path = PyObject_GetAttrString(spec, "origin"); if (path == NULL) { Py_DECREF(name); return NULL; } mod = _PyImport_FindExtensionObject(name, path); if (mod != NULL || PyErr_Occurred()) { Py_DECREF(name); Py_DECREF(path); Py_XINCREF(mod); return mod; } if (file != NULL) { fp = _Py_fopen_obj(path, "r"); if (fp == NULL) { Py_DECREF(name); Py_DECREF(path); return NULL; } } else fp = NULL; mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp); Py_DECREF(name); Py_DECREF(path); if (fp) fclose(fp); return mod; } /*[clinic input] _imp.exec_dynamic -> int mod: object / Initialize an extension module. [clinic start generated code]*/ static int _imp_exec_dynamic_impl(PyObject *module, PyObject *mod) /*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/ { return exec_builtin_or_dynamic(mod); } #endif /* HAVE_DYNAMIC_LOADING */ /*[clinic input] _imp.exec_builtin -> int mod: object / Initialize a built-in module. [clinic start generated code]*/ static int _imp_exec_builtin_impl(PyObject *module, PyObject *mod) /*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/ { return exec_builtin_or_dynamic(mod); } /*[clinic input] dump buffer [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/ static PyObject *_check_path_mode(const char *path, uint32_t mode) { struct stat stinfo; if (stat(path, &stinfo)) Py_RETURN_FALSE; if ((stinfo.st_mode & S_IFMT) == mode) Py_RETURN_TRUE; Py_RETURN_FALSE; } static PyObject *_imp_path_is_mode_type(PyObject *module, PyObject **args, Py_ssize_t nargs) { Py_ssize_t n; const char *path; uint32_t mode; if (!_PyArg_ParseStack(args, nargs, "s#I:_path_is_mode_type", &path, &n, &mode)) return 0; return _check_path_mode(path, mode); } PyDoc_STRVAR(_imp_path_is_mode_type_doc, "check if path is mode type"); static PyObject *_imp_path_isfile(PyObject *module, PyObject *arg) { Py_ssize_t n; const char *path; if (!PyArg_Parse(arg, "s#:_path_isfile", &path, &n)) return 0; return _check_path_mode(path, S_IFREG); } PyDoc_STRVAR(_imp_path_isfile_doc, "check if path is file"); static PyObject *_imp_path_isdir(PyObject *module, PyObject *arg) { Py_ssize_t n; const char *path; if (!PyArg_Parse(arg, "z#:_path_isdir", &path, &n)) return 0; if (path == NULL) path = _gc(getcwd(NULL, 0)); return _check_path_mode(path, S_IFDIR); } PyDoc_STRVAR(_imp_path_isdir_doc, "check if path is dir"); static PyObject *_imp_calc_mode(PyObject *module, PyObject *arg) { struct stat stinfo; Py_ssize_t n; const char *path; if (!PyArg_Parse(arg, "s#:_calc_mode", &path, &n)) return 0; if (stat(path, &stinfo)) return PyLong_FromUnsignedLong((unsigned long)0666); return PyLong_FromUnsignedLong((unsigned long)stinfo.st_mode | 0200); } PyDoc_STRVAR(_imp_calc_mode_doc, "return stat.st_mode of path"); static PyObject *_imp_calc_mtime_and_size(PyObject *module, PyObject *arg) { struct stat stinfo; Py_ssize_t n; const char *path; if (!PyArg_Parse(arg, "z#:_calc_mtime_and_size", &path, &n)) return 0; if (path == NULL) path = _gc(getcwd(NULL, 0)); if (stat(path, &stinfo)) return PyTuple_Pack(2, PyLong_FromLong((long)-1), PyLong_FromLong((long)0)); return PyTuple_Pack(2, PyLong_FromLong((long)stinfo.st_mtime), PyLong_FromLong((long)stinfo.st_size)); } PyDoc_STRVAR(_imp_calc_mtime_and_size_doc, "return stat.st_mtime and stat.st_size of path in tuple"); static PyObject *_imp_w_long(PyObject *module, PyObject *arg) { int32_t value; if (!PyArg_Parse(arg, "i:_w_long", &value)) return 0; return PyBytes_FromStringAndSize((const char *)(&value), 4); } PyDoc_STRVAR(_imp_w_long_doc, "convert 32-bit int to 4 bytes"); static PyObject *_imp_r_long(PyObject *module, PyObject *arg) { char b[4] = {0}; const char *path; Py_ssize_t i, n; if (!PyArg_Parse(arg, "y#:_r_long", &path, &n)) return 0; if (n > 4) n = 4; for (i = 0; i < n; i++) b[i] = path[i]; return PyLong_FromLong(READ32LE(b)); } PyDoc_STRVAR(_imp_r_long_doc, "convert 4 bytes to 32bit int"); static PyObject *_imp_relax_case(PyObject *module, PyObject *Py_UNUSED(ignored)) { // TODO: check if this affects case-insensitive system imports. // if yes, then have an IsWindows() check along w/ PYTHONCASEOK Py_RETURN_FALSE; } static PyObject *_imp_write_atomic(PyObject *module, PyObject **args, Py_ssize_t nargs) { const char *path; Py_ssize_t n; Py_buffer data = {NULL, NULL}; uint32_t mode = 0666; int fd; int failure = 0; if (!_PyArg_ParseStack(args, nargs, "s#y*|I:_write_atomic", &path, &n, &data, &mode)) goto end; mode &= 0666; if ((fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, mode)) == -1) { failure = 1; PyErr_Format(PyExc_OSError, "failed to create file: %s\n", path); goto end; } if (write(fd, data.buf, data.len) == -1) { failure = 1; PyErr_Format(PyExc_OSError, "failed to write to file: %s\n", path); goto end; } end: if (data.obj) PyBuffer_Release(&data); if (failure) return 0; Py_RETURN_NONE; } PyDoc_STRVAR(_imp_write_atomic_doc, "atomic write to a file"); static PyObject *_imp_compile_bytecode(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { static const char * const _keywords[] = {"data", "name", "bytecode_path", "source_path", NULL}; static _PyArg_Parser _parser = {"|y*zzz*", _keywords, 0}; Py_buffer data = {NULL, NULL}; const char *name = NULL; const char *bpath = NULL; Py_buffer spath = {NULL, NULL}; PyObject *code = NULL; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwargs, &_parser, &data, &name, &bpath, &spath)) { goto exit; } if (!(code = PyMarshal_ReadObjectFromString(data.buf, data.len))) goto exit; if (!PyCode_Check(code)) { PyErr_Format(PyExc_ImportError, "non-code object in %s\n", bpath); goto exit; } else { if (Py_VerboseFlag) PySys_FormatStderr("# code object from '%s'\n", bpath); if (spath.buf != NULL) update_compiled_module((PyCodeObject *)code, PyUnicode_FromStringAndSize(spath.buf, spath.len)); } exit: if (data.obj) PyBuffer_Release(&data); if (spath.obj) PyBuffer_Release(&spath); return code; } PyDoc_STRVAR(_imp_compile_bytecode_doc, "compile bytecode to a code object"); static PyObject *_imp_validate_bytecode_header(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { static const char * const _keywords[] = {"data", "source_stats", "name", "path", NULL}; static _PyArg_Parser _parser = {"|y*Ozz", _keywords, 0}; static const char defname[] = "<bytecode>"; static const char defpath[] = ""; Py_buffer data = {NULL, NULL}; PyObject *source_stats = NULL; PyObject *result = NULL; const char *name = defname; const char *path = defpath; long magic = 0; int64_t raw_timestamp = 0; int64_t raw_size = 0; PyObject *tmp = NULL; int64_t source_size = 0; int64_t source_mtime = 0; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwargs, &_parser, &data, &source_stats, &name, &path)) { goto exit; } char *buf = data.buf; if (data.len < 4 || (magic = READ16LE(buf)) != 3390 || buf[2] != '\r' || buf[3] != '\n') { PyErr_Format(PyExc_ImportError, "bad magic number in %s: %d\n", name, magic); goto exit; } if (data.len < 8) { PyErr_Format(PyExc_ImportError, "reached EOF while reading timestamp in %s\n", name); goto exit; } raw_timestamp = (int64_t)(READ32LE(&(buf[4]))); if (data.len < 12) { PyErr_Format(PyExc_ImportError, "reached EOF while size of source in %s\n", name); goto exit; } raw_size = (int64_t)(READ32LE(&(buf[8]))); if (source_stats && PyDict_Check(source_stats)) { if ((tmp = PyDict_GetItemString(source_stats, "mtime")) && PyLong_Check(tmp)) { source_mtime = PyLong_AsLong(tmp); if (source_mtime != raw_timestamp) PyErr_Format(PyExc_ImportError, "bytecode is stale for %s\n", name); } Py_XDECREF(tmp); if ((tmp = PyDict_GetItemString(source_stats, "size")) && PyLong_Check(tmp)) { source_size = PyLong_AsLong(tmp) & 0xFFFFFFFF; if (source_size != raw_size) PyErr_Format(PyExc_ImportError, "bytecode is stale for %s\n", name); } Py_XDECREF(tmp); } // shift buffer pointer to prevent copying data.buf = &(buf[12]); data.len -= 12; result = PyMemoryView_FromBuffer(&data); // TODO: figure out how refcounts are managed between data and result // if there is a memory fault, use the below line which copies // result = PyBytes_FromStringAndSize(&(buf[12]), data.len-12); exit: if (!result && data.obj) PyBuffer_Release(&data); // if (data.obj) PyBuffer_Release(&data); return result; } PyDoc_STRVAR(_imp_validate_bytecode_header_doc, "validate first 12 bytes and stat info of bytecode"); static PyObject *_imp_cache_from_source(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { static const char * const _keywords[] = {"path", "debug_override", "optimization", NULL}; static struct _PyArg_Parser _parser = {"|OO$O:cache_from_source", _keywords, 0}; PyObject *path = NULL; PyObject *debug_override = NULL; PyObject *optimization = NULL; PyObject *res = NULL; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwargs, &_parser, &path, &debug_override, &optimization)) { return NULL; } res = PyUnicode_FromFormat("%Sc", PyOS_FSPath(path)); return res; } PyDoc_STRVAR(_imp_cache_from_source_doc, "given a .py filename, return .pyc"); static PyObject *_imp_source_from_cache(PyObject *module, PyObject *arg) { struct stat stinfo; char *path = NULL; Py_ssize_t pathlen = 0; if (!PyArg_Parse(PyOS_FSPath(arg), "z#:source_from_cache", &path, &pathlen)) return NULL; if (!path || !_endswith(path, ".pyc")) { PyErr_Format(PyExc_ValueError, "%s does not end in .pyc", path); return NULL; } path[pathlen - 1] = '\0'; if (stat(path, &stinfo)) { path[pathlen - 1] = 'c'; Py_INCREF(arg); return arg; } return PyUnicode_FromStringAndSize(path, pathlen - 1); } PyDoc_STRVAR(_imp_source_from_cache_doc, "given a .pyc filename, return .py"); typedef struct { PyObject_HEAD char *name; char *path; Py_ssize_t namelen; Py_ssize_t pathlen; Py_ssize_t present; } SourcelessFileLoader; static PyTypeObject SourcelessFileLoaderType; #define SourcelessFileLoaderCheck(o) (Py_TYPE(o) == &SourcelessFileLoaderType) static SourcelessFileLoader *SFLObject_new(PyObject *cls, PyObject *args, PyObject *kwargs) { SourcelessFileLoader *obj = PyObject_New(SourcelessFileLoader, &SourcelessFileLoaderType); if (obj == NULL) return NULL; obj->name = NULL; obj->path = NULL; obj->namelen = 0; obj->pathlen = 0; obj->present = 0; return obj; } static void SFLObject_dealloc(SourcelessFileLoader *self) { if (self->name) { free(self->name); self->name = NULL; self->namelen = 0; } if (self->path) { free(self->path); self->path = NULL; self->pathlen = 0; } PyObject_Del(self); } static int SFLObject_init(SourcelessFileLoader *self, PyObject *args, PyObject *kwargs) { static char *_keywords[] = {"fullname", "path", NULL}; char *name = NULL; char *path = NULL; Py_ssize_t namelen = 0; Py_ssize_t pathlen = 0; int result = 0; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|z#z#", _keywords, &name, &namelen, &path, &pathlen)) { result = -1; } if (result == 0) { if (self->name) free(self->name); if (self->path) free(self->name); self->namelen = namelen; self->pathlen = pathlen; // TODO: should this be via PyMem_RawMalloc? self->name = strndup(name, namelen); self->path = strndup(path, pathlen); self->present = 0; } return result; } static Py_hash_t SFLObject_hash(SourcelessFileLoader *self) { return _Py_HashBytes(self->name, self->namelen) ^ _Py_HashBytes(self->path, self->pathlen); } static PyObject *SFLObject_richcompare(PyObject *self, PyObject *other, int op) { if (op != Py_EQ || !SourcelessFileLoaderCheck(self) || !SourcelessFileLoaderCheck(other)) { // this is equivalent to comparing self.__class__ Py_RETURN_NOTIMPLEMENTED; } if (strncmp(((SourcelessFileLoader *)self)->name, ((SourcelessFileLoader *)other)->name, ((SourcelessFileLoader *)self)->namelen)) { Py_RETURN_FALSE; } if (strncmp(((SourcelessFileLoader *)self)->path, ((SourcelessFileLoader *)other)->path, ((SourcelessFileLoader *)self)->pathlen)) { Py_RETURN_FALSE; } Py_RETURN_TRUE; } static PyObject *SFLObject_get_source(SourcelessFileLoader *self, PyObject *arg) { Py_RETURN_NONE; } static PyObject *SFLObject_get_code(SourcelessFileLoader *self, PyObject *arg) { struct stat stinfo; char bytecode_header[12] = {0}; int32_t magic = 0; size_t headerlen; char *name = NULL; FILE *fp = NULL; PyObject *res = NULL; char *rawbuf = NULL; size_t rawlen = 0; if (!PyArg_Parse(arg, "z:get_code", &name)) return 0; if (!name) name = self->name; // path = self.get_filename(fullname) if (strncmp(name, self->name, self->namelen)) { PyErr_Format(PyExc_ImportError, "loader for %s cannot handle %s\n", self->name, name); goto exit; } self->present = self->present || !stat(self->path, &stinfo); if (!self->present || !(fp = fopen(self->path, "rb"))) { PyErr_Format(PyExc_ImportError, "%s does not exist\n", self->path); goto exit; } // data = self.get_data(path) // bytes_data = _validate_bytecode_header(data, name=fullname, path=path) headerlen = fread(bytecode_header, sizeof(char), sizeof(bytecode_header), fp); if (headerlen < 4 || (magic = READ32LE(bytecode_header)) != PyImport_GetMagicNumber()) { PyErr_Format(PyExc_ImportError, "bad magic number in %s: %d\n", name, magic); goto exit; } if (headerlen < 8) { PyErr_Format(PyExc_ImportError, "reached EOF while reading timestamp in %s\n", name); goto exit; } if (headerlen < 12) { PyErr_Format(PyExc_ImportError, "reached EOF while size of source in %s\n", name); goto exit; } // return _compile_bytecode(bytes_data, name=fullname, bytecode_path=path) /* since we don't have the stat call sometimes, we need * a different way to load the remaining bytes into file */ /* rawlen = stinfo.st_size - headerlen; rawbuf = PyMem_RawMalloc(rawlen); if (rawlen != fread(rawbuf, sizeof(char), rawlen, fp)) { PyErr_Format(PyExc_ImportError, "reached EOF while size of source in %s\n", name); goto exit; }*/ if (!(res = PyMarshal_ReadObjectFromFile(fp))) goto exit; exit: if (rawbuf) PyMem_RawFree(rawbuf); if (fp) fclose(fp); return res; } static PyObject *SFLObject_get_data(SourcelessFileLoader *self, PyObject *arg) { struct stat stinfo; char *name = NULL; char *data = NULL; size_t datalen = 0; PyObject *res = NULL; if (!PyArg_Parse(arg, "z:get_data", &name)) return 0; if (name == NULL || stat(name, &stinfo)) { PyErr_SetString(PyExc_ImportError, "invalid file for get_data\n"); return res; } // TODO: these two allocations can be combined into one data = xslurp(name, &datalen); res = PyBytes_FromStringAndSize(data, (Py_ssize_t)stinfo.st_size); return res; } static PyObject *SFLObject_get_filename(SourcelessFileLoader *self, PyObject *arg) { char *name = NULL; if (!PyArg_Parse(arg, "z:get_filename", &name)) return 0; if (!name) name = self->name; if (strncmp(name, self->name, self->namelen)) { PyErr_Format(PyExc_ImportError, "loader for %s cannot handle %s\n", self->name, name); return NULL; } return PyUnicode_FromStringAndSize(self->path, self->pathlen); } static PyObject *SFLObject_load_module(SourcelessFileLoader *self, PyObject **args, Py_ssize_t nargs) { _Py_IDENTIFIER(_load_module_shim); char *name = NULL; PyObject *bootstrap = NULL; PyObject *fullname = NULL; PyObject *res = NULL; PyInterpreterState *interp = PyThreadState_GET()->interp; if (!_PyArg_ParseStack(args, nargs, "|z:load_module", &name)) goto exit; if (!name) name = self->name; if (strncmp(name, self->name, self->namelen)) { PyErr_Format(PyExc_ImportError, "loader for %s cannot handle %s\n", self->name, name); goto exit; } else { // name == self->name fullname = PyUnicode_FromStringAndSize(self->name, self->namelen); } res = _PyObject_CallMethodIdObjArgs( interp->importlib, &PyId__load_module_shim, self, fullname, NULL); Py_XDECREF(bootstrap); exit: Py_XDECREF(fullname); return res; } static PyObject *SFLObject_create_module(SourcelessFileLoader *self, PyObject *arg) { Py_RETURN_NONE; } static PyObject *SFLObject_exec_module(SourcelessFileLoader *self, PyObject *arg) { _Py_IDENTIFIER(__builtins__); PyObject *module = NULL; PyObject *name = NULL; PyObject *code = NULL; PyObject *globals = NULL; PyObject *v = NULL; if (!PyArg_Parse(arg, "O:exec_module", &module)) goto exit; name = PyObject_GetAttrString(module, "__name__"); code = SFLObject_get_code(self, name); if (code == NULL || code == Py_None) { if (code == Py_None) { PyErr_Format(PyExc_ImportError, "cannot load module %U when get_code() returns None", name); } goto exit; } globals = PyModule_GetDict(module); if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) { if (_PyDict_SetItemId(globals, &PyId___builtins__, PyEval_GetBuiltins()) != 0) goto exit; } v = _PyEval_EvalCodeWithName(code, globals, globals, (PyObject**)NULL, 0, // args, argcount (PyObject**)NULL, 0, // kwnames, kwargs, 0, 2, // kwcount, kwstep (PyObject**)NULL, 0, // defs, defcount NULL, NULL, // kwdefs, closure NULL, NULL // name, qualname ); if(v != NULL) { Py_DECREF(v); Py_RETURN_NONE; } exit: Py_XDECREF(name); Py_XDECREF(code); return NULL; } static PyObject *SFLObject_is_package(SourcelessFileLoader *self, PyObject *arg) { char *name = NULL; if (!PyArg_Parse(arg, "z:is_package", &name)) return 0; if (!name) name = self->name; // path = self.get_filename(fullname) if (strncmp(name, self->name, self->namelen)) { PyErr_Format(PyExc_ImportError, "loader for %s cannot handle %s\n", self->name, name); return NULL; } if (_startswith(basename(self->path), "__init__")) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyMethodDef SFLObject_methods[] = { {"is_package", (PyCFunction)SFLObject_is_package, METH_O, PyDoc_STR("")}, {"create_module", (PyCFunction)SFLObject_create_module, METH_O, PyDoc_STR("")}, {"load_module", (PyCFunction)SFLObject_load_module, METH_FASTCALL, PyDoc_STR("")}, {"exec_module", (PyCFunction)SFLObject_exec_module, METH_O, PyDoc_STR("")}, {"get_filename", (PyCFunction)SFLObject_get_filename, METH_O, PyDoc_STR("")}, {"get_data", (PyCFunction)SFLObject_get_data, METH_O, PyDoc_STR("")}, {"get_code", (PyCFunction)SFLObject_get_code, METH_O, PyDoc_STR("")}, {"get_source", (PyCFunction)SFLObject_get_source, METH_O, PyDoc_STR("")}, {NULL, NULL} // sentinel }; static PyTypeObject SourcelessFileLoaderType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "_imp.SourcelessFileLoader", /*tp_name*/ .tp_basicsize = sizeof(SourcelessFileLoader), /*tp_basicsize*/ .tp_dealloc = (destructor)SFLObject_dealloc, /*tp_dealloc*/ .tp_hash = (hashfunc)SFLObject_hash, /*tp_hash*/ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ .tp_richcompare = (richcmpfunc)SFLObject_richcompare, /*tp_richcompare*/ .tp_methods = SFLObject_methods, /*tp_methods*/ .tp_init = (initproc)SFLObject_init, /*tp_init*/ .tp_new = (newfunc)SFLObject_new, /*tp_new*/ }; typedef struct { PyObject_HEAD } CosmoImporter; static PyTypeObject CosmoImporterType; #define CosmoImporterCheck(o) (Py_TYPE(o) == &CosmoImporterType) static PyObject *CosmoImporter_find_spec(PyObject *cls, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { static const char *const _keywords[] = {"fullname", "path", "target", NULL}; static _PyArg_Parser _parser = {"U|OO", _keywords, 0}; _Py_IDENTIFIER(_get_builtin_spec); _Py_IDENTIFIER(_get_frozen_spec); _Py_IDENTIFIER(_get_zipstore_spec); PyObject *fullname = NULL; PyObject *path = NULL; /* path is a LIST! it contains strings similar to those in sys.path, * ie folders that are likely to contain a particular file. * during startup the expected scenario is checking the ZIP store * of the APE, so we ignore path and let these slower cases to * handled by the importer objects already provided by Python. */ PyObject *target = NULL; PyInterpreterState *interp = PyThreadState_GET()->interp; const struct _frozen *p = NULL; static const char basepath[] = "/zip/.python/"; const char *cname = NULL; Py_ssize_t cnamelen = 0; char *newpath = NULL; Py_ssize_t newpathsize = 0; Py_ssize_t newpathlen = 0; Py_ssize_t i = 0; SourcelessFileLoader *loader = NULL; PyObject *origin = NULL; int inside_zip = 0; int is_package = 0; int is_available = 0; struct stat stinfo; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwargs, &_parser, &fullname, &path, &target)) { return NULL; } if (fullname == NULL) { PyErr_SetString(PyExc_ImportError, "fullname not provided\n"); return NULL; } if ((!path || path == Py_None)) { /* we do some of BuiltinImporter's work */ if (is_builtin(fullname) == 1) { return _PyObject_CallMethodIdObjArgs( interp->importlib, &PyId__get_builtin_spec, fullname, NULL); } /* we do some of FrozenImporter's work */ else if ((p = find_frozen(fullname)) != NULL) { return _PyObject_CallMethodIdObjArgs(interp->importlib, &PyId__get_frozen_spec, fullname, PyBool_FromLong(p->size < 0), NULL); } } if (!PyArg_Parse(fullname, "z#:find_spec", &cname, &cnamelen)) return 0; /* before checking within the zip store, * we can check cname here to skip any values * of cname that we know for sure won't be there, * because worst case is two failed stat calls here */ newpathsize = sizeof(basepath) + cnamelen + sizeof("/__init__.pyc") + 1; newpath = _gc(malloc(newpathsize)); bzero(newpath, newpathsize); /* performing a memccpy sequence equivalent to: * snprintf(newpath, newpathsize, "/zip/.python/%s.pyc", cname); */ memccpy(newpath, basepath, '\0', newpathsize); memccpy(newpath + sizeof(basepath) - 1, cname, '\0', newpathsize - sizeof(basepath)); memccpy(newpath + sizeof(basepath) + cnamelen - 1, ".pyc", '\0', newpathsize - (sizeof(basepath) + cnamelen)); /* if cname part of newpath has '.' (e.g. encodings.utf_8) convert them to '/' */ for (i = sizeof(basepath); i < sizeof(basepath) + cnamelen - 1; i++) { if (newpath[i] == '.') newpath[i] = '/'; } is_available = inside_zip || !stat(newpath, &stinfo); if (is_package || !is_available) { memccpy(newpath + sizeof(basepath) + cnamelen - 1, "/__init__.pyc", '\0', newpathsize); is_available = is_available || !stat(newpath, &stinfo); is_package = 1; } if (is_available) { newpathlen = strlen(newpath); loader = SFLObject_new(NULL, NULL, NULL); origin = PyUnicode_FromStringAndSize(newpath, newpathlen); if (loader == NULL || origin == NULL) { return NULL; } loader->name = strdup(cname); loader->namelen = cnamelen; loader->path = strdup(newpath); loader->pathlen = newpathlen; loader->present = 1; /* this means we avoid atleast one stat call (the one in SFLObject_get_code) */ return _PyObject_CallMethodIdObjArgs(interp->importlib, &PyId__get_zipstore_spec, fullname, (PyObject *)loader, (PyObject *)origin, PyBool_FromLong(is_package), NULL); } Py_RETURN_NONE; } static PyMethodDef CosmoImporter_methods[] = { {"find_spec", (PyCFunction)CosmoImporter_find_spec, METH_FASTCALL | METH_KEYWORDS | METH_CLASS, PyDoc_STR("")}, {NULL, NULL} // sentinel }; static PyTypeObject CosmoImporterType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "_imp.CosmoImporter", /* tp_name */ .tp_dealloc = 0, .tp_basicsize = sizeof(CosmoImporter), /* tp_basicsize */ .tp_flags = Py_TPFLAGS_DEFAULT, /* tp_flags */ .tp_methods = CosmoImporter_methods, /* tp_methods */ .tp_init = 0, .tp_new = 0, }; PyDoc_STRVAR(doc_imp, "(Extremely) low-level import machinery bits as used by importlib and imp."); static PyMethodDef imp_methods[] = { _IMP_EXTENSION_SUFFIXES_METHODDEF _IMP_LOCK_HELD_METHODDEF _IMP_ACQUIRE_LOCK_METHODDEF _IMP_RELEASE_LOCK_METHODDEF _IMP_GET_FROZEN_OBJECT_METHODDEF _IMP_IS_FROZEN_PACKAGE_METHODDEF _IMP_CREATE_BUILTIN_METHODDEF _IMP_INIT_FROZEN_METHODDEF _IMP_IS_BUILTIN_METHODDEF _IMP_IS_FROZEN_METHODDEF _IMP_CREATE_DYNAMIC_METHODDEF _IMP_EXEC_DYNAMIC_METHODDEF _IMP_EXEC_BUILTIN_METHODDEF _IMP__FIX_CO_FILENAME_METHODDEF {"_path_is_mode_type", (PyCFunction)_imp_path_is_mode_type, METH_FASTCALL, _imp_path_is_mode_type_doc}, {"_path_isfile", _imp_path_isfile, METH_O, _imp_path_isfile_doc}, {"_path_isdir", _imp_path_isdir, METH_O, _imp_path_isdir_doc}, {"_calc_mode", _imp_calc_mode, METH_O, _imp_calc_mode_doc}, {"_calc_mtime_and_size", _imp_calc_mtime_and_size, METH_O, _imp_calc_mtime_and_size_doc}, {"_w_long", _imp_w_long, METH_O, _imp_w_long_doc}, {"_r_long", _imp_r_long, METH_O, _imp_r_long_doc}, {"_relax_case", _imp_relax_case, METH_NOARGS, NULL}, {"_write_atomic", (PyCFunction)_imp_write_atomic, METH_FASTCALL, _imp_write_atomic_doc}, {"_compile_bytecode", (PyCFunction)_imp_compile_bytecode, METH_FASTCALL | METH_KEYWORDS , _imp_compile_bytecode_doc}, {"_validate_bytecode_header", (PyCFunction)_imp_validate_bytecode_header, METH_FASTCALL | METH_KEYWORDS , _imp_validate_bytecode_header_doc}, {"cache_from_source", (PyCFunction)_imp_cache_from_source, METH_FASTCALL | METH_KEYWORDS , _imp_cache_from_source_doc}, {"source_from_cache", (PyCFunction)_imp_source_from_cache, METH_O , _imp_source_from_cache_doc}, {NULL, NULL} /* sentinel */ }; static struct PyModuleDef impmodule = { PyModuleDef_HEAD_INIT, "_imp", doc_imp, 0, imp_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_imp(void) { PyObject *m, *d; m = PyModule_Create(&impmodule); if (m == NULL) goto failure; d = PyModule_GetDict(m); if (d == NULL) goto failure; if (PyType_Ready(&SourcelessFileLoaderType) < 0) goto failure; if (PyModule_AddObject(m, "SourcelessFileLoader", (PyObject*)&SourcelessFileLoaderType) < 0) goto failure; if (PyType_Ready(&CosmoImporterType) < 0) goto failure; if (PyModule_AddObject(m, "CosmoImporter", (PyObject*)&CosmoImporterType) < 0) goto failure; /* test_atexit segfaults without the below incref, but * I'm not supposed to Py_INCREF a static PyTypeObject, so * what's going on? */ Py_INCREF(&CosmoImporterType); return m; failure: Py_XDECREF(m); return NULL; } /* API for embedding applications that want to add their own entries to the table of built-in modules. This should normally be called *before* Py_Initialize(). When the table resize fails, -1 is returned and the existing table is unchanged. After a similar function by Just van Rossum. */ int PyImport_ExtendInittab(struct _inittab *newtab) { static struct _inittab *our_copy = NULL; struct _inittab *p; int i, n; /* Count the number of entries in both tables */ for (n = 0; newtab[n].name != NULL; n++) ; if (n == 0) return 0; /* Nothing to do */ for (i = 0; PyImport_Inittab[i].name != NULL; i++) ; /* Allocate new memory for the combined table */ p = our_copy; PyMem_RESIZE(p, struct _inittab, i+n+1); if (p == NULL) return -1; /* Copy the tables into the new memory */ if (our_copy != PyImport_Inittab) memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); PyImport_Inittab = our_copy = p; memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); return 0; } /* Shorthand to add a single entry given a name and a function */ int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void)) { struct _inittab newtab[2]; bzero(newtab, sizeof newtab); newtab[0].name = name; newtab[0].initfunc = initfunc; return PyImport_ExtendInittab(newtab); }
89,659
2,967
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/getargs.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" /* clang-format off */ #define FLAG_COMPAT 1 #define FLAG_SIZE_T 2 typedef int (*destr_t)(PyObject *, void *); /* Keep track of "objects" that have been allocated or initialized and which will need to be deallocated or cleaned up somehow if overall parsing fails. */ typedef struct { void *item; destr_t destructor; } freelistentry_t; typedef struct { freelistentry_t *entries; int first_available; int entries_malloced; } freelist_t; #define STATIC_FREELIST_ENTRIES 8 static const char *skipitem(const char **, va_list *, int); static int vgetargs1_impl(PyObject *args, PyObject **stack, Py_ssize_t nargs, const char *format, va_list *p_va, int flags); static int vgetargs1(PyObject *, const char *, va_list *, int); static void seterror(Py_ssize_t, const char *, int *, const char *, const char *); static const char *convertitem(PyObject *, const char **, va_list *, int, int *, char *, size_t, freelist_t *); static const char *converttuple(PyObject *, const char **, va_list *, int, int *, char *, size_t, int, freelist_t *); static const char *convertsimple(PyObject *, const char **, va_list *, int, char *, size_t, freelist_t *); static Py_ssize_t convertbuffer(PyObject *, void **, const char **); static int getbuffer(PyObject *, Py_buffer *, const char**); static int vgetargskeywords(PyObject *, PyObject *, const char *, char **, va_list *, int); static int vgetargskeywordsfast(PyObject *, PyObject *, struct _PyArg_Parser *, va_list *, int); static int vgetargskeywordsfast_impl(PyObject **, Py_ssize_t, PyObject *, PyObject *, struct _PyArg_Parser *, va_list *, int ); /** * Deconstruct argument lists of “old-style” functions. * * These are functions which use the METH_O parameter parsing method, * which has been removed in Python 3. This is not recommended for use * in parameter parsing in new code, and most code in the standard * interpreter has been modified to no longer use this for that purpose. * It does remain a convenient way to decompose other tuples, however, * and may continue to be used for that purpose. */ int PyArg_Parse(PyObject *args, const char *format, ...) { int retval; va_list va; va_start(va, format); retval = vgetargs1(args, format, &va, FLAG_COMPAT); va_end(va); return retval; } int _PyArg_Parse_SizeT(PyObject *args, const char *format, ...) { int retval; va_list va; va_start(va, format); retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T); va_end(va); return retval; } int PyArg_ParseTuple(PyObject *args, const char *format, ...) { int retval; va_list va; va_start(va, format); retval = vgetargs1(args, format, &va, 0); va_end(va); return retval; } int _PyArg_ParseTuple_SizeT(PyObject *args, const char *format, ...) { int retval; va_list va; va_start(va, format); retval = vgetargs1(args, format, &va, FLAG_SIZE_T); va_end(va); return retval; } int _PyArg_ParseStack(PyObject **args, Py_ssize_t nargs, const char *format, ...) { int retval; va_list va; va_start(va, format); retval = vgetargs1_impl(NULL, args, nargs, format, &va, 0); va_end(va); return retval; } int _PyArg_ParseStack_SizeT(PyObject **args, Py_ssize_t nargs, const char *format, ...) { int retval; va_list va; va_start(va, format); retval = vgetargs1_impl(NULL, args, nargs, format, &va, FLAG_SIZE_T); va_end(va); return retval; } int PyArg_VaParse(PyObject *args, const char *format, va_list va) { va_list lva; int retval; va_copy(lva, va); retval = vgetargs1(args, format, &lva, 0); va_end(lva); return retval; } int _PyArg_VaParse_SizeT(PyObject *args, const char *format, va_list va) { va_list lva; int retval; va_copy(lva, va); retval = vgetargs1(args, format, &lva, FLAG_SIZE_T); va_end(lva); return retval; } /* Handle cleanup of allocated memory in case of exception */ static int cleanup_ptr(PyObject *self, void *ptr) { if (ptr) { PyMem_FREE(ptr); } return 0; } static int cleanup_buffer(PyObject *self, void *ptr) { Py_buffer *buf = (Py_buffer *)ptr; if (buf) { PyBuffer_Release(buf); } return 0; } static int addcleanup(void *ptr, freelist_t *freelist, destr_t destructor) { int index; index = freelist->first_available; freelist->first_available += 1; freelist->entries[index].item = ptr; freelist->entries[index].destructor = destructor; return 0; } static int cleanreturn(int retval, freelist_t *freelist) { int index; if (retval == 0) { /* A failure occurred, therefore execute all of the cleanup functions. */ for (index = 0; index < freelist->first_available; ++index) { freelist->entries[index].destructor(NULL, freelist->entries[index].item); } } if (freelist->entries_malloced) PyMem_FREE(freelist->entries); return retval; } static int vgetargs1_impl(PyObject *compat_args, PyObject **stack, Py_ssize_t nargs, const char *format, va_list *p_va, int flags) { char msgbuf[256]; int levels[32]; const char *fname = NULL; const char *message = NULL; int min = -1; int max = 0; int level = 0; int endfmt = 0; const char *formatsave = format; Py_ssize_t i; const char *msg; int compat = flags & FLAG_COMPAT; freelistentry_t static_entries[STATIC_FREELIST_ENTRIES]; freelist_t freelist; assert(nargs == 0 || stack != NULL); freelist.entries = static_entries; freelist.first_available = 0; freelist.entries_malloced = 0; flags = flags & ~FLAG_COMPAT; while (endfmt == 0) { int c = *format++; switch (c) { case '(': if (level == 0) max++; level++; if (level >= 30) Py_FatalError("too many tuple nesting levels " "in argument format string"); break; case ')': if (level == 0) Py_FatalError("excess ')' in getargs format"); else level--; break; case '\0': endfmt = 1; break; case ':': fname = format; endfmt = 1; break; case ';': message = format; endfmt = 1; break; case '|': if (level == 0) min = max; break; default: if (level == 0) { if (Py_ISALPHA(Py_CHARMASK(c))) if (c != 'e') /* skip encoded */ max++; } break; } } if (level != 0) Py_FatalError(/* '(' */ "missing ')' in getargs format"); if (min < 0) min = max; format = formatsave; if (max > STATIC_FREELIST_ENTRIES) { freelist.entries = PyMem_NEW(freelistentry_t, max); if (freelist.entries == NULL) { PyErr_NoMemory(); return 0; } freelist.entries_malloced = 1; } if (compat) { if (max == 0) { if (compat_args == NULL) return 1; PyErr_Format(PyExc_TypeError, "%.200s%s takes no arguments", fname==NULL ? "function" : fname, fname==NULL ? "" : "()"); return cleanreturn(0, &freelist); } else if (min == 1 && max == 1) { if (compat_args == NULL) { PyErr_Format(PyExc_TypeError, "%.200s%s takes at least one argument", fname==NULL ? "function" : fname, fname==NULL ? "" : "()"); return cleanreturn(0, &freelist); } msg = convertitem(compat_args, &format, p_va, flags, levels, msgbuf, sizeof(msgbuf), &freelist); if (msg == NULL) return cleanreturn(1, &freelist); seterror(levels[0], msg, levels+1, fname, message); return cleanreturn(0, &freelist); } else { PyErr_SetString(PyExc_SystemError, "old style getargs format uses new features"); return cleanreturn(0, &freelist); } } if (nargs < min || max < nargs) { if (message == NULL) PyErr_Format(PyExc_TypeError, "%.150s%s takes %s %d argument%s (%ld given)", fname==NULL ? "function" : fname, fname==NULL ? "" : "()", min==max ? "exactly" : nargs < min ? "at least" : "at most", nargs < min ? min : max, (nargs < min ? min : max) == 1 ? "" : "s", Py_SAFE_DOWNCAST(nargs, Py_ssize_t, long)); else PyErr_SetString(PyExc_TypeError, message); return cleanreturn(0, &freelist); } for (i = 0; i < nargs; i++) { if (*format == '|') format++; msg = convertitem(stack[i], &format, p_va, flags, levels, msgbuf, sizeof(msgbuf), &freelist); if (msg) { seterror(i+1, msg, levels, fname, message); return cleanreturn(0, &freelist); } } if (*format != '\0' && !Py_ISALPHA(Py_CHARMASK(*format)) && *format != '(' && *format != '|' && *format != ':' && *format != ';') { PyErr_Format(PyExc_SystemError, "bad format string: %.200s", formatsave); return cleanreturn(0, &freelist); } return cleanreturn(1, &freelist); } static int vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags) { PyObject **stack; Py_ssize_t nargs; if (!(flags & FLAG_COMPAT)) { assert(args != NULL); if (!PyTuple_Check(args)) { PyErr_SetString(PyExc_SystemError, "new style getargs format but argument is not a tuple"); return 0; } stack = &PyTuple_GET_ITEM(args, 0); nargs = PyTuple_GET_SIZE(args); } else { stack = NULL; nargs = 0; } return vgetargs1_impl(args, stack, nargs, format, p_va, flags); } static void seterror(Py_ssize_t iarg, const char *msg, int *levels, const char *fname, const char *message) { char buf[512]; int i; char *p = buf; if (PyErr_Occurred()) return; else if (message == NULL) { if (fname != NULL) { PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname); p += strlen(p); } if (iarg != 0) { PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument %" PY_FORMAT_SIZE_T "d", iarg); i = 0; p += strlen(p); while (i < 32 && levels[i] > 0 && (int)(p-buf) < 220) { PyOS_snprintf(p, sizeof(buf) - (p - buf), ", item %d", levels[i]-1); p += strlen(p); i++; } } else { PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument"); p += strlen(p); } PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg); message = buf; } if (msg[0] == '(') { PyErr_SetString(PyExc_SystemError, message); } else { PyErr_SetString(PyExc_TypeError, message); } } /* Convert a tuple argument. On entry, *p_format points to the character _after_ the opening '('. On successful exit, *p_format points to the closing ')'. If successful: *p_format and *p_va are updated, *levels and *msgbuf are untouched, and NULL is returned. If the argument is invalid: *p_format is unchanged, *p_va is undefined, *levels is a 0-terminated list of item numbers, *msgbuf contains an error message, whose format is: "must be <typename1>, not <typename2>", where: <typename1> is the name of the expected type, and <typename2> is the name of the actual type, and msgbuf is returned. */ static const char * converttuple(PyObject *arg, const char **p_format, va_list *p_va, int flags, int *levels, char *msgbuf, size_t bufsize, int toplevel, freelist_t *freelist) { int level = 0; int n = 0; const char *format = *p_format; int i; Py_ssize_t len; for (;;) { int c = *format++; if (c == '(') { if (level == 0) n++; level++; } else if (c == ')') { if (level == 0) break; level--; } else if (c == ':' || c == ';' || c == '\0') break; else if (level == 0 && Py_ISALPHA(c)) n++; } if (!PySequence_Check(arg) || PyBytes_Check(arg)) { levels[0] = 0; PyOS_snprintf(msgbuf, bufsize, toplevel ? "expected %d arguments, not %.50s" : "must be %d-item sequence, not %.50s", n, arg == Py_None ? "None" : arg->ob_type->tp_name); return msgbuf; } len = PySequence_Size(arg); if (len != n) { levels[0] = 0; if (toplevel) { PyOS_snprintf(msgbuf, bufsize, "expected %d arguments, not %" PY_FORMAT_SIZE_T "d", n, len); } else { PyOS_snprintf(msgbuf, bufsize, "must be sequence of length %d, " "not %" PY_FORMAT_SIZE_T "d", n, len); } return msgbuf; } format = *p_format; for (i = 0; i < n; i++) { const char *msg; PyObject *item; item = PySequence_GetItem(arg, i); if (item == NULL) { PyErr_Clear(); levels[0] = i+1; levels[1] = 0; strncpy(msgbuf, "is not retrievable", bufsize); return msgbuf; } msg = convertitem(item, &format, p_va, flags, levels+1, msgbuf, bufsize, freelist); /* PySequence_GetItem calls tp->sq_item, which INCREFs */ Py_XDECREF(item); if (msg != NULL) { levels[0] = i+1; return msg; } } *p_format = format; return NULL; } /* Convert a single item. */ static const char * convertitem(PyObject *arg, const char **p_format, va_list *p_va, int flags, int *levels, char *msgbuf, size_t bufsize, freelist_t *freelist) { const char *msg; const char *format = *p_format; if (*format == '(' /* ')' */) { format++; msg = converttuple(arg, &format, p_va, flags, levels, msgbuf, bufsize, 0, freelist); if (msg == NULL) format++; } else { msg = convertsimple(arg, &format, p_va, flags, msgbuf, bufsize, freelist); if (msg != NULL) levels[0] = 0; } if (msg == NULL) *p_format = format; return msg; } /* Format an error message generated by convertsimple(). */ static const char * converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize) { assert(expected != NULL); assert(arg != NULL); if (expected[0] == '(') { PyOS_snprintf(msgbuf, bufsize, "%.100s", expected); } else { PyOS_snprintf(msgbuf, bufsize, "must be %.50s, not %.50s", expected, arg == Py_None ? "None" : arg->ob_type->tp_name); } return msgbuf; } #define CONV_UNICODE "(unicode conversion error)" /* Explicitly check for float arguments when integers are expected. Return 1 for error, 0 if ok. */ static int float_argument_error(PyObject *arg) { if (PyFloat_Check(arg)) { PyErr_SetString(PyExc_TypeError, "integer argument expected, got float" ); return 1; } else return 0; } /* Convert a non-tuple argument. Return NULL if conversion went OK, or a string with a message describing the failure. The message is formatted as "must be <desired type>, not <actual type>". When failing, an exception may or may not have been raised. Don't call if a tuple is expected. When you add new format codes, please don't forget poor skipitem() below. */ static const char * convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags, char *msgbuf, size_t bufsize, freelist_t *freelist) { /* For # codes */ #define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\ if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \ else q=va_arg(*p_va, int*); #define STORE_SIZE(s) \ if (flags & FLAG_SIZE_T) \ *q2=s; \ else { \ if (INT_MAX < s) { \ PyErr_SetString(PyExc_OverflowError, \ "size does not fit in an int"); \ return converterr("", arg, msgbuf, bufsize); \ } \ *q = (int)s; \ } #define BUFFER_LEN ((flags & FLAG_SIZE_T) ? *q2:*q) #define RETURN_ERR_OCCURRED return msgbuf const char *format = *p_format; char c = *format++; char *sarg; switch (c) { case 'b': { /* unsigned byte -- very short int */ char *p = va_arg(*p_va, char *); long ival; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; ival = PyLong_AsLong(arg); if (ival == -1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; else if (ival < 0) { PyErr_SetString(PyExc_OverflowError, "unsigned byte integer is less than minimum"); RETURN_ERR_OCCURRED; } else if (ival > UCHAR_MAX) { PyErr_SetString(PyExc_OverflowError, "unsigned byte integer is greater than maximum"); RETURN_ERR_OCCURRED; } else *p = (unsigned char) ival; break; } case 'B': {/* byte sized bitfield - both signed and unsigned values allowed */ char *p = va_arg(*p_va, char *); long ival; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; ival = PyLong_AsUnsignedLongMask(arg); if (ival == -1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; else *p = (unsigned char) ival; break; } case 'h': {/* signed short int */ short *p = va_arg(*p_va, short *); long ival; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; ival = PyLong_AsLong(arg); if (ival == -1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; else if (ival < SHRT_MIN) { PyErr_SetString(PyExc_OverflowError, "signed short integer is less than minimum"); RETURN_ERR_OCCURRED; } else if (ival > SHRT_MAX) { PyErr_SetString(PyExc_OverflowError, "signed short integer is greater than maximum"); RETURN_ERR_OCCURRED; } else *p = (short) ival; break; } case 'H': { /* short int sized bitfield, both signed and unsigned allowed */ unsigned short *p = va_arg(*p_va, unsigned short *); long ival; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; ival = PyLong_AsUnsignedLongMask(arg); if (ival == -1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; else *p = (unsigned short) ival; break; } case 'i': {/* signed int */ int *p = va_arg(*p_va, int *); long ival; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; ival = PyLong_AsLong(arg); if (ival == -1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; else if (ival > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "signed integer is greater than maximum"); RETURN_ERR_OCCURRED; } else if (ival < INT_MIN) { PyErr_SetString(PyExc_OverflowError, "signed integer is less than minimum"); RETURN_ERR_OCCURRED; } else *p = ival; break; } case 'I': { /* int sized bitfield, both signed and unsigned allowed */ unsigned int *p = va_arg(*p_va, unsigned int *); unsigned int ival; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; ival = (unsigned int)PyLong_AsUnsignedLongMask(arg); if (ival == (unsigned int)-1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; else *p = ival; break; } case 'n': /* Py_ssize_t */ { PyObject *iobj; Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); Py_ssize_t ival = -1; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; iobj = PyNumber_Index(arg); if (iobj != NULL) { ival = PyLong_AsSsize_t(iobj); Py_DECREF(iobj); } if (ival == -1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; *p = ival; break; } case 'l': {/* long int */ long *p = va_arg(*p_va, long *); long ival; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; ival = PyLong_AsLong(arg); if (ival == -1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; else *p = ival; break; } case 'k': { /* long sized bitfield */ unsigned long *p = va_arg(*p_va, unsigned long *); unsigned long ival; if (PyLong_Check(arg)) ival = PyLong_AsUnsignedLongMask(arg); else return converterr("int", arg, msgbuf, bufsize); *p = ival; break; } case 'L': {/* long long */ long long *p = va_arg( *p_va, long long * ); long long ival; if (float_argument_error(arg)) RETURN_ERR_OCCURRED; ival = PyLong_AsLongLong(arg); if (ival == (long long)-1 && PyErr_Occurred()) RETURN_ERR_OCCURRED; else *p = ival; break; } case 'K': { /* long long sized bitfield */ unsigned long long *p = va_arg(*p_va, unsigned long long *); unsigned long long ival; if (PyLong_Check(arg)) ival = PyLong_AsUnsignedLongLongMask(arg); else return converterr("int", arg, msgbuf, bufsize); *p = ival; break; } case 'f': {/* float */ float *p = va_arg(*p_va, float *); double dval = PyFloat_AsDouble(arg); if (PyErr_Occurred()) RETURN_ERR_OCCURRED; else *p = (float) dval; break; } case 'd': {/* double */ double *p = va_arg(*p_va, double *); double dval = PyFloat_AsDouble(arg); if (PyErr_Occurred()) RETURN_ERR_OCCURRED; else *p = dval; break; } case 'D': {/* complex double */ Py_complex *p = va_arg(*p_va, Py_complex *); Py_complex cval; cval = PyComplex_AsCComplex(arg); if (PyErr_Occurred()) RETURN_ERR_OCCURRED; else *p = cval; break; } case 'c': {/* char */ char *p = va_arg(*p_va, char *); if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) *p = PyBytes_AS_STRING(arg)[0]; else if (PyByteArray_Check(arg) && PyByteArray_Size(arg) == 1) *p = PyByteArray_AS_STRING(arg)[0]; else return converterr("a byte string of length 1", arg, msgbuf, bufsize); break; } case 'C': {/* unicode char */ int *p = va_arg(*p_va, int *); int kind; void *data; if (!PyUnicode_Check(arg)) return converterr("a unicode character", arg, msgbuf, bufsize); if (PyUnicode_READY(arg)) RETURN_ERR_OCCURRED; if (PyUnicode_GET_LENGTH(arg) != 1) return converterr("a unicode character", arg, msgbuf, bufsize); kind = PyUnicode_KIND(arg); data = PyUnicode_DATA(arg); *p = PyUnicode_READ(kind, data, 0); break; } case 'p': {/* boolean *p*redicate */ int *p = va_arg(*p_va, int *); int val = PyObject_IsTrue(arg); if (val > 0) *p = 1; else if (val == 0) *p = 0; else RETURN_ERR_OCCURRED; break; } /* XXX WAAAAH! 's', 'y', 'z', 'u', 'Z', 'e', 'w' codes all need to be cleaned up! */ case 'y': {/* any bytes-like object */ void **p = (void **)va_arg(*p_va, char **); const char *buf; Py_ssize_t count; if (*format == '*') { if (getbuffer(arg, (Py_buffer*)p, &buf) < 0) return converterr(buf, arg, msgbuf, bufsize); format++; if (addcleanup(p, freelist, cleanup_buffer)) { return converterr( "(cleanup problem)", arg, msgbuf, bufsize); } break; } count = convertbuffer(arg, p, &buf); if (count < 0) return converterr(buf, arg, msgbuf, bufsize); if (*format == '#') { FETCH_SIZE; STORE_SIZE(count); format++; } else { if (strlen(*p) != (size_t)count) { PyErr_SetString(PyExc_ValueError, "embedded null byte"); RETURN_ERR_OCCURRED; } } break; } case 's': /* text string or bytes-like object */ case 'z': /* text string, bytes-like object or None */ { if (*format == '*') { /* "s*" or "z*" */ Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); if (c == 'z' && arg == Py_None) PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0); else if (PyUnicode_Check(arg)) { Py_ssize_t len; sarg = PyUnicode_AsUTF8AndSize(arg, &len); if (sarg == NULL) return converterr(CONV_UNICODE, arg, msgbuf, bufsize); PyBuffer_FillInfo(p, arg, sarg, len, 1, 0); } else { /* any bytes-like object */ const char *buf; if (getbuffer(arg, p, &buf) < 0) return converterr(buf, arg, msgbuf, bufsize); } if (addcleanup(p, freelist, cleanup_buffer)) { return converterr( "(cleanup problem)", arg, msgbuf, bufsize); } format++; } else if (*format == '#') { /* a string or read-only bytes-like object */ /* "s#" or "z#" */ void **p = (void **)va_arg(*p_va, char **); FETCH_SIZE; if (c == 'z' && arg == Py_None) { *p = NULL; STORE_SIZE(0); } else if (PyUnicode_Check(arg)) { Py_ssize_t len; sarg = PyUnicode_AsUTF8AndSize(arg, &len); if (sarg == NULL) return converterr(CONV_UNICODE, arg, msgbuf, bufsize); *p = sarg; STORE_SIZE(len); } else { /* read-only bytes-like object */ /* XXX Really? */ const char *buf; Py_ssize_t count = convertbuffer(arg, p, &buf); if (count < 0) return converterr(buf, arg, msgbuf, bufsize); STORE_SIZE(count); } format++; } else { /* "s" or "z" */ char **p = va_arg(*p_va, char **); Py_ssize_t len; sarg = NULL; if (c == 'z' && arg == Py_None) *p = NULL; else if (PyUnicode_Check(arg)) { sarg = PyUnicode_AsUTF8AndSize(arg, &len); if (sarg == NULL) return converterr(CONV_UNICODE, arg, msgbuf, bufsize); if (strlen(sarg) != (size_t)len) { PyErr_SetString(PyExc_ValueError, "embedded null character"); RETURN_ERR_OCCURRED; } *p = sarg; } else return converterr(c == 'z' ? "str or None" : "str", arg, msgbuf, bufsize); } break; } case 'u': /* raw unicode buffer (Py_UNICODE *) */ case 'Z': /* raw unicode buffer or None */ { Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); if (*format == '#') { /* "u#" or "Z#" */ FETCH_SIZE; if (c == 'Z' && arg == Py_None) { *p = NULL; STORE_SIZE(0); } else if (PyUnicode_Check(arg)) { Py_ssize_t len; *p = PyUnicode_AsUnicodeAndSize(arg, &len); if (*p == NULL) RETURN_ERR_OCCURRED; STORE_SIZE(len); } else return converterr(c == 'Z' ? "str or None" : "str", arg, msgbuf, bufsize); format++; } else { /* "u" or "Z" */ if (c == 'Z' && arg == Py_None) *p = NULL; else if (PyUnicode_Check(arg)) { Py_ssize_t len; *p = PyUnicode_AsUnicodeAndSize(arg, &len); if (*p == NULL) RETURN_ERR_OCCURRED; if (wcslen(*p) != (size_t)len) { PyErr_SetString(PyExc_ValueError, "embedded null character"); RETURN_ERR_OCCURRED; } } else return converterr(c == 'Z' ? "str or None" : "str", arg, msgbuf, bufsize); } break; } case 'e': {/* encoded string */ char **buffer; const char *encoding; PyObject *s; int recode_strings; Py_ssize_t size; const char *ptr; /* Get 'e' parameter: the encoding name */ encoding = (const char *)va_arg(*p_va, const char *); if (encoding == NULL) encoding = PyUnicode_GetDefaultEncoding(); /* Get output buffer parameter: 's' (recode all objects via Unicode) or 't' (only recode non-string objects) */ if (*format == 's') recode_strings = 1; else if (*format == 't') recode_strings = 0; else return converterr( "(unknown parser marker combination)", arg, msgbuf, bufsize); buffer = (char **)va_arg(*p_va, char **); format++; if (buffer == NULL) return converterr("(buffer is NULL)", arg, msgbuf, bufsize); /* Encode object */ if (!recode_strings && (PyBytes_Check(arg) || PyByteArray_Check(arg))) { s = arg; Py_INCREF(s); if (PyObject_AsCharBuffer(s, &ptr, &size) < 0) return converterr("(AsCharBuffer failed)", arg, msgbuf, bufsize); } else if (PyUnicode_Check(arg)) { /* Encode object; use default error handling */ s = PyUnicode_AsEncodedString(arg, encoding, NULL); if (s == NULL) return converterr("(encoding failed)", arg, msgbuf, bufsize); assert(PyBytes_Check(s)); size = PyBytes_GET_SIZE(s); ptr = PyBytes_AS_STRING(s); if (ptr == NULL) ptr = ""; } else { return converterr( recode_strings ? "str" : "str, bytes or bytearray", arg, msgbuf, bufsize); } /* Write output; output is guaranteed to be 0-terminated */ if (*format == '#') { /* Using buffer length parameter '#': - if *buffer is NULL, a new buffer of the needed size is allocated and the data copied into it; *buffer is updated to point to the new buffer; the caller is responsible for PyMem_Free()ing it after usage - if *buffer is not NULL, the data is copied to *buffer; *buffer_len has to be set to the size of the buffer on input; buffer overflow is signalled with an error; buffer has to provide enough room for the encoded string plus the trailing 0-byte - in both cases, *buffer_len is updated to the size of the buffer /excluding/ the trailing 0-byte */ FETCH_SIZE; format++; if (q == NULL && q2 == NULL) { Py_DECREF(s); return converterr( "(buffer_len is NULL)", arg, msgbuf, bufsize); } if (*buffer == NULL) { *buffer = PyMem_NEW(char, size + 1); if (*buffer == NULL) { Py_DECREF(s); PyErr_NoMemory(); RETURN_ERR_OCCURRED; } if (addcleanup(*buffer, freelist, cleanup_ptr)) { Py_DECREF(s); return converterr( "(cleanup problem)", arg, msgbuf, bufsize); } } else { if (size + 1 > BUFFER_LEN) { Py_DECREF(s); PyErr_Format(PyExc_ValueError, "encoded string too long " "(%zd, maximum length %zd)", (Py_ssize_t)size, (Py_ssize_t)(BUFFER_LEN-1)); RETURN_ERR_OCCURRED; } } memcpy(*buffer, ptr, size+1); STORE_SIZE(size); } else { /* Using a 0-terminated buffer: - the encoded string has to be 0-terminated for this variant to work; if it is not, an error raised - a new buffer of the needed size is allocated and the data copied into it; *buffer is updated to point to the new buffer; the caller is responsible for PyMem_Free()ing it after usage */ if ((Py_ssize_t)strlen(ptr) != size) { Py_DECREF(s); return converterr( "encoded string without null bytes", arg, msgbuf, bufsize); } *buffer = PyMem_NEW(char, size + 1); if (*buffer == NULL) { Py_DECREF(s); PyErr_NoMemory(); RETURN_ERR_OCCURRED; } if (addcleanup(*buffer, freelist, cleanup_ptr)) { Py_DECREF(s); return converterr("(cleanup problem)", arg, msgbuf, bufsize); } memcpy(*buffer, ptr, size+1); } Py_DECREF(s); break; } case 'S': { /* PyBytes object */ PyObject **p = va_arg(*p_va, PyObject **); if (PyBytes_Check(arg)) *p = arg; else return converterr("bytes", arg, msgbuf, bufsize); break; } case 'Y': { /* PyByteArray object */ PyObject **p = va_arg(*p_va, PyObject **); if (PyByteArray_Check(arg)) *p = arg; else return converterr("bytearray", arg, msgbuf, bufsize); break; } case 'U': { /* PyUnicode object */ PyObject **p = va_arg(*p_va, PyObject **); if (PyUnicode_Check(arg)) { if (PyUnicode_READY(arg) == -1) RETURN_ERR_OCCURRED; *p = arg; } else return converterr("str", arg, msgbuf, bufsize); break; } case 'O': { /* object */ PyTypeObject *type; PyObject **p; if (*format == '!') { type = va_arg(*p_va, PyTypeObject*); p = va_arg(*p_va, PyObject **); format++; if (PyType_IsSubtype(arg->ob_type, type)) *p = arg; else return converterr(type->tp_name, arg, msgbuf, bufsize); } else if (*format == '&') { typedef int (*converter)(PyObject *, void *); converter convert = va_arg(*p_va, converter); void *addr = va_arg(*p_va, void *); int res; format++; if (! (res = (*convert)(arg, addr))) return converterr("(unspecified)", arg, msgbuf, bufsize); if (res == Py_CLEANUP_SUPPORTED && addcleanup(addr, freelist, convert) == -1) return converterr("(cleanup problem)", arg, msgbuf, bufsize); } else { p = va_arg(*p_va, PyObject **); *p = arg; } break; } case 'w': { /* "w*": memory buffer, read-write access */ void **p = va_arg(*p_va, void **); if (*format != '*') return converterr( "(invalid use of 'w' format character)", arg, msgbuf, bufsize); format++; /* Caller is interested in Py_buffer, and the object supports it directly. */ if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) { PyErr_Clear(); return converterr("read-write bytes-like object", arg, msgbuf, bufsize); } if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) { PyBuffer_Release((Py_buffer*)p); return converterr("contiguous buffer", arg, msgbuf, bufsize); } if (addcleanup(p, freelist, cleanup_buffer)) { return converterr( "(cleanup problem)", arg, msgbuf, bufsize); } break; } default: return converterr("(impossible<bad format char>)", arg, msgbuf, bufsize); } *p_format = format; return NULL; #undef FETCH_SIZE #undef STORE_SIZE #undef BUFFER_LEN #undef RETURN_ERR_OCCURRED } static Py_ssize_t convertbuffer(PyObject *arg, void **p, const char **errmsg) { PyBufferProcs *pb = Py_TYPE(arg)->tp_as_buffer; Py_ssize_t count; Py_buffer view; *errmsg = NULL; *p = NULL; if (pb != NULL && pb->bf_releasebuffer != NULL) { *errmsg = "read-only bytes-like object"; return -1; } if (getbuffer(arg, &view, errmsg) < 0) return -1; count = view.len; *p = view.buf; PyBuffer_Release(&view); return count; } static int getbuffer(PyObject *arg, Py_buffer *view, const char **errmsg) { if (PyObject_GetBuffer(arg, view, PyBUF_SIMPLE) != 0) { *errmsg = "bytes-like object"; return -1; } if (!PyBuffer_IsContiguous(view, 'C')) { PyBuffer_Release(view); *errmsg = "contiguous buffer"; return -1; } return 0; } /* Support for keyword arguments donated by Geoff Philbrick <[email protected]> */ /* Return false (0) for error, else true. */ int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kwargs, const char *format, char **kwlist, ...) { int retval; va_list va; if ((args == NULL || !PyTuple_Check(args)) || (kwargs != NULL && !PyDict_Check(kwargs)) || format == NULL || kwlist == NULL) { PyErr_BadInternalCall(); return 0; } va_start(va, kwlist); retval = vgetargskeywords(args, kwargs, format, kwlist, &va, 0); va_end(va); return retval; } int _PyArg_ParseTupleAndKeywords_SizeT(PyObject *args, PyObject *kwargs, const char *format, char **kwlist, ...) { int retval; va_list va; if ((args == NULL || !PyTuple_Check(args)) || (kwargs != NULL && !PyDict_Check(kwargs)) || format == NULL || kwlist == NULL) { PyErr_BadInternalCall(); return 0; } va_start(va, kwlist); retval = vgetargskeywords(args, kwargs, format, kwlist, &va, FLAG_SIZE_T); va_end(va); return retval; } int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kwargs, const char *format, char **kwlist, va_list va) { int retval; va_list lva; if ((args == NULL || !PyTuple_Check(args)) || (kwargs != NULL && !PyDict_Check(kwargs)) || format == NULL || kwlist == NULL) { PyErr_BadInternalCall(); return 0; } va_copy(lva, va); retval = vgetargskeywords(args, kwargs, format, kwlist, &lva, 0); va_end(lva); return retval; } int _PyArg_VaParseTupleAndKeywords_SizeT(PyObject *args, PyObject *kwargs, const char *format, char **kwlist, va_list va) { int retval; va_list lva; if ((args == NULL || !PyTuple_Check(args)) || (kwargs != NULL && !PyDict_Check(kwargs)) || format == NULL || kwlist == NULL) { PyErr_BadInternalCall(); return 0; } va_copy(lva, va); retval = vgetargskeywords(args, kwargs, format, kwlist, &lva, FLAG_SIZE_T); va_end(lva); return retval; } int _PyArg_ParseTupleAndKeywordsFast(PyObject *args, PyObject *kwargs, struct _PyArg_Parser *parser, ...) { int retval; va_list va; va_start(va, parser); retval = vgetargskeywordsfast(args, kwargs, parser, &va, 0); va_end(va); return retval; } int _PyArg_ParseTupleAndKeywordsFast_SizeT(PyObject *args, PyObject *kwargs, struct _PyArg_Parser *parser, ...) { int retval; va_list va; va_start(va, parser); retval = vgetargskeywordsfast(args, kwargs, parser, &va, FLAG_SIZE_T); va_end(va); return retval; } int _PyArg_ParseStackAndKeywords(PyObject **args, Py_ssize_t nargs, PyObject *kwnames, struct _PyArg_Parser *parser, ...) { int retval; va_list va; va_start(va, parser); retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va, 0); va_end(va); return retval; } int _PyArg_ParseStackAndKeywords_SizeT(PyObject **args, Py_ssize_t nargs, PyObject *kwnames, struct _PyArg_Parser *parser, ...) { int retval; va_list va; va_start(va, parser); retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va, FLAG_SIZE_T); va_end(va); return retval; } int _PyArg_VaParseTupleAndKeywordsFast(PyObject *args, PyObject *kwargs, struct _PyArg_Parser *parser, va_list va) { int retval; va_list lva; va_copy(lva, va); retval = vgetargskeywordsfast(args, kwargs, parser, &lva, 0); va_end(lva); return retval; } int _PyArg_VaParseTupleAndKeywordsFast_SizeT(PyObject *args, PyObject *kwargs, struct _PyArg_Parser *parser, va_list va) { int retval; va_list lva; va_copy(lva, va); retval = vgetargskeywordsfast(args, kwargs, parser, &lva, FLAG_SIZE_T); va_end(lva); return retval; } int PyArg_ValidateKeywordArguments(PyObject *kwargs) { if (!PyDict_Check(kwargs)) { PyErr_BadInternalCall(); return 0; } if (!_PyDict_HasOnlyStringKeys(kwargs)) { PyErr_SetString(PyExc_TypeError, "keyword arguments must be strings"); return 0; } return 1; } #define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':') static int vgetargskeywords(PyObject *args, PyObject *kwargs, const char *format, char **kwlist, va_list *p_va, int flags) { char msgbuf[512]; int levels[32]; const char *fname, *msg, *custom_msg; int min = INT_MAX; int max = INT_MAX; int i, pos, len; int skip = 0; Py_ssize_t nargs, nkwargs; PyObject *current_arg; freelistentry_t static_entries[STATIC_FREELIST_ENTRIES]; freelist_t freelist; freelist.entries = static_entries; freelist.first_available = 0; freelist.entries_malloced = 0; assert(args != NULL && PyTuple_Check(args)); assert(kwargs == NULL || PyDict_Check(kwargs)); assert(format != NULL); assert(kwlist != NULL); assert(p_va != NULL); /* grab the function name or custom error msg first (mutually exclusive) */ fname = strchr(format, ':'); if (fname) { fname++; custom_msg = NULL; } else { custom_msg = strchr(format,';'); if (custom_msg) custom_msg++; } /* scan kwlist and count the number of positional-only parameters */ for (pos = 0; kwlist[pos] && !*kwlist[pos]; pos++) { } /* scan kwlist and get greatest possible nbr of args */ for (len = pos; kwlist[len]; len++) { if (!*kwlist[len]) { PyErr_SetString(PyExc_SystemError, "Empty keyword parameter name"); return cleanreturn(0, &freelist); } } if (len > STATIC_FREELIST_ENTRIES) { freelist.entries = PyMem_NEW(freelistentry_t, len); if (freelist.entries == NULL) { PyErr_NoMemory(); return 0; } freelist.entries_malloced = 1; } nargs = PyTuple_GET_SIZE(args); nkwargs = (kwargs == NULL) ? 0 : PyDict_GET_SIZE(kwargs); if (nargs + nkwargs > len) { PyErr_Format(PyExc_TypeError, "%s%s takes at most %d argument%s (%zd given)", (fname == NULL) ? "function" : fname, (fname == NULL) ? "" : "()", len, (len == 1) ? "" : "s", nargs + nkwargs); return cleanreturn(0, &freelist); } /* convert tuple args and keyword args in same loop, using kwlist to drive process */ for (i = 0; i < len; i++) { if (*format == '|') { if (min != INT_MAX) { PyErr_SetString(PyExc_SystemError, "Invalid format string (| specified twice)"); return cleanreturn(0, &freelist); } min = i; format++; if (max != INT_MAX) { PyErr_SetString(PyExc_SystemError, "Invalid format string ($ before |)"); return cleanreturn(0, &freelist); } } if (*format == '$') { if (max != INT_MAX) { PyErr_SetString(PyExc_SystemError, "Invalid format string ($ specified twice)"); return cleanreturn(0, &freelist); } max = i; format++; if (max < pos) { PyErr_SetString(PyExc_SystemError, "Empty parameter name after $"); return cleanreturn(0, &freelist); } if (skip) { /* Now we know the minimal and the maximal numbers of * positional arguments and can raise an exception with * informative message (see below). */ break; } if (max < nargs) { PyErr_Format(PyExc_TypeError, "Function takes %s %d positional arguments" " (%d given)", (min != INT_MAX) ? "at most" : "exactly", max, nargs); return cleanreturn(0, &freelist); } } if (IS_END_OF_FORMAT(*format)) { PyErr_Format(PyExc_SystemError, "More keyword list entries (%d) than " "format specifiers (%d)", len, i); return cleanreturn(0, &freelist); } if (!skip) { if (i < nargs) { current_arg = PyTuple_GET_ITEM(args, i); } else if (nkwargs && i >= pos) { current_arg = PyDict_GetItemString(kwargs, kwlist[i]); if (current_arg) --nkwargs; } else { current_arg = NULL; } if (current_arg) { msg = convertitem(current_arg, &format, p_va, flags, levels, msgbuf, sizeof(msgbuf), &freelist); if (msg) { seterror(i+1, msg, levels, fname, custom_msg); return cleanreturn(0, &freelist); } continue; } if (i < min) { if (i < pos) { assert (min == INT_MAX); assert (max == INT_MAX); skip = 1; /* At that moment we still don't know the minimal and * the maximal numbers of positional arguments. Raising * an exception is deferred until we encounter | and $ * or the end of the format. */ } else { PyErr_Format(PyExc_TypeError, "Required argument " "'%s' (pos %d) not found", kwlist[i], i+1); return cleanreturn(0, &freelist); } } /* current code reports success when all required args * fulfilled and no keyword args left, with no further * validation. XXX Maybe skip this in debug build ? */ if (!nkwargs && !skip) { return cleanreturn(1, &freelist); } } /* We are into optional args, skip thru to any remaining * keyword args */ msg = skipitem(&format, p_va, flags); if (msg) { PyErr_Format(PyExc_SystemError, "%s: '%s'", msg, format); return cleanreturn(0, &freelist); } } if (skip) { PyErr_Format(PyExc_TypeError, "Function takes %s %d positional arguments" " (%d given)", (Py_MIN(pos, min) < i) ? "at least" : "exactly", Py_MIN(pos, min), nargs); return cleanreturn(0, &freelist); } if (!IS_END_OF_FORMAT(*format) && (*format != '|') && (*format != '$')) { PyErr_Format(PyExc_SystemError, "more argument specifiers than keyword list entries " "(remaining format:'%s')", format); return cleanreturn(0, &freelist); } if (nkwargs > 0) { PyObject *key; Py_ssize_t j; /* make sure there are no arguments given by name and position */ for (i = pos; i < nargs; i++) { current_arg = PyDict_GetItemString(kwargs, kwlist[i]); if (current_arg) { /* arg present in tuple and in dict */ PyErr_Format(PyExc_TypeError, "Argument given by name ('%s') " "and position (%d)", kwlist[i], i+1); return cleanreturn(0, &freelist); } } /* make sure there are no extraneous keyword arguments */ j = 0; while (PyDict_Next(kwargs, &j, &key, NULL)) { int match = 0; if (!PyUnicode_Check(key)) { PyErr_SetString(PyExc_TypeError, "keywords must be strings"); return cleanreturn(0, &freelist); } for (i = pos; i < len; i++) { if (_PyUnicode_EqualToASCIIString(key, kwlist[i])) { match = 1; break; } } if (!match) { PyErr_Format(PyExc_TypeError, "'%U' is an invalid keyword " "argument for this function", key); return cleanreturn(0, &freelist); } } } return cleanreturn(1, &freelist); } /* List of static parsers. */ static struct _PyArg_Parser *static_arg_parsers = NULL; static int parser_init(struct _PyArg_Parser *parser) { const char * const *kwargs; const char *format, *msg; int i, len, min, max, nkw; PyObject *kwtuple; assert(parser->format != NULL); assert(parser->keywords != NULL); if (parser->kwtuple != NULL) { return 1; } /* grab the function name or custom error msg first (mutually exclusive) */ parser->fname = strchr(parser->format, ':'); if (parser->fname) { parser->fname++; parser->custom_msg = NULL; } else { parser->custom_msg = strchr(parser->format,';'); if (parser->custom_msg) parser->custom_msg++; } kwargs = parser->keywords; /* scan kwargs and count the number of positional-only parameters */ for (i = 0; kwargs[i] && !*kwargs[i]; i++) { } parser->pos = i; /* scan kwargs and get greatest possible nbr of args */ for (; kwargs[i]; i++) { if (!*kwargs[i]) { PyErr_SetString(PyExc_SystemError, "Empty keyword parameter name"); return 0; } } len = i; min = max = INT_MAX; format = parser->format; for (i = 0; i < len; i++) { if (*format == '|') { if (min != INT_MAX) { PyErr_SetString(PyExc_SystemError, "Invalid format string (| specified twice)"); return 0; } if (max != INT_MAX) { PyErr_SetString(PyExc_SystemError, "Invalid format string ($ before |)"); return 0; } min = i; format++; } if (*format == '$') { if (max != INT_MAX) { PyErr_SetString(PyExc_SystemError, "Invalid format string ($ specified twice)"); return 0; } if (i < parser->pos) { PyErr_SetString(PyExc_SystemError, "Empty parameter name after $"); return 0; } max = i; format++; } if (IS_END_OF_FORMAT(*format)) { PyErr_Format(PyExc_SystemError, "More keyword list entries (%d) than " "format specifiers (%d)", len, i); return 0; } msg = skipitem(&format, NULL, 0); if (msg) { PyErr_Format(PyExc_SystemError, "%s: '%s'", msg, format); return 0; } } parser->min = Py_MIN(min, len); parser->max = Py_MIN(max, len); if (!IS_END_OF_FORMAT(*format) && (*format != '|') && (*format != '$')) { PyErr_Format(PyExc_SystemError, "more argument specifiers than keyword list entries " "(remaining format:'%s')", format); return 0; } nkw = len - parser->pos; kwtuple = PyTuple_New(nkw); if (kwtuple == NULL) { return 0; } kwargs = parser->keywords + parser->pos; for (i = 0; i < nkw; i++) { PyObject *str = PyUnicode_FromString(kwargs[i]); if (str == NULL) { Py_DECREF(kwtuple); return 0; } PyUnicode_InternInPlace(&str); PyTuple_SET_ITEM(kwtuple, i, str); } parser->kwtuple = kwtuple; assert(parser->next == NULL); parser->next = static_arg_parsers; static_arg_parsers = parser; return 1; } static void parser_clear(struct _PyArg_Parser *parser) { Py_CLEAR(parser->kwtuple); } static PyObject* find_keyword(PyObject *kwargs, PyObject *kwnames, PyObject **kwstack, PyObject *key) { Py_ssize_t i, nkwargs; if (kwargs != NULL) { return PyDict_GetItem(kwargs, key); } nkwargs = PyTuple_GET_SIZE(kwnames); for (i=0; i < nkwargs; i++) { PyObject *kwname = PyTuple_GET_ITEM(kwnames, i); /* ptr==ptr should match in most cases since keyword keys should be interned strings */ if (kwname == key) { return kwstack[i]; } if (!PyUnicode_Check(kwname)) { /* ignore non-string keyword keys: an error will be raised below */ continue; } if (_PyUnicode_EQ(kwname, key)) { return kwstack[i]; } } return NULL; } static int vgetargskeywordsfast_impl(PyObject **args, Py_ssize_t nargs, PyObject *kwargs, PyObject *kwnames, struct _PyArg_Parser *parser, va_list *p_va, int flags) { PyObject *kwtuple; char msgbuf[512]; int levels[32]; const char *format; const char *msg; PyObject *keyword; int i, pos, len; Py_ssize_t nkwargs; PyObject *current_arg; freelistentry_t static_entries[STATIC_FREELIST_ENTRIES]; freelist_t freelist; PyObject **kwstack = NULL; freelist.entries = static_entries; freelist.first_available = 0; freelist.entries_malloced = 0; assert(kwargs == NULL || PyDict_Check(kwargs)); assert(kwargs == NULL || kwnames == NULL); assert(p_va != NULL); if (parser == NULL) { PyErr_BadInternalCall(); return 0; } if (kwnames != NULL && !PyTuple_Check(kwnames)) { PyErr_BadInternalCall(); return 0; } if (!parser_init(parser)) { return 0; } kwtuple = parser->kwtuple; pos = parser->pos; len = pos + PyTuple_GET_SIZE(kwtuple); if (len > STATIC_FREELIST_ENTRIES) { freelist.entries = PyMem_NEW(freelistentry_t, len); if (freelist.entries == NULL) { PyErr_NoMemory(); return 0; } freelist.entries_malloced = 1; } if (kwargs != NULL) { nkwargs = PyDict_GET_SIZE(kwargs); } else if (kwnames != NULL) { nkwargs = PyTuple_GET_SIZE(kwnames); kwstack = args + nargs; } else { nkwargs = 0; } if (nargs + nkwargs > len) { PyErr_Format(PyExc_TypeError, "%s%s takes at most %d argument%s (%zd given)", (parser->fname == NULL) ? "function" : parser->fname, (parser->fname == NULL) ? "" : "()", len, (len == 1) ? "" : "s", nargs + nkwargs); return cleanreturn(0, &freelist); } if (parser->max < nargs) { PyErr_Format(PyExc_TypeError, "Function takes %s %d positional arguments (%d given)", (parser->min != INT_MAX) ? "at most" : "exactly", parser->max, nargs); return cleanreturn(0, &freelist); } format = parser->format; /* convert tuple args and keyword args in same loop, using kwtuple to drive process */ for (i = 0; i < len; i++) { if (*format == '|') { format++; } if (*format == '$') { format++; } assert(!IS_END_OF_FORMAT(*format)); if (i < nargs) { current_arg = args[i]; } else if (nkwargs && i >= pos) { keyword = PyTuple_GET_ITEM(kwtuple, i - pos); current_arg = find_keyword(kwargs, kwnames, kwstack, keyword); if (current_arg) --nkwargs; } else { current_arg = NULL; } if (current_arg) { msg = convertitem(current_arg, &format, p_va, flags, levels, msgbuf, sizeof(msgbuf), &freelist); if (msg) { seterror(i+1, msg, levels, parser->fname, parser->custom_msg); return cleanreturn(0, &freelist); } continue; } if (i < parser->min) { /* Less arguments than required */ if (i < pos) { Py_ssize_t min = Py_MIN(pos, parser->min); PyErr_Format(PyExc_TypeError, "Function takes %s %d positional arguments" " (%d given)", min < parser->max ? "at least" : "exactly", min, nargs); } else { keyword = PyTuple_GET_ITEM(kwtuple, i - pos); PyErr_Format(PyExc_TypeError, "Required argument " "'%U' (pos %d) not found", keyword, i+1); } return cleanreturn(0, &freelist); } /* current code reports success when all required args * fulfilled and no keyword args left, with no further * validation. XXX Maybe skip this in debug build ? */ if (!nkwargs) { return cleanreturn(1, &freelist); } /* We are into optional args, skip thru to any remaining * keyword args */ msg = skipitem(&format, p_va, flags); assert(msg == NULL); } assert(IS_END_OF_FORMAT(*format) || (*format == '|') || (*format == '$')); if (nkwargs > 0) { Py_ssize_t j; /* make sure there are no arguments given by name and position */ for (i = pos; i < nargs; i++) { keyword = PyTuple_GET_ITEM(kwtuple, i - pos); current_arg = find_keyword(kwargs, kwnames, kwstack, keyword); if (current_arg) { /* arg present in tuple and in dict */ PyErr_Format(PyExc_TypeError, "Argument given by name ('%U') " "and position (%d)", keyword, i+1); return cleanreturn(0, &freelist); } } /* make sure there are no extraneous keyword arguments */ j = 0; while (1) { int match; if (kwargs != NULL) { if (!PyDict_Next(kwargs, &j, &keyword, NULL)) break; } else { if (j >= PyTuple_GET_SIZE(kwnames)) break; keyword = PyTuple_GET_ITEM(kwnames, j); j++; } if (!PyUnicode_Check(keyword)) { PyErr_SetString(PyExc_TypeError, "keywords must be strings"); return cleanreturn(0, &freelist); } match = PySequence_Contains(kwtuple, keyword); if (match <= 0) { if (!match) { PyErr_Format(PyExc_TypeError, "'%U' is an invalid keyword " "argument for this function", keyword); } return cleanreturn(0, &freelist); } } } return cleanreturn(1, &freelist); } static int vgetargskeywordsfast(PyObject *args, PyObject *kwargs, struct _PyArg_Parser *parser, va_list *p_va, int flags) { PyObject **stack; Py_ssize_t nargs; if(args == NULL || !PyTuple_Check(args) || (kwargs != NULL && !PyDict_Check(kwargs))) { PyErr_BadInternalCall(); return 0; } stack = &PyTuple_GET_ITEM(args, 0); nargs = PyTuple_GET_SIZE(args); return vgetargskeywordsfast_impl(stack, nargs, kwargs, NULL, parser, p_va, flags); } static const char * skipitem(const char **p_format, va_list *p_va, int flags) { const char *format = *p_format; char c = *format++; switch (c) { /* * codes that take a single data pointer as an argument * (the type of the pointer is irrelevant) */ case 'b': /* byte -- very short int */ case 'B': /* byte as bitfield */ case 'h': /* short int */ case 'H': /* short int as bitfield */ case 'i': /* int */ case 'I': /* int sized bitfield */ case 'l': /* long int */ case 'k': /* long int sized bitfield */ case 'L': /* long long */ case 'K': /* long long sized bitfield */ case 'n': /* Py_ssize_t */ case 'f': /* float */ case 'd': /* double */ case 'D': /* complex double */ case 'c': /* char */ case 'C': /* unicode char */ case 'p': /* boolean predicate */ case 'S': /* string object */ case 'Y': /* string object */ case 'U': /* unicode string object */ { if (p_va != NULL) { (void) va_arg(*p_va, void *); } break; } /* string codes */ case 'e': /* string with encoding */ { if (p_va != NULL) { (void) va_arg(*p_va, const char *); } if (!(*format == 's' || *format == 't')) /* after 'e', only 's' and 't' is allowed */ goto err; format++; } /* fall through */ case 's': /* string */ case 'z': /* string or None */ case 'y': /* bytes */ case 'u': /* unicode string */ case 'Z': /* unicode string or None */ case 'w': /* buffer, read-write */ { if (p_va != NULL) { (void) va_arg(*p_va, char **); } if (*format == '#') { if (p_va != NULL) { if (flags & FLAG_SIZE_T) (void) va_arg(*p_va, Py_ssize_t *); else (void) va_arg(*p_va, int *); } format++; } else if ((c == 's' || c == 'z' || c == 'y' || c == 'w') && *format == '*') { format++; } break; } case 'O': /* object */ { if (*format == '!') { format++; if (p_va != NULL) { (void) va_arg(*p_va, PyTypeObject*); (void) va_arg(*p_va, PyObject **); } } else if (*format == '&') { typedef int (*converter)(PyObject *, void *); if (p_va != NULL) { (void) va_arg(*p_va, converter); (void) va_arg(*p_va, void *); } format++; } else { if (p_va != NULL) { (void) va_arg(*p_va, PyObject **); } } break; } case '(': /* bypass tuple, not handled at all previously */ { const char *msg; for (;;) { if (*format==')') break; if (IS_END_OF_FORMAT(*format)) return "Unmatched left paren in format " "string"; msg = skipitem(&format, p_va, flags); if (msg) return msg; } format++; break; } case ')': return "Unmatched right paren in format string"; default: err: return "impossible<bad format char>"; } *p_format = format; return NULL; } static int PyArg_UnpackStack_impl(PyObject **args, Py_ssize_t l, const char *name, Py_ssize_t min, Py_ssize_t max, va_list vargs) { Py_ssize_t i; PyObject **o; assert(min >= 0); assert(min <= max); if (l < min) { if (name != NULL) PyErr_Format( PyExc_TypeError, "%s expected %s%zd arguments, got %zd", name, (min == max ? "" : "at least "), min, l); else PyErr_Format( PyExc_TypeError, "unpacked tuple should have %s%zd elements," " but has %zd", (min == max ? "" : "at least "), min, l); return 0; } if (l == 0) { return 1; } if (l > max) { if (name != NULL) PyErr_Format( PyExc_TypeError, "%s expected %s%zd arguments, got %zd", name, (min == max ? "" : "at most "), max, l); else PyErr_Format( PyExc_TypeError, "unpacked tuple should have %s%zd elements," " but has %zd", (min == max ? "" : "at most "), max, l); return 0; } for (i = 0; i < l; i++) { o = va_arg(vargs, PyObject **); *o = args[i]; } return 1; } int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) { PyObject **stack; Py_ssize_t nargs; int retval; va_list vargs; if (!PyTuple_Check(args)) { PyErr_SetString(PyExc_SystemError, "PyArg_UnpackTuple() argument list is not a tuple"); return 0; } stack = &PyTuple_GET_ITEM(args, 0); nargs = PyTuple_GET_SIZE(args); #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, max); #else va_start(vargs); #endif retval = PyArg_UnpackStack_impl(stack, nargs, name, min, max, vargs); va_end(vargs); return retval; } int _PyArg_UnpackStack(PyObject **args, Py_ssize_t nargs, const char *name, Py_ssize_t min, Py_ssize_t max, ...) { int retval; va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, max); #else va_start(vargs); #endif retval = PyArg_UnpackStack_impl(args, nargs, name, min, max, vargs); va_end(vargs); return retval; } /* For type constructors that don't take keyword args * * Sets a TypeError and returns 0 if the args/kwargs is * not empty, returns 1 otherwise */ int (_PyArg_NoKeywords)(const char *funcname, PyObject *kwargs) { if (kwargs == NULL) return 1; if (!PyDict_CheckExact(kwargs)) { PyErr_BadInternalCall(); return 0; } if (PyDict_GET_SIZE(kwargs) == 0) { return 1; } PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments", funcname); return 0; } int (_PyArg_NoStackKeywords)(const char *funcname, PyObject *kwnames) { if (kwnames == NULL) return 1; assert(PyTuple_CheckExact(kwnames)); if (PyTuple_GET_SIZE(kwnames) == 0) { return 1; } PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments", funcname); return 0; } int (_PyArg_NoPositional)(const char *funcname, PyObject *args) { if (args == NULL) return 1; if (!PyTuple_CheckExact(args)) { PyErr_BadInternalCall(); return 0; } if (PyTuple_GET_SIZE(args) == 0) return 1; PyErr_Format(PyExc_TypeError, "%s does not take positional arguments", funcname); return 0; } void _PyArg_Fini(void) { struct _PyArg_Parser *tmp, *s = static_arg_parsers; while (s) { tmp = s->next; s->next = NULL; parser_clear(s); s = tmp; } static_arg_parsers = NULL; }
74,568
2,457
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/dtoa.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/errno.h" #include "libc/math.h" #include "libc/runtime/runtime.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pyport.h" /* clang-format off */ /**************************************************************** * * The author of this software is David M. Gay. * * Copyright (c) 1991, 2000, 2001 by Lucent Technologies. * * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. * ***************************************************************/ /**************************************************************** * This is dtoa.c by David M. Gay, downloaded from * http://www.netlib.org/fp/dtoa.c on April 15, 2009 and modified for * inclusion into the Python core by Mark E. T. Dickinson and Eric V. Smith. * * Please remember to check http://www.netlib.org/fp regularly (and especially * before any Python release) for bugfixes and updates. * * The major modifications from Gay's original code are as follows: * * 0. The original code has been specialized to Python's needs by removing * many of the #ifdef'd sections. In particular, code to support VAX and * IBM floating-point formats, hex NaNs, hex floats, locale-aware * treatment of the decimal point, and setting of the inexact flag have * been removed. * * 1. We use PyMem_Malloc and PyMem_Free in place of malloc and free. * * 2. The public functions strtod, dtoa and freedtoa all now have * a _Py_dg_ prefix. * * 3. Instead of assuming that PyMem_Malloc always succeeds, we thread * PyMem_Malloc failures through the code. The functions * * Balloc, multadd, s2b, i2b, mult, pow5mult, lshift, diff, d2b * * of return type *Bigint all return NULL to indicate a malloc failure. * Similarly, rv_alloc and nrv_alloc (return type char *) return NULL on * failure. bigcomp now has return type int (it used to be void) and * returns -1 on failure and 0 otherwise. _Py_dg_dtoa returns NULL * on failure. _Py_dg_strtod indicates failure due to malloc failure * by returning -1.0, setting errno=ENOMEM and *se to s00. * * 4. The static variable dtoa_result has been removed. Callers of * _Py_dg_dtoa are expected to call _Py_dg_freedtoa to free * the memory allocated by _Py_dg_dtoa. * * 5. The code has been reformatted to better fit with Python's * C style guide (PEP 7). * * 6. A bug in the memory allocation has been fixed: to avoid FREEing memory * that hasn't been MALLOC'ed, private_mem should only be used when k <= * Kmax. * * 7. _Py_dg_strtod has been modified so that it doesn't accept strings with * leading whitespace. * ***************************************************************/ /* Please send bug reports for the original dtoa.c code to David M. Gay (dmg * at acm dot org, with " at " changed at "@" and " dot " changed to "."). * Please report bugs for this modified version using the Python issue tracker * (http://bugs.python.org). */ /* On a machine with IEEE extended-precision registers, it is * necessary to specify double-precision (53-bit) rounding precision * before invoking strtod or dtoa. If the machine uses (the equivalent * of) Intel 80x87 arithmetic, the call * _control87(PC_53, MCW_PC); * does this with many compilers. Whether this or another call is * appropriate depends on the compiler; for this to work, it may be * necessary to #include "float.h" or another system-dependent header * file. */ /* strtod for IEEE-, VAX-, and IBM-arithmetic machines. * * This strtod returns a nearest machine number to the input decimal * string (or sets errno to ERANGE). With IEEE arithmetic, ties are * broken by the IEEE round-even rule. Otherwise ties are broken by * biased rounding (add half and chop). * * Inspired loosely by William D. Clinger's paper "How to Read Floating * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101]. * * Modifications: * * 1. We only require IEEE, IBM, or VAX double-precision * arithmetic (not IEEE double-extended). * 2. We get by with floating-point arithmetic in a case that * Clinger missed -- when we're computing d * 10^n * for a small integer d and the integer n is not too * much larger than 22 (the maximum integer k for which * we can represent 10^k exactly), we may be able to * compute (d*10^k) * 10^(e-k) with just one roundoff. * 3. Rather than a bit-at-a-time adjustment of the binary * result in the hard case, we use floating-point * arithmetic to determine the adjustment to within * one bit; only in really hard cases do we need to * compute a second residual. * 4. Because of 3., we don't need a large table of powers of 10 * for ten-to-e (just some small tables, e.g. of 10^k * for 0 <= k <= 22). */ /* Linking of Python's #defines to Gay's #defines starts here. */ /* if PY_NO_SHORT_FLOAT_REPR is defined, then don't even try to compile the following code */ #ifndef PY_NO_SHORT_FLOAT_REPR #define MALLOC PyMem_Malloc #define FREE PyMem_Free /* This code should also work for ARM mixed-endian format on little-endian machines, where doubles have byte order 45670123 (in increasing address order, 0 being the least significant byte). */ #ifdef DOUBLE_IS_LITTLE_ENDIAN_IEEE754 # define IEEE_8087 #endif #if defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) || \ defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754) # define IEEE_MC68k #endif #if defined(IEEE_8087) + defined(IEEE_MC68k) != 1 #error "Exactly one of IEEE_8087 or IEEE_MC68k should be defined." #endif /* The code below assumes that the endianness of integers matches the endianness of the two 32-bit words of a double. Check this. */ #if defined(WORDS_BIGENDIAN) && (defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) || \ defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)) #error "doubles and ints have incompatible endianness" #endif #if !defined(WORDS_BIGENDIAN) && defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) #error "doubles and ints have incompatible endianness" #endif typedef uint32_t ULong; typedef int32_t Long; typedef uint64_t ULLong; #undef DEBUG #ifdef Py_DEBUG #define DEBUG #endif /* End Python #define linking */ #ifdef DEBUG #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);} #endif #ifndef PRIVATE_MEM #define PRIVATE_MEM 2304 #endif #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double)) static double private_mem[PRIVATE_mem], *pmem_next = private_mem; typedef union { double d; ULong L[2]; } U; #ifdef IEEE_8087 #define word0(x) (x)->L[1] #define word1(x) (x)->L[0] #else #define word0(x) (x)->L[0] #define word1(x) (x)->L[1] #endif #define dval(x) (x)->d #ifndef STRTOD_DIGLIM #define STRTOD_DIGLIM 40 #endif /* maximum permitted exponent value for strtod; exponents larger than MAX_ABS_EXP in absolute value get truncated to +-MAX_ABS_EXP. MAX_ABS_EXP should fit into an int. */ #ifndef MAX_ABS_EXP #define MAX_ABS_EXP 1100000000U #endif /* Bound on length of pieces of input strings in _Py_dg_strtod; specifically, this is used to bound the total number of digits ignoring leading zeros and the number of digits that follow the decimal point. Ideally, MAX_DIGITS should satisfy MAX_DIGITS + 400 < MAX_ABS_EXP; that ensures that the exponent clipping in _Py_dg_strtod can't affect the value of the output. */ #ifndef MAX_DIGITS #define MAX_DIGITS 1000000000U #endif /* Guard against trying to use the above values on unusual platforms with ints * of width less than 32 bits. */ #if MAX_ABS_EXP > INT_MAX #error "MAX_ABS_EXP should fit in an int" #endif #if MAX_DIGITS > INT_MAX #error "MAX_DIGITS should fit in an int" #endif /* The following definition of Storeinc is appropriate for MIPS processors. * An alternative that might be better on some machines is * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff) */ #if defined(IEEE_8087) #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \ ((unsigned short *)a)[0] = (unsigned short)c, a++) #else #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \ ((unsigned short *)a)[1] = (unsigned short)c, a++) #endif /* #define P DBL_MANT_DIG */ /* Ten_pmax = floor(P*log(2)/log(5)) */ /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */ /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */ /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */ #define Exp_shift 20 #define Exp_shift1 20 #define Exp_msk1 0x100000 #define Exp_msk11 0x100000 #define Exp_mask 0x7ff00000 #define P 53 #define Nbits 53 #define Bias 1023 #define Emax 1023 #define Emin (-1022) #define Etiny (-1074) /* smallest denormal is 2**Etiny */ #define Exp_1 0x3ff00000 #define Exp_11 0x3ff00000 #define Ebits 11 #define Frac_mask 0xfffff #define Frac_mask1 0xfffff #define Ten_pmax 22 #define Bletch 0x10 #define Bndry_mask 0xfffff #define Bndry_mask1 0xfffff #define Sign_bit 0x80000000 #define Log2P 1 #define Tiny0 0 #define Tiny1 1 #define Quick_max 14 #define Int_max 14 #ifndef Flt_Rounds #ifdef FLT_ROUNDS #define Flt_Rounds FLT_ROUNDS #else #define Flt_Rounds 1 #endif #endif /*Flt_Rounds*/ #define Rounding Flt_Rounds #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1)) #define Big1 0xffffffff /* Standard NaN used by _Py_dg_stdnan. */ #define NAN_WORD0 0x7ff80000 #define NAN_WORD1 0 /* Bits of the representation of positive infinity. */ #define POSINF_WORD0 0x7ff00000 #define POSINF_WORD1 0 /* struct BCinfo is used to pass information from _Py_dg_strtod to bigcomp */ typedef struct BCinfo BCinfo; struct BCinfo { int e0, nd, nd0, scale; }; #define FFFFFFFF 0xffffffffUL #define Kmax 7 /* struct Bigint is used to represent arbitrary-precision integers. These integers are stored in sign-magnitude format, with the magnitude stored as an array of base 2**32 digits. Bigints are always normalized: if x is a Bigint then x->wds >= 1, and either x->wds == 1 or x[wds-1] is nonzero. The Bigint fields are as follows: - next is a header used by Balloc and Bfree to keep track of lists of freed Bigints; it's also used for the linked list of powers of 5 of the form 5**2**i used by pow5mult. - k indicates which pool this Bigint was allocated from - maxwds is the maximum number of words space was allocated for (usually maxwds == 2**k) - sign is 1 for negative Bigints, 0 for positive. The sign is unused (ignored on inputs, set to 0 on outputs) in almost all operations involving Bigints: a notable exception is the diff function, which ignores signs on inputs but sets the sign of the output correctly. - wds is the actual number of significant words - x contains the vector of words (digits) for this Bigint, from least significant (x[0]) to most significant (x[wds-1]). */ struct Bigint { struct Bigint *next; int k, maxwds, sign, wds; ULong x[1]; }; typedef struct Bigint Bigint; #ifndef Py_USING_MEMORY_DEBUGGER /* Memory management: memory is allocated from, and returned to, Kmax+1 pools of memory, where pool k (0 <= k <= Kmax) is for Bigints b with b->maxwds == 1 << k. These pools are maintained as linked lists, with freelist[k] pointing to the head of the list for pool k. On allocation, if there's no free slot in the appropriate pool, MALLOC is called to get more memory. This memory is not returned to the system until Python quits. There's also a private memory pool that's allocated from in preference to using MALLOC. For Bigints with more than (1 << Kmax) digits (which implies at least 1233 decimal digits), memory is directly allocated using MALLOC, and freed using FREE. XXX: it would be easy to bypass this memory-management system and translate each call to Balloc into a call to PyMem_Malloc, and each Bfree to PyMem_Free. Investigate whether this has any significant performance on impact. */ static Bigint *freelist[Kmax+1]; /* Allocate space for a Bigint with up to 1<<k digits */ static Bigint * Balloc(int k) { int x; Bigint *rv; unsigned int len; if (k <= Kmax && (rv = freelist[k])) freelist[k] = rv->next; else { x = 1 << k; len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1) /sizeof(double); if (k <= Kmax && pmem_next - private_mem + len <= (Py_ssize_t)PRIVATE_mem) { rv = (Bigint*)pmem_next; pmem_next += len; } else { rv = (Bigint*)MALLOC(len*sizeof(double)); if (rv == NULL) return NULL; } rv->k = k; rv->maxwds = x; } rv->sign = rv->wds = 0; return rv; } /* Free a Bigint allocated with Balloc */ static void Bfree(Bigint *v) { if (v) { if (v->k > Kmax) FREE((void*)v); else { v->next = freelist[v->k]; freelist[v->k] = v; } } } #else /* Alternative versions of Balloc and Bfree that use PyMem_Malloc and PyMem_Free directly in place of the custom memory allocation scheme above. These are provided for the benefit of memory debugging tools like Valgrind. */ /* Allocate space for a Bigint with up to 1<<k digits */ static Bigint * Balloc(int k) { int x; Bigint *rv; unsigned int len; x = 1 << k; len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1) /sizeof(double); rv = (Bigint*)MALLOC(len*sizeof(double)); if (rv == NULL) return NULL; rv->k = k; rv->maxwds = x; rv->sign = rv->wds = 0; return rv; } /* Free a Bigint allocated with Balloc */ static void Bfree(Bigint *v) { if (v) { FREE((void*)v); } } #endif /* Py_USING_MEMORY_DEBUGGER */ #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \ y->wds*sizeof(Long) + 2*sizeof(int)) /* Multiply a Bigint b by m and add a. Either modifies b in place and returns a pointer to the modified b, or Bfrees b and returns a pointer to a copy. On failure, return NULL. In this case, b will have been already freed. */ static Bigint * multadd(Bigint *b, int m, int a) /* multiply by m and add a */ { int i, wds; ULong *x; ULLong carry, y; Bigint *b1; wds = b->wds; x = b->x; i = 0; carry = a; do { y = *x * (ULLong)m + carry; carry = y >> 32; *x++ = (ULong)(y & FFFFFFFF); } while(++i < wds); if (carry) { if (wds >= b->maxwds) { b1 = Balloc(b->k+1); if (b1 == NULL){ Bfree(b); return NULL; } Bcopy(b1, b); Bfree(b); b = b1; } b->x[wds++] = (ULong)carry; b->wds = wds; } return b; } /* convert a string s containing nd decimal digits (possibly containing a decimal separator at position nd0, which is ignored) to a Bigint. This function carries on where the parsing code in _Py_dg_strtod leaves off: on entry, y9 contains the result of converting the first 9 digits. Returns NULL on failure. */ static Bigint * s2b(const char *s, int nd0, int nd, ULong y9) { Bigint *b; int i, k; Long x, y; x = (nd + 8) / 9; for(k = 0, y = 1; x > y; y <<= 1, k++) ; b = Balloc(k); if (b == NULL) return NULL; b->x[0] = y9; b->wds = 1; if (nd <= 9) return b; s += 9; for (i = 9; i < nd0; i++) { b = multadd(b, 10, *s++ - '0'); if (b == NULL) return NULL; } s++; for(; i < nd; i++) { b = multadd(b, 10, *s++ - '0'); if (b == NULL) return NULL; } return b; } /* count leading 0 bits in the 32-bit integer x. */ static inline int hi0bits(ULong x) { #if defined(__GNUC__) && !defined(__STRICT_ANSI__) return x ? __builtin_clz(x) : 32; #else int k = 0; if (!(x & 0xffff0000)) { k = 16; x <<= 16; } if (!(x & 0xff000000)) { k += 8; x <<= 8; } if (!(x & 0xf0000000)) { k += 4; x <<= 4; } if (!(x & 0xc0000000)) { k += 2; x <<= 2; } if (!(x & 0x80000000)) { k++; if (!(x & 0x40000000)) return 32; } return k; #endif } /* count trailing 0 bits in the 32-bit integer y, and shift y right by that number of bits. */ static inline int lo0bits(ULong *y) { int k; #if defined(__GNUC__) && !defined(__STRICT_ANSI__) if (*y) { k = __builtin_ctz(*y); *y >>= k; return k; } else { return 32; } #else ULong x = *y; if (x & 7) { if (x & 1) return 0; if (x & 2) { *y = x >> 1; return 1; } *y = x >> 2; return 2; } k = 0; if (!(x & 0xffff)) { k = 16; x >>= 16; } if (!(x & 0xff)) { k += 8; x >>= 8; } if (!(x & 0xf)) { k += 4; x >>= 4; } if (!(x & 0x3)) { k += 2; x >>= 2; } if (!(x & 1)) { k++; x >>= 1; if (!x) return 32; } *y = x; return k; #endif } /* convert a small nonnegative integer to a Bigint */ static Bigint * i2b(int i) { Bigint *b; b = Balloc(1); if (b == NULL) return NULL; b->x[0] = i; b->wds = 1; return b; } /* multiply two Bigints. Returns a new Bigint, or NULL on failure. Ignores the signs of a and b. */ static Bigint * mult(Bigint *a, Bigint *b) { Bigint *c; int k, wa, wb, wc; ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0; ULong y; ULLong carry, z; if ((!a->x[0] && a->wds == 1) || (!b->x[0] && b->wds == 1)) { c = Balloc(0); if (c == NULL) return NULL; c->wds = 1; c->x[0] = 0; return c; } if (a->wds < b->wds) { c = a; a = b; b = c; } k = a->k; wa = a->wds; wb = b->wds; wc = wa + wb; if (wc > a->maxwds) k++; c = Balloc(k); if (c == NULL) return NULL; for(x = c->x, xa = x + wc; x < xa; x++) *x = 0; xa = a->x; xae = xa + wa; xb = b->x; xbe = xb + wb; xc0 = c->x; for(; xb < xbe; xc0++) { if ((y = *xb++)) { x = xa; xc = xc0; carry = 0; do { z = *x++ * (ULLong)y + *xc + carry; carry = z >> 32; *xc++ = (ULong)(z & FFFFFFFF); } while(x < xae); *xc = (ULong)carry; } } for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ; c->wds = wc; return c; } #ifndef Py_USING_MEMORY_DEBUGGER /* p5s is a linked list of powers of 5 of the form 5**(2**i), i >= 2 */ static Bigint *p5s; /* multiply the Bigint b by 5**k. Returns a pointer to the result, or NULL on failure; if the returned pointer is distinct from b then the original Bigint b will have been Bfree'd. Ignores the sign of b. */ static Bigint * pow5mult(Bigint *b, int k) { Bigint *b1, *p5, *p51; int i; static const int p05[3] = { 5, 25, 125 }; if ((i = k & 3)) { b = multadd(b, p05[i-1], 0); if (b == NULL) return NULL; } if (!(k >>= 2)) return b; p5 = p5s; if (!p5) { /* first time */ p5 = i2b(625); if (p5 == NULL) { Bfree(b); return NULL; } p5s = p5; p5->next = 0; } for(;;) { if (k & 1) { b1 = mult(b, p5); Bfree(b); b = b1; if (b == NULL) return NULL; } if (!(k >>= 1)) break; p51 = p5->next; if (!p51) { p51 = mult(p5,p5); if (p51 == NULL) { Bfree(b); return NULL; } p51->next = 0; p5->next = p51; } p5 = p51; } return b; } #else /* Version of pow5mult that doesn't cache powers of 5. Provided for the benefit of memory debugging tools like Valgrind. */ static Bigint * pow5mult(Bigint *b, int k) { Bigint *b1, *p5, *p51; int i; static const int p05[3] = { 5, 25, 125 }; if ((i = k & 3)) { b = multadd(b, p05[i-1], 0); if (b == NULL) return NULL; } if (!(k >>= 2)) return b; p5 = i2b(625); if (p5 == NULL) { Bfree(b); return NULL; } for(;;) { if (k & 1) { b1 = mult(b, p5); Bfree(b); b = b1; if (b == NULL) { Bfree(p5); return NULL; } } if (!(k >>= 1)) break; p51 = mult(p5, p5); Bfree(p5); p5 = p51; if (p5 == NULL) { Bfree(b); return NULL; } } Bfree(p5); return b; } #endif /* Py_USING_MEMORY_DEBUGGER */ /* shift a Bigint b left by k bits. Return a pointer to the shifted result, or NULL on failure. If the returned pointer is distinct from b then the original b will have been Bfree'd. Ignores the sign of b. */ static Bigint * lshift(Bigint *b, int k) { int i, k1, n, n1; Bigint *b1; ULong *x, *x1, *xe, z; if (!k || (!b->x[0] && b->wds == 1)) return b; n = k >> 5; k1 = b->k; n1 = n + b->wds + 1; for(i = b->maxwds; n1 > i; i <<= 1) k1++; b1 = Balloc(k1); if (b1 == NULL) { Bfree(b); return NULL; } x1 = b1->x; for(i = 0; i < n; i++) *x1++ = 0; x = b->x; xe = x + b->wds; if (k &= 0x1f) { k1 = 32 - k; z = 0; do { *x1++ = *x << k | z; z = *x++ >> k1; } while(x < xe); if ((*x1 = z)) ++n1; } else do *x1++ = *x++; while(x < xe); b1->wds = n1 - 1; Bfree(b); return b1; } /* Do a three-way compare of a and b, returning -1 if a < b, 0 if a == b and 1 if a > b. Ignores signs of a and b. */ static int cmp(Bigint *a, Bigint *b) { ULong *xa, *xa0, *xb, *xb0; int i, j; i = a->wds; j = b->wds; #ifdef DEBUG if (i > 1 && !a->x[i-1]) Bug("cmp called with a->x[a->wds-1] == 0"); if (j > 1 && !b->x[j-1]) Bug("cmp called with b->x[b->wds-1] == 0"); #endif if (i -= j) return i; xa0 = a->x; xa = xa0 + j; xb0 = b->x; xb = xb0 + j; for(;;) { if (*--xa != *--xb) return *xa < *xb ? -1 : 1; if (xa <= xa0) break; } return 0; } /* Take the difference of Bigints a and b, returning a new Bigint. Returns NULL on failure. The signs of a and b are ignored, but the sign of the result is set appropriately. */ static Bigint * diff(Bigint *a, Bigint *b) { Bigint *c; int i, wa, wb; ULong *xa, *xae, *xb, *xbe, *xc; ULLong borrow, y; i = cmp(a,b); if (!i) { c = Balloc(0); if (c == NULL) return NULL; c->wds = 1; c->x[0] = 0; return c; } if (i < 0) { c = a; a = b; b = c; i = 1; } else i = 0; c = Balloc(a->k); if (c == NULL) return NULL; c->sign = i; wa = a->wds; xa = a->x; xae = xa + wa; wb = b->wds; xb = b->x; xbe = xb + wb; xc = c->x; borrow = 0; do { y = (ULLong)*xa++ - *xb++ - borrow; borrow = y >> 32 & (ULong)1; *xc++ = (ULong)(y & FFFFFFFF); } while(xb < xbe); while(xa < xae) { y = *xa++ - borrow; borrow = y >> 32 & (ULong)1; *xc++ = (ULong)(y & FFFFFFFF); } while(!*--xc) wa--; c->wds = wa; return c; } /* Given a positive normal double x, return the difference between x and the next double up. Doesn't give correct results for subnormals. */ static double ulp(U *x) { Long L; U u; L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1; word0(&u) = L; word1(&u) = 0; return dval(&u); } /* Convert a Bigint to a double plus an exponent */ static double b2d(Bigint *a, int *e) { ULong *xa, *xa0, w, y, z; int k; U d; xa0 = a->x; xa = xa0 + a->wds; y = *--xa; #ifdef DEBUG if (!y) Bug("zero y in b2d"); #endif k = hi0bits(y); *e = 32 - k; if (k < Ebits) { word0(&d) = Exp_1 | y >> (Ebits - k); w = xa > xa0 ? *--xa : 0; word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k); goto ret_d; } z = xa > xa0 ? *--xa : 0; if (k -= Ebits) { word0(&d) = Exp_1 | y << k | z >> (32 - k); y = xa > xa0 ? *--xa : 0; word1(&d) = z << k | y >> (32 - k); } else { word0(&d) = Exp_1 | y; word1(&d) = z; } ret_d: return dval(&d); } /* Convert a scaled double to a Bigint plus an exponent. Similar to d2b, except that it accepts the scale parameter used in _Py_dg_strtod (which should be either 0 or 2*P), and the normalization for the return value is different (see below). On input, d should be finite and nonnegative, and d / 2**scale should be exactly representable as an IEEE 754 double. Returns a Bigint b and an integer e such that dval(d) / 2**scale = b * 2**e. Unlike d2b, b is not necessarily odd: b and e are normalized so that either 2**(P-1) <= b < 2**P and e >= Etiny, or b < 2**P and e == Etiny. This applies equally to an input of 0.0: in that case the return values are b = 0 and e = Etiny. The above normalization ensures that for all possible inputs d, 2**e gives ulp(d/2**scale). Returns NULL on failure. */ static Bigint * sd2b(U *d, int scale, int *e) { Bigint *b; b = Balloc(1); if (b == NULL) return NULL; /* First construct b and e assuming that scale == 0. */ b->wds = 2; b->x[0] = word1(d); b->x[1] = word0(d) & Frac_mask; *e = Etiny - 1 + (int)((word0(d) & Exp_mask) >> Exp_shift); if (*e < Etiny) *e = Etiny; else b->x[1] |= Exp_msk1; /* Now adjust for scale, provided that b != 0. */ if (scale && (b->x[0] || b->x[1])) { *e -= scale; if (*e < Etiny) { scale = Etiny - *e; *e = Etiny; /* We can't shift more than P-1 bits without shifting out a 1. */ assert(0 < scale && scale <= P - 1); if (scale >= 32) { /* The bits shifted out should all be zero. */ assert(b->x[0] == 0); b->x[0] = b->x[1]; b->x[1] = 0; scale -= 32; } if (scale) { /* The bits shifted out should all be zero. */ assert(b->x[0] << (32 - scale) == 0); b->x[0] = (b->x[0] >> scale) | (b->x[1] << (32 - scale)); b->x[1] >>= scale; } } } /* Ensure b is normalized. */ if (!b->x[1]) b->wds = 1; return b; } /* Convert a double to a Bigint plus an exponent. Return NULL on failure. Given a finite nonzero double d, return an odd Bigint b and exponent *e such that fabs(d) = b * 2**e. On return, *bbits gives the number of significant bits of b; that is, 2**(*bbits-1) <= b < 2**(*bbits). If d is zero, then b == 0, *e == -1010, *bbits = 0. */ static Bigint * d2b(U *d, int *e, int *bits) { Bigint *b; int de, k; ULong *x, y, z; int i; b = Balloc(1); if (b == NULL) return NULL; x = b->x; z = word0(d) & Frac_mask; word0(d) &= 0x7fffffff; /* clear sign bit, which we ignore */ if ((de = (int)(word0(d) >> Exp_shift))) z |= Exp_msk1; if ((y = word1(d))) { if ((k = lo0bits(&y))) { x[0] = y | z << (32 - k); z >>= k; } else x[0] = y; i = b->wds = (x[1] = z) ? 2 : 1; } else { k = lo0bits(&z); x[0] = z; i = b->wds = 1; k += 32; } if (de) { *e = de - Bias - (P-1) + k; *bits = P - k; } else { *e = de - Bias - (P-1) + 1 + k; *bits = 32*i - hi0bits(x[i-1]); } return b; } /* Compute the ratio of two Bigints, as a double. The result may have an error of up to 2.5 ulps. */ static double ratio(Bigint *a, Bigint *b) { U da, db; int k, ka, kb; dval(&da) = b2d(a, &ka); dval(&db) = b2d(b, &kb); k = ka - kb + 32*(a->wds - b->wds); if (k > 0) word0(&da) += k*Exp_msk1; else { k = -k; word0(&db) += k*Exp_msk1; } return dval(&da) / dval(&db); } static const double tens[] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22 }; static const double bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 }; static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128, 9007199254740992.*9007199254740992.e-256 /* = 2^106 * 1e-256 */ }; /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */ /* flag unnecessarily. It leads to a song and dance at the end of strtod. */ #define Scale_Bit 0x10 #define n_bigtens 5 #define ULbits 32 #define kshift 5 #define kmask 31 static int dshift(Bigint *b, int p2) { int rv = hi0bits(b->x[b->wds-1]) - 4; if (p2 > 0) rv -= p2; return rv & kmask; } /* special case of Bigint division. The quotient is always in the range 0 <= quotient < 10, and on entry the divisor S is normalized so that its top 4 bits (28--31) are zero and bit 27 is set. */ static int quorem(Bigint *b, Bigint *S) { int n; ULong *bx, *bxe, q, *sx, *sxe; ULLong borrow, carry, y, ys; n = S->wds; #ifdef DEBUG /*debug*/ if (b->wds > n) /*debug*/ Bug("oversize b in quorem"); #endif if (b->wds < n) return 0; sx = S->x; sxe = sx + --n; bx = b->x; bxe = bx + n; q = *bxe / (*sxe + 1); /* ensure q <= true quotient */ #ifdef DEBUG /*debug*/ if (q > 9) /*debug*/ Bug("oversized quotient in quorem"); #endif if (q) { borrow = 0; carry = 0; do { ys = *sx++ * (ULLong)q + carry; carry = ys >> 32; y = *bx - (ys & FFFFFFFF) - borrow; borrow = y >> 32 & (ULong)1; *bx++ = (ULong)(y & FFFFFFFF); } while(sx <= sxe); if (!*bxe) { bx = b->x; while(--bxe > bx && !*bxe) --n; b->wds = n; } } if (cmp(b, S) >= 0) { q++; borrow = 0; carry = 0; bx = b->x; sx = S->x; do { ys = *sx++ + carry; carry = ys >> 32; y = *bx - (ys & FFFFFFFF) - borrow; borrow = y >> 32 & (ULong)1; *bx++ = (ULong)(y & FFFFFFFF); } while(sx <= sxe); bx = b->x; bxe = bx + n; if (!*bxe) { while(--bxe > bx && !*bxe) --n; b->wds = n; } } return q; } /* sulp(x) is a version of ulp(x) that takes bc.scale into account. Assuming that x is finite and nonnegative (positive zero is fine here) and x / 2^bc.scale is exactly representable as a double, sulp(x) is equivalent to 2^bc.scale * ulp(x / 2^bc.scale). */ static double sulp(U *x, BCinfo *bc) { U u; if (bc->scale && 2*P + 1 > (int)((word0(x) & Exp_mask) >> Exp_shift)) { /* rv/2^bc->scale is subnormal */ word0(&u) = (P+2)*Exp_msk1; word1(&u) = 0; return u.d; } else { assert(word0(x) || word1(x)); /* x != 0.0 */ return ulp(x); } } /* The bigcomp function handles some hard cases for strtod, for inputs with more than STRTOD_DIGLIM digits. It's called once an initial estimate for the double corresponding to the input string has already been obtained by the code in _Py_dg_strtod. The bigcomp function is only called after _Py_dg_strtod has found a double value rv such that either rv or rv + 1ulp represents the correctly rounded value corresponding to the original string. It determines which of these two values is the correct one by computing the decimal digits of rv + 0.5ulp and comparing them with the corresponding digits of s0. In the following, write dv for the absolute value of the number represented by the input string. Inputs: s0 points to the first significant digit of the input string. rv is a (possibly scaled) estimate for the closest double value to the value represented by the original input to _Py_dg_strtod. If bc->scale is nonzero, then rv/2^(bc->scale) is the approximation to the input value. bc is a struct containing information gathered during the parsing and estimation steps of _Py_dg_strtod. Description of fields follows: bc->e0 gives the exponent of the input value, such that dv = (integer given by the bd->nd digits of s0) * 10**e0 bc->nd gives the total number of significant digits of s0. It will be at least 1. bc->nd0 gives the number of significant digits of s0 before the decimal separator. If there's no decimal separator, bc->nd0 == bc->nd. bc->scale is the value used to scale rv to avoid doing arithmetic with subnormal values. It's either 0 or 2*P (=106). Outputs: On successful exit, rv/2^(bc->scale) is the closest double to dv. Returns 0 on success, -1 on failure (e.g., due to a failed malloc call). */ static int bigcomp(U *rv, const char *s0, BCinfo *bc) { Bigint *b, *d; int b2, d2, dd, i, nd, nd0, odd, p2, p5; nd = bc->nd; nd0 = bc->nd0; p5 = nd + bc->e0; b = sd2b(rv, bc->scale, &p2); if (b == NULL) return -1; /* record whether the lsb of rv/2^(bc->scale) is odd: in the exact halfway case, this is used for round to even. */ odd = b->x[0] & 1; /* left shift b by 1 bit and or a 1 into the least significant bit; this gives us b * 2**p2 = rv/2^(bc->scale) + 0.5 ulp. */ b = lshift(b, 1); if (b == NULL) return -1; b->x[0] |= 1; p2--; p2 -= p5; d = i2b(1); if (d == NULL) { Bfree(b); return -1; } /* Arrange for convenient computation of quotients: * shift left if necessary so divisor has 4 leading 0 bits. */ if (p5 > 0) { d = pow5mult(d, p5); if (d == NULL) { Bfree(b); return -1; } } else if (p5 < 0) { b = pow5mult(b, -p5); if (b == NULL) { Bfree(d); return -1; } } if (p2 > 0) { b2 = p2; d2 = 0; } else { b2 = 0; d2 = -p2; } i = dshift(d, d2); if ((b2 += i) > 0) { b = lshift(b, b2); if (b == NULL) { Bfree(d); return -1; } } if ((d2 += i) > 0) { d = lshift(d, d2); if (d == NULL) { Bfree(b); return -1; } } /* Compare s0 with b/d: set dd to -1, 0, or 1 according as s0 < b/d, s0 == * b/d, or s0 > b/d. Here the digits of s0 are thought of as representing * a number in the range [0.1, 1). */ if (cmp(b, d) >= 0) /* b/d >= 1 */ dd = -1; else { i = 0; for(;;) { b = multadd(b, 10, 0); if (b == NULL) { Bfree(d); return -1; } dd = s0[i < nd0 ? i : i+1] - '0' - quorem(b, d); i++; if (dd) break; if (!b->x[0] && b->wds == 1) { /* b/d == 0 */ dd = i < nd; break; } if (!(i < nd)) { /* b/d != 0, but digits of s0 exhausted */ dd = -1; break; } } } Bfree(b); Bfree(d); if (dd > 0 || (dd == 0 && odd)) dval(rv) += sulp(rv, bc); return 0; } /* Return a 'standard' NaN value. There are exactly two quiet NaNs that don't arise by 'quieting' signaling NaNs (see IEEE 754-2008, section 6.2.1). If sign == 0, return the one whose sign bit is cleared. Otherwise, return the one whose sign bit is set. */ double _Py_dg_stdnan(int sign) { U rv; word0(&rv) = NAN_WORD0; word1(&rv) = NAN_WORD1; if (sign) word0(&rv) |= Sign_bit; return dval(&rv); } /* Return positive or negative infinity, according to the given sign (0 for * positive infinity, 1 for negative infinity). */ double _Py_dg_infinity(int sign) { U rv; word0(&rv) = POSINF_WORD0; word1(&rv) = POSINF_WORD1; return sign ? -dval(&rv) : dval(&rv); } double _Py_dg_strtod(const char *s00, char **se) { int bb2, bb5, bbe, bd2, bd5, bs2, c, dsign, e, e1, error; int esign, i, j, k, lz, nd, nd0, odd, sign; const char *s, *s0, *s1; double aadj, aadj1; U aadj2, adj, rv, rv0; ULong y, z, abs_exp; Long L; BCinfo bc; Bigint *bb, *bb1, *bd, *bd0, *bs, *delta; size_t ndigits, fraclen; dval(&rv) = 0.; /* Start parsing. */ c = *(s = s00); /* Parse optional sign, if present. */ sign = 0; switch (c) { case '-': sign = 1; /* fall through */ case '+': c = *++s; } /* Skip leading zeros: lz is true iff there were leading zeros. */ s1 = s; while (c == '0') c = *++s; lz = s != s1; /* Point s0 at the first nonzero digit (if any). fraclen will be the number of digits between the decimal point and the end of the digit string. ndigits will be the total number of digits ignoring leading zeros. */ s0 = s1 = s; while ('0' <= c && c <= '9') c = *++s; ndigits = s - s1; fraclen = 0; /* Parse decimal point and following digits. */ if (c == '.') { c = *++s; if (!ndigits) { s1 = s; while (c == '0') c = *++s; lz = lz || s != s1; fraclen += (s - s1); s0 = s; } s1 = s; while ('0' <= c && c <= '9') c = *++s; ndigits += s - s1; fraclen += s - s1; } /* Now lz is true if and only if there were leading zero digits, and ndigits gives the total number of digits ignoring leading zeros. A valid input must have at least one digit. */ if (!ndigits && !lz) { if (se) *se = (char *)s00; goto parse_error; } /* Range check ndigits and fraclen to make sure that they, and values computed with them, can safely fit in an int. */ if (ndigits > MAX_DIGITS || fraclen > MAX_DIGITS) { if (se) *se = (char *)s00; goto parse_error; } nd = (int)ndigits; nd0 = (int)ndigits - (int)fraclen; /* Parse exponent. */ e = 0; if (c == 'e' || c == 'E') { s00 = s; c = *++s; /* Exponent sign. */ esign = 0; switch (c) { case '-': esign = 1; /* fall through */ case '+': c = *++s; } /* Skip zeros. lz is true iff there are leading zeros. */ s1 = s; while (c == '0') c = *++s; lz = s != s1; /* Get absolute value of the exponent. */ s1 = s; abs_exp = 0; while ('0' <= c && c <= '9') { abs_exp = 10*abs_exp + (c - '0'); c = *++s; } /* abs_exp will be correct modulo 2**32. But 10**9 < 2**32, so if there are at most 9 significant exponent digits then overflow is impossible. */ if (s - s1 > 9 || abs_exp > MAX_ABS_EXP) e = (int)MAX_ABS_EXP; else e = (int)abs_exp; if (esign) e = -e; /* A valid exponent must have at least one digit. */ if (s == s1 && !lz) s = s00; } /* Adjust exponent to take into account position of the point. */ e -= nd - nd0; if (nd0 <= 0) nd0 = nd; /* Finished parsing. Set se to indicate how far we parsed */ if (se) *se = (char *)s; /* If all digits were zero, exit with return value +-0.0. Otherwise, strip trailing zeros: scan back until we hit a nonzero digit. */ if (!nd) goto ret; for (i = nd; i > 0; ) { --i; if (s0[i < nd0 ? i : i+1] != '0') { ++i; break; } } e += nd - i; nd = i; if (nd0 > nd) nd0 = nd; /* Summary of parsing results. After parsing, and dealing with zero * inputs, we have values s0, nd0, nd, e, sign, where: * * - s0 points to the first significant digit of the input string * * - nd is the total number of significant digits (here, and * below, 'significant digits' means the set of digits of the * significand of the input that remain after ignoring leading * and trailing zeros). * * - nd0 indicates the position of the decimal point, if present; it * satisfies 1 <= nd0 <= nd. The nd significant digits are in * s0[0:nd0] and s0[nd0+1:nd+1] using the usual Python half-open slice * notation. (If nd0 < nd, then s0[nd0] contains a '.' character; if * nd0 == nd, then s0[nd0] could be any non-digit character.) * * - e is the adjusted exponent: the absolute value of the number * represented by the original input string is n * 10**e, where * n is the integer represented by the concatenation of * s0[0:nd0] and s0[nd0+1:nd+1] * * - sign gives the sign of the input: 1 for negative, 0 for positive * * - the first and last significant digits are nonzero */ /* put first DBL_DIG+1 digits into integer y and z. * * - y contains the value represented by the first min(9, nd) * significant digits * * - if nd > 9, z contains the value represented by significant digits * with indices in [9, min(16, nd)). So y * 10**(min(16, nd) - 9) + z * gives the value represented by the first min(16, nd) sig. digits. */ bc.e0 = e1 = e; y = z = 0; for (i = 0; i < nd; i++) { if (i < 9) y = 10*y + s0[i < nd0 ? i : i+1] - '0'; else if (i < DBL_DIG+1) z = 10*z + s0[i < nd0 ? i : i+1] - '0'; else break; } k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1; dval(&rv) = y; if (k > 9) { dval(&rv) = tens[k - 9] * dval(&rv) + z; } bd0 = 0; if (nd <= DBL_DIG && Flt_Rounds == 1 ) { if (!e) goto ret; if (e > 0) { if (e <= Ten_pmax) { dval(&rv) *= tens[e]; goto ret; } i = DBL_DIG - nd; if (e <= Ten_pmax + i) { /* A fancier test would sometimes let us do * this for larger i values. */ e -= i; dval(&rv) *= tens[i]; dval(&rv) *= tens[e]; goto ret; } } else if (e >= -Ten_pmax) { dval(&rv) /= tens[-e]; goto ret; } } e1 += nd - k; bc.scale = 0; /* Get starting approximation = rv * 10**e1 */ if (e1 > 0) { if ((i = e1 & 15)) dval(&rv) *= tens[i]; if (e1 &= ~15) { if (e1 > DBL_MAX_10_EXP) goto ovfl; e1 >>= 4; for(j = 0; e1 > 1; j++, e1 >>= 1) if (e1 & 1) dval(&rv) *= bigtens[j]; /* The last multiplication could overflow. */ word0(&rv) -= P*Exp_msk1; dval(&rv) *= bigtens[j]; if ((z = word0(&rv) & Exp_mask) > Exp_msk1*(DBL_MAX_EXP+Bias-P)) goto ovfl; if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) { /* set to largest number */ /* (Can't trust DBL_MAX) */ word0(&rv) = Big0; word1(&rv) = Big1; } else word0(&rv) += P*Exp_msk1; } } else if (e1 < 0) { /* The input decimal value lies in [10**e1, 10**(e1+16)). If e1 <= -512, underflow immediately. If e1 <= -256, set bc.scale to 2*P. So for input value < 1e-256, bc.scale is always set; for input value >= 1e-240, bc.scale is never set. For input values in [1e-256, 1e-240), bc.scale may or may not be set. */ e1 = -e1; if ((i = e1 & 15)) dval(&rv) /= tens[i]; if (e1 >>= 4) { if (e1 >= 1 << n_bigtens) goto undfl; if (e1 & Scale_Bit) bc.scale = 2*P; for(j = 0; e1 > 0; j++, e1 >>= 1) if (e1 & 1) dval(&rv) *= tinytens[j]; if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask) >> Exp_shift)) > 0) { /* scaled rv is denormal; clear j low bits */ if (j >= 32) { word1(&rv) = 0; if (j >= 53) word0(&rv) = (P+2)*Exp_msk1; else word0(&rv) &= 0xffffffff << (j-32); } else word1(&rv) &= 0xffffffff << j; } if (!dval(&rv)) goto undfl; } } /* Now the hard part -- adjusting rv to the correct value.*/ /* Put digits into bd: true value = bd * 10^e */ bc.nd = nd; bc.nd0 = nd0; /* Only needed if nd > STRTOD_DIGLIM, but done here */ /* to silence an erroneous warning about bc.nd0 */ /* possibly not being initialized. */ if (nd > STRTOD_DIGLIM) { /* ASSERT(STRTOD_DIGLIM >= 18); 18 == one more than the */ /* minimum number of decimal digits to distinguish double values */ /* in IEEE arithmetic. */ /* Truncate input to 18 significant digits, then discard any trailing zeros on the result by updating nd, nd0, e and y suitably. (There's no need to update z; it's not reused beyond this point.) */ for (i = 18; i > 0; ) { /* scan back until we hit a nonzero digit. significant digit 'i' is s0[i] if i < nd0, s0[i+1] if i >= nd0. */ --i; if (s0[i < nd0 ? i : i+1] != '0') { ++i; break; } } e += nd - i; nd = i; if (nd0 > nd) nd0 = nd; if (nd < 9) { /* must recompute y */ y = 0; for(i = 0; i < nd0; ++i) y = 10*y + s0[i] - '0'; for(; i < nd; ++i) y = 10*y + s0[i+1] - '0'; } } bd0 = s2b(s0, nd0, nd, y); if (bd0 == NULL) goto failed_malloc; /* Notation for the comments below. Write: - dv for the absolute value of the number represented by the original decimal input string. - if we've truncated dv, write tdv for the truncated value. Otherwise, set tdv == dv. - srv for the quantity rv/2^bc.scale; so srv is the current binary approximation to tdv (and dv). It should be exactly representable in an IEEE 754 double. */ for(;;) { /* This is the main correction loop for _Py_dg_strtod. We've got a decimal value tdv, and a floating-point approximation srv=rv/2^bc.scale to tdv. The aim is to determine whether srv is close enough (i.e., within 0.5 ulps) to tdv, and to compute a new approximation if not. To determine whether srv is close enough to tdv, compute integers bd, bb and bs proportional to tdv, srv and 0.5 ulp(srv) respectively, and then use integer arithmetic to determine whether |tdv - srv| is less than, equal to, or greater than 0.5 ulp(srv). */ bd = Balloc(bd0->k); if (bd == NULL) { Bfree(bd0); goto failed_malloc; } Bcopy(bd, bd0); bb = sd2b(&rv, bc.scale, &bbe); /* srv = bb * 2^bbe */ if (bb == NULL) { Bfree(bd); Bfree(bd0); goto failed_malloc; } /* Record whether lsb of bb is odd, in case we need this for the round-to-even step later. */ odd = bb->x[0] & 1; /* tdv = bd * 10**e; srv = bb * 2**bbe */ bs = i2b(1); if (bs == NULL) { Bfree(bb); Bfree(bd); Bfree(bd0); goto failed_malloc; } if (e >= 0) { bb2 = bb5 = 0; bd2 = bd5 = e; } else { bb2 = bb5 = -e; bd2 = bd5 = 0; } if (bbe >= 0) bb2 += bbe; else bd2 -= bbe; bs2 = bb2; bb2++; bd2++; /* At this stage bd5 - bb5 == e == bd2 - bb2 + bbe, bb2 - bs2 == 1, and bs == 1, so: tdv == bd * 10**e = bd * 2**(bbe - bb2 + bd2) * 5**(bd5 - bb5) srv == bb * 2**bbe = bb * 2**(bbe - bb2 + bb2) 0.5 ulp(srv) == 2**(bbe-1) = bs * 2**(bbe - bb2 + bs2) It follows that: M * tdv = bd * 2**bd2 * 5**bd5 M * srv = bb * 2**bb2 * 5**bb5 M * 0.5 ulp(srv) = bs * 2**bs2 * 5**bb5 for some constant M. (Actually, M == 2**(bb2 - bbe) * 5**bb5, but this fact is not needed below.) */ /* Remove factor of 2**i, where i = min(bb2, bd2, bs2). */ i = bb2 < bd2 ? bb2 : bd2; if (i > bs2) i = bs2; if (i > 0) { bb2 -= i; bd2 -= i; bs2 -= i; } /* Scale bb, bd, bs by the appropriate powers of 2 and 5. */ if (bb5 > 0) { bs = pow5mult(bs, bb5); if (bs == NULL) { Bfree(bb); Bfree(bd); Bfree(bd0); goto failed_malloc; } bb1 = mult(bs, bb); Bfree(bb); bb = bb1; if (bb == NULL) { Bfree(bs); Bfree(bd); Bfree(bd0); goto failed_malloc; } } if (bb2 > 0) { bb = lshift(bb, bb2); if (bb == NULL) { Bfree(bs); Bfree(bd); Bfree(bd0); goto failed_malloc; } } if (bd5 > 0) { bd = pow5mult(bd, bd5); if (bd == NULL) { Bfree(bb); Bfree(bs); Bfree(bd0); goto failed_malloc; } } if (bd2 > 0) { bd = lshift(bd, bd2); if (bd == NULL) { Bfree(bb); Bfree(bs); Bfree(bd0); goto failed_malloc; } } if (bs2 > 0) { bs = lshift(bs, bs2); if (bs == NULL) { Bfree(bb); Bfree(bd); Bfree(bd0); goto failed_malloc; } } /* Now bd, bb and bs are scaled versions of tdv, srv and 0.5 ulp(srv), respectively. Compute the difference |tdv - srv|, and compare with 0.5 ulp(srv). */ delta = diff(bb, bd); if (delta == NULL) { Bfree(bb); Bfree(bs); Bfree(bd); Bfree(bd0); goto failed_malloc; } dsign = delta->sign; delta->sign = 0; i = cmp(delta, bs); if (bc.nd > nd && i <= 0) { if (dsign) break; /* Must use bigcomp(). */ /* Here rv overestimates the truncated decimal value by at most 0.5 ulp(rv). Hence rv either overestimates the true decimal value by <= 0.5 ulp(rv), or underestimates it by some small amount (< 0.1 ulp(rv)); either way, rv is within 0.5 ulps of the true decimal value, so it's possible to exit. Exception: if scaled rv is a normal exact power of 2, but not DBL_MIN, then rv - 0.5 ulp(rv) takes us all the way down to the next double, so the correctly rounded result is either rv - 0.5 ulp(rv) or rv; in this case, use bigcomp to distinguish. */ if (!word1(&rv) && !(word0(&rv) & Bndry_mask)) { /* rv can't be 0, since it's an overestimate for some nonzero value. So rv is a normal power of 2. */ j = (int)(word0(&rv) & Exp_mask) >> Exp_shift; /* rv / 2^bc.scale = 2^(j - 1023 - bc.scale); use bigcomp if rv / 2^bc.scale >= 2^-1021. */ if (j - bc.scale >= 2) { dval(&rv) -= 0.5 * sulp(&rv, &bc); break; /* Use bigcomp. */ } } { bc.nd = nd; i = -1; /* Discarded digits make delta smaller. */ } } if (i < 0) { /* Error is less than half an ulp -- check for * special case of mantissa a power of two. */ if (dsign || word1(&rv) || word0(&rv) & Bndry_mask || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1 ) { break; } if (!delta->x[0] && delta->wds <= 1) { /* exact result */ break; } delta = lshift(delta,Log2P); if (delta == NULL) { Bfree(bb); Bfree(bs); Bfree(bd); Bfree(bd0); goto failed_malloc; } if (cmp(delta, bs) > 0) goto drop_down; break; } if (i == 0) { /* exactly half-way between */ if (dsign) { if ((word0(&rv) & Bndry_mask1) == Bndry_mask1 && word1(&rv) == ( (bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) : 0xffffffff)) { /*boundary case -- increment exponent*/ word0(&rv) = (word0(&rv) & Exp_mask) + Exp_msk1 ; word1(&rv) = 0; /* dsign = 0; */ break; } } else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) { drop_down: /* boundary case -- decrement exponent */ if (bc.scale) { L = word0(&rv) & Exp_mask; if (L <= (2*P+1)*Exp_msk1) { if (L > (P+2)*Exp_msk1) /* round even ==> */ /* accept rv */ break; /* rv = smallest denormal */ if (bc.nd > nd) break; goto undfl; } } L = (word0(&rv) & Exp_mask) - Exp_msk1; word0(&rv) = L | Bndry_mask1; word1(&rv) = 0xffffffff; break; } if (!odd) break; if (dsign) dval(&rv) += sulp(&rv, &bc); else { dval(&rv) -= sulp(&rv, &bc); if (!dval(&rv)) { if (bc.nd >nd) break; goto undfl; } } /* dsign = 1 - dsign; */ break; } if ((aadj = ratio(delta, bs)) <= 2.) { if (dsign) aadj = aadj1 = 1.; else if (word1(&rv) || word0(&rv) & Bndry_mask) { if (word1(&rv) == Tiny1 && !word0(&rv)) { if (bc.nd >nd) break; goto undfl; } aadj = 1.; aadj1 = -1.; } else { /* special case -- power of FLT_RADIX to be */ /* rounded down... */ if (aadj < 2./FLT_RADIX) aadj = 1./FLT_RADIX; else aadj *= 0.5; aadj1 = -aadj; } } else { aadj *= 0.5; aadj1 = dsign ? aadj : -aadj; if (Flt_Rounds == 0) aadj1 += 0.5; } y = word0(&rv) & Exp_mask; /* Check for overflow */ if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) { dval(&rv0) = dval(&rv); word0(&rv) -= P*Exp_msk1; adj.d = aadj1 * ulp(&rv); dval(&rv) += adj.d; if ((word0(&rv) & Exp_mask) >= Exp_msk1*(DBL_MAX_EXP+Bias-P)) { if (word0(&rv0) == Big0 && word1(&rv0) == Big1) { Bfree(bb); Bfree(bd); Bfree(bs); Bfree(bd0); Bfree(delta); goto ovfl; } word0(&rv) = Big0; word1(&rv) = Big1; goto cont; } else word0(&rv) += P*Exp_msk1; } else { if (bc.scale && y <= 2*P*Exp_msk1) { if (aadj <= 0x7fffffff) { if ((z = (ULong)aadj) <= 0) z = 1; aadj = z; aadj1 = dsign ? aadj : -aadj; } dval(&aadj2) = aadj1; word0(&aadj2) += (2*P+1)*Exp_msk1 - y; aadj1 = dval(&aadj2); } adj.d = aadj1 * ulp(&rv); dval(&rv) += adj.d; } z = word0(&rv) & Exp_mask; if (bc.nd == nd) { if (!bc.scale) if (y == z) { /* Can we stop now? */ L = (Long)aadj; aadj -= L; /* The tolerances below are conservative. */ if (dsign || word1(&rv) || word0(&rv) & Bndry_mask) { if (aadj < .4999999 || aadj > .5000001) break; } else if (aadj < .4999999/FLT_RADIX) break; } } cont: Bfree(bb); Bfree(bd); Bfree(bs); Bfree(delta); } Bfree(bb); Bfree(bd); Bfree(bs); Bfree(bd0); Bfree(delta); if (bc.nd > nd) { error = bigcomp(&rv, s0, &bc); if (error) goto failed_malloc; } if (bc.scale) { word0(&rv0) = Exp_1 - 2*P*Exp_msk1; word1(&rv0) = 0; dval(&rv) *= dval(&rv0); } ret: return sign ? -dval(&rv) : dval(&rv); parse_error: return 0.0; failed_malloc: errno = ENOMEM; return -1.0; undfl: return sign ? -0.0 : 0.0; ovfl: errno = ERANGE; /* Can't trust HUGE_VAL */ word0(&rv) = Exp_mask; word1(&rv) = 0; return sign ? -dval(&rv) : dval(&rv); } static char * rv_alloc(int i) { int j, k, *r; j = sizeof(ULong); for(k = 0; sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i; j <<= 1) k++; r = (int*)Balloc(k); if (r == NULL) return NULL; *r = k; return (char *)(r+1); } static char * nrv_alloc(const char *s, char **rve, int n) { char *rv, *t; rv = rv_alloc(n); if (rv == NULL) return NULL; t = rv; while((*t = *s++)) t++; if (rve) *rve = t; return rv; } /* freedtoa(s) must be used to free values s returned by dtoa * when MULTIPLE_THREADS is #defined. It should be used in all cases, * but for consistency with earlier versions of dtoa, it is optional * when MULTIPLE_THREADS is not defined. */ void _Py_dg_freedtoa(char *s) { Bigint *b = (Bigint *)((int *)s - 1); b->maxwds = 1 << (b->k = *(int*)b); Bfree(b); } /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string. * * Inspired by "How to Print Floating-Point Numbers Accurately" by * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126]. * * Modifications: * 1. Rather than iterating, we use a simple numeric overestimate * to determine k = floor(log10(d)). We scale relevant * quantities using O(log2(k)) rather than O(k) multiplications. * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't * try to generate digits strictly left to right. Instead, we * compute with fewer bits and propagate the carry if necessary * when rounding the final digit up. This is often faster. * 3. Under the assumption that input will be rounded nearest, * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22. * That is, we allow equality in stopping tests when the * round-nearest rule will give the same floating-point value * as would satisfaction of the stopping test with strict * inequality. * 4. We remove common factors of powers of 2 from relevant * quantities. * 5. When converting floating-point integers less than 1e16, * we use floating-point arithmetic rather than resorting * to multiple-precision integers. * 6. When asked to produce fewer than 15 digits, we first try * to get by with floating-point arithmetic; we resort to * multiple-precision integer arithmetic only if we cannot * guarantee that the floating-point calculation has given * the correctly rounded result. For k requested digits and * "uniformly" distributed input, the probability is * something like 10^(k-15) that we must resort to the Long * calculation. */ /* Additional notes (METD): (1) returns NULL on failure. (2) to avoid memory leakage, a successful call to _Py_dg_dtoa should always be matched by a call to _Py_dg_freedtoa. */ char * _Py_dg_dtoa(double dd, int mode, int ndigits, int *decpt, int *sign, char **rve) { /* Arguments ndigits, decpt, sign are similar to those of ecvt and fcvt; trailing zeros are suppressed from the returned string. If not null, *rve is set to point to the end of the return value. If d is +-Infinity or NaN, then *decpt is set to 9999. mode: 0 ==> shortest string that yields d when read in and rounded to nearest. 1 ==> like 0, but with Steele & White stopping rule; e.g. with IEEE P754 arithmetic , mode 0 gives 1e23 whereas mode 1 gives 9.999999999999999e22. 2 ==> max(1,ndigits) significant digits. This gives a return value similar to that of ecvt, except that trailing zeros are suppressed. 3 ==> through ndigits past the decimal point. This gives a return value similar to that from fcvt, except that trailing zeros are suppressed, and ndigits can be negative. 4,5 ==> similar to 2 and 3, respectively, but (in round-nearest mode) with the tests of mode 0 to possibly return a shorter string that rounds to d. With IEEE arithmetic and compilation with -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same as modes 2 and 3 when FLT_ROUNDS != 1. 6-9 ==> Debugging modes similar to mode - 4: don't try fast floating-point estimate (if applicable). Values of mode other than 0-9 are treated as mode 0. Sufficient space is allocated to the return value to hold the suppressed trailing zeros. */ int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1, j, j1, k, k0, k_check, leftright, m2, m5, s2, s5, spec_case, try_quick; Long L; int denorm; ULong x; Bigint *b, *b1, *delta, *mlo, *mhi, *S; U d2, eps, u; double ds; char *s, *s0; /* set pointers to NULL, to silence gcc compiler warnings and make cleanup easier on error */ mlo = mhi = S = 0; s0 = 0; u.d = dd; if (word0(&u) & Sign_bit) { /* set sign for everything, including 0's and NaNs */ *sign = 1; word0(&u) &= ~Sign_bit; /* clear sign bit */ } else *sign = 0; /* quick return for Infinities, NaNs and zeros */ if ((word0(&u) & Exp_mask) == Exp_mask) { /* Infinity or NaN */ *decpt = 9999; if (!word1(&u) && !(word0(&u) & 0xfffff)) return nrv_alloc("Infinity", rve, 8); return nrv_alloc("NaN", rve, 3); } if (!dval(&u)) { *decpt = 1; return nrv_alloc("0", rve, 1); } /* compute k = floor(log10(d)). The computation may leave k one too large, but should never leave k too small. */ b = d2b(&u, &be, &bbits); if (b == NULL) goto failed_malloc; if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) { dval(&d2) = dval(&u); word0(&d2) &= Frac_mask1; word0(&d2) |= Exp_11; /* log(x) ~=~ log(1.5) + (x-1.5)/1.5 * log10(x) = log(x) / log(10) * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10)) * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2) * * This suggests computing an approximation k to log10(d) by * * k = (i - Bias)*0.301029995663981 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 ); * * We want k to be too large rather than too small. * The error in the first-order Taylor series approximation * is in our favor, so we just round up the constant enough * to compensate for any error in the multiplication of * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077, * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14, * adding 1e-13 to the constant term more than suffices. * Hence we adjust the constant term to 0.1760912590558. * (We could get a more accurate k by invoking log10, * but this is probably not worthwhile.) */ i -= Bias; denorm = 0; } else { /* d is denormalized */ i = bbits + be + (Bias + (P-1) - 1); x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32) : word1(&u) << (32 - i); dval(&d2) = x; word0(&d2) -= 31*Exp_msk1; /* adjust exponent */ i -= (Bias + (P-1) - 1) + 1; denorm = 1; } ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981; k = (int)ds; if (ds < 0. && ds != k) k--; /* want k = floor(ds) */ k_check = 1; if (k >= 0 && k <= Ten_pmax) { if (dval(&u) < tens[k]) k--; k_check = 0; } j = bbits - i - 1; if (j >= 0) { b2 = 0; s2 = j; } else { b2 = -j; s2 = 0; } if (k >= 0) { b5 = 0; s5 = k; s2 += k; } else { b2 -= k; b5 = -k; s5 = 0; } if (mode < 0 || mode > 9) mode = 0; try_quick = 1; if (mode > 5) { mode -= 4; try_quick = 0; } leftright = 1; ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */ /* silence erroneous "gcc -Wall" warning. */ switch(mode) { case 0: case 1: i = 18; ndigits = 0; break; case 2: leftright = 0; /* fall through */ case 4: if (ndigits <= 0) ndigits = 1; ilim = ilim1 = i = ndigits; break; case 3: leftright = 0; /* fall through */ case 5: i = ndigits + k + 1; ilim = i; ilim1 = i - 1; if (i <= 0) i = 1; } s0 = rv_alloc(i); if (s0 == NULL) goto failed_malloc; s = s0; if (ilim >= 0 && ilim <= Quick_max && try_quick) { /* Try to get by with floating-point arithmetic. */ i = 0; dval(&d2) = dval(&u); k0 = k; ilim0 = ilim; ieps = 2; /* conservative */ if (k > 0) { ds = tens[k&0xf]; j = k >> 4; if (j & Bletch) { /* prevent overflows */ j &= Bletch - 1; dval(&u) /= bigtens[n_bigtens-1]; ieps++; } for(; j; j >>= 1, i++) if (j & 1) { ieps++; ds *= bigtens[i]; } dval(&u) /= ds; } else if ((j1 = -k)) { dval(&u) *= tens[j1 & 0xf]; for(j = j1 >> 4; j; j >>= 1, i++) if (j & 1) { ieps++; dval(&u) *= bigtens[i]; } } if (k_check && dval(&u) < 1. && ilim > 0) { if (ilim1 <= 0) goto fast_failed; ilim = ilim1; k--; dval(&u) *= 10.; ieps++; } dval(&eps) = ieps*dval(&u) + 7.; word0(&eps) -= (P-1)*Exp_msk1; if (ilim == 0) { S = mhi = 0; dval(&u) -= 5.; if (dval(&u) > dval(&eps)) goto one_digit; if (dval(&u) < -dval(&eps)) goto no_digits; goto fast_failed; } if (leftright) { /* Use Steele & White method of only * generating digits needed. */ dval(&eps) = 0.5/tens[ilim-1] - dval(&eps); for(i = 0;;) { L = (Long)dval(&u); dval(&u) -= L; *s++ = '0' + (int)L; if (dval(&u) < dval(&eps)) goto ret1; if (1. - dval(&u) < dval(&eps)) goto bump_up; if (++i >= ilim) break; dval(&eps) *= 10.; dval(&u) *= 10.; } } else { /* Generate ilim digits, then fix them up. */ dval(&eps) *= tens[ilim-1]; for(i = 1;; i++, dval(&u) *= 10.) { L = (Long)(dval(&u)); if (!(dval(&u) -= L)) ilim = i; *s++ = '0' + (int)L; if (i == ilim) { if (dval(&u) > 0.5 + dval(&eps)) goto bump_up; else if (dval(&u) < 0.5 - dval(&eps)) { while(*--s == '0'); s++; goto ret1; } break; } } } fast_failed: s = s0; dval(&u) = dval(&d2); k = k0; ilim = ilim0; } /* Do we have a "small" integer? */ if (be >= 0 && k <= Int_max) { /* Yes. */ ds = tens[k]; if (ndigits < 0 && ilim <= 0) { S = mhi = 0; if (ilim < 0 || dval(&u) <= 5*ds) goto no_digits; goto one_digit; } for(i = 1;; i++, dval(&u) *= 10.) { L = (Long)(dval(&u) / ds); dval(&u) -= L*ds; *s++ = '0' + (int)L; if (!dval(&u)) { break; } if (i == ilim) { dval(&u) += dval(&u); if (dval(&u) > ds || (dval(&u) == ds && L & 1)) { bump_up: while(*--s == '9') if (s == s0) { k++; *s = '0'; break; } ++*s++; } break; } } goto ret1; } m2 = b2; m5 = b5; if (leftright) { i = denorm ? be + (Bias + (P-1) - 1 + 1) : 1 + P - bbits; b2 += i; s2 += i; mhi = i2b(1); if (mhi == NULL) goto failed_malloc; } if (m2 > 0 && s2 > 0) { i = m2 < s2 ? m2 : s2; b2 -= i; m2 -= i; s2 -= i; } if (b5 > 0) { if (leftright) { if (m5 > 0) { mhi = pow5mult(mhi, m5); if (mhi == NULL) goto failed_malloc; b1 = mult(mhi, b); Bfree(b); b = b1; if (b == NULL) goto failed_malloc; } if ((j = b5 - m5)) { b = pow5mult(b, j); if (b == NULL) goto failed_malloc; } } else { b = pow5mult(b, b5); if (b == NULL) goto failed_malloc; } } S = i2b(1); if (S == NULL) goto failed_malloc; if (s5 > 0) { S = pow5mult(S, s5); if (S == NULL) goto failed_malloc; } /* Check for special case that d is a normalized power of 2. */ spec_case = 0; if ((mode < 2 || leftright) ) { if (!word1(&u) && !(word0(&u) & Bndry_mask) && word0(&u) & (Exp_mask & ~Exp_msk1) ) { /* The special case */ b2 += Log2P; s2 += Log2P; spec_case = 1; } } /* Arrange for convenient computation of quotients: * shift left if necessary so divisor has 4 leading 0 bits. * * Perhaps we should just compute leading 28 bits of S once * and for all and pass them and a shift to quorem, so it * can do shifts and ors to compute the numerator for q. */ #define iInc 28 i = dshift(S, s2); b2 += i; m2 += i; s2 += i; if (b2 > 0) { b = lshift(b, b2); if (b == NULL) goto failed_malloc; } if (s2 > 0) { S = lshift(S, s2); if (S == NULL) goto failed_malloc; } if (k_check) { if (cmp(b,S) < 0) { k--; b = multadd(b, 10, 0); /* we botched the k estimate */ if (b == NULL) goto failed_malloc; if (leftright) { mhi = multadd(mhi, 10, 0); if (mhi == NULL) goto failed_malloc; } ilim = ilim1; } } if (ilim <= 0 && (mode == 3 || mode == 5)) { if (ilim < 0) { /* no digits, fcvt style */ no_digits: k = -1 - ndigits; goto ret; } else { S = multadd(S, 5, 0); if (S == NULL) goto failed_malloc; if (cmp(b, S) <= 0) goto no_digits; } one_digit: *s++ = '1'; k++; goto ret; } if (leftright) { if (m2 > 0) { mhi = lshift(mhi, m2); if (mhi == NULL) goto failed_malloc; } /* Compute mlo -- check for special case * that d is a normalized power of 2. */ mlo = mhi; if (spec_case) { mhi = Balloc(mhi->k); if (mhi == NULL) goto failed_malloc; Bcopy(mhi, mlo); mhi = lshift(mhi, Log2P); if (mhi == NULL) goto failed_malloc; } for(i = 1;;i++) { dig = quorem(b,S) + '0'; /* Do we yet have the shortest decimal string * that will round to d? */ j = cmp(b, mlo); delta = diff(S, mhi); if (delta == NULL) goto failed_malloc; j1 = delta->sign ? 1 : cmp(b, delta); Bfree(delta); if (j1 == 0 && mode != 1 && !(word1(&u) & 1) ) { if (dig == '9') goto round_9_up; if (j > 0) dig++; *s++ = dig; goto ret; } if (j < 0 || (j == 0 && mode != 1 && !(word1(&u) & 1) )) { if (!b->x[0] && b->wds <= 1) { goto accept_dig; } if (j1 > 0) { b = lshift(b, 1); if (b == NULL) goto failed_malloc; j1 = cmp(b, S); if ((j1 > 0 || (j1 == 0 && dig & 1)) && dig++ == '9') goto round_9_up; } accept_dig: *s++ = dig; goto ret; } if (j1 > 0) { if (dig == '9') { /* possible if i == 1 */ round_9_up: *s++ = '9'; goto roundoff; } *s++ = dig + 1; goto ret; } *s++ = dig; if (i == ilim) break; b = multadd(b, 10, 0); if (b == NULL) goto failed_malloc; if (mlo == mhi) { mlo = mhi = multadd(mhi, 10, 0); if (mlo == NULL) goto failed_malloc; } else { mlo = multadd(mlo, 10, 0); if (mlo == NULL) goto failed_malloc; mhi = multadd(mhi, 10, 0); if (mhi == NULL) goto failed_malloc; } } } else for(i = 1;; i++) { *s++ = dig = quorem(b,S) + '0'; if (!b->x[0] && b->wds <= 1) { goto ret; } if (i >= ilim) break; b = multadd(b, 10, 0); if (b == NULL) goto failed_malloc; } /* Round off last digit */ b = lshift(b, 1); if (b == NULL) goto failed_malloc; j = cmp(b, S); if (j > 0 || (j == 0 && dig & 1)) { roundoff: while(*--s == '9') if (s == s0) { k++; *s++ = '1'; goto ret; } ++*s++; } else { while(*--s == '0'); s++; } ret: Bfree(S); if (mhi) { if (mlo && mlo != mhi) Bfree(mlo); Bfree(mhi); } ret1: Bfree(b); *s = 0; *decpt = k + 1; if (rve) *rve = s; return s0; failed_malloc: if (S) Bfree(S); if (mlo && mlo != mhi) Bfree(mlo); if (mhi) Bfree(mhi); if (b) Bfree(b); if (s0) _Py_dg_freedtoa(s0); return NULL; } #endif /* PY_NO_SHORT_FLOAT_REPR */
81,659
2,892
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/marshal.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "dsp/mpeg/video.h" #include "libc/calls/calls.h" #include "libc/calls/weirdtypes.h" #include "libc/mem/mem.h" #include "libc/mem/gc.internal.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longintrepr.h" #include "third_party/python/Include/marshal.h" #include "third_party/python/Include/memoryobject.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystrtod.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/yoink.h" #include "third_party/python/Modules/hashtable.h" /* clang-format off */ PYTHON_PROVIDE("marshal"); /* Write Python objects to files and read them back. This is primarily intended for writing and reading compiled Python code, even though dicts, lists, sets and frozensets, not commonly seen in code objects, are supported. Version 3 of this protocol properly supports circular links and sharing. */ /* High water mark to determine when the marshalled object is dangerously deep * and risks coring the interpreter. When the object stack gets this deep, * raise an exception instead of continuing. * On Windows debug builds, reduce this value. */ #if defined(MS_WINDOWS) && defined(_DEBUG) #define MAX_MARSHAL_STACK_DEPTH 1000 #else #define MAX_MARSHAL_STACK_DEPTH 2000 #endif #define TYPE_NULL '0' #define TYPE_NONE 'N' #define TYPE_FALSE 'F' #define TYPE_TRUE 'T' #define TYPE_STOPITER 'S' #define TYPE_ELLIPSIS '.' #define TYPE_INT 'i' /* TYPE_INT64 is not generated anymore. Supported for backward compatibility only. */ #define TYPE_INT64 'I' #define TYPE_FLOAT 'f' #define TYPE_BINARY_FLOAT 'g' #define TYPE_COMPLEX 'x' #define TYPE_BINARY_COMPLEX 'y' #define TYPE_LONG 'l' #define TYPE_STRING 's' #define TYPE_INTERNED 't' #define TYPE_REF 'r' #define TYPE_TUPLE '(' #define TYPE_LIST '[' #define TYPE_DICT '{' #define TYPE_CODE 'c' #define TYPE_UNICODE 'u' #define TYPE_UNKNOWN '?' #define TYPE_SET '<' #define TYPE_FROZENSET '>' #define FLAG_REF '\x80' /* with a type, add obj to index */ #define TYPE_ASCII 'a' #define TYPE_ASCII_INTERNED 'A' #define TYPE_SMALL_TUPLE ')' #define TYPE_SHORT_ASCII 'z' #define TYPE_SHORT_ASCII_INTERNED 'Z' #define WFERR_OK 0 #define WFERR_UNMARSHALLABLE 1 #define WFERR_NESTEDTOODEEP 2 #define WFERR_NOMEMORY 3 typedef struct { FILE *fp; int error; /* see WFERR_* values */ int depth; PyObject *str; char *ptr; char *end; char *buf; _Py_hashtable_t *hashtable; int version; } WFILE; #define w_byte(c, p) do { \ if ((p)->ptr != (p)->end || w_reserve((p), 1)) \ *(p)->ptr++ = (c); \ } while(0) static void w_flush(WFILE *p) { assert(p->fp != NULL); fwrite(p->buf, 1, p->ptr - p->buf, p->fp); p->ptr = p->buf; } static int w_reserve(WFILE *p, Py_ssize_t needed) { Py_ssize_t pos, size, delta; if (p->ptr == NULL) return 0; /* An error already occurred */ if (p->fp != NULL) { w_flush(p); return needed <= p->end - p->ptr; } assert(p->str != NULL); pos = p->ptr - p->buf; size = PyBytes_Size(p->str); if (size > 16*1024*1024) delta = (size >> 3); /* 12.5% overallocation */ else delta = size + 1024; delta = Py_MAX(delta, needed); if (delta > PY_SSIZE_T_MAX - size) { p->error = WFERR_NOMEMORY; return 0; } size += delta; if (_PyBytes_Resize(&p->str, size) != 0) { p->ptr = p->buf = p->end = NULL; return 0; } else { p->buf = PyBytes_AS_STRING(p->str); p->ptr = p->buf + pos; p->end = p->buf + size; return 1; } } static void w_string(const char *s, Py_ssize_t n, WFILE *p) { Py_ssize_t m; if (!n || p->ptr == NULL) return; m = p->end - p->ptr; if (p->fp != NULL) { if (n <= m) { memcpy(p->ptr, s, n); p->ptr += n; } else { w_flush(p); fwrite(s, 1, n, p->fp); } } else { if (n <= m || w_reserve(p, n - m)) { memcpy(p->ptr, s, n); p->ptr += n; } } } static void w_short(int x, WFILE *p) { w_byte((char)( x & 0xff), p); w_byte((char)((x>> 8) & 0xff), p); } static void w_long(long x, WFILE *p) { w_byte((char)( x & 0xff), p); w_byte((char)((x>> 8) & 0xff), p); w_byte((char)((x>>16) & 0xff), p); w_byte((char)((x>>24) & 0xff), p); } #define SIZE32_MAX 0x7FFFFFFF #if SIZEOF_SIZE_T > 4 # define W_SIZE(n, p) do { \ if ((n) > SIZE32_MAX) { \ (p)->depth--; \ (p)->error = WFERR_UNMARSHALLABLE; \ return; \ } \ w_long((long)(n), p); \ } while(0) #else # define W_SIZE w_long #endif static void w_pstring(const char *s, Py_ssize_t n, WFILE *p) { W_SIZE(n, p); w_string(s, n, p); } static void w_short_pstring(const char *s, Py_ssize_t n, WFILE *p) { w_byte(Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char), p); w_string(s, n, p); } /* We assume that Python ints are stored internally in base some power of 2**15; for the sake of portability we'll always read and write them in base exactly 2**15. */ #define PyLong_MARSHAL_SHIFT 15 #define PyLong_MARSHAL_BASE ((short)1 << PyLong_MARSHAL_SHIFT) #define PyLong_MARSHAL_MASK (PyLong_MARSHAL_BASE - 1) #if PyLong_SHIFT % PyLong_MARSHAL_SHIFT != 0 #error "PyLong_SHIFT must be a multiple of PyLong_MARSHAL_SHIFT" #endif #define PyLong_MARSHAL_RATIO (PyLong_SHIFT / PyLong_MARSHAL_SHIFT) #define W_TYPE(t, p) do { \ w_byte((t) | flag, (p)); \ } while(0) static void w_PyLong(const PyLongObject *ob, char flag, WFILE *p) { Py_ssize_t i, j, n, l; digit d; W_TYPE(TYPE_LONG, p); if (Py_SIZE(ob) == 0) { w_long((long)0, p); return; } /* set l to number of base PyLong_MARSHAL_BASE digits */ n = Py_ABS(Py_SIZE(ob)); l = (n-1) * PyLong_MARSHAL_RATIO; d = ob->ob_digit[n-1]; assert(d != 0); /* a PyLong is always normalized */ do { d >>= PyLong_MARSHAL_SHIFT; l++; } while (d != 0); if (l > SIZE32_MAX) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); for (i=0; i < n-1; i++) { d = ob->ob_digit[i]; for (j=0; j < PyLong_MARSHAL_RATIO; j++) { w_short(d & PyLong_MARSHAL_MASK, p); d >>= PyLong_MARSHAL_SHIFT; } assert (d == 0); } d = ob->ob_digit[n-1]; do { w_short(d & PyLong_MARSHAL_MASK, p); d >>= PyLong_MARSHAL_SHIFT; } while (d != 0); } static int w_ref(PyObject *v, char *flag, WFILE *p) { _Py_hashtable_entry_t *entry; int w; if (p->version < 3 || p->hashtable == NULL) return 0; /* not writing object references */ /* if it has only one reference, it definitely isn't shared */ if (Py_REFCNT(v) == 1) return 0; entry = _Py_HASHTABLE_GET_ENTRY(p->hashtable, v); if (entry != NULL) { /* write the reference index to the stream */ _Py_HASHTABLE_ENTRY_READ_DATA(p->hashtable, entry, w); /* we don't store "long" indices in the dict */ assert(0 <= w && w <= 0x7fffffff); w_byte(TYPE_REF, p); w_long(w, p); return 1; } else { size_t s = p->hashtable->entries; /* we don't support long indices */ if (s >= 0x7fffffff) { PyErr_SetString(PyExc_ValueError, "too many objects"); goto err; } w = (int)s; Py_INCREF(v); if (_Py_HASHTABLE_SET(p->hashtable, v, w) < 0) { Py_DECREF(v); goto err; } *flag |= FLAG_REF; return 0; } err: p->error = WFERR_UNMARSHALLABLE; return 1; } static void w_complex_object(PyObject *v, char flag, WFILE *p); static void w_object(PyObject *v, WFILE *p) { char flag = '\0'; p->depth++; if (p->depth > MAX_MARSHAL_STACK_DEPTH) { p->error = WFERR_NESTEDTOODEEP; } else if (v == NULL) { w_byte(TYPE_NULL, p); } else if (v == Py_None) { w_byte(TYPE_NONE, p); } else if (v == PyExc_StopIteration) { w_byte(TYPE_STOPITER, p); } else if (v == Py_Ellipsis) { w_byte(TYPE_ELLIPSIS, p); } else if (v == Py_False) { w_byte(TYPE_FALSE, p); } else if (v == Py_True) { w_byte(TYPE_TRUE, p); } else if (!w_ref(v, &flag, p)) w_complex_object(v, flag, p); p->depth--; } static void w_complex_object(PyObject *v, char flag, WFILE *p) { Py_ssize_t i, n; if (PyLong_CheckExact(v)) { long x = PyLong_AsLong(v); if ((x == -1) && PyErr_Occurred()) { PyLongObject *ob = (PyLongObject *)v; PyErr_Clear(); w_PyLong(ob, flag, p); } else { #if SIZEOF_LONG > 4 long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); if (y && y != -1) { /* Too large for TYPE_INT */ w_PyLong((PyLongObject*)v, flag, p); } else #endif { W_TYPE(TYPE_INT, p); w_long(x, p); } } } else if (PyFloat_CheckExact(v)) { if (p->version > 1) { unsigned char buf[8]; if (_PyFloat_Pack8(PyFloat_AsDouble(v), buf, 1) < 0) { p->error = WFERR_UNMARSHALLABLE; return; } W_TYPE(TYPE_BINARY_FLOAT, p); w_string((char*)buf, 8, p); } else { char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), 'g', 17, 0, NULL); if (!buf) { p->error = WFERR_NOMEMORY; return; } n = strlen(buf); W_TYPE(TYPE_FLOAT, p); w_byte((int)n, p); w_string(buf, n, p); PyMem_Free(buf); } } else if (PyComplex_CheckExact(v)) { if (p->version > 1) { unsigned char buf[8]; if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), buf, 1) < 0) { p->error = WFERR_UNMARSHALLABLE; return; } W_TYPE(TYPE_BINARY_COMPLEX, p); w_string((char*)buf, 8, p); if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), buf, 1) < 0) { p->error = WFERR_UNMARSHALLABLE; return; } w_string((char*)buf, 8, p); } else { char *buf; W_TYPE(TYPE_COMPLEX, p); buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), 'g', 17, 0, NULL); if (!buf) { p->error = WFERR_NOMEMORY; return; } n = strlen(buf); w_byte((int)n, p); w_string(buf, n, p); PyMem_Free(buf); buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), 'g', 17, 0, NULL); if (!buf) { p->error = WFERR_NOMEMORY; return; } n = strlen(buf); w_byte((int)n, p); w_string(buf, n, p); PyMem_Free(buf); } } else if (PyBytes_CheckExact(v)) { W_TYPE(TYPE_STRING, p); w_pstring(PyBytes_AS_STRING(v), PyBytes_GET_SIZE(v), p); } else if (PyUnicode_CheckExact(v)) { if (p->version >= 4 && PyUnicode_IS_ASCII(v)) { int is_short = PyUnicode_GET_LENGTH(v) < 256; if (is_short) { if (PyUnicode_CHECK_INTERNED(v)) W_TYPE(TYPE_SHORT_ASCII_INTERNED, p); else W_TYPE(TYPE_SHORT_ASCII, p); w_short_pstring((char *) PyUnicode_1BYTE_DATA(v), PyUnicode_GET_LENGTH(v), p); } else { if (PyUnicode_CHECK_INTERNED(v)) W_TYPE(TYPE_ASCII_INTERNED, p); else W_TYPE(TYPE_ASCII, p); w_pstring((char *) PyUnicode_1BYTE_DATA(v), PyUnicode_GET_LENGTH(v), p); } } else { PyObject *utf8; utf8 = PyUnicode_AsEncodedString(v, "utf8", "surrogatepass"); if (utf8 == NULL) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } if (p->version >= 3 && PyUnicode_CHECK_INTERNED(v)) W_TYPE(TYPE_INTERNED, p); else W_TYPE(TYPE_UNICODE, p); w_pstring(PyBytes_AS_STRING(utf8), PyBytes_GET_SIZE(utf8), p); Py_DECREF(utf8); } } else if (PyTuple_CheckExact(v)) { n = PyTuple_Size(v); if (p->version >= 4 && n < 256) { W_TYPE(TYPE_SMALL_TUPLE, p); w_byte((unsigned char)n, p); } else { W_TYPE(TYPE_TUPLE, p); W_SIZE(n, p); } for (i = 0; i < n; i++) { w_object(PyTuple_GET_ITEM(v, i), p); } } else if (PyList_CheckExact(v)) { W_TYPE(TYPE_LIST, p); n = PyList_GET_SIZE(v); W_SIZE(n, p); for (i = 0; i < n; i++) { w_object(PyList_GET_ITEM(v, i), p); } } else if (PyDict_CheckExact(v)) { Py_ssize_t pos; PyObject *key, *value; W_TYPE(TYPE_DICT, p); /* This one is NULL object terminated! */ pos = 0; while (PyDict_Next(v, &pos, &key, &value)) { w_object(key, p); w_object(value, p); } w_object((PyObject *)NULL, p); } else if (PyAnySet_CheckExact(v)) { PyObject *value, *it; if (PyObject_TypeCheck(v, &PySet_Type)) W_TYPE(TYPE_SET, p); else W_TYPE(TYPE_FROZENSET, p); n = PyObject_Size(v); if (n == -1) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } W_SIZE(n, p); it = PyObject_GetIter(v); if (it == NULL) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } while ((value = PyIter_Next(it)) != NULL) { w_object(value, p); Py_DECREF(value); } Py_DECREF(it); if (PyErr_Occurred()) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } } else if (PyCode_Check(v)) { PyCodeObject *co = (PyCodeObject *)v; W_TYPE(TYPE_CODE, p); w_long(co->co_argcount, p); w_long(co->co_kwonlyargcount, p); w_long(co->co_nlocals, p); w_long(co->co_stacksize, p); w_long(co->co_flags, p); w_object(co->co_code, p); w_object(co->co_consts, p); w_object(co->co_names, p); w_object(co->co_varnames, p); w_object(co->co_freevars, p); w_object(co->co_cellvars, p); w_object(co->co_filename, p); w_object(co->co_name, p); w_long(co->co_firstlineno, p); w_object(co->co_lnotab, p); } else if (PyObject_CheckBuffer(v)) { /* Write unknown bytes-like objects as a bytes object */ Py_buffer view; if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) != 0) { w_byte(TYPE_UNKNOWN, p); p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } W_TYPE(TYPE_STRING, p); w_pstring(view.buf, view.len, p); PyBuffer_Release(&view); } else { W_TYPE(TYPE_UNKNOWN, p); p->error = WFERR_UNMARSHALLABLE; } } static int w_init_refs(WFILE *wf, int version) { if (version >= 3) { wf->hashtable = _Py_hashtable_new(sizeof(PyObject *), sizeof(int), _Py_hashtable_hash_ptr, _Py_hashtable_compare_direct); if (wf->hashtable == NULL) { PyErr_NoMemory(); return -1; } } return 0; } static int w_decref_entry(_Py_hashtable_t *ht, _Py_hashtable_entry_t *entry, void *Py_UNUSED(data)) { PyObject *entry_key; _Py_HASHTABLE_ENTRY_READ_KEY(ht, entry, entry_key); Py_XDECREF(entry_key); return 0; } static void w_clear_refs(WFILE *wf) { if (wf->hashtable != NULL) { _Py_hashtable_foreach(wf->hashtable, w_decref_entry, NULL); _Py_hashtable_destroy(wf->hashtable); } } /* version currently has no effect for writing ints. */ void PyMarshal_WriteLongToFile(long x, FILE *fp, int version) { char buf[4]; WFILE wf; bzero(&wf, sizeof(wf)); wf.fp = fp; wf.ptr = wf.buf = buf; wf.end = wf.ptr + sizeof(buf); wf.error = WFERR_OK; wf.version = version; w_long(x, &wf); w_flush(&wf); } void PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version) { WFILE wf; char *buf = gc(malloc(BUFSIZ)); bzero(&wf, sizeof(wf)); wf.fp = fp; wf.ptr = wf.buf = buf; wf.end = wf.ptr + BUFSIZ; wf.error = WFERR_OK; wf.version = version; if (w_init_refs(&wf, version)) return; /* caller mush check PyErr_Occurred() */ w_object(x, &wf); w_clear_refs(&wf); w_flush(&wf); } typedef struct { FILE *fp; int depth; PyObject *readable; /* Stream-like object being read from */ PyObject *current_filename; char *ptr; char *end; char *buf; Py_ssize_t buf_size; PyObject *refs; /* a list */ } RFILE; static const char * r_string(Py_ssize_t n, RFILE *p) { Py_ssize_t read = -1; if (p->ptr != NULL) { /* Fast path for loads() */ char *res = p->ptr; Py_ssize_t left = p->end - p->ptr; if (left < n) { PyErr_SetString(PyExc_EOFError, "marshal data too short"); return NULL; } p->ptr += n; return res; } if (p->buf == NULL) { p->buf = PyMem_MALLOC(n); if (p->buf == NULL) { PyErr_NoMemory(); return NULL; } p->buf_size = n; } else if (p->buf_size < n) { char *tmp = PyMem_REALLOC(p->buf, n); if (tmp == NULL) { PyErr_NoMemory(); return NULL; } p->buf = tmp; p->buf_size = n; } if (!p->readable) { assert(p->fp != NULL); read = fread(p->buf, 1, n, p->fp); } else { _Py_IDENTIFIER(readinto); PyObject *res, *mview; Py_buffer buf; if (PyBuffer_FillInfo(&buf, NULL, p->buf, n, 0, PyBUF_CONTIG) == -1) return NULL; mview = PyMemoryView_FromBuffer(&buf); if (mview == NULL) return NULL; res = _PyObject_CallMethodId(p->readable, &PyId_readinto, "N", mview); if (res != NULL) { read = PyNumber_AsSsize_t(res, PyExc_ValueError); Py_DECREF(res); } } if (read != n) { if (!PyErr_Occurred()) { if (read > n) PyErr_Format(PyExc_ValueError, "read() returned too much data: " "%zd bytes requested, %zd returned", n, read); else PyErr_SetString(PyExc_EOFError, "EOF read where not expected"); } return NULL; } return p->buf; } static int r_byte(RFILE *p) { int c = EOF; if (p->ptr != NULL) { if (p->ptr < p->end) c = (unsigned char) *p->ptr++; return c; } if (!p->readable) { assert(p->fp); c = getc(p->fp); } else { const char *ptr = r_string(1, p); if (ptr != NULL) c = *(unsigned char *) ptr; } return c; } static int r_short(RFILE *p) { short x = -1; const unsigned char *buffer; buffer = (const unsigned char *) r_string(2, p); if (buffer != NULL) { x = buffer[0]; x |= buffer[1] << 8; /* Sign-extension, in case short greater than 16 bits */ x |= -(x & 0x8000); } return x; } static long r_long(RFILE *p) { long x = -1; const unsigned char *buffer; buffer = (const unsigned char *) r_string(4, p); if (buffer != NULL) { x = buffer[0]; x |= (long)buffer[1] << 8; x |= (long)buffer[2] << 16; x |= (long)buffer[3] << 24; #if SIZEOF_LONG > 4 /* Sign extension for 64-bit machines */ x |= -(x & 0x80000000L); #endif } return x; } /* r_long64 deals with the TYPE_INT64 code. */ static PyObject * r_long64(RFILE *p) { const unsigned char *buffer = (const unsigned char *) r_string(8, p); if (buffer == NULL) { return NULL; } return _PyLong_FromByteArray(buffer, 8, 1 /* little endian */, 1 /* signed */); } static PyObject * r_PyLong(RFILE *p) { PyLongObject *ob; long n, size, i; int j, md, shorts_in_top_digit; digit d; n = r_long(p); if (PyErr_Occurred()) return NULL; if (n == 0) return (PyObject *)_PyLong_New(0); if (n < -SIZE32_MAX || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (long size out of range)"); return NULL; } size = 1 + (Py_ABS(n) - 1) / PyLong_MARSHAL_RATIO; shorts_in_top_digit = 1 + (Py_ABS(n) - 1) % PyLong_MARSHAL_RATIO; ob = _PyLong_New(size); if (ob == NULL) return NULL; Py_SIZE(ob) = n > 0 ? size : -size; for (i = 0; i < size-1; i++) { d = 0; for (j=0; j < PyLong_MARSHAL_RATIO; j++) { md = r_short(p); if (PyErr_Occurred()) { Py_DECREF(ob); return NULL; } if (md < 0 || md > PyLong_MARSHAL_BASE) goto bad_digit; d += (digit)md << j*PyLong_MARSHAL_SHIFT; } ob->ob_digit[i] = d; } d = 0; for (j=0; j < shorts_in_top_digit; j++) { md = r_short(p); if (PyErr_Occurred()) { Py_DECREF(ob); return NULL; } if (md < 0 || md > PyLong_MARSHAL_BASE) goto bad_digit; /* topmost marshal digit should be nonzero */ if (md == 0 && j == shorts_in_top_digit - 1) { Py_DECREF(ob); PyErr_SetString(PyExc_ValueError, "bad marshal data (unnormalized long data)"); return NULL; } d += (digit)md << j*PyLong_MARSHAL_SHIFT; } if (PyErr_Occurred()) { Py_DECREF(ob); return NULL; } /* top digit should be nonzero, else the resulting PyLong won't be normalized */ ob->ob_digit[size-1] = d; return (PyObject *)ob; bad_digit: Py_DECREF(ob); PyErr_SetString(PyExc_ValueError, "bad marshal data (digit out of range in long)"); return NULL; } /* allocate the reflist index for a new object. Return -1 on failure */ static Py_ssize_t r_ref_reserve(int flag, RFILE *p) { if (flag) { /* currently only FLAG_REF is defined */ Py_ssize_t idx = PyList_GET_SIZE(p->refs); if (idx >= 0x7ffffffe) { PyErr_SetString(PyExc_ValueError, "bad marshal data (index list too large)"); return -1; } if (PyList_Append(p->refs, Py_None) < 0) return -1; return idx; } else return 0; } /* insert the new object 'o' to the reflist at previously * allocated index 'idx'. * 'o' can be NULL, in which case nothing is done. * if 'o' was non-NULL, and the function succeeds, 'o' is returned. * if 'o' was non-NULL, and the function fails, 'o' is released and * NULL returned. This simplifies error checking at the call site since * a single test for NULL for the function result is enough. */ static PyObject * r_ref_insert(PyObject *o, Py_ssize_t idx, int flag, RFILE *p) { if (o != NULL && flag) { /* currently only FLAG_REF is defined */ PyObject *tmp = PyList_GET_ITEM(p->refs, idx); Py_INCREF(o); PyList_SET_ITEM(p->refs, idx, o); Py_DECREF(tmp); } return o; } /* combination of both above, used when an object can be * created whenever it is seen in the file, as opposed to * after having loaded its sub-objects. */ static PyObject * r_ref(PyObject *o, int flag, RFILE *p) { assert(flag & FLAG_REF); if (o == NULL) return NULL; if (PyList_Append(p->refs, o) < 0) { Py_DECREF(o); /* release the new object */ return NULL; } return o; } static PyObject * r_object(RFILE *p) { /* NULL is a valid return value, it does not necessarily means that an exception is set. */ PyObject *v, *v2; Py_ssize_t idx = 0; long i, n; int type, code = r_byte(p); int flag, is_interned = 0; PyObject *retval = NULL; if (code == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); return NULL; } p->depth++; if (p->depth > MAX_MARSHAL_STACK_DEPTH) { p->depth--; PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); return NULL; } flag = code & FLAG_REF; type = code & ~FLAG_REF; #define R_REF(O) do{\ if (flag) \ O = r_ref(O, flag, p);\ } while (0) switch (type) { case TYPE_NULL: break; case TYPE_NONE: Py_INCREF(Py_None); retval = Py_None; break; case TYPE_STOPITER: Py_INCREF(PyExc_StopIteration); retval = PyExc_StopIteration; break; case TYPE_ELLIPSIS: Py_INCREF(Py_Ellipsis); retval = Py_Ellipsis; break; case TYPE_FALSE: Py_INCREF(Py_False); retval = Py_False; break; case TYPE_TRUE: Py_INCREF(Py_True); retval = Py_True; break; case TYPE_INT: n = r_long(p); retval = PyErr_Occurred() ? NULL : PyLong_FromLong(n); R_REF(retval); break; case TYPE_INT64: retval = r_long64(p); R_REF(retval); break; case TYPE_LONG: retval = r_PyLong(p); R_REF(retval); break; case TYPE_FLOAT: { char buf[256]; const char *ptr; double dx; n = r_byte(p); if (n == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } ptr = r_string(n, p); if (ptr == NULL) break; memcpy(buf, ptr, n); buf[n] = '\0'; dx = PyOS_string_to_double(buf, NULL, NULL); if (dx == -1.0 && PyErr_Occurred()) break; retval = PyFloat_FromDouble(dx); R_REF(retval); break; } case TYPE_BINARY_FLOAT: { const unsigned char *buf; double x; buf = (const unsigned char *) r_string(8, p); if (buf == NULL) break; x = _PyFloat_Unpack8(buf, 1); if (x == -1.0 && PyErr_Occurred()) break; retval = PyFloat_FromDouble(x); R_REF(retval); break; } case TYPE_COMPLEX: { char buf[256]; const char *ptr; Py_complex c; n = r_byte(p); if (n == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } ptr = r_string(n, p); if (ptr == NULL) break; memcpy(buf, ptr, n); buf[n] = '\0'; c.real = PyOS_string_to_double(buf, NULL, NULL); if (c.real == -1.0 && PyErr_Occurred()) break; n = r_byte(p); if (n == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } ptr = r_string(n, p); if (ptr == NULL) break; memcpy(buf, ptr, n); buf[n] = '\0'; c.imag = PyOS_string_to_double(buf, NULL, NULL); if (c.imag == -1.0 && PyErr_Occurred()) break; retval = PyComplex_FromCComplex(c); R_REF(retval); break; } case TYPE_BINARY_COMPLEX: { const unsigned char *buf; Py_complex c; buf = (const unsigned char *) r_string(8, p); if (buf == NULL) break; c.real = _PyFloat_Unpack8(buf, 1); if (c.real == -1.0 && PyErr_Occurred()) break; buf = (const unsigned char *) r_string(8, p); if (buf == NULL) break; c.imag = _PyFloat_Unpack8(buf, 1); if (c.imag == -1.0 && PyErr_Occurred()) break; retval = PyComplex_FromCComplex(c); R_REF(retval); break; } case TYPE_STRING: { const char *ptr; n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (bytes object size out of range)"); break; } v = PyBytes_FromStringAndSize((char *)NULL, n); if (v == NULL) break; ptr = r_string(n, p); if (ptr == NULL) { Py_DECREF(v); break; } memcpy(PyBytes_AS_STRING(v), ptr, n); retval = v; R_REF(retval); break; } case TYPE_ASCII_INTERNED: is_interned = 1; /* fall through */ case TYPE_ASCII: n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); break; } goto _read_ascii; case TYPE_SHORT_ASCII_INTERNED: is_interned = 1; /* fall through */ case TYPE_SHORT_ASCII: n = r_byte(p); if (n == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } _read_ascii: { const char *ptr; ptr = r_string(n, p); if (ptr == NULL) break; v = PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, ptr, n); if (v == NULL) break; if (is_interned) PyUnicode_InternInPlace(&v); retval = v; R_REF(retval); break; } case TYPE_INTERNED: is_interned = 1; /* fall through */ case TYPE_UNICODE: { const char *buffer; n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); break; } if (n != 0) { buffer = r_string(n, p); if (buffer == NULL) break; v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); } else { v = PyUnicode_New(0, 0); } if (v == NULL) break; if (is_interned) PyUnicode_InternInPlace(&v); retval = v; R_REF(retval); break; } case TYPE_SMALL_TUPLE: n = (unsigned char) r_byte(p); if (PyErr_Occurred()) break; goto _read_tuple; case TYPE_TUPLE: n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); break; } _read_tuple: v = PyTuple_New(n); R_REF(v); if (v == NULL) break; for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for tuple"); Py_DECREF(v); v = NULL; break; } PyTuple_SET_ITEM(v, i, v2); } retval = v; break; case TYPE_LIST: n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); break; } v = PyList_New(n); R_REF(v); if (v == NULL) break; for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for list"); Py_DECREF(v); v = NULL; break; } PyList_SET_ITEM(v, i, v2); } retval = v; break; case TYPE_DICT: v = PyDict_New(); R_REF(v); if (v == NULL) break; for (;;) { PyObject *key, *val; key = r_object(p); if (key == NULL) break; val = r_object(p); if (val == NULL) { Py_DECREF(key); break; } if (PyDict_SetItem(v, key, val) < 0) { Py_DECREF(key); Py_DECREF(val); break; } Py_DECREF(key); Py_DECREF(val); } if (PyErr_Occurred()) { Py_DECREF(v); v = NULL; } retval = v; break; case TYPE_SET: case TYPE_FROZENSET: n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); break; } if (n == 0 && type == TYPE_FROZENSET) { /* call frozenset() to get the empty frozenset singleton */ v = PyObject_CallFunction((PyObject*)&PyFrozenSet_Type, NULL); if (v == NULL) break; R_REF(v); retval = v; } else { v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); if (type == TYPE_SET) { R_REF(v); } else { /* must use delayed registration of frozensets because they must * be init with a refcount of 1 */ idx = r_ref_reserve(flag, p); if (idx < 0) Py_CLEAR(v); /* signal error */ } if (v == NULL) break; for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for set"); Py_DECREF(v); v = NULL; break; } if (PySet_Add(v, v2) == -1) { Py_DECREF(v); Py_DECREF(v2); v = NULL; break; } Py_DECREF(v2); } if (type != TYPE_SET) v = r_ref_insert(v, idx, flag, p); retval = v; } break; case TYPE_CODE: { int argcount; int kwonlyargcount; int nlocals; int stacksize; int flags; PyObject *code = NULL; PyObject *consts = NULL; PyObject *names = NULL; PyObject *varnames = NULL; PyObject *freevars = NULL; PyObject *cellvars = NULL; PyObject *filename = NULL; PyObject *name = NULL; int firstlineno; PyObject *lnotab = NULL; idx = r_ref_reserve(flag, p); if (idx < 0) break; v = NULL; /* XXX ignore long->int overflows for now */ argcount = (int)r_long(p); if (PyErr_Occurred()) goto code_error; kwonlyargcount = (int)r_long(p); if (PyErr_Occurred()) goto code_error; nlocals = (int)r_long(p); if (PyErr_Occurred()) goto code_error; stacksize = (int)r_long(p); if (PyErr_Occurred()) goto code_error; flags = (int)r_long(p); if (PyErr_Occurred()) goto code_error; code = r_object(p); if (code == NULL) goto code_error; consts = r_object(p); if (consts == NULL) goto code_error; names = r_object(p); if (names == NULL) goto code_error; varnames = r_object(p); if (varnames == NULL) goto code_error; freevars = r_object(p); if (freevars == NULL) goto code_error; cellvars = r_object(p); if (cellvars == NULL) goto code_error; filename = r_object(p); if (filename == NULL) goto code_error; if (PyUnicode_CheckExact(filename)) { if (p->current_filename != NULL) { if (!PyUnicode_Compare(filename, p->current_filename)) { Py_DECREF(filename); Py_INCREF(p->current_filename); filename = p->current_filename; } } else { p->current_filename = filename; } } name = r_object(p); if (name == NULL) goto code_error; firstlineno = (int)r_long(p); if (firstlineno == -1 && PyErr_Occurred()) break; lnotab = r_object(p); if (lnotab == NULL) goto code_error; v = (PyObject *) PyCode_New( argcount, kwonlyargcount, nlocals, stacksize, flags, code, consts, names, varnames, freevars, cellvars, filename, name, firstlineno, lnotab); v = r_ref_insert(v, idx, flag, p); code_error: Py_XDECREF(code); Py_XDECREF(consts); Py_XDECREF(names); Py_XDECREF(varnames); Py_XDECREF(freevars); Py_XDECREF(cellvars); Py_XDECREF(filename); Py_XDECREF(name); Py_XDECREF(lnotab); } retval = v; break; case TYPE_REF: n = r_long(p); if (n < 0 || n >= PyList_GET_SIZE(p->refs)) { if (n == -1 && PyErr_Occurred()) break; PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)"); break; } v = PyList_GET_ITEM(p->refs, n); if (v == Py_None) { PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)"); break; } Py_INCREF(v); retval = v; break; default: /* Bogus data got written, which isn't ideal. This will let you keep working and recover. */ PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); break; } p->depth--; return retval; } static PyObject * read_object(RFILE *p) { PyObject *v; if (PyErr_Occurred()) { fprintf(stderr, "XXX readobject called with exception set\n"); return NULL; } v = r_object(p); if (v == NULL && !PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); return v; } int PyMarshal_ReadShortFromFile(FILE *fp) { RFILE rf; int res; assert(fp); rf.readable = NULL; rf.fp = fp; rf.current_filename = NULL; rf.end = rf.ptr = NULL; rf.buf = NULL; res = r_short(&rf); if (rf.buf != NULL) PyMem_FREE(rf.buf); return res; } long PyMarshal_ReadLongFromFile(FILE *fp) { RFILE rf; long res; rf.fp = fp; rf.readable = NULL; rf.current_filename = NULL; rf.ptr = rf.end = NULL; rf.buf = NULL; res = r_long(&rf); if (rf.buf != NULL) PyMem_FREE(rf.buf); return res; } /* Return size of file in bytes; < 0 if unknown or INT_MAX if too big */ static off_t getfilesize(FILE *fp) { struct _Py_stat_struct st; if (_Py_fstat_noraise(fileno(fp), &st) != 0) return -1; #if SIZEOF_OFF_T == 4 else if (st.st_size >= INT_MAX) return (off_t)INT_MAX; #endif else return (off_t)st.st_size; } /* If we can get the size of the file up-front, and it's reasonably small, * read it in one gulp and delegate to ...FromString() instead. Much quicker * than reading a byte at a time from file; speeds .pyc imports. * CAUTION: since this may read the entire remainder of the file, don't * call it unless you know you're done with the file. */ PyObject * PyMarshal_ReadLastObjectFromFile(FILE *fp) { /* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */ #define REASONABLE_FILE_LIMIT (1L << 18) off_t filesize; filesize = getfilesize(fp); if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) { char* pBuf = (char *)PyMem_MALLOC(filesize); if (pBuf != NULL) { size_t n = fread(pBuf, 1, (size_t)filesize, fp); PyObject* v = PyMarshal_ReadObjectFromString(pBuf, n); PyMem_FREE(pBuf); return v; } } /* We don't have fstat, or we do but the file is larger than * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. */ return PyMarshal_ReadObjectFromFile(fp); #undef REASONABLE_FILE_LIMIT } PyObject * PyMarshal_ReadObjectFromFile(FILE *fp) { RFILE rf; PyObject *result; rf.fp = fp; rf.readable = NULL; rf.current_filename = NULL; rf.depth = 0; rf.ptr = rf.end = NULL; rf.buf = NULL; rf.refs = PyList_New(0); if (rf.refs == NULL) return NULL; result = r_object(&rf); Py_DECREF(rf.refs); if (rf.buf != NULL) PyMem_FREE(rf.buf); return result; } PyObject * PyMarshal_ReadObjectFromString(const char *str, Py_ssize_t len) { RFILE rf; PyObject *result; rf.fp = NULL; rf.readable = NULL; rf.current_filename = NULL; rf.ptr = (char *)str; rf.end = (char *)str + len; rf.buf = NULL; rf.depth = 0; rf.refs = PyList_New(0); if (rf.refs == NULL) return NULL; result = r_object(&rf); Py_DECREF(rf.refs); if (rf.buf != NULL) PyMem_FREE(rf.buf); return result; } PyObject * PyMarshal_WriteObjectToString(PyObject *x, int version) { WFILE wf; bzero(&wf, sizeof(wf)); wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); if (wf.str == NULL) return NULL; wf.ptr = wf.buf = PyBytes_AS_STRING((PyBytesObject *)wf.str); wf.end = wf.ptr + PyBytes_Size(wf.str); wf.error = WFERR_OK; wf.version = version; if (w_init_refs(&wf, version)) { Py_DECREF(wf.str); return NULL; } w_object(x, &wf); w_clear_refs(&wf); if (wf.str != NULL) { char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); if (wf.ptr - base > PY_SSIZE_T_MAX) { Py_DECREF(wf.str); PyErr_SetString(PyExc_OverflowError, "too much marshal data for a bytes object"); return NULL; } if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) return NULL; } if (wf.error != WFERR_OK) { Py_XDECREF(wf.str); if (wf.error == WFERR_NOMEMORY) PyErr_NoMemory(); else PyErr_SetString(PyExc_ValueError, (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" :"object too deeply nested to marshal"); return NULL; } return wf.str; } /* And an interface for Python programs... */ static PyObject * marshal_dump(PyObject *self, PyObject **args, Py_ssize_t nargs) { /* XXX Quick hack -- need to do this differently */ PyObject *x; PyObject *f; int version = Py_MARSHAL_VERSION; PyObject *s; PyObject *res; _Py_IDENTIFIER(write); if (!_PyArg_ParseStack(args, nargs, "OO|i:dump", &x, &f, &version)) return NULL; s = PyMarshal_WriteObjectToString(x, version); if (s == NULL) return NULL; res = _PyObject_CallMethodId(f, &PyId_write, "O", s); Py_DECREF(s); return res; } PyDoc_STRVAR(dump_doc, "dump(value, file[, version])\n\ \n\ Write the value on the open file. The value must be a supported type.\n\ The file must be a writeable binary file.\n\ \n\ If the value has (or contains an object that has) an unsupported type, a\n\ ValueError exception is raised - but garbage data will also be written\n\ to the file. The object will not be properly read back by load()\n\ \n\ The version argument indicates the data format that dump should use."); static PyObject * marshal_load(PyObject *self, PyObject *f) { PyObject *data, *result; _Py_IDENTIFIER(read); RFILE rf; /* * Make a call to the read method, but read zero bytes. * This is to ensure that the object passed in at least * has a read method which returns bytes. * This can be removed if we guarantee good error handling * for r_string() */ data = _PyObject_CallMethodId(f, &PyId_read, "i", 0); if (data == NULL) return NULL; if (!PyBytes_Check(data)) { PyErr_Format(PyExc_TypeError, "f.read() returned not bytes but %.100s", data->ob_type->tp_name); result = NULL; } else { rf.depth = 0; rf.fp = NULL; rf.readable = f; rf.current_filename = NULL; rf.ptr = rf.end = NULL; rf.buf = NULL; if ((rf.refs = PyList_New(0)) != NULL) { result = read_object(&rf); Py_DECREF(rf.refs); if (rf.buf != NULL) PyMem_FREE(rf.buf); } else result = NULL; } Py_DECREF(data); return result; } PyDoc_STRVAR(load_doc, "load(file)\n\ \n\ Read one value from the open file and return it. If no valid value is\n\ read (e.g. because the data has a different Python version's\n\ incompatible marshal format), raise EOFError, ValueError or TypeError.\n\ The file must be a readable binary file.\n\ \n\ Note: If an object containing an unsupported type was marshalled with\n\ dump(), load() will substitute None for the unmarshallable type."); static PyObject * marshal_dumps(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *x; int version = Py_MARSHAL_VERSION; if (!_PyArg_ParseStack(args, nargs, "O|i:dumps", &x, &version)) return NULL; return PyMarshal_WriteObjectToString(x, version); } PyDoc_STRVAR(dumps_doc, "dumps(value[, version])\n\ \n\ Return the bytes object that would be written to a file by dump(value, file).\n\ The value must be a supported type. Raise a ValueError exception if\n\ value has (or contains an object that has) an unsupported type.\n\ \n\ The version argument indicates the data format that dumps should use."); static PyObject * marshal_loads(PyObject *self, PyObject **args, Py_ssize_t nargs) { RFILE rf; Py_buffer p; char *s; Py_ssize_t n; PyObject* result; if (!_PyArg_ParseStack(args, nargs, "y*:loads", &p)) return NULL; s = p.buf; n = p.len; rf.fp = NULL; rf.readable = NULL; rf.current_filename = NULL; rf.ptr = s; rf.end = s + n; rf.depth = 0; if ((rf.refs = PyList_New(0)) == NULL) return NULL; result = read_object(&rf); PyBuffer_Release(&p); Py_DECREF(rf.refs); return result; } PyDoc_STRVAR(loads_doc, "loads(bytes)\n\ \n\ Convert the bytes-like object to a value. If no valid value is found,\n\ raise EOFError, ValueError or TypeError. Extra bytes in the input are\n\ ignored."); static PyMethodDef marshal_methods[] = { {"dump", (PyCFunction)marshal_dump, METH_FASTCALL, dump_doc}, {"load", marshal_load, METH_O, load_doc}, {"dumps", (PyCFunction)marshal_dumps, METH_FASTCALL, dumps_doc}, {"loads", (PyCFunction)marshal_loads, METH_FASTCALL, loads_doc}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "This module contains functions that can read and write Python values in\n\ a binary format. The format is specific to Python, but independent of\n\ machine architecture issues.\n\ \n\ Not all Python object types are supported; in general, only objects\n\ whose value is independent from a particular invocation of Python can be\n\ written and read by this module. The following types are supported:\n\ None, integers, floating point numbers, strings, bytes, bytearrays,\n\ tuples, lists, sets, dictionaries, and code objects, where it\n\ should be understood that tuples, lists and dictionaries are only\n\ supported as long as the values contained therein are themselves\n\ supported; and recursive lists and dictionaries should not be written\n\ (they will cause infinite loops).\n\ \n\ Variables:\n\ \n\ version -- indicates the format that the module uses. Version 0 is the\n\ historical format, version 1 shares interned strings and version 2\n\ uses a binary format for floating point numbers.\n\ Version 3 shares common object references (New in version 3.4).\n\ \n\ Functions:\n\ \n\ dump() -- write value to a file\n\ load() -- read value from a file\n\ dumps() -- marshal value as a bytes object\n\ loads() -- read value from a bytes-like object"); static struct PyModuleDef marshalmodule = { PyModuleDef_HEAD_INIT, "marshal", module_doc, 0, marshal_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyMarshal_Init(void) { PyObject *mod = PyModule_Create(&marshalmodule); if (mod == NULL) return NULL; PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); return mod; }
53,664
1,892
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/importdl.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Python/importdl.h" /* clang-format off */ /* Support for dynamic loading of extension modules */ /* ./configure sets HAVE_DYNAMIC_LOADING if dynamic loading of modules is supported on this platform. configure will then compile and link in one of the dynload_*.c files, as appropriate. We will call a function in those modules to get a function pointer to the module's init function. */ #ifdef HAVE_DYNAMIC_LOADING #ifdef MS_WINDOWS extern dl_funcptr _PyImport_FindSharedFuncptrWindows(const char *prefix, const char *shortname, PyObject *pathname, FILE *fp); #else extern dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix, const char *shortname, const char *pathname, FILE *fp); #endif static const char * const ascii_only_prefix = "PyInit"; static const char * const nonascii_prefix = "PyInitU"; /* Get the variable part of a module's export symbol name. * Returns a bytes instance. For non-ASCII-named modules, the name is * encoded as per PEP 489. * The hook_prefix pointer is set to either ascii_only_prefix or * nonascii_prefix, as appropriate. */ static PyObject * get_encoded_name(PyObject *name, const char **hook_prefix) { PyObject *tmp; PyObject *encoded = NULL; PyObject *modname = NULL; Py_ssize_t name_len, lastdot; _Py_IDENTIFIER(replace); /* Get the short name (substring after last dot) */ name_len = PyUnicode_GetLength(name); lastdot = PyUnicode_FindChar(name, '.', 0, name_len, -1); if (lastdot < -1) { return NULL; } else if (lastdot >= 0) { tmp = PyUnicode_Substring(name, lastdot + 1, name_len); if (tmp == NULL) return NULL; name = tmp; /* "name" now holds a new reference to the substring */ } else { Py_INCREF(name); } /* Encode to ASCII or Punycode, as needed */ encoded = PyUnicode_AsEncodedString(name, "ascii", NULL); if (encoded != NULL) { *hook_prefix = ascii_only_prefix; } else { if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) { PyErr_Clear(); encoded = PyUnicode_AsEncodedString(name, "punycode", NULL); if (encoded == NULL) { goto error; } *hook_prefix = nonascii_prefix; } else { goto error; } } /* Replace '-' by '_' */ modname = _PyObject_CallMethodId(encoded, &PyId_replace, "cc", '-', '_'); if (modname == NULL) goto error; Py_DECREF(name); Py_DECREF(encoded); return modname; error: Py_DECREF(name); Py_XDECREF(encoded); return NULL; } PyObject * _PyImport_LoadDynamicModuleWithSpec(PyObject *spec, FILE *fp) { #ifndef MS_WINDOWS PyObject *pathbytes = NULL; #endif PyObject *name_unicode = NULL, *name = NULL, *path = NULL, *m = NULL; const char *name_buf, *hook_prefix; char *oldcontext; dl_funcptr exportfunc; PyModuleDef *def; PyObject *(*p0)(void); name_unicode = PyObject_GetAttrString(spec, "name"); if (name_unicode == NULL) { return NULL; } if (!PyUnicode_Check(name_unicode)) { PyErr_SetString(PyExc_TypeError, "spec.name must be a string"); goto error; } name = get_encoded_name(name_unicode, &hook_prefix); if (name == NULL) { goto error; } name_buf = PyBytes_AS_STRING(name); path = PyObject_GetAttrString(spec, "origin"); if (path == NULL) goto error; #ifdef MS_WINDOWS exportfunc = _PyImport_FindSharedFuncptrWindows(hook_prefix, name_buf, path, fp); #else pathbytes = PyUnicode_EncodeFSDefault(path); if (pathbytes == NULL) goto error; exportfunc = _PyImport_FindSharedFuncptr(hook_prefix, name_buf, PyBytes_AS_STRING(pathbytes), fp); Py_DECREF(pathbytes); #endif if (exportfunc == NULL) { if (!PyErr_Occurred()) { PyObject *msg; msg = PyUnicode_FromFormat( "dynamic module does not define " "module export function (%s_%s)", hook_prefix, name_buf); if (msg == NULL) goto error; PyErr_SetImportError(msg, name_unicode, path); Py_DECREF(msg); } goto error; } p0 = (PyObject *(*)(void))exportfunc; /* Package context is needed for single-phase init */ oldcontext = _Py_PackageContext; _Py_PackageContext = PyUnicode_AsUTF8(name_unicode); if (_Py_PackageContext == NULL) { _Py_PackageContext = oldcontext; goto error; } m = p0(); _Py_PackageContext = oldcontext; if (m == NULL) { if (!PyErr_Occurred()) { PyErr_Format( PyExc_SystemError, "initialization of %s failed without raising an exception", name_buf); } goto error; } else if (PyErr_Occurred()) { PyErr_Clear(); PyErr_Format( PyExc_SystemError, "initialization of %s raised unreported exception", name_buf); m = NULL; goto error; } if (Py_TYPE(m) == NULL) { /* This can happen when a PyModuleDef is returned without calling * PyModuleDef_Init on it */ PyErr_Format(PyExc_SystemError, "init function of %s returned uninitialized object", name_buf); m = NULL; /* prevent segfault in DECREF */ goto error; } if (PyObject_TypeCheck(m, &PyModuleDef_Type)) { Py_DECREF(name_unicode); Py_DECREF(name); Py_DECREF(path); return PyModule_FromDefAndSpec((PyModuleDef*)m, spec); } /* Fall back to single-phase init mechanism */ if (hook_prefix == nonascii_prefix) { /* don't allow legacy init for non-ASCII module names */ PyErr_Format( PyExc_SystemError, "initialization of * did not return PyModuleDef", name_buf); goto error; } /* Remember pointer to module init function. */ def = PyModule_GetDef(m); if (def == NULL) { PyErr_Format(PyExc_SystemError, "initialization of %s did not return an extension " "module", name_buf); goto error; } def->m_base.m_init = p0; /* Remember the filename as the __file__ attribute */ if (PyModule_AddObject(m, "__file__", path) < 0) PyErr_Clear(); /* Not important enough to report */ else Py_INCREF(path); if (_PyImport_FixupExtensionObject(m, name_unicode, path) < 0) goto error; Py_DECREF(name_unicode); Py_DECREF(name); Py_DECREF(path); return m; error: Py_DECREF(name_unicode); Py_XDECREF(name); Py_XDECREF(path); Py_XDECREF(m); return NULL; } #endif /* HAVE_DYNAMIC_LOADING */
8,458
252
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/getcompiler.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ #ifndef COMPILER #ifdef __llvm__ #define COMPILER "[LLVM " __VERSION__ "]" #elif defined(__GNUC__) #define COMPILER "[GCC " __VERSION__ "]" #elif defined(__cplusplus) #define COMPILER "[C++]" #else #define COMPILER "[C]" #endif #endif /* !COMPILER */ const char * Py_GetCompiler(void) { return COMPILER; }
1,203
27
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/initsite.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ /* PYTHON_YOINK("site"); */ /* PYTHON_YOINK("_sysconfigdata_m_cosmo_x86_64_cosmo"); */ void _Py_InitSite(void) { PyObject *m; m = PyImport_ImportModule("site"); if (m == NULL) { fputs("Failed to import the site module\n", stderr); PyErr_Print(); Py_Finalize(); exit(1); } else { Py_DECREF(m); } }
1,508
34
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/clinic/import.inc
/* clang-format off */ /*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(_imp_lock_held__doc__, "lock_held($module, /)\n" "--\n" "\n" "Return True if the import lock is currently held, else False.\n" "\n" "On platforms without threads, return False."); #define _IMP_LOCK_HELD_METHODDEF \ {"lock_held", (PyCFunction)_imp_lock_held, METH_NOARGS, _imp_lock_held__doc__}, static PyObject * _imp_lock_held_impl(PyObject *module); static PyObject * _imp_lock_held(PyObject *module, PyObject *Py_UNUSED(ignored)) { return _imp_lock_held_impl(module); } PyDoc_STRVAR(_imp_acquire_lock__doc__, "acquire_lock($module, /)\n" "--\n" "\n" "Acquires the interpreter\'s import lock for the current thread.\n" "\n" "This lock should be used by import hooks to ensure thread-safety when importing\n" "modules. On platforms without threads, this function does nothing."); #define _IMP_ACQUIRE_LOCK_METHODDEF \ {"acquire_lock", (PyCFunction)_imp_acquire_lock, METH_NOARGS, _imp_acquire_lock__doc__}, static PyObject * _imp_acquire_lock_impl(PyObject *module); static PyObject * _imp_acquire_lock(PyObject *module, PyObject *Py_UNUSED(ignored)) { return _imp_acquire_lock_impl(module); } PyDoc_STRVAR(_imp_release_lock__doc__, "release_lock($module, /)\n" "--\n" "\n" "Release the interpreter\'s import lock.\n" "\n" "On platforms without threads, this function does nothing."); #define _IMP_RELEASE_LOCK_METHODDEF \ {"release_lock", (PyCFunction)_imp_release_lock, METH_NOARGS, _imp_release_lock__doc__}, static PyObject * _imp_release_lock_impl(PyObject *module); static PyObject * _imp_release_lock(PyObject *module, PyObject *Py_UNUSED(ignored)) { return _imp_release_lock_impl(module); } PyDoc_STRVAR(_imp__fix_co_filename__doc__, "_fix_co_filename($module, code, path, /)\n" "--\n" "\n" "Changes code.co_filename to specify the passed-in file path.\n" "\n" " code\n" " Code object to change.\n" " path\n" " File path to use."); #define _IMP__FIX_CO_FILENAME_METHODDEF \ {"_fix_co_filename", (PyCFunction)_imp__fix_co_filename, METH_FASTCALL, _imp__fix_co_filename__doc__}, static PyObject * _imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code, PyObject *path); static PyObject * _imp__fix_co_filename(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyCodeObject *code; PyObject *path; if (!_PyArg_ParseStack(args, nargs, "O!U:_fix_co_filename", &PyCode_Type, &code, &path)) { goto exit; } return_value = _imp__fix_co_filename_impl(module, code, path); exit: return return_value; } PyDoc_STRVAR(_imp_create_builtin__doc__, "create_builtin($module, spec, /)\n" "--\n" "\n" "Create an extension module."); #define _IMP_CREATE_BUILTIN_METHODDEF \ {"create_builtin", (PyCFunction)_imp_create_builtin, METH_O, _imp_create_builtin__doc__}, PyDoc_STRVAR(_imp_extension_suffixes__doc__, "extension_suffixes($module, /)\n" "--\n" "\n" "Returns the list of file suffixes used to identify extension modules."); #define _IMP_EXTENSION_SUFFIXES_METHODDEF \ {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__}, static PyObject * _imp_extension_suffixes_impl(PyObject *module); static PyObject * _imp_extension_suffixes(PyObject *module, PyObject *Py_UNUSED(ignored)) { return _imp_extension_suffixes_impl(module); } PyDoc_STRVAR(_imp_init_frozen__doc__, "init_frozen($module, name, /)\n" "--\n" "\n" "Initializes a frozen module."); #define _IMP_INIT_FROZEN_METHODDEF \ {"init_frozen", (PyCFunction)_imp_init_frozen, METH_O, _imp_init_frozen__doc__}, static PyObject * _imp_init_frozen_impl(PyObject *module, PyObject *name); static PyObject * _imp_init_frozen(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; PyObject *name; if (!PyArg_Parse(arg, "U:init_frozen", &name)) { goto exit; } return_value = _imp_init_frozen_impl(module, name); exit: return return_value; } PyDoc_STRVAR(_imp_get_frozen_object__doc__, "get_frozen_object($module, name, /)\n" "--\n" "\n" "Create a code object for a frozen module."); #define _IMP_GET_FROZEN_OBJECT_METHODDEF \ {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_O, _imp_get_frozen_object__doc__}, static PyObject * _imp_get_frozen_object_impl(PyObject *module, PyObject *name); static PyObject * _imp_get_frozen_object(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; PyObject *name; if (!PyArg_Parse(arg, "U:get_frozen_object", &name)) { goto exit; } return_value = _imp_get_frozen_object_impl(module, name); exit: return return_value; } PyDoc_STRVAR(_imp_is_frozen_package__doc__, "is_frozen_package($module, name, /)\n" "--\n" "\n" "Returns True if the module name is of a frozen package."); #define _IMP_IS_FROZEN_PACKAGE_METHODDEF \ {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_O, _imp_is_frozen_package__doc__}, static PyObject * _imp_is_frozen_package_impl(PyObject *module, PyObject *name); static PyObject * _imp_is_frozen_package(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; PyObject *name; if (!PyArg_Parse(arg, "U:is_frozen_package", &name)) { goto exit; } return_value = _imp_is_frozen_package_impl(module, name); exit: return return_value; } PyDoc_STRVAR(_imp_is_builtin__doc__, "is_builtin($module, name, /)\n" "--\n" "\n" "Returns True if the module name corresponds to a built-in module."); #define _IMP_IS_BUILTIN_METHODDEF \ {"is_builtin", (PyCFunction)_imp_is_builtin, METH_O, _imp_is_builtin__doc__}, static PyObject * _imp_is_builtin_impl(PyObject *module, PyObject *name); static PyObject * _imp_is_builtin(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; PyObject *name; if (!PyArg_Parse(arg, "U:is_builtin", &name)) { goto exit; } return_value = _imp_is_builtin_impl(module, name); exit: return return_value; } PyDoc_STRVAR(_imp_is_frozen__doc__, "is_frozen($module, name, /)\n" "--\n" "\n" "Returns True if the module name corresponds to a frozen module."); #define _IMP_IS_FROZEN_METHODDEF \ {"is_frozen", (PyCFunction)_imp_is_frozen, METH_O, _imp_is_frozen__doc__}, static PyObject * _imp_is_frozen_impl(PyObject *module, PyObject *name); static PyObject * _imp_is_frozen(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; PyObject *name; if (!PyArg_Parse(arg, "U:is_frozen", &name)) { goto exit; } return_value = _imp_is_frozen_impl(module, name); exit: return return_value; } #if defined(HAVE_DYNAMIC_LOADING) PyDoc_STRVAR(_imp_create_dynamic__doc__, "create_dynamic($module, spec, file=None, /)\n" "--\n" "\n" "Create an extension module."); #define _IMP_CREATE_DYNAMIC_METHODDEF \ {"create_dynamic", (PyCFunction)_imp_create_dynamic, METH_FASTCALL, _imp_create_dynamic__doc__}, static PyObject * _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file); static PyObject * _imp_create_dynamic(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *spec; PyObject *file = NULL; if (!_PyArg_UnpackStack(args, nargs, "create_dynamic", 1, 2, &spec, &file)) { goto exit; } return_value = _imp_create_dynamic_impl(module, spec, file); exit: return return_value; } #endif /* defined(HAVE_DYNAMIC_LOADING) */ #if defined(HAVE_DYNAMIC_LOADING) PyDoc_STRVAR(_imp_exec_dynamic__doc__, "exec_dynamic($module, mod, /)\n" "--\n" "\n" "Initialize an extension module."); #define _IMP_EXEC_DYNAMIC_METHODDEF \ {"exec_dynamic", (PyCFunction)_imp_exec_dynamic, METH_O, _imp_exec_dynamic__doc__}, static int _imp_exec_dynamic_impl(PyObject *module, PyObject *mod); static PyObject * _imp_exec_dynamic(PyObject *module, PyObject *mod) { PyObject *return_value = NULL; int _return_value; _return_value = _imp_exec_dynamic_impl(module, mod); if ((_return_value == -1) && PyErr_Occurred()) { goto exit; } return_value = PyLong_FromLong((long)_return_value); exit: return return_value; } #endif /* defined(HAVE_DYNAMIC_LOADING) */ PyDoc_STRVAR(_imp_exec_builtin__doc__, "exec_builtin($module, mod, /)\n" "--\n" "\n" "Initialize a built-in module."); #define _IMP_EXEC_BUILTIN_METHODDEF \ {"exec_builtin", (PyCFunction)_imp_exec_builtin, METH_O, _imp_exec_builtin__doc__}, static int _imp_exec_builtin_impl(PyObject *module, PyObject *mod); static PyObject * _imp_exec_builtin(PyObject *module, PyObject *mod) { PyObject *return_value = NULL; int _return_value; _return_value = _imp_exec_builtin_impl(module, mod); if ((_return_value == -1) && PyErr_Occurred()) { goto exit; } return_value = PyLong_FromLong((long)_return_value); exit: return return_value; } #ifndef _IMP_CREATE_DYNAMIC_METHODDEF #define _IMP_CREATE_DYNAMIC_METHODDEF #endif /* !defined(_IMP_CREATE_DYNAMIC_METHODDEF) */ #ifndef _IMP_EXEC_DYNAMIC_METHODDEF #define _IMP_EXEC_DYNAMIC_METHODDEF #endif /* !defined(_IMP_EXEC_DYNAMIC_METHODDEF) */ /*[clinic end generated code: output=d068dd493e513604 input=a9049054013a1b77]*/
9,377
366
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/clinic/bltinmodule.inc
/* clang-format off */ /*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(builtin_abs__doc__, "abs($module, x, /)\n" "--\n" "\n" "Return the absolute value of the argument."); #define BUILTIN_ABS_METHODDEF \ {"abs", (PyCFunction)builtin_abs, METH_O, builtin_abs__doc__}, PyDoc_STRVAR(builtin_all__doc__, "all($module, iterable, /)\n" "--\n" "\n" "Return True if bool(x) is True for all values x in the iterable.\n" "\n" "If the iterable is empty, return True."); #define BUILTIN_ALL_METHODDEF \ {"all", (PyCFunction)builtin_all, METH_O, builtin_all__doc__}, PyDoc_STRVAR(builtin_any__doc__, "any($module, iterable, /)\n" "--\n" "\n" "Return True if bool(x) is True for any x in the iterable.\n" "\n" "If the iterable is empty, return False."); #define BUILTIN_ANY_METHODDEF \ {"any", (PyCFunction)builtin_any, METH_O, builtin_any__doc__}, PyDoc_STRVAR(builtin_ascii__doc__, "ascii($module, obj, /)\n" "--\n" "\n" "Return an ASCII-only representation of an object.\n" "\n" "As repr(), return a string containing a printable representation of an\n" "object, but escape the non-ASCII characters in the string returned by\n" "repr() using \\\\x, \\\\u or \\\\U escapes. This generates a string similar\n" "to that returned by repr() in Python 2."); #define BUILTIN_ASCII_METHODDEF \ {"ascii", (PyCFunction)builtin_ascii, METH_O, builtin_ascii__doc__}, PyDoc_STRVAR(builtin_bin__doc__, "bin($module, number, /)\n" "--\n" "\n" "Return the binary representation of an integer.\n" "\n" " >>> bin(2796202)\n" " \'0b1010101010101010101010\'"); #define BUILTIN_BIN_METHODDEF \ {"bin", (PyCFunction)builtin_bin, METH_O, builtin_bin__doc__}, PyDoc_STRVAR(builtin_callable__doc__, "callable($module, obj, /)\n" "--\n" "\n" "Return whether the object is callable (i.e., some kind of function).\n" "\n" "Note that classes are callable, as are instances of classes with a\n" "__call__() method."); #define BUILTIN_CALLABLE_METHODDEF \ {"callable", (PyCFunction)builtin_callable, METH_O, builtin_callable__doc__}, PyDoc_STRVAR(builtin_format__doc__, "format($module, value, format_spec=\'\', /)\n" "--\n" "\n" "Return value.__format__(format_spec)\n" "\n" "format_spec defaults to the empty string.\n" "See the Format Specification Mini-Language section of help(\'FORMATTING\') for\n" "details."); #define BUILTIN_FORMAT_METHODDEF \ {"format", (PyCFunction)builtin_format, METH_FASTCALL, builtin_format__doc__}, static PyObject * builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec); static PyObject * builtin_format(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *value; PyObject *format_spec = NULL; if (!_PyArg_ParseStack(args, nargs, "O|U:format", &value, &format_spec)) { goto exit; } return_value = builtin_format_impl(module, value, format_spec); exit: return return_value; } PyDoc_STRVAR(builtin_chr__doc__, "chr($module, i, /)\n" "--\n" "\n" "Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."); #define BUILTIN_CHR_METHODDEF \ {"chr", (PyCFunction)builtin_chr, METH_O, builtin_chr__doc__}, static PyObject * builtin_chr_impl(PyObject *module, int i); static PyObject * builtin_chr(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; int i; if (!PyArg_Parse(arg, "i:chr", &i)) { goto exit; } return_value = builtin_chr_impl(module, i); exit: return return_value; } PyDoc_STRVAR(builtin_compile__doc__, "compile($module, /, source, filename, mode, flags=0,\n" " dont_inherit=False, optimize=-1)\n" "--\n" "\n" "Compile source into a code object that can be executed by exec() or eval().\n" "\n" "The source code may represent a Python module, statement or expression.\n" "The filename will be used for run-time error messages.\n" "The mode must be \'exec\' to compile a module, \'single\' to compile a\n" "single (interactive) statement, or \'eval\' to compile an expression.\n" "The flags argument, if present, controls which future statements influence\n" "the compilation of the code.\n" "The dont_inherit argument, if true, stops the compilation inheriting\n" "the effects of any future statements in effect in the code calling\n" "compile; if absent or false these statements do influence the compilation,\n" "in addition to any features explicitly specified."); #define BUILTIN_COMPILE_METHODDEF \ {"compile", (PyCFunction)builtin_compile, METH_FASTCALL|METH_KEYWORDS, builtin_compile__doc__}, static PyObject * builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize); static PyObject * builtin_compile(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"source", "filename", "mode", "flags", "dont_inherit", "optimize", NULL}; static _PyArg_Parser _parser = {"OO&s|iii:compile", _keywords, 0}; PyObject *source; PyObject *filename; const char *mode; int flags = 0; int dont_inherit = 0; int optimize = -1; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &source, PyUnicode_FSDecoder, &filename, &mode, &flags, &dont_inherit, &optimize)) { goto exit; } return_value = builtin_compile_impl(module, source, filename, mode, flags, dont_inherit, optimize); exit: return return_value; } PyDoc_STRVAR(builtin_divmod__doc__, "divmod($module, x, y, /)\n" "--\n" "\n" "Return the tuple (x//y, x%y). Invariant: div*y + mod == x."); #define BUILTIN_DIVMOD_METHODDEF \ {"divmod", (PyCFunction)builtin_divmod, METH_FASTCALL, builtin_divmod__doc__}, static PyObject * builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y); static PyObject * builtin_divmod(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *x; PyObject *y; if (!_PyArg_UnpackStack(args, nargs, "divmod", 2, 2, &x, &y)) { goto exit; } return_value = builtin_divmod_impl(module, x, y); exit: return return_value; } PyDoc_STRVAR(builtin_eval__doc__, "eval($module, source, globals=None, locals=None, /)\n" "--\n" "\n" "Evaluate the given source in the context of globals and locals.\n" "\n" "The source may be a string representing a Python expression\n" "or a code object as returned by compile().\n" "The globals must be a dictionary and locals can be any mapping,\n" "defaulting to the current globals and locals.\n" "If only globals is given, locals defaults to it."); #define BUILTIN_EVAL_METHODDEF \ {"eval", (PyCFunction)builtin_eval, METH_FASTCALL, builtin_eval__doc__}, static PyObject * builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals, PyObject *locals); static PyObject * builtin_eval(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *source; PyObject *globals = Py_None; PyObject *locals = Py_None; if (!_PyArg_UnpackStack(args, nargs, "eval", 1, 3, &source, &globals, &locals)) { goto exit; } return_value = builtin_eval_impl(module, source, globals, locals); exit: return return_value; } PyDoc_STRVAR(builtin_exec__doc__, "exec($module, source, globals=None, locals=None, /)\n" "--\n" "\n" "Execute the given source in the context of globals and locals.\n" "\n" "The source may be a string representing one or more Python statements\n" "or a code object as returned by compile().\n" "The globals must be a dictionary and locals can be any mapping,\n" "defaulting to the current globals and locals.\n" "If only globals is given, locals defaults to it."); #define BUILTIN_EXEC_METHODDEF \ {"exec", (PyCFunction)builtin_exec, METH_FASTCALL, builtin_exec__doc__}, static PyObject * builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals, PyObject *locals); static PyObject * builtin_exec(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *source; PyObject *globals = Py_None; PyObject *locals = Py_None; if (!_PyArg_UnpackStack(args, nargs, "exec", 1, 3, &source, &globals, &locals)) { goto exit; } return_value = builtin_exec_impl(module, source, globals, locals); exit: return return_value; } PyDoc_STRVAR(builtin_globals__doc__, "globals($module, /)\n" "--\n" "\n" "Return the dictionary containing the current scope\'s global variables.\n" "\n" "NOTE: Updates to this dictionary *will* affect name lookups in the current\n" "global scope and vice-versa."); #define BUILTIN_GLOBALS_METHODDEF \ {"globals", (PyCFunction)builtin_globals, METH_NOARGS, builtin_globals__doc__}, static PyObject * builtin_globals_impl(PyObject *module); static PyObject * builtin_globals(PyObject *module, PyObject *Py_UNUSED(ignored)) { return builtin_globals_impl(module); } PyDoc_STRVAR(builtin_hasattr__doc__, "hasattr($module, obj, name, /)\n" "--\n" "\n" "Return whether the object has an attribute with the given name.\n" "\n" "This is done by calling getattr(obj, name) and catching AttributeError."); #define BUILTIN_HASATTR_METHODDEF \ {"hasattr", (PyCFunction)builtin_hasattr, METH_FASTCALL, builtin_hasattr__doc__}, static PyObject * builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name); static PyObject * builtin_hasattr(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *obj; PyObject *name; if (!_PyArg_UnpackStack(args, nargs, "hasattr", 2, 2, &obj, &name)) { goto exit; } return_value = builtin_hasattr_impl(module, obj, name); exit: return return_value; } PyDoc_STRVAR(builtin_id__doc__, "id($module, obj, /)\n" "--\n" "\n" "Return the identity of an object.\n" "\n" "This is guaranteed to be unique among simultaneously existing objects.\n" "(CPython uses the object\'s memory address.)"); #define BUILTIN_ID_METHODDEF \ {"id", (PyCFunction)builtin_id, METH_O, builtin_id__doc__}, PyDoc_STRVAR(builtin_setattr__doc__, "setattr($module, obj, name, value, /)\n" "--\n" "\n" "Sets the named attribute on the given object to the specified value.\n" "\n" "setattr(x, \'y\', v) is equivalent to ``x.y = v\'\'"); #define BUILTIN_SETATTR_METHODDEF \ {"setattr", (PyCFunction)builtin_setattr, METH_FASTCALL, builtin_setattr__doc__}, static PyObject * builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name, PyObject *value); static PyObject * builtin_setattr(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *obj; PyObject *name; PyObject *value; if (!_PyArg_UnpackStack(args, nargs, "setattr", 3, 3, &obj, &name, &value)) { goto exit; } return_value = builtin_setattr_impl(module, obj, name, value); exit: return return_value; } PyDoc_STRVAR(builtin_delattr__doc__, "delattr($module, obj, name, /)\n" "--\n" "\n" "Deletes the named attribute from the given object.\n" "\n" "delattr(x, \'y\') is equivalent to ``del x.y\'\'"); #define BUILTIN_DELATTR_METHODDEF \ {"delattr", (PyCFunction)builtin_delattr, METH_FASTCALL, builtin_delattr__doc__}, static PyObject * builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name); static PyObject * builtin_delattr(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *obj; PyObject *name; if (!_PyArg_UnpackStack(args, nargs, "delattr", 2, 2, &obj, &name)) { goto exit; } return_value = builtin_delattr_impl(module, obj, name); exit: return return_value; } PyDoc_STRVAR(builtin_hash__doc__, "hash($module, obj, /)\n" "--\n" "\n" "Return the hash value for the given object.\n" "\n" "Two objects that compare equal must also have the same hash value, but the\n" "reverse is not necessarily true."); #define BUILTIN_HASH_METHODDEF \ {"hash", (PyCFunction)builtin_hash, METH_O, builtin_hash__doc__}, PyDoc_STRVAR(builtin_hex__doc__, "hex($module, number, /)\n" "--\n" "\n" "Return the hexadecimal representation of an integer.\n" "\n" " >>> hex(12648430)\n" " \'0xc0ffee\'"); #define BUILTIN_HEX_METHODDEF \ {"hex", (PyCFunction)builtin_hex, METH_O, builtin_hex__doc__}, PyDoc_STRVAR(builtin_len__doc__, "len($module, obj, /)\n" "--\n" "\n" "Return the number of items in a container."); #define BUILTIN_LEN_METHODDEF \ {"len", (PyCFunction)builtin_len, METH_O, builtin_len__doc__}, PyDoc_STRVAR(builtin_locals__doc__, "locals($module, /)\n" "--\n" "\n" "Return a dictionary containing the current scope\'s local variables.\n" "\n" "NOTE: Whether or not updates to this dictionary will affect name lookups in\n" "the local scope and vice-versa is *implementation dependent* and not\n" "covered by any backwards compatibility guarantees."); #define BUILTIN_LOCALS_METHODDEF \ {"locals", (PyCFunction)builtin_locals, METH_NOARGS, builtin_locals__doc__}, static PyObject * builtin_locals_impl(PyObject *module); static PyObject * builtin_locals(PyObject *module, PyObject *Py_UNUSED(ignored)) { return builtin_locals_impl(module); } PyDoc_STRVAR(builtin_oct__doc__, "oct($module, number, /)\n" "--\n" "\n" "Return the octal representation of an integer.\n" "\n" " >>> oct(342391)\n" " \'0o1234567\'"); #define BUILTIN_OCT_METHODDEF \ {"oct", (PyCFunction)builtin_oct, METH_O, builtin_oct__doc__}, PyDoc_STRVAR(builtin_ord__doc__, "ord($module, c, /)\n" "--\n" "\n" "Return the Unicode code point for a one-character string."); #define BUILTIN_ORD_METHODDEF \ {"ord", (PyCFunction)builtin_ord, METH_O, builtin_ord__doc__}, PyDoc_STRVAR(builtin_pow__doc__, "pow($module, x, y, z=None, /)\n" "--\n" "\n" "Equivalent to x**y (with two arguments) or x**y % z (with three arguments)\n" "\n" "Some types, such as ints, are able to use a more efficient algorithm when\n" "invoked using the three argument form."); #define BUILTIN_POW_METHODDEF \ {"pow", (PyCFunction)builtin_pow, METH_FASTCALL, builtin_pow__doc__}, static PyObject * builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z); static PyObject * builtin_pow(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *x; PyObject *y; PyObject *z = Py_None; if (!_PyArg_UnpackStack(args, nargs, "pow", 2, 3, &x, &y, &z)) { goto exit; } return_value = builtin_pow_impl(module, x, y, z); exit: return return_value; } PyDoc_STRVAR(builtin_input__doc__, "input($module, prompt=None, /)\n" "--\n" "\n" "Read a string from standard input. The trailing newline is stripped.\n" "\n" "The prompt string, if given, is printed to standard output without a\n" "trailing newline before reading input.\n" "\n" "If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.\n" "On *nix systems, readline is used if available."); #define BUILTIN_INPUT_METHODDEF \ {"input", (PyCFunction)builtin_input, METH_FASTCALL, builtin_input__doc__}, static PyObject * builtin_input_impl(PyObject *module, PyObject *prompt); static PyObject * builtin_input(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *prompt = NULL; if (!_PyArg_UnpackStack(args, nargs, "input", 0, 1, &prompt)) { goto exit; } return_value = builtin_input_impl(module, prompt); exit: return return_value; } PyDoc_STRVAR(builtin_repr__doc__, "repr($module, obj, /)\n" "--\n" "\n" "Return the canonical string representation of the object.\n" "\n" "For many object types, including most builtins, eval(repr(obj)) == obj."); #define BUILTIN_REPR_METHODDEF \ {"repr", (PyCFunction)builtin_repr, METH_O, builtin_repr__doc__}, PyDoc_STRVAR(builtin_sum__doc__, "sum($module, iterable, start=0, /)\n" "--\n" "\n" "Return the sum of a \'start\' value (default: 0) plus an iterable of numbers\n" "\n" "When the iterable is empty, return the start value.\n" "This function is intended specifically for use with numeric values and may\n" "reject non-numeric types."); #define BUILTIN_SUM_METHODDEF \ {"sum", (PyCFunction)builtin_sum, METH_FASTCALL, builtin_sum__doc__}, static PyObject * builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start); static PyObject * builtin_sum(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *iterable; PyObject *start = NULL; if (!_PyArg_UnpackStack(args, nargs, "sum", 1, 2, &iterable, &start)) { goto exit; } return_value = builtin_sum_impl(module, iterable, start); exit: return return_value; } PyDoc_STRVAR(builtin_isinstance__doc__, "isinstance($module, obj, class_or_tuple, /)\n" "--\n" "\n" "Return whether an object is an instance of a class or of a subclass thereof.\n" "\n" "A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to\n" "check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)\n" "or ...`` etc."); #define BUILTIN_ISINSTANCE_METHODDEF \ {"isinstance", (PyCFunction)builtin_isinstance, METH_FASTCALL, builtin_isinstance__doc__}, static PyObject * builtin_isinstance_impl(PyObject *module, PyObject *obj, PyObject *class_or_tuple); static PyObject * builtin_isinstance(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *obj; PyObject *class_or_tuple; if (!_PyArg_UnpackStack(args, nargs, "isinstance", 2, 2, &obj, &class_or_tuple)) { goto exit; } return_value = builtin_isinstance_impl(module, obj, class_or_tuple); exit: return return_value; } PyDoc_STRVAR(builtin_issubclass__doc__, "issubclass($module, cls, class_or_tuple, /)\n" "--\n" "\n" "Return whether \'cls\' is a derived from another class or is the same class.\n" "\n" "A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to\n" "check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)\n" "or ...`` etc."); #define BUILTIN_ISSUBCLASS_METHODDEF \ {"issubclass", (PyCFunction)builtin_issubclass, METH_FASTCALL, builtin_issubclass__doc__}, static PyObject * builtin_issubclass_impl(PyObject *module, PyObject *cls, PyObject *class_or_tuple); static PyObject * builtin_issubclass(PyObject *module, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *cls; PyObject *class_or_tuple; if (!_PyArg_UnpackStack(args, nargs, "issubclass", 2, 2, &cls, &class_or_tuple)) { goto exit; } return_value = builtin_issubclass_impl(module, cls, class_or_tuple); exit: return return_value; } /*[clinic end generated code: output=09752daa8cdd6ec7 input=a9049054013a1b77]*/
19,284
681
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/dl_nt.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ /* Entry point for the Windows NT DLL. About the only reason for having this, is so initall() can automatically be called, removing that burden (and possible source of frustration if forgotten) from the programmer. */ #include "third_party/python/Include/Python.h" #ifdef Py_ENABLE_SHARED #ifdef MS_DLL_ID // The string is available at build, so fill the buffer immediately char dllVersionBuffer[16] = MS_DLL_ID; #else char dllVersionBuffer[16] = ""; // a private buffer #endif // Python Globals HMODULE PyWin_DLLhModule = NULL; const char *PyWin_DLLVersionString = dllVersionBuffer; #if HAVE_SXS // Windows "Activation Context" work. // Our .pyd extension modules are generally built without a manifest (ie, // those included with Python and those built with a default distutils. // This requires we perform some "activation context" magic when loading our // extensions. In summary: // * As our DLL loads we save the context being used. // * Before loading our extensions we re-activate our saved context. // * After extension load is complete we restore the old context. // As an added complication, this magic only works on XP or later - we simply // use the existence (or not) of the relevant function pointers from kernel32. // See bug 4566 (http://python.org/sf/4566) for more details. // In Visual Studio 2010, side by side assemblies are no longer used by // default. typedef BOOL (WINAPI * PFN_GETCURRENTACTCTX)(HANDLE *); typedef BOOL (WINAPI * PFN_ACTIVATEACTCTX)(HANDLE, ULONG_PTR *); typedef BOOL (WINAPI * PFN_DEACTIVATEACTCTX)(DWORD, ULONG_PTR); typedef BOOL (WINAPI * PFN_ADDREFACTCTX)(HANDLE); typedef BOOL (WINAPI * PFN_RELEASEACTCTX)(HANDLE); // locals and function pointers for this activation context magic. static HANDLE PyWin_DLLhActivationContext = NULL; // one day it might be public static PFN_GETCURRENTACTCTX pfnGetCurrentActCtx = NULL; static PFN_ACTIVATEACTCTX pfnActivateActCtx = NULL; static PFN_DEACTIVATEACTCTX pfnDeactivateActCtx = NULL; static PFN_ADDREFACTCTX pfnAddRefActCtx = NULL; static PFN_RELEASEACTCTX pfnReleaseActCtx = NULL; void _LoadActCtxPointers() { HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); if (hKernel32) pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. if (pfnGetCurrentActCtx) { pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); } } ULONG_PTR _Py_ActivateActCtx() { ULONG_PTR ret = 0; if (PyWin_DLLhActivationContext && pfnActivateActCtx) if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); ret = 0; // no promise the failing function didn't change it! } return ret; } void _Py_DeactivateActCtx(ULONG_PTR cookie) { if (cookie && pfnDeactivateActCtx) if (!(*pfnDeactivateActCtx)(0, cookie)) OutputDebugString("Python failed to de-activate the activation context\n"); } #endif /* HAVE_SXS */ BOOL WINAPI DllMain (HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: PyWin_DLLhModule = hInst; #ifndef MS_DLL_ID // If we have MS_DLL_ID, we don't need to load the string. // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); #endif #if HAVE_SXS // and capture our activation context for use when loading extensions. _LoadActCtxPointers(); if (pfnGetCurrentActCtx && pfnAddRefActCtx) if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) OutputDebugString("Python failed to load the default activation context\n"); #endif break; case DLL_PROCESS_DETACH: #if HAVE_SXS if (pfnReleaseActCtx) (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); #endif break; } return TRUE; } #endif /* Py_ENABLE_SHARED */
5,530
130
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/testpy.py
import sys # This is a test module for Python. It looks in the standard # places for various *.py files. If these are moved, you must # change this module too. try: import os except: print("""Could not import the standard "os" module. Please check your PYTHONPATH environment variable.""") sys.exit(1) try: import symbol except: print("""Could not import the standard "symbol" module. If this is a PC, you should add the dos_8x3 directory to your PYTHONPATH.""") sys.exit(1) for dir in sys.path: file = os.path.join(dir, "os.py") if os.path.isfile(file): test = os.path.join(dir, "test") if os.path.isdir(test): # Add the "test" directory to PYTHONPATH. sys.path = sys.path + [test] import libregrtest # Standard Python tester. libregrtest.main()
831
31
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/frozen_dllmain.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* FreezeDLLMain.cpp This is a DLLMain suitable for frozen applications/DLLs on a Windows platform. The general problem is that many Python extension modules may define DLL main functions, but when statically linked together to form a frozen application, this DLLMain symbol exists multiple times. The solution is: * Each module checks for a frozen build, and if so, defines its DLLMain function as "__declspec(dllexport) DllMain%module%" (eg, DllMainpythoncom, or DllMainpywintypes) * The frozen .EXE/.DLL links against this module, which provides the single DllMain. * This DllMain attempts to locate and call the DllMain for each of the extension modules. * This code also has hooks to "simulate" DllMain when used from a frozen .EXE. At this stage, there is a static table of "possibly embedded modules". This should change to something better, but it will work OK for now. Note that this scheme does not handle dependencies in the order of DllMain calls - except it does call pywintypes first :-) As an example of how an extension module with a DllMain should be changed, here is a snippet from the pythoncom extension module. // end of example code from pythoncom's DllMain.cpp #ifndef BUILD_FREEZE #define DLLMAIN DllMain #define DLLMAIN_DECL #else #define DLLMAIN DllMainpythoncom #define DLLMAIN_DECL __declspec(dllexport) #endif extern "C" DLLMAIN_DECL BOOL WINAPI DLLMAIN(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) // end of example code from pythoncom's DllMain.cpp ***************************************************************************/ static char *possibleModules[] = { "pywintypes", "pythoncom", "win32ui", NULL, }; BOOL CallModuleDllMain(char *modName, DWORD dwReason); /* Called by a frozen .EXE only, so that built-in extension modules are initialized correctly */ void PyWinFreeze_ExeInit(void) { char **modName; for (modName = possibleModules; *modName; *modName++) { /* printf("Initialising '%s'\n", *modName); */ CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); } } /* Called by a frozen .EXE only, so that built-in extension modules are cleaned up */ void PyWinFreeze_ExeTerm(void) { // Must go backwards char **modName; for (modName = possibleModules + Py_ARRAY_LENGTH(possibleModules) - 2; modName >= possibleModules; *modName--) { /* printf("Terminating '%s'\n", *modName);*/ CallModuleDllMain(*modName, DLL_PROCESS_DETACH); } } BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { BOOL ret = TRUE; switch (dwReason) { case DLL_PROCESS_ATTACH: { char **modName; for (modName = possibleModules; *modName; *modName++) { BOOL ok = CallModuleDllMain(*modName, dwReason); if (!ok) ret = FALSE; } break; } case DLL_PROCESS_DETACH: { // Must go backwards char **modName; for (modName = possibleModules + Py_ARRAY_LENGTH(possibleModules) - 2; modName >= possibleModules; *modName--) CallModuleDllMain(*modName, DLL_PROCESS_DETACH); break; } } return ret; } BOOL CallModuleDllMain(char *modName, DWORD dwReason) { BOOL(WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); char funcName[255]; HMODULE hmod = GetModuleHandleW(NULL); strcpy(funcName, "_DllMain"); strcat(funcName, modName); strcat(funcName, "@12"); // stdcall convention. pfndllmain = (BOOL(WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); if (pfndllmain == NULL) { /* No function by that name exported - then that module does not appear in our frozen program - return OK */ return TRUE; } return (*pfndllmain)(hmod, dwReason, NULL); }
4,583
131
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/getpathp.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "windows.h" /* clang-format off */ /* Return the initial module search path. */ /* Used by DOS, Windows 3.1, Windows 95/98, Windows NT. */ /* ---------------------------------------------------------------- PATH RULES FOR WINDOWS: This describes how sys.path is formed on Windows. It describes the functionality, not the implementation (ie, the order in which these are actually fetched is different). The presence of a python._pth or pythonXY._pth file alongside the program overrides these rules - see below. * Python always adds an empty entry at the start, which corresponds to the current directory. * If the PYTHONPATH env. var. exists, its entries are added next. * We look in the registry for "application paths" - that is, sub-keys under the main PythonPath registry key. These are added next (the order of sub-key processing is undefined). HKEY_CURRENT_USER is searched and added first. HKEY_LOCAL_MACHINE is searched and added next. (Note that all known installers only use HKLM, so HKCU is typically empty) * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate one of our "landmarks" and deduce our home. - If we DO have a Python Home: The relevant sub-directories (Lib, DLLs, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, have not had a PYTHONPATH specified, and can't locate any Registry entries (ie, we have _nothing_ we can assume is a good path), a default path with relative entries is used (eg. .\Lib;.\DLLs, etc) If a '._pth' file exists adjacent to the executable with the same base name (e.g. python._pth adjacent to python.exe) or adjacent to the shared library (e.g. python36._pth adjacent to python36.dll), it is used in preference to the above process. The shared library file takes precedence over the executable. The path file must contain a list of paths to add to sys.path, one per line. Each path is relative to the directory containing the file. Blank lines and comments beginning with '#' are permitted. In the presence of this ._pth file, no other paths are added to the search path, the registry finder is not enabled, site.py is not imported and isolated mode is enabled. The site package can be enabled by including a line reading "import site"; no other imports are recognized. Any invalid entry (other than directories that do not exist) will result in immediate termination of the program. The end result of all this is: * When running python.exe, or any other .exe in the main Python directory (either an installed version, or directly from the PCbuild directory), the core path is deduced, and the core paths in the registry are ignored. Other "application paths" in the registry are always read. * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from the registry is used. Other "application paths" in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen exe, some very strange installation setup) you get a path with some default, but relative, paths. * An embedding application can use Py_SetPath() to override all of these automatic path computations. * An install of Python can fully specify the contents of sys.path using either a 'EXENAME._pth' or 'DLLNAME._pth' file, optionally including "import site" to enable the site module. ---------------------------------------------------------------- */ #ifndef MS_WINDOWS #error getpathp.c should only be built on Windows #endif /* Search in some common locations for the associated Python libraries. * * Py_GetPath() tries to return a sensible Python module search path. * * The approach is an adaptation for Windows of the strategy used in * ../Modules/getpath.c; it uses the Windows Registry as one of its * information sources. * * Py_SetPath() can be used to override this mechanism. Call Py_SetPath * with a semicolon separated path prior to calling Py_Initialize. */ #ifndef LANDMARK #define LANDMARK L"lib\\os.py" #endif static wchar_t prefix[MAXPATHLEN + 1]; static wchar_t progpath[MAXPATHLEN + 1]; static wchar_t *module_search_path = NULL; static int is_sep(wchar_t ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP return ch == SEP || ch == ALTSEP; #else return ch == SEP; #endif } /* assumes 'dir' null terminated in bounds. Never writes beyond existing terminator. */ static void reduce(wchar_t *dir) { size_t i = wcsnlen_s(dir, MAXPATHLEN + 1); if (i >= MAXPATHLEN + 1) Py_FatalError("buffer overflow in getpathp.c's reduce()"); while (i > 0 && !is_sep(dir[i])) --i; dir[i] = '\0'; } static int change_ext(wchar_t *dest, const wchar_t *src, const wchar_t *ext) { if (src && src != dest) { size_t src_len = wcsnlen_s(src, MAXPATHLEN + 1); size_t i = src_len; if (i >= MAXPATHLEN + 1) { Py_FatalError("buffer overflow in getpathp.c's reduce()"); } while (i > 0 && src[i] != '.' && !is_sep(src[i])) --i; if (i == 0) { dest[0] = '\0'; return -1; } if (is_sep(src[i])) { i = src_len; } if (wcsncpy_s(dest, MAXPATHLEN + 1, src, i)) { dest[0] = '\0'; return -1; } } else { wchar_t *s = wcsrchr(dest, L'.'); if (s) { s[0] = '\0'; } } if (wcscat_s(dest, MAXPATHLEN + 1, ext)) { dest[0] = '\0'; return -1; } return 0; } static int exists(wchar_t *filename) { return GetFileAttributesW(filename) != 0xFFFFFFFF; } /* Assumes 'filename' MAXPATHLEN+1 bytes long - may extend 'filename' by one character. */ static int ismodule(wchar_t *filename, int update_filename) /* Is module -- check for .pyc too */ { size_t n; if (exists(filename)) return 1; /* Check for the compiled version of prefix. */ n = wcsnlen_s(filename, MAXPATHLEN + 1); if (n < MAXPATHLEN) { int exist = 0; filename[n] = L'c'; filename[n + 1] = L'\0'; exist = exists(filename); if (!update_filename) filename[n] = L'\0'; return exist; } return 0; } /* Add a path component, by appending stuff to buffer. buffer must have at least MAXPATHLEN + 1 bytes allocated, and contain a NUL-terminated string with no more than MAXPATHLEN characters (not counting the trailing NUL). It's a fatal error if it contains a string longer than that (callers must be careful!). If these requirements are met, it's guaranteed that buffer will still be a NUL-terminated string with no more than MAXPATHLEN characters at exit. If stuff is too long, only as much of stuff as fits will be appended. */ static int _PathCchCombineEx_Initialized = 0; typedef HRESULT(__stdcall *PPathCchCombineEx)(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFlags); static PPathCchCombineEx _PathCchCombineEx; static void join(wchar_t *buffer, const wchar_t *stuff) { if (_PathCchCombineEx_Initialized == 0) { HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); if (pathapi) _PathCchCombineEx = (PPathCchCombineEx)GetProcAddress(pathapi, "PathCchCombineEx"); else _PathCchCombineEx = NULL; _PathCchCombineEx_Initialized = 1; } if (_PathCchCombineEx) { if (FAILED(_PathCchCombineEx(buffer, MAXPATHLEN + 1, buffer, stuff, 0))) Py_FatalError("buffer overflow in getpathp.c's join()"); } else { if (!PathCombineW(buffer, buffer, stuff)) Py_FatalError("buffer overflow in getpathp.c's join()"); } } static int _PathCchCanonicalizeEx_Initialized = 0; typedef HRESULT(__stdcall *PPathCchCanonicalizeEx)(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn, unsigned long dwFlags); static PPathCchCanonicalizeEx _PathCchCanonicalizeEx; static void canonicalize(wchar_t *buffer, const wchar_t *path) { if (_PathCchCanonicalizeEx_Initialized == 0) { HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); if (pathapi) { _PathCchCanonicalizeEx = (PPathCchCanonicalizeEx)GetProcAddress( pathapi, "PathCchCanonicalizeEx"); } else { _PathCchCanonicalizeEx = NULL; } _PathCchCanonicalizeEx_Initialized = 1; } if (_PathCchCanonicalizeEx) { if (FAILED(_PathCchCanonicalizeEx(buffer, MAXPATHLEN + 1, path, 0))) { Py_FatalError("buffer overflow in getpathp.c's canonicalize()"); } } else { if (!PathCanonicalizeW(buffer, path)) { Py_FatalError("buffer overflow in getpathp.c's canonicalize()"); } } } /* gotlandmark only called by search_for_prefix, which ensures 'prefix' is null terminated in bounds. join() ensures 'landmark' can not overflow prefix if too long. */ static int gotlandmark(const wchar_t *landmark) { int ok; Py_ssize_t n = wcsnlen_s(prefix, MAXPATHLEN); join(prefix, landmark); ok = ismodule(prefix, FALSE); prefix[n] = '\0'; return ok; } /* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. assumption provided by only caller, calculate_path() */ static int search_for_prefix(wchar_t *argv0_path, const wchar_t *landmark) { /* Search from argv0_path, until landmark is found */ wcscpy_s(prefix, MAXPATHLEN + 1, argv0_path); do { if (gotlandmark(landmark)) return 1; reduce(prefix); } while (prefix[0]); return 0; } static int get_dllpath(wchar_t *dllpath) { #ifdef Py_ENABLE_SHARED extern HANDLE PyWin_DLLhModule; if (PyWin_DLLhModule && GetModuleFileNameW(PyWin_DLLhModule, dllpath, MAXPATHLEN)) { return 0; } #endif return -1; } #ifdef Py_ENABLE_SHARED /* a string loaded from the DLL at startup.*/ extern const char *PyWin_DLLVersionString; /* Load a PYTHONPATH value from the registry. Load from either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER. Works in both Unicode and 8bit environments. Only uses the Ex family of functions so it also works with Windows CE. Returns NULL, or a pointer that should be freed. XXX - this code is pretty strange, as it used to also work on Win16, where the buffer sizes werent available in advance. It could be simplied now Win16/Win32s is dead! */ static wchar_t *getpythonregpath(HKEY keyBase, int skipcore) { HKEY newKey = 0; DWORD dataSize = 0; DWORD numKeys = 0; LONG rc; wchar_t *retval = NULL; WCHAR *dataBuf = NULL; static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; static const WCHAR keySuffix[] = L"\\PythonPath"; size_t versionLen, keyBufLen; DWORD index; WCHAR *keyBuf = NULL; WCHAR *keyBufPtr; WCHAR **ppPaths = NULL; /* Tried to use sysget("winver") but here is too early :-( */ versionLen = strlen(PyWin_DLLVersionString); /* Space for all the chars, plus one \0 */ keyBufLen = sizeof(keyPrefix) + sizeof(WCHAR) * (versionLen - 1) + sizeof(keySuffix); keyBuf = keyBufPtr = PyMem_RawMalloc(keyBufLen); if (keyBuf == NULL) goto done; memcpy_s(keyBufPtr, keyBufLen, keyPrefix, sizeof(keyPrefix) - sizeof(WCHAR)); keyBufPtr += Py_ARRAY_LENGTH(keyPrefix) - 1; mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); keyBufPtr += versionLen; /* NULL comes with this one! */ memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); /* Open the root Python key */ rc = RegOpenKeyExW(keyBase, keyBuf, /* subkey */ 0, /* reserved */ KEY_READ, &newKey); if (rc != ERROR_SUCCESS) goto done; /* Find out how big our core buffer is, and how many subkeys we have */ rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, NULL, NULL, &dataSize, NULL, NULL); if (rc != ERROR_SUCCESS) goto done; if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ /* Allocate a temp array of char buffers, so we only need to loop reading the registry once */ ppPaths = PyMem_RawMalloc(sizeof(WCHAR *) * numKeys); if (ppPaths == NULL) goto done; bzero(ppPaths, sizeof(WCHAR *) * numKeys); /* Loop over all subkeys, allocating a temp sub-buffer. */ for (index = 0; index < numKeys; index++) { WCHAR keyBuf[MAX_PATH + 1]; HKEY subKey = 0; DWORD reqdSize = MAX_PATH + 1; /* Get the sub-key name */ DWORD rc = RegEnumKeyExW(newKey, index, keyBuf, &reqdSize, NULL, NULL, NULL, NULL); if (rc != ERROR_SUCCESS) goto done; /* Open the sub-key */ rc = RegOpenKeyExW(newKey, keyBuf, /* subkey */ 0, /* reserved */ KEY_READ, &subKey); if (rc != ERROR_SUCCESS) goto done; /* Find the value of the buffer size, malloc, then read it */ RegQueryValueExW(subKey, NULL, 0, NULL, NULL, &reqdSize); if (reqdSize) { ppPaths[index] = PyMem_RawMalloc(reqdSize); if (ppPaths[index]) { RegQueryValueExW(subKey, NULL, 0, NULL, (LPBYTE)ppPaths[index], &reqdSize); dataSize += reqdSize + 1; /* 1 for the ";" */ } } RegCloseKey(subKey); } /* return null if no path to return */ if (dataSize == 0) goto done; /* original datasize from RegQueryInfo doesn't include the \0 */ dataBuf = PyMem_RawMalloc((dataSize + 1) * sizeof(WCHAR)); if (dataBuf) { WCHAR *szCur = dataBuf; /* Copy our collected strings */ for (index = 0; index < numKeys; index++) { if (index > 0) { *(szCur++) = L';'; dataSize--; } if (ppPaths[index]) { Py_ssize_t len = wcslen(ppPaths[index]); wcsncpy(szCur, ppPaths[index], len); szCur += len; assert(dataSize > (DWORD)len); dataSize -= (DWORD)len; } } if (skipcore) *szCur = '\0'; else { /* If we have no values, we dont need a ';' */ if (numKeys) { *(szCur++) = L';'; dataSize--; } /* Now append the core path entries - this will include the NULL */ rc = RegQueryValueExW(newKey, NULL, 0, NULL, (LPBYTE)szCur, &dataSize); if (rc != ERROR_SUCCESS) { PyMem_RawFree(dataBuf); goto done; } } /* And set the result - caller must free */ retval = dataBuf; } done: /* Loop freeing my temp buffers */ if (ppPaths) { for (index = 0; index < numKeys; index++) PyMem_RawFree(ppPaths[index]); PyMem_RawFree(ppPaths); } if (newKey) RegCloseKey(newKey); PyMem_RawFree(keyBuf); return retval; } #endif /* Py_ENABLE_SHARED */ static void get_progpath(void) { extern wchar_t *Py_GetProgramName(void); wchar_t modulepath[MAXPATHLEN]; wchar_t *path = _wgetenv(L"PATH"); wchar_t *prog = Py_GetProgramName(); if (GetModuleFileNameW(NULL, modulepath, MAXPATHLEN)) { canonicalize(progpath, modulepath); return; } if (prog == NULL || *prog == '\0') prog = L"python"; /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no * other way to find a directory to start the search from. If * $PATH isn't exported, you lose. */ #ifdef ALTSEP if (wcschr(prog, SEP) || wcschr(prog, ALTSEP)) #else if (wcschr(prog, SEP)) #endif wcsncpy(progpath, prog, MAXPATHLEN); else if (path) { while (1) { wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; /* ensure we can't overwrite buffer */ len = min(MAXPATHLEN, len); wcsncpy(progpath, path, len); *(progpath + len) = '\0'; } else wcsncpy(progpath, path, MAXPATHLEN); /* join() is safe for MAXPATHLEN+1 size buffer */ join(progpath, prog); if (exists(progpath)) break; if (!delim) { progpath[0] = '\0'; break; } path = delim + 1; } } else progpath[0] = '\0'; } static int find_env_config_value(FILE *env_file, const wchar_t *key, wchar_t *value) { int result = 0; /* meaning not found */ char buffer[MAXPATHLEN * 2 + 1]; /* allow extra for key, '=', etc. */ fseek(env_file, 0, SEEK_SET); while (!feof(env_file)) { char *p = fgets(buffer, MAXPATHLEN * 2, env_file); wchar_t tmpbuffer[MAXPATHLEN * 2 + 1]; PyObject *decoded; size_t n; if (p == NULL) break; n = strlen(p); if (p[n - 1] != '\n') { /* line has overflowed - bail */ break; } if (p[0] == '#') /* Comment - skip */ continue; decoded = PyUnicode_DecodeUTF8(buffer, n, "surrogateescape"); if (decoded != NULL) { Py_ssize_t k; k = PyUnicode_AsWideChar(decoded, tmpbuffer, MAXPATHLEN * 2); Py_DECREF(decoded); if (k >= 0) { wchar_t *context = NULL; wchar_t *tok = wcstok_s(tmpbuffer, L" \t\r\n", &context); if ((tok != NULL) && !wcscmp(tok, key)) { tok = wcstok_s(NULL, L" \t", &context); if ((tok != NULL) && !wcscmp(tok, L"=")) { tok = wcstok_s(NULL, L"\r\n", &context); if (tok != NULL) { wcsncpy(value, tok, MAXPATHLEN); result = 1; break; } } } } } } return result; } static int read_pth_file(const wchar_t *path, wchar_t *prefix, int *isolated, int *nosite) { FILE *sp_file = _Py_wfopen(path, L"r"); if (sp_file == NULL) return -1; wcscpy_s(prefix, MAXPATHLEN + 1, path); reduce(prefix); *isolated = 1; *nosite = 1; size_t bufsiz = MAXPATHLEN; size_t prefixlen = wcslen(prefix); wchar_t *buf = (wchar_t *)PyMem_RawMalloc(bufsiz * sizeof(wchar_t)); if (buf == NULL) { goto error; } buf[0] = '\0'; while (!feof(sp_file)) { char line[MAXPATHLEN + 1]; char *p = fgets(line, MAXPATHLEN + 1, sp_file); if (!p) break; if (*p == '\0' || *p == '\r' || *p == '\n' || *p == '#') continue; while (*++p) { if (*p == '\r' || *p == '\n') { *p = '\0'; break; } } if (strcmp(line, "import site") == 0) { *nosite = 0; continue; } else if (strncmp(line, "import ", 7) == 0) { Py_FatalError("only 'import site' is supported in ._pth file"); } DWORD wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0); wchar_t *wline = (wchar_t *)PyMem_RawMalloc((wn + 1) * sizeof(wchar_t)); if (wline == NULL) { goto error; } wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, wline, wn + 1); wline[wn] = '\0'; size_t usedsiz = wcslen(buf); while (usedsiz + wn + prefixlen + 4 > bufsiz) { bufsiz += MAXPATHLEN; wchar_t *tmp = (wchar_t *)PyMem_RawRealloc(buf, (bufsiz + 1) * sizeof(wchar_t)); if (tmp == NULL) { PyMem_RawFree(wline); goto error; } buf = tmp; } if (usedsiz) { wcscat_s(buf, bufsiz, L";"); usedsiz += 1; } errno_t result; _Py_BEGIN_SUPPRESS_IPH result = wcscat_s(buf, bufsiz, prefix); _Py_END_SUPPRESS_IPH if (result == EINVAL) { Py_FatalError("invalid argument during ._pth processing"); } else if (result == ERANGE) { Py_FatalError("buffer overflow during ._pth processing"); } wchar_t *b = &buf[usedsiz]; join(b, wline); PyMem_RawFree(wline); } module_search_path = buf; fclose(sp_file); return 0; error: PyMem_RawFree(buf); fclose(sp_file); return -1; } static void calculate_path(void) { wchar_t argv0_path[MAXPATHLEN + 1]; wchar_t *buf; size_t bufsz; wchar_t *pythonhome = Py_GetPythonHome(); wchar_t *envpath = NULL; int skiphome, skipdefault; wchar_t *machinepath = NULL; wchar_t *userpath = NULL; wchar_t zip_path[MAXPATHLEN + 1]; if (!Py_IgnoreEnvironmentFlag) { envpath = _wgetenv(L"PYTHONPATH"); } get_progpath(); /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ wcscpy_s(argv0_path, MAXPATHLEN + 1, progpath); reduce(argv0_path); /* Search for a sys.path file */ { wchar_t spbuffer[MAXPATHLEN + 1]; if ((!get_dllpath(spbuffer) && !change_ext(spbuffer, spbuffer, L"._pth") && exists(spbuffer)) || (progpath[0] && !change_ext(spbuffer, progpath, L"._pth") && exists(spbuffer))) { if (!read_pth_file(spbuffer, prefix, &Py_IsolatedFlag, &Py_NoSiteFlag)) { return; } } } /* Search for an environment configuration file, first in the executable's directory and then in the parent directory. If found, open it for use when searching for prefixes. */ { wchar_t envbuffer[MAXPATHLEN + 1]; wchar_t tmpbuffer[MAXPATHLEN + 1]; const wchar_t *env_cfg = L"pyvenv.cfg"; FILE *env_file = NULL; wcscpy_s(envbuffer, MAXPATHLEN + 1, argv0_path); join(envbuffer, env_cfg); env_file = _Py_wfopen(envbuffer, L"r"); if (env_file == NULL) { errno = 0; reduce(envbuffer); reduce(envbuffer); join(envbuffer, env_cfg); env_file = _Py_wfopen(envbuffer, L"r"); if (env_file == NULL) { errno = 0; } } if (env_file != NULL) { /* Look for a 'home' variable and set argv0_path to it, if found */ if (find_env_config_value(env_file, L"home", tmpbuffer)) { wcscpy_s(argv0_path, MAXPATHLEN + 1, tmpbuffer); } fclose(env_file); env_file = NULL; } } /* Calculate zip archive path from DLL or exe path */ if (!get_dllpath(zip_path)) { change_ext(zip_path, zip_path, L".zip"); } else { change_ext(zip_path, progpath, L".zip"); } if (pythonhome == NULL || *pythonhome == '\0') { if (zip_path[0] && exists(zip_path)) { wcscpy_s(prefix, MAXPATHLEN + 1, zip_path); reduce(prefix); pythonhome = prefix; } else if (search_for_prefix(argv0_path, LANDMARK)) pythonhome = prefix; else pythonhome = NULL; } else wcscpy_s(prefix, MAXPATHLEN + 1, pythonhome); if (envpath && *envpath == '\0') envpath = NULL; skiphome = pythonhome == NULL ? 0 : 1; #ifdef Py_ENABLE_SHARED machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); #endif /* We only use the default relative PYTHONPATH if we havent anything better to use! */ skipdefault = envpath != NULL || pythonhome != NULL || machinepath != NULL || userpath != NULL; /* We need to construct a path from the following parts. (1) the PYTHONPATH environment variable, if set; (2) for Win32, the zip archive file path; (3) for Win32, the machinepath and userpath, if set; (4) the PYTHONPATH config macro, with the leading "." of each component replaced with pythonhome, if set; (5) the directory containing the executable (argv0_path). The length calculation calculates #4 first. Extra rules: - If PYTHONHOME is set (in any way) item (3) is ignored. - If registry values are used, (4) and (5) are ignored. */ /* Calculate size of return buffer */ if (pythonhome != NULL) { wchar_t *p; bufsz = 1; for (p = PYTHONPATH; *p; p++) { if (*p == DELIM) bufsz++; /* number of DELIM plus one */ } bufsz *= wcslen(pythonhome); } else bufsz = 0; bufsz += wcslen(PYTHONPATH) + 1; bufsz += wcslen(argv0_path) + 1; if (userpath) bufsz += wcslen(userpath) + 1; if (machinepath) bufsz += wcslen(machinepath) + 1; bufsz += wcslen(zip_path) + 1; if (envpath != NULL) bufsz += wcslen(envpath) + 1; module_search_path = buf = PyMem_RawMalloc(bufsz * sizeof(wchar_t)); if (buf == NULL) { /* We can't exit, so print a warning and limp along */ fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); if (envpath) { fprintf(stderr, "Using environment $PYTHONPATH.\n"); module_search_path = envpath; } else { fprintf(stderr, "Using default static path.\n"); module_search_path = PYTHONPATH; } PyMem_RawFree(machinepath); PyMem_RawFree(userpath); return; } if (envpath) { if (wcscpy_s(buf, bufsz - (buf - module_search_path), envpath)) Py_FatalError("buffer overflow in getpathp.c's calculate_path()"); buf = wcschr(buf, L'\0'); *buf++ = DELIM; } if (zip_path[0]) { if (wcscpy_s(buf, bufsz - (buf - module_search_path), zip_path)) Py_FatalError("buffer overflow in getpathp.c's calculate_path()"); buf = wcschr(buf, L'\0'); *buf++ = DELIM; } if (userpath) { if (wcscpy_s(buf, bufsz - (buf - module_search_path), userpath)) Py_FatalError("buffer overflow in getpathp.c's calculate_path()"); buf = wcschr(buf, L'\0'); *buf++ = DELIM; PyMem_RawFree(userpath); } if (machinepath) { if (wcscpy_s(buf, bufsz - (buf - module_search_path), machinepath)) Py_FatalError("buffer overflow in getpathp.c's calculate_path()"); buf = wcschr(buf, L'\0'); *buf++ = DELIM; PyMem_RawFree(machinepath); } if (pythonhome == NULL) { if (!skipdefault) { if (wcscpy_s(buf, bufsz - (buf - module_search_path), PYTHONPATH)) Py_FatalError("buffer overflow in getpathp.c's calculate_path()"); buf = wcschr(buf, L'\0'); *buf++ = DELIM; } } else { wchar_t *p = PYTHONPATH; wchar_t *q; size_t n; for (;;) { q = wcschr(p, DELIM); if (q == NULL) n = wcslen(p); else n = q - p; if (p[0] == '.' && is_sep(p[1])) { if (wcscpy_s(buf, bufsz - (buf - module_search_path), pythonhome)) Py_FatalError("buffer overflow in getpathp.c's calculate_path()"); buf = wcschr(buf, L'\0'); p++; n--; } wcsncpy(buf, p, n); buf += n; *buf++ = DELIM; if (q == NULL) break; p = q + 1; } } if (argv0_path) { wcscpy(buf, argv0_path); buf = wcschr(buf, L'\0'); *buf++ = DELIM; } *(buf - 1) = L'\0'; /* Now to pull one last hack/trick. If sys.prefix is empty, then try and find it somewhere on the paths we calculated. We scan backwards, as our general policy is that Python core directories are at the *end* of sys.path. We assume that our "lib" directory is on the path, and that our 'prefix' directory is the parent of that. */ if (*prefix == L'\0') { wchar_t lookBuf[MAXPATHLEN + 1]; wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ while (1) { Py_ssize_t nchars; wchar_t *lookEnd = look; /* 'look' will end up one character before the start of the path in question - even if this is one character before the start of the buffer */ while (look >= module_search_path && *look != DELIM) look--; nchars = lookEnd - look; wcsncpy(lookBuf, look + 1, nchars); lookBuf[nchars] = L'\0'; /* Up one level to the parent */ reduce(lookBuf); if (search_for_prefix(lookBuf, LANDMARK)) { break; } /* If we are out of paths to search - give up */ if (look < module_search_path) break; look--; } } } void Py_SetPath(const wchar_t *path) { if (module_search_path != NULL) { PyMem_RawFree(module_search_path); module_search_path = NULL; } if (path != NULL) { extern wchar_t *Py_GetProgramName(void); wchar_t *prog = Py_GetProgramName(); wcsncpy(progpath, prog, MAXPATHLEN); prefix[0] = L'\0'; module_search_path = PyMem_RawMalloc((wcslen(path) + 1) * sizeof(wchar_t)); if (module_search_path != NULL) wcscpy(module_search_path, path); } } wchar_t *Py_GetPath(void) { if (!module_search_path) calculate_path(); return module_search_path; } wchar_t *Py_GetPrefix(void) { if (!module_search_path) calculate_path(); return prefix; } wchar_t *Py_GetExecPrefix(void) { return Py_GetPrefix(); } wchar_t *Py_GetProgramFullPath(void) { if (!module_search_path) calculate_path(); return progpath; } /* Load python3.dll before loading any extension module that might refer to it. That way, we can be sure that always the python3.dll corresponding to this python DLL is loaded, not a python3.dll that might be on the path by chance. Return whether the DLL was found. */ static int python3_checked = 0; static HANDLE hPython3; int _Py_CheckPython3() { wchar_t py3path[MAXPATHLEN + 1]; if (python3_checked) { return hPython3 != NULL; } python3_checked = 1; /* If there is a python3.dll next to the python3y.dll, use that DLL */ if (!get_dllpath(py3path)) { reduce(py3path); join(py3path, PY3_DLLNAME); hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if (hPython3 != NULL) { return 1; } } /* If we can locate python3.dll in our application dir, use that DLL */ wcscpy(py3path, Py_GetPrefix()); if (py3path[0]) { join(py3path, PY3_DLLNAME); hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if (hPython3 != NULL) { return 1; } } /* For back-compat, also search {sys.prefix}\DLLs, though that has not been a normal install layout for a while */ wcscpy(py3path, Py_GetPrefix()); if (py3path[0]) { join(py3path, L"DLLs\\" PY3_DLLNAME); hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } return hPython3 != NULL; }
30,941
955
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/launcher.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ /* * Copyright (C) 2011-2013 Vinay Sajip. * Licensed to PSF under a contributor agreement. * * Based on the work of: * * Mark Hammond (original author of Python version) * Curt Hagenlocher (job management) */ #define BUFSIZE 256 #define MSGSIZE 1024 /* Build options. */ #define SKIP_PREFIX #define SEARCH_PATH /* Error codes */ #define RC_NO_STD_HANDLES 100 #define RC_CREATE_PROCESS 101 #define RC_BAD_VIRTUAL_PATH 102 #define RC_NO_PYTHON 103 #define RC_NO_MEMORY 104 /* * SCRIPT_WRAPPER is used to choose between two variants of an executable built * from this source file. If not defined, the PEP 397 Python launcher is built; * if defined, a script launcher of the type used by setuptools is built, which * looks for a script name related to the executable name and runs that script * with the appropriate Python interpreter. * * SCRIPT_WRAPPER should be undefined in the source, and defined in a VS project * which builds the setuptools-style launcher. */ #if defined(SCRIPT_WRAPPER) #define RC_NO_SCRIPT 105 #endif /* Just for now - static definition */ static FILE * log_fp = NULL; static wchar_t * skip_whitespace(wchar_t * p) { while (*p && isspace(*p)) ++p; return p; } static void debug(wchar_t * format, ...) { va_list va; if (log_fp != NULL) { va_start(va, format); vfwprintf_s(log_fp, format, va); va_end(va); } } static void winerror(int rc, wchar_t * message, int size) { FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, rc, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), message, size, NULL); } static void error(int rc, wchar_t * format, ... ) { va_list va; wchar_t message[MSGSIZE]; wchar_t win_message[MSGSIZE]; int len; va_start(va, format); len = _vsnwprintf_s(message, MSGSIZE, _TRUNCATE, format, va); va_end(va); if (rc == 0) { /* a Windows error */ winerror(GetLastError(), win_message, MSGSIZE); if (len >= 0) { _snwprintf_s(&message[len], MSGSIZE - len, _TRUNCATE, L": %ls", win_message); } } #if !defined(_WINDOWS) fwprintf(stderr, L"%ls\n", message); #else MessageBox(NULL, message, TEXT("Python Launcher is sorry to say ..."), MB_OK); #endif exit(rc); } /* * This function is here to simplify memory management * and to treat blank values as if they are absent. */ static wchar_t * get_env(wchar_t * key) { /* This is not thread-safe, just like getenv */ static wchar_t buf[BUFSIZE]; DWORD result = GetEnvironmentVariableW(key, buf, BUFSIZE); if (result >= BUFSIZE) { /* Large environment variable. Accept some leakage */ wchar_t *buf2 = (wchar_t*)malloc(sizeof(wchar_t) * (result+1)); if (buf2 == NULL) { error(RC_NO_MEMORY, L"Could not allocate environment buffer"); } GetEnvironmentVariableW(key, buf2, result); return buf2; } if (result == 0) /* Either some error, e.g. ERROR_ENVVAR_NOT_FOUND, or an empty environment variable. */ return NULL; return buf; } #if defined(_WINDOWS) #define PYTHON_EXECUTABLE L"pythonw.exe" #else #define PYTHON_EXECUTABLE L"python.exe" #endif #define MAX_VERSION_SIZE 4 typedef struct { wchar_t version[MAX_VERSION_SIZE]; /* m.n */ int bits; /* 32 or 64 */ wchar_t executable[MAX_PATH]; } INSTALLED_PYTHON; /* * To avoid messing about with heap allocations, just assume we can allocate * statically and never have to deal with more versions than this. */ #define MAX_INSTALLED_PYTHONS 100 static INSTALLED_PYTHON installed_pythons[MAX_INSTALLED_PYTHONS]; static size_t num_installed_pythons = 0; /* * To hold SOFTWARE\Python\PythonCore\X.Y...\InstallPath * The version name can be longer than MAX_VERSION_SIZE, but will be * truncated to just X.Y for comparisons. */ #define IP_BASE_SIZE 40 #define IP_VERSION_SIZE 8 #define IP_SIZE (IP_BASE_SIZE + IP_VERSION_SIZE) #define CORE_PATH L"SOFTWARE\\Python\\PythonCore" static wchar_t * location_checks[] = { L"\\", L"\\PCBuild\\win32\\", L"\\PCBuild\\amd64\\", // To support early 32bit versions of Python that stuck the build binaries // directly in PCBuild... L"\\PCBuild\\", NULL }; static INSTALLED_PYTHON * find_existing_python(wchar_t * path) { INSTALLED_PYTHON * result = NULL; size_t i; INSTALLED_PYTHON * ip; for (i = 0, ip = installed_pythons; i < num_installed_pythons; i++, ip++) { if (_wcsicmp(path, ip->executable) == 0) { result = ip; break; } } return result; } static void locate_pythons_for_key(HKEY root, REGSAM flags) { HKEY core_root, ip_key; LSTATUS status = RegOpenKeyExW(root, CORE_PATH, 0, flags, &core_root); wchar_t message[MSGSIZE]; DWORD i; size_t n; BOOL ok; DWORD type, data_size, attrs; INSTALLED_PYTHON * ip, * pip; wchar_t ip_version[IP_VERSION_SIZE]; wchar_t ip_path[IP_SIZE]; wchar_t * check; wchar_t ** checkp; wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU"; if (status != ERROR_SUCCESS) debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n", key_name); else { ip = &installed_pythons[num_installed_pythons]; for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) { status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE); if (status != ERROR_SUCCESS) { if (status != ERROR_NO_MORE_ITEMS) { /* unexpected error */ winerror(status, message, MSGSIZE); debug(L"Can't enumerate registry key for version %ls: %ls\n", ip_version, message); } break; } else { wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version, MAX_VERSION_SIZE-1); _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE, L"%ls\\%ls\\InstallPath", CORE_PATH, ip_version); status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key); if (status != ERROR_SUCCESS) { winerror(status, message, MSGSIZE); // Note: 'message' already has a trailing \n debug(L"%ls\\%ls: %ls", key_name, ip_path, message); continue; } data_size = sizeof(ip->executable) - 1; status = RegQueryValueExW(ip_key, NULL, NULL, &type, (LPBYTE)ip->executable, &data_size); RegCloseKey(ip_key); if (status != ERROR_SUCCESS) { winerror(status, message, MSGSIZE); debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message); continue; } if (type == REG_SZ) { data_size = data_size / sizeof(wchar_t) - 1; /* for NUL */ if (ip->executable[data_size - 1] == L'\\') --data_size; /* reg value ended in a backslash */ /* ip->executable is data_size long */ for (checkp = location_checks; *checkp; ++checkp) { check = *checkp; _snwprintf_s(&ip->executable[data_size], MAX_PATH - data_size, MAX_PATH - data_size, L"%ls%ls", check, PYTHON_EXECUTABLE); attrs = GetFileAttributesW(ip->executable); if (attrs == INVALID_FILE_ATTRIBUTES) { winerror(GetLastError(), message, MSGSIZE); debug(L"locate_pythons_for_key: %ls: %ls", ip->executable, message); } else if (attrs & FILE_ATTRIBUTE_DIRECTORY) { debug(L"locate_pythons_for_key: '%ls' is a \ directory\n", ip->executable, attrs); } else if (find_existing_python(ip->executable)) { debug(L"locate_pythons_for_key: %ls: already \ found\n", ip->executable); } else { /* check the executable type. */ ok = GetBinaryTypeW(ip->executable, &attrs); if (!ok) { debug(L"Failure getting binary type: %ls\n", ip->executable); } else { if (attrs == SCS_64BIT_BINARY) ip->bits = 64; else if (attrs == SCS_32BIT_BINARY) ip->bits = 32; else ip->bits = 0; if (ip->bits == 0) { debug(L"locate_pythons_for_key: %ls: \ invalid binary type: %X\n", ip->executable, attrs); } else { if (wcschr(ip->executable, L' ') != NULL) { /* has spaces, so quote */ n = wcslen(ip->executable); memmove(&ip->executable[1], ip->executable, n * sizeof(wchar_t)); ip->executable[0] = L'\"'; ip->executable[n + 1] = L'\"'; ip->executable[n + 2] = L'\0'; } debug(L"locate_pythons_for_key: %ls \ is a %dbit executable\n", ip->executable, ip->bits); ++num_installed_pythons; pip = ip++; if (num_installed_pythons >= MAX_INSTALLED_PYTHONS) break; /* Copy over the attributes for the next */ *ip = *pip; } } } } } } } RegCloseKey(core_root); } } static int compare_pythons(const void * p1, const void * p2) { INSTALLED_PYTHON * ip1 = (INSTALLED_PYTHON *) p1; INSTALLED_PYTHON * ip2 = (INSTALLED_PYTHON *) p2; /* note reverse sorting on version */ int result = wcscmp(ip2->version, ip1->version); if (result == 0) result = ip2->bits - ip1->bits; /* 64 before 32 */ return result; } static void locate_all_pythons() { #if defined(_M_X64) // If we are a 64bit process, first hit the 32bit keys. debug(L"locating Pythons in 32bit registry\n"); locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_32KEY); locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_32KEY); #else // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys. BOOL f64 = FALSE; if (IsWow64Process(GetCurrentProcess(), &f64) && f64) { debug(L"locating Pythons in 64bit registry\n"); locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ | KEY_WOW64_64KEY); locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY); } #endif // now hit the "native" key for this process bittedness. debug(L"locating Pythons in native registry\n"); locate_pythons_for_key(HKEY_CURRENT_USER, KEY_READ); locate_pythons_for_key(HKEY_LOCAL_MACHINE, KEY_READ); qsort(installed_pythons, num_installed_pythons, sizeof(INSTALLED_PYTHON), compare_pythons); } static INSTALLED_PYTHON * find_python_by_version(wchar_t const * wanted_ver) { INSTALLED_PYTHON * result = NULL; INSTALLED_PYTHON * ip = installed_pythons; size_t i, n; size_t wlen = wcslen(wanted_ver); int bits = 0; if (wcsstr(wanted_ver, L"-32")) bits = 32; for (i = 0; i < num_installed_pythons; i++, ip++) { n = wcslen(ip->version); if (n > wlen) n = wlen; if ((wcsncmp(ip->version, wanted_ver, n) == 0) && /* bits == 0 => don't care */ ((bits == 0) || (ip->bits == bits))) { result = ip; break; } } return result; } static wchar_t * find_python_by_venv() { static wchar_t venv_python[MAX_PATH]; wchar_t *virtual_env = get_env(L"VIRTUAL_ENV"); DWORD attrs; /* Check for VIRTUAL_ENV environment variable */ if (virtual_env == NULL || virtual_env[0] == L'\0') { return NULL; } /* Check for a python executable in the venv */ debug(L"Checking for Python executable in virtual env '%ls'\n", virtual_env); _snwprintf_s(venv_python, MAX_PATH, _TRUNCATE, L"%ls\\Scripts\\%ls", virtual_env, PYTHON_EXECUTABLE); attrs = GetFileAttributesW(venv_python); if (attrs == INVALID_FILE_ATTRIBUTES) { debug(L"Python executable %ls missing from virtual env\n", venv_python); return NULL; } return venv_python; } static wchar_t appdata_ini_path[MAX_PATH]; static wchar_t launcher_ini_path[MAX_PATH]; /* * Get a value either from the environment or a configuration file. * The key passed in will either be "python", "python2" or "python3". */ static wchar_t * get_configured_value(wchar_t * key) { /* * Note: this static value is used to return a configured value * obtained either from the environment or configuration file. * This should be OK since there wouldn't be any concurrent calls. */ static wchar_t configured_value[MSGSIZE]; wchar_t * result = NULL; wchar_t * found_in = L"environment"; DWORD size; /* First, search the environment. */ _snwprintf_s(configured_value, MSGSIZE, _TRUNCATE, L"py_%ls", key); result = get_env(configured_value); if (result == NULL && appdata_ini_path[0]) { /* Not in environment: check local configuration. */ size = GetPrivateProfileStringW(L"defaults", key, NULL, configured_value, MSGSIZE, appdata_ini_path); if (size > 0) { result = configured_value; found_in = appdata_ini_path; } } if (result == NULL && launcher_ini_path[0]) { /* Not in environment or local: check global configuration. */ size = GetPrivateProfileStringW(L"defaults", key, NULL, configured_value, MSGSIZE, launcher_ini_path); if (size > 0) { result = configured_value; found_in = launcher_ini_path; } } if (result) { debug(L"found configured value '%ls=%ls' in %ls\n", key, result, found_in ? found_in : L"(unknown)"); } else { debug(L"found no configured value for '%ls'\n", key); } return result; } static INSTALLED_PYTHON * locate_python(wchar_t * wanted_ver, BOOL from_shebang) { static wchar_t config_key [] = { L"pythonX" }; static wchar_t * last_char = &config_key[sizeof(config_key) / sizeof(wchar_t) - 2]; INSTALLED_PYTHON * result = NULL; size_t n = wcslen(wanted_ver); wchar_t * configured_value; if (num_installed_pythons == 0) locate_all_pythons(); if (n == 1) { /* just major version specified */ *last_char = *wanted_ver; configured_value = get_configured_value(config_key); if (configured_value != NULL) wanted_ver = configured_value; } if (*wanted_ver) { result = find_python_by_version(wanted_ver); debug(L"search for Python version '%ls' found ", wanted_ver); if (result) { debug(L"'%ls'\n", result->executable); } else { debug(L"no interpreter\n"); } } else { *last_char = L'\0'; /* look for an overall default */ configured_value = get_configured_value(config_key); if (configured_value) result = find_python_by_version(configured_value); /* Not found a value yet - try by major version. * If we're looking for an interpreter specified in a shebang line, * we want to try Python 2 first, then Python 3 (for Unix and backward * compatibility). If we're being called interactively, assume the user * wants the latest version available, so try Python 3 first, then * Python 2. */ if (result == NULL) result = find_python_by_version(from_shebang ? L"2" : L"3"); if (result == NULL) result = find_python_by_version(from_shebang ? L"3" : L"2"); debug(L"search for default Python found "); if (result) { debug(L"version %ls at '%ls'\n", result->version, result->executable); } else { debug(L"no interpreter\n"); } } return result; } #if defined(SCRIPT_WRAPPER) /* * Check for a script located alongside the executable */ #if defined(_WINDOWS) #define SCRIPT_SUFFIX L"-script.pyw" #else #define SCRIPT_SUFFIX L"-script.py" #endif static wchar_t wrapped_script_path[MAX_PATH]; /* Locate the script being wrapped. * * This code should store the name of the wrapped script in * wrapped_script_path, or terminate the program with an error if there is no * valid wrapped script file. */ static void locate_wrapped_script() { wchar_t * p; size_t plen; DWORD attrs; plen = GetModuleFileNameW(NULL, wrapped_script_path, MAX_PATH); p = wcsrchr(wrapped_script_path, L'.'); if (p == NULL) { debug(L"GetModuleFileNameW returned value has no extension: %ls\n", wrapped_script_path); error(RC_NO_SCRIPT, L"Wrapper name '%ls' is not valid.", wrapped_script_path); } wcsncpy_s(p, MAX_PATH - (p - wrapped_script_path) + 1, SCRIPT_SUFFIX, _TRUNCATE); attrs = GetFileAttributesW(wrapped_script_path); if (attrs == INVALID_FILE_ATTRIBUTES) { debug(L"File '%ls' non-existent\n", wrapped_script_path); error(RC_NO_SCRIPT, L"Script file '%ls' is not present.", wrapped_script_path); } debug(L"Using wrapped script file '%ls'\n", wrapped_script_path); } #endif /* * Process creation code */ static BOOL safe_duplicate_handle(HANDLE in, HANDLE * pout) { BOOL ok; HANDLE process = GetCurrentProcess(); DWORD rc; *pout = NULL; ok = DuplicateHandle(process, in, process, pout, 0, TRUE, DUPLICATE_SAME_ACCESS); if (!ok) { rc = GetLastError(); if (rc == ERROR_INVALID_HANDLE) { debug(L"DuplicateHandle returned ERROR_INVALID_HANDLE\n"); ok = TRUE; } else { debug(L"DuplicateHandle returned %d\n", rc); } } return ok; } static BOOL WINAPI ctrl_c_handler(DWORD code) { return TRUE; /* We just ignore all control events. */ } static void run_child(wchar_t * cmdline) { HANDLE job; JOBOBJECT_EXTENDED_LIMIT_INFORMATION info; DWORD rc; BOOL ok; STARTUPINFOW si; PROCESS_INFORMATION pi; #if defined(_WINDOWS) // When explorer launches a Windows (GUI) application, it displays // the "app starting" (the "pointer + hourglass") cursor for a number // of seconds, or until the app does something UI-ish (eg, creating a // window, or fetching a message). As this launcher doesn't do this // directly, that cursor remains even after the child process does these // things. We avoid that by doing a simple post+get message. // See http://bugs.python.org/issue17290 and // https://bitbucket.org/vinay.sajip/pylauncher/issue/20/busy-cursor-for-a-long-time-when-running MSG msg; PostMessage(0, 0, 0, 0); GetMessage(&msg, 0, 0, 0); #endif debug(L"run_child: about to run '%ls'\n", cmdline); job = CreateJobObject(NULL, NULL); ok = QueryInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info), &rc); if (!ok || (rc != sizeof(info)) || !job) error(RC_CREATE_PROCESS, L"Job information querying failed"); info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK; ok = SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info)); if (!ok) error(RC_CREATE_PROCESS, L"Job information setting failed"); bzero(&si, sizeof(si)); si.cb = sizeof(si); ok = safe_duplicate_handle(GetStdHandle(STD_INPUT_HANDLE), &si.hStdInput); if (!ok) error(RC_NO_STD_HANDLES, L"stdin duplication failed"); ok = safe_duplicate_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si.hStdOutput); if (!ok) error(RC_NO_STD_HANDLES, L"stdout duplication failed"); ok = safe_duplicate_handle(GetStdHandle(STD_ERROR_HANDLE), &si.hStdError); if (!ok) error(RC_NO_STD_HANDLES, L"stderr duplication failed"); ok = SetConsoleCtrlHandler(ctrl_c_handler, TRUE); if (!ok) error(RC_CREATE_PROCESS, L"control handler setting failed"); si.dwFlags = STARTF_USESTDHANDLES; ok = CreateProcessW(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi); if (!ok) error(RC_CREATE_PROCESS, L"Unable to create process using '%ls'", cmdline); AssignProcessToJobObject(job, pi.hProcess); CloseHandle(pi.hThread); WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE); ok = GetExitCodeProcess(pi.hProcess, &rc); if (!ok) error(RC_CREATE_PROCESS, L"Failed to get exit code of process"); debug(L"child process exit code: %d\n", rc); exit(rc); } static void invoke_child(wchar_t * executable, wchar_t * suffix, wchar_t * cmdline) { wchar_t * child_command; size_t child_command_size; BOOL no_suffix = (suffix == NULL) || (*suffix == L'\0'); BOOL no_cmdline = (*cmdline == L'\0'); if (no_suffix && no_cmdline) run_child(executable); else { if (no_suffix) { /* add 2 for space separator + terminating NUL. */ child_command_size = wcslen(executable) + wcslen(cmdline) + 2; } else { /* add 3 for 2 space separators + terminating NUL. */ child_command_size = wcslen(executable) + wcslen(suffix) + wcslen(cmdline) + 3; } child_command = calloc(child_command_size, sizeof(wchar_t)); if (child_command == NULL) error(RC_CREATE_PROCESS, L"unable to allocate %d bytes for child command.", child_command_size); if (no_suffix) _snwprintf_s(child_command, child_command_size, child_command_size - 1, L"%ls %ls", executable, cmdline); else _snwprintf_s(child_command, child_command_size, child_command_size - 1, L"%ls %ls %ls", executable, suffix, cmdline); run_child(child_command); free(child_command); } } typedef struct { wchar_t *shebang; BOOL search; } SHEBANG; static SHEBANG builtin_virtual_paths [] = { { L"/usr/bin/env python", TRUE }, { L"/usr/bin/python", FALSE }, { L"/usr/local/bin/python", FALSE }, { L"python", FALSE }, { NULL, FALSE }, }; /* For now, a static array of commands. */ #define MAX_COMMANDS 100 typedef struct { wchar_t key[MAX_PATH]; wchar_t value[MSGSIZE]; } COMMAND; static COMMAND commands[MAX_COMMANDS]; static int num_commands = 0; #if defined(SKIP_PREFIX) static wchar_t * builtin_prefixes [] = { /* These must be in an order that the longest matches should be found, * i.e. if the prefix is "/usr/bin/env ", it should match that entry * *before* matching "/usr/bin/". */ L"/usr/bin/env ", L"/usr/bin/", L"/usr/local/bin/", NULL }; static wchar_t * skip_prefix(wchar_t * name) { wchar_t ** pp = builtin_prefixes; wchar_t * result = name; wchar_t * p; size_t n; for (; p = *pp; pp++) { n = wcslen(p); if (_wcsnicmp(p, name, n) == 0) { result += n; /* skip the prefix */ if (p[n - 1] == L' ') /* No empty strings in table, so n > 1 */ result = skip_whitespace(result); break; } } return result; } #endif #if defined(SEARCH_PATH) static COMMAND path_command; static COMMAND * find_on_path(wchar_t * name) { wchar_t * pathext; size_t varsize; wchar_t * context = NULL; wchar_t * extension; COMMAND * result = NULL; DWORD len; errno_t rc; wcscpy_s(path_command.key, MAX_PATH, name); if (wcschr(name, L'.') != NULL) { /* assume it has an extension. */ len = SearchPathW(NULL, name, NULL, MSGSIZE, path_command.value, NULL); if (len) { result = &path_command; } } else { /* No extension - search using registered extensions. */ rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT"); if (rc == 0) { extension = wcstok_s(pathext, L";", &context); while (extension) { len = SearchPathW(NULL, name, extension, MSGSIZE, path_command.value, NULL); if (len) { result = &path_command; break; } extension = wcstok_s(NULL, L";", &context); } free(pathext); } } return result; } #endif static COMMAND * find_command(wchar_t * name) { COMMAND * result = NULL; COMMAND * cp = commands; int i; for (i = 0; i < num_commands; i++, cp++) { if (_wcsicmp(cp->key, name) == 0) { result = cp; break; } } #if defined(SEARCH_PATH) if (result == NULL) result = find_on_path(name); #endif return result; } static void update_command(COMMAND * cp, wchar_t * name, wchar_t * cmdline) { wcsncpy_s(cp->key, MAX_PATH, name, _TRUNCATE); wcsncpy_s(cp->value, MSGSIZE, cmdline, _TRUNCATE); } static void add_command(wchar_t * name, wchar_t * cmdline) { if (num_commands >= MAX_COMMANDS) { debug(L"can't add %ls = '%ls': no room\n", name, cmdline); } else { COMMAND * cp = &commands[num_commands++]; update_command(cp, name, cmdline); } } static void read_config_file(wchar_t * config_path) { wchar_t keynames[MSGSIZE]; wchar_t value[MSGSIZE]; DWORD read; wchar_t * key; COMMAND * cp; wchar_t * cmdp; read = GetPrivateProfileStringW(L"commands", NULL, NULL, keynames, MSGSIZE, config_path); if (read == MSGSIZE - 1) { debug(L"read_commands: %ls: not enough space for names\n", config_path); } key = keynames; while (*key) { read = GetPrivateProfileStringW(L"commands", key, NULL, value, MSGSIZE, config_path); if (read == MSGSIZE - 1) { debug(L"read_commands: %ls: not enough space for %ls\n", config_path, key); } cmdp = skip_whitespace(value); if (*cmdp) { cp = find_command(key); if (cp == NULL) add_command(key, value); else update_command(cp, key, value); } key += wcslen(key) + 1; } } static void read_commands() { if (launcher_ini_path[0]) read_config_file(launcher_ini_path); if (appdata_ini_path[0]) read_config_file(appdata_ini_path); } static BOOL parse_shebang(wchar_t * shebang_line, int nchars, wchar_t ** command, wchar_t ** suffix, BOOL *search) { BOOL rc = FALSE; SHEBANG * vpp; size_t plen; wchar_t * p; wchar_t zapped; wchar_t * endp = shebang_line + nchars - 1; COMMAND * cp; wchar_t * skipped; *command = NULL; /* failure return */ *suffix = NULL; *search = FALSE; if ((*shebang_line++ == L'#') && (*shebang_line++ == L'!')) { shebang_line = skip_whitespace(shebang_line); if (*shebang_line) { *command = shebang_line; for (vpp = builtin_virtual_paths; vpp->shebang; ++vpp) { plen = wcslen(vpp->shebang); if (wcsncmp(shebang_line, vpp->shebang, plen) == 0) { rc = TRUE; *search = vpp->search; /* We can do this because all builtin commands contain * "python". */ *command = wcsstr(shebang_line, L"python"); break; } } if (vpp->shebang == NULL) { /* * Not found in builtins - look in customized commands. * * We can't permanently modify the shebang line in case * it's not a customized command, but we can temporarily * stick a NUL after the command while searching for it, * then put back the char we zapped. */ #if defined(SKIP_PREFIX) skipped = skip_prefix(shebang_line); #else skipped = shebang_line; #endif p = wcspbrk(skipped, L" \t\r\n"); if (p != NULL) { zapped = *p; *p = L'\0'; } cp = find_command(skipped); if (p != NULL) *p = zapped; if (cp != NULL) { *command = cp->value; if (p != NULL) *suffix = skip_whitespace(p); } } /* remove trailing whitespace */ while ((endp > shebang_line) && isspace(*endp)) --endp; if (endp > shebang_line) endp[1] = L'\0'; } } return rc; } /* #define CP_UTF8 65001 defined in winnls.h */ #define CP_UTF16LE 1200 #define CP_UTF16BE 1201 #define CP_UTF32LE 12000 #define CP_UTF32BE 12001 typedef struct { int length; char sequence[4]; UINT code_page; } BOM; /* * Strictly, we don't need to handle UTF-16 and UTF-32, since Python itself * doesn't. Never mind, one day it might - there's no harm leaving it in. */ static BOM BOMs[] = { { 3, { 0xEF, 0xBB, 0xBF }, CP_UTF8 }, /* UTF-8 - keep first */ /* Test UTF-32LE before UTF-16LE since UTF-16LE BOM is a prefix * of UTF-32LE BOM. */ { 4, { 0xFF, 0xFE, 0x00, 0x00 }, CP_UTF32LE }, /* UTF-32LE */ { 4, { 0x00, 0x00, 0xFE, 0xFF }, CP_UTF32BE }, /* UTF-32BE */ { 2, { 0xFF, 0xFE }, CP_UTF16LE }, /* UTF-16LE */ { 2, { 0xFE, 0xFF }, CP_UTF16BE }, /* UTF-16BE */ { 0 } /* sentinel */ }; static BOM * find_BOM(char * buffer) { /* * Look for a BOM in the input and return a pointer to the * corresponding structure, or NULL if not found. */ BOM * result = NULL; BOM *bom; for (bom = BOMs; bom->length; bom++) { if (strncmp(bom->sequence, buffer, bom->length) == 0) { result = bom; break; } } return result; } static char * find_terminator(char * buffer, int len, BOM *bom) { char * result = NULL; char * end = buffer + len; char * p; char c; int cp; for (p = buffer; p < end; p++) { c = *p; if (c == '\r') { result = p; break; } if (c == '\n') { result = p; break; } } if (result != NULL) { cp = bom->code_page; /* adjustments to include all bytes of the char */ /* no adjustment needed for UTF-8 or big endian */ if (cp == CP_UTF16LE) ++result; else if (cp == CP_UTF32LE) result += 3; ++result; /* point just past terminator */ } return result; } static BOOL validate_version(wchar_t * p) { BOOL result = TRUE; if (!isdigit(*p)) /* expect major version */ result = FALSE; else if (*++p) { /* more to do */ if (*p != L'.') /* major/minor separator */ result = FALSE; else { ++p; if (!isdigit(*p)) /* expect minor version */ result = FALSE; else { ++p; if (*p) { /* more to do */ if (*p != L'-') result = FALSE; else { ++p; if ((*p != '3') && (*++p != '2') && !*++p) result = FALSE; } } } } } return result; } typedef struct { unsigned short min; unsigned short max; wchar_t version[MAX_VERSION_SIZE]; } PYC_MAGIC; static PYC_MAGIC magic_values[] = { { 50823, 50823, L"2.0" }, { 60202, 60202, L"2.1" }, { 60717, 60717, L"2.2" }, { 62011, 62021, L"2.3" }, { 62041, 62061, L"2.4" }, { 62071, 62131, L"2.5" }, { 62151, 62161, L"2.6" }, { 62171, 62211, L"2.7" }, { 3000, 3131, L"3.0" }, { 3141, 3151, L"3.1" }, { 3160, 3180, L"3.2" }, { 3190, 3230, L"3.3" }, { 3250, 3310, L"3.4" }, { 3320, 3351, L"3.5" }, { 3360, 3379, L"3.6" }, { 3390, 3399, L"3.7" }, { 0 } }; static INSTALLED_PYTHON * find_by_magic(unsigned short magic) { INSTALLED_PYTHON * result = NULL; PYC_MAGIC * mp; for (mp = magic_values; mp->min; mp++) { if ((magic >= mp->min) && (magic <= mp->max)) { result = locate_python(mp->version, FALSE); if (result != NULL) break; } } return result; } static void maybe_handle_shebang(wchar_t ** argv, wchar_t * cmdline) { /* * Look for a shebang line in the first argument. If found * and we spawn a child process, this never returns. If it * does return then we process the args "normally". * * argv[0] might be a filename with a shebang. */ FILE * fp; errno_t rc = _wfopen_s(&fp, *argv, L"rb"); char buffer[BUFSIZE]; wchar_t shebang_line[BUFSIZE + 1]; size_t read; char *p; char * start; char * shebang_alias = (char *) shebang_line; BOM* bom; int i, j, nchars = 0; int header_len; BOOL is_virt; BOOL search; wchar_t * command; wchar_t * suffix; COMMAND *cmd = NULL; INSTALLED_PYTHON * ip; if (rc == 0) { read = fread(buffer, sizeof(char), BUFSIZE, fp); debug(L"maybe_handle_shebang: read %d bytes\n", read); fclose(fp); if ((read >= 4) && (buffer[3] == '\n') && (buffer[2] == '\r')) { ip = find_by_magic((((unsigned char)buffer[1]) << 8 | (unsigned char)buffer[0]) & 0xFFFF); if (ip != NULL) { debug(L"script file is compiled against Python %ls\n", ip->version); invoke_child(ip->executable, NULL, cmdline); } } /* Look for BOM */ bom = find_BOM(buffer); if (bom == NULL) { start = buffer; debug(L"maybe_handle_shebang: BOM not found, using UTF-8\n"); bom = BOMs; /* points to UTF-8 entry - the default */ } else { debug(L"maybe_handle_shebang: BOM found, code page %d\n", bom->code_page); start = &buffer[bom->length]; } p = find_terminator(start, BUFSIZE, bom); /* * If no CR or LF was found in the heading, * we assume it's not a shebang file. */ if (p == NULL) { debug(L"maybe_handle_shebang: No line terminator found\n"); } else { /* * Found line terminator - parse the shebang. * * Strictly, we don't need to handle UTF-16 anf UTF-32, * since Python itself doesn't. * Never mind, one day it might. */ header_len = (int) (p - start); switch(bom->code_page) { case CP_UTF8: nchars = MultiByteToWideChar(bom->code_page, 0, start, header_len, shebang_line, BUFSIZE); break; case CP_UTF16BE: if (header_len % 2 != 0) { debug(L"maybe_handle_shebang: UTF-16BE, but an odd number \ of bytes: %d\n", header_len); /* nchars = 0; Not needed - initialised to 0. */ } else { for (i = header_len; i > 0; i -= 2) { shebang_alias[i - 1] = start[i - 2]; shebang_alias[i - 2] = start[i - 1]; } nchars = header_len / sizeof(wchar_t); } break; case CP_UTF16LE: if ((header_len % 2) != 0) { debug(L"UTF-16LE, but an odd number of bytes: %d\n", header_len); /* nchars = 0; Not needed - initialised to 0. */ } else { /* no actual conversion needed. */ memcpy(shebang_line, start, header_len); nchars = header_len / sizeof(wchar_t); } break; case CP_UTF32BE: if (header_len % 4 != 0) { debug(L"UTF-32BE, but not divisible by 4: %d\n", header_len); /* nchars = 0; Not needed - initialised to 0. */ } else { for (i = header_len, j = header_len / 2; i > 0; i -= 4, j -= 2) { shebang_alias[j - 1] = start[i - 2]; shebang_alias[j - 2] = start[i - 1]; } nchars = header_len / sizeof(wchar_t); } break; case CP_UTF32LE: if (header_len % 4 != 0) { debug(L"UTF-32LE, but not divisible by 4: %d\n", header_len); /* nchars = 0; Not needed - initialised to 0. */ } else { for (i = header_len, j = header_len / 2; i > 0; i -= 4, j -= 2) { shebang_alias[j - 1] = start[i - 3]; shebang_alias[j - 2] = start[i - 4]; } nchars = header_len / sizeof(wchar_t); } break; } if (nchars > 0) { shebang_line[--nchars] = L'\0'; is_virt = parse_shebang(shebang_line, nchars, &command, &suffix, &search); if (command != NULL) { debug(L"parse_shebang: found command: %ls\n", command); if (!is_virt) { invoke_child(command, suffix, cmdline); } else { suffix = wcschr(command, L' '); if (suffix != NULL) { *suffix++ = L'\0'; suffix = skip_whitespace(suffix); } if (wcsncmp(command, L"python", 6)) error(RC_BAD_VIRTUAL_PATH, L"Unknown virtual \ path '%ls'", command); command += 6; /* skip past "python" */ if (search && ((*command == L'\0') || isspace(*command))) { /* Command is eligible for path search, and there * is no version specification. */ debug(L"searching PATH for python executable\n"); cmd = find_on_path(PYTHON_EXECUTABLE); debug(L"Python on path: %ls\n", cmd ? cmd->value : L"<not found>"); if (cmd) { debug(L"located python on PATH: %ls\n", cmd->value); invoke_child(cmd->value, suffix, cmdline); /* Exit here, as we have found the command */ return; } /* FALL THROUGH: No python found on PATH, so fall * back to locating the correct installed python. */ } if (*command && !validate_version(command)) error(RC_BAD_VIRTUAL_PATH, L"Invalid version \ specification: '%ls'.\nIn the first line of the script, 'python' needs to be \ followed by a valid version specifier.\nPlease check the documentation.", command); /* TODO could call validate_version(command) */ ip = locate_python(command, TRUE); if (ip == NULL) { error(RC_NO_PYTHON, L"Requested Python version \ (%ls) is not installed", command); } else { invoke_child(ip->executable, suffix, cmdline); } } } } } } } static wchar_t * skip_me(wchar_t * cmdline) { BOOL quoted; wchar_t c; wchar_t * result = cmdline; quoted = cmdline[0] == L'\"'; if (!quoted) c = L' '; else { c = L'\"'; ++result; } result = wcschr(result, c); if (result == NULL) /* when, for example, just exe name on command line */ result = L""; else { ++result; /* skip past space or closing quote */ result = skip_whitespace(result); } return result; } static DWORD version_high = 0; static DWORD version_low = 0; static void get_version_info(wchar_t * version_text, size_t size) { WORD maj, min, rel, bld; if (!version_high && !version_low) wcsncpy_s(version_text, size, L"0.1", _TRUNCATE); /* fallback */ else { maj = HIWORD(version_high); min = LOWORD(version_high); rel = HIWORD(version_low); bld = LOWORD(version_low); _snwprintf_s(version_text, size, _TRUNCATE, L"%d.%d.%d.%d", maj, min, rel, bld); } } static int process(int argc, wchar_t ** argv) { wchar_t * wp; wchar_t * command; wchar_t * executable; wchar_t * p; int rc = 0; size_t plen; INSTALLED_PYTHON * ip; BOOL valid; DWORD size, attrs; HRESULT hr; wchar_t message[MSGSIZE]; wchar_t version_text [MAX_PATH]; void * version_data; VS_FIXEDFILEINFO * file_info; UINT block_size; int index; #if defined(SCRIPT_WRAPPER) int newlen; wchar_t * newcommand; wchar_t * av[2]; #endif setvbuf(stderr, (char *)NULL, _IONBF, 0); wp = get_env(L"PYLAUNCH_DEBUG"); if ((wp != NULL) && (*wp != L'\0')) log_fp = stderr; #if defined(_M_X64) debug(L"launcher build: 64bit\n"); #else debug(L"launcher build: 32bit\n"); #endif #if defined(_WINDOWS) debug(L"launcher executable: Windows\n"); #else debug(L"launcher executable: Console\n"); #endif /* Get the local appdata folder (non-roaming) */ hr = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, appdata_ini_path); if (hr != S_OK) { debug(L"SHGetFolderPath failed: %X\n", hr); appdata_ini_path[0] = L'\0'; } else { plen = wcslen(appdata_ini_path); p = &appdata_ini_path[plen]; wcsncpy_s(p, MAX_PATH - plen, L"\\py.ini", _TRUNCATE); attrs = GetFileAttributesW(appdata_ini_path); if (attrs == INVALID_FILE_ATTRIBUTES) { debug(L"File '%ls' non-existent\n", appdata_ini_path); appdata_ini_path[0] = L'\0'; } else { debug(L"Using local configuration file '%ls'\n", appdata_ini_path); } } plen = GetModuleFileNameW(NULL, launcher_ini_path, MAX_PATH); size = GetFileVersionInfoSizeW(launcher_ini_path, &size); if (size == 0) { winerror(GetLastError(), message, MSGSIZE); debug(L"GetFileVersionInfoSize failed: %ls\n", message); } else { version_data = malloc(size); if (version_data) { valid = GetFileVersionInfoW(launcher_ini_path, 0, size, version_data); if (!valid) debug(L"GetFileVersionInfo failed: %X\n", GetLastError()); else { valid = VerQueryValueW(version_data, L"\\", (LPVOID *) &file_info, &block_size); if (!valid) debug(L"VerQueryValue failed: %X\n", GetLastError()); else { version_high = file_info->dwFileVersionMS; version_low = file_info->dwFileVersionLS; } } free(version_data); } } p = wcsrchr(launcher_ini_path, L'\\'); if (p == NULL) { debug(L"GetModuleFileNameW returned value has no backslash: %ls\n", launcher_ini_path); launcher_ini_path[0] = L'\0'; } else { wcsncpy_s(p, MAX_PATH - (p - launcher_ini_path), L"\\py.ini", _TRUNCATE); attrs = GetFileAttributesW(launcher_ini_path); if (attrs == INVALID_FILE_ATTRIBUTES) { debug(L"File '%ls' non-existent\n", launcher_ini_path); launcher_ini_path[0] = L'\0'; } else { debug(L"Using global configuration file '%ls'\n", launcher_ini_path); } } command = skip_me(GetCommandLineW()); debug(L"Called with command line: %ls\n", command); #if defined(SCRIPT_WRAPPER) /* The launcher is being used in "script wrapper" mode. * There should therefore be a Python script named <exename>-script.py in * the same directory as the launcher executable. * Put the script name into argv as the first (script name) argument. */ /* Get the wrapped script name - if the script is not present, this will * terminate the program with an error. */ locate_wrapped_script(); /* Add the wrapped script to the start of command */ newlen = wcslen(wrapped_script_path) + wcslen(command) + 2; /* ' ' + NUL */ newcommand = malloc(sizeof(wchar_t) * newlen); if (!newcommand) { error(RC_NO_MEMORY, L"Could not allocate new command line"); } else { wcscpy_s(newcommand, newlen, wrapped_script_path); wcscat_s(newcommand, newlen, L" "); wcscat_s(newcommand, newlen, command); debug(L"Running wrapped script with command line '%ls'\n", newcommand); read_commands(); av[0] = wrapped_script_path; av[1] = NULL; maybe_handle_shebang(av, newcommand); /* Returns if no shebang line - pass to default processing */ command = newcommand; valid = FALSE; } #else if (argc <= 1) { valid = FALSE; p = NULL; } else { p = argv[1]; plen = wcslen(p); valid = (*p == L'-') && validate_version(&p[1]); if (valid) { ip = locate_python(&p[1], FALSE); if (ip == NULL) error(RC_NO_PYTHON, L"Requested Python version (%ls) not \ installed", &p[1]); executable = ip->executable; command += wcslen(p); command = skip_whitespace(command); } else { for (index = 1; index < argc; ++index) { if (*argv[index] != L'-') break; } if (index < argc) { read_commands(); maybe_handle_shebang(&argv[index], command); } } } #endif if (!valid) { /* Look for an active virtualenv */ executable = find_python_by_venv(); /* If we didn't find one, look for the default Python */ if (executable == NULL) { ip = locate_python(L"", FALSE); if (ip == NULL) error(RC_NO_PYTHON, L"Can't find a default Python."); executable = ip->executable; } if ((argc == 2) && (!_wcsicmp(p, L"-h") || !_wcsicmp(p, L"--help"))) { #if defined(_M_X64) BOOL canDo64bit = TRUE; #else // If we are a 32bit process on a 64bit Windows, first hit the 64bit keys. BOOL canDo64bit = FALSE; IsWow64Process(GetCurrentProcess(), &canDo64bit); #endif get_version_info(version_text, MAX_PATH); fwprintf(stdout, L"\ Python Launcher for Windows Version %ls\n\n", version_text); fwprintf(stdout, L"\ usage: %ls [ launcher-arguments ] [ python-arguments ] script [ script-arguments ]\n\n", argv[0]); fputws(L"\ Launcher arguments:\n\n\ -2 : Launch the latest Python 2.x version\n\ -3 : Launch the latest Python 3.x version\n\ -X.Y : Launch the specified Python version\n", stdout); if (canDo64bit) { fputws(L"\ -X.Y-32: Launch the specified 32bit Python version", stdout); } fputws(L"\n\nThe following help text is from Python:\n\n", stdout); fflush(stdout); } } invoke_child(executable, NULL, command); return rc; } #if defined(_WINDOWS) int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpstrCmd, int nShow) { return process(__argc, __wargv); } #else int cdecl wmain(int argc, wchar_t ** argv) { return process(argc, argv); } #endif
52,122
1,580
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/winsound.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ /* Author: Toby Dickenson <[email protected]> * * Copyright (c) 1999 Toby Dickenson * * Permission to use this software in any way is granted without * fee, provided that the copyright notice above appears in all * copies. This software is provided "as is" without any warranty. */ /* Modified by Guido van Rossum */ /* Beep added by Mark Hammond */ /* Win9X Beep and platform identification added by Uncle Timmy */ /* Example: import winsound import time # Play wav file winsound.PlaySound('c:/windows/media/Chord.wav', winsound.SND_FILENAME) # Play sound from control panel settings winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS) # Play wav file from memory data=open('c:/windows/media/Chimes.wav',"rb").read() winsound.PlaySound(data, winsound.SND_MEMORY) # Start playing the first bit of wav file asynchronously winsound.PlaySound('c:/windows/media/Chord.wav', winsound.SND_FILENAME|winsound.SND_ASYNC) # But dont let it go for too long... time.sleep(0.1) # ...Before stopping it winsound.PlaySound(None, 0) */ #include "third_party/python/Include/Python.h" PyDoc_STRVAR(sound_module_doc, "PlaySound(sound, flags) - play a sound\n" "SND_FILENAME - sound is a wav file name\n" "SND_ALIAS - sound is a registry sound association name\n" "SND_LOOP - Play the sound repeatedly; must also specify SND_ASYNC\n" "SND_MEMORY - sound is a memory image of a wav file\n" "SND_PURGE - stop all instances of the specified sound\n" "SND_ASYNC - PlaySound returns immediately\n" "SND_NODEFAULT - Do not play a default beep if the sound can not be found\n" "SND_NOSTOP - Do not interrupt any sounds currently playing\n" // Raising RuntimeError if needed "SND_NOWAIT - Return immediately if the sound driver is busy\n" // Without any errors "\n" "Beep(frequency, duration) - Make a beep through the PC speaker.\n" "MessageBeep(type) - Call Windows MessageBeep."); /*[clinic input] module winsound [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=a18401142d97b8d5]*/ #include "third_party/python/PC/clinic/winsound.inc" /*[clinic input] winsound.PlaySound sound: object The sound to play; a filename, data, or None. flags: int Flag values, ored together. See module documentation. A wrapper around the Windows PlaySound API. [clinic start generated code]*/ static PyObject * winsound_PlaySound_impl(PyObject *module, PyObject *sound, int flags) /*[clinic end generated code: output=49a0fd16a372ebeb input=c63e1f2d848da2f2]*/ { int ok; wchar_t *wsound; Py_buffer view = {NULL, NULL}; if (sound == Py_None) { wsound = NULL; } else if (flags & SND_MEMORY) { if (flags & SND_ASYNC) { /* Sidestep reference counting headache; unfortunately this also prevent SND_LOOP from memory. */ PyErr_SetString(PyExc_RuntimeError, "Cannot play asynchronously from memory"); return NULL; } if (PyObject_GetBuffer(sound, &view, PyBUF_SIMPLE) < 0) { return NULL; } wsound = (wchar_t *)view.buf; } else { if (!PyUnicode_Check(sound)) { PyErr_Format(PyExc_TypeError, "'sound' must be str or None, not '%s'", Py_TYPE(sound)->tp_name); return NULL; } wsound = _PyUnicode_AsWideCharString(sound); if (wsound == NULL) { return NULL; } } Py_BEGIN_ALLOW_THREADS ok = PlaySoundW(wsound, NULL, flags); Py_END_ALLOW_THREADS if (view.obj) { PyBuffer_Release(&view); } else if (sound != Py_None) { PyMem_Free(wsound); } if (!ok) { PyErr_SetString(PyExc_RuntimeError, "Failed to play sound"); return NULL; } Py_RETURN_NONE; } /*[clinic input] winsound.Beep frequency: int Frequency of the sound in hertz. Must be in the range 37 through 32,767. duration: int How long the sound should play, in milliseconds. A wrapper around the Windows Beep API. [clinic start generated code]*/ static PyObject * winsound_Beep_impl(PyObject *module, int frequency, int duration) /*[clinic end generated code: output=f32382e52ee9b2fb input=40e360cfa00a5cf0]*/ { BOOL ok; if (frequency < 37 || frequency > 32767) { PyErr_SetString(PyExc_ValueError, "frequency must be in 37 thru 32767"); return NULL; } Py_BEGIN_ALLOW_THREADS ok = Beep(frequency, duration); Py_END_ALLOW_THREADS if (!ok) { PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); return NULL; } Py_RETURN_NONE; } /*[clinic input] winsound.MessageBeep type: int(c_default="MB_OK") = MB_OK Call Windows MessageBeep(x). x defaults to MB_OK. [clinic start generated code]*/ static PyObject * winsound_MessageBeep_impl(PyObject *module, int type) /*[clinic end generated code: output=120875455121121f input=db185f741ae21401]*/ { BOOL ok; Py_BEGIN_ALLOW_THREADS ok = MessageBeep(type); Py_END_ALLOW_THREADS if (!ok) { PyErr_SetExcFromWindowsErr(PyExc_RuntimeError, 0); return NULL; } Py_RETURN_NONE; } static struct PyMethodDef sound_methods[] = { WINSOUND_PLAYSOUND_METHODDEF WINSOUND_BEEP_METHODDEF WINSOUND_MESSAGEBEEP_METHODDEF {NULL, NULL} }; static void add_define(PyObject *dict, const char *key, long value) { PyObject *k = PyUnicode_FromString(key); PyObject *v = PyLong_FromLong(value); if (v && k) { PyDict_SetItem(dict, k, v); } Py_XDECREF(k); Py_XDECREF(v); } #define ADD_DEFINE(tok) add_define(dict,#tok,tok) static struct PyModuleDef winsoundmodule = { PyModuleDef_HEAD_INIT, "winsound", sound_module_doc, -1, sound_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_winsound(void) { PyObject *dict; PyObject *module = PyModule_Create(&winsoundmodule); if (module == NULL) return NULL; dict = PyModule_GetDict(module); ADD_DEFINE(SND_ASYNC); ADD_DEFINE(SND_NODEFAULT); ADD_DEFINE(SND_NOSTOP); ADD_DEFINE(SND_NOWAIT); ADD_DEFINE(SND_ALIAS); ADD_DEFINE(SND_FILENAME); ADD_DEFINE(SND_MEMORY); ADD_DEFINE(SND_PURGE); ADD_DEFINE(SND_LOOP); ADD_DEFINE(SND_APPLICATION); ADD_DEFINE(MB_OK); ADD_DEFINE(MB_ICONASTERISK); ADD_DEFINE(MB_ICONEXCLAMATION); ADD_DEFINE(MB_ICONHAND); ADD_DEFINE(MB_ICONQUESTION); return module; }
7,466
257
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/winreg.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/isystem/windows.h" #include "libc/nt/registry.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/structmember.h" /* clang-format off */ /* winreg.c Windows Registry access module for Python. * Simple registry access written by Mark Hammond in win32api module circa 1995. * Bill Tutt expanded the support significantly not long after. * Numerous other people have submitted patches since then. * Ripped from win32api module 03-Feb-2000 by Mark Hammond, and basic Unicode support added. */ static BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pRes, BOOL bNoneOK); static BOOL clinic_HKEY_converter(PyObject *ob, void *p); static PyObject *PyHKEY_FromHKEY(HKEY h); static BOOL PyHKEY_Close(PyObject *obHandle); static char errNotAHandle[] = "Object is not a handle"; /* The win32api module reports the function name that failed, but this concept is not in the Python core. Hopefully it will one day, and in the meantime I dont want to lose this info... */ #define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \ PyErr_SetFromWindowsErr(rc) /* Forward declares */ /* Doc strings */ PyDoc_STRVAR(module_doc, "This module provides access to the Windows registry API.\n" "\n" "Functions:\n" "\n" "CloseKey() - Closes a registry key.\n" "ConnectRegistry() - Establishes a connection to a predefined registry handle\n" " on another computer.\n" "CreateKey() - Creates the specified key, or opens it if it already exists.\n" "DeleteKey() - Deletes the specified key.\n" "DeleteValue() - Removes a named value from the specified registry key.\n" "EnumKey() - Enumerates subkeys of the specified open registry key.\n" "EnumValue() - Enumerates values of the specified open registry key.\n" "ExpandEnvironmentStrings() - Expand the env strings in a REG_EXPAND_SZ\n" " string.\n" "FlushKey() - Writes all the attributes of the specified key to the registry.\n" "LoadKey() - Creates a subkey under HKEY_USER or HKEY_LOCAL_MACHINE and\n" " stores registration information from a specified file into that\n" " subkey.\n" "OpenKey() - Opens the specified key.\n" "OpenKeyEx() - Alias of OpenKey().\n" "QueryValue() - Retrieves the value associated with the unnamed value for a\n" " specified key in the registry.\n" "QueryValueEx() - Retrieves the type and data for a specified value name\n" " associated with an open registry key.\n" "QueryInfoKey() - Returns information about the specified key.\n" "SaveKey() - Saves the specified key, and all its subkeys a file.\n" "SetValue() - Associates a value with a specified key.\n" "SetValueEx() - Stores data in the value field of an open registry key.\n" "\n" "Special objects:\n" "\n" "HKEYType -- type object for HKEY objects\n" "error -- exception raised for Win32 errors\n" "\n" "Integer constants:\n" "Many constants are defined - see the documentation for each function\n" "to see what constants are used, and where."); /* PyHKEY docstrings */ PyDoc_STRVAR(PyHKEY_doc, "PyHKEY Object - A Python object, representing a win32 registry key.\n" "\n" "This object wraps a Windows HKEY object, automatically closing it when\n" "the object is destroyed. To guarantee cleanup, you can call either\n" "the Close() method on the PyHKEY, or the CloseKey() method.\n" "\n" "All functions which accept a handle object also accept an integer - \n" "however, use of the handle object is encouraged.\n" "\n" "Functions:\n" "Close() - Closes the underlying handle.\n" "Detach() - Returns the integer Win32 handle, detaching it from the object\n" "\n" "Properties:\n" "handle - The integer Win32 handle.\n" "\n" "Operations:\n" "__bool__ - Handles with an open object return true, otherwise false.\n" "__int__ - Converting a handle to an integer returns the Win32 handle.\n" "rich comparison - Handle objects are compared using the handle value."); /************************************************************************ The PyHKEY object definition ************************************************************************/ typedef struct { PyObject_VAR_HEAD HKEY hkey; } PyHKEYObject; #define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type) static char *failMsg = "bad operand type"; static PyObject * PyHKEY_unaryFailureFunc(PyObject *ob) { PyErr_SetString(PyExc_TypeError, failMsg); return NULL; } static PyObject * PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2) { PyErr_SetString(PyExc_TypeError, failMsg); return NULL; } static PyObject * PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3) { PyErr_SetString(PyExc_TypeError, failMsg); return NULL; } static void PyHKEY_deallocFunc(PyObject *ob) { /* Can not call PyHKEY_Close, as the ob->tp_type has already been cleared, thus causing the type check to fail! */ PyHKEYObject *obkey = (PyHKEYObject *)ob; if (obkey->hkey) RegCloseKey((HKEY)obkey->hkey); PyObject_DEL(ob); } static int PyHKEY_boolFunc(PyObject *ob) { return ((PyHKEYObject *)ob)->hkey != 0; } static PyObject * PyHKEY_intFunc(PyObject *ob) { PyHKEYObject *pyhkey = (PyHKEYObject *)ob; return PyLong_FromVoidPtr((void *)pyhkey->hkey); } static PyObject * PyHKEY_strFunc(PyObject *ob) { PyHKEYObject *pyhkey = (PyHKEYObject *)ob; return PyUnicode_FromFormat("<PyHKEY:%p>", pyhkey->hkey); } static int PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2) { PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; return pyhkey1 == pyhkey2 ? 0 : (pyhkey1 < pyhkey2 ? -1 : 1); } static Py_hash_t PyHKEY_hashFunc(PyObject *ob) { /* Just use the address. XXX - should we use the handle value? */ return _Py_HashPointer(ob); } static PyNumberMethods PyHKEY_NumberMethods = { PyHKEY_binaryFailureFunc, /* nb_add */ PyHKEY_binaryFailureFunc, /* nb_subtract */ PyHKEY_binaryFailureFunc, /* nb_multiply */ PyHKEY_binaryFailureFunc, /* nb_remainder */ PyHKEY_binaryFailureFunc, /* nb_divmod */ PyHKEY_ternaryFailureFunc, /* nb_power */ PyHKEY_unaryFailureFunc, /* nb_negative */ PyHKEY_unaryFailureFunc, /* nb_positive */ PyHKEY_unaryFailureFunc, /* nb_absolute */ PyHKEY_boolFunc, /* nb_bool */ PyHKEY_unaryFailureFunc, /* nb_invert */ PyHKEY_binaryFailureFunc, /* nb_lshift */ PyHKEY_binaryFailureFunc, /* nb_rshift */ PyHKEY_binaryFailureFunc, /* nb_and */ PyHKEY_binaryFailureFunc, /* nb_xor */ PyHKEY_binaryFailureFunc, /* nb_or */ PyHKEY_intFunc, /* nb_int */ 0, /* nb_reserved */ PyHKEY_unaryFailureFunc, /* nb_float */ }; /*[clinic input] module winreg class winreg.HKEYType "PyHKEYObject *" "&PyHKEY_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=4c964eba3bf914d6]*/ /*[python input] class REGSAM_converter(CConverter): type = 'REGSAM' format_unit = 'i' class DWORD_converter(CConverter): type = 'DWORD' format_unit = 'k' class HKEY_converter(CConverter): type = 'HKEY' converter = 'clinic_HKEY_converter' class HKEY_return_converter(CReturnConverter): type = 'HKEY' def render(self, function, data): self.declare(data) self.err_occurred_if_null_pointer("_return_value", data) data.return_conversion.append( 'return_value = PyHKEY_FromHKEY(_return_value);\n') # HACK: this only works for PyHKEYObjects, nothing else. # Should this be generalized and enshrined in clinic.py, # destroy this converter with prejudice. class self_return_converter(CReturnConverter): type = 'PyHKEYObject *' def render(self, function, data): self.declare(data) data.return_conversion.append( 'return_value = (PyObject *)_return_value;\n') [python start generated code]*/ /*[python end generated code: output=da39a3ee5e6b4b0d input=22f7aedc6d68e80e]*/ #include "third_party/python/PC/clinic/winreg.inc" /************************************************************************ The PyHKEY object methods ************************************************************************/ /*[clinic input] winreg.HKEYType.Close Closes the underlying Windows handle. If the handle is already closed, no error is raised. [clinic start generated code]*/ static PyObject * winreg_HKEYType_Close_impl(PyHKEYObject *self) /*[clinic end generated code: output=fced3a624fb0c344 input=6786ac75f6b89de6]*/ { if (!PyHKEY_Close((PyObject *)self)) return NULL; Py_RETURN_NONE; } /*[clinic input] winreg.HKEYType.Detach Detaches the Windows handle from the handle object. The result is the value of the handle before it is detached. If the handle is already detached, this will return zero. After calling this function, the handle is effectively invalidated, but the handle is not closed. You would call this function when you need the underlying win32 handle to exist beyond the lifetime of the handle object. [clinic start generated code]*/ static PyObject * winreg_HKEYType_Detach_impl(PyHKEYObject *self) /*[clinic end generated code: output=dda5a9e1a01ae78f input=dd2cc09e6c6ba833]*/ { void* ret; ret = (void*)self->hkey; self->hkey = 0; return PyLong_FromVoidPtr(ret); } /*[clinic input] winreg.HKEYType.__enter__ -> self [clinic start generated code]*/ static PyHKEYObject * winreg_HKEYType___enter___impl(PyHKEYObject *self) /*[clinic end generated code: output=52c34986dab28990 input=c40fab1f0690a8e2]*/ { Py_XINCREF(self); return self; } /*[clinic input] winreg.HKEYType.__exit__ exc_type: object exc_value: object traceback: object [clinic start generated code]*/ static PyObject * winreg_HKEYType___exit___impl(PyHKEYObject *self, PyObject *exc_type, PyObject *exc_value, PyObject *traceback) /*[clinic end generated code: output=923ebe7389e6a263 input=fb32489ee92403c7]*/ { if (!PyHKEY_Close((PyObject *)self)) return NULL; Py_RETURN_NONE; } /*[clinic input] [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=da39a3ee5e6b4b0d]*/ static struct PyMethodDef PyHKEY_methods[] = { WINREG_HKEYTYPE_CLOSE_METHODDEF WINREG_HKEYTYPE_DETACH_METHODDEF WINREG_HKEYTYPE___ENTER___METHODDEF WINREG_HKEYTYPE___EXIT___METHODDEF {NULL} }; #define OFF(e) offsetof(PyHKEYObject, e) static PyMemberDef PyHKEY_memberlist[] = { {"handle", T_INT, OFF(hkey), READONLY}, {NULL} /* Sentinel */ }; /* The type itself */ PyTypeObject PyHKEY_Type = { PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ "PyHKEY", sizeof(PyHKEYObject), 0, PyHKEY_deallocFunc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ &PyHKEY_NumberMethods, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ PyHKEY_hashFunc, /* tp_hash */ 0, /* tp_call */ PyHKEY_strFunc, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ PyHKEY_doc, /* tp_doc */ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ PyHKEY_methods, /*tp_methods*/ PyHKEY_memberlist, /*tp_members*/ }; /************************************************************************ The public PyHKEY API (well, not public yet :-) ************************************************************************/ PyObject * PyHKEY_New(HKEY hInit) { PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); if (key) key->hkey = hInit; return (PyObject *)key; } BOOL PyHKEY_Close(PyObject *ob_handle) { LONG rc; PyHKEYObject *key; if (!PyHKEY_Check(ob_handle)) { PyErr_SetString(PyExc_TypeError, "bad operand type"); return FALSE; } key = (PyHKEYObject *)ob_handle; rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; key->hkey = 0; if (rc != ERROR_SUCCESS) PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); return rc == ERROR_SUCCESS; } BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK) { if (ob == Py_None) { if (!bNoneOK) { PyErr_SetString( PyExc_TypeError, "None is not a valid HKEY in this context"); return FALSE; } *pHANDLE = (HKEY)0; } else if (PyHKEY_Check(ob)) { PyHKEYObject *pH = (PyHKEYObject *)ob; *pHANDLE = pH->hkey; } else if (PyLong_Check(ob)) { /* We also support integers */ PyErr_Clear(); *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); if (PyErr_Occurred()) return FALSE; } else { PyErr_SetString( PyExc_TypeError, "The object is not a PyHKEY object"); return FALSE; } return TRUE; } BOOL clinic_HKEY_converter(PyObject *ob, void *p) { if (!PyHKEY_AsHKEY(ob, (HKEY *)p, FALSE)) return FALSE; return TRUE; } PyObject * PyHKEY_FromHKEY(HKEY h) { PyHKEYObject *op; /* Inline PyObject_New */ op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); if (op == NULL) return PyErr_NoMemory(); PyObject_INIT(op, &PyHKEY_Type); op->hkey = h; return (PyObject *)op; } /************************************************************************ The module methods ************************************************************************/ BOOL PyWinObject_CloseHKEY(PyObject *obHandle) { BOOL ok; if (PyHKEY_Check(obHandle)) { ok = PyHKEY_Close(obHandle); } #if SIZEOF_LONG >= SIZEOF_HKEY else if (PyLong_Check(obHandle)) { long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle)); ok = (rc == ERROR_SUCCESS); if (!ok) PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); } #else else if (PyLong_Check(obHandle)) { long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); ok = (rc == ERROR_SUCCESS); if (!ok) PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); } #endif else { PyErr_SetString( PyExc_TypeError, "A handle must be a HKEY object or an integer"); return FALSE; } return ok; } /* Private Helper functions for the registry interfaces ** Note that fixupMultiSZ and countString have both had changes ** made to support "incorrect strings". The registry specification ** calls for strings to be terminated with 2 null bytes. It seems ** some commercial packages install strings which dont conform, ** causing this code to fail - however, "regedit" etc still work ** with these strings (ie only we dont!). */ static void fixupMultiSZ(wchar_t **str, wchar_t *data, int len) { wchar_t *P; int i; wchar_t *Q; Q = data + len; for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { str[i] = P; for (; P < Q && *P != '\0'; P++) ; } } static int countStrings(wchar_t *data, int len) { int strings; wchar_t *P; wchar_t *Q = data + len; for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) for (; P < Q && *P != '\0'; P++) ; return strings; } /* Convert PyObject into Registry data. Allocates space as needed. */ static BOOL Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize) { Py_ssize_t i,j; switch (typ) { case REG_DWORD: if (value != Py_None && !PyLong_Check(value)) return FALSE; *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); if (*retDataBuf == NULL){ PyErr_NoMemory(); return FALSE; } *retDataSize = sizeof(DWORD); if (value == Py_None) { DWORD zero = 0; memcpy(*retDataBuf, &zero, sizeof(DWORD)); } else { DWORD d = PyLong_AsUnsignedLong(value); memcpy(*retDataBuf, &d, sizeof(DWORD)); } break; case REG_QWORD: if (value != Py_None && !PyLong_Check(value)) return FALSE; *retDataBuf = (BYTE *)PyMem_NEW(DWORD64, 1); if (*retDataBuf == NULL){ PyErr_NoMemory(); return FALSE; } *retDataSize = sizeof(DWORD64); if (value == Py_None) { DWORD64 zero = 0; memcpy(*retDataBuf, &zero, sizeof(DWORD64)); } else { DWORD64 d = PyLong_AsUnsignedLongLong(value); memcpy(*retDataBuf, &d, sizeof(DWORD64)); } break; case REG_SZ: case REG_EXPAND_SZ: { if (value != Py_None) { Py_ssize_t len; if (!PyUnicode_Check(value)) return FALSE; *retDataBuf = (BYTE*)PyUnicode_AsWideCharString(value, &len); if (*retDataBuf == NULL) return FALSE; *retDataSize = Py_SAFE_DOWNCAST( (len + 1) * sizeof(wchar_t), Py_ssize_t, DWORD); } else { *retDataBuf = (BYTE *)PyMem_NEW(wchar_t, 1); if (*retDataBuf == NULL) { PyErr_NoMemory(); return FALSE; } ((wchar_t *)*retDataBuf)[0] = L'\0'; *retDataSize = 1 * sizeof(wchar_t); } break; } case REG_MULTI_SZ: { DWORD size = 0; wchar_t *P; if (value == Py_None) i = 0; else { if (!PyList_Check(value)) return FALSE; i = PyList_Size(value); } for (j = 0; j < i; j++) { PyObject *t; wchar_t *wstr; Py_ssize_t len; t = PyList_GET_ITEM(value, j); if (!PyUnicode_Check(t)) return FALSE; wstr = PyUnicode_AsUnicodeAndSize(t, &len); if (wstr == NULL) return FALSE; size += Py_SAFE_DOWNCAST((len + 1) * sizeof(wchar_t), size_t, DWORD); } *retDataSize = size + 2; *retDataBuf = (BYTE *)PyMem_NEW(char, *retDataSize); if (*retDataBuf == NULL){ PyErr_NoMemory(); return FALSE; } P = (wchar_t *)*retDataBuf; for (j = 0; j < i; j++) { PyObject *t; wchar_t *wstr; Py_ssize_t len; t = PyList_GET_ITEM(value, j); wstr = PyUnicode_AsUnicodeAndSize(t, &len); if (wstr == NULL) return FALSE; wcscpy(P, wstr); P += (len + 1); } /* And doubly-terminate the list... */ *P = '\0'; break; } case REG_BINARY: /* ALSO handle ALL unknown data types here. Even if we can't support it natively, we should handle the bits. */ default: if (value == Py_None) { *retDataSize = 0; *retDataBuf = NULL; } else { Py_buffer view; if (!PyObject_CheckBuffer(value)) { PyErr_Format(PyExc_TypeError, "Objects of type '%s' can not " "be used as binary registry values", value->ob_type->tp_name); return FALSE; } if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) return FALSE; *retDataBuf = (BYTE *)PyMem_NEW(char, view.len); if (*retDataBuf == NULL){ PyBuffer_Release(&view); PyErr_NoMemory(); return FALSE; } *retDataSize = Py_SAFE_DOWNCAST(view.len, Py_ssize_t, DWORD); memcpy(*retDataBuf, view.buf, view.len); PyBuffer_Release(&view); } break; } return TRUE; } /* Convert Registry data into PyObject*/ static PyObject * Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ) { PyObject *obData; switch (typ) { case REG_DWORD: if (retDataSize == 0) obData = PyLong_FromUnsignedLong(0); else obData = PyLong_FromUnsignedLong(*(DWORD *)retDataBuf); break; case REG_QWORD: if (retDataSize == 0) obData = PyLong_FromUnsignedLongLong(0); else obData = PyLong_FromUnsignedLongLong(*(DWORD64 *)retDataBuf); break; case REG_SZ: case REG_EXPAND_SZ: { /* REG_SZ should be a NUL terminated string, but only by * convention. The buffer may have been saved without a NUL * or with embedded NULs. To be consistent with reg.exe and * regedit.exe, consume only up to the first NUL. */ wchar_t *data = (wchar_t *)retDataBuf; size_t len = wcsnlen(data, retDataSize / sizeof(wchar_t)); obData = PyUnicode_FromWideChar(data, len); break; } case REG_MULTI_SZ: if (retDataSize == 0) obData = PyList_New(0); else { int index = 0; wchar_t *data = (wchar_t *)retDataBuf; int len = retDataSize / 2; int s = countStrings(data, len); wchar_t **str = PyMem_New(wchar_t *, s); if (str == NULL) return PyErr_NoMemory(); fixupMultiSZ(str, data, len); obData = PyList_New(s); if (obData == NULL) { PyMem_Free(str); return NULL; } for (index = 0; index < s; index++) { size_t len = wcslen(str[index]); if (len > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "registry string is too long for a Python string"); Py_DECREF(obData); PyMem_Free(str); return NULL; } PyObject *uni = PyUnicode_FromWideChar(str[index], len); if (uni == NULL) { Py_DECREF(obData); PyMem_Free(str); return NULL; } PyList_SET_ITEM(obData, index, uni); } PyMem_Free(str); break; } case REG_BINARY: /* ALSO handle ALL unknown data types here. Even if we can't support it natively, we should handle the bits. */ default: if (retDataSize == 0) { Py_INCREF(Py_None); obData = Py_None; } else obData = PyBytes_FromStringAndSize( (char *)retDataBuf, retDataSize); break; } return obData; } /* The Python methods */ /*[clinic input] winreg.CloseKey hkey: object A previously opened key. / Closes a previously opened registry key. Note that if the key is not closed using this method, it will be closed when the hkey object is destroyed by Python. [clinic start generated code]*/ static PyObject * winreg_CloseKey(PyObject *module, PyObject *hkey) /*[clinic end generated code: output=a4fa537019a80d15 input=5b1aac65ba5127ad]*/ { if (!PyHKEY_Close(hkey)) return NULL; Py_RETURN_NONE; } /*[clinic input] winreg.ConnectRegistry -> HKEY computer_name: Py_UNICODE(accept={str, NoneType}) The name of the remote computer, of the form r"\\computername". If None, the local computer is used. key: HKEY The predefined key to connect to. / Establishes a connection to the registry on another computer. The return value is the handle of the opened key. If the function fails, an OSError exception is raised. [clinic start generated code]*/ static HKEY winreg_ConnectRegistry_impl(PyObject *module, Py_UNICODE *computer_name, HKEY key) /*[clinic end generated code: output=5ab79d02aa3167b4 input=5f98a891a347e68e]*/ { HKEY retKey; long rc; Py_BEGIN_ALLOW_THREADS rc = RegConnectRegistry(computer_name, key, &retKey); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) { PyErr_SetFromWindowsErrWithFunction(rc, "ConnectRegistry"); return NULL; } return retKey; } /*[clinic input] winreg.CreateKey -> HKEY key: HKEY An already open key, or one of the predefined HKEY_* constants. sub_key: Py_UNICODE(accept={str, NoneType}) The name of the key this method opens or creates. / Creates or opens the specified key. If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function. If the key already exists, this function opens the existing key. The return value is the handle of the opened key. If the function fails, an OSError exception is raised. [clinic start generated code]*/ static HKEY winreg_CreateKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key) /*[clinic end generated code: output=9c81d4095527c927 input=3cdd1622488acea2]*/ { HKEY retKey; long rc; rc = RegCreateKeyW(key, sub_key, &retKey); if (rc != ERROR_SUCCESS) { PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); return NULL; } return retKey; } /*[clinic input] winreg.CreateKeyEx -> HKEY key: HKEY An already open key, or one of the predefined HKEY_* constants. sub_key: Py_UNICODE(accept={str, NoneType}) The name of the key this method opens or creates. reserved: int = 0 A reserved integer, and must be zero. Default is zero. access: REGSAM(c_default='KEY_WRITE') = winreg.KEY_WRITE An integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WRITE. Creates or opens the specified key. If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function. If the key already exists, this function opens the existing key The return value is the handle of the opened key. If the function fails, an OSError exception is raised. [clinic start generated code]*/ static HKEY winreg_CreateKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, int reserved, REGSAM access) /*[clinic end generated code: output=b9fce6dc5c4e39b1 input=42c2b03f98406b66]*/ { HKEY retKey; long rc; rc = RegCreateKeyExW(key, sub_key, reserved, NULL, (DWORD)NULL, access, NULL, &retKey, NULL); if (rc != ERROR_SUCCESS) { PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx"); return NULL; } return retKey; } /*[clinic input] winreg.DeleteKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. sub_key: Py_UNICODE A string that must be the name of a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys. / Deletes the specified key. This method can not delete keys with subkeys. If the function succeeds, the entire key, including all of its values, is removed. If the function fails, an OSError exception is raised. [clinic start generated code]*/ static PyObject * winreg_DeleteKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key) /*[clinic end generated code: output=7734b1e431991ae4 input=b31d225b935e4211]*/ { long rc; rc = RegDeleteKeyW(key, sub_key ); if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); Py_RETURN_NONE; } /*[clinic input] winreg.DeleteKeyEx key: HKEY An already open key, or any one of the predefined HKEY_* constants. sub_key: Py_UNICODE A string that must be the name of a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys. access: REGSAM(c_default='KEY_WOW64_64KEY') = winreg.KEY_WOW64_64KEY An integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WOW64_64KEY. reserved: int = 0 A reserved integer, and must be zero. Default is zero. Deletes the specified key (64-bit OS only). This method can not delete keys with subkeys. If the function succeeds, the entire key, including all of its values, is removed. If the function fails, an OSError exception is raised. On unsupported Windows versions, NotImplementedError is raised. [clinic start generated code]*/ static PyObject * winreg_DeleteKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, REGSAM access, int reserved) /*[clinic end generated code: output=01378d86ad3eb936 input=711d9d89e7ecbed7]*/ { HMODULE hMod; typedef LONG (WINAPI *RDKEFunc)(HKEY, const wchar_t*, REGSAM, int); RDKEFunc pfn = NULL; long rc; /* Only available on 64bit platforms, so we must load it dynamically. */ hMod = GetModuleHandleW(L"advapi32.dll"); if (hMod) pfn = (RDKEFunc)GetProcAddress(hMod, "RegDeleteKeyExW"); if (!pfn) { PyErr_SetString(PyExc_NotImplementedError, "not implemented on this platform"); return NULL; } Py_BEGIN_ALLOW_THREADS rc = (*pfn)(key, sub_key, access, reserved); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx"); Py_RETURN_NONE; } /*[clinic input] winreg.DeleteValue key: HKEY An already open key, or any one of the predefined HKEY_* constants. value: Py_UNICODE(accept={str, NoneType}) A string that identifies the value to remove. / Removes a named value from a registry key. [clinic start generated code]*/ static PyObject * winreg_DeleteValue_impl(PyObject *module, HKEY key, Py_UNICODE *value) /*[clinic end generated code: output=67e7e9a514f84951 input=a78d3407a4197b21]*/ { long rc; Py_BEGIN_ALLOW_THREADS rc = RegDeleteValueW(key, value); Py_END_ALLOW_THREADS if (rc !=ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteValue"); Py_RETURN_NONE; } /*[clinic input] winreg.EnumKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. index: int An integer that identifies the index of the key to retrieve. / Enumerates subkeys of an open registry key. The function retrieves the name of one subkey each time it is called. It is typically called repeatedly until an OSError exception is raised, indicating no more values are available. [clinic start generated code]*/ static PyObject * winreg_EnumKey_impl(PyObject *module, HKEY key, int index) /*[clinic end generated code: output=25a6ec52cd147bc4 input=fad9a7c00ab0e04b]*/ { long rc; PyObject *retStr; /* The Windows docs claim that the max key name length is 255 * characters, plus a terminating nul character. However, * empirical testing demonstrates that it is possible to * create a 256 character key that is missing the terminating * nul. RegEnumKeyEx requires a 257 character buffer to * retrieve such a key name. */ wchar_t tmpbuf[257]; DWORD len = sizeof(tmpbuf)/sizeof(wchar_t); /* includes NULL terminator */ Py_BEGIN_ALLOW_THREADS rc = RegEnumKeyExW(key, index, tmpbuf, &len, NULL, NULL, NULL, NULL); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); retStr = PyUnicode_FromWideChar(tmpbuf, len); return retStr; /* can be NULL */ } /*[clinic input] winreg.EnumValue key: HKEY An already open key, or any one of the predefined HKEY_* constants. index: int An integer that identifies the index of the value to retrieve. / Enumerates values of an open registry key. The function retrieves the name of one subkey each time it is called. It is typically called repeatedly, until an OSError exception is raised, indicating no more values. The result is a tuple of 3 items: value_name A string that identifies the value. value_data An object that holds the value data, and whose type depends on the underlying registry type. data_type An integer that identifies the type of the value data. [clinic start generated code]*/ static PyObject * winreg_EnumValue_impl(PyObject *module, HKEY key, int index) /*[clinic end generated code: output=d363b5a06f8789ac input=4414f47a6fb238b5]*/ { long rc; wchar_t *retValueBuf; BYTE *tmpBuf; BYTE *retDataBuf; DWORD retValueSize, bufValueSize; DWORD retDataSize, bufDataSize; DWORD typ; PyObject *obData; PyObject *retVal; if ((rc = RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &retValueSize, &retDataSize, NULL, NULL)) != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); ++retValueSize; /* include null terminators */ ++retDataSize; bufDataSize = retDataSize; bufValueSize = retValueSize; retValueBuf = PyMem_New(wchar_t, retValueSize); if (retValueBuf == NULL) return PyErr_NoMemory(); retDataBuf = (BYTE *)PyMem_Malloc(retDataSize); if (retDataBuf == NULL) { PyMem_Free(retValueBuf); return PyErr_NoMemory(); } while (1) { Py_BEGIN_ALLOW_THREADS rc = RegEnumValueW(key, index, retValueBuf, &retValueSize, NULL, &typ, (BYTE *)retDataBuf, &retDataSize); Py_END_ALLOW_THREADS if (rc != ERROR_MORE_DATA) break; bufDataSize *= 2; tmpBuf = (BYTE *)PyMem_Realloc(retDataBuf, bufDataSize); if (tmpBuf == NULL) { PyErr_NoMemory(); retVal = NULL; goto fail; } retDataBuf = tmpBuf; retDataSize = bufDataSize; retValueSize = bufValueSize; } if (rc != ERROR_SUCCESS) { retVal = PyErr_SetFromWindowsErrWithFunction(rc, "PyRegEnumValue"); goto fail; } obData = Reg2Py(retDataBuf, retDataSize, typ); if (obData == NULL) { retVal = NULL; goto fail; } retVal = Py_BuildValue("uOi", retValueBuf, obData, typ); Py_DECREF(obData); fail: PyMem_Free(retValueBuf); PyMem_Free(retDataBuf); return retVal; } /*[clinic input] winreg.ExpandEnvironmentStrings string: Py_UNICODE / Expand environment vars. [clinic start generated code]*/ static PyObject * winreg_ExpandEnvironmentStrings_impl(PyObject *module, Py_UNICODE *string) /*[clinic end generated code: output=cba46ac293a8af1a input=b2a9714d2b751aa6]*/ { wchar_t *retValue = NULL; DWORD retValueSize; DWORD rc; PyObject *o; retValueSize = ExpandEnvironmentStringsW(string, retValue, 0); if (retValueSize == 0) { return PyErr_SetFromWindowsErrWithFunction(retValueSize, "ExpandEnvironmentStrings"); } retValue = PyMem_New(wchar_t, retValueSize); if (retValue == NULL) { return PyErr_NoMemory(); } rc = ExpandEnvironmentStringsW(string, retValue, retValueSize); if (rc == 0) { PyMem_Free(retValue); return PyErr_SetFromWindowsErrWithFunction(retValueSize, "ExpandEnvironmentStrings"); } o = PyUnicode_FromWideChar(retValue, wcslen(retValue)); PyMem_Free(retValue); return o; } /*[clinic input] winreg.FlushKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. / Writes all the attributes of a key to the registry. It is not necessary to call FlushKey to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are also flushed to disk at system shutdown. Unlike CloseKey(), the FlushKey() method returns only when all the data has been written to the registry. An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk. If you don't know whether a FlushKey() call is required, it probably isn't. [clinic start generated code]*/ static PyObject * winreg_FlushKey_impl(PyObject *module, HKEY key) /*[clinic end generated code: output=e6fc230d4c5dc049 input=f57457c12297d82f]*/ { long rc; Py_BEGIN_ALLOW_THREADS rc = RegFlushKey(key); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); Py_RETURN_NONE; } /*[clinic input] winreg.LoadKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. sub_key: Py_UNICODE A string that identifies the sub-key to load. file_name: Py_UNICODE The name of the file to load registry data from. This file must have been created with the SaveKey() function. Under the file allocation table (FAT) file system, the filename may not have an extension. / Insert data into the registry from a file. Creates a subkey under the specified key and stores registration information from a specified file into that subkey. A call to LoadKey() fails if the calling process does not have the SE_RESTORE_PRIVILEGE privilege. If key is a handle returned by ConnectRegistry(), then the path specified in fileName is relative to the remote computer. The MSDN docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE tree. [clinic start generated code]*/ static PyObject * winreg_LoadKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, Py_UNICODE *file_name) /*[clinic end generated code: output=87344005c5905cde input=e3b5b45ade311582]*/ { long rc; Py_BEGIN_ALLOW_THREADS rc = RegLoadKeyW(key, sub_key, file_name ); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); Py_RETURN_NONE; } /*[clinic input] winreg.OpenKey -> HKEY key: HKEY An already open key, or any one of the predefined HKEY_* constants. sub_key: Py_UNICODE(accept={str, NoneType}) A string that identifies the sub_key to open. reserved: int = 0 A reserved integer that must be zero. Default is zero. access: REGSAM(c_default='KEY_READ') = winreg.KEY_READ An integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ. Opens the specified key. The result is a new handle to the specified key. If the function fails, an OSError exception is raised. [clinic start generated code]*/ static HKEY winreg_OpenKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, int reserved, REGSAM access) /*[clinic end generated code: output=a905f1b947f3ce85 input=098505ac36a9ae28]*/ { HKEY retKey; long rc; Py_BEGIN_ALLOW_THREADS rc = RegOpenKeyExW(key, sub_key, reserved, access, &retKey); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) { PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); return NULL; } return retKey; } /*[clinic input] winreg.OpenKeyEx = winreg.OpenKey Opens the specified key. The result is a new handle to the specified key. If the function fails, an OSError exception is raised. [clinic start generated code]*/ static HKEY winreg_OpenKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, int reserved, REGSAM access) /*[clinic end generated code: output=226042593b37e940 input=c6c4972af8622959]*/ { return winreg_OpenKey_impl(module, key, sub_key, reserved, access); } /*[clinic input] winreg.QueryInfoKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. / Returns information about a key. The result is a tuple of 3 items: An integer that identifies the number of sub keys this key has. An integer that identifies the number of values this key has. An integer that identifies when the key was last modified (if available) as 100's of nanoseconds since Jan 1, 1600. [clinic start generated code]*/ static PyObject * winreg_QueryInfoKey_impl(PyObject *module, HKEY key) /*[clinic end generated code: output=dc657b8356a4f438 input=c3593802390cde1f]*/ { long rc; DWORD nSubKeys, nValues; FILETIME ft; LARGE_INTEGER li; PyObject *l; PyObject *ret; if ((rc = RegQueryInfoKey(key, NULL, NULL, 0, &nSubKeys, NULL, NULL, &nValues, NULL, NULL, NULL, &ft)) != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; l = PyLong_FromLongLong(li.QuadPart); if (l == NULL) return NULL; ret = Py_BuildValue("iiO", nSubKeys, nValues, l); Py_DECREF(l); return ret; } /*[clinic input] winreg.QueryValue key: HKEY An already open key, or any one of the predefined HKEY_* constants. sub_key: Py_UNICODE(accept={str, NoneType}) 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. / Retrieves the unnamed value for a 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 since the underlying API call doesn't return the type, you'll probably be happier using QueryValueEx; this function is just here for completeness. [clinic start generated code]*/ static PyObject * winreg_QueryValue_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key) /*[clinic end generated code: output=2bb8d1e02c10d0b6 input=41cafbbf423b21d6]*/ { long rc; PyObject *retStr; wchar_t *retBuf; DWORD bufSize = 0; DWORD retSize = 0; wchar_t *tmp; rc = RegQueryValueW(key, sub_key, NULL, &retSize); if (rc == ERROR_MORE_DATA) retSize = 256; else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); bufSize = retSize; retBuf = (wchar_t *) PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); while (1) { retSize = bufSize; rc = RegQueryValueW(key, sub_key, retBuf, &retSize); if (rc != ERROR_MORE_DATA) break; bufSize *= 2; tmp = (wchar_t *) PyMem_Realloc(retBuf, bufSize); if (tmp == NULL) { PyMem_Free(retBuf); return PyErr_NoMemory(); } retBuf = tmp; } if (rc != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); } retStr = PyUnicode_FromWideChar(retBuf, wcslen(retBuf)); PyMem_Free(retBuf); return retStr; } /*[clinic input] winreg.QueryValueEx key: HKEY An already open key, or any one of the predefined HKEY_* constants. name: Py_UNICODE(accept={str, NoneType}) A string indicating the value to query. / Retrieves the type and value of a specified sub-key. Behaves mostly like QueryValue(), but also returns the type of the specified value name associated with the given open registry key. The return value is a tuple of the value and the type_id. [clinic start generated code]*/ static PyObject * winreg_QueryValueEx_impl(PyObject *module, HKEY key, Py_UNICODE *name) /*[clinic end generated code: output=5b4fa3e33d6d3e8f input=cf366cada4836891]*/ { long rc; BYTE *retBuf, *tmp; DWORD bufSize = 0, retSize; DWORD typ; PyObject *obData; PyObject *result; rc = RegQueryValueExW(key, name, NULL, NULL, NULL, &bufSize); if (rc == ERROR_MORE_DATA) bufSize = 256; else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); retBuf = (BYTE *)PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); while (1) { retSize = bufSize; rc = RegQueryValueExW(key, name, NULL, &typ, (BYTE *)retBuf, &retSize); if (rc != ERROR_MORE_DATA) break; bufSize *= 2; tmp = (char *) PyMem_Realloc(retBuf, bufSize); if (tmp == NULL) { PyMem_Free(retBuf); return PyErr_NoMemory(); } retBuf = tmp; } if (rc != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); } obData = Reg2Py(retBuf, bufSize, typ); PyMem_Free(retBuf); if (obData == NULL) return NULL; result = Py_BuildValue("Oi", obData, typ); Py_DECREF(obData); return result; } /*[clinic input] winreg.SaveKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. file_name: Py_UNICODE The name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file allocation table (FAT) file systems by the LoadKey(), ReplaceKey() or RestoreKey() methods. / Saves the specified key, and all its subkeys to the specified file. If key represents a key on a remote computer, the path described by file_name is relative to the remote computer. The caller of this method must possess the SeBackupPrivilege security privilege. This function passes NULL for security_attributes to the API. [clinic start generated code]*/ static PyObject * winreg_SaveKey_impl(PyObject *module, HKEY key, Py_UNICODE *file_name) /*[clinic end generated code: output=1dda1502bd4c30d8 input=da735241f91ac7a2]*/ { LPSECURITY_ATTRIBUTES pSA = NULL; long rc; /* One day we may get security into the core? if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) return NULL; */ Py_BEGIN_ALLOW_THREADS rc = RegSaveKeyW(key, file_name, pSA ); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); Py_RETURN_NONE; } /*[clinic input] winreg.SetValue key: HKEY An already open key, or any one of the predefined HKEY_* constants. sub_key: Py_UNICODE(accept={str, NoneType}) A string that names the subkey with which the value is associated. type: DWORD An integer that specifies the type of the data. Currently this must be REG_SZ, meaning only strings are supported. value: Py_UNICODE(zeroes=True) A string that specifies the new value. / Associates a value with a specified key. If the key specified by the sub_key parameter does not exist, the SetValue function creates it. Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry to help the registry perform efficiently. The key identified by the key parameter must have been opened with KEY_SET_VALUE access. [clinic start generated code]*/ static PyObject * winreg_SetValue_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, DWORD type, Py_UNICODE *value, Py_ssize_clean_t value_length) /*[clinic end generated code: output=1e31931174820631 input=2cd2adab79339c53]*/ { long rc; if (type != REG_SZ) { PyErr_SetString(PyExc_TypeError, "Type must be winreg.REG_SZ"); return NULL; } Py_BEGIN_ALLOW_THREADS rc = RegSetValueW(key, sub_key, REG_SZ, value, value_length+1); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); Py_RETURN_NONE; } /*[clinic input] winreg.SetValueEx key: HKEY An already open key, or any one of the predefined HKEY_* constants. value_name: Py_UNICODE(accept={str, NoneType}) A string containing the name of the value to set, or None. reserved: object Can be anything - zero is always passed to the API. type: DWORD An integer that specifies the type of the data, one of: REG_BINARY -- Binary data in any form. REG_DWORD -- A 32-bit number. REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format. Equivalent to REG_DWORD REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format. REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references to environment variables (for example, %PATH%). REG_LINK -- A Unicode symbolic link. REG_MULTI_SZ -- A sequence of null-terminated strings, terminated by two null characters. Note that Python handles this termination automatically. REG_NONE -- No defined value type. REG_QWORD -- A 64-bit number. REG_QWORD_LITTLE_ENDIAN -- A 64-bit number in little-endian format. Equivalent to REG_QWORD. REG_RESOURCE_LIST -- A device-driver resource list. REG_SZ -- A null-terminated string. value: object A string that specifies the new value. / Stores data in the value field of an open registry key. This method can also set additional value and type information for the specified key. The key identified by the key parameter must have been opened with KEY_SET_VALUE access. To open the key, use the CreateKeyEx() or OpenKeyEx() methods. Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry to help the registry perform efficiently. [clinic start generated code]*/ static PyObject * winreg_SetValueEx_impl(PyObject *module, HKEY key, Py_UNICODE *value_name, PyObject *reserved, DWORD type, PyObject *value) /*[clinic end generated code: output=c88c8426b6c00ec7 input=900a9e3990bfb196]*/ { BYTE *data; DWORD len; LONG rc; if (!Py2Reg(value, type, &data, &len)) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "Could not convert the data to the specified type."); return NULL; } Py_BEGIN_ALLOW_THREADS rc = RegSetValueExW(key, value_name, 0, type, data, len); Py_END_ALLOW_THREADS PyMem_DEL(data); if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValueEx"); Py_RETURN_NONE; } /*[clinic input] winreg.DisableReflectionKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. / Disables registry reflection for 32bit processes running on a 64bit OS. Will generally raise NotImplemented if executed on a 32bit OS. If the key is not on the reflection list, the function succeeds but has no effect. Disabling reflection for a key does not affect reflection of any subkeys. [clinic start generated code]*/ static PyObject * winreg_DisableReflectionKey_impl(PyObject *module, HKEY key) /*[clinic end generated code: output=830cce504cc764b4 input=a6c9e5ca5410193c]*/ { HMODULE hMod; typedef LONG (WINAPI *RDRKFunc)(HKEY); RDRKFunc pfn = NULL; LONG rc; /* Only available on 64bit platforms, so we must load it dynamically.*/ hMod = GetModuleHandleW(L"advapi32.dll"); if (hMod) pfn = (RDRKFunc)GetProcAddress(hMod, "RegDisableReflectionKey"); if (!pfn) { PyErr_SetString(PyExc_NotImplementedError, "not implemented on this platform"); return NULL; } Py_BEGIN_ALLOW_THREADS rc = (*pfn)(key); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegDisableReflectionKey"); Py_RETURN_NONE; } /*[clinic input] winreg.EnableReflectionKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. / Restores registry reflection for the specified disabled key. Will generally raise NotImplemented if executed on a 32bit OS. Restoring reflection for a key does not affect reflection of any subkeys. [clinic start generated code]*/ static PyObject * winreg_EnableReflectionKey_impl(PyObject *module, HKEY key) /*[clinic end generated code: output=86fa1385fdd9ce57 input=7748abbacd1e166a]*/ { HMODULE hMod; typedef LONG (WINAPI *RERKFunc)(HKEY); RERKFunc pfn = NULL; LONG rc; /* Only available on 64bit platforms, so we must load it dynamically.*/ hMod = GetModuleHandleW(L"advapi32.dll"); if (hMod) pfn = (RERKFunc)GetProcAddress(hMod, "RegEnableReflectionKey"); if (!pfn) { PyErr_SetString(PyExc_NotImplementedError, "not implemented on this platform"); return NULL; } Py_BEGIN_ALLOW_THREADS rc = (*pfn)(key); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnableReflectionKey"); Py_RETURN_NONE; } /*[clinic input] winreg.QueryReflectionKey key: HKEY An already open key, or any one of the predefined HKEY_* constants. / Returns the reflection state for the specified key as a bool. Will generally raise NotImplemented if executed on a 32bit OS. [clinic start generated code]*/ static PyObject * winreg_QueryReflectionKey_impl(PyObject *module, HKEY key) /*[clinic end generated code: output=4e774af288c3ebb9 input=9f325eacb5a65d88]*/ { HMODULE hMod; typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); RQRKFunc pfn = NULL; BOOL result; LONG rc; /* Only available on 64bit platforms, so we must load it dynamically.*/ hMod = GetModuleHandleW(L"advapi32.dll"); if (hMod) pfn = (RQRKFunc)GetProcAddress(hMod, "RegQueryReflectionKey"); if (!pfn) { PyErr_SetString(PyExc_NotImplementedError, "not implemented on this platform"); return NULL; } Py_BEGIN_ALLOW_THREADS rc = (*pfn)(key, &result); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryReflectionKey"); return PyBool_FromLong(result); } static struct PyMethodDef winreg_methods[] = { WINREG_CLOSEKEY_METHODDEF WINREG_CONNECTREGISTRY_METHODDEF WINREG_CREATEKEY_METHODDEF WINREG_CREATEKEYEX_METHODDEF WINREG_DELETEKEY_METHODDEF WINREG_DELETEKEYEX_METHODDEF WINREG_DELETEVALUE_METHODDEF WINREG_DISABLEREFLECTIONKEY_METHODDEF WINREG_ENABLEREFLECTIONKEY_METHODDEF WINREG_ENUMKEY_METHODDEF WINREG_ENUMVALUE_METHODDEF WINREG_EXPANDENVIRONMENTSTRINGS_METHODDEF WINREG_FLUSHKEY_METHODDEF WINREG_LOADKEY_METHODDEF WINREG_OPENKEY_METHODDEF WINREG_OPENKEYEX_METHODDEF WINREG_QUERYVALUE_METHODDEF WINREG_QUERYVALUEEX_METHODDEF WINREG_QUERYINFOKEY_METHODDEF WINREG_QUERYREFLECTIONKEY_METHODDEF WINREG_SAVEKEY_METHODDEF WINREG_SETVALUE_METHODDEF WINREG_SETVALUEEX_METHODDEF NULL, }; static void insint(PyObject * d, char * name, long value) { PyObject *v = PyLong_FromLong(value); if (!v || PyDict_SetItemString(d, name, v)) PyErr_Clear(); Py_XDECREF(v); } #define ADD_INT(val) insint(d, #val, val) static void inskey(PyObject * d, char * name, HKEY key) { PyObject *v = PyLong_FromVoidPtr(key); if (!v || PyDict_SetItemString(d, name, v)) PyErr_Clear(); Py_XDECREF(v); } #define ADD_KEY(val) inskey(d, #val, val) static struct PyModuleDef winregmodule = { PyModuleDef_HEAD_INIT, "winreg", module_doc, -1, winreg_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_winreg(void) { PyObject *m, *d; m = PyModule_Create(&winregmodule); if (m == NULL) return NULL; d = PyModule_GetDict(m); PyHKEY_Type.tp_doc = PyHKEY_doc; if (PyType_Ready(&PyHKEY_Type) < 0) return NULL; Py_INCREF(&PyHKEY_Type); if (PyDict_SetItemString(d, "HKEYType", (PyObject *)&PyHKEY_Type) != 0) return NULL; Py_INCREF(PyExc_OSError); if (PyDict_SetItemString(d, "error", PyExc_OSError) != 0) return NULL; /* Add the relevant constants */ ADD_KEY(HKEY_CLASSES_ROOT); ADD_KEY(HKEY_CURRENT_USER); ADD_KEY(HKEY_LOCAL_MACHINE); ADD_KEY(HKEY_USERS); ADD_KEY(HKEY_PERFORMANCE_DATA); #ifdef HKEY_CURRENT_CONFIG ADD_KEY(HKEY_CURRENT_CONFIG); #endif #ifdef HKEY_DYN_DATA ADD_KEY(HKEY_DYN_DATA); #endif ADD_INT(KEY_QUERY_VALUE); ADD_INT(KEY_SET_VALUE); ADD_INT(KEY_CREATE_SUB_KEY); ADD_INT(KEY_ENUMERATE_SUB_KEYS); ADD_INT(KEY_NOTIFY); ADD_INT(KEY_CREATE_LINK); ADD_INT(KEY_READ); ADD_INT(KEY_WRITE); ADD_INT(KEY_EXECUTE); ADD_INT(KEY_ALL_ACCESS); #ifdef KEY_WOW64_64KEY ADD_INT(KEY_WOW64_64KEY); #endif #ifdef KEY_WOW64_32KEY ADD_INT(KEY_WOW64_32KEY); #endif ADD_INT(REG_OPTION_RESERVED); ADD_INT(REG_OPTION_NON_VOLATILE); ADD_INT(REG_OPTION_VOLATILE); ADD_INT(REG_OPTION_CREATE_LINK); ADD_INT(REG_OPTION_BACKUP_RESTORE); ADD_INT(REG_OPTION_OPEN_LINK); ADD_INT(REG_LEGAL_OPTION); ADD_INT(REG_CREATED_NEW_KEY); ADD_INT(REG_OPENED_EXISTING_KEY); ADD_INT(REG_WHOLE_HIVE_VOLATILE); ADD_INT(REG_REFRESH_HIVE); ADD_INT(REG_NO_LAZY_FLUSH); ADD_INT(REG_NOTIFY_CHANGE_NAME); ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); ADD_INT(REG_NOTIFY_CHANGE_SECURITY); ADD_INT(REG_LEGAL_CHANGE_FILTER); ADD_INT(REG_NONE); ADD_INT(REG_SZ); ADD_INT(REG_EXPAND_SZ); ADD_INT(REG_BINARY); ADD_INT(REG_DWORD); ADD_INT(REG_DWORD_LITTLE_ENDIAN); ADD_INT(REG_DWORD_BIG_ENDIAN); ADD_INT(REG_QWORD); ADD_INT(REG_QWORD_LITTLE_ENDIAN); ADD_INT(REG_LINK); ADD_INT(REG_MULTI_SZ); ADD_INT(REG_RESOURCE_LIST); ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); return m; }
62,702
1,978
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/invalid_parameter_handler.c
#ifdef _MSC_VER #if _MSC_VER >= 1900 /* pyconfig.h uses this function in the _Py_BEGIN/END_SUPPRESS_IPH * macros. It does not need to be defined when building using MSVC * earlier than 14.0 (_MSC_VER == 1900). */ static void __cdecl _silent_invalid_parameter_handler(wchar_t const* expression, wchar_t const* function, wchar_t const* file, unsigned int line, uintptr_t pReserved) { } _invalid_parameter_handler _Py_silent_invalid_parameter_handler = _silent_invalid_parameter_handler; #endif #endif
727
22
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/clinic/winsound.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ /*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(winsound_PlaySound__doc__, "PlaySound($module, /, sound, flags)\n" "--\n" "\n" "A wrapper around the Windows PlaySound API.\n" "\n" " sound\n" " The sound to play; a filename, data, or None.\n" " flags\n" " Flag values, ored together. See module documentation."); #define WINSOUND_PLAYSOUND_METHODDEF \ {"PlaySound", (PyCFunction)winsound_PlaySound, METH_FASTCALL, winsound_PlaySound__doc__}, static PyObject * winsound_PlaySound_impl(PyObject *module, PyObject *sound, int flags); static PyObject * winsound_PlaySound(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"sound", "flags", NULL}; static _PyArg_Parser _parser = {"Oi:PlaySound", _keywords, 0}; PyObject *sound; int flags; if (!_PyArg_ParseStack(args, nargs, kwnames, &_parser, &sound, &flags)) { goto exit; } return_value = winsound_PlaySound_impl(module, sound, flags); exit: return return_value; } PyDoc_STRVAR(winsound_Beep__doc__, "Beep($module, /, frequency, duration)\n" "--\n" "\n" "A wrapper around the Windows Beep API.\n" "\n" " frequency\n" " Frequency of the sound in hertz.\n" " Must be in the range 37 through 32,767.\n" " duration\n" " How long the sound should play, in milliseconds."); #define WINSOUND_BEEP_METHODDEF \ {"Beep", (PyCFunction)winsound_Beep, METH_FASTCALL, winsound_Beep__doc__}, static PyObject * winsound_Beep_impl(PyObject *module, int frequency, int duration); static PyObject * winsound_Beep(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"frequency", "duration", NULL}; static _PyArg_Parser _parser = {"ii:Beep", _keywords, 0}; int frequency; int duration; if (!_PyArg_ParseStack(args, nargs, kwnames, &_parser, &frequency, &duration)) { goto exit; } return_value = winsound_Beep_impl(module, frequency, duration); exit: return return_value; } PyDoc_STRVAR(winsound_MessageBeep__doc__, "MessageBeep($module, /, type=MB_OK)\n" "--\n" "\n" "Call Windows MessageBeep(x).\n" "\n" "x defaults to MB_OK."); #define WINSOUND_MESSAGEBEEP_METHODDEF \ {"MessageBeep", (PyCFunction)winsound_MessageBeep, METH_FASTCALL, winsound_MessageBeep__doc__}, static PyObject * winsound_MessageBeep_impl(PyObject *module, int type); static PyObject * winsound_MessageBeep(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"type", NULL}; static _PyArg_Parser _parser = {"|i:MessageBeep", _keywords, 0}; int type = MB_OK; if (!_PyArg_ParseStack(args, nargs, kwnames, &_parser, &type)) { goto exit; } return_value = winsound_MessageBeep_impl(module, type); exit: return return_value; } /*[clinic end generated code: output=bfe16b2b8b490cb1 input=a9049054013a1b77]*/
3,955
118
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/clinic/winreg.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ /*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(winreg_HKEYType_Close__doc__, "Close($self, /)\n" "--\n" "\n" "Closes the underlying Windows handle.\n" "\n" "If the handle is already closed, no error is raised."); #define WINREG_HKEYTYPE_CLOSE_METHODDEF \ {"Close", (PyCFunction)winreg_HKEYType_Close, METH_NOARGS, winreg_HKEYType_Close__doc__}, static PyObject * winreg_HKEYType_Close_impl(PyHKEYObject *self); static PyObject * winreg_HKEYType_Close(PyHKEYObject *self, PyObject *Py_UNUSED(ignored)) { return winreg_HKEYType_Close_impl(self); } PyDoc_STRVAR(winreg_HKEYType_Detach__doc__, "Detach($self, /)\n" "--\n" "\n" "Detaches the Windows handle from the handle object.\n" "\n" "The result is the value of the handle before it is detached. If the\n" "handle is already detached, this will return zero.\n" "\n" "After calling this function, the handle is effectively invalidated,\n" "but the handle is not closed. You would call this function when you\n" "need the underlying win32 handle to exist beyond the lifetime of the\n" "handle object."); #define WINREG_HKEYTYPE_DETACH_METHODDEF \ {"Detach", (PyCFunction)winreg_HKEYType_Detach, METH_NOARGS, winreg_HKEYType_Detach__doc__}, static PyObject * winreg_HKEYType_Detach_impl(PyHKEYObject *self); static PyObject * winreg_HKEYType_Detach(PyHKEYObject *self, PyObject *Py_UNUSED(ignored)) { return winreg_HKEYType_Detach_impl(self); } PyDoc_STRVAR(winreg_HKEYType___enter____doc__, "__enter__($self, /)\n" "--\n" "\n"); #define WINREG_HKEYTYPE___ENTER___METHODDEF \ {"__enter__", (PyCFunction)winreg_HKEYType___enter__, METH_NOARGS, winreg_HKEYType___enter____doc__}, static PyHKEYObject * winreg_HKEYType___enter___impl(PyHKEYObject *self); static PyObject * winreg_HKEYType___enter__(PyHKEYObject *self, PyObject *Py_UNUSED(ignored)) { PyObject *return_value = NULL; PyHKEYObject *_return_value; _return_value = winreg_HKEYType___enter___impl(self); return_value = (PyObject *)_return_value; return return_value; } PyDoc_STRVAR(winreg_HKEYType___exit____doc__, "__exit__($self, /, exc_type, exc_value, traceback)\n" "--\n" "\n"); #define WINREG_HKEYTYPE___EXIT___METHODDEF \ {"__exit__", (PyCFunction)winreg_HKEYType___exit__, METH_FASTCALL, winreg_HKEYType___exit____doc__}, static PyObject * winreg_HKEYType___exit___impl(PyHKEYObject *self, PyObject *exc_type, PyObject *exc_value, PyObject *traceback); static PyObject * winreg_HKEYType___exit__(PyHKEYObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"exc_type", "exc_value", "traceback", NULL}; static _PyArg_Parser _parser = {"OOO:__exit__", _keywords, 0}; PyObject *exc_type; PyObject *exc_value; PyObject *traceback; if (!_PyArg_ParseStack(args, nargs, kwnames, &_parser, &exc_type, &exc_value, &traceback)) { goto exit; } return_value = winreg_HKEYType___exit___impl(self, exc_type, exc_value, traceback); exit: return return_value; } PyDoc_STRVAR(winreg_CloseKey__doc__, "CloseKey($module, hkey, /)\n" "--\n" "\n" "Closes a previously opened registry key.\n" "\n" " hkey\n" " A previously opened key.\n" "\n" "Note that if the key is not closed using this method, it will be\n" "closed when the hkey object is destroyed by Python."); #define WINREG_CLOSEKEY_METHODDEF \ {"CloseKey", (PyCFunction)winreg_CloseKey, METH_O, winreg_CloseKey__doc__}, PyDoc_STRVAR(winreg_ConnectRegistry__doc__, "ConnectRegistry($module, computer_name, key, /)\n" "--\n" "\n" "Establishes a connection to the registry on another computer.\n" "\n" " computer_name\n" " The name of the remote computer, of the form r\"\\\\computername\". If\n" " None, the local computer is used.\n" " key\n" " The predefined key to connect to.\n" "\n" "The return value is the handle of the opened key.\n" "If the function fails, an OSError exception is raised."); #define WINREG_CONNECTREGISTRY_METHODDEF \ {"ConnectRegistry", (PyCFunction)winreg_ConnectRegistry, METH_VARARGS, winreg_ConnectRegistry__doc__}, static HKEY winreg_ConnectRegistry_impl(PyObject *module, Py_UNICODE *computer_name, HKEY key); static PyObject * winreg_ConnectRegistry(PyObject *module, PyObject *args) { PyObject *return_value = NULL; Py_UNICODE *computer_name; HKEY key; HKEY _return_value; if (!PyArg_ParseTuple(args, "ZO&:ConnectRegistry", &computer_name, clinic_HKEY_converter, &key)) { goto exit; } _return_value = winreg_ConnectRegistry_impl(module, computer_name, key); if (_return_value == NULL) { goto exit; } return_value = PyHKEY_FromHKEY(_return_value); exit: return return_value; } PyDoc_STRVAR(winreg_CreateKey__doc__, "CreateKey($module, key, sub_key, /)\n" "--\n" "\n" "Creates or opens the specified key.\n" "\n" " key\n" " An already open key, or one of the predefined HKEY_* constants.\n" " sub_key\n" " The name of the key this method opens or creates.\n" "\n" "If key is one of the predefined keys, sub_key may be None. In that case,\n" "the handle returned is the same key handle passed in to the function.\n" "\n" "If the key already exists, this function opens the existing key.\n" "\n" "The return value is the handle of the opened key.\n" "If the function fails, an OSError exception is raised."); #define WINREG_CREATEKEY_METHODDEF \ {"CreateKey", (PyCFunction)winreg_CreateKey, METH_VARARGS, winreg_CreateKey__doc__}, static HKEY winreg_CreateKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key); static PyObject * winreg_CreateKey(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *sub_key; HKEY _return_value; if (!PyArg_ParseTuple(args, "O&Z:CreateKey", clinic_HKEY_converter, &key, &sub_key)) { goto exit; } _return_value = winreg_CreateKey_impl(module, key, sub_key); if (_return_value == NULL) { goto exit; } return_value = PyHKEY_FromHKEY(_return_value); exit: return return_value; } PyDoc_STRVAR(winreg_CreateKeyEx__doc__, "CreateKeyEx($module, /, key, sub_key, reserved=0,\n" " access=winreg.KEY_WRITE)\n" "--\n" "\n" "Creates or opens the specified key.\n" "\n" " key\n" " An already open key, or one of the predefined HKEY_* constants.\n" " sub_key\n" " The name of the key this method opens or creates.\n" " reserved\n" " A reserved integer, and must be zero. Default is zero.\n" " access\n" " An integer that specifies an access mask that describes the\n" " desired security access for the key. Default is KEY_WRITE.\n" "\n" "If key is one of the predefined keys, sub_key may be None. In that case,\n" "the handle returned is the same key handle passed in to the function.\n" "\n" "If the key already exists, this function opens the existing key\n" "\n" "The return value is the handle of the opened key.\n" "If the function fails, an OSError exception is raised."); #define WINREG_CREATEKEYEX_METHODDEF \ {"CreateKeyEx", (PyCFunction)winreg_CreateKeyEx, METH_FASTCALL, winreg_CreateKeyEx__doc__}, static HKEY winreg_CreateKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, int reserved, REGSAM access); static PyObject * winreg_CreateKeyEx(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"key", "sub_key", "reserved", "access", NULL}; static _PyArg_Parser _parser = {"O&Z|ii:CreateKeyEx", _keywords, 0}; HKEY key; Py_UNICODE *sub_key; int reserved = 0; REGSAM access = KEY_WRITE; HKEY _return_value; if (!_PyArg_ParseStack(args, nargs, kwnames, &_parser, clinic_HKEY_converter, &key, &sub_key, &reserved, &access)) { goto exit; } _return_value = winreg_CreateKeyEx_impl(module, key, sub_key, reserved, access); if (_return_value == NULL) { goto exit; } return_value = PyHKEY_FromHKEY(_return_value); exit: return return_value; } PyDoc_STRVAR(winreg_DeleteKey__doc__, "DeleteKey($module, key, sub_key, /)\n" "--\n" "\n" "Deletes the specified key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " sub_key\n" " A string that must be the name of a subkey of the key identified by\n" " the key parameter. This value must not be None, and the key may not\n" " have subkeys.\n" "\n" "This method can not delete keys with subkeys.\n" "\n" "If the function succeeds, the entire key, including all of its values,\n" "is removed. If the function fails, an OSError exception is raised."); #define WINREG_DELETEKEY_METHODDEF \ {"DeleteKey", (PyCFunction)winreg_DeleteKey, METH_VARARGS, winreg_DeleteKey__doc__}, static PyObject * winreg_DeleteKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key); static PyObject * winreg_DeleteKey(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *sub_key; if (!PyArg_ParseTuple(args, "O&u:DeleteKey", clinic_HKEY_converter, &key, &sub_key)) { goto exit; } return_value = winreg_DeleteKey_impl(module, key, sub_key); exit: return return_value; } PyDoc_STRVAR(winreg_DeleteKeyEx__doc__, "DeleteKeyEx($module, /, key, sub_key, access=winreg.KEY_WOW64_64KEY,\n" " reserved=0)\n" "--\n" "\n" "Deletes the specified key (64-bit OS only).\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " sub_key\n" " A string that must be the name of a subkey of the key identified by\n" " the key parameter. This value must not be None, and the key may not\n" " have subkeys.\n" " access\n" " An integer that specifies an access mask that describes the\n" " desired security access for the key. Default is KEY_WOW64_64KEY.\n" " reserved\n" " A reserved integer, and must be zero. Default is zero.\n" "\n" "This method can not delete keys with subkeys.\n" "\n" "If the function succeeds, the entire key, including all of its values,\n" "is removed. If the function fails, an OSError exception is raised.\n" "On unsupported Windows versions, NotImplementedError is raised."); #define WINREG_DELETEKEYEX_METHODDEF \ {"DeleteKeyEx", (PyCFunction)winreg_DeleteKeyEx, METH_FASTCALL, winreg_DeleteKeyEx__doc__}, static PyObject * winreg_DeleteKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, REGSAM access, int reserved); static PyObject * winreg_DeleteKeyEx(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"key", "sub_key", "access", "reserved", NULL}; static _PyArg_Parser _parser = {"O&u|ii:DeleteKeyEx", _keywords, 0}; HKEY key; Py_UNICODE *sub_key; REGSAM access = /*wut*/ -1 /* KEY_WOW64_64KEY */; int reserved = 0; if (!_PyArg_ParseStack(args, nargs, kwnames, &_parser, clinic_HKEY_converter, &key, &sub_key, &access, &reserved)) { goto exit; } return_value = winreg_DeleteKeyEx_impl(module, key, sub_key, access, reserved); exit: return return_value; } PyDoc_STRVAR(winreg_DeleteValue__doc__, "DeleteValue($module, key, value, /)\n" "--\n" "\n" "Removes a named value from a registry key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " value\n" " A string that identifies the value to remove."); #define WINREG_DELETEVALUE_METHODDEF \ {"DeleteValue", (PyCFunction)winreg_DeleteValue, METH_VARARGS, winreg_DeleteValue__doc__}, static PyObject * winreg_DeleteValue_impl(PyObject *module, HKEY key, Py_UNICODE *value); static PyObject * winreg_DeleteValue(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *value; if (!PyArg_ParseTuple(args, "O&Z:DeleteValue", clinic_HKEY_converter, &key, &value)) { goto exit; } return_value = winreg_DeleteValue_impl(module, key, value); exit: return return_value; } PyDoc_STRVAR(winreg_EnumKey__doc__, "EnumKey($module, key, index, /)\n" "--\n" "\n" "Enumerates subkeys of an open registry key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " index\n" " An integer that identifies the index of the key to retrieve.\n" "\n" "The function retrieves the name of one subkey each time it is called.\n" "It is typically called repeatedly until an OSError exception is\n" "raised, indicating no more values are available."); #define WINREG_ENUMKEY_METHODDEF \ {"EnumKey", (PyCFunction)winreg_EnumKey, METH_VARARGS, winreg_EnumKey__doc__}, static PyObject * winreg_EnumKey_impl(PyObject *module, HKEY key, int index); static PyObject * winreg_EnumKey(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; int index; if (!PyArg_ParseTuple(args, "O&i:EnumKey", clinic_HKEY_converter, &key, &index)) { goto exit; } return_value = winreg_EnumKey_impl(module, key, index); exit: return return_value; } PyDoc_STRVAR(winreg_EnumValue__doc__, "EnumValue($module, key, index, /)\n" "--\n" "\n" "Enumerates values of an open registry key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " index\n" " An integer that identifies the index of the value to retrieve.\n" "\n" "The function retrieves the name of one subkey each time it is called.\n" "It is typically called repeatedly, until an OSError exception\n" "is raised, indicating no more values.\n" "\n" "The result is a tuple of 3 items:\n" " value_name\n" " A string that identifies the value.\n" " value_data\n" " An object that holds the value data, and whose type depends\n" " on the underlying registry type.\n" " data_type\n" " An integer that identifies the type of the value data."); #define WINREG_ENUMVALUE_METHODDEF \ {"EnumValue", (PyCFunction)winreg_EnumValue, METH_VARARGS, winreg_EnumValue__doc__}, static PyObject * winreg_EnumValue_impl(PyObject *module, HKEY key, int index); static PyObject * winreg_EnumValue(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; int index; if (!PyArg_ParseTuple(args, "O&i:EnumValue", clinic_HKEY_converter, &key, &index)) { goto exit; } return_value = winreg_EnumValue_impl(module, key, index); exit: return return_value; } PyDoc_STRVAR(winreg_ExpandEnvironmentStrings__doc__, "ExpandEnvironmentStrings($module, string, /)\n" "--\n" "\n" "Expand environment vars."); #define WINREG_EXPANDENVIRONMENTSTRINGS_METHODDEF \ {"ExpandEnvironmentStrings", (PyCFunction)winreg_ExpandEnvironmentStrings, METH_O, winreg_ExpandEnvironmentStrings__doc__}, static PyObject * winreg_ExpandEnvironmentStrings_impl(PyObject *module, Py_UNICODE *string); static PyObject * winreg_ExpandEnvironmentStrings(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; Py_UNICODE *string; if (!PyArg_Parse(arg, "u:ExpandEnvironmentStrings", &string)) { goto exit; } return_value = winreg_ExpandEnvironmentStrings_impl(module, string); exit: return return_value; } PyDoc_STRVAR(winreg_FlushKey__doc__, "FlushKey($module, key, /)\n" "--\n" "\n" "Writes all the attributes of a key to the registry.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" "\n" "It is not necessary to call FlushKey to change a key. Registry changes\n" "are flushed to disk by the registry using its lazy flusher. Registry\n" "changes are also flushed to disk at system shutdown. Unlike\n" "CloseKey(), the FlushKey() method returns only when all the data has\n" "been written to the registry.\n" "\n" "An application should only call FlushKey() if it requires absolute\n" "certainty that registry changes are on disk. If you don\'t know whether\n" "a FlushKey() call is required, it probably isn\'t."); #define WINREG_FLUSHKEY_METHODDEF \ {"FlushKey", (PyCFunction)winreg_FlushKey, METH_O, winreg_FlushKey__doc__}, static PyObject * winreg_FlushKey_impl(PyObject *module, HKEY key); static PyObject * winreg_FlushKey(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; HKEY key; if (!PyArg_Parse(arg, "O&:FlushKey", clinic_HKEY_converter, &key)) { goto exit; } return_value = winreg_FlushKey_impl(module, key); exit: return return_value; } PyDoc_STRVAR(winreg_LoadKey__doc__, "LoadKey($module, key, sub_key, file_name, /)\n" "--\n" "\n" "Insert data into the registry from a file.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " sub_key\n" " A string that identifies the sub-key to load.\n" " file_name\n" " The name of the file to load registry data from. This file must\n" " have been created with the SaveKey() function. Under the file\n" " allocation table (FAT) file system, the filename may not have an\n" " extension.\n" "\n" "Creates a subkey under the specified key and stores registration\n" "information from a specified file into that subkey.\n" "\n" "A call to LoadKey() fails if the calling process does not have the\n" "SE_RESTORE_PRIVILEGE privilege.\n" "\n" "If key is a handle returned by ConnectRegistry(), then the path\n" "specified in fileName is relative to the remote computer.\n" "\n" "The MSDN docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE\n" "tree."); #define WINREG_LOADKEY_METHODDEF \ {"LoadKey", (PyCFunction)winreg_LoadKey, METH_VARARGS, winreg_LoadKey__doc__}, static PyObject * winreg_LoadKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, Py_UNICODE *file_name); static PyObject * winreg_LoadKey(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *sub_key; Py_UNICODE *file_name; if (!PyArg_ParseTuple(args, "O&uu:LoadKey", clinic_HKEY_converter, &key, &sub_key, &file_name)) { goto exit; } return_value = winreg_LoadKey_impl(module, key, sub_key, file_name); exit: return return_value; } PyDoc_STRVAR(winreg_OpenKey__doc__, "OpenKey($module, /, key, sub_key, reserved=0, access=winreg.KEY_READ)\n" "--\n" "\n" "Opens the specified key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " sub_key\n" " A string that identifies the sub_key to open.\n" " reserved\n" " A reserved integer that must be zero. Default is zero.\n" " access\n" " An integer that specifies an access mask that describes the desired\n" " security access for the key. Default is KEY_READ.\n" "\n" "The result is a new handle to the specified key.\n" "If the function fails, an OSError exception is raised."); #define WINREG_OPENKEY_METHODDEF \ {"OpenKey", (PyCFunction)winreg_OpenKey, METH_FASTCALL, winreg_OpenKey__doc__}, static HKEY winreg_OpenKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, int reserved, REGSAM access); static PyObject * winreg_OpenKey(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"key", "sub_key", "reserved", "access", NULL}; static _PyArg_Parser _parser = {"O&Z|ii:OpenKey", _keywords, 0}; HKEY key; Py_UNICODE *sub_key; int reserved = 0; REGSAM access = KEY_READ; HKEY _return_value; if (!_PyArg_ParseStack(args, nargs, kwnames, &_parser, clinic_HKEY_converter, &key, &sub_key, &reserved, &access)) { goto exit; } _return_value = winreg_OpenKey_impl(module, key, sub_key, reserved, access); if (_return_value == NULL) { goto exit; } return_value = PyHKEY_FromHKEY(_return_value); exit: return return_value; } PyDoc_STRVAR(winreg_OpenKeyEx__doc__, "OpenKeyEx($module, /, key, sub_key, reserved=0, access=winreg.KEY_READ)\n" "--\n" "\n" "Opens the specified key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " sub_key\n" " A string that identifies the sub_key to open.\n" " reserved\n" " A reserved integer that must be zero. Default is zero.\n" " access\n" " An integer that specifies an access mask that describes the desired\n" " security access for the key. Default is KEY_READ.\n" "\n" "The result is a new handle to the specified key.\n" "If the function fails, an OSError exception is raised."); #define WINREG_OPENKEYEX_METHODDEF \ {"OpenKeyEx", (PyCFunction)winreg_OpenKeyEx, METH_FASTCALL, winreg_OpenKeyEx__doc__}, static HKEY winreg_OpenKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, int reserved, REGSAM access); static PyObject * winreg_OpenKeyEx(PyObject *module, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"key", "sub_key", "reserved", "access", NULL}; static _PyArg_Parser _parser = {"O&Z|ii:OpenKeyEx", _keywords, 0}; HKEY key; Py_UNICODE *sub_key; int reserved = 0; REGSAM access = KEY_READ; HKEY _return_value; if (!_PyArg_ParseStack(args, nargs, kwnames, &_parser, clinic_HKEY_converter, &key, &sub_key, &reserved, &access)) { goto exit; } _return_value = winreg_OpenKeyEx_impl(module, key, sub_key, reserved, access); if (_return_value == NULL) { goto exit; } return_value = PyHKEY_FromHKEY(_return_value); exit: return return_value; } PyDoc_STRVAR(winreg_QueryInfoKey__doc__, "QueryInfoKey($module, key, /)\n" "--\n" "\n" "Returns information about a key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" "\n" "The result is a tuple of 3 items:\n" "An integer that identifies the number of sub keys this key has.\n" "An integer that identifies the number of values this key has.\n" "An integer that identifies when the key was last modified (if available)\n" "as 100\'s of nanoseconds since Jan 1, 1600."); #define WINREG_QUERYINFOKEY_METHODDEF \ {"QueryInfoKey", (PyCFunction)winreg_QueryInfoKey, METH_O, winreg_QueryInfoKey__doc__}, static PyObject * winreg_QueryInfoKey_impl(PyObject *module, HKEY key); static PyObject * winreg_QueryInfoKey(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; HKEY key; if (!PyArg_Parse(arg, "O&:QueryInfoKey", clinic_HKEY_converter, &key)) { goto exit; } return_value = winreg_QueryInfoKey_impl(module, key); exit: return return_value; } PyDoc_STRVAR(winreg_QueryValue__doc__, "QueryValue($module, key, sub_key, /)\n" "--\n" "\n" "Retrieves the unnamed value for a key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " sub_key\n" " A string that holds the name of the subkey with which the value\n" " is associated. If this parameter is None or empty, the function\n" " retrieves the value set by the SetValue() method for the key\n" " identified by key.\n" "\n" "Values in the registry have name, type, and data components. This method\n" "retrieves the data for a key\'s first value that has a NULL name.\n" "But since the underlying API call doesn\'t return the type, you\'ll\n" "probably be happier using QueryValueEx; this function is just here for\n" "completeness."); #define WINREG_QUERYVALUE_METHODDEF \ {"QueryValue", (PyCFunction)winreg_QueryValue, METH_VARARGS, winreg_QueryValue__doc__}, static PyObject * winreg_QueryValue_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key); static PyObject * winreg_QueryValue(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *sub_key; if (!PyArg_ParseTuple(args, "O&Z:QueryValue", clinic_HKEY_converter, &key, &sub_key)) { goto exit; } return_value = winreg_QueryValue_impl(module, key, sub_key); exit: return return_value; } PyDoc_STRVAR(winreg_QueryValueEx__doc__, "QueryValueEx($module, key, name, /)\n" "--\n" "\n" "Retrieves the type and value of a specified sub-key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " name\n" " A string indicating the value to query.\n" "\n" "Behaves mostly like QueryValue(), but also returns the type of the\n" "specified value name associated with the given open registry key.\n" "\n" "The return value is a tuple of the value and the type_id."); #define WINREG_QUERYVALUEEX_METHODDEF \ {"QueryValueEx", (PyCFunction)winreg_QueryValueEx, METH_VARARGS, winreg_QueryValueEx__doc__}, static PyObject * winreg_QueryValueEx_impl(PyObject *module, HKEY key, Py_UNICODE *name); static PyObject * winreg_QueryValueEx(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *name; if (!PyArg_ParseTuple(args, "O&Z:QueryValueEx", clinic_HKEY_converter, &key, &name)) { goto exit; } return_value = winreg_QueryValueEx_impl(module, key, name); exit: return return_value; } PyDoc_STRVAR(winreg_SaveKey__doc__, "SaveKey($module, key, file_name, /)\n" "--\n" "\n" "Saves the specified key, and all its subkeys to the specified file.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " file_name\n" " The name of the file to save registry data to. This file cannot\n" " already exist. If this filename includes an extension, it cannot be\n" " used on file allocation table (FAT) file systems by the LoadKey(),\n" " ReplaceKey() or RestoreKey() methods.\n" "\n" "If key represents a key on a remote computer, the path described by\n" "file_name is relative to the remote computer.\n" "\n" "The caller of this method must possess the SeBackupPrivilege\n" "security privilege. This function passes NULL for security_attributes\n" "to the API."); #define WINREG_SAVEKEY_METHODDEF \ {"SaveKey", (PyCFunction)winreg_SaveKey, METH_VARARGS, winreg_SaveKey__doc__}, static PyObject * winreg_SaveKey_impl(PyObject *module, HKEY key, Py_UNICODE *file_name); static PyObject * winreg_SaveKey(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *file_name; if (!PyArg_ParseTuple(args, "O&u:SaveKey", clinic_HKEY_converter, &key, &file_name)) { goto exit; } return_value = winreg_SaveKey_impl(module, key, file_name); exit: return return_value; } PyDoc_STRVAR(winreg_SetValue__doc__, "SetValue($module, key, sub_key, type, value, /)\n" "--\n" "\n" "Associates a value with a specified key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " sub_key\n" " A string that names the subkey with which the value is associated.\n" " type\n" " An integer that specifies the type of the data. Currently this must\n" " be REG_SZ, meaning only strings are supported.\n" " value\n" " A string that specifies the new value.\n" "\n" "If the key specified by the sub_key parameter does not exist, the\n" "SetValue function creates it.\n" "\n" "Value lengths are limited by available memory. Long values (more than\n" "2048 bytes) should be stored as files with the filenames stored in\n" "the configuration registry to help the registry perform efficiently.\n" "\n" "The key identified by the key parameter must have been opened with\n" "KEY_SET_VALUE access."); #define WINREG_SETVALUE_METHODDEF \ {"SetValue", (PyCFunction)winreg_SetValue, METH_VARARGS, winreg_SetValue__doc__}, static PyObject * winreg_SetValue_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key, DWORD type, Py_UNICODE *value, Py_ssize_clean_t value_length); static PyObject * winreg_SetValue(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *sub_key; DWORD type; Py_UNICODE *value; Py_ssize_clean_t value_length; if (!PyArg_ParseTuple(args, "O&Zku#:SetValue", clinic_HKEY_converter, &key, &sub_key, &type, &value, &value_length)) { goto exit; } return_value = winreg_SetValue_impl(module, key, sub_key, type, value, value_length); exit: return return_value; } PyDoc_STRVAR(winreg_SetValueEx__doc__, "SetValueEx($module, key, value_name, reserved, type, value, /)\n" "--\n" "\n" "Stores data in the value field of an open registry key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" " value_name\n" " A string containing the name of the value to set, or None.\n" " reserved\n" " Can be anything - zero is always passed to the API.\n" " type\n" " An integer that specifies the type of the data, one of:\n" " REG_BINARY -- Binary data in any form.\n" " REG_DWORD -- A 32-bit number.\n" " REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format. Equivalent to REG_DWORD\n" " REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format.\n" " REG_EXPAND_SZ -- A null-terminated string that contains unexpanded\n" " references to environment variables (for example,\n" " %PATH%).\n" " REG_LINK -- A Unicode symbolic link.\n" " REG_MULTI_SZ -- A sequence of null-terminated strings, terminated\n" " by two null characters. Note that Python handles\n" " this termination automatically.\n" " REG_NONE -- No defined value type.\n" " REG_QWORD -- A 64-bit number.\n" " REG_QWORD_LITTLE_ENDIAN -- A 64-bit number in little-endian format. Equivalent to REG_QWORD.\n" " REG_RESOURCE_LIST -- A device-driver resource list.\n" " REG_SZ -- A null-terminated string.\n" " value\n" " A string that specifies the new value.\n" "\n" "This method can also set additional value and type information for the\n" "specified key. The key identified by the key parameter must have been\n" "opened with KEY_SET_VALUE access.\n" "\n" "To open the key, use the CreateKeyEx() or OpenKeyEx() methods.\n" "\n" "Value lengths are limited by available memory. Long values (more than\n" "2048 bytes) should be stored as files with the filenames stored in\n" "the configuration registry to help the registry perform efficiently."); #define WINREG_SETVALUEEX_METHODDEF \ {"SetValueEx", (PyCFunction)winreg_SetValueEx, METH_VARARGS, winreg_SetValueEx__doc__}, static PyObject * winreg_SetValueEx_impl(PyObject *module, HKEY key, Py_UNICODE *value_name, PyObject *reserved, DWORD type, PyObject *value); static PyObject * winreg_SetValueEx(PyObject *module, PyObject *args) { PyObject *return_value = NULL; HKEY key; Py_UNICODE *value_name; PyObject *reserved; DWORD type; PyObject *value; if (!PyArg_ParseTuple(args, "O&ZOkO:SetValueEx", clinic_HKEY_converter, &key, &value_name, &reserved, &type, &value)) { goto exit; } return_value = winreg_SetValueEx_impl(module, key, value_name, reserved, type, value); exit: return return_value; } PyDoc_STRVAR(winreg_DisableReflectionKey__doc__, "DisableReflectionKey($module, key, /)\n" "--\n" "\n" "Disables registry reflection for 32bit processes running on a 64bit OS.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" "\n" "Will generally raise NotImplemented if executed on a 32bit OS.\n" "\n" "If the key is not on the reflection list, the function succeeds but has\n" "no effect. Disabling reflection for a key does not affect reflection\n" "of any subkeys."); #define WINREG_DISABLEREFLECTIONKEY_METHODDEF \ {"DisableReflectionKey", (PyCFunction)winreg_DisableReflectionKey, METH_O, winreg_DisableReflectionKey__doc__}, static PyObject * winreg_DisableReflectionKey_impl(PyObject *module, HKEY key); static PyObject * winreg_DisableReflectionKey(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; HKEY key; if (!PyArg_Parse(arg, "O&:DisableReflectionKey", clinic_HKEY_converter, &key)) { goto exit; } return_value = winreg_DisableReflectionKey_impl(module, key); exit: return return_value; } PyDoc_STRVAR(winreg_EnableReflectionKey__doc__, "EnableReflectionKey($module, key, /)\n" "--\n" "\n" "Restores registry reflection for the specified disabled key.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" "\n" "Will generally raise NotImplemented if executed on a 32bit OS.\n" "Restoring reflection for a key does not affect reflection of any\n" "subkeys."); #define WINREG_ENABLEREFLECTIONKEY_METHODDEF \ {"EnableReflectionKey", (PyCFunction)winreg_EnableReflectionKey, METH_O, winreg_EnableReflectionKey__doc__}, static PyObject * winreg_EnableReflectionKey_impl(PyObject *module, HKEY key); static PyObject * winreg_EnableReflectionKey(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; HKEY key; if (!PyArg_Parse(arg, "O&:EnableReflectionKey", clinic_HKEY_converter, &key)) { goto exit; } return_value = winreg_EnableReflectionKey_impl(module, key); exit: return return_value; } PyDoc_STRVAR(winreg_QueryReflectionKey__doc__, "QueryReflectionKey($module, key, /)\n" "--\n" "\n" "Returns the reflection state for the specified key as a bool.\n" "\n" " key\n" " An already open key, or any one of the predefined HKEY_* constants.\n" "\n" "Will generally raise NotImplemented if executed on a 32bit OS."); #define WINREG_QUERYREFLECTIONKEY_METHODDEF \ {"QueryReflectionKey", (PyCFunction)winreg_QueryReflectionKey, METH_O, winreg_QueryReflectionKey__doc__}, static PyObject * winreg_QueryReflectionKey_impl(PyObject *module, HKEY key); static PyObject * winreg_QueryReflectionKey(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; HKEY key; if (!PyArg_Parse(arg, "O&:QueryReflectionKey", clinic_HKEY_converter, &key)) { goto exit; } return_value = winreg_QueryReflectionKey_impl(module, key); exit: return return_value; } /*[clinic end generated code: output=16dd06be6e14b86e input=a9049054013a1b77]*/
35,382
1,103
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/icons/python.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-white{fill:#fff}.icon-vso-bg{fill:#656565}.icon-visualstudio-online{fill:#007acc}.icon-vs-bg{fill:#424242}.icon-vs-green{fill:#393}.st0{fill:url(#path1948_1_)}.st1{fill:url(#path1950_1_)}</style><path class="icon-canvas-transparent" d="M32 32H0V0h32v32z" id="canvas"/><g id="iconBg"><path class="icon-visualstudio-online" d="M30 4H2V2h28v2z"/><path class="icon-vso-bg" d="M29 4v21H3V4H2v22h28V4z"/><path class="icon-vs-bg" d="M10 4H3v21h26V4z"/></g><g id="iconFg"><path class="icon-white" d="M29.141 3l.429.429-.14.142-.43-.43-.43.43-.14-.142.429-.429-.429-.429.141-.142.429.43.43-.43.141.142-.43.429zM27.6 2.4h-1.2v1.2h1.2V2.4zm-1 .2h.8v.8h-.8v-.8zm-1.139.8h-1v.2h1v-.2z"/><path class="icon-vs-green" d="M16 14H5v-1h11.031c-.014.044-.031 1-.031 1zm-4-5H5v1h7V9zm-7 8v1h8v-1H5z"/></g><g id="colorImportance"><path class="icon-white" d="M31.596 24.063C31.246 25.116 30.595 27 28.349 27H27v1.313c0 .905-.368 2.537-2.996 3.298-.904.261-1.728.389-2.566.389-.83 0-1.597-.128-2.492-.392C17.029 31.045 16 29.844 16 28.313V27h-1.297c-1.698 0-2.943-1.141-3.416-3.11-.469-1.946-.469-3.021 0-4.967.451-1.881 1.96-2.923 3.845-2.923H16v-1.697c0-2.005.834-2.845 3.054-3.238.728-.128 1.474-.065 2.296-.065h.003c.921 0 1.735-.07 2.537.064 1.816.303 3.11 1.585 3.11 3.24V16h1.349c1.142 0 2.636.356 3.27 2.912.515 2.072.509 3.558-.023 5.151z"/><linearGradient id="path1948_1_" gradientUnits="userSpaceOnUse" x1="522.205" y1="-288.668" x2="540.902" y2="-304.754" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#5a9fd4"/><stop offset="1" stop-color="#306998"/></linearGradient><path id="path1948_3_" class="st0" d="M21.354 11.725c-.786.004-1.537.071-2.197.188-1.946.344-2.299 1.063-2.299 2.39v1.753h4.598v.584h-6.324c-1.336 0-2.507.803-2.873 2.331-.422 1.751-.441 2.844 0 4.673.327 1.361 1.107 2.331 2.444 2.331h1.581v-2.101c0-1.518 1.313-2.857 2.873-2.857h4.593c1.279 0 2.299-1.053 2.299-2.337v-4.379c0-1.246-1.051-2.182-2.299-2.39-.79-.13-1.61-.189-2.396-.186zm-2.486 1.41c.475 0 .863.394.863.879a.87.87 0 0 1-.863.874.868.868 0 0 1-.863-.874c0-.485.386-.879.863-.879z"/><linearGradient id="path1950_1_" gradientUnits="userSpaceOnUse" x1="548.13" y1="-314.489" x2="541.454" y2="-305.043" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ffe873"/></linearGradient><path id="path1950_3_" class="st1" d="M26.623 16.64v2.042c0 1.583-1.342 2.915-2.873 2.915h-4.593c-1.258 0-2.299 1.077-2.299 2.337v4.379c0 1.246 1.084 1.979 2.299 2.337 1.456.428 2.851.505 4.593 0 1.158-.335 2.299-1.01 2.299-2.337V26.56h-4.593v-.584h6.892c1.336 0 1.834-.932 2.299-2.331.48-1.44.46-2.826 0-4.673-.33-1.33-.961-2.331-2.299-2.331h-1.725zm-2.584 11.089c.477 0 .863.391.863.874a.871.871 0 0 1-.863.879.872.872 0 0 1-.863-.879.87.87 0 0 1 .863-.874z"/></g></svg>
2,962
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/icons/pyc.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vso-bg{fill:#656565}.icon-vs-bg{fill:#424242}.icon-vs-green{fill:#393}.icon-white{fill:#fff}.st0{fill:url(#path1948_1_)}.st1{fill:url(#path1950_1_)}</style><path class="icon-canvas-transparent" d="M32 32H0V0h32v32z" id="canvas"/><g id="iconBg"><path class="icon-vs-bg" d="M21.053 3H7v26h19V8.009z"/><path class="icon-vso-bg" d="M21.471 2H6v28h21V7.599L21.471 2zM21 3h.053l4.939 5H21V3zm5 26H7V3h13v6h6v20z"/></g><path class="icon-vs-green" d="M10 16H9v-1h1v1zm1.011 5H9v1h2.032a8.368 8.368 0 0 1-.021-1zM14 10h2V9h-2v1zm-3-4H9v1h2V6zm0 6H9v1h2v-1zm2-3H9v1h4V9zm4-3v1h1V6h-1zm-3 6h-2v1h2v-1zm1-6h-2v1h2V6zm-4 10h1v-1h-1v1zm4-4v1h2v-1h-2zm-2 4h3v-1h-3v1zm-4 2v1h3v-1H9zm0 6v1h3v-1H9z" id="iconFg"/><g id="colorImportance"><path class="icon-white" d="M31.66 24.063C31.312 25.116 30.661 27 28.413 27H27v1.313c0 .905-.335 2.537-2.965 3.298-.904.261-1.694.389-2.531.389-.83 0-1.63-.128-2.526-.392C17.061 31.045 16 29.844 16 28.313V27h-1.232c-1.699 0-2.944-1.141-3.416-3.11-.469-1.946-.469-3.021 0-4.967.451-1.881 1.96-2.923 3.845-2.923H16v-1.697c0-2.005.866-2.845 3.087-3.238.727-.128 1.506-.065 2.327-.065h.003c.921 0 1.703-.07 2.504.064 1.818.302 3.079 1.585 3.079 3.239V16h1.413c1.142 0 2.636.356 3.27 2.912.515 2.072.509 3.558-.023 5.151z"/><linearGradient id="path1948_1_" gradientUnits="userSpaceOnUse" x1="522.32" y1="-288.668" x2="541.017" y2="-304.754" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#5a9fd4"/><stop offset="1" stop-color="#306998"/></linearGradient><path id="path1948_4_" class="st0" d="M21.419 11.725c-.786.004-1.537.071-2.197.188-1.946.344-2.299 1.063-2.299 2.39v1.753h4.598v.584h-6.324c-1.336 0-2.507.803-2.873 2.331-.422 1.751-.441 2.844 0 4.673.327 1.361 1.108 2.331 2.444 2.331h1.581v-2.101c0-1.518 1.313-2.857 2.873-2.857h4.593c1.278 0 2.299-1.053 2.299-2.337v-4.379c0-1.246-1.051-2.182-2.299-2.39-.79-.13-1.61-.189-2.396-.186zm-2.487 1.41c.475 0 .863.394.863.879a.87.87 0 0 1-.863.874.868.868 0 0 1-.863-.874c0-.485.387-.879.863-.879z"/><linearGradient id="path1950_1_" gradientUnits="userSpaceOnUse" x1="548.245" y1="-314.489" x2="541.569" y2="-305.043" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ffe873"/></linearGradient><path id="path1950_4_" class="st1" d="M26.687 16.64v2.042c0 1.583-1.342 2.915-2.873 2.915h-4.593c-1.258 0-2.299 1.077-2.299 2.337v4.379c0 1.246 1.084 1.979 2.299 2.337 1.456.428 2.851.505 4.593 0 1.158-.335 2.299-1.01 2.299-2.337V26.56H21.52v-.584H28.412c1.336 0 1.834-.932 2.299-2.331.48-1.44.46-2.826 0-4.673-.33-1.33-.961-2.331-2.299-2.331h-1.725zm-2.583 11.089c.477 0 .863.391.863.874a.871.871 0 0 1-.863.879.872.872 0 0 1-.863-.879c0-.484.388-.874.863-.874z"/></g></svg>
2,878
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/icons/setup.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-visualstudio-online{fill:#007acc}.icon-disabled-grey{fill:#848484}.icon-white{fill:#fff}.st0{fill:#f0eff1}.st1{fill:#424242}.st2{fill:url(#path1948_1_)}.st3{fill:url(#path1950_1_)}</style><path class="icon-canvas-transparent" d="M32 32H0V0h32v32z" id="canvas"/><g id="iconBg"><path class="st0" d="M18 8v10H1V8h17zm-1.191 15.572a1.004 1.004 0 0 0-.903-.572H2.907c-.385 0-.74.225-.903.572L.886 25.928A.748.748 0 0 0 1.563 27H17.25a.748.748 0 0 0 .677-1.072l-1.118-2.356z"/><path class="icon-disabled-grey" d="M17.927 25.929l-1.118-2.356a1.003 1.003 0 0 0-.903-.573H2.907c-.385 0-.74.225-.903.572L.886 25.928A.748.748 0 0 0 1.563 27H17.25a.747.747 0 0 0 .633-.349.746.746 0 0 0 .044-.722zM1.959 26l.949-2h12.998l.949 2H1.959zM6 22v-1h3v-2h1v2h3v1H6z"/><path class="st1" d="M0 7v12h19V7H0zm18 11H1V8h17v10z"/></g><g id="iconFg"><path class="icon-white" d="M12 6V0H7v6H2.755L9.5 13.495 16.245 6z"/><path class="icon-visualstudio-online" d="M8 4h3v3h3l-4.5 5L5 7h3V4zm3-2H8v1h3V2zm0-2H8v1h3V0z"/></g><g id="colorImportance"><path class="icon-white" d="M31.596 24.063C31.246 25.116 30.595 27 28.349 27H27v1.313c0 .905-.368 2.537-2.997 3.298-.903.261-1.727.389-2.565.389-.83 0-1.597-.128-2.493-.392C17.029 31.045 16 29.844 16 28.313V27h-1.296c-1.698 0-2.944-1.141-3.417-3.11-.469-1.944-.469-3.02 0-4.967.451-1.881 1.961-2.923 3.845-2.923H16v-1.697c0-2.005.834-2.845 3.054-3.238.728-.128 1.474-.065 2.296-.065h.003c.921 0 1.735-.07 2.537.064 1.816.303 3.11 1.585 3.11 3.24V16h1.349c1.142 0 2.636.356 3.27 2.912.515 2.072.509 3.559-.023 5.151z"/><linearGradient id="path1948_1_" gradientUnits="userSpaceOnUse" x1="522.205" y1="-288.668" x2="540.902" y2="-304.754" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#5a9fd4"/><stop offset="1" stop-color="#306998"/></linearGradient><path id="path1948_9_" class="st2" d="M21.354 11.725c-.786.004-1.537.071-2.197.188-1.946.344-2.299 1.063-2.299 2.39v1.753h4.598v.584h-6.324c-1.336 0-2.507.803-2.873 2.331-.422 1.751-.441 2.844 0 4.673.327 1.361 1.108 2.331 2.444 2.331h1.581v-2.101c0-1.518 1.313-2.857 2.873-2.857h4.593c1.279 0 2.299-1.053 2.299-2.337v-4.379c0-1.246-1.051-2.182-2.299-2.39-.79-.13-1.61-.189-2.396-.186zm-2.486 1.41c.475 0 .863.394.863.879a.87.87 0 0 1-.863.874.868.868 0 0 1-.863-.874c0-.485.386-.879.863-.879z"/><linearGradient id="path1950_1_" gradientUnits="userSpaceOnUse" x1="548.13" y1="-314.489" x2="541.454" y2="-305.043" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ffe873"/></linearGradient><path id="path1950_9_" class="st3" d="M26.623 16.64v2.042c0 1.583-1.342 2.915-2.873 2.915h-4.593c-1.258 0-2.299 1.077-2.299 2.337v4.379c0 1.246 1.084 1.979 2.299 2.337 1.456.428 2.851.505 4.593 0 1.158-.335 2.299-1.01 2.299-2.337V26.56h-4.593v-.584H28.348c1.336 0 1.834-.932 2.299-2.331.48-1.44.46-2.826 0-4.673-.33-1.33-.961-2.331-2.299-2.331h-1.725zm-2.584 11.089c.477 0 .863.391.863.874a.871.871 0 0 1-.863.879.872.872 0 0 1-.863-.879.87.87 0 0 1 .863-.874z"/></g></svg>
3,173
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/icons/py.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vs-out{fill:#f6f6f6}.icon-vso-bg{fill:#656565}.icon-vso-lightgrey{fill:#bfbfbf}.icon-white{fill:#fff}.st0{fill:url(#path1948_1_)}.st1{fill:url(#path1950_1_)}</style><path class="icon-canvas-transparent" d="M32 32H0V0h32v32z" id="canvas"/><g id="iconBg"><path class="icon-vs-out" d="M26 8.009V29H7V3h14.053L26 8.009z"/><path class="icon-vso-bg" d="M21.471 2H6v28h21V7.599L21.471 2zM21 3h.053l4.939 5H21V3zm5 26H7V3h13v6h6v20z"/></g><path class="icon-vso-lightgrey" d="M17 7H9V6h8v1zm0 2H9v1h8V9zm7 3H9v1h15v-1zm0 3H9v1h15v-1zm0 3H9v1h15v-1zm0 3H9v1h15v-1zm0 3H9v1h15v-1z" id="iconFg"/><g id="colorImportance"><path class="icon-white" d="M31.66 24.063C31.312 25.116 30.661 27 28.413 27H27v1.313c0 .905-.335 2.537-2.965 3.298-.904.261-1.694.389-2.531.389-.83 0-1.63-.128-2.526-.392C17.061 31.045 16 29.844 16 28.313V27h-1.232c-1.699 0-2.944-1.141-3.416-3.11-.469-1.946-.469-3.021 0-4.967.451-1.881 1.96-2.923 3.845-2.923H16v-1.697c0-2.005.866-2.845 3.087-3.238.727-.128 1.506-.065 2.327-.065h.003c.921 0 1.703-.07 2.504.064 1.818.302 3.079 1.585 3.079 3.239V16h1.413c1.142 0 2.636.356 3.27 2.912.515 2.072.509 3.559-.023 5.151z"/><linearGradient id="path1948_1_" gradientUnits="userSpaceOnUse" x1="522.32" y1="-288.668" x2="541.017" y2="-304.754" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#5a9fd4"/><stop offset="1" stop-color="#306998"/></linearGradient><path id="path1948_2_" class="st0" d="M21.419 11.725c-.786.004-1.537.071-2.197.188-1.946.344-2.299 1.063-2.299 2.39v1.753h4.598v.584h-6.324c-1.336 0-2.507.803-2.873 2.331-.422 1.751-.441 2.844 0 4.673.327 1.361 1.108 2.331 2.444 2.331h1.581v-2.101c0-1.518 1.313-2.857 2.873-2.857h4.593c1.278 0 2.299-1.053 2.299-2.337v-4.379c0-1.246-1.051-2.182-2.299-2.39-.79-.13-1.61-.189-2.396-.186zm-2.487 1.41c.475 0 .863.394.863.879a.87.87 0 0 1-.863.874.868.868 0 0 1-.863-.874c0-.485.387-.879.863-.879z"/><linearGradient id="path1950_1_" gradientUnits="userSpaceOnUse" x1="548.245" y1="-314.489" x2="541.569" y2="-305.043" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ffe873"/></linearGradient><path id="path1950_2_" class="st1" d="M26.687 16.64v2.042c0 1.583-1.342 2.915-2.873 2.915h-4.593c-1.258 0-2.299 1.077-2.299 2.337v4.379c0 1.246 1.084 1.979 2.299 2.337 1.456.428 2.851.505 4.593 0 1.158-.335 2.299-1.01 2.299-2.337V26.56H21.52v-.584H28.412c1.336 0 1.834-.932 2.299-2.331.48-1.44.46-2.826 0-4.673-.33-1.33-.961-2.331-2.299-2.331h-1.725zm-2.583 11.089c.477 0 .863.391.863.874a.871.871 0 0 1-.863.879.872.872 0 0 1-.863-.879c0-.484.388-.874.863-.874z"/></g></svg>
2,766
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/icons/pyd.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vso-bg{fill:#656565}.icon-vs-out{fill:#f6f6f6}.icon-f12-hover-bg{fill:#d9ebf7}.icon-f12-ltgrey-disabled{fill:#ababac}.icon-white{fill:#fff}.st0{fill:#9ca2a7}.st1{fill:url(#path1948_1_)}.st2{fill:url(#path1950_1_)}</style><path class="icon-canvas-transparent" d="M32 32H0V0h32v32z" id="canvas"/><g id="iconBg"><path class="icon-vs-out" d="M21.053 3H7v26h19V8.009z"/><path class="icon-vso-bg" d="M21.471 2H6v28h21V7.599L21.471 2zM21 3h.053l4.939 5H21V3zm5 26H7V3h13v6h6v20z"/></g><g id="iconFg"><path class="st0" d="M13.784 17.705c-1.296 0-2.35-1.054-2.35-2.35s1.054-2.35 2.35-2.35 2.35 1.054 2.35 2.35-1.054 2.35-2.35 2.35zm0-4.5c-1.186 0-2.15.964-2.15 2.15s.964 2.151 2.15 2.151 2.15-.965 2.15-2.151-.964-2.15-2.15-2.15z"/><path class="icon-f12-hover-bg" d="M18.05 16.122c.016-.069.031-.139.043-.209l1.376-.618-.103-1.015-1.47-.33c-.025-.068-.056-.134-.086-.199l-.026-.056.892-1.236-.595-.827-1.45.453c-.069-.061-.141-.118-.213-.175l.151-1.511-.929-.418-1.032 1.121-.056-.013a3.089 3.089 0 0 0-.217-.045l-.618-1.374-1.015.104-.329 1.472c-.049.019-.096.04-.143.063l-.056.025-1.225-.907-.835.586.435 1.457c-.06.067-.123.138-.182.212l-1.506-.172-.429.925L9.54 14.48l-.005.024a4.127 4.127 0 0 0-.051.246l-1.387.606.092 1.015 1.463.346c.024.067.055.132.084.194l.03.067-.86 1.17-.042.059.588.832 1.456-.44c.07.063.138.122.209.178l-.167 1.508.926.427L12.92 19.6l.048.01c.074.017.149.034.226.046l.609 1.385 1.015-.095.342-1.466c.075-.027.147-.061.216-.093l.067-.031 1.235.892.827-.595-.452-1.45c.062-.071.12-.142.176-.215l1.512.151.418-.929-1.122-1.033.013-.055zm-4.266 1.583c-1.296 0-2.35-1.054-2.35-2.35s1.054-2.35 2.35-2.35 2.35 1.054 2.35 2.35-1.054 2.35-2.35 2.35z"/><path class="icon-f12-ltgrey-disabled" d="M13.803 21.04l-.609-1.384a3.08 3.08 0 0 1-.236-.048l-.038-.008-1.043 1.111-.925-.427.167-1.507a4.013 4.013 0 0 1-.209-.179l-1.456.439-.588-.832.902-1.228-.033-.072c-.028-.061-.058-.124-.082-.19l-1.463-.344-.091-1.015 1.387-.605c.012-.078.03-.154.047-.231l.009-.039-1.109-1.045.428-.925 1.507.17c.058-.072.118-.14.183-.211l-.435-1.458.834-.585 1.225.907.052-.024c.048-.022.097-.044.147-.063l.329-1.473 1.014-.104.62 1.375a2.389 2.389 0 0 1 .271.058l1.032-1.122.93.418-.153 1.511c.073.055.143.113.214.174l1.45-.453.595.827-.892 1.236a.8.8 0 0 1 .024.053c.03.064.062.131.087.201l1.471.332.103 1.014-1.376.618c-.012.071-.027.14-.043.208l-.014.058 1.122 1.033-.419.929-1.511-.152a3.851 3.851 0 0 1-.176.215l.452 1.45-.827.595-1.236-.892-.07.032a2.94 2.94 0 0 1-.212.092l-.341 1.465-1.015.095zm-.951-1.66l.151.033c.089.021.179.042.272.053l.056.007.597 1.354.728-.067.333-1.435.054-.018c.083-.025.161-.062.244-.101.042-.02.084-.039.127-.057l.052-.022 1.211.874.593-.427-.442-1.421.038-.043c.085-.094.163-.188.236-.288l.033-.046 1.48.15.3-.667-1.099-1.012.012-.055.025-.117c.019-.08.037-.16.047-.244l.007-.056 1.348-.605-.073-.728-1.441-.324-.018-.055c-.025-.081-.061-.157-.096-.233a2.145 2.145 0 0 1-.05-.109l-.022-.052.874-1.212-.427-.593-1.42.443-.042-.038a3.896 3.896 0 0 0-.288-.235L16.207 12l.149-1.48-.667-.3-1.012 1.1-.056-.011c-.04-.008-.08-.018-.119-.027-.082-.019-.162-.038-.246-.048l-.056-.005-.607-1.346-.727.074-.323 1.441-.054.018c-.063.02-.121.047-.18.074-.037.017-.073.034-.111.049l-.052.022-1.2-.89-.599.42.426 1.429-.038.042a4.07 4.07 0 0 0-.244.284l-.034.045-1.476-.167-.307.663 1.086 1.024-.034.151c-.02.089-.041.177-.052.269l-.007.056-1.358.593.066.728 1.431.337.017.055c.024.077.058.148.091.22.021.043.041.086.059.131l.022.052-.885 1.203.422.598 1.426-.432.042.038c.083.075.179.163.282.24l.045.035-.163 1.476.664.306 1.024-1.087zM20.918 22.972a1.35 1.35 0 1 1 .001-2.699 1.35 1.35 0 0 1-.001 2.699zm0-2.5c-.634 0-1.15.517-1.15 1.15s.517 1.15 1.15 1.15 1.15-.517 1.15-1.15-.516-1.15-1.15-1.15z"/><path class="icon-f12-hover-bg" d="M24.901 22.028v-.812l-1.269-.423a2.747 2.747 0 0 0-.21-.505l.599-1.196-.574-.574-1.196.599a2.81 2.81 0 0 0-.505-.209l-.423-1.268h-.811l-.423 1.268a2.81 2.81 0 0 0-.505.209l-1.197-.599-.573.574.599 1.196a2.747 2.747 0 0 0-.21.505l-1.268.423v.812l1.268.422c.054.175.124.345.21.506l-.599 1.196.573.574 1.197-.6c.161.087.331.157.505.21l.423 1.269h.811l.423-1.269c.174-.053.343-.123.505-.21l1.196.6.574-.574-.599-1.196c.086-.161.156-.331.21-.506l1.269-.422zm-3.983.943c-.744 0-1.35-.606-1.35-1.35 0-.744.605-1.35 1.35-1.35.744 0 1.35.605 1.35 1.35 0 .745-.606 1.35-1.35 1.35z"/><path class="icon-f12-ltgrey-disabled" d="M21.323 25.604h-.811l-.423-1.269a2.814 2.814 0 0 1-.505-.209l-1.197.599-.573-.574.599-1.196a2.747 2.747 0 0 1-.21-.505l-1.269-.423v-.812l1.269-.422c.054-.175.124-.345.21-.506l-.599-1.196.573-.573 1.197.599c.161-.087.331-.157.505-.21l.423-1.269h.811l.423 1.269c.174.053.344.123.505.21l1.196-.599.574.573-.599 1.196c.086.161.156.331.21.506l1.269.422v.812l-1.269.423a2.747 2.747 0 0 1-.21.505l.599 1.196-.574.574-1.196-.599a2.814 2.814 0 0 1-.505.209l-.423 1.269zm-.666-.199h.521l.411-1.232.051-.015c.193-.054.382-.132.56-.231l.046-.026 1.162.581.369-.369-.58-1.162.026-.046c.099-.178.177-.366.232-.56l.014-.051 1.232-.411v-.523l-1.232-.41-.014-.051a2.81 2.81 0 0 0-.232-.561l-.026-.046.58-1.162-.369-.368-1.162.58-.046-.026a2.627 2.627 0 0 0-.56-.232l-.05-.014-.411-1.232h-.521l-.411 1.232-.051.014a2.758 2.758 0 0 0-.56.232l-.046.026-1.163-.58-.368.368.58 1.162-.026.046a2.675 2.675 0 0 0-.232.561l-.014.051-1.232.41v.522l1.232.411.014.051c.056.193.134.382.232.56l.026.046-.58 1.162.368.369 1.163-.581.046.026c.178.1.366.178.56.231l.051.015.41 1.233z"/></g><g id="colorImportance"><path class="icon-white" d="M31.66 24.063C31.312 25.116 30.661 27 28.413 27H27v1.313c0 .905-.335 2.537-2.965 3.298-.904.261-1.694.389-2.531.389-.83 0-1.63-.128-2.526-.392C17.061 31.045 16 29.844 16 28.313V27h-1.232c-1.699 0-2.944-1.141-3.416-3.11-.469-1.946-.469-3.021 0-4.967.451-1.881 1.96-2.923 3.845-2.923H16v-1.697c0-2.005.866-2.845 3.087-3.238.727-.128 1.506-.065 2.327-.065h.003c.921 0 1.703-.07 2.504.064 1.818.302 3.079 1.585 3.079 3.239V16h1.413c1.142 0 2.636.356 3.27 2.912.515 2.072.509 3.558-.023 5.151z"/><linearGradient id="path1948_1_" gradientUnits="userSpaceOnUse" x1="522.32" y1="-288.668" x2="541.017" y2="-304.754" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#5a9fd4"/><stop offset="1" stop-color="#306998"/></linearGradient><path id="path1948_5_" class="st1" d="M21.419 11.725c-.786.004-1.537.071-2.197.188-1.946.344-2.299 1.063-2.299 2.39v1.753h4.598v.584h-6.324c-1.336 0-2.507.803-2.873 2.331-.422 1.751-.441 2.844 0 4.673.327 1.361 1.108 2.331 2.444 2.331h1.581v-2.101c0-1.518 1.313-2.857 2.873-2.857h4.593c1.278 0 2.299-1.053 2.299-2.337v-4.379c0-1.246-1.051-2.182-2.299-2.39-.79-.13-1.61-.189-2.396-.186zm-2.487 1.41c.475 0 .863.394.863.879a.87.87 0 0 1-.863.874.868.868 0 0 1-.863-.874c0-.485.387-.879.863-.879z"/><linearGradient id="path1950_1_" gradientUnits="userSpaceOnUse" x1="548.245" y1="-314.489" x2="541.569" y2="-305.043" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ffe873"/></linearGradient><path id="path1950_5_" class="st2" d="M26.687 16.64v2.042c0 1.583-1.342 2.915-2.873 2.915h-4.593c-1.258 0-2.299 1.077-2.299 2.337v4.379c0 1.246 1.084 1.979 2.299 2.337 1.456.428 2.851.505 4.593 0 1.158-.335 2.299-1.01 2.299-2.337V26.56H21.52v-.584H28.412c1.336 0 1.834-.932 2.299-2.331.48-1.44.46-2.826 0-4.673-.33-1.33-.961-2.331-2.299-2.331h-1.725zm-2.583 11.089c.477 0 .863.391.863.874a.871.871 0 0 1-.863.879.872.872 0 0 1-.863-.879c0-.484.388-.874.863-.874z"/></g></svg>
7,604
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/icons/launcher.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vs-out{fill:#f6f6f6}.icon-white{fill:#fff}.icon-vso-bg{fill:#656565}.icon-visualstudio-online{fill:#007acc}.graph-lightgrey{fill:#dfdfdf}.st0{fill:#0078d7}.st1{fill:#fff}.st2{fill:url(#path1948_1_)}.st3{fill:url(#path1950_1_)}</style><path class="icon-canvas-transparent" d="M32 32H0V0h32v32z" id="canvas"/><g id="iconBg"><path class="icon-visualstudio-online" d="M30 5H5V3h25v2z"/><path class="icon-vso-bg" d="M29.972 26.972H5.029V5h.942v21.028h23.057V5h.943v21.972z"/><path class="icon-vs-out" d="M29 5v21H6V5h23z"/><path class="icon-white" d="M29.141 4l.429.429-.14.142-.43-.43-.43.43-.14-.142.429-.429-.429-.429.141-.142.429.43.43-.43.141.142-.43.429zM27.6 3.4h-1.2v1.2h1.2V3.4zm-1 .2h.8v.8h-.8v-.8zm-1.139.8h-1v.2h1v-.2z"/><path class="graph-lightgrey" d="M6 5h23v2H6z"/></g><g id="iconFg"><path class="st0" d="M4.5 23v6"/><path class="st1" d="M11.429 13.019a19.88 19.88 0 0 0 .071-1.645c0-4.223-1.329-8.165-3.556-10.545L7.17 0H5.83l-.774.829C2.829 3.209 1.5 7.151 1.5 11.374c0 .453.023.9.053 1.345C.887 13.472.357 14.438 0 15.533v6.603L.229 23H3v7h2v2h3v-1h2v-8h2.772l.394-1.488c.222-.842.335-1.714.335-2.592-.001-2.419-.803-4.534-2.072-5.901z"/><path class="st0" d="M6.5 22v9M8.5 23v7"/><path class="icon-visualstudio-online" d="M5 29H4v-6h1v6zm2-6H6v8h1v-8zm2 0H8v7h1v-7z"/><path class="icon-vso-bg" d="M10.381 13.38c.07-.658.119-1.325.119-2.006 0-3.975-1.229-7.662-3.286-9.862L6.5.748l-.714.763C3.729 3.712 2.5 7.399 2.5 11.374c0 .681.049 1.348.119 2.006C1.339 14.521.5 16.552.5 18.92c0 .793.102 1.578.302 2.336L.999 22h1.966l.072-.922c.081-1.046.471-1.966.993-2.503.487 1.019 1.07 1.929 1.756 2.662L6.5 22l.714-.763c.686-.733 1.269-1.643 1.756-2.662.522.537.912 1.457.993 2.503l.072.922h1.966l.197-.744c.2-.758.302-1.543.302-2.336 0-2.368-.839-4.399-2.119-5.54z"/><path class="icon-vs-out" d="M3.619 17.615c-.854.672-1.464 1.913-1.579 3.385h-.272a8.184 8.184 0 0 1-.268-2.08c0-1.722.505-3.259 1.297-4.272.187 1.05.465 2.045.822 2.967zm6.585-2.967a16.145 16.145 0 0 1-.822 2.967c.854.671 1.464 1.913 1.579 3.385h.272a8.184 8.184 0 0 0 .268-2.08c-.001-1.722-.506-3.259-1.297-4.272zM3.5 11.374c0 3.837 1.198 7.2 3 9.128 1.802-1.927 3-5.291 3-9.128s-1.198-7.2-3-9.128c-1.802 1.928-3 5.291-3 9.128z"/><path class="icon-visualstudio-online" d="M7.5 7a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/></g><g id="colorImportance"><path class="icon-white" d="M31.596 23.961c-.35 1.053-1.001 3.015-3.247 3.015h-1.3v1.337c0 .905-.392 2.537-3.021 3.298a9.213 9.213 0 0 1-2.59.39c-.83 0-1.668-.128-2.564-.392-1.918-.563-3.017-1.765-3.017-3.296v-1.337h-1.155c-1.698 0-2.943-1.129-3.416-3.098-.469-1.946-.469-3.195 0-5.141.451-1.881 1.96-3.098 3.845-3.098h.726v-1.337c0-2.005.905-2.982 3.126-3.374.729-.13 1.549-.2 2.367-.203h.004c.925 0 1.761.067 2.56.201 1.816.303 3.134 1.723 3.134 3.376v1.337h1.3c1.142 0 2.636.536 3.27 3.092.516 2.073.51 3.637-.022 5.23z"/><linearGradient id="path1948_1_" gradientUnits="userSpaceOnUse" x1="522.205" y1="-288.668" x2="540.902" y2="-304.754" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#5a9fd4"/><stop offset="1" stop-color="#306998"/></linearGradient><path id="path1948_7_" class="st2" d="M21.354 11.725c-.786.004-1.537.071-2.197.188-1.946.344-2.299 1.063-2.299 2.39v1.753h4.598v.584h-6.324c-1.336 0-2.507.803-2.873 2.331-.422 1.751-.441 2.844 0 4.673.327 1.361 1.107 2.331 2.444 2.331h1.581v-2.101c0-1.518 1.313-2.857 2.873-2.857h4.593c1.279 0 2.299-1.053 2.299-2.337v-4.379c0-1.246-1.051-2.182-2.299-2.39-.79-.13-1.61-.189-2.396-.186zm-2.486 1.41c.475 0 .863.394.863.879a.87.87 0 0 1-.863.874.868.868 0 0 1-.863-.874c0-.485.386-.879.863-.879z"/><linearGradient id="path1950_1_" gradientUnits="userSpaceOnUse" x1="548.13" y1="-314.489" x2="541.454" y2="-305.043" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ffe873"/></linearGradient><path id="path1950_7_" class="st3" d="M26.623 16.64v2.042c0 1.583-1.342 2.915-2.873 2.915h-4.593c-1.258 0-2.299 1.077-2.299 2.337v4.379c0 1.246 1.084 1.979 2.299 2.337 1.456.428 2.851.505 4.593 0 1.158-.335 2.299-1.01 2.299-2.337V26.56h-4.593v-.584H28.348c1.336 0 1.834-.932 2.299-2.331.48-1.44.46-2.826 0-4.673-.33-1.33-.961-2.331-2.299-2.331h-1.725zm-2.584 11.089c.477 0 .863.391.863.874a.871.871 0 0 1-.863.879.872.872 0 0 1-.863-.879.87.87 0 0 1 .863-.874z"/></g></svg>
4,476
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/PC/icons/pythonw.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-white{fill:#fff}.icon-visualstudio-online{fill:#007acc}.graph-lightgrey{fill:#dfdfdf}.st0{fill:#f6f6f6}.st1{fill:#656565}.st2{fill:#bfbfbf}.st3{fill:#fff}.st4{fill:url(#path1948_1_)}.st5{fill:url(#path1950_1_)}</style><path class="icon-canvas-transparent" d="M32 32H0V0h32v32z" id="canvas"/><g id="iconBg"><path class="graph-lightgrey" d="M29 7H3V5h26v2z"/><path class="icon-visualstudio-online" d="M30 5H2V3h28v2z"/><path class="icon-white" d="M29.141 4l.429.429-.14.142-.43-.43-.43.43-.14-.142.429-.429-.429-.429.141-.142.429.43.43-.43.141.142-.43.429zM27.6 3.4h-1.2v1.2h1.2V3.4zm-1 .2h.8v.8h-.8v-.8zm-1.139.8h-1v.2h1v-.2z"/><path class="st0" d="M3 7h26v19H3z"/><path class="st1" d="M29 5v21H3V5H2v22h28V5z"/><path class="st1" d="M4 5.75h2v.5H4z"/></g><path class="st2" d="M12 11H5v-1h7v1zm-7 7v1h11v-1H5zm0-4v1h11v-1H5z" id="iconFg"/><g id="colorImportance"><path class="st3" d="M31.618 18.912C30.984 16.356 29.49 16 28.349 16H27v-1.697c0-1.654-1.294-2.937-3.11-3.24-.802-.133-1.617-.063-2.537-.063h-.003c-.821 0-1.568-.063-2.295.065-2.221.393-3.055 1.233-3.055 3.238V16h-.868c-1.885 0-3.394 1.042-3.845 2.924-.469 1.946-.469 3.022 0 4.967C11.76 25.859 13.005 27 14.703 27H16v1.313c0 1.531 1.029 2.732 2.946 3.296.896.263 1.662.391 2.492.391.838 0 1.661-.128 2.565-.39C26.632 30.85 27 29.218 27 28.313V27h1.349c2.246 0 2.897-1.884 3.247-2.937.532-1.592.538-3.079.022-5.151z"/><linearGradient id="path1948_1_" gradientUnits="userSpaceOnUse" x1="522.205" y1="-288.668" x2="540.902" y2="-304.754" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#5a9fd4"/><stop offset="1" stop-color="#306998"/></linearGradient><path id="path1948_6_" class="st4" d="M21.354 11.725c-.786.004-1.537.071-2.197.188-1.946.344-2.299 1.063-2.299 2.39v1.753h4.598v.584h-6.324c-1.336 0-2.507.803-2.873 2.331-.422 1.751-.441 2.844 0 4.673.327 1.361 1.107 2.331 2.444 2.331h1.581v-2.101c0-1.518 1.313-2.857 2.873-2.857h4.593c1.278 0 2.299-1.053 2.299-2.337v-4.379c0-1.246-1.051-2.182-2.299-2.39-.79-.13-1.61-.189-2.396-.186zm-2.486 1.41c.475 0 .863.394.863.879a.87.87 0 0 1-.863.874.868.868 0 0 1-.863-.874c0-.485.386-.879.863-.879z"/><linearGradient id="path1950_1_" gradientUnits="userSpaceOnUse" x1="548.13" y1="-314.489" x2="541.454" y2="-305.043" gradientTransform="matrix(.5625 0 0 -.568 -282.272 -151.69)"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ffe873"/></linearGradient><path id="path1950_6_" class="st5" d="M26.623 16.64v2.042c0 1.583-1.342 2.915-2.873 2.915h-4.593c-1.258 0-2.299 1.077-2.299 2.337v4.379c0 1.246 1.084 1.979 2.299 2.337 1.456.428 2.851.505 4.593 0 1.158-.335 2.299-1.01 2.299-2.337V26.56h-4.593v-.584h6.892c1.336 0 1.834-.932 2.299-2.331.48-1.44.46-2.826 0-4.673-.33-1.33-.961-2.331-2.299-2.331h-1.725zm-2.584 11.089c.477 0 .863.391.863.874a.871.871 0 0 1-.863.879.872.872 0 0 1-.863-.879.87.87 0 0 1 .863-.874z"/></g></svg>
3,015
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/getpass.py
"""Utilities to get a password and/or the current user name. getpass(prompt[, stream]) - Prompt for a password, with echo turned off. getuser() - Get the user name from the environment or password database. GetPassWarning - This UserWarning is issued when getpass() cannot prevent echoing of the password contents while reading. On Windows, the msvcrt module will be used. """ # Authors: Piers Lauder (original) # Guido van Rossum (Windows support and cleanup) # Gregory P. Smith (tty support & GetPassWarning) import contextlib import io import os import sys import warnings __all__ = ["getpass","getuser","GetPassWarning"] class GetPassWarning(UserWarning): pass def unix_getpass(prompt='Password: ', stream=None): """Prompt for a password, with echo turned off. Args: prompt: Written on stream to ask for the input. Default: 'Password: ' stream: A writable file object to display the prompt. Defaults to the tty. If no tty is available defaults to sys.stderr. Returns: The seKr3t input. Raises: EOFError: If our input tty or stdin was closed. GetPassWarning: When we were unable to turn echo off on the input. Always restores terminal settings before returning. """ passwd = None with contextlib.ExitStack() as stack: try: # Always try reading and writing directly on the tty first. fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY) tty = io.FileIO(fd, 'w+') stack.enter_context(tty) input = io.TextIOWrapper(tty) stack.enter_context(input) if not stream: stream = input except OSError as e: # If that fails, see if stdin can be controlled. stack.close() try: fd = sys.stdin.fileno() except (AttributeError, ValueError): fd = None passwd = fallback_getpass(prompt, stream) input = sys.stdin if not stream: stream = sys.stderr if fd is not None: try: old = termios.tcgetattr(fd) # a copy to save new = old[:] new[3] &= ~termios.ECHO # 3 == 'lflags' tcsetattr_flags = termios.TCSAFLUSH if hasattr(termios, 'TCSASOFT'): tcsetattr_flags |= termios.TCSASOFT try: termios.tcsetattr(fd, tcsetattr_flags, new) passwd = _raw_input(prompt, stream, input=input) finally: termios.tcsetattr(fd, tcsetattr_flags, old) stream.flush() # issue7208 except termios.error: if passwd is not None: # _raw_input succeeded. The final tcsetattr failed. Reraise # instead of leaving the terminal in an unknown state. raise # We can't control the tty or stdin. Give up and use normal IO. # fallback_getpass() raises an appropriate warning. if stream is not input: # clean up unused file objects before blocking stack.close() passwd = fallback_getpass(prompt, stream) stream.write('\n') return passwd def win_getpass(prompt='Password: ', stream=None): """Prompt for password with echo off, using Windows getch().""" if sys.stdin is not sys.__stdin__: return fallback_getpass(prompt, stream) for c in prompt: msvcrt.putwch(c) pw = "" while 1: c = msvcrt.getwch() if c == '\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putwch('\r') msvcrt.putwch('\n') return pw def fallback_getpass(prompt='Password: ', stream=None): warnings.warn("Can not control echo on the terminal.", GetPassWarning, stacklevel=2) if not stream: stream = sys.stderr print("Warning: Password input may be echoed.", file=stream) return _raw_input(prompt, stream) def _raw_input(prompt="", stream=None, input=None): # This doesn't save the string in the GNU readline history. if not stream: stream = sys.stderr if not input: input = sys.stdin prompt = str(prompt) if prompt: try: stream.write(prompt) except UnicodeEncodeError: # Use replace error handler to get as much as possible printed. prompt = prompt.encode(stream.encoding, 'replace') prompt = prompt.decode(stream.encoding) stream.write(prompt) stream.flush() # NOTE: The Python C API calls flockfile() (and unlock) during readline. line = input.readline() if not line: raise EOFError if line[-1] == '\n': line = line[:-1] return line def getuser(): """Get the username from the environment or password database. First try various environment variables, then the password database. This works on Windows as long as USERNAME is set. """ for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'): user = os.environ.get(name) if user: return user # If this fails, the exception will "explain" why import pwd return pwd.getpwuid(os.getuid())[0] # Bind the name getpass to the appropriate function try: import termios # it's possible there is an incompatible termios from the # McMillan Installer, make sure we have a UNIX-compatible termios termios.tcgetattr, termios.tcsetattr except (ImportError, AttributeError): try: import msvcrt except ImportError: getpass = fallback_getpass else: getpass = win_getpass else: getpass = unix_getpass
5,994
186
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/_compression.py
"""Internal classes used by the gzip, lzma and bz2 modules""" import io BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE # Compressed data read chunk size class BaseStream(io.BufferedIOBase): """Mode-checking helper functions.""" def _check_not_closed(self): if self.closed: raise ValueError("I/O operation on closed file") def _check_can_read(self): if not self.readable(): raise io.UnsupportedOperation("File not open for reading") def _check_can_write(self): if not self.writable(): raise io.UnsupportedOperation("File not open for writing") def _check_can_seek(self): if not self.readable(): raise io.UnsupportedOperation("Seeking is only supported " "on files open for reading") if not self.seekable(): raise io.UnsupportedOperation("The underlying file object " "does not support seeking") class DecompressReader(io.RawIOBase): """Adapts the decompressor API to a RawIOBase reader API""" def readable(self): return True def __init__(self, fp, decomp_factory, trailing_error=(), **decomp_args): self._fp = fp self._eof = False self._pos = 0 # Current offset in decompressed stream # Set to size of decompressed stream once it is known, for SEEK_END self._size = -1 # Save the decompressor factory and arguments. # If the file contains multiple compressed streams, each # stream will need a separate decompressor object. A new decompressor # object is also needed when implementing a backwards seek(). self._decomp_factory = decomp_factory self._decomp_args = decomp_args self._decompressor = self._decomp_factory(**self._decomp_args) # Exception class to catch from decompressor signifying invalid # trailing data to ignore self._trailing_error = trailing_error def close(self): self._decompressor = None return super().close() def seekable(self): return self._fp.seekable() def readinto(self, b): with memoryview(b) as view, view.cast("B") as byte_view: data = self.read(len(byte_view)) byte_view[:len(data)] = data return len(data) def read(self, size=-1): if size < 0: return self.readall() if not size or self._eof: return b"" data = None # Default if EOF is encountered # Depending on the input data, our call to the decompressor may not # return any data. In this case, try again after reading another block. while True: if self._decompressor.eof: rawblock = (self._decompressor.unused_data or self._fp.read(BUFFER_SIZE)) if not rawblock: break # Continue to next stream. self._decompressor = self._decomp_factory( **self._decomp_args) try: data = self._decompressor.decompress(rawblock, size) except self._trailing_error: # Trailing data isn't a valid compressed stream; ignore it. break else: if self._decompressor.needs_input: rawblock = self._fp.read(BUFFER_SIZE) if not rawblock: raise EOFError("Compressed file ended before the " "end-of-stream marker was reached") else: rawblock = b"" data = self._decompressor.decompress(rawblock, size) if data: break if not data: self._eof = True self._size = self._pos return b"" self._pos += len(data) return data # Rewind the file to the beginning of the data stream. def _rewind(self): self._fp.seek(0) self._eof = False self._pos = 0 self._decompressor = self._decomp_factory(**self._decomp_args) def seek(self, offset, whence=io.SEEK_SET): # Recalculate offset as an absolute file position. if whence == io.SEEK_SET: pass elif whence == io.SEEK_CUR: offset = self._pos + offset elif whence == io.SEEK_END: # Seeking relative to EOF - we need to know the file's size. if self._size < 0: while self.read(io.DEFAULT_BUFFER_SIZE): pass offset = self._size + offset else: raise ValueError("Invalid value for whence: {}".format(whence)) # Make it so that offset is the number of bytes to skip forward. if offset < self._pos: self._rewind() else: offset -= self._pos # Read and discard data until we reach the desired position. while offset > 0: data = self.read(min(io.DEFAULT_BUFFER_SIZE, offset)) if not data: break offset -= len(data) return self._pos def tell(self): """Return the current file position.""" return self._pos
5,340
153
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/selectors.py
"""Selectors module. This module allows high-level and efficient I/O multiplexing, built upon the `select` module primitives. """ from abc import ABCMeta, abstractmethod from collections import namedtuple from collections.abc import Mapping import math import select import sys # generic events, that must be mapped to implementation-specific ones EVENT_READ = (1 << 0) EVENT_WRITE = (1 << 1) def _fileobj_to_fd(fileobj): """Return a file descriptor from a file object. Parameters: fileobj -- file object or file descriptor Returns: corresponding file descriptor Raises: ValueError if the object is invalid """ if isinstance(fileobj, int): fd = fileobj else: try: fd = int(fileobj.fileno()) except (AttributeError, TypeError, ValueError): raise ValueError("Invalid file object: " "{!r}".format(fileobj)) from None if fd < 0: raise ValueError("Invalid file descriptor: {}".format(fd)) return fd SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data']) SelectorKey.__doc__ = """SelectorKey(fileobj, fd, events, data) Object used to associate a file object to its backing file descriptor, selected event mask, and attached data. """ if sys.version_info >= (3, 5): SelectorKey.fileobj.__doc__ = 'File object registered.' SelectorKey.fd.__doc__ = 'Underlying file descriptor.' SelectorKey.events.__doc__ = 'Events that must be waited for on this file object.' SelectorKey.data.__doc__ = ('''Optional opaque data associated to this file object. For example, this could be used to store a per-client session ID.''') class _SelectorMapping(Mapping): """Mapping of file objects to selector keys.""" def __init__(self, selector): self._selector = selector def __len__(self): return len(self._selector._fd_to_key) def __getitem__(self, fileobj): try: fd = self._selector._fileobj_lookup(fileobj) return self._selector._fd_to_key[fd] except KeyError: raise KeyError("{!r} is not registered".format(fileobj)) from None def __iter__(self): return iter(self._selector._fd_to_key) class BaseSelector(metaclass=ABCMeta): """Selector abstract base class. A selector supports registering file objects to be monitored for specific I/O events. A file object is a file descriptor or any object with a `fileno()` method. An arbitrary object can be attached to the file object, which can be used for example to store context information, a callback, etc. A selector can use various implementations (select(), poll(), epoll()...) depending on the platform. The default `Selector` class uses the most efficient implementation on the current platform. """ @abstractmethod def register(self, fileobj, events, data=None): """Register a file object. Parameters: fileobj -- file object or file descriptor events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) data -- attached data Returns: SelectorKey instance Raises: ValueError if events is invalid KeyError if fileobj is already registered OSError if fileobj is closed or otherwise is unacceptable to the underlying system call (if a system call is made) Note: OSError may or may not be raised """ raise NotImplementedError @abstractmethod def unregister(self, fileobj): """Unregister a file object. Parameters: fileobj -- file object or file descriptor Returns: SelectorKey instance Raises: KeyError if fileobj is not registered Note: If fileobj is registered but has since been closed this does *not* raise OSError (even if the wrapped syscall does) """ raise NotImplementedError def modify(self, fileobj, events, data=None): """Change a registered file object monitored events or attached data. Parameters: fileobj -- file object or file descriptor events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) data -- attached data Returns: SelectorKey instance Raises: Anything that unregister() or register() raises """ self.unregister(fileobj) return self.register(fileobj, events, data) @abstractmethod def select(self, timeout=None): """Perform the actual selection, until some monitored file objects are ready or a timeout expires. Parameters: timeout -- if timeout > 0, this specifies the maximum wait time, in seconds if timeout <= 0, the select() call won't block, and will report the currently ready file objects if timeout is None, select() will block until a monitored file object becomes ready Returns: list of (key, events) for ready file objects `events` is a bitwise mask of EVENT_READ|EVENT_WRITE """ raise NotImplementedError def close(self): """Close the selector. This must be called to make sure that any underlying resource is freed. """ pass def get_key(self, fileobj): """Return the key associated to a registered file object. Returns: SelectorKey for this file object """ mapping = self.get_map() if mapping is None: raise RuntimeError('Selector is closed') try: return mapping[fileobj] except KeyError: raise KeyError("{!r} is not registered".format(fileobj)) from None @abstractmethod def get_map(self): """Return a mapping of file objects to selector keys.""" raise NotImplementedError def __enter__(self): return self def __exit__(self, *args): self.close() class _BaseSelectorImpl(BaseSelector): """Base selector implementation.""" def __init__(self): # this maps file descriptors to keys self._fd_to_key = {} # read-only mapping returned by get_map() self._map = _SelectorMapping(self) def _fileobj_lookup(self, fileobj): """Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. This is used by unregister() so we can unregister an object that was previously registered even if it is closed. It is also used by _SelectorMapping. """ try: return _fileobj_to_fd(fileobj) except ValueError: # Do an exhaustive search. for key in self._fd_to_key.values(): if key.fileobj is fileobj: return key.fd # Raise ValueError after all. raise def register(self, fileobj, events, data=None): if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)): raise ValueError("Invalid events: {!r}".format(events)) key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data) if key.fd in self._fd_to_key: raise KeyError("{!r} (FD {}) is already registered" .format(fileobj, key.fd)) self._fd_to_key[key.fd] = key return key def unregister(self, fileobj): try: key = self._fd_to_key.pop(self._fileobj_lookup(fileobj)) except KeyError: raise KeyError("{!r} is not registered".format(fileobj)) from None return key def modify(self, fileobj, events, data=None): # TODO: Subclasses can probably optimize this even further. try: key = self._fd_to_key[self._fileobj_lookup(fileobj)] except KeyError: raise KeyError("{!r} is not registered".format(fileobj)) from None if events != key.events: self.unregister(fileobj) key = self.register(fileobj, events, data) elif data != key.data: # Use a shortcut to update the data. key = key._replace(data=data) self._fd_to_key[key.fd] = key return key def close(self): self._fd_to_key.clear() self._map = None def get_map(self): return self._map def _key_from_fd(self, fd): """Return the key associated to a given file descriptor. Parameters: fd -- file descriptor Returns: corresponding key, or None if not found """ try: return self._fd_to_key[fd] except KeyError: return None class SelectSelector(_BaseSelectorImpl): """Select-based selector.""" def __init__(self): super().__init__() self._readers = set() self._writers = set() def register(self, fileobj, events, data=None): key = super().register(fileobj, events, data) if events & EVENT_READ: self._readers.add(key.fd) if events & EVENT_WRITE: self._writers.add(key.fd) return key def unregister(self, fileobj): key = super().unregister(fileobj) self._readers.discard(key.fd) self._writers.discard(key.fd) return key if sys.platform == 'win32': def _select(self, r, w, _, timeout=None): r, w, x = select.select(r, w, w, timeout) return r, w + x, [] else: _select = select.select def select(self, timeout=None): timeout = None if timeout is None else max(timeout, 0) ready = [] try: r, w, _ = self._select(self._readers, self._writers, [], timeout) except InterruptedError: return ready r = set(r) w = set(w) for fd in r | w: events = 0 if fd in r: events |= EVENT_READ if fd in w: events |= EVENT_WRITE key = self._key_from_fd(fd) if key: ready.append((key, events & key.events)) return ready if hasattr(select, 'poll'): class PollSelector(_BaseSelectorImpl): """Poll-based selector.""" def __init__(self): super().__init__() self._poll = select.poll() def register(self, fileobj, events, data=None): key = super().register(fileobj, events, data) poll_events = 0 if events & EVENT_READ: poll_events |= select.POLLIN if events & EVENT_WRITE: poll_events |= select.POLLOUT self._poll.register(key.fd, poll_events) return key def unregister(self, fileobj): key = super().unregister(fileobj) self._poll.unregister(key.fd) return key def select(self, timeout=None): if timeout is None: timeout = None elif timeout <= 0: timeout = 0 else: # poll() has a resolution of 1 millisecond, round away from # zero to wait *at least* timeout seconds. timeout = math.ceil(timeout * 1e3) ready = [] try: fd_event_list = self._poll.poll(timeout) except InterruptedError: return ready for fd, event in fd_event_list: events = 0 if event & ~select.POLLIN: events |= EVENT_WRITE if event & ~select.POLLOUT: events |= EVENT_READ key = self._key_from_fd(fd) if key: ready.append((key, events & key.events)) return ready if hasattr(select, 'epoll'): class EpollSelector(_BaseSelectorImpl): """Epoll-based selector.""" def __init__(self): super().__init__() self._epoll = select.epoll() def fileno(self): return self._epoll.fileno() def register(self, fileobj, events, data=None): key = super().register(fileobj, events, data) epoll_events = 0 if events & EVENT_READ: epoll_events |= select.EPOLLIN if events & EVENT_WRITE: epoll_events |= select.EPOLLOUT try: self._epoll.register(key.fd, epoll_events) except BaseException: super().unregister(fileobj) raise return key def unregister(self, fileobj): key = super().unregister(fileobj) try: self._epoll.unregister(key.fd) except OSError: # This can happen if the FD was closed since it # was registered. pass return key def select(self, timeout=None): if timeout is None: timeout = -1 elif timeout <= 0: timeout = 0 else: # epoll_wait() has a resolution of 1 millisecond, round away # from zero to wait *at least* timeout seconds. timeout = math.ceil(timeout * 1e3) * 1e-3 # epoll_wait() expects `maxevents` to be greater than zero; # we want to make sure that `select()` can be called when no # FD is registered. max_ev = max(len(self._fd_to_key), 1) ready = [] try: fd_event_list = self._epoll.poll(timeout, max_ev) except InterruptedError: return ready for fd, event in fd_event_list: events = 0 if event & ~select.EPOLLIN: events |= EVENT_WRITE if event & ~select.EPOLLOUT: events |= EVENT_READ key = self._key_from_fd(fd) if key: ready.append((key, events & key.events)) return ready def close(self): self._epoll.close() super().close() if hasattr(select, 'devpoll'): class DevpollSelector(_BaseSelectorImpl): """Solaris /dev/poll selector.""" def __init__(self): super().__init__() self._devpoll = select.devpoll() def fileno(self): return self._devpoll.fileno() def register(self, fileobj, events, data=None): key = super().register(fileobj, events, data) poll_events = 0 if events & EVENT_READ: poll_events |= select.POLLIN if events & EVENT_WRITE: poll_events |= select.POLLOUT self._devpoll.register(key.fd, poll_events) return key def unregister(self, fileobj): key = super().unregister(fileobj) self._devpoll.unregister(key.fd) return key def select(self, timeout=None): if timeout is None: timeout = None elif timeout <= 0: timeout = 0 else: # devpoll() has a resolution of 1 millisecond, round away from # zero to wait *at least* timeout seconds. timeout = math.ceil(timeout * 1e3) ready = [] try: fd_event_list = self._devpoll.poll(timeout) except InterruptedError: return ready for fd, event in fd_event_list: events = 0 if event & ~select.POLLIN: events |= EVENT_WRITE if event & ~select.POLLOUT: events |= EVENT_READ key = self._key_from_fd(fd) if key: ready.append((key, events & key.events)) return ready def close(self): self._devpoll.close() super().close() if hasattr(select, 'kqueue'): class KqueueSelector(_BaseSelectorImpl): """Kqueue-based selector.""" def __init__(self): super().__init__() self._kqueue = select.kqueue() def fileno(self): return self._kqueue.fileno() def register(self, fileobj, events, data=None): key = super().register(fileobj, events, data) try: if events & EVENT_READ: kev = select.kevent(key.fd, select.KQ_FILTER_READ, select.KQ_EV_ADD) self._kqueue.control([kev], 0, 0) if events & EVENT_WRITE: kev = select.kevent(key.fd, select.KQ_FILTER_WRITE, select.KQ_EV_ADD) self._kqueue.control([kev], 0, 0) except BaseException: super().unregister(fileobj) raise return key def unregister(self, fileobj): key = super().unregister(fileobj) if key.events & EVENT_READ: kev = select.kevent(key.fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE) try: self._kqueue.control([kev], 0, 0) except OSError: # This can happen if the FD was closed since it # was registered. pass if key.events & EVENT_WRITE: kev = select.kevent(key.fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE) try: self._kqueue.control([kev], 0, 0) except OSError: # See comment above. pass return key def select(self, timeout=None): timeout = None if timeout is None else max(timeout, 0) max_ev = len(self._fd_to_key) ready = [] try: kev_list = self._kqueue.control(None, max_ev, timeout) except InterruptedError: return ready for kev in kev_list: fd = kev.ident flag = kev.filter events = 0 if flag == select.KQ_FILTER_READ: events |= EVENT_READ if flag == select.KQ_FILTER_WRITE: events |= EVENT_WRITE key = self._key_from_fd(fd) if key: ready.append((key, events & key.events)) return ready def close(self): self._kqueue.close() super().close() # Choose the best implementation, roughly: # epoll|kqueue|devpoll > poll > select. # select() also can't accept a FD > FD_SETSIZE (usually around 1024) if 'KqueueSelector' in globals(): DefaultSelector = KqueueSelector elif 'EpollSelector' in globals(): DefaultSelector = EpollSelector elif 'DevpollSelector' in globals(): DefaultSelector = DevpollSelector elif 'PollSelector' in globals(): DefaultSelector = PollSelector else: DefaultSelector = SelectSelector
19,465
613
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/glob.py
"""Filename globbing utility.""" import os import re import fnmatch __all__ = ["glob", "iglob", "escape"] def glob(pathname, *, recursive=False): """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories. """ return list(iglob(pathname, recursive=recursive)) def iglob(pathname, *, recursive=False): """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories. """ it = _iglob(pathname, recursive, False) if recursive and _isrecursive(pathname): s = next(it) # skip empty string assert not s return it def _iglob(pathname, recursive, dironly): dirname, basename = os.path.split(pathname) if not has_magic(pathname): assert not dironly if basename: if os.path.lexists(pathname): yield pathname else: # Patterns ending with a slash should match only directories if os.path.isdir(dirname): yield pathname return if not dirname: if recursive and _isrecursive(basename): yield from _glob2(dirname, basename, dironly) else: yield from _glob1(dirname, basename, dironly) return # `os.path.split()` returns the argument itself as a dirname if it is a # drive or UNC path. Prevent an infinite recursion if a drive or UNC path # contains magic characters (i.e. r'\\?\C:'). if dirname != pathname and has_magic(dirname): dirs = _iglob(dirname, recursive, True) else: dirs = [dirname] if has_magic(basename): if recursive and _isrecursive(basename): glob_in_dir = _glob2 else: glob_in_dir = _glob1 else: glob_in_dir = _glob0 for dirname in dirs: for name in glob_in_dir(dirname, basename, dironly): yield os.path.join(dirname, name) # These 2 helper functions non-recursively glob inside a literal directory. # They return a list of basenames. _glob1 accepts a pattern while _glob0 # takes a literal basename (so it only has to check for its existence). def _glob1(dirname, pattern, dironly): names = list(_iterdir(dirname, dironly)) if not _ishidden(pattern): names = (x for x in names if not _ishidden(x)) return fnmatch.filter(names, pattern) def _glob0(dirname, basename, dironly): if not basename: # `os.path.split()` returns an empty basename for paths ending with a # directory separator. 'q*x/' should match only directories. if os.path.isdir(dirname): return [basename] else: if os.path.lexists(os.path.join(dirname, basename)): return [basename] return [] # Following functions are not public but can be used by third-party code. def glob0(dirname, pattern): return _glob0(dirname, pattern, False) def glob1(dirname, pattern): return _glob1(dirname, pattern, False) # This helper function recursively yields relative pathnames inside a literal # directory. def _glob2(dirname, pattern, dironly): assert _isrecursive(pattern) yield pattern[:0] yield from _rlistdir(dirname, dironly) # If dironly is false, yields all file names inside a directory. # If dironly is true, yields only directory names. def _iterdir(dirname, dironly): if not dirname: if isinstance(dirname, bytes): dirname = bytes(os.curdir, 'ASCII') else: dirname = os.curdir try: with os.scandir(dirname) as it: for entry in it: try: if not dironly or entry.is_dir(): yield entry.name except OSError: pass except OSError: return # Recursively yields relative pathnames inside a literal directory. def _rlistdir(dirname, dironly): names = list(_iterdir(dirname, dironly)) for x in names: if not _ishidden(x): yield x path = os.path.join(dirname, x) if dirname else x for y in _rlistdir(path, dironly): yield os.path.join(x, y) magic_check = re.compile('([*?[])') magic_check_bytes = re.compile(b'([*?[])') def has_magic(s): if isinstance(s, bytes): match = magic_check_bytes.search(s) else: match = magic_check.search(s) return match is not None def _ishidden(path): return path[0] in ('.', b'.'[0]) def _isrecursive(pattern): if isinstance(pattern, bytes): return pattern == b'**' else: return pattern == '**' def escape(pathname): """Escape all special characters. """ # Escaping is done by wrapping any of "*?[" between square brackets. # Metacharacters do not work in the drive part and shouldn't be escaped. drive, pathname = os.path.splitdrive(pathname) if isinstance(pathname, bytes): pathname = magic_check_bytes.sub(br'[\1]', pathname) else: pathname = magic_check.sub(r'[\1]', pathname) return drive + pathname
5,638
172
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/rlcompleter.py
"""Word completion for GNU readline. The completer completes keywords, built-ins and globals in a selectable namespace (which defaults to __main__); when completing NAME.NAME..., it evaluates (!) the expression up to the last dot and completes its attributes. It's very cool to do "import sys" type "sys.", hit the completion key (twice), and see the list of names defined by the sys module! Tip: to use the tab key as the completion key, call readline.parse_and_bind("tab: complete") Notes: - Exceptions raised by the completer function are *ignored* (and generally cause the completion to fail). This is a feature -- since readline sets the tty device in raw (or cbreak) mode, printing a traceback wouldn't work well without some complicated hoopla to save, reset and restore the tty state. - The evaluation of the NAME.NAME... form may cause arbitrary application defined code to be executed if an object with a __getattr__ hook is found. Since it is the responsibility of the application (or the user) to enable this feature, I consider this an acceptable risk. More complicated expressions (e.g. function calls or indexing operations) are *not* evaluated. - When the original stdin is not a tty device, GNU readline is never used, and this module (and the readline module) are silently inactive. """ import atexit import builtins import __main__ __all__ = ["Completer"] class Completer: def __init__(self, namespace = None): """Create a new completer for the command line. Completer([namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete) """ if namespace and not isinstance(namespace, dict): raise TypeError('namespace must be a dictionary') # Don't bind to namespace quite yet, but flag whether the user wants a # specific namespace or to use __main__.__dict__. This will allow us # to bind to __main__.__dict__ at completion time, not now. if namespace is None: self.use_main_ns = 1 else: self.use_main_ns = 0 self.namespace = namespace def complete(self, text, state): """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. """ if self.use_main_ns: self.namespace = __main__.__dict__ if not text.strip(): if state == 0: if _readline_available: readline.insert_text('\t') readline.redisplay() return '' else: return '\t' else: return None if state == 0: if "." in text: self.matches = self.attr_matches(text) else: self.matches = self.global_matches(text) try: return self.matches[state] except IndexError: return None def _callable_postfix(self, val, word): if callable(val): word = word + "(" return word def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] seen = {"__builtins__"} n = len(text) for word in keyword.kwlist: if word[:n] == text: seen.add(word) if word in {'finally', 'try'}: word = word + ':' elif word not in {'False', 'None', 'True', 'break', 'continue', 'pass', 'else'}: word = word + ' ' matches.append(word) for nspace in [self.namespace, builtins.__dict__]: for word, val in nspace.items(): if word[:n] == text and word not in seen: seen.add(word) matches.append(self._callable_postfix(val, word)) return matches def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluable in self.namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ import re m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return [] expr, attr = m.group(1, 3) try: thisobject = eval(expr, self.namespace) except Exception: return [] # get the content of the object, except __builtins__ words = set(dir(thisobject)) words.discard("__builtins__") if hasattr(thisobject, '__class__'): words.add('__class__') words.update(get_class_members(thisobject.__class__)) matches = [] n = len(attr) if attr == '': noprefix = '_' elif attr == '_': noprefix = '__' else: noprefix = None while True: for word in words: if (word[:n] == attr and not (noprefix and word[:n+1] == noprefix)): match = "%s.%s" % (expr, word) try: val = getattr(thisobject, word) except Exception: pass # Include even if attribute not set else: match = self._callable_postfix(val, match) matches.append(match) if matches or not noprefix: break if noprefix == '_': noprefix = '__' else: noprefix = None matches.sort() return matches def get_class_members(klass): ret = dir(klass) if hasattr(klass,'__bases__'): for base in klass.__bases__: ret = ret + get_class_members(base) return ret try: import readline except ImportError: _readline_available = False else: readline.set_completer(Completer().complete) # Release references early at shutdown (the readline module's # contents are quasi-immortal, and the completer function holds a # reference to globals). atexit.register(lambda: readline.set_completer(None)) _readline_available = True
7,097
206
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/decimal.py
try: from _decimal import * from _decimal import __version__ from _decimal import __libmpdec_version__ except ImportError: from _pydecimal import * from _pydecimal import __version__ from _pydecimal import __libmpdec_version__ try: from _decimal import __doc__ except ImportError: try: from _pydecimal import __doc__ except ImportError: pass if __name__ == 'PYOBJ.COM': import _decimal BasicContext = 0 Clamped = 0 Context = 0 ConversionSyntax = 0 Decimal = 0 DecimalException = 0 DecimalTuple = 0 DefaultContext = 0 DivisionByZero = 0 DivisionImpossible = 0 DivisionUndefined = 0 ExtendedContext = 0 FloatOperation = 0 HAVE_THREADS = 0 Inexact = 0 InvalidContext = 0 InvalidOperation = 0 MAX_EMAX = 0 MAX_PREC = 0 MIN_EMIN = 0 MIN_ETINY = 0 Overflow = 0 ROUND_05UP = 0 ROUND_CEILING = 0 ROUND_DOWN = 0 ROUND_FLOOR = 0 ROUND_HALF_DOWN = 0 ROUND_HALF_EVEN = 0 ROUND_HALF_UP = 0 ROUND_UP = 0 Rounded = 0 Subnormal = 0 Underflow = 0 __libmpdec_version__ = 0 __version__ = 0 getcontext = 0 localcontext = 0 setcontext = 0
1,228
58
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/linecache.py
"""Cache lines from Python source files. This is intended to read lines from modules imported -- hence if a filename is not found, it will look down the module search path for a file by that name. """ import functools import sys import os import tokenize __all__ = ["getline", "clearcache", "checkcache"] def getline(filename, lineno, module_globals=None): lines = getlines(filename, module_globals) if 1 <= lineno <= len(lines): return lines[lineno-1] else: return '' # The cache # The cache. Maps filenames to either a thunk which will provide source code, # or a tuple (size, mtime, lines, fullname) once loaded. cache = {} def clearcache(): """Clear the cache entirely.""" global cache cache = {} def getlines(filename, module_globals=None): """Get the lines for a Python source file from the cache. Update the cache if it doesn't contain an entry for this file already.""" if filename in cache: entry = cache[filename] if len(entry) != 1: return cache[filename][2] try: return updatecache(filename, module_globals) except MemoryError: clearcache() return [] def checkcache(filename=None): """Discard cache entries that are out of date. (This is not checked upon each call!)""" if filename is None: filenames = list(cache.keys()) else: if filename in cache: filenames = [filename] else: return for filename in filenames: entry = cache[filename] if len(entry) == 1: # lazy cache entry, leave it lazy. continue size, mtime, lines, fullname = entry if mtime is None: continue # no-op for files loaded via a __loader__ try: stat = os.stat(fullname) except OSError: del cache[filename] continue if size != stat.st_size or mtime != stat.st_mtime: del cache[filename] def updatecache(filename, module_globals=None): """Update a cache entry and return its list of lines. If something's wrong, print a message, discard the cache entry, and return an empty list.""" if filename in cache: if len(cache[filename]) != 1: del cache[filename] if not filename or (filename.startswith('<') and filename.endswith('>')): return [] fullname = filename try: stat = os.stat(fullname) except OSError: basename = filename # Realise a lazy loader based lookup if there is one # otherwise try to lookup right now. if lazycache(filename, module_globals): try: data = cache[filename][0]() except (ImportError, OSError): pass else: if data is None: # No luck, the PEP302 loader cannot find the source # for this module. return [] cache[filename] = ( len(data), None, [line+'\n' for line in data.splitlines()], fullname ) return cache[filename][2] # Try looking through the module search path, which is only useful # when handling a relative filename. if os.path.isabs(filename): return [] for dirname in sys.path: try: fullname = os.path.join(dirname, basename) except (TypeError, AttributeError): # Not sufficiently string-like to do anything useful with. continue try: stat = os.stat(fullname) break except OSError: pass else: return [] try: with tokenize.open(fullname) as fp: lines = fp.readlines() except OSError: return [] if lines and not lines[-1].endswith('\n'): lines[-1] += '\n' size, mtime = stat.st_size, stat.st_mtime cache[filename] = size, mtime, lines, fullname return lines def lazycache(filename, module_globals): """Seed the cache for filename with module_globals. The module loader will be asked for the source only when getlines is called, not immediately. If there is an entry in the cache already, it is not altered. :return: True if a lazy load is registered in the cache, otherwise False. To register such a load a module loader with a get_source method must be found, the filename must be a cachable filename, and the filename must not be already cached. """ if filename in cache: if len(cache[filename]) == 1: return True else: return False if not filename or (filename.startswith('<') and filename.endswith('>')): return False # Try for a __loader__, if available if module_globals and '__loader__' in module_globals: name = module_globals.get('__name__') loader = module_globals['__loader__'] get_source = getattr(loader, 'get_source', None) if name and get_source: get_lines = functools.partial(get_source, name) cache[filename] = (get_lines,) return True return False
5,312
178
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/stat.py
"""Constants/functions for interpreting results of os.stat() and os.lstat(). Suggested usage: from stat import * """ from _stat import * # Windows FILE_ATTRIBUTE constants for interpreting os.stat()'s # "st_file_attributes" member FILE_ATTRIBUTE_ARCHIVE = 32 FILE_ATTRIBUTE_COMPRESSED = 2048 FILE_ATTRIBUTE_DEVICE = 64 FILE_ATTRIBUTE_DIRECTORY = 16 FILE_ATTRIBUTE_ENCRYPTED = 16384 FILE_ATTRIBUTE_HIDDEN = 2 FILE_ATTRIBUTE_INTEGRITY_STREAM = 32768 FILE_ATTRIBUTE_NORMAL = 128 FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192 FILE_ATTRIBUTE_NO_SCRUB_DATA = 131072 FILE_ATTRIBUTE_OFFLINE = 4096 FILE_ATTRIBUTE_READONLY = 1 FILE_ATTRIBUTE_REPARSE_POINT = 1024 FILE_ATTRIBUTE_SPARSE_FILE = 512 FILE_ATTRIBUTE_SYSTEM = 4 FILE_ATTRIBUTE_TEMPORARY = 256 FILE_ATTRIBUTE_VIRTUAL = 65536 if __name__ == 'PYOBJ.COM': import _stat
819
31
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/pstats.py
"""Class for printing reports on profiled python code.""" # Written by James Roskind # Based on prior profile module by Sjoerd Mullender... # which was hacked somewhat by: Guido van Rossum # Copyright Disney Enterprises, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific language # governing permissions and limitations under the License. import sys import os import time import marshal import re from functools import cmp_to_key __all__ = ["Stats"] class Stats: """This class is used for creating reports from data generated by the Profile class. It is a "friend" of that class, and imports data either by direct access to members of Profile class, or by reading in a dictionary that was emitted (via marshal) from the Profile class. The big change from the previous Profiler (in terms of raw functionality) is that an "add()" method has been provided to combine Stats from several distinct profile runs. Both the constructor and the add() method now take arbitrarily many file names as arguments. All the print methods now take an argument that indicates how many lines to print. If the arg is a floating point number between 0 and 1.0, then it is taken as a decimal percentage of the available lines to be printed (e.g., .1 means print 10% of all available lines). If it is an integer, it is taken to mean the number of lines of data that you wish to have printed. The sort_stats() method now processes some additional options (i.e., in addition to the old -1, 0, 1, or 2 that are respectively interpreted as 'stdname', 'calls', 'time', and 'cumulative'). It takes an arbitrary number of quoted strings to select the sort order. For example sort_stats('time', 'name') sorts on the major key of 'internal function time', and on the minor key of 'the name of the function'. Look at the two tables in sort_stats() and get_sort_arg_defs(self) for more examples. All methods return self, so you can string together commands like: Stats('foo', 'goo').strip_dirs().sort_stats('calls').\ print_stats(5).print_callers(5) """ def __init__(self, *args, stream=None): self.stream = stream or sys.stdout if not len(args): arg = None else: arg = args[0] args = args[1:] self.init(arg) self.add(*args) def init(self, arg): self.all_callees = None # calc only if needed self.files = [] self.fcn_list = None self.total_tt = 0 self.total_calls = 0 self.prim_calls = 0 self.max_name_len = 0 self.top_level = set() self.stats = {} self.sort_arg_dict = {} self.load_stats(arg) try: self.get_top_level_stats() except Exception: print("Invalid timing data %s" % (self.files[-1] if self.files else ''), file=self.stream) raise def load_stats(self, arg): if arg is None: self.stats = {} return elif isinstance(arg, str): with open(arg, 'rb') as f: self.stats = marshal.load(f) try: file_stats = os.stat(arg) arg = time.ctime(file_stats.st_mtime) + " " + arg except: # in case this is not unix pass self.files = [arg] elif hasattr(arg, 'create_stats'): arg.create_stats() self.stats = arg.stats arg.stats = {} if not self.stats: raise TypeError("Cannot create or construct a %r object from %r" % (self.__class__, arg)) return def get_top_level_stats(self): for func, (cc, nc, tt, ct, callers) in self.stats.items(): self.total_calls += nc self.prim_calls += cc self.total_tt += tt if ("jprofile", 0, "profiler") in callers: self.top_level.add(func) if len(func_std_string(func)) > self.max_name_len: self.max_name_len = len(func_std_string(func)) def add(self, *arg_list): if not arg_list: return self for item in reversed(arg_list): if type(self) != type(item): item = Stats(item) self.files += item.files self.total_calls += item.total_calls self.prim_calls += item.prim_calls self.total_tt += item.total_tt for func in item.top_level: self.top_level.add(func) if self.max_name_len < item.max_name_len: self.max_name_len = item.max_name_len self.fcn_list = None for func, stat in item.stats.items(): if func in self.stats: old_func_stat = self.stats[func] else: old_func_stat = (0, 0, 0, 0, {},) self.stats[func] = add_func_stats(old_func_stat, stat) return self def dump_stats(self, filename): """Write the profile data to a file we know how to load back.""" with open(filename, 'wb') as f: marshal.dump(self.stats, f) # list the tuple indices and directions for sorting, # along with some printable description sort_arg_dict_default = { "calls" : (((1,-1), ), "call count"), "ncalls" : (((1,-1), ), "call count"), "cumtime" : (((3,-1), ), "cumulative time"), "cumulative": (((3,-1), ), "cumulative time"), "file" : (((4, 1), ), "file name"), "filename" : (((4, 1), ), "file name"), "line" : (((5, 1), ), "line number"), "module" : (((4, 1), ), "file name"), "name" : (((6, 1), ), "function name"), "nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"), "pcalls" : (((0,-1), ), "primitive call count"), "stdname" : (((7, 1), ), "standard name"), "time" : (((2,-1), ), "internal time"), "tottime" : (((2,-1), ), "internal time"), } def get_sort_arg_defs(self): """Expand all abbreviations that are unique.""" if not self.sort_arg_dict: self.sort_arg_dict = dict = {} bad_list = {} for word, tup in self.sort_arg_dict_default.items(): fragment = word while fragment: if not fragment: break if fragment in dict: bad_list[fragment] = 0 break dict[fragment] = tup fragment = fragment[:-1] for word in bad_list: del dict[word] return self.sort_arg_dict def sort_stats(self, *field): if not field: self.fcn_list = 0 return self if len(field) == 1 and isinstance(field[0], int): # Be compatible with old profiler field = [ {-1: "stdname", 0: "calls", 1: "time", 2: "cumulative"}[field[0]] ] sort_arg_defs = self.get_sort_arg_defs() sort_tuple = () self.sort_type = "" connector = "" for word in field: sort_tuple = sort_tuple + sort_arg_defs[word][0] self.sort_type += connector + sort_arg_defs[word][1] connector = ", " stats_list = [] for func, (cc, nc, tt, ct, callers) in self.stats.items(): stats_list.append((cc, nc, tt, ct) + func + (func_std_string(func), func)) stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare)) self.fcn_list = fcn_list = [] for tuple in stats_list: fcn_list.append(tuple[-1]) return self def reverse_order(self): if self.fcn_list: self.fcn_list.reverse() return self def strip_dirs(self): oldstats = self.stats self.stats = newstats = {} max_name_len = 0 for func, (cc, nc, tt, ct, callers) in oldstats.items(): newfunc = func_strip_path(func) if len(func_std_string(newfunc)) > max_name_len: max_name_len = len(func_std_string(newfunc)) newcallers = {} for func2, caller in callers.items(): newcallers[func_strip_path(func2)] = caller if newfunc in newstats: newstats[newfunc] = add_func_stats( newstats[newfunc], (cc, nc, tt, ct, newcallers)) else: newstats[newfunc] = (cc, nc, tt, ct, newcallers) old_top = self.top_level self.top_level = new_top = set() for func in old_top: new_top.add(func_strip_path(func)) self.max_name_len = max_name_len self.fcn_list = None self.all_callees = None return self def calc_callees(self): if self.all_callees: return self.all_callees = all_callees = {} for func, (cc, nc, tt, ct, callers) in self.stats.items(): if not func in all_callees: all_callees[func] = {} for func2, caller in callers.items(): if not func2 in all_callees: all_callees[func2] = {} all_callees[func2][func] = caller return #****************************************************************** # The following functions support actual printing of reports #****************************************************************** # Optional "amount" is either a line count, or a percentage of lines. def eval_print_amount(self, sel, list, msg): new_list = list if isinstance(sel, str): try: rex = re.compile(sel) except re.error: msg += " <Invalid regular expression %r>\n" % sel return new_list, msg new_list = [] for func in list: if rex.search(func_std_string(func)): new_list.append(func) else: count = len(list) if isinstance(sel, float) and 0.0 <= sel < 1.0: count = int(count * sel + .5) new_list = list[:count] elif isinstance(sel, int) and 0 <= sel < count: count = sel new_list = list[:count] if len(list) != len(new_list): msg += " List reduced from %r to %r due to restriction <%r>\n" % ( len(list), len(new_list), sel) return new_list, msg def get_print_list(self, sel_list): width = self.max_name_len if self.fcn_list: stat_list = self.fcn_list[:] msg = " Ordered by: " + self.sort_type + '\n' else: stat_list = list(self.stats.keys()) msg = " Random listing order was used\n" for selection in sel_list: stat_list, msg = self.eval_print_amount(selection, stat_list, msg) count = len(stat_list) if not stat_list: return 0, stat_list print(msg, file=self.stream) if count < len(self.stats): width = 0 for func in stat_list: if len(func_std_string(func)) > width: width = len(func_std_string(func)) return width+2, stat_list def print_stats(self, *amount): for filename in self.files: print(filename, file=self.stream) if self.files: print(file=self.stream) indent = ' ' * 8 for func in self.top_level: print(indent, func_get_function_name(func), file=self.stream) print(indent, self.total_calls, "function calls", end=' ', file=self.stream) if self.total_calls != self.prim_calls: print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream) print("in %.3f seconds" % self.total_tt, file=self.stream) print(file=self.stream) width, list = self.get_print_list(amount) if list: self.print_title() for func in list: self.print_line(func) print(file=self.stream) print(file=self.stream) return self def print_callees(self, *amount): width, list = self.get_print_list(amount) if list: self.calc_callees() self.print_call_heading(width, "called...") for func in list: if func in self.all_callees: self.print_call_line(width, func, self.all_callees[func]) else: self.print_call_line(width, func, {}) print(file=self.stream) print(file=self.stream) return self def print_callers(self, *amount): width, list = self.get_print_list(amount) if list: self.print_call_heading(width, "was called by...") for func in list: cc, nc, tt, ct, callers = self.stats[func] self.print_call_line(width, func, callers, "<-") print(file=self.stream) print(file=self.stream) return self def print_call_heading(self, name_size, column_title): print("Function ".ljust(name_size) + column_title, file=self.stream) # print sub-header only if we have new-style callers subheader = False for cc, nc, tt, ct, callers in self.stats.values(): if callers: value = next(iter(callers.values())) subheader = isinstance(value, tuple) break if subheader: print(" "*name_size + " ncalls tottime cumtime", file=self.stream) def print_call_line(self, name_size, source, call_dict, arrow="->"): print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream) if not call_dict: print(file=self.stream) return clist = sorted(call_dict.keys()) indent = "" for func in clist: name = func_std_string(func) value = call_dict[func] if isinstance(value, tuple): nc, cc, tt, ct = value if nc != cc: substats = '%d/%d' % (nc, cc) else: substats = '%d' % (nc,) substats = '%s %s %s %s' % (substats.rjust(7+2*len(indent)), f8(tt), f8(ct), name) left_width = name_size + 1 else: substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3])) left_width = name_size + 3 print(indent*left_width + substats, file=self.stream) indent = " " def print_title(self): print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream) print('filename:lineno(function)', file=self.stream) def print_line(self, func): # hack: should print percentages cc, nc, tt, ct, callers = self.stats[func] c = str(nc) if nc != cc: c = c + '/' + str(cc) print(c.rjust(9), end=' ', file=self.stream) print(f8(tt), end=' ', file=self.stream) if nc == 0: print(' '*8, end=' ', file=self.stream) else: print(f8(tt/nc), end=' ', file=self.stream) print(f8(ct), end=' ', file=self.stream) if cc == 0: print(' '*8, end=' ', file=self.stream) else: print(f8(ct/cc), end=' ', file=self.stream) print(func_std_string(func), file=self.stream) class TupleComp: """This class provides a generic function for comparing any two tuples. Each instance records a list of tuple-indices (from most significant to least significant), and sort direction (ascending or decending) for each tuple-index. The compare functions can then be used as the function argument to the system sort() function when a list of tuples need to be sorted in the instances order.""" def __init__(self, comp_select_list): self.comp_select_list = comp_select_list def compare (self, left, right): for index, direction in self.comp_select_list: l = left[index] r = right[index] if l < r: return -direction if l > r: return direction return 0 #************************************************************************** # func_name is a triple (file:string, line:int, name:string) def func_strip_path(func_name): filename, line, name = func_name return os.path.basename(filename), line, name def func_get_function_name(func): return func[2] def func_std_string(func_name): # match what old profile produced if func_name[:2] == ('~', 0): # special case for built-in functions name = func_name[2] if name.startswith('<') and name.endswith('>'): return '{%s}' % name[1:-1] else: return name else: return "%s:%d(%s)" % func_name #************************************************************************** # The following functions combine statists for pairs functions. # The bulk of the processing involves correctly handling "call" lists, # such as callers and callees. #************************************************************************** def add_func_stats(target, source): """Add together all the stats for two profile entries.""" cc, nc, tt, ct, callers = source t_cc, t_nc, t_tt, t_ct, t_callers = target return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct, add_callers(t_callers, callers)) def add_callers(target, source): """Combine two caller lists in a single list.""" new_callers = {} for func, caller in target.items(): new_callers[func] = caller for func, caller in source.items(): if func in new_callers: if isinstance(caller, tuple): # format used by cProfile new_callers[func] = tuple([i[0] + i[1] for i in zip(caller, new_callers[func])]) else: # format used by profile new_callers[func] += caller else: new_callers[func] = caller return new_callers def count_calls(callers): """Sum the caller statistics to get total number of calls received.""" nc = 0 for calls in callers.values(): nc += calls return nc #************************************************************************** # The following functions support printing of reports #************************************************************************** def f8(x): return "%8.3f" % x #************************************************************************** # Statistics browser added by ESR, April 2001 #************************************************************************** if __name__ == '__main__': import cmd try: import readline except ImportError: pass class ProfileBrowser(cmd.Cmd): def __init__(self, profile=None): cmd.Cmd.__init__(self) self.prompt = "% " self.stats = None self.stream = sys.stdout if profile is not None: self.do_read(profile) def generic(self, fn, line): args = line.split() processed = [] for term in args: try: processed.append(int(term)) continue except ValueError: pass try: frac = float(term) if frac > 1 or frac < 0: print("Fraction argument must be in [0, 1]", file=self.stream) continue processed.append(frac) continue except ValueError: pass processed.append(term) if self.stats: getattr(self.stats, fn)(*processed) else: print("No statistics object is loaded.", file=self.stream) return 0 def generic_help(self): print("Arguments may be:", file=self.stream) print("* An integer maximum number of entries to print.", file=self.stream) print("* A decimal fractional number between 0 and 1, controlling", file=self.stream) print(" what fraction of selected entries to print.", file=self.stream) print("* A regular expression; only entries with function names", file=self.stream) print(" that match it are printed.", file=self.stream) def do_add(self, line): if self.stats: try: self.stats.add(line) except IOError as e: print("Failed to load statistics for %s: %s" % (line, e), file=self.stream) else: print("No statistics object is loaded.", file=self.stream) return 0 def help_add(self): print("Add profile info from given file to current statistics object.", file=self.stream) def do_callees(self, line): return self.generic('print_callees', line) def help_callees(self): print("Print callees statistics from the current stat object.", file=self.stream) self.generic_help() def do_callers(self, line): return self.generic('print_callers', line) def help_callers(self): print("Print callers statistics from the current stat object.", file=self.stream) self.generic_help() def do_EOF(self, line): print("", file=self.stream) return 1 def help_EOF(self): print("Leave the profile brower.", file=self.stream) def do_quit(self, line): return 1 def help_quit(self): print("Leave the profile brower.", file=self.stream) def do_read(self, line): if line: try: self.stats = Stats(line) except OSError as err: print(err.args[1], file=self.stream) return except Exception as err: print(err.__class__.__name__ + ':', err, file=self.stream) return self.prompt = line + "% " elif len(self.prompt) > 2: line = self.prompt[:-2] self.do_read(line) else: print("No statistics object is current -- cannot reload.", file=self.stream) return 0 def help_read(self): print("Read in profile data from a specified file.", file=self.stream) print("Without argument, reload the current file.", file=self.stream) def do_reverse(self, line): if self.stats: self.stats.reverse_order() else: print("No statistics object is loaded.", file=self.stream) return 0 def help_reverse(self): print("Reverse the sort order of the profiling report.", file=self.stream) def do_sort(self, line): if not self.stats: print("No statistics object is loaded.", file=self.stream) return abbrevs = self.stats.get_sort_arg_defs() if line and all((x in abbrevs) for x in line.split()): self.stats.sort_stats(*line.split()) else: print("Valid sort keys (unique prefixes are accepted):", file=self.stream) for (key, value) in Stats.sort_arg_dict_default.items(): print("%s -- %s" % (key, value[1]), file=self.stream) return 0 def help_sort(self): print("Sort profile data according to specified keys.", file=self.stream) print("(Typing `sort' without arguments lists valid keys.)", file=self.stream) def complete_sort(self, text, *args): return [a for a in Stats.sort_arg_dict_default if a.startswith(text)] def do_stats(self, line): return self.generic('print_stats', line) def help_stats(self): print("Print statistics from the current stat object.", file=self.stream) self.generic_help() def do_strip(self, line): if self.stats: self.stats.strip_dirs() else: print("No statistics object is loaded.", file=self.stream) def help_strip(self): print("Strip leading path information from filenames in the report.", file=self.stream) def help_help(self): print("Show help for a given command.", file=self.stream) def postcmd(self, stop, line): if stop: return stop return None if len(sys.argv) > 1: initprofile = sys.argv[1] else: initprofile = None try: browser = ProfileBrowser(initprofile) for profile in sys.argv[2:]: browser.do_add(profile) print("Welcome to the profile statistics browser.", file=browser.stream) browser.cmdloop() print("Goodbye.", file=browser.stream) except KeyboardInterrupt: pass # That's all, folks.
26,564
698
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/pty.py
"""Pseudo terminal utilities.""" # Bugs: No signal handling. Doesn't set slave termios and window size. # Only tested on Linux. # See: W. Richard Stevens. 1992. Advanced Programming in the # UNIX Environment. Chapter 19. # Author: Steen Lumholt -- with additions by Guido. from select import select import os import tty __all__ = ["openpty","fork","spawn"] STDIN_FILENO = 0 STDOUT_FILENO = 1 STDERR_FILENO = 2 CHILD = 0 def openpty(): """openpty() -> (master_fd, slave_fd) Open a pty master/slave pair, using os.openpty() if possible.""" try: return os.openpty() except (AttributeError, OSError): pass master_fd, slave_name = _open_terminal() slave_fd = slave_open(slave_name) return master_fd, slave_fd def master_open(): """master_open() -> (master_fd, slave_name) Open a pty master and return the fd, and the filename of the slave end. Deprecated, use openpty() instead.""" try: master_fd, slave_fd = os.openpty() except (AttributeError, OSError): pass else: slave_name = os.ttyname(slave_fd) os.close(slave_fd) return master_fd, slave_name return _open_terminal() def _open_terminal(): """Open pty master and return (master_fd, tty_name).""" for x in 'pqrstuvwxyzPQRST': for y in '0123456789abcdef': pty_name = '/dev/pty' + x + y try: fd = os.open(pty_name, os.O_RDWR) except OSError: continue return (fd, '/dev/tty' + x + y) raise OSError('out of pty devices') def slave_open(tty_name): """slave_open(tty_name) -> slave_fd Open the pty slave and acquire the controlling terminal, returning opened filedescriptor. Deprecated, use openpty() instead.""" result = os.open(tty_name, os.O_RDWR) try: from fcntl import ioctl, I_PUSH except ImportError: return result try: ioctl(result, I_PUSH, "ptem") ioctl(result, I_PUSH, "ldterm") except OSError: pass return result def fork(): """fork() -> (pid, master_fd) Fork and make the child a session leader with a controlling terminal.""" try: pid, fd = os.forkpty() except (AttributeError, OSError): pass else: if pid == CHILD: try: os.setsid() except OSError: # os.forkpty() already set us session leader pass return pid, fd master_fd, slave_fd = openpty() pid = os.fork() if pid == CHILD: # Establish a new session. os.setsid() os.close(master_fd) # Slave becomes stdin/stdout/stderr of child. os.dup2(slave_fd, STDIN_FILENO) os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if (slave_fd > STDERR_FILENO): os.close (slave_fd) # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) os.close(tmp_fd) else: os.close(slave_fd) # Parent and child process. return pid, master_fd def _writen(fd, data): """Write all the data to a descriptor.""" while data: n = os.write(fd, data) data = data[n:] def _read(fd): """Default read function.""" return os.read(fd, 1024) def _copy(master_fd, master_read=_read, stdin_read=_read): """Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read)""" fds = [master_fd, STDIN_FILENO] while True: rfds, wfds, xfds = select(fds, [], []) if master_fd in rfds: data = master_read(master_fd) if not data: # Reached EOF. fds.remove(master_fd) else: os.write(STDOUT_FILENO, data) if STDIN_FILENO in rfds: data = stdin_read(STDIN_FILENO) if not data: fds.remove(STDIN_FILENO) else: _writen(master_fd, data) def spawn(argv, master_read=_read, stdin_read=_read): """Create a spawned process.""" if type(argv) == type(''): argv = (argv,) pid, master_fd = fork() if pid == CHILD: os.execlp(argv[0], *argv) try: mode = tty.tcgetattr(STDIN_FILENO) tty.setraw(STDIN_FILENO) restore = 1 except tty.error: # This is the same as termios.error restore = 0 try: _copy(master_fd, master_read, stdin_read) except OSError: if restore: tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode) os.close(master_fd) return os.waitpid(pid, 0)[1]
4,763
171
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/symbol.py
#! /usr/bin/env python3 """Non-terminal symbols of Python grammar (from "graminit.h").""" # This file is automatically generated; please don't muck it up! # # To update the symbols in this file, 'cd' to the top directory of # the python source tree after building the interpreter and run: # # ./python Lib/symbol.py #--start constants-- single_input = 256 file_input = 257 eval_input = 258 decorator = 259 decorators = 260 decorated = 261 async_funcdef = 262 funcdef = 263 parameters = 264 typedargslist = 265 tfpdef = 266 varargslist = 267 vfpdef = 268 stmt = 269 simple_stmt = 270 small_stmt = 271 expr_stmt = 272 annassign = 273 testlist_star_expr = 274 augassign = 275 del_stmt = 276 pass_stmt = 277 flow_stmt = 278 break_stmt = 279 continue_stmt = 280 return_stmt = 281 yield_stmt = 282 raise_stmt = 283 import_stmt = 284 import_name = 285 import_from = 286 import_as_name = 287 dotted_as_name = 288 import_as_names = 289 dotted_as_names = 290 dotted_name = 291 global_stmt = 292 nonlocal_stmt = 293 assert_stmt = 294 compound_stmt = 295 async_stmt = 296 if_stmt = 297 while_stmt = 298 for_stmt = 299 try_stmt = 300 with_stmt = 301 with_item = 302 except_clause = 303 suite = 304 test = 305 test_nocond = 306 lambdef = 307 lambdef_nocond = 308 or_test = 309 and_test = 310 not_test = 311 comparison = 312 comp_op = 313 star_expr = 314 expr = 315 xor_expr = 316 and_expr = 317 shift_expr = 318 arith_expr = 319 term = 320 factor = 321 power = 322 atom_expr = 323 atom = 324 testlist_comp = 325 trailer = 326 subscriptlist = 327 subscript = 328 sliceop = 329 exprlist = 330 testlist = 331 dictorsetmaker = 332 classdef = 333 arglist = 334 argument = 335 comp_iter = 336 comp_for = 337 comp_if = 338 encoding_decl = 339 yield_expr = 340 yield_arg = 341 #--end constants-- sym_name = {} for _name, _value in list(globals().items()): if type(_value) is type(0): sym_name[_value] = _name def _main(): import sys import token if len(sys.argv) == 1: sys.argv = sys.argv + ["Include/graminit.h", "Lib/symbol.py"] token._main() if __name__ == "__main__": _main()
2,111
116
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/colorsys.py
"""Conversion functions between RGB and other color systems. This modules provides two functions for each color system ABC: rgb_to_abc(r, g, b) --> a, b, c abc_to_rgb(a, b, c) --> r, g, b All inputs and outputs are triples of floats in the range [0.0...1.0] (with the exception of I and Q, which covers a slightly larger range). Inputs outside the valid range may cause exceptions or invalid outputs. Supported color systems: RGB: Red, Green, Blue components YIQ: Luminance, Chrominance (used by composite video signals) HLS: Hue, Luminance, Saturation HSV: Hue, Saturation, Value """ # References: # http://en.wikipedia.org/wiki/YIQ # http://en.wikipedia.org/wiki/HLS_color_space # http://en.wikipedia.org/wiki/HSV_color_space __all__ = ["rgb_to_yiq","yiq_to_rgb","rgb_to_hls","hls_to_rgb", "rgb_to_hsv","hsv_to_rgb"] # Some floating point constants ONE_THIRD = 1.0/3.0 ONE_SIXTH = 1.0/6.0 TWO_THIRD = 2.0/3.0 # YIQ: used by composite video signals (linear combinations of RGB) # Y: perceived grey level (0.0 == black, 1.0 == white) # I, Q: color components # # There are a great many versions of the constants used in these formulae. # The ones in this library uses constants from the FCC version of NTSC. def rgb_to_yiq(r, g, b): y = 0.30*r + 0.59*g + 0.11*b i = 0.74*(r-y) - 0.27*(b-y) q = 0.48*(r-y) + 0.41*(b-y) return (y, i, q) def yiq_to_rgb(y, i, q): # r = y + (0.27*q + 0.41*i) / (0.74*0.41 + 0.27*0.48) # b = y + (0.74*q - 0.48*i) / (0.74*0.41 + 0.27*0.48) # g = y - (0.30*(r-y) + 0.11*(b-y)) / 0.59 r = y + 0.9468822170900693*i + 0.6235565819861433*q g = y - 0.27478764629897834*i - 0.6356910791873801*q b = y - 1.1085450346420322*i + 1.7090069284064666*q if r < 0.0: r = 0.0 if g < 0.0: g = 0.0 if b < 0.0: b = 0.0 if r > 1.0: r = 1.0 if g > 1.0: g = 1.0 if b > 1.0: b = 1.0 return (r, g, b) # HLS: Hue, Luminance, Saturation # H: position in the spectrum # L: color lightness # S: color saturation def rgb_to_hls(r, g, b): maxc = max(r, g, b) minc = min(r, g, b) # XXX Can optimize (maxc+minc) and (maxc-minc) l = (minc+maxc)/2.0 if minc == maxc: return 0.0, l, 0.0 if l <= 0.5: s = (maxc-minc) / (maxc+minc) else: s = (maxc-minc) / (2.0-maxc-minc) rc = (maxc-r) / (maxc-minc) gc = (maxc-g) / (maxc-minc) bc = (maxc-b) / (maxc-minc) if r == maxc: h = bc-gc elif g == maxc: h = 2.0+rc-bc else: h = 4.0+gc-rc h = (h/6.0) % 1.0 return h, l, s def hls_to_rgb(h, l, s): if s == 0.0: return l, l, l if l <= 0.5: m2 = l * (1.0+s) else: m2 = l+s-(l*s) m1 = 2.0*l - m2 return (_v(m1, m2, h+ONE_THIRD), _v(m1, m2, h), _v(m1, m2, h-ONE_THIRD)) def _v(m1, m2, hue): hue = hue % 1.0 if hue < ONE_SIXTH: return m1 + (m2-m1)*hue*6.0 if hue < 0.5: return m2 if hue < TWO_THIRD: return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0 return m1 # HSV: Hue, Saturation, Value # H: position in the spectrum # S: color saturation ("purity") # V: color brightness def rgb_to_hsv(r, g, b): maxc = max(r, g, b) minc = min(r, g, b) v = maxc if minc == maxc: return 0.0, 0.0, v s = (maxc-minc) / maxc rc = (maxc-r) / (maxc-minc) gc = (maxc-g) / (maxc-minc) bc = (maxc-b) / (maxc-minc) if r == maxc: h = bc-gc elif g == maxc: h = 2.0+rc-bc else: h = 4.0+gc-rc h = (h/6.0) % 1.0 return h, s, v def hsv_to_rgb(h, s, v): if s == 0.0: return v, v, v i = int(h*6.0) # XXX assume int() truncates! f = (h*6.0) - i p = v*(1.0 - s) q = v*(1.0 - s*f) t = v*(1.0 - s*(1.0-f)) i = i%6 if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v if i == 4: return t, p, v if i == 5: return v, p, q # Cannot get here
4,064
165
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/sre_compile.py
# # Secret Labs' Regular Expression Engine # # convert template to internal format # # Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support module for sre""" import _sre import sre_parse from sre_constants import * assert _sre.MAGIC == MAGIC, "SRE module mismatch" _LITERAL_CODES = {LITERAL, NOT_LITERAL} _REPEATING_CODES = {REPEAT, MIN_REPEAT, MAX_REPEAT} _SUCCESS_CODES = {SUCCESS, FAILURE} _ASSERT_CODES = {ASSERT, ASSERT_NOT} # Sets of lowercase characters which have the same uppercase. _equivalences = ( # LATIN SMALL LETTER I, LATIN SMALL LETTER DOTLESS I (0x69, 0x131), # iı # LATIN SMALL LETTER S, LATIN SMALL LETTER LONG S (0x73, 0x17f), # sſ # MICRO SIGN, GREEK SMALL LETTER MU (0xb5, 0x3bc), # µμ # COMBINING GREEK YPOGEGRAMMENI, GREEK SMALL LETTER IOTA, GREEK PROSGEGRAMMENI (0x345, 0x3b9, 0x1fbe), # \u0345ιι # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS, GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA (0x390, 0x1fd3), # ΐΐ # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS, GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA (0x3b0, 0x1fe3), # ΰΰ # GREEK SMALL LETTER BETA, GREEK BETA SYMBOL (0x3b2, 0x3d0), # βϐ # GREEK SMALL LETTER EPSILON, GREEK LUNATE EPSILON SYMBOL (0x3b5, 0x3f5), # εϵ # GREEK SMALL LETTER THETA, GREEK THETA SYMBOL (0x3b8, 0x3d1), # θϑ # GREEK SMALL LETTER KAPPA, GREEK KAPPA SYMBOL (0x3ba, 0x3f0), # κϰ # GREEK SMALL LETTER PI, GREEK PI SYMBOL (0x3c0, 0x3d6), # πϖ # GREEK SMALL LETTER RHO, GREEK RHO SYMBOL (0x3c1, 0x3f1), # ρϱ # GREEK SMALL LETTER FINAL SIGMA, GREEK SMALL LETTER SIGMA (0x3c2, 0x3c3), # ςσ # GREEK SMALL LETTER PHI, GREEK PHI SYMBOL (0x3c6, 0x3d5), # φϕ # LATIN SMALL LETTER S WITH DOT ABOVE, LATIN SMALL LETTER LONG S WITH DOT ABOVE (0x1e61, 0x1e9b), # ṡẛ # LATIN SMALL LIGATURE LONG S T, LATIN SMALL LIGATURE ST (0xfb05, 0xfb06), # ſtst ) # Maps the lowercase code to lowercase codes which have the same uppercase. _ignorecase_fixes = {i: tuple(j for j in t if i != j) for t in _equivalences for i in t} def _compile(code, pattern, flags): # internal: compile a (sub)pattern emit = code.append _len = len LITERAL_CODES = _LITERAL_CODES REPEATING_CODES = _REPEATING_CODES SUCCESS_CODES = _SUCCESS_CODES ASSERT_CODES = _ASSERT_CODES if (flags & SRE_FLAG_IGNORECASE and not (flags & SRE_FLAG_LOCALE) and flags & SRE_FLAG_UNICODE and not (flags & SRE_FLAG_ASCII)): fixes = _ignorecase_fixes else: fixes = None for op, av in pattern: if op in LITERAL_CODES: if flags & SRE_FLAG_IGNORECASE: lo = _sre.getlower(av, flags) if fixes and lo in fixes: emit(IN_IGNORE) skip = _len(code); emit(0) if op is NOT_LITERAL: emit(NEGATE) for k in (lo,) + fixes[lo]: emit(LITERAL) emit(k) emit(FAILURE) code[skip] = _len(code) - skip else: emit(OP_IGNORE[op]) emit(lo) else: emit(op) emit(av) elif op is IN: if flags & SRE_FLAG_IGNORECASE: emit(OP_IGNORE[op]) def fixup(literal, flags=flags): return _sre.getlower(literal, flags) else: emit(op) fixup = None skip = _len(code); emit(0) _compile_charset(av, flags, code, fixup, fixes) code[skip] = _len(code) - skip elif op is ANY: if flags & SRE_FLAG_DOTALL: emit(ANY_ALL) else: emit(ANY) elif op in REPEATING_CODES: if flags & SRE_FLAG_TEMPLATE: raise error("internal: unsupported template operator %r" % (op,)) elif _simple(av) and op is not REPEAT: if op is MAX_REPEAT: emit(REPEAT_ONE) else: emit(MIN_REPEAT_ONE) skip = _len(code); emit(0) emit(av[0]) emit(av[1]) _compile(code, av[2], flags) emit(SUCCESS) code[skip] = _len(code) - skip else: emit(REPEAT) skip = _len(code); emit(0) emit(av[0]) emit(av[1]) _compile(code, av[2], flags) code[skip] = _len(code) - skip if op is MAX_REPEAT: emit(MAX_UNTIL) else: emit(MIN_UNTIL) elif op is SUBPATTERN: group, add_flags, del_flags, p = av if group: emit(MARK) emit((group-1)*2) # _compile_info(code, p, (flags | add_flags) & ~del_flags) _compile(code, p, (flags | add_flags) & ~del_flags) if group: emit(MARK) emit((group-1)*2+1) elif op in SUCCESS_CODES: emit(op) elif op in ASSERT_CODES: emit(op) skip = _len(code); emit(0) if av[0] >= 0: emit(0) # look ahead else: lo, hi = av[1].getwidth() if lo != hi: raise error("look-behind requires fixed-width pattern") emit(lo) # look behind _compile(code, av[1], flags) emit(SUCCESS) code[skip] = _len(code) - skip elif op is CALL: emit(op) skip = _len(code); emit(0) _compile(code, av, flags) emit(SUCCESS) code[skip] = _len(code) - skip elif op is AT: emit(op) if flags & SRE_FLAG_MULTILINE: av = AT_MULTILINE.get(av, av) if flags & SRE_FLAG_LOCALE: av = AT_LOCALE.get(av, av) elif (flags & SRE_FLAG_UNICODE) and not (flags & SRE_FLAG_ASCII): av = AT_UNICODE.get(av, av) emit(av) elif op is BRANCH: emit(op) tail = [] tailappend = tail.append for av in av[1]: skip = _len(code); emit(0) # _compile_info(code, av, flags) _compile(code, av, flags) emit(JUMP) tailappend(_len(code)); emit(0) code[skip] = _len(code) - skip emit(FAILURE) # end of branch for tail in tail: code[tail] = _len(code) - tail elif op is CATEGORY: emit(op) if flags & SRE_FLAG_LOCALE: av = CH_LOCALE[av] elif (flags & SRE_FLAG_UNICODE) and not (flags & SRE_FLAG_ASCII): av = CH_UNICODE[av] emit(av) elif op is GROUPREF: if flags & SRE_FLAG_IGNORECASE: emit(OP_IGNORE[op]) else: emit(op) emit(av-1) elif op is GROUPREF_EXISTS: emit(op) emit(av[0]-1) skipyes = _len(code); emit(0) _compile(code, av[1], flags) if av[2]: emit(JUMP) skipno = _len(code); emit(0) code[skipyes] = _len(code) - skipyes + 1 _compile(code, av[2], flags) code[skipno] = _len(code) - skipno else: code[skipyes] = _len(code) - skipyes + 1 else: raise error("internal: unsupported operand type %r" % (op,)) def _compile_charset(charset, flags, code, fixup=None, fixes=None): # compile charset subprogram emit = code.append for op, av in _optimize_charset(charset, fixup, fixes): emit(op) if op is NEGATE: pass elif op is LITERAL: emit(av) elif op is RANGE or op is RANGE_IGNORE: emit(av[0]) emit(av[1]) elif op is CHARSET: code.extend(av) elif op is BIGCHARSET: code.extend(av) elif op is CATEGORY: if flags & SRE_FLAG_LOCALE: emit(CH_LOCALE[av]) elif (flags & SRE_FLAG_UNICODE) and not (flags & SRE_FLAG_ASCII): emit(CH_UNICODE[av]) else: emit(av) else: raise error("internal: unsupported set operator %r" % (op,)) emit(FAILURE) def _optimize_charset(charset, fixup, fixes): # internal: optimize character set out = [] tail = [] charmap = bytearray(256) for op, av in charset: while True: try: if op is LITERAL: if fixup: lo = fixup(av) charmap[lo] = 1 if fixes and lo in fixes: for k in fixes[lo]: charmap[k] = 1 else: charmap[av] = 1 elif op is RANGE: r = range(av[0], av[1]+1) if fixup: r = map(fixup, r) if fixup and fixes: for i in r: charmap[i] = 1 if i in fixes: for k in fixes[i]: charmap[k] = 1 else: for i in r: charmap[i] = 1 elif op is NEGATE: out.append((op, av)) else: tail.append((op, av)) except IndexError: if len(charmap) == 256: # character set contains non-UCS1 character codes charmap += b'\0' * 0xff00 continue # Character set contains non-BMP character codes. # There are only two ranges of cased non-BMP characters: # 10400-1044F (Deseret) and 118A0-118DF (Warang Citi), # and for both ranges RANGE_IGNORE works. if fixup and op is RANGE: op = RANGE_IGNORE tail.append((op, av)) break # compress character map runs = [] q = 0 while True: p = charmap.find(1, q) if p < 0: break if len(runs) >= 2: runs = None break q = charmap.find(0, p) if q < 0: runs.append((p, len(charmap))) break runs.append((p, q)) if runs is not None: # use literal/range for p, q in runs: if q - p == 1: out.append((LITERAL, p)) else: out.append((RANGE, (p, q - 1))) out += tail # if the case was changed or new representation is more compact if fixup or len(out) < len(charset): return out # else original character set is good enough return charset # use bitmap if len(charmap) == 256: data = _mk_bitmap(charmap) out.append((CHARSET, data)) out += tail return out # To represent a big charset, first a bitmap of all characters in the # set is constructed. Then, this bitmap is sliced into chunks of 256 # characters, duplicate chunks are eliminated, and each chunk is # given a number. In the compiled expression, the charset is # represented by a 32-bit word sequence, consisting of one word for # the number of different chunks, a sequence of 256 bytes (64 words) # of chunk numbers indexed by their original chunk position, and a # sequence of 256-bit chunks (8 words each). # Compression is normally good: in a typical charset, large ranges of # Unicode will be either completely excluded (e.g. if only cyrillic # letters are to be matched), or completely included (e.g. if large # subranges of Kanji match). These ranges will be represented by # chunks of all one-bits or all zero-bits. # Matching can be also done efficiently: the more significant byte of # the Unicode character is an index into the chunk number, and the # less significant byte is a bit index in the chunk (just like the # CHARSET matching). charmap = bytes(charmap) # should be hashable comps = {} mapping = bytearray(256) block = 0 data = bytearray() for i in range(0, 65536, 256): chunk = charmap[i: i + 256] if chunk in comps: mapping[i // 256] = comps[chunk] else: mapping[i // 256] = comps[chunk] = block block += 1 data += chunk data = _mk_bitmap(data) data[0:0] = [block] + _bytes_to_codes(mapping) out.append((BIGCHARSET, data)) out += tail return out _CODEBITS = _sre.CODESIZE * 8 MAXCODE = (1 << _CODEBITS) - 1 _BITS_TRANS = b'0' + b'1' * 255 def _mk_bitmap(bits, _CODEBITS=_CODEBITS, _int=int): s = bits.translate(_BITS_TRANS)[::-1] return [_int(s[i - _CODEBITS: i], 2) for i in range(len(s), 0, -_CODEBITS)] def _bytes_to_codes(b): # Convert block indices to word array a = memoryview(b).cast('I') assert a.itemsize == _sre.CODESIZE assert len(a) * a.itemsize == len(b) return a.tolist() def _simple(av): # check if av is a "simple" operator lo, hi = av[2].getwidth() return lo == hi == 1 and av[2][0][0] != SUBPATTERN def _generate_overlap_table(prefix): """ Generate an overlap table for the following prefix. An overlap table is a table of the same size as the prefix which informs about the potential self-overlap for each index in the prefix: - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...] - if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps with prefix[0:k] """ table = [0] * len(prefix) for i in range(1, len(prefix)): idx = table[i - 1] while prefix[i] != prefix[idx]: if idx == 0: table[i] = 0 break idx = table[idx - 1] else: table[i] = idx + 1 return table def _get_literal_prefix(pattern): # look for literal prefix prefix = [] prefixappend = prefix.append prefix_skip = None for op, av in pattern.data: if op is LITERAL: prefixappend(av) elif op is SUBPATTERN: group, add_flags, del_flags, p = av if add_flags & SRE_FLAG_IGNORECASE: break prefix1, prefix_skip1, got_all = _get_literal_prefix(p) if prefix_skip is None: if group is not None: prefix_skip = len(prefix) elif prefix_skip1 is not None: prefix_skip = len(prefix) + prefix_skip1 prefix.extend(prefix1) if not got_all: break else: break else: return prefix, prefix_skip, True return prefix, prefix_skip, False def _get_charset_prefix(pattern): charset = [] # not used charsetappend = charset.append if pattern.data: op, av = pattern.data[0] if op is SUBPATTERN: group, add_flags, del_flags, p = av if p and not (add_flags & SRE_FLAG_IGNORECASE): op, av = p[0] if op is LITERAL: charsetappend((op, av)) elif op is BRANCH: c = [] cappend = c.append for p in av[1]: if not p: break op, av = p[0] if op is LITERAL: cappend((op, av)) else: break else: charset = c elif op is BRANCH: c = [] cappend = c.append for p in av[1]: if not p: break op, av = p[0] if op is LITERAL: cappend((op, av)) else: break else: charset = c elif op is IN: charset = av return charset def _compile_info(code, pattern, flags): # internal: compile an info block. in the current version, # this contains min/max pattern width, and an optional literal # prefix or a character map lo, hi = pattern.getwidth() if hi > MAXCODE: hi = MAXCODE if lo == 0: code.extend([INFO, 4, 0, lo, hi]) return # look for a literal prefix prefix = [] prefix_skip = 0 charset = [] # not used if not (flags & SRE_FLAG_IGNORECASE): # look for literal prefix prefix, prefix_skip, got_all = _get_literal_prefix(pattern) # if no prefix, look for charset prefix if not prefix: charset = _get_charset_prefix(pattern) ## if prefix: ## print("*** PREFIX", prefix, prefix_skip) ## if charset: ## print("*** CHARSET", charset) # add an info block emit = code.append emit(INFO) skip = len(code); emit(0) # literal flag mask = 0 if prefix: mask = SRE_INFO_PREFIX if prefix_skip is None and got_all: mask = mask | SRE_INFO_LITERAL elif charset: mask = mask | SRE_INFO_CHARSET emit(mask) # pattern length if lo < MAXCODE: emit(lo) else: emit(MAXCODE) prefix = prefix[:MAXCODE] emit(min(hi, MAXCODE)) # add literal prefix if prefix: emit(len(prefix)) # length if prefix_skip is None: prefix_skip = len(prefix) emit(prefix_skip) # skip code.extend(prefix) # generate overlap table code.extend(_generate_overlap_table(prefix)) elif charset: _compile_charset(charset, flags, code) code[skip] = len(code) - skip def isstring(obj): return isinstance(obj, (str, bytes)) def _code(p, flags): flags = p.pattern.flags | flags code = [] # compile info block _compile_info(code, p, flags) # compile the pattern _compile(code, p.data, flags) code.append(SUCCESS) return code def compile(p, flags=0): # internal: convert pattern list to internal format if isstring(p): pattern = p p = sre_parse.parse(p, flags) else: pattern = None code = _code(p, flags) # print(code) # map in either direction groupindex = p.pattern.groupdict indexgroup = [None] * p.pattern.groups for k, i in groupindex.items(): indexgroup[i] = k return _sre.compile( pattern, flags | p.pattern.flags, code, p.pattern.groups-1, groupindex, indexgroup )
19,338
581
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/random.py
"""Random variable generators. integers -------- uniform within range sequences --------- pick random element pick random sample pick weighted random sample generate random permutation distributions on the real line: ------------------------------ uniform triangular normal (Gaussian) lognormal negative exponential gamma beta pareto Weibull distributions on the circle (angles 0 to 2pi) --------------------------------------------- circular uniform von Mises General notes on the underlying Mersenne Twister core generator: * The period is 2**19937-1. * It is one of the most extensively tested generators in existence. * The random() method is implemented in C, executes in a single Python step, and is, therefore, threadsafe. """ from warnings import warn as _warn from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin from os import urandom as _urandom from collections.abc import Set as _Set, Sequence as _Sequence from hashlib import sha512 as _sha512 import itertools as _itertools import bisect as _bisect __all__ = ["Random","seed","random","uniform","randint","choice","sample", "randrange","shuffle","normalvariate","lognormvariate", "expovariate","vonmisesvariate","gammavariate","triangular", "gauss","betavariate","paretovariate","weibullvariate", "getstate","setstate", "getrandbits", "choices", "SystemRandom"] NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0) TWOPI = 2.0*_pi LOG4 = _log(4.0) SG_MAGICCONST = 1.0 + _log(4.5) BPF = 53 # Number of bits in a float RECIP_BPF = 2**-BPF # Translated by Guido van Rossum from C source provided by # Adrian Baddeley. Adapted by Raymond Hettinger for use with # the Mersenne Twister and os.urandom() core generators. import _random class Random(_random.Random): """Random number generator base class used by bound module functions. Used to instantiate instances of Random to get generators that don't share state. Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the following methods: random(), seed(), getstate(), and setstate(). Optionally, implement a getrandbits() method so that randrange() can cover arbitrarily large ranges. """ VERSION = 3 # used by getstate/setstate def __init__(self, x=None): """Initialize an instance. Optional argument x controls seeding, as for Random.seed(). """ self.seed(x) self.gauss_next = None def seed(self, a=None, version=2): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds. """ if version == 1 and isinstance(a, (str, bytes)): a = a.decode('latin-1') if isinstance(a, bytes) else a x = ord(a[0]) << 7 if a else 0 for c in map(ord, a): x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF x ^= len(a) a = -2 if x == -1 else x if version == 2 and isinstance(a, (str, bytes, bytearray)): if isinstance(a, str): a = a.encode() a += _sha512(a).digest() a = int.from_bytes(a, 'big') super().seed(a) self.gauss_next = None def getstate(self): """Return internal state; can be passed to setstate() later.""" return self.VERSION, super().getstate(), self.gauss_next def setstate(self, state): """Restore internal state from object returned by getstate().""" version = state[0] if version == 3: version, internalstate, self.gauss_next = state super().setstate(internalstate) elif version == 2: version, internalstate, self.gauss_next = state # In version 2, the state was saved as signed ints, which causes # inconsistencies between 32/64-bit systems. The state is # really unsigned 32-bit ints, so we convert negative ints from # version 2 to positive longs for version 3. try: internalstate = tuple(x % (2**32) for x in internalstate) except ValueError as e: raise TypeError from e super().setstate(internalstate) else: raise ValueError("state with version %s passed to " "Random.setstate() of version %s" % (version, self.VERSION)) ## ---- Methods below this point do not need to be overridden when ## ---- subclassing for the purpose of using a different core generator. ## -------------------- pickle support ------------------- # Issue 17489: Since __reduce__ was defined to fix #759889 this is no # longer called; we leave it here because it has been here since random was # rewritten back in 2001 and why risk breaking something. def __getstate__(self): # for pickle return self.getstate() def __setstate__(self, state): # for pickle self.setstate(state) def __reduce__(self): return self.__class__, (), self.getstate() ## -------------------- integer methods ------------------- def randrange(self, start, stop=None, step=1, _int=int): """Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. """ # This code is a bit messy to make it fast for the # common case while still doing adequate error checking. istart = _int(start) if istart != start: raise ValueError("non-integer arg 1 for randrange()") if stop is None: if istart > 0: return self._randbelow(istart) raise ValueError("empty range for randrange()") # stop argument supplied. istop = _int(stop) if istop != stop: raise ValueError("non-integer stop for randrange()") width = istop - istart if step == 1 and width > 0: return istart + self._randbelow(width) if step == 1: raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width)) # Non-unit step argument supplied. istep = _int(step) if istep != step: raise ValueError("non-integer step for randrange()") if istep > 0: n = (width + istep - 1) // istep elif istep < 0: n = (width + istep + 1) // istep else: raise ValueError("zero step for randrange()") if n <= 0: raise ValueError("empty range for randrange()") return istart + istep*self._randbelow(n) def randint(self, a, b): """Return random integer in range [a, b], including both end points. """ return self.randrange(a, b+1) def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type, Method=_MethodType, BuiltinMethod=_BuiltinMethodType): "Return a random int in the range [0,n). Raises ValueError if n==0." random = self.random getrandbits = self.getrandbits # Only call self.getrandbits if the original random() builtin method # has not been overridden or if a new getrandbits() was supplied. if type(random) is BuiltinMethod or type(getrandbits) is Method: k = n.bit_length() # don't use (n-1) here because n can be 1 r = getrandbits(k) # 0 <= r < 2**k while r >= n: r = getrandbits(k) return r # There's an overridden random() method but no new getrandbits() method, # so we can only use random() from here. if n >= maxsize: _warn("Underlying random() generator does not supply \n" "enough bits to choose from a population range this large.\n" "To remove the range limitation, add a getrandbits() method.") return int(random() * n) if n == 0: raise ValueError("Boundary cannot be zero") rem = maxsize % n limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0 r = random() while r >= limit: r = random() return int(r*maxsize) % n ## -------------------- sequence methods ------------------- def choice(self, seq): """Choose a random element from a non-empty sequence.""" try: i = self._randbelow(len(seq)) except ValueError: raise IndexError('Cannot choose from an empty sequence') from None return seq[i] def shuffle(self, x, random=None): """Shuffle list x in place, and return None. Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used. """ if random is None: randbelow = self._randbelow for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = randbelow(i+1) x[i], x[j] = x[j], x[i] else: _int = int for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = _int(random() * (i+1)) x[i], x[j] = x[j], x[i] def sample(self, population, k): """Chooses k unique random elements from a population sequence or set. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use range as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) """ # Sampling without replacement entails tracking either potential # selections (the pool) in a list or previous selections in a set. # When the number of selections is small compared to the # population, then tracking selections is efficient, requiring # only a small set and an occasional reselection. For # a larger number of selections, the pool tracking method is # preferred since the list takes less space than the # set and it doesn't suffer from frequent reselections. if isinstance(population, _Set): population = tuple(population) if not isinstance(population, _Sequence): raise TypeError("Population must be a sequence or set. For dicts, use list(d).") randbelow = self._randbelow n = len(population) if not 0 <= k <= n: raise ValueError("Sample larger than population or is negative") result = [None] * k setsize = 21 # size of a small set minus size of an empty list if k > 5: setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets if n <= setsize: # An n-length list is smaller than a k-length set pool = list(population) for i in range(k): # invariant: non-selected at [0,n-i) j = randbelow(n-i) result[i] = pool[j] pool[j] = pool[n-i-1] # move non-selected item into vacancy else: selected = set() selected_add = selected.add for i in range(k): j = randbelow(n) while j in selected: j = randbelow(n) selected_add(j) result[i] = population[j] return result def choices(self, population, weights=None, *, cum_weights=None, k=1): """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ random = self.random if cum_weights is None: if weights is None: _int = int total = len(population) return [population[_int(random() * total)] for i in range(k)] cum_weights = list(_itertools.accumulate(weights)) elif weights is not None: raise TypeError('Cannot specify both weights and cumulative weights') if len(cum_weights) != len(population): raise ValueError('The number of weights does not match the population') bisect = _bisect.bisect total = cum_weights[-1] hi = len(cum_weights) - 1 return [population[bisect(cum_weights, random() * total, 0, hi)] for i in range(k)] ## -------------------- real-valued distributions ------------------- ## -------------------- uniform distribution ------------------- def uniform(self, a, b): "Get a random number in the range [a, b) or [a, b] depending on rounding." return a + (b-a) * self.random() ## -------------------- triangular -------------------- def triangular(self, low=0.0, high=1.0, mode=None): """Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution """ u = self.random() try: c = 0.5 if mode is None else (mode - low) / (high - low) except ZeroDivisionError: return low if u > c: u = 1.0 - u c = 1.0 - c low, high = high, low return low + (high - low) * (u * c) ** 0.5 ## -------------------- normal distribution -------------------- def normalvariate(self, mu, sigma): """Normal distribution. mu is the mean, and sigma is the standard deviation. """ # mu = mean, sigma = standard deviation # Uses Kinderman and Monahan method. Reference: Kinderman, # A.J. and Monahan, J.F., "Computer generation of random # variables using the ratio of uniform deviates", ACM Trans # Math Software, 3, (1977), pp257-260. random = self.random while 1: u1 = random() u2 = 1.0 - random() z = NV_MAGICCONST*(u1-0.5)/u2 zz = z*z/4.0 if zz <= -_log(u2): break return mu + z*sigma ## -------------------- lognormal distribution -------------------- def lognormvariate(self, mu, sigma): """Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero. """ return _exp(self.normalvariate(mu, sigma)) ## -------------------- exponential distribution -------------------- def expovariate(self, lambd): """Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative. """ # lambd: rate lambd = 1/mean # ('lambda' is a Python reserved word) # we use 1-random() instead of random() to preclude the # possibility of taking the log of zero. return -_log(1.0 - self.random())/lambd ## -------------------- von Mises distribution -------------------- def vonmisesvariate(self, mu, kappa): """Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. """ # mu: mean angle (in radians between 0 and 2*pi) # kappa: concentration parameter kappa (>= 0) # if kappa = 0 generate uniform random angle # Based upon an algorithm published in: Fisher, N.I., # "Statistical Analysis of Circular Data", Cambridge # University Press, 1993. # Thanks to Magnus Kessler for a correction to the # implementation of step 4. random = self.random if kappa <= 1e-6: return TWOPI * random() s = 0.5 / kappa r = s + _sqrt(1.0 + s * s) while 1: u1 = random() z = _cos(_pi * u1) d = z / (r + z) u2 = random() if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d): break q = 1.0 / r f = (q + z) / (1.0 + q * z) u3 = random() if u3 > 0.5: theta = (mu + _acos(f)) % TWOPI else: theta = (mu - _acos(f)) % TWOPI return theta ## -------------------- gamma distribution -------------------- def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is: x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha """ # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2 # Warning: a few older sources define the gamma distribution in terms # of alpha > -1.0 if alpha <= 0.0 or beta <= 0.0: raise ValueError('gammavariate: alpha and beta must be > 0.0') random = self.random if alpha > 1.0: # Uses R.C.H. Cheng, "The generation of Gamma # variables with non-integral shape parameters", # Applied Statistics, (1977), 26, No. 1, p71-74 ainv = _sqrt(2.0 * alpha - 1.0) bbb = alpha - LOG4 ccc = alpha + ainv while 1: u1 = random() if not 1e-7 < u1 < .9999999: continue u2 = 1.0 - random() v = _log(u1/(1.0-u1))/ainv x = alpha*_exp(v) z = u1*u1*u2 r = bbb+ccc*v-x if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z): return x * beta elif alpha == 1.0: # expovariate(1) u = random() while u <= 1e-7: u = random() return -_log(u) * beta else: # alpha is between 0 and 1 (exclusive) # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle while 1: u = random() b = (_e + alpha)/_e p = b*u if p <= 1.0: x = p ** (1.0/alpha) else: x = -_log((b-p)/alpha) u1 = random() if p > 1.0: if u1 <= x ** (alpha - 1.0): break elif u1 <= _exp(-x): break return x * beta ## -------------------- Gauss (faster alternative) -------------------- def gauss(self, mu, sigma): """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. """ # When x and y are two variables from [0, 1), uniformly # distributed, then # # cos(2*pi*x)*sqrt(-2*log(1-y)) # sin(2*pi*x)*sqrt(-2*log(1-y)) # # are two *independent* variables with normal distribution # (mu = 0, sigma = 1). # (Lambert Meertens) # (corrected version; bug discovered by Mike Miller, fixed by LM) # Multithreading note: When two threads call this function # simultaneously, it is possible that they will receive the # same return value. The window is very small though. To # avoid this, you have to use a lock around all calls. (I # didn't want to slow this down in the serial case by using a # lock here.) random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z*sigma ## -------------------- beta -------------------- ## See ## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html ## for Ivan Frohne's insightful analysis of why the original implementation: ## ## def betavariate(self, alpha, beta): ## # Discrete Event Simulation in C, pp 87-88. ## ## y = self.expovariate(alpha) ## z = self.expovariate(1.0/beta) ## return z/(y+z) ## ## was dead wrong, and how it probably got that way. def betavariate(self, alpha, beta): """Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. """ # This version due to Janne Sinkkonen, and matches all the std # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). y = self.gammavariate(alpha, 1.0) if y == 0: return 0.0 else: return y / (y + self.gammavariate(beta, 1.0)) ## -------------------- Pareto -------------------- def paretovariate(self, alpha): """Pareto distribution. alpha is the shape parameter.""" # Jain, pg. 495 u = 1.0 - self.random() return 1.0 / u ** (1.0/alpha) ## -------------------- Weibull -------------------- def weibullvariate(self, alpha, beta): """Weibull distribution. alpha is the scale parameter and beta is the shape parameter. """ # Jain, pg. 499; bug fix courtesy Bill Arms u = 1.0 - self.random() return alpha * (-_log(u)) ** (1.0/beta) ## --------------- Operating System Random Source ------------------ class SystemRandom(Random): """Alternate random number generator using sources provided by the operating system (such as /dev/urandom on Unix or CryptGenRandom on Windows). Not available on all systems (see os.urandom() for details). """ def random(self): """Get the next random number in the range [0.0, 1.0).""" return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF def getrandbits(self, k): """getrandbits(k) -> x. Generates an int with k random bits.""" if k <= 0: raise ValueError('number of bits must be greater than zero') if k != int(k): raise TypeError('number of bits should be an integer') numbytes = (k + 7) // 8 # bits / 8 and rounded up x = int.from_bytes(_urandom(numbytes), 'big') return x >> (numbytes * 8 - k) # trim excess bits def seed(self, *args, **kwds): "Stub method. Not used for a system random number generator." return None def _notimplemented(self, *args, **kwds): "Method should not be called for a system random number generator." raise NotImplementedError('System entropy source does not have state.') getstate = setstate = _notimplemented ## -------------------- test program -------------------- def _test_generator(n, func, args): import time print(n, 'times', func.__name__) total = 0.0 sqsum = 0.0 smallest = 1e10 largest = -1e10 t0 = time.time() for i in range(n): x = func(*args) total += x sqsum = sqsum + x*x smallest = min(x, smallest) largest = max(x, largest) t1 = time.time() print(round(t1-t0, 3), 'sec,', end=' ') avg = total/n stddev = _sqrt(sqsum/n - avg*avg) print('avg %g, stddev %g, min %g, max %g\n' % \ (avg, stddev, smallest, largest)) def _test(N=2000): _test_generator(N, random, ()) _test_generator(N, normalvariate, (0.0, 1.0)) _test_generator(N, lognormvariate, (0.0, 1.0)) _test_generator(N, vonmisesvariate, (0.0, 1.0)) _test_generator(N, gammavariate, (0.01, 1.0)) _test_generator(N, gammavariate, (0.1, 1.0)) _test_generator(N, gammavariate, (0.1, 2.0)) _test_generator(N, gammavariate, (0.5, 1.0)) _test_generator(N, gammavariate, (0.9, 1.0)) _test_generator(N, gammavariate, (1.0, 1.0)) _test_generator(N, gammavariate, (2.0, 1.0)) _test_generator(N, gammavariate, (20.0, 1.0)) _test_generator(N, gammavariate, (200.0, 1.0)) _test_generator(N, gauss, (0.0, 1.0)) _test_generator(N, betavariate, (3.0, 3.0)) _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0)) # Create one instance, seeded from current time, and export its methods # as module-level functions. The functions share state across all uses #(both in the user's code and in the Python libraries), but that's fine # for most programs and is easier for the casual user than making them # instantiate their own Random() instance. _inst = Random() seed = _inst.seed random = _inst.random uniform = _inst.uniform triangular = _inst.triangular randint = _inst.randint choice = _inst.choice randrange = _inst.randrange sample = _inst.sample shuffle = _inst.shuffle choices = _inst.choices normalvariate = _inst.normalvariate lognormvariate = _inst.lognormvariate expovariate = _inst.expovariate vonmisesvariate = _inst.vonmisesvariate gammavariate = _inst.gammavariate gauss = _inst.gauss betavariate = _inst.betavariate paretovariate = _inst.paretovariate weibullvariate = _inst.weibullvariate getstate = _inst.getstate setstate = _inst.setstate getrandbits = _inst.getrandbits if __name__ == '__main__': _test()
27,441
773
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/dis.py
"""Disassembler of Python byte code into mnemonics.""" import sys import types import collections import io from opcode import * __all__ = ["code_info", "dis", "disassemble", "distb", "disco", "findlinestarts", "findlabels", "show_code", "get_instructions", "Instruction", "Bytecode", "cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG", "hasnargs", 'stack_effect'] _have_code = (types.MethodType, types.FunctionType, types.CodeType, classmethod, staticmethod, type) FORMAT_VALUE = opmap['FORMAT_VALUE'] def _try_compile(source, name): """Attempts to compile the given source, first as an expression and then as a statement if the first approach fails. Utility function to accept strings in functions that otherwise expect code objects """ try: c = compile(source, name, 'eval') except SyntaxError: c = compile(source, name, 'exec') return c def dis(x=None, *, file=None): """Disassemble classes, methods, functions, generators, or code. With no argument, disassemble the last traceback. """ if x is None: distb(file=file) return if hasattr(x, '__func__'): # Method x = x.__func__ if hasattr(x, '__code__'): # Function x = x.__code__ if hasattr(x, 'gi_code'): # Generator x = x.gi_code if hasattr(x, '__dict__'): # Class or module items = sorted(x.__dict__.items()) for name, x1 in items: if isinstance(x1, _have_code): print("Disassembly of %s:" % name, file=file) try: dis(x1, file=file) except TypeError as msg: print("Sorry:", msg, file=file) print(file=file) elif hasattr(x, 'co_code'): # Code object disassemble(x, file=file) elif isinstance(x, (bytes, bytearray)): # Raw bytecode _disassemble_bytes(x, file=file) elif isinstance(x, str): # Source code _disassemble_str(x, file=file) else: raise TypeError("don't know how to disassemble %s objects" % type(x).__name__) def distb(tb=None, *, file=None): """Disassemble a traceback (default: last traceback).""" if tb is None: try: tb = sys.last_traceback except AttributeError: raise RuntimeError("no last traceback to disassemble") while tb.tb_next: tb = tb.tb_next disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file) # The inspect module interrogates this dictionary to build its # list of CO_* constants. It is also used by pretty_flags to # turn the co_flags field into a human readable list. COMPILER_FLAG_NAMES = { 1: "OPTIMIZED", 2: "NEWLOCALS", 4: "VARARGS", 8: "VARKEYWORDS", 16: "NESTED", 32: "GENERATOR", 64: "NOFREE", 128: "COROUTINE", 256: "ITERABLE_COROUTINE", 512: "ASYNC_GENERATOR", } def pretty_flags(flags): """Return pretty representation of code flags.""" names = [] for i in range(32): flag = 1<<i if flags & flag: names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag))) flags ^= flag if not flags: break else: names.append(hex(flags)) return ", ".join(names) def _get_code_object(x): """Helper to handle methods, functions, generators, strings and raw code objects""" if hasattr(x, '__func__'): # Method x = x.__func__ if hasattr(x, '__code__'): # Function x = x.__code__ if hasattr(x, 'gi_code'): # Generator x = x.gi_code if isinstance(x, str): # Source code x = _try_compile(x, "<disassembly>") if hasattr(x, 'co_code'): # Code object return x raise TypeError("don't know how to disassemble %s objects" % type(x).__name__) def code_info(x): """Formatted details of methods, functions, or code.""" return _format_code_info(_get_code_object(x)) def _format_code_info(co): lines = [] lines.append("Name: %s" % co.co_name) lines.append("Filename: %s" % co.co_filename) lines.append("Argument count: %s" % co.co_argcount) lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount) lines.append("Number of locals: %s" % co.co_nlocals) lines.append("Stack size: %s" % co.co_stacksize) lines.append("Flags: %s" % pretty_flags(co.co_flags)) if co.co_consts: lines.append("Constants:") for i_c in enumerate(co.co_consts): lines.append("%4d: %r" % i_c) if co.co_names: lines.append("Names:") for i_n in enumerate(co.co_names): lines.append("%4d: %s" % i_n) if co.co_varnames: lines.append("Variable names:") for i_n in enumerate(co.co_varnames): lines.append("%4d: %s" % i_n) if co.co_freevars: lines.append("Free variables:") for i_n in enumerate(co.co_freevars): lines.append("%4d: %s" % i_n) if co.co_cellvars: lines.append("Cell variables:") for i_n in enumerate(co.co_cellvars): lines.append("%4d: %s" % i_n) return "\n".join(lines) def show_code(co, *, file=None): """Print details of methods, functions, or code to *file*. If *file* is not provided, the output is printed on stdout. """ print(code_info(co), file=file) _Instruction = collections.namedtuple("_Instruction", "opname opcode arg argval argrepr offset starts_line is_jump_target") _Instruction.opname.__doc__ = "Human readable name for operation" _Instruction.opcode.__doc__ = "Numeric code for operation" _Instruction.arg.__doc__ = "Numeric argument to operation (if any), otherwise None" _Instruction.argval.__doc__ = "Resolved arg value (if known), otherwise same as arg" _Instruction.argrepr.__doc__ = "Human readable description of operation argument" _Instruction.offset.__doc__ = "Start index of operation within bytecode sequence" _Instruction.starts_line.__doc__ = "Line started by this opcode (if any), otherwise None" _Instruction.is_jump_target.__doc__ = "True if other code jumps to here, otherwise False" class Instruction(_Instruction): """Details for a bytecode operation Defined fields: opname - human readable name for operation opcode - numeric code for operation arg - numeric argument to operation (if any), otherwise None argval - resolved arg value (if known), otherwise same as arg argrepr - human readable description of operation argument offset - start index of operation within bytecode sequence starts_line - line started by this opcode (if any), otherwise None is_jump_target - True if other code jumps to here, otherwise False """ def _disassemble(self, lineno_width=3, mark_as_current=False): """Format instruction details for inclusion in disassembly output *lineno_width* sets the width of the line number field (0 omits it) *mark_as_current* inserts a '-->' marker arrow as part of the line """ fields = [] # Column: Source code line number if lineno_width: if self.starts_line is not None: lineno_fmt = "%%%dd" % lineno_width fields.append(lineno_fmt % self.starts_line) else: fields.append(' ' * lineno_width) # Column: Current instruction indicator if mark_as_current: fields.append('-->') else: fields.append(' ') # Column: Jump target marker if self.is_jump_target: fields.append('>>') else: fields.append(' ') # Column: Instruction offset from start of code sequence fields.append(repr(self.offset).rjust(4)) # Column: Opcode name fields.append(self.opname.ljust(20)) # Column: Opcode argument if self.arg is not None: fields.append(repr(self.arg).rjust(5)) # Column: Opcode argument details if self.argrepr: fields.append('(' + self.argrepr + ')') return ' '.join(fields).rstrip() def get_instructions(x, *, first_line=None): """Iterator for the opcodes in methods, functions or code Generates a series of Instruction named tuples giving the details of each operations in the supplied code. If *first_line* is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source line information (if any) is taken directly from the disassembled code object. """ co = _get_code_object(x) cell_names = co.co_cellvars + co.co_freevars linestarts = dict(findlinestarts(co)) if first_line is not None: line_offset = first_line - co.co_firstlineno else: line_offset = 0 return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names, co.co_consts, cell_names, linestarts, line_offset) def _get_const_info(const_index, const_list): """Helper to get optional details about const references Returns the dereferenced constant and its repr if the constant list is defined. Otherwise returns the constant index and its repr(). """ argval = const_index if const_list is not None: argval = const_list[const_index] return argval, repr(argval) def _get_name_info(name_index, name_list): """Helper to get optional details about named references Returns the dereferenced name as both value and repr if the name list is defined. Otherwise returns the name index and its repr(). """ argval = name_index if name_list is not None: argval = name_list[name_index] argrepr = argval else: argrepr = repr(argval) return argval, argrepr def _get_instructions_bytes(code, varnames=None, names=None, constants=None, cells=None, linestarts=None, line_offset=0): """Iterate over the instructions in a bytecode string. Generates a sequence of Instruction namedtuples giving the details of each opcode. Additional information about the code's runtime environment (e.g. variable names, constants) can be specified using optional arguments. """ labels = findlabels(code) starts_line = None for offset, op, arg in _unpack_opargs(code): if linestarts is not None: starts_line = linestarts.get(offset, None) if starts_line is not None: starts_line += line_offset is_jump_target = offset in labels argval = None argrepr = '' if arg is not None: # Set argval to the dereferenced value of the argument when # available, and argrepr to the string representation of argval. # _disassemble_bytes needs the string repr of the # raw name index for LOAD_GLOBAL, LOAD_CONST, etc. argval = arg if op in hasconst: argval, argrepr = _get_const_info(arg, constants) elif op in hasname: argval, argrepr = _get_name_info(arg, names) elif op in hasjrel: argval = offset + 2 + arg argrepr = "to " + repr(argval) elif op in haslocal: argval, argrepr = _get_name_info(arg, varnames) elif op in hascompare: argval = cmp_op[arg] argrepr = argval elif op in hasfree: argval, argrepr = _get_name_info(arg, cells) elif op == FORMAT_VALUE: argval = ((None, str, repr, ascii)[arg & 0x3], bool(arg & 0x4)) argrepr = ('', 'str', 'repr', 'ascii')[arg & 0x3] if argval[1]: if argrepr: argrepr += ', ' argrepr += 'with format' yield Instruction(opname[op], op, arg, argval, argrepr, offset, starts_line, is_jump_target) def disassemble(co, lasti=-1, *, file=None): """Disassemble a code object.""" cell_names = co.co_cellvars + co.co_freevars linestarts = dict(findlinestarts(co)) _disassemble_bytes(co.co_code, lasti, co.co_varnames, co.co_names, co.co_consts, cell_names, linestarts, file=file) def _disassemble_bytes(code, lasti=-1, varnames=None, names=None, constants=None, cells=None, linestarts=None, *, file=None, line_offset=0): # Omit the line number column entirely if we have no line number info show_lineno = linestarts is not None # TODO?: Adjust width upwards if max(linestarts.values()) >= 1000? lineno_width = 3 if show_lineno else 0 for instr in _get_instructions_bytes(code, varnames, names, constants, cells, linestarts, line_offset=line_offset): new_source_line = (show_lineno and instr.starts_line is not None and instr.offset > 0) if new_source_line: print(file=file) is_current_instr = instr.offset == lasti print(instr._disassemble(lineno_width, is_current_instr), file=file) def _disassemble_str(source, *, file=None): """Compile the source string, then disassemble the code object.""" disassemble(_try_compile(source, '<dis>'), file=file) disco = disassemble # XXX For backwards compatibility def _unpack_opargs(code): extended_arg = 0 for i in range(0, len(code), 2): op = code[i] if op >= HAVE_ARGUMENT: arg = code[i+1] | extended_arg extended_arg = (arg << 8) if op == EXTENDED_ARG else 0 else: arg = None yield (i, op, arg) def findlabels(code): """Detect all offsets in a byte code which are jump targets. Return the list of offsets. """ labels = [] for offset, op, arg in _unpack_opargs(code): if arg is not None: if op in hasjrel: label = offset + 2 + arg elif op in hasjabs: label = arg else: continue if label not in labels: labels.append(label) return labels def findlinestarts(code): """Find the offsets in a byte code which are start of lines in the source. Generate pairs (offset, lineno) as described in Python/compile.c. """ byte_increments = code.co_lnotab[0::2] line_increments = code.co_lnotab[1::2] lastlineno = None lineno = code.co_firstlineno addr = 0 for byte_incr, line_incr in zip(byte_increments, line_increments): if byte_incr: if lineno != lastlineno: yield (addr, lineno) lastlineno = lineno addr += byte_incr if line_incr >= 0x80: # line_increments is an array of 8-bit signed integers line_incr -= 0x100 lineno += line_incr if lineno != lastlineno: yield (addr, lineno) class Bytecode: """The bytecode operations of a piece of code Instantiate this with a function, method, string of code, or a code object (as returned by compile()). Iterating over this yields the bytecode operations as Instruction instances. """ def __init__(self, x, *, first_line=None, current_offset=None): self.codeobj = co = _get_code_object(x) if first_line is None: self.first_line = co.co_firstlineno self._line_offset = 0 else: self.first_line = first_line self._line_offset = first_line - co.co_firstlineno self._cell_names = co.co_cellvars + co.co_freevars self._linestarts = dict(findlinestarts(co)) self._original_object = x self.current_offset = current_offset def __iter__(self): co = self.codeobj return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names, co.co_consts, self._cell_names, self._linestarts, line_offset=self._line_offset) def __repr__(self): return "{}({!r})".format(self.__class__.__name__, self._original_object) @classmethod def from_traceback(cls, tb): """ Construct a Bytecode from the given traceback """ while tb.tb_next: tb = tb.tb_next return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti) def info(self): """Return formatted information about the code object.""" return _format_code_info(self.codeobj) def dis(self): """Return a formatted view of the bytecode operations.""" co = self.codeobj if self.current_offset is not None: offset = self.current_offset else: offset = -1 with io.StringIO() as output: _disassemble_bytes(co.co_code, varnames=co.co_varnames, names=co.co_names, constants=co.co_consts, cells=self._cell_names, linestarts=self._linestarts, line_offset=self._line_offset, file=output, lasti=offset) return output.getvalue() def _test(): """Simple test program to disassemble a file.""" import argparse parser = argparse.ArgumentParser() parser.add_argument('infile', type=argparse.FileType(), nargs='?', default='-') args = parser.parse_args() with args.infile as infile: source = infile.read() code = compile(source, args.infile.name, "exec") dis(code) if __name__ == "__main__": _test()
18,262
492
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/ast.py
""" ast ~~~ The `ast` module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like and allows modifications of it. An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as a flag to the `compile()` builtin function or by using the `parse()` function from this module. The result will be a tree of objects whose classes all inherit from `ast.AST`. A modified abstract syntax tree can be compiled into a Python code object using the built-in `compile()` function. Additionally various helper functions are provided that make working with the trees simpler. The main intention of the helper functions and this module in general is to provide an easy to use interface for libraries that work tightly with the python syntax (template engines for example). :copyright: Copyright 2008 by Armin Ronacher. :license: Python License. """ from _ast import * def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST) _NUM_TYPES = (int, float, complex) def literal_eval(node_or_string): """ Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. """ if isinstance(node_or_string, str): node_or_string = parse(node_or_string, mode='eval') if isinstance(node_or_string, Expression): node_or_string = node_or_string.body def _convert(node): if isinstance(node, Constant): return node.value elif isinstance(node, (Str, Bytes)): return node.s elif isinstance(node, Num): return node.n elif isinstance(node, Tuple): return tuple(map(_convert, node.elts)) elif isinstance(node, List): return list(map(_convert, node.elts)) elif isinstance(node, Set): return set(map(_convert, node.elts)) elif isinstance(node, Dict): return dict((_convert(k), _convert(v)) for k, v in zip(node.keys, node.values)) elif isinstance(node, NameConstant): return node.value elif isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)): operand = _convert(node.operand) if isinstance(operand, _NUM_TYPES): if isinstance(node.op, UAdd): return + operand else: return - operand elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)): left = _convert(node.left) right = _convert(node.right) if isinstance(left, _NUM_TYPES) and isinstance(right, _NUM_TYPES): if isinstance(node.op, Add): return left + right else: return left - right raise ValueError('malformed node or string: ' + repr(node)) return _convert(node_or_string) def dump(node, annotate_fields=True, include_attributes=False): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True. """ def _format(node): if isinstance(node, AST): fields = [(a, _format(b)) for a, b in iter_fields(node)] rv = '%s(%s' % (node.__class__.__name__, ', '.join( ('%s=%s' % field for field in fields) if annotate_fields else (b for a, b in fields) )) if include_attributes and node._attributes: rv += fields and ', ' or ' ' rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) for a in node._attributes) return rv + ')' elif isinstance(node, list): return '[%s]' % ', '.join(_format(x) for x in node) return repr(node) if not isinstance(node, AST): raise TypeError('expected AST, got %r' % node.__class__.__name__) return _format(node) def copy_location(new_node, old_node): """ Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ for attr in 'lineno', 'col_offset': if attr in old_node._attributes and attr in new_node._attributes \ and hasattr(old_node, attr): setattr(new_node, attr, getattr(old_node, attr)) return new_node def fix_missing_locations(node): """ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*. """ def _fix(node, lineno, col_offset): if 'lineno' in node._attributes: if not hasattr(node, 'lineno'): node.lineno = lineno else: lineno = node.lineno if 'col_offset' in node._attributes: if not hasattr(node, 'col_offset'): node.col_offset = col_offset else: col_offset = node.col_offset for child in iter_child_nodes(node): _fix(child, lineno, col_offset) _fix(node, 1, 0) return node def increment_lineno(node, n=1): """ Increment the line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file. """ for child in walk(node): if 'lineno' in child._attributes: child.lineno = getattr(child, 'lineno', 0) + n return node def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass def iter_child_nodes(node): """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): for item in field: if isinstance(item, AST): yield item def get_docstring(node, clean=True): """ Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised. """ if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)): raise TypeError("%r can't have docstrings" % node.__class__.__name__) if not(node.body and isinstance(node.body[0], Expr)): return node = node.body[0].value if isinstance(node, Str): text = node.s elif isinstance(node, Constant) and isinstance(node.value, str): text = node.value else: return if clean: import inspect text = inspect.cleandoc(text) return text def walk(node): """ Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) while todo: node = todo.popleft() todo.extend(iter_child_nodes(node)) yield node class NodeVisitor(object): """ A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. Per default the visitor functions for the nodes are ``'visit_'`` + class name of the node. So a `TryFinally` node visit function would be `visit_TryFinally`. This behavior can be changed by overriding the `visit` method. If no visitor function exists for a node (return value `None`) the `generic_visit` visitor is used instead. Don't use the `NodeVisitor` if you want to apply changes to nodes during traversing. For this a special visitor exists (`NodeTransformer`) that allows modifications. """ def visit(self, node): """Visit a node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node) def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field, value in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(value) class NodeTransformer(NodeVisitor): """ A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes. The `NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is ``None``, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place. Here is an example transformer that rewrites all occurrences of name lookups (``foo``) to ``data['foo']``:: class RewriteName(NodeTransformer): def visit_Name(self, node): return copy_location(Subscript( value=Name(id='data', ctx=Load()), slice=Index(value=Str(s=node.id)), ctx=node.ctx ), node) Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the :meth:`generic_visit` method for the node first. For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node. Usually you use the transformer like this:: node = YourTransformer().visit(node) """ def generic_visit(self, node): for field, old_value in iter_fields(node): if isinstance(old_value, list): new_values = [] for value in old_value: if isinstance(value, AST): value = self.visit(value) if value is None: continue elif not isinstance(value, AST): new_values.extend(value) continue new_values.append(value) old_value[:] = new_values elif isinstance(old_value, AST): new_node = self.visit(old_value) if new_node is None: delattr(node, field) else: setattr(node, field, new_node) return node
12,166
323
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/nntplib.py
"""An NNTP client class based on: - RFC 977: Network News Transfer Protocol - RFC 2980: Common NNTP Extensions - RFC 3977: Network News Transfer Protocol (version 2) Example: >>> from nntplib import NNTP >>> s = NNTP('news') >>> resp, count, first, last, name = s.group('comp.lang.python') >>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) Group comp.lang.python has 51 articles, range 5770 to 5821 >>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last)) >>> resp = s.quit() >>> Here 'resp' is the server response line. Error responses are turned into exceptions. To post an article from a file: >>> f = open(filename, 'rb') # file containing article, including header >>> resp = s.post(f) >>> For descriptions of all methods, read the comments in the code below. Note that all arguments and return values representing article numbers are strings, not numbers, since they are rarely used for calculations. """ # RFC 977 by Brian Kantor and Phil Lapsley. # xover, xgtitle, xpath, date methods by Kevan Heydon # Incompatible changes from the 2.x nntplib: # - all commands are encoded as UTF-8 data (using the "surrogateescape" # error handler), except for raw message data (POST, IHAVE) # - all responses are decoded as UTF-8 data (using the "surrogateescape" # error handler), except for raw message data (ARTICLE, HEAD, BODY) # - the `file` argument to various methods is keyword-only # # - NNTP.date() returns a datetime object # - NNTP.newgroups() and NNTP.newnews() take a datetime (or date) object, # rather than a pair of (date, time) strings. # - NNTP.newgroups() and NNTP.list() return a list of GroupInfo named tuples # - NNTP.descriptions() returns a dict mapping group names to descriptions # - NNTP.xover() returns a list of dicts mapping field names (header or metadata) # to field values; each dict representing a message overview. # - NNTP.article(), NNTP.head() and NNTP.body() return a (response, ArticleInfo) # tuple. # - the "internal" methods have been marked private (they now start with # an underscore) # Other changes from the 2.x/3.1 nntplib: # - automatic querying of capabilities at connect # - New method NNTP.getcapabilities() # - New method NNTP.over() # - New helper function decode_header() # - NNTP.post() and NNTP.ihave() accept file objects, bytes-like objects and # arbitrary iterables yielding lines. # - An extensive test suite :-) # TODO: # - return structured data (GroupInfo etc.) everywhere # - support HDR # Imports import re import socket import collections import datetime import warnings try: import ssl except ImportError: _have_ssl = False else: _have_ssl = True from email.header import decode_header as _email_decode_header from socket import _GLOBAL_DEFAULT_TIMEOUT __all__ = ["NNTP", "NNTPError", "NNTPReplyError", "NNTPTemporaryError", "NNTPPermanentError", "NNTPProtocolError", "NNTPDataError", "decode_header", ] # maximal line length when calling readline(). This is to prevent # reading arbitrary length lines. RFC 3977 limits NNTP line length to # 512 characters, including CRLF. We have selected 2048 just to be on # the safe side. _MAXLINE = 2048 # Exceptions raised when an error or invalid response is received class NNTPError(Exception): """Base class for all nntplib exceptions""" def __init__(self, *args): Exception.__init__(self, *args) try: self.response = args[0] except IndexError: self.response = 'No response given' class NNTPReplyError(NNTPError): """Unexpected [123]xx reply""" pass class NNTPTemporaryError(NNTPError): """4xx errors""" pass class NNTPPermanentError(NNTPError): """5xx errors""" pass class NNTPProtocolError(NNTPError): """Response does not begin with [1-5]""" pass class NNTPDataError(NNTPError): """Error in response data""" pass # Standard port used by NNTP servers NNTP_PORT = 119 NNTP_SSL_PORT = 563 # Response numbers that are followed by additional text (e.g. article) _LONGRESP = { '100', # HELP '101', # CAPABILITIES '211', # LISTGROUP (also not multi-line with GROUP) '215', # LIST '220', # ARTICLE '221', # HEAD, XHDR '222', # BODY '224', # OVER, XOVER '225', # HDR '230', # NEWNEWS '231', # NEWGROUPS '282', # XGTITLE } # Default decoded value for LIST OVERVIEW.FMT if not supported _DEFAULT_OVERVIEW_FMT = [ "subject", "from", "date", "message-id", "references", ":bytes", ":lines"] # Alternative names allowed in LIST OVERVIEW.FMT response _OVERVIEW_FMT_ALTERNATIVES = { 'bytes': ':bytes', 'lines': ':lines', } # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) _CRLF = b'\r\n' GroupInfo = collections.namedtuple('GroupInfo', ['group', 'last', 'first', 'flag']) ArticleInfo = collections.namedtuple('ArticleInfo', ['number', 'message_id', 'lines']) # Helper function(s) def decode_header(header_str): """Takes a unicode string representing a munged header value and decodes it as a (possibly non-ASCII) readable value.""" parts = [] for v, enc in _email_decode_header(header_str): if isinstance(v, bytes): parts.append(v.decode(enc or 'ascii')) else: parts.append(v) return ''.join(parts) def _parse_overview_fmt(lines): """Parse a list of string representing the response to LIST OVERVIEW.FMT and return a list of header/metadata names. Raises NNTPDataError if the response is not compliant (cf. RFC 3977, section 8.4).""" fmt = [] for line in lines: if line[0] == ':': # Metadata name (e.g. ":bytes") name, _, suffix = line[1:].partition(':') name = ':' + name else: # Header name (e.g. "Subject:" or "Xref:full") name, _, suffix = line.partition(':') name = name.lower() name = _OVERVIEW_FMT_ALTERNATIVES.get(name, name) # Should we do something with the suffix? fmt.append(name) defaults = _DEFAULT_OVERVIEW_FMT if len(fmt) < len(defaults): raise NNTPDataError("LIST OVERVIEW.FMT response too short") if fmt[:len(defaults)] != defaults: raise NNTPDataError("LIST OVERVIEW.FMT redefines default fields") return fmt def _parse_overview(lines, fmt, data_process_func=None): """Parse the response to an OVER or XOVER command according to the overview format `fmt`.""" n_defaults = len(_DEFAULT_OVERVIEW_FMT) overview = [] for line in lines: fields = {} article_number, *tokens = line.split('\t') article_number = int(article_number) for i, token in enumerate(tokens): if i >= len(fmt): # XXX should we raise an error? Some servers might not # support LIST OVERVIEW.FMT and still return additional # headers. continue field_name = fmt[i] is_metadata = field_name.startswith(':') if i >= n_defaults and not is_metadata: # Non-default header names are included in full in the response # (unless the field is totally empty) h = field_name + ": " if token and token[:len(h)].lower() != h: raise NNTPDataError("OVER/XOVER response doesn't include " "names of additional headers") token = token[len(h):] if token else None fields[fmt[i]] = token overview.append((article_number, fields)) return overview def _parse_datetime(date_str, time_str=None): """Parse a pair of (date, time) strings, and return a datetime object. If only the date is given, it is assumed to be date and time concatenated together (e.g. response to the DATE command). """ if time_str is None: time_str = date_str[-6:] date_str = date_str[:-6] hours = int(time_str[:2]) minutes = int(time_str[2:4]) seconds = int(time_str[4:]) year = int(date_str[:-4]) month = int(date_str[-4:-2]) day = int(date_str[-2:]) # RFC 3977 doesn't say how to interpret 2-char years. Assume that # there are no dates before 1970 on Usenet. if year < 70: year += 2000 elif year < 100: year += 1900 return datetime.datetime(year, month, day, hours, minutes, seconds) def _unparse_datetime(dt, legacy=False): """Format a date or datetime object as a pair of (date, time) strings in the format required by the NEWNEWS and NEWGROUPS commands. If a date object is passed, the time is assumed to be midnight (00h00). The returned representation depends on the legacy flag: * if legacy is False (the default): date has the YYYYMMDD format and time the HHMMSS format * if legacy is True: date has the YYMMDD format and time the HHMMSS format. RFC 3977 compliant servers should understand both formats; therefore, legacy is only needed when talking to old servers. """ if not isinstance(dt, datetime.datetime): time_str = "000000" else: time_str = "{0.hour:02d}{0.minute:02d}{0.second:02d}".format(dt) y = dt.year if legacy: y = y % 100 date_str = "{0:02d}{1.month:02d}{1.day:02d}".format(y, dt) else: date_str = "{0:04d}{1.month:02d}{1.day:02d}".format(y, dt) return date_str, time_str if _have_ssl: def _encrypt_on(sock, context, hostname): """Wrap a socket in SSL/TLS. Arguments: - sock: Socket to wrap - context: SSL context to use for the encrypted connection Returns: - sock: New, encrypted socket. """ # Generate a default SSL context if none was passed. if context is None: context = ssl._create_stdlib_context() return context.wrap_socket(sock, server_hostname=hostname) # The classes themselves class _NNTPBase: # UTF-8 is the character set for all NNTP commands and responses: they # are automatically encoded (when sending) and decoded (and receiving) # by this class. # However, some multi-line data blocks can contain arbitrary bytes (for # example, latin-1 or utf-16 data in the body of a message). Commands # taking (POST, IHAVE) or returning (HEAD, BODY, ARTICLE) raw message # data will therefore only accept and produce bytes objects. # Furthermore, since there could be non-compliant servers out there, # we use 'surrogateescape' as the error handler for fault tolerance # and easy round-tripping. This could be useful for some applications # (e.g. NNTP gateways). encoding = 'utf-8' errors = 'surrogateescape' def __init__(self, file, host, readermode=None, timeout=_GLOBAL_DEFAULT_TIMEOUT): """Initialize an instance. Arguments: - file: file-like object (open for read/write in binary mode) - host: hostname of the server - readermode: if true, send 'mode reader' command after connecting. - timeout: timeout (in seconds) used for socket connections readermode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as `group'. If you get unexpected NNTPPermanentErrors, you might need to set readermode. """ self.host = host self.file = file self.debugging = 0 self.welcome = self._getresp() # Inquire about capabilities (RFC 3977). self._caps = None self.getcapabilities() # 'MODE READER' is sometimes necessary to enable 'reader' mode. # However, the order in which 'MODE READER' and 'AUTHINFO' need to # arrive differs between some NNTP servers. If _setreadermode() fails # with an authorization failed error, it will set this to True; # the login() routine will interpret that as a request to try again # after performing its normal function. # Enable only if we're not already in READER mode anyway. self.readermode_afterauth = False if readermode and 'READER' not in self._caps: self._setreadermode() if not self.readermode_afterauth: # Capabilities might have changed after MODE READER self._caps = None self.getcapabilities() # RFC 4642 2.2.2: Both the client and the server MUST know if there is # a TLS session active. A client MUST NOT attempt to start a TLS # session if a TLS session is already active. self.tls_on = False # Log in and encryption setup order is left to subclasses. self.authenticated = False def __enter__(self): return self def __exit__(self, *args): is_connected = lambda: hasattr(self, "file") if is_connected(): try: self.quit() except (OSError, EOFError): pass finally: if is_connected(): self._close() def getwelcome(self): """Get the welcome message from the server (this is read and squirreled away by __init__()). If the response code is 200, posting is allowed; if it 201, posting is not allowed.""" if self.debugging: print('*welcome*', repr(self.welcome)) return self.welcome def getcapabilities(self): """Get the server capabilities, as read by __init__(). If the CAPABILITIES command is not supported, an empty dict is returned.""" if self._caps is None: self.nntp_version = 1 self.nntp_implementation = None try: resp, caps = self.capabilities() except (NNTPPermanentError, NNTPTemporaryError): # Server doesn't support capabilities self._caps = {} else: self._caps = caps if 'VERSION' in caps: # The server can advertise several supported versions, # choose the highest. self.nntp_version = max(map(int, caps['VERSION'])) if 'IMPLEMENTATION' in caps: self.nntp_implementation = ' '.join(caps['IMPLEMENTATION']) return self._caps def set_debuglevel(self, level): """Set the debugging level. Argument 'level' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF""" self.debugging = level debug = set_debuglevel def _putline(self, line): """Internal: send one line to the server, appending CRLF. The `line` must be a bytes-like object.""" line = line + _CRLF if self.debugging > 1: print('*put*', repr(line)) self.file.write(line) self.file.flush() def _putcmd(self, line): """Internal: send one command to the server (through _putline()). The `line` must be a unicode string.""" if self.debugging: print('*cmd*', repr(line)) line = line.encode(self.encoding, self.errors) self._putline(line) def _getline(self, strip_crlf=True): """Internal: return one line from the server, stripping _CRLF. Raise EOFError if the connection is closed. Returns a bytes object.""" line = self.file.readline(_MAXLINE +1) if len(line) > _MAXLINE: raise NNTPDataError('line too long') if self.debugging > 1: print('*get*', repr(line)) if not line: raise EOFError if strip_crlf: if line[-2:] == _CRLF: line = line[:-2] elif line[-1:] in _CRLF: line = line[:-1] return line def _getresp(self): """Internal: get a response from the server. Raise various errors if the response indicates an error. Returns a unicode string.""" resp = self._getline() if self.debugging: print('*resp*', repr(resp)) resp = resp.decode(self.encoding, self.errors) c = resp[:1] if c == '4': raise NNTPTemporaryError(resp) if c == '5': raise NNTPPermanentError(resp) if c not in '123': raise NNTPProtocolError(resp) return resp def _getlongresp(self, file=None): """Internal: get a response plus following text from the server. Raise various errors if the response indicates an error. Returns a (response, lines) tuple where `response` is a unicode string and `lines` is a list of bytes objects. If `file` is a file-like object, it must be open in binary mode. """ openedFile = None try: # If a string was passed then open a file with that name if isinstance(file, (str, bytes)): openedFile = file = open(file, "wb") resp = self._getresp() if resp[:3] not in _LONGRESP: raise NNTPReplyError(resp) lines = [] if file is not None: # XXX lines = None instead? terminators = (b'.' + _CRLF, b'.\n') while 1: line = self._getline(False) if line in terminators: break if line.startswith(b'..'): line = line[1:] file.write(line) else: terminator = b'.' while 1: line = self._getline() if line == terminator: break if line.startswith(b'..'): line = line[1:] lines.append(line) finally: # If this method created the file, then it must close it if openedFile: openedFile.close() return resp, lines def _shortcmd(self, line): """Internal: send a command and get the response. Same return value as _getresp().""" self._putcmd(line) return self._getresp() def _longcmd(self, line, file=None): """Internal: send a command and get the response plus following text. Same return value as _getlongresp().""" self._putcmd(line) return self._getlongresp(file) def _longcmdstring(self, line, file=None): """Internal: send a command and get the response plus following text. Same as _longcmd() and _getlongresp(), except that the returned `lines` are unicode strings rather than bytes objects. """ self._putcmd(line) resp, list = self._getlongresp(file) return resp, [line.decode(self.encoding, self.errors) for line in list] def _getoverviewfmt(self): """Internal: get the overview format. Queries the server if not already done, else returns the cached value.""" try: return self._cachedoverviewfmt except AttributeError: pass try: resp, lines = self._longcmdstring("LIST OVERVIEW.FMT") except NNTPPermanentError: # Not supported by server? fmt = _DEFAULT_OVERVIEW_FMT[:] else: fmt = _parse_overview_fmt(lines) self._cachedoverviewfmt = fmt return fmt def _grouplist(self, lines): # Parse lines into "group last first flag" return [GroupInfo(*line.split()) for line in lines] def capabilities(self): """Process a CAPABILITIES command. Not supported by all servers. Return: - resp: server response if successful - caps: a dictionary mapping capability names to lists of tokens (for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] }) """ caps = {} resp, lines = self._longcmdstring("CAPABILITIES") for line in lines: name, *tokens = line.split() caps[name] = tokens return resp, caps def newgroups(self, date, *, file=None): """Process a NEWGROUPS command. Arguments: - date: a date or datetime object Return: - resp: server response if successful - list: list of newsgroup names """ if not isinstance(date, (datetime.date, datetime.date)): raise TypeError( "the date parameter must be a date or datetime object, " "not '{:40}'".format(date.__class__.__name__)) date_str, time_str = _unparse_datetime(date, self.nntp_version < 2) cmd = 'NEWGROUPS {0} {1}'.format(date_str, time_str) resp, lines = self._longcmdstring(cmd, file) return resp, self._grouplist(lines) def newnews(self, group, date, *, file=None): """Process a NEWNEWS command. Arguments: - group: group name or '*' - date: a date or datetime object Return: - resp: server response if successful - list: list of message ids """ if not isinstance(date, (datetime.date, datetime.date)): raise TypeError( "the date parameter must be a date or datetime object, " "not '{:40}'".format(date.__class__.__name__)) date_str, time_str = _unparse_datetime(date, self.nntp_version < 2) cmd = 'NEWNEWS {0} {1} {2}'.format(group, date_str, time_str) return self._longcmdstring(cmd, file) def list(self, group_pattern=None, *, file=None): """Process a LIST or LIST ACTIVE command. Arguments: - group_pattern: a pattern indicating which groups to query - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of (group, last, first, flag) (strings) """ if group_pattern is not None: command = 'LIST ACTIVE ' + group_pattern else: command = 'LIST' resp, lines = self._longcmdstring(command, file) return resp, self._grouplist(lines) def _getdescriptions(self, group_pattern, return_all): line_pat = re.compile('^(?P<group>[^ \t]+)[ \t]+(.*)$') # Try the more std (acc. to RFC2980) LIST NEWSGROUPS first resp, lines = self._longcmdstring('LIST NEWSGROUPS ' + group_pattern) if not resp.startswith('215'): # Now the deprecated XGTITLE. This either raises an error # or succeeds with the same output structure as LIST # NEWSGROUPS. resp, lines = self._longcmdstring('XGTITLE ' + group_pattern) groups = {} for raw_line in lines: match = line_pat.search(raw_line.strip()) if match: name, desc = match.group(1, 2) if not return_all: return desc groups[name] = desc if return_all: return resp, groups else: # Nothing found return '' def description(self, group): """Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.""" return self._getdescriptions(group, False) def descriptions(self, group_pattern): """Get descriptions for a range of groups.""" return self._getdescriptions(group_pattern, True) def group(self, name): """Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles - first: first article number - last: last article number - name: the group name """ resp = self._shortcmd('GROUP ' + name) if not resp.startswith('211'): raise NNTPReplyError(resp) words = resp.split() count = first = last = 0 n = len(words) if n > 1: count = words[1] if n > 2: first = words[2] if n > 3: last = words[3] if n > 4: name = words[4].lower() return resp, int(count), int(first), int(last), name def help(self, *, file=None): """Process a HELP command. Argument: - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of strings returned by the server in response to the HELP command """ return self._longcmdstring('HELP', file) def _statparse(self, resp): """Internal: parse the response line of a STAT, NEXT, LAST, ARTICLE, HEAD or BODY command.""" if not resp.startswith('22'): raise NNTPReplyError(resp) words = resp.split() art_num = int(words[1]) message_id = words[2] return resp, art_num, message_id def _statcmd(self, line): """Internal: process a STAT, NEXT or LAST command.""" resp = self._shortcmd(line) return self._statparse(resp) def stat(self, message_spec=None): """Process a STAT command. Argument: - message_spec: article number or message id (if not specified, the current article is selected) Returns: - resp: server response if successful - art_num: the article number - message_id: the message id """ if message_spec: return self._statcmd('STAT {0}'.format(message_spec)) else: return self._statcmd('STAT') def next(self): """Process a NEXT command. No arguments. Return as for STAT.""" return self._statcmd('NEXT') def last(self): """Process a LAST command. No arguments. Return as for STAT.""" return self._statcmd('LAST') def _artcmd(self, line, file=None): """Internal: process a HEAD, BODY or ARTICLE command.""" resp, lines = self._longcmd(line, file) resp, art_num, message_id = self._statparse(resp) return resp, ArticleInfo(art_num, message_id, lines) def head(self, message_spec=None, *, file=None): """Process a HEAD command. Argument: - message_spec: article number or message id - file: filename string or file object to store the headers in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of header lines) """ if message_spec is not None: cmd = 'HEAD {0}'.format(message_spec) else: cmd = 'HEAD' return self._artcmd(cmd, file) def body(self, message_spec=None, *, file=None): """Process a BODY command. Argument: - message_spec: article number or message id - file: filename string or file object to store the body in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of body lines) """ if message_spec is not None: cmd = 'BODY {0}'.format(message_spec) else: cmd = 'BODY' return self._artcmd(cmd, file) def article(self, message_spec=None, *, file=None): """Process an ARTICLE command. Argument: - message_spec: article number or message id - file: filename string or file object to store the article in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of article lines) """ if message_spec is not None: cmd = 'ARTICLE {0}'.format(message_spec) else: cmd = 'ARTICLE' return self._artcmd(cmd, file) def slave(self): """Process a SLAVE command. Returns: - resp: server response if successful """ return self._shortcmd('SLAVE') def xhdr(self, hdr, str, *, file=None): """Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of (nr, value) strings """ pat = re.compile('^([0-9]+) ?(.*)\n?') resp, lines = self._longcmdstring('XHDR {0} {1}'.format(hdr, str), file) def remove_number(line): m = pat.match(line) return m.group(1, 2) if m else line return resp, [remove_number(line) for line in lines] def xover(self, start, end, *, file=None): """Process an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of dicts containing the response fields """ resp, lines = self._longcmdstring('XOVER {0}-{1}'.format(start, end), file) fmt = self._getoverviewfmt() return resp, _parse_overview(lines, fmt) def over(self, message_spec, *, file=None): """Process an OVER command. If the command isn't supported, fall back to XOVER. Arguments: - message_spec: - either a message id, indicating the article to fetch information about - or a (start, end) tuple, indicating a range of article numbers; if end is None, information up to the newest message will be retrieved - or None, indicating the current article number must be used - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of dicts containing the response fields NOTE: the "message id" form isn't supported by XOVER """ cmd = 'OVER' if 'OVER' in self._caps else 'XOVER' if isinstance(message_spec, (tuple, list)): start, end = message_spec cmd += ' {0}-{1}'.format(start, end or '') elif message_spec is not None: cmd = cmd + ' ' + message_spec resp, lines = self._longcmdstring(cmd, file) fmt = self._getoverviewfmt() return resp, _parse_overview(lines, fmt) def xgtitle(self, group, *, file=None): """Process an XGTITLE command (optional server extension) Arguments: - group: group name wildcard (i.e. news.*) Returns: - resp: server response if successful - list: list of (name,title) strings""" warnings.warn("The XGTITLE extension is not actively used, " "use descriptions() instead", DeprecationWarning, 2) line_pat = re.compile('^([^ \t]+)[ \t]+(.*)$') resp, raw_lines = self._longcmdstring('XGTITLE ' + group, file) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return resp, lines def xpath(self, id): """Process an XPATH command (optional server extension) Arguments: - id: Message id of article Returns: resp: server response if successful path: directory path to article """ warnings.warn("The XPATH extension is not actively used", DeprecationWarning, 2) resp = self._shortcmd('XPATH {0}'.format(id)) if not resp.startswith('223'): raise NNTPReplyError(resp) try: [resp_num, path] = resp.split() except ValueError: raise NNTPReplyError(resp) else: return resp, path def date(self): """Process the DATE command. Returns: - resp: server response if successful - date: datetime object """ resp = self._shortcmd("DATE") if not resp.startswith('111'): raise NNTPReplyError(resp) elem = resp.split() if len(elem) != 2: raise NNTPDataError(resp) date = elem[1] if len(date) != 14: raise NNTPDataError(resp) return resp, _parse_datetime(date, None) def _post(self, command, f): resp = self._shortcmd(command) # Raises a specific exception if posting is not allowed if not resp.startswith('3'): raise NNTPReplyError(resp) if isinstance(f, (bytes, bytearray)): f = f.splitlines() # We don't use _putline() because: # - we don't want additional CRLF if the file or iterable is already # in the right format # - we don't want a spurious flush() after each line is written for line in f: if not line.endswith(_CRLF): line = line.rstrip(b"\r\n") + _CRLF if line.startswith(b'.'): line = b'.' + line self.file.write(line) self.file.write(b".\r\n") self.file.flush() return self._getresp() def post(self, data): """Process a POST command. Arguments: - data: bytes object, iterable or file containing the article Returns: - resp: server response if successful""" return self._post('POST', data) def ihave(self, message_id, data): """Process an IHAVE command. Arguments: - message_id: message-id of the article - data: file containing the article Returns: - resp: server response if successful Note that if the server refuses the article an exception is raised.""" return self._post('IHAVE {0}'.format(message_id), data) def _close(self): self.file.close() del self.file def quit(self): """Process a QUIT command and close the socket. Returns: - resp: server response if successful""" try: resp = self._shortcmd('QUIT') finally: self._close() return resp def login(self, user=None, password=None, usenetrc=True): if self.authenticated: raise ValueError("Already logged in.") if not user and not usenetrc: raise ValueError( "At least one of `user` and `usenetrc` must be specified") # If no login/password was specified but netrc was requested, # try to get them from ~/.netrc # Presume that if .netrc has an entry, NNRP authentication is required. try: if usenetrc and not user: import netrc credentials = netrc.netrc() auth = credentials.authenticators(self.host) if auth: user = auth[0] password = auth[2] except OSError: pass # Perform NNTP authentication if needed. if not user: return resp = self._shortcmd('authinfo user ' + user) if resp.startswith('381'): if not password: raise NNTPReplyError(resp) else: resp = self._shortcmd('authinfo pass ' + password) if not resp.startswith('281'): raise NNTPPermanentError(resp) # Capabilities might have changed after login self._caps = None self.getcapabilities() # Attempt to send mode reader if it was requested after login. # Only do so if we're not in reader mode already. if self.readermode_afterauth and 'READER' not in self._caps: self._setreadermode() # Capabilities might have changed after MODE READER self._caps = None self.getcapabilities() def _setreadermode(self): try: self.welcome = self._shortcmd('mode reader') except NNTPPermanentError: # Error 5xx, probably 'not implemented' pass except NNTPTemporaryError as e: if e.response.startswith('480'): # Need authorization before 'mode reader' self.readermode_afterauth = True else: raise if _have_ssl: def starttls(self, context=None): """Process a STARTTLS command. Arguments: - context: SSL context to use for the encrypted connection """ # Per RFC 4642, STARTTLS MUST NOT be sent after authentication or if # a TLS session already exists. if self.tls_on: raise ValueError("TLS is already enabled.") if self.authenticated: raise ValueError("TLS cannot be started after authentication.") resp = self._shortcmd('STARTTLS') if resp.startswith('382'): self.file.close() self.sock = _encrypt_on(self.sock, context, self.host) self.file = self.sock.makefile("rwb") self.tls_on = True # Capabilities may change after TLS starts up, so ask for them # again. self._caps = None self.getcapabilities() else: raise NNTPError("TLS failed to start.") class NNTP(_NNTPBase): def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None, usenetrc=False, timeout=_GLOBAL_DEFAULT_TIMEOUT): """Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send 'mode reader' command after connecting. - usenetrc: allow loading username and password from ~/.netrc file if not specified explicitly - timeout: timeout (in seconds) used for socket connections readermode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as `group'. If you get unexpected NNTPPermanentErrors, you might need to set readermode. """ self.host = host self.port = port self.sock = socket.create_connection((host, port), timeout) file = None try: file = self.sock.makefile("rwb") _NNTPBase.__init__(self, file, host, readermode, timeout) if user or usenetrc: self.login(user, password, usenetrc) except: if file: file.close() self.sock.close() raise def _close(self): try: _NNTPBase._close(self) finally: self.sock.close() if _have_ssl: class NNTP_SSL(_NNTPBase): def __init__(self, host, port=NNTP_SSL_PORT, user=None, password=None, ssl_context=None, readermode=None, usenetrc=False, timeout=_GLOBAL_DEFAULT_TIMEOUT): """This works identically to NNTP.__init__, except for the change in default port and the `ssl_context` argument for SSL connections. """ self.sock = socket.create_connection((host, port), timeout) file = None try: self.sock = _encrypt_on(self.sock, ssl_context, host) file = self.sock.makefile("rwb") _NNTPBase.__init__(self, file, host, readermode=readermode, timeout=timeout) if user or usenetrc: self.login(user, password, usenetrc) except: if file: file.close() self.sock.close() raise def _close(self): try: _NNTPBase._close(self) finally: self.sock.close() __all__.append("NNTP_SSL") # Test retrieval when run as a script. if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description="""\ nntplib built-in demo - display the latest articles in a newsgroup""") parser.add_argument('-g', '--group', default='gmane.comp.python.general', help='group to fetch messages from (default: %(default)s)') parser.add_argument('-s', '--server', default='news.gmane.org', help='NNTP server hostname (default: %(default)s)') parser.add_argument('-p', '--port', default=-1, type=int, help='NNTP port number (default: %s / %s)' % (NNTP_PORT, NNTP_SSL_PORT)) parser.add_argument('-n', '--nb-articles', default=10, type=int, help='number of articles to fetch (default: %(default)s)') parser.add_argument('-S', '--ssl', action='store_true', default=False, help='use NNTP over SSL') args = parser.parse_args() port = args.port if not args.ssl: if port == -1: port = NNTP_PORT s = NNTP(host=args.server, port=port) else: if port == -1: port = NNTP_SSL_PORT s = NNTP_SSL(host=args.server, port=port) caps = s.getcapabilities() if 'STARTTLS' in caps: s.starttls() resp, count, first, last, name = s.group(args.group) print('Group', name, 'has', count, 'articles, range', first, 'to', last) def cut(s, lim): if len(s) > lim: s = s[:lim - 4] + "..." return s first = str(int(last) - args.nb_articles + 1) resp, overviews = s.xover(first, last) for artnum, over in overviews: author = decode_header(over['from']).split('<', 1)[0] subject = decode_header(over['subject']) lines = int(over[':lines']) print("{:7} {:20} {:42} ({})".format( artnum, cut(author, 20), cut(subject, 42), lines) ) s.quit()
43,078
1,148
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/py_compile.py
"""Routine to "compile" a .py file to a .pyc file. This module has intimate knowledge of the format of .pyc files. """ import importlib._bootstrap_external import importlib.machinery import importlib.util import os import os.path import sys import traceback __all__ = ["compile", "main", "PyCompileError"] class PyCompileError(Exception): """Exception raised when an error occurs while attempting to compile the file. To raise this exception, use raise PyCompileError(exc_type,exc_value,file[,msg]) where exc_type: exception type to be used in error message type name can be accesses as class variable 'exc_type_name' exc_value: exception value to be used in error message can be accesses as class variable 'exc_value' file: name of file being compiled to be used in error message can be accesses as class variable 'file' msg: string message to be written as error message If no value is given, a default exception message will be given, consistent with 'standard' py_compile output. message (or default) can be accesses as class variable 'msg' """ def __init__(self, exc_type, exc_value, file, msg=''): exc_type_name = exc_type.__name__ if exc_type is SyntaxError: tbtext = ''.join(traceback.format_exception_only( exc_type, exc_value)) errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file) else: errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value) Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file) self.exc_type_name = exc_type_name self.exc_value = exc_value self.file = file self.msg = msg or errmsg def __str__(self): return self.msg def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1): """Byte-compile one Python source file to Python bytecode. :param file: The source file name. :param cfile: The target byte compiled file name. When not given, this defaults to the PEP 3147/PEP 488 location. :param dfile: Purported file name, i.e. the file name that shows up in error messages. Defaults to the source file name. :param doraise: Flag indicating whether or not an exception should be raised when a compile error is found. If an exception occurs and this flag is set to False, a string indicating the nature of the exception will be printed, and the function will return to the caller. If an exception occurs and this flag is set to True, a PyCompileError exception will be raised. :param optimize: The optimization level for the compiler. Valid values are -1, 0, 1 and 2. A value of -1 means to use the optimization level of the current interpreter, as given by -O command line options. :return: Path to the resulting byte compiled file. Note that it isn't necessary to byte-compile Python modules for execution efficiency -- Python itself byte-compiles a module when it is loaded, and if it can, writes out the bytecode to the corresponding .pyc file. However, if a Python installation is shared between users, it is a good idea to byte-compile all modules upon installation, since other users may not be able to write in the source directories, and thus they won't be able to write the .pyc file, and then they would be byte-compiling every module each time it is loaded. This can slow down program start-up considerably. See compileall.py for a script/module that uses this module to byte-compile all installed files (or all files in selected directories). Do note that FileExistsError is raised if cfile ends up pointing at a non-regular file or symlink. Because the compilation uses a file renaming, the resulting file would be regular and thus not the same type of file as it was previously. """ if cfile is None: if optimize >= 0: optimization = optimize if optimize >= 1 else '' cfile = importlib.util.cache_from_source(file, optimization=optimization) else: cfile = importlib.util.cache_from_source(file) if os.path.islink(cfile): msg = ('{} is a symlink and will be changed into a regular file if ' 'import writes a byte-compiled file to it') raise FileExistsError(msg.format(cfile)) elif os.path.exists(cfile) and not os.path.isfile(cfile): msg = ('{} is a non-regular file and will be changed into a regular ' 'one if import writes a byte-compiled file to it') raise FileExistsError(msg.format(cfile)) loader = importlib.machinery.SourceFileLoader('<py_compile>', file) source_bytes = loader.get_data(file) try: code = loader.source_to_code(source_bytes, dfile or file, _optimize=optimize) except Exception as err: py_exc = PyCompileError(err.__class__, err, dfile or file) if doraise: raise py_exc else: sys.stderr.write(py_exc.msg + '\n') return try: dirname = os.path.dirname(cfile) if dirname: os.makedirs(dirname) except FileExistsError: pass source_stats = loader.path_stats(file) bytecode = importlib._bootstrap_external._code_to_bytecode( code, source_stats['mtime'], source_stats['size']) mode = importlib._bootstrap_external._calc_mode(file) importlib._bootstrap_external._write_atomic(cfile, bytecode, mode) return cfile def main(args=None): """Compile several source files. The files named in 'args' (or on the command line, if 'args' is not specified) are compiled and the resulting bytecode is cached in the normal manner. This function does not search a directory structure to locate source files; it only compiles files named explicitly. If '-' is the only parameter in args, the list of files is taken from standard input. """ if args is None: args = sys.argv[1:] rv = 0 if args == ['-']: while True: filename = sys.stdin.readline() if not filename: break filename = filename.rstrip('\n') try: compile(filename, doraise=True) except PyCompileError as error: rv = 1 sys.stderr.write("%s\n" % error.msg) except OSError as error: rv = 1 sys.stderr.write("%s\n" % error) else: for filename in args: try: compile(filename, doraise=True) except PyCompileError as error: # return value to indicate at least one failure rv = 1 sys.stderr.write("%s\n" % error.msg) return rv if __name__ == "__main__": sys.exit(main())
7,181
187
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/modulefinder.py
"""Find modules used by a script, using introspection.""" import dis import importlib._bootstrap_external import importlib.machinery import marshal import os import sys import types import struct import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) import imp LOAD_CONST = dis.opmap['LOAD_CONST'] IMPORT_NAME = dis.opmap['IMPORT_NAME'] STORE_NAME = dis.opmap['STORE_NAME'] STORE_GLOBAL = dis.opmap['STORE_GLOBAL'] STORE_OPS = STORE_NAME, STORE_GLOBAL EXTENDED_ARG = dis.EXTENDED_ARG # Modulefinder does a good job at simulating Python's, but it can not # handle __path__ modifications packages make at runtime. Therefore there # is a mechanism whereby you can register extra paths in this map for a # package, and it will be honored. # Note this is a mapping is lists of paths. packagePathMap = {} # A Public interface def AddPackagePath(packagename, path): packagePathMap.setdefault(packagename, []).append(path) replacePackageMap = {} # This ReplacePackage mechanism allows modulefinder to work around # situations in which a package injects itself under the name # of another package into sys.modules at runtime by calling # ReplacePackage("real_package_name", "faked_package_name") # before running ModuleFinder. def ReplacePackage(oldname, newname): replacePackageMap[oldname] = newname class Module: def __init__(self, name, file=None, path=None): self.__name__ = name self.__file__ = file self.__path__ = path self.__code__ = None # The set of global names that are assigned to in the module. # This includes those names imported through starimports of # Python modules. self.globalnames = {} # The set of starimports this module did that could not be # resolved, ie. a starimport from a non-Python module. self.starimports = {} def __repr__(self): s = "Module(%r" % (self.__name__,) if self.__file__ is not None: s = s + ", %r" % (self.__file__,) if self.__path__ is not None: s = s + ", %r" % (self.__path__,) s = s + ")" return s class ModuleFinder: def __init__(self, path=None, debug=0, excludes=[], replace_paths=[]): if path is None: path = sys.path self.path = path self.modules = {} self.badmodules = {} self.debug = debug self.indent = 0 self.excludes = excludes self.replace_paths = replace_paths self.processed_paths = [] # Used in debugging only def msg(self, level, str, *args): if level <= self.debug: for i in range(self.indent): print(" ", end=' ') print(str, end=' ') for arg in args: print(repr(arg), end=' ') print() def msgin(self, *args): level = args[0] if level <= self.debug: self.indent = self.indent + 1 self.msg(*args) def msgout(self, *args): level = args[0] if level <= self.debug: self.indent = self.indent - 1 self.msg(*args) def run_script(self, pathname): self.msg(2, "run_script", pathname) with open(pathname) as fp: stuff = ("", "r", imp.PY_SOURCE) self.load_module('__main__', fp, pathname, stuff) def load_file(self, pathname): dir, name = os.path.split(pathname) name, ext = os.path.splitext(name) with open(pathname) as fp: stuff = (ext, "r", imp.PY_SOURCE) self.load_module(name, fp, pathname, stuff) def import_hook(self, name, caller=None, fromlist=None, level=-1): self.msg(3, "import_hook", name, caller, fromlist, level) parent = self.determine_parent(caller, level=level) q, tail = self.find_head_package(parent, name) m = self.load_tail(q, tail) if not fromlist: return q if m.__path__: self.ensure_fromlist(m, fromlist) return None def determine_parent(self, caller, level=-1): self.msgin(4, "determine_parent", caller, level) if not caller or level == 0: self.msgout(4, "determine_parent -> None") return None pname = caller.__name__ if level >= 1: # relative import if caller.__path__: level -= 1 if level == 0: parent = self.modules[pname] assert parent is caller self.msgout(4, "determine_parent ->", parent) return parent if pname.count(".") < level: raise ImportError("relative importpath too deep") pname = ".".join(pname.split(".")[:-level]) parent = self.modules[pname] self.msgout(4, "determine_parent ->", parent) return parent if caller.__path__: parent = self.modules[pname] assert caller is parent self.msgout(4, "determine_parent ->", parent) return parent if '.' in pname: i = pname.rfind('.') pname = pname[:i] parent = self.modules[pname] assert parent.__name__ == pname self.msgout(4, "determine_parent ->", parent) return parent self.msgout(4, "determine_parent -> None") return None def find_head_package(self, parent, name): self.msgin(4, "find_head_package", parent, name) if '.' in name: i = name.find('.') head = name[:i] tail = name[i+1:] else: head = name tail = "" if parent: qname = "%s.%s" % (parent.__name__, head) else: qname = head q = self.import_module(head, qname, parent) if q: self.msgout(4, "find_head_package ->", (q, tail)) return q, tail if parent: qname = head parent = None q = self.import_module(head, qname, parent) if q: self.msgout(4, "find_head_package ->", (q, tail)) return q, tail self.msgout(4, "raise ImportError: No module named", qname) raise ImportError("No module named " + qname) def load_tail(self, q, tail): self.msgin(4, "load_tail", q, tail) m = q while tail: i = tail.find('.') if i < 0: i = len(tail) head, tail = tail[:i], tail[i+1:] mname = "%s.%s" % (m.__name__, head) m = self.import_module(head, mname, m) if not m: self.msgout(4, "raise ImportError: No module named", mname) raise ImportError("No module named " + mname) self.msgout(4, "load_tail ->", m) return m def ensure_fromlist(self, m, fromlist, recursive=0): self.msg(4, "ensure_fromlist", m, fromlist, recursive) for sub in fromlist: if sub == "*": if not recursive: all = self.find_all_submodules(m) if all: self.ensure_fromlist(m, all, 1) elif not hasattr(m, sub): subname = "%s.%s" % (m.__name__, sub) submod = self.import_module(sub, subname, m) if not submod: raise ImportError("No module named " + subname) def find_all_submodules(self, m): if not m.__path__: return modules = {} # 'suffixes' used to be a list hardcoded to [".py", ".pyc"]. # But we must also collect Python extension modules - although # we cannot separate normal dlls from Python extensions. suffixes = [] suffixes += importlib.machinery.EXTENSION_SUFFIXES[:] suffixes += importlib.machinery.SOURCE_SUFFIXES[:] suffixes += importlib.machinery.BYTECODE_SUFFIXES[:] for dir in m.__path__: try: names = os.listdir(dir) except OSError: self.msg(2, "can't list directory", dir) continue for name in names: mod = None for suff in suffixes: n = len(suff) if name[-n:] == suff: mod = name[:-n] break if mod and mod != "__init__": modules[mod] = mod return modules.keys() def import_module(self, partname, fqname, parent): self.msgin(3, "import_module", partname, fqname, parent) try: m = self.modules[fqname] except KeyError: pass else: self.msgout(3, "import_module ->", m) return m if fqname in self.badmodules: self.msgout(3, "import_module -> None") return None if parent and parent.__path__ is None: self.msgout(3, "import_module -> None") return None try: fp, pathname, stuff = self.find_module(partname, parent and parent.__path__, parent) except ImportError: self.msgout(3, "import_module ->", None) return None try: m = self.load_module(fqname, fp, pathname, stuff) finally: if fp: fp.close() if parent: setattr(parent, partname, m) self.msgout(3, "import_module ->", m) return m def load_module(self, fqname, fp, pathname, file_info): suffix, mode, type = file_info self.msgin(2, "load_module", fqname, fp and "fp", pathname) if type == imp.PKG_DIRECTORY: m = self.load_package(fqname, pathname) self.msgout(2, "load_module ->", m) return m if type == imp.PY_SOURCE: co = compile(fp.read()+'\n', pathname, 'exec') elif type == imp.PY_COMPILED: try: marshal_data = importlib._bootstrap_external._validate_bytecode_header(fp.read()) except ImportError as exc: self.msgout(2, "raise ImportError: " + str(exc), pathname) raise co = marshal.loads(marshal_data) else: co = None m = self.add_module(fqname) m.__file__ = pathname if co: if self.replace_paths: co = self.replace_paths_in_code(co) m.__code__ = co self.scan_code(co, m) self.msgout(2, "load_module ->", m) return m def _add_badmodule(self, name, caller): if name not in self.badmodules: self.badmodules[name] = {} if caller: self.badmodules[name][caller.__name__] = 1 else: self.badmodules[name]["-"] = 1 def _safe_import_hook(self, name, caller, fromlist, level=-1): # wrapper for self.import_hook() that won't raise ImportError if name in self.badmodules: self._add_badmodule(name, caller) return try: self.import_hook(name, caller, level=level) except ImportError as msg: self.msg(2, "ImportError:", str(msg)) self._add_badmodule(name, caller) else: if fromlist: for sub in fromlist: if sub in self.badmodules: self._add_badmodule(sub, caller) continue try: self.import_hook(name, caller, [sub], level=level) except ImportError as msg: self.msg(2, "ImportError:", str(msg)) fullname = name + "." + sub self._add_badmodule(fullname, caller) def scan_opcodes(self, co): # Scan the code, and yield 'interesting' opcode combinations code = co.co_code names = co.co_names consts = co.co_consts opargs = [(op, arg) for _, op, arg in dis._unpack_opargs(code) if op != EXTENDED_ARG] for i, (op, oparg) in enumerate(opargs): if op in STORE_OPS: yield "store", (names[oparg],) continue if (op == IMPORT_NAME and i >= 2 and opargs[i-1][0] == opargs[i-2][0] == LOAD_CONST): level = consts[opargs[i-2][1]] fromlist = consts[opargs[i-1][1]] if level == 0: # absolute import yield "absolute_import", (fromlist, names[oparg]) else: # relative import yield "relative_import", (level, fromlist, names[oparg]) continue def scan_code(self, co, m): code = co.co_code scanner = self.scan_opcodes for what, args in scanner(co): if what == "store": name, = args m.globalnames[name] = 1 elif what == "absolute_import": fromlist, name = args have_star = 0 if fromlist is not None: if "*" in fromlist: have_star = 1 fromlist = [f for f in fromlist if f != "*"] self._safe_import_hook(name, m, fromlist, level=0) if have_star: # We've encountered an "import *". If it is a Python module, # the code has already been parsed and we can suck out the # global names. mm = None if m.__path__: # At this point we don't know whether 'name' is a # submodule of 'm' or a global module. Let's just try # the full name first. mm = self.modules.get(m.__name__ + "." + name) if mm is None: mm = self.modules.get(name) if mm is not None: m.globalnames.update(mm.globalnames) m.starimports.update(mm.starimports) if mm.__code__ is None: m.starimports[name] = 1 else: m.starimports[name] = 1 elif what == "relative_import": level, fromlist, name = args if name: self._safe_import_hook(name, m, fromlist, level=level) else: parent = self.determine_parent(m, level=level) self._safe_import_hook(parent.__name__, None, fromlist, level=0) else: # We don't expect anything else from the generator. raise RuntimeError(what) for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m) def load_package(self, fqname, pathname): self.msgin(2, "load_package", fqname, pathname) newname = replacePackageMap.get(fqname) if newname: fqname = newname m = self.add_module(fqname) m.__file__ = pathname m.__path__ = [pathname] # As per comment at top of file, simulate runtime __path__ additions. m.__path__ = m.__path__ + packagePathMap.get(fqname, []) fp, buf, stuff = self.find_module("__init__", m.__path__) try: self.load_module(fqname, fp, buf, stuff) self.msgout(2, "load_package ->", m) return m finally: if fp: fp.close() def add_module(self, fqname): if fqname in self.modules: return self.modules[fqname] self.modules[fqname] = m = Module(fqname) return m def find_module(self, name, path, parent=None): if parent is not None: # assert path is not None fullname = parent.__name__+'.'+name else: fullname = name if fullname in self.excludes: self.msgout(3, "find_module -> Excluded", fullname) raise ImportError(name) if path is None: if name in sys.builtin_module_names: return (None, None, ("", "", imp.C_BUILTIN)) path = self.path return imp.find_module(name, path) def report(self): """Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing. """ print() print(" %-25s %s" % ("Name", "File")) print(" %-25s %s" % ("----", "----")) # Print modules found keys = sorted(self.modules.keys()) for key in keys: m = self.modules[key] if m.__path__: print("P", end=' ') else: print("m", end=' ') print("%-25s" % key, m.__file__ or "") # Print missing modules missing, maybe = self.any_missing_maybe() if missing: print() print("Missing modules:") for name in missing: mods = sorted(self.badmodules[name].keys()) print("?", name, "imported from", ', '.join(mods)) # Print modules that may be missing, but then again, maybe not... if maybe: print() print("Submodules that appear to be missing, but could also be", end=' ') print("global names in the parent package:") for name in maybe: mods = sorted(self.badmodules[name].keys()) print("?", name, "imported from", ', '.join(mods)) def any_missing(self): """Return a list of modules that appear to be missing. Use any_missing_maybe() if you want to know which modules are certain to be missing, and which *may* be missing. """ missing, maybe = self.any_missing_maybe() return missing + maybe def any_missing_maybe(self): """Return two lists, one with modules that are certainly missing and one with modules that *may* be missing. The latter names could either be submodules *or* just global names in the package. The reason it can't always be determined is that it's impossible to tell which names are imported when "from module import *" is done with an extension module, short of actually importing it. """ missing = [] maybe = [] for name in self.badmodules: if name in self.excludes: continue i = name.rfind(".") if i < 0: missing.append(name) continue subname = name[i+1:] pkgname = name[:i] pkg = self.modules.get(pkgname) if pkg is not None: if pkgname in self.badmodules[name]: # The package tried to import this module itself and # failed. It's definitely missing. missing.append(name) elif subname in pkg.globalnames: # It's a global in the package: definitely not missing. pass elif pkg.starimports: # It could be missing, but the package did an "import *" # from a non-Python module, so we simply can't be sure. maybe.append(name) else: # It's not a global in the package, the package didn't # do funny star imports, it's very likely to be missing. # The symbol could be inserted into the package from the # outside, but since that's not good style we simply list # it missing. missing.append(name) else: missing.append(name) missing.sort() maybe.sort() return missing, maybe def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f, r in self.replace_paths: if original_filename.startswith(f): new_filename = r + original_filename[len(f):] break if self.debug and original_filename not in self.processed_paths: if new_filename != original_filename: self.msgout(2, "co_filename %r changed to %r" \ % (original_filename,new_filename,)) else: self.msgout(2, "co_filename %r remains unchanged" \ % (original_filename,)) self.processed_paths.append(original_filename) consts = list(co.co_consts) for i in range(len(consts)): if isinstance(consts[i], type(co)): consts[i] = self.replace_paths_in_code(consts[i]) return types.CodeType(co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, tuple(consts), co.co_names, co.co_varnames, new_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars) def test(): # Parse command line import getopt try: opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") except getopt.error as msg: print(msg) return # Process options debug = 1 domods = 0 addpath = [] exclude = [] for o, a in opts: if o == '-d': debug = debug + 1 if o == '-m': domods = 1 if o == '-p': addpath = addpath + a.split(os.pathsep) if o == '-q': debug = 0 if o == '-x': exclude.append(a) # Provide default arguments if not args: script = "hello.py" else: script = args[0] # Set the path based on sys.path and the script directory path = sys.path[:] path[0] = os.path.dirname(script) path = addpath + path if debug > 1: print("path:") for item in path: print(" ", repr(item)) # Create the module finder and turn its crank mf = ModuleFinder(path, debug, exclude) for arg in args[1:]: if arg == '-m': domods = 1 continue if domods: if arg[-2:] == '.*': mf.import_hook(arg[:-2], None, ["*"]) else: mf.import_hook(arg) else: mf.load_file(arg) mf.run_script(script) mf.report() return mf # for -i debugging if __name__ == '__main__': try: mf = test() except KeyboardInterrupt: print("\n[interrupted]")
23,027
634
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/sysconfig.py
"""Access to Python's configuration information.""" import os import sys from os.path import pardir, realpath import _sysconfigdata_m_cosmo_x86_64_cosmo __all__ = [ 'get_config_h_filename', 'get_config_var', 'get_config_vars', 'get_makefile_filename', 'get_path', 'get_path_names', 'get_paths', 'get_platform', 'get_python_version', 'get_scheme_names', 'parse_config_h', ] _INSTALL_SCHEMES = { 'posix_prefix': { 'stdlib': '{installed_base}/lib/python{py_version_short}', 'platstdlib': '{platbase}/lib/python{py_version_short}', 'purelib': '{base}/lib/python{py_version_short}/site-packages', 'platlib': '{platbase}/lib/python{py_version_short}/site-packages', 'include': '{installed_base}/include/python{py_version_short}{abiflags}', 'platinclude': '{installed_platbase}/include/python{py_version_short}{abiflags}', 'scripts': '{base}/bin', 'data': '{base}', }, 'posix_home': { 'stdlib': '{installed_base}/lib/python', 'platstdlib': '{base}/lib/python', 'purelib': '{base}/lib/python', 'platlib': '{base}/lib/python', 'include': '{installed_base}/include/python', 'platinclude': '{installed_base}/include/python', 'scripts': '{base}/bin', 'data': '{base}', }, 'nt': { 'stdlib': '{installed_base}/Lib', 'platstdlib': '{base}/Lib', 'purelib': '{base}/Lib/site-packages', 'platlib': '{base}/Lib/site-packages', 'include': '{installed_base}/Include', 'platinclude': '{installed_base}/Include', 'scripts': '{base}/Scripts', 'data': '{base}', }, 'nt_user': { 'stdlib': '{userbase}/Python{py_version_nodot}', 'platstdlib': '{userbase}/Python{py_version_nodot}', 'purelib': '{userbase}/Python{py_version_nodot}/site-packages', 'platlib': '{userbase}/Python{py_version_nodot}/site-packages', 'include': '{userbase}/Python{py_version_nodot}/Include', 'scripts': '{userbase}/Python{py_version_nodot}/Scripts', 'data': '{userbase}', }, 'posix_user': { 'stdlib': '{userbase}/lib/python{py_version_short}', 'platstdlib': '{userbase}/lib/python{py_version_short}', 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data': '{userbase}', }, 'osx_framework_user': { 'stdlib': '{userbase}/lib/python', 'platstdlib': '{userbase}/lib/python', 'purelib': '{userbase}/lib/python/site-packages', 'platlib': '{userbase}/lib/python/site-packages', 'include': '{userbase}/include', 'scripts': '{userbase}/bin', 'data': '{userbase}', }, } _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include', 'scripts', 'data') # FIXME don't rely on sys.version here, its format is an implementation detail # of CPython, use sys.version_info or sys.hexversion _PY_VERSION = sys.version.split()[0] _PY_VERSION_SHORT = '%d.%d' % sys.version_info[:2] _PY_VERSION_SHORT_NO_DOT = '%d%d' % sys.version_info[:2] _PREFIX = os.path.normpath(sys.prefix) _BASE_PREFIX = os.path.normpath(sys.base_prefix) _EXEC_PREFIX = os.path.normpath(sys.exec_prefix) _BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix) _CONFIG_VARS = None _USER_BASE = None def _safe_realpath(path): try: return realpath(path) except OSError: return path if sys.executable: _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable)) else: # sys.executable can be empty if argv[0] has been changed and Python is # unable to retrieve the real program name _PROJECT_BASE = _safe_realpath(os.getcwd()) if (os.name == 'nt' and _PROJECT_BASE.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) # set for cross builds if "_PYTHON_PROJECT_BASE" in os.environ: _PROJECT_BASE = _safe_realpath(os.environ["_PYTHON_PROJECT_BASE"]) def _is_python_source_dir(d): for fn in ("Setup.dist", "Setup.local"): if os.path.isfile(os.path.join(d, "Modules", fn)): return True return False _sys_home = getattr(sys, '_home', None) if (_sys_home and os.name == 'nt' and _sys_home.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))): _sys_home = os.path.dirname(os.path.dirname(_sys_home)) def is_python_build(check_home=False): if check_home and _sys_home: return _is_python_source_dir(_sys_home) return _is_python_source_dir(_PROJECT_BASE) _PYTHON_BUILD = is_python_build(True) if _PYTHON_BUILD: for scheme in ('posix_prefix', 'posix_home'): _INSTALL_SCHEMES[scheme]['include'] = '{srcdir}/Include' _INSTALL_SCHEMES[scheme]['platinclude'] = '{projectbase}/.' def _subst_vars(s, local_vars): try: return s.format(**local_vars) except KeyError: try: return s.format(**os.environ) except KeyError as var: raise AttributeError('{%s}' % var) def _extend_dict(target_dict, other_dict): target_keys = target_dict.keys() for key, value in other_dict.items(): if key in target_keys: continue target_dict[key] = value def _expand_vars(scheme, vars): res = {} if vars is None: vars = {} _extend_dict(vars, get_config_vars()) for key, value in _INSTALL_SCHEMES[scheme].items(): if os.name in ('posix', 'nt'): value = os.path.expanduser(value) res[key] = os.path.normpath(_subst_vars(value, vars)) return res def _get_default_scheme(): if os.name == 'posix': # the default scheme for posix is posix_prefix return 'posix_prefix' return os.name def _getuserbase(): env_base = os.environ.get("PYTHONUSERBASE", None) def joinuser(*args): return os.path.expanduser(os.path.join(*args)) if os.name == "nt": base = os.environ.get("APPDATA") or "~" if env_base: return env_base else: return joinuser(base, "Python") if sys.platform == "darwin": framework = get_config_var("PYTHONFRAMEWORK") if framework: if env_base: return env_base else: return joinuser("~", "Library", framework, "%d.%d" % sys.version_info[:2]) if env_base: return env_base else: return joinuser("~", ".local") def _parse_makefile(filename, vars=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ # Regexes needed for parsing Makefile (and similar syntaxes, # like old-style Setup files). import re _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)") _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") if vars is None: vars = {} done = {} notdone = {} with open(filename, errors="surrogateescape") as f: lines = f.readlines() for line in lines: if line.startswith('#') or line.strip() == '': continue m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = v.strip() # `$$' is a literal `$' in make tmpv = v.replace('$$', '') if "$" in tmpv: notdone[n] = v else: try: v = int(v) except ValueError: # insert literal `$' done[n] = v.replace('$$', '$') else: done[n] = v # do variable interpolation here variables = list(notdone.keys()) # Variables with a 'PY_' prefix in the makefile. These need to # be made available without that prefix through sysconfig. # Special care is needed to ensure that variable expansion works, even # if the expansion uses the name without a prefix. renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') while len(variables) > 0: for name in tuple(variables): value = notdone[name] m1 = _findvar1_rx.search(value) m2 = _findvar2_rx.search(value) if m1 and m2: m = m1 if m1.start() < m2.start() else m2 else: m = m1 if m1 else m2 if m is not None: n = m.group(1) found = True if n in done: item = str(done[n]) elif n in notdone: # get it on a subsequent round found = False elif n in os.environ: # do it like make: fall back to environment item = os.environ[n] elif n in renamed_variables: if (name.startswith('PY_') and name[3:] in renamed_variables): item = "" elif 'PY_' + n in notdone: found = False else: item = str(done['PY_' + n]) else: done[n] = item = "" if found: after = value[m.end():] value = value[:m.start()] + item + after if "$" in after: notdone[name] = value else: try: value = int(value) except ValueError: done[name] = value.strip() else: done[name] = value variables.remove(name) if name.startswith('PY_') \ and name[3:] in renamed_variables: name = name[3:] if name not in done: done[name] = value else: # bogus variable reference (e.g. "prefix=$/opt/python"); # just drop it since we can't deal done[name] = value variables.remove(name) # strip spurious spaces for k, v in done.items(): if isinstance(v, str): done[k] = v.strip() # save the results in the global dictionary vars.update(done) return vars def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_sys_home or _PROJECT_BASE, "Makefile") if hasattr(sys, 'abiflags'): config_dir_name = 'config_%s%s' % (_PY_VERSION_SHORT, sys.abiflags) else: config_dir_name = 'config' if hasattr(sys.implementation, '_multiarch'): config_dir_name += '_%s' % sys.implementation._multiarch return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile') def _get_sysconfigdata_name(): return '_sysconfigdata_m_cosmo_x86_64_cosmo' return os.environ.get('_PYTHON_SYSCONFIGDATA_NAME', '_sysconfigdata_{abi}_{platform}_{multiarch}'.format( abi=sys.abiflags, platform=sys.platform, multiarch=getattr(sys.implementation, '_multiarch', ''), )) def _generate_posix_vars(): """Generate the Python module containing build-time variables.""" import pprint vars = {} # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except OSError as e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise OSError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except OSError as e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise OSError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['BLDSHARED'] = vars['LDSHARED'] # There's a chicken-and-egg situation on OS X with regards to the # _sysconfigdata module after the changes introduced by #15298: # get_config_vars() is called by get_platform() as part of the # `make pybuilddir.txt` target -- which is a precursor to the # _sysconfigdata.py module being constructed. Unfortunately, # get_config_vars() eventually calls _init_posix(), which attempts # to import _sysconfigdata, which we won't have built yet. In order # for _init_posix() to work, if we're on Darwin, just mock up the # _sysconfigdata module manually and populate it with the build vars. # This is more than sufficient for ensuring the subsequent call to # get_platform() succeeds. name = _get_sysconfigdata_name() if 'darwin' in sys.platform: import types module = types.ModuleType(name) module.build_time_vars = vars sys.modules[name] = module pybuilddir = 'build/lib.%s-%s' % (get_platform(), _PY_VERSION_SHORT) if hasattr(sys, "gettotalrefcount"): pybuilddir += '-pydebug' os.makedirs(pybuilddir, exist_ok=True) destfile = os.path.join(pybuilddir, name + '.py') with open(destfile, 'w', encoding='utf8') as f: f.write('# system configuration generated and used by' ' the sysconfig module\n') f.write('build_time_vars = ') pprint.pprint(vars, stream=f) # Create file used for sys.path fixup -- see Modules/getpath.c with open('pybuilddir.txt', 'w', encoding='ascii') as f: f.write(pybuilddir) def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # _sysconfigdata is generated at build time, see _generate_posix_vars() name = _get_sysconfigdata_name() _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0) build_time_vars = _temp.build_time_vars vars.update(build_time_vars) def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['EXT_SUFFIX'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable)) # # public APIs # def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} import re define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars def get_config_h_filename(): """Return the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_sys_home or _PROJECT_BASE, "PC") else: inc_dir = _sys_home or _PROJECT_BASE else: inc_dir = get_path('platinclude') return os.path.join(inc_dir, 'pyconfig.h') def get_scheme_names(): """Return a tuple containing the schemes names.""" return tuple(sorted(_INSTALL_SCHEMES)) def get_path_names(): """Return a tuple containing the paths names.""" return _SCHEME_KEYS def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ if expand: return _expand_vars(scheme, vars) else: return _INSTALL_SCHEMES[scheme] def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name] def get_config_vars(*args): """With no arguments, return a dictionary of all configuration variables relevant for the current platform. On Unix, this means every variable defined in Python's installed Makefile; On Windows it's a much smaller set. With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary. """ global _CONFIG_VARS if _CONFIG_VARS is None: _CONFIG_VARS = {} # Normalized versions of prefix and exec_prefix are handy to have; # in fact, these are the standard versions used most places in the # Distutils. _CONFIG_VARS['prefix'] = _PREFIX _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX _CONFIG_VARS['py_version'] = _PY_VERSION _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT _CONFIG_VARS['py_version_nodot'] = _PY_VERSION_SHORT_NO_DOT _CONFIG_VARS['installed_base'] = _BASE_PREFIX _CONFIG_VARS['base'] = _PREFIX _CONFIG_VARS['installed_platbase'] = _BASE_EXEC_PREFIX _CONFIG_VARS['platbase'] = _EXEC_PREFIX _CONFIG_VARS['projectbase'] = _PROJECT_BASE try: _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: # sys.abiflags may not be defined on all platforms. _CONFIG_VARS['abiflags'] = '' if os.name == 'nt': _init_non_posix(_CONFIG_VARS) if os.name == 'posix': _init_posix(_CONFIG_VARS) # For backward compatibility, see issue19555 SO = _CONFIG_VARS.get('EXT_SUFFIX') if SO is not None: _CONFIG_VARS['SO'] = SO # Setting 'userbase' is done below the call to the # init function to enable using 'get_config_var' in # the init-function. _CONFIG_VARS['userbase'] = _getuserbase() # Always convert srcdir to an absolute path srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE) if os.name == 'posix': if _PYTHON_BUILD: # If srcdir is a relative path (typically '.' or '..') # then it should be interpreted relative to the directory # containing Makefile. base = os.path.dirname(get_makefile_filename()) srcdir = os.path.join(base, srcdir) else: # srcdir is not meaningful since the installation is # spread about the filesystem. We choose the # directory containing the Makefile since we know it # exists. srcdir = os.path.dirname(get_makefile_filename()) _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir) # OS X platforms require special customization to handle # multi-architecture, multi-os-version installers if sys.platform == 'darwin': # import _osx_support _osx_support.customize_config_vars(_CONFIG_VARS) if args: vals = [] for name in args: vals.append(_CONFIG_VARS.get(name)) return vals else: return _CONFIG_VARS def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ if name == 'SO': import warnings warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2) return get_config_vars().get(name) def get_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'. """ if os.name == 'nt': # sniff sys.version for architecture. prefix = " bit (" i = sys.version.find(prefix) if i == -1: return sys.platform j = sys.version.find(")", i) look = sys.version[i+len(prefix):j].lower() if look == 'amd64': return 'win-amd64' if look == 'itanium': return 'win-ia64' return sys.platform if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha return sys.platform # Set for cross builds explicitly if "_PYTHON_HOST_PLATFORM" in os.environ: return os.environ["_PYTHON_HOST_PLATFORM"] # Try to distinguish various flavours of Unix osname, host, release, version, machine = os.uname() # Convert the OS name to lowercase, remove '/' characters # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") osname = osname.lower().replace('/', '') machine = machine.replace(' ', '_') machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # We can't use "platform.architecture()[0]" because a # bootstrap problem. We use a dict to get an error # if some suspicious happens. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} machine += ".%s" % bitness[sys.maxsize] # fall through to standard osname-release-machine representation elif osname[:4] == "irix": # could be "irix64"! return "%s-%s" % (osname, release) elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" import re rel_re = re.compile(r'[\d.]+') m = rel_re.match(release) if m: release = m.group() elif osname[:6] == "darwin": # import _osx_support osname, release, machine = _osx_support.get_platform_osx( get_config_vars(), osname, release, machine) return "%s-%s-%s" % (osname, release, machine) def get_python_version(): return _PY_VERSION_SHORT def _print_dict(title, data): for index, (key, value) in enumerate(sorted(data.items())): if index == 0: print('%s: ' % (title)) print('\t%s = "%s"' % (key, value)) def _main(): """Display all information sysconfig detains.""" if '--generate-posix-vars' in sys.argv: _generate_posix_vars() return print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', get_paths()) print() _print_dict('Variables', get_config_vars()) if __name__ == '__main__': _main()
24,957
724
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/binhex.py
"""Macintosh binhex compression/decompression. easy interface: binhex(inputfilename, outputfilename) hexbin(inputfilename, outputfilename) """ # # Jack Jansen, CWI, August 1995. # # The module is supposed to be as compatible as possible. Especially the # easy interface should work "as expected" on any platform. # XXXX Note: currently, textfiles appear in mac-form on all platforms. # We seem to lack a simple character-translate in python. # (we should probably use ISO-Latin-1 on all but the mac platform). # XXXX The simple routines are too simple: they expect to hold the complete # files in-core. Should be fixed. # XXXX It would be nice to handle AppleDouble format on unix # (for servers serving macs). # XXXX I don't understand what happens when you get 0x90 times the same byte on # input. The resulting code (xx 90 90) would appear to be interpreted as an # escaped *value* of 0x90. All coders I've seen appear to ignore this nicety... # import io import os import struct import binascii __all__ = ["binhex","hexbin","Error"] class Error(Exception): pass # States (what have we written) _DID_HEADER = 0 _DID_DATA = 1 # Various constants REASONABLY_LARGE = 32768 # Minimal amount we pass the rle-coder LINELEN = 64 RUNCHAR = b"\x90" # # This code is no longer byte-order dependent class FInfo: def __init__(self): self.Type = '????' self.Creator = '????' self.Flags = 0 def getfileinfo(name): finfo = FInfo() with io.open(name, 'rb') as fp: # Quick check for textfile data = fp.read(512) if 0 not in data: finfo.Type = 'TEXT' fp.seek(0, 2) dsize = fp.tell() dir, file = os.path.split(name) file = file.replace(':', '-', 1) return file, finfo, dsize, 0 class openrsrc: def __init__(self, *args): pass def read(self, *args): return b'' def write(self, *args): pass def close(self): pass class _Hqxcoderengine: """Write data to the coder in 3-byte chunks""" def __init__(self, ofp): self.ofp = ofp self.data = b'' self.hqxdata = b'' self.linelen = LINELEN - 1 def write(self, data): self.data = self.data + data datalen = len(self.data) todo = (datalen // 3) * 3 data = self.data[:todo] self.data = self.data[todo:] if not data: return self.hqxdata = self.hqxdata + binascii.b2a_hqx(data) self._flush(0) def _flush(self, force): first = 0 while first <= len(self.hqxdata) - self.linelen: last = first + self.linelen self.ofp.write(self.hqxdata[first:last] + b'\n') self.linelen = LINELEN first = last self.hqxdata = self.hqxdata[first:] if force: self.ofp.write(self.hqxdata + b':\n') def close(self): if self.data: self.hqxdata = self.hqxdata + binascii.b2a_hqx(self.data) self._flush(1) self.ofp.close() del self.ofp class _Rlecoderengine: """Write data to the RLE-coder in suitably large chunks""" def __init__(self, ofp): self.ofp = ofp self.data = b'' def write(self, data): self.data = self.data + data if len(self.data) < REASONABLY_LARGE: return rledata = binascii.rlecode_hqx(self.data) self.ofp.write(rledata) self.data = b'' def close(self): if self.data: rledata = binascii.rlecode_hqx(self.data) self.ofp.write(rledata) self.ofp.close() del self.ofp class BinHex: def __init__(self, name_finfo_dlen_rlen, ofp): name, finfo, dlen, rlen = name_finfo_dlen_rlen close_on_error = False if isinstance(ofp, str): ofname = ofp ofp = io.open(ofname, 'wb') close_on_error = True try: ofp.write(b'(This file must be converted with BinHex 4.0)\r\r:') hqxer = _Hqxcoderengine(ofp) self.ofp = _Rlecoderengine(hqxer) self.crc = 0 if finfo is None: finfo = FInfo() self.dlen = dlen self.rlen = rlen self._writeinfo(name, finfo) self.state = _DID_HEADER except: if close_on_error: ofp.close() raise def _writeinfo(self, name, finfo): nl = len(name) if nl > 63: raise Error('Filename too long') d = bytes([nl]) + name.encode("latin-1") + b'\0' tp, cr = finfo.Type, finfo.Creator if isinstance(tp, str): tp = tp.encode("latin-1") if isinstance(cr, str): cr = cr.encode("latin-1") d2 = tp + cr # Force all structs to be packed with big-endian d3 = struct.pack('>h', finfo.Flags) d4 = struct.pack('>ii', self.dlen, self.rlen) info = d + d2 + d3 + d4 self._write(info) self._writecrc() def _write(self, data): self.crc = binascii.crc_hqx(data, self.crc) self.ofp.write(data) def _writecrc(self): # XXXX Should this be here?? # self.crc = binascii.crc_hqx('\0\0', self.crc) if self.crc < 0: fmt = '>h' else: fmt = '>H' self.ofp.write(struct.pack(fmt, self.crc)) self.crc = 0 def write(self, data): if self.state != _DID_HEADER: raise Error('Writing data at the wrong time') self.dlen = self.dlen - len(data) self._write(data) def close_data(self): if self.dlen != 0: raise Error('Incorrect data size, diff=%r' % (self.rlen,)) self._writecrc() self.state = _DID_DATA def write_rsrc(self, data): if self.state < _DID_DATA: self.close_data() if self.state != _DID_DATA: raise Error('Writing resource data at the wrong time') self.rlen = self.rlen - len(data) self._write(data) def close(self): if self.state is None: return try: if self.state < _DID_DATA: self.close_data() if self.state != _DID_DATA: raise Error('Close at the wrong time') if self.rlen != 0: raise Error("Incorrect resource-datasize, diff=%r" % (self.rlen,)) self._writecrc() finally: self.state = None ofp = self.ofp del self.ofp ofp.close() def binhex(inp, out): """binhex(infilename, outfilename): create binhex-encoded copy of a file""" finfo = getfileinfo(inp) ofp = BinHex(finfo, out) with io.open(inp, 'rb') as ifp: # XXXX Do textfile translation on non-mac systems while True: d = ifp.read(128000) if not d: break ofp.write(d) ofp.close_data() ifp = openrsrc(inp, 'rb') while True: d = ifp.read(128000) if not d: break ofp.write_rsrc(d) ofp.close() ifp.close() class _Hqxdecoderengine: """Read data via the decoder in 4-byte chunks""" def __init__(self, ifp): self.ifp = ifp self.eof = 0 def read(self, totalwtd): """Read at least wtd bytes (or until EOF)""" decdata = b'' wtd = totalwtd # # The loop here is convoluted, since we don't really now how # much to decode: there may be newlines in the incoming data. while wtd > 0: if self.eof: return decdata wtd = ((wtd + 2) // 3) * 4 data = self.ifp.read(wtd) # # Next problem: there may not be a complete number of # bytes in what we pass to a2b. Solve by yet another # loop. # while True: try: decdatacur, self.eof = binascii.a2b_hqx(data) break except binascii.Incomplete: pass newdata = self.ifp.read(1) if not newdata: raise Error('Premature EOF on binhex file') data = data + newdata decdata = decdata + decdatacur wtd = totalwtd - len(decdata) if not decdata and not self.eof: raise Error('Premature EOF on binhex file') return decdata def close(self): self.ifp.close() class _Rledecoderengine: """Read data via the RLE-coder""" def __init__(self, ifp): self.ifp = ifp self.pre_buffer = b'' self.post_buffer = b'' self.eof = 0 def read(self, wtd): if wtd > len(self.post_buffer): self._fill(wtd - len(self.post_buffer)) rv = self.post_buffer[:wtd] self.post_buffer = self.post_buffer[wtd:] return rv def _fill(self, wtd): self.pre_buffer = self.pre_buffer + self.ifp.read(wtd + 4) if self.ifp.eof: self.post_buffer = self.post_buffer + \ binascii.rledecode_hqx(self.pre_buffer) self.pre_buffer = b'' return # # Obfuscated code ahead. We have to take care that we don't # end up with an orphaned RUNCHAR later on. So, we keep a couple # of bytes in the buffer, depending on what the end of # the buffer looks like: # '\220\0\220' - Keep 3 bytes: repeated \220 (escaped as \220\0) # '?\220' - Keep 2 bytes: repeated something-else # '\220\0' - Escaped \220: Keep 2 bytes. # '?\220?' - Complete repeat sequence: decode all # otherwise: keep 1 byte. # mark = len(self.pre_buffer) if self.pre_buffer[-3:] == RUNCHAR + b'\0' + RUNCHAR: mark = mark - 3 elif self.pre_buffer[-1:] == RUNCHAR: mark = mark - 2 elif self.pre_buffer[-2:] == RUNCHAR + b'\0': mark = mark - 2 elif self.pre_buffer[-2:-1] == RUNCHAR: pass # Decode all else: mark = mark - 1 self.post_buffer = self.post_buffer + \ binascii.rledecode_hqx(self.pre_buffer[:mark]) self.pre_buffer = self.pre_buffer[mark:] def close(self): self.ifp.close() class HexBin: def __init__(self, ifp): if isinstance(ifp, str): ifp = io.open(ifp, 'rb') # # Find initial colon. # while True: ch = ifp.read(1) if not ch: raise Error("No binhex data found") # Cater for \r\n terminated lines (which show up as \n\r, hence # all lines start with \r) if ch == b'\r': continue if ch == b':': break hqxifp = _Hqxdecoderengine(ifp) self.ifp = _Rledecoderengine(hqxifp) self.crc = 0 self._readheader() def _read(self, len): data = self.ifp.read(len) self.crc = binascii.crc_hqx(data, self.crc) return data def _checkcrc(self): filecrc = struct.unpack('>h', self.ifp.read(2))[0] & 0xffff #self.crc = binascii.crc_hqx('\0\0', self.crc) # XXXX Is this needed?? self.crc = self.crc & 0xffff if filecrc != self.crc: raise Error('CRC error, computed %x, read %x' % (self.crc, filecrc)) self.crc = 0 def _readheader(self): len = self._read(1) fname = self._read(ord(len)) rest = self._read(1 + 4 + 4 + 2 + 4 + 4) self._checkcrc() type = rest[1:5] creator = rest[5:9] flags = struct.unpack('>h', rest[9:11])[0] self.dlen = struct.unpack('>l', rest[11:15])[0] self.rlen = struct.unpack('>l', rest[15:19])[0] self.FName = fname self.FInfo = FInfo() self.FInfo.Creator = creator self.FInfo.Type = type self.FInfo.Flags = flags self.state = _DID_HEADER def read(self, *n): if self.state != _DID_HEADER: raise Error('Read data at wrong time') if n: n = n[0] n = min(n, self.dlen) else: n = self.dlen rv = b'' while len(rv) < n: rv = rv + self._read(n-len(rv)) self.dlen = self.dlen - n return rv def close_data(self): if self.state != _DID_HEADER: raise Error('close_data at wrong time') if self.dlen: dummy = self._read(self.dlen) self._checkcrc() self.state = _DID_DATA def read_rsrc(self, *n): if self.state == _DID_HEADER: self.close_data() if self.state != _DID_DATA: raise Error('Read resource data at wrong time') if n: n = n[0] n = min(n, self.rlen) else: n = self.rlen self.rlen = self.rlen - n return self._read(n) def close(self): if self.state is None: return try: if self.rlen: dummy = self.read_rsrc(self.rlen) self._checkcrc() finally: self.state = None self.ifp.close() def hexbin(inp, out): """hexbin(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName with io.open(out, 'wb') as ofp: # XXXX Do translation on non-mac systems while True: d = ifp.read(128000) if not d: break ofp.write(d) ifp.close_data() d = ifp.read_rsrc(128000) if d: ofp = openrsrc(out, 'wb') ofp.write(d) while True: d = ifp.read_rsrc(128000) if not d: break ofp.write(d) ofp.close() ifp.close()
13,954
480
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/site.py
"""Append module search paths for third-party packages to sys.path. **************************************************************** * This module is automatically imported during initialization. * **************************************************************** This will append site-specific paths to the module search path. On Unix (including Mac OSX), it starts with sys.prefix and sys.exec_prefix (if different) and appends lib/python<version>/site-packages. On other platforms (such as Windows), it tries each of the prefixes directly, as well as with lib/site-packages appended. The resulting directories, if they exist, are appended to sys.path, and also inspected for path configuration files. If a file named "pyvenv.cfg" exists one directory above sys.executable, sys.prefix and sys.exec_prefix are set to that directory and it is also checked for site-packages (sys.base_prefix and sys.base_exec_prefix will always be the "real" prefixes of the Python installation). If "pyvenv.cfg" (a bootstrap configuration file) contains the key "include-system-site-packages" set to anything other than "false" (case-insensitive), the system-level prefixes will still also be searched for site-packages; otherwise they won't. All of the resulting site-specific directories, if they exist, are appended to sys.path, and also inspected for path configuration files. A path configuration file is a file whose name has the form <package>.pth; its contents are additional directories (one per line) to be added to sys.path. Non-existing directories (or non-directories) are never added to sys.path; no directory is added to sys.path more than once. Blank lines and lines beginning with '#' are skipped. Lines starting with 'import' are executed. For example, suppose sys.prefix and sys.exec_prefix are set to /usr/local and there is a directory /usr/local/lib/python2.5/site-packages with three subdirectories, foo, bar and spam, and two path configuration files, foo.pth and bar.pth. Assume foo.pth contains the following: # foo package configuration foo bar bletch and bar.pth contains: # bar package configuration bar Then the following directories are added to sys.path, in this order: /usr/local/lib/python2.5/site-packages/bar /usr/local/lib/python2.5/site-packages/foo Note that bletch is omitted because it doesn't exist; bar precedes foo because bar.pth comes alphabetically before foo.pth; and spam is omitted because it is not mentioned in either path configuration file. The readline module is also automatically configured to enable completion for systems that support it. This can be overridden in sitecustomize, usercustomize or PYTHONSTARTUP. Starting Python in isolated mode (-I) disables automatic readline configuration. After these operations, an attempt is made to import a module named sitecustomize, which can perform arbitrary additional site-specific customizations. If this import fails with an ImportError exception, it is silently ignored. """ import sys import os import builtins import _sitebuiltins # Prefixes for site-packages; add additional prefixes like /usr/local here PREFIXES = [sys.prefix, sys.exec_prefix] # Enable per user site-packages directory # set it to False to disable the feature or True to force the feature ENABLE_USER_SITE = None # for distutils.commands.install # These values are initialized by the getuserbase() and getusersitepackages() # functions, through the main() function when Python starts. USER_SITE = None USER_BASE = None def makepath(*paths): dir = os.path.join(*paths) try: dir = os.path.abspath(dir) except OSError: pass return dir, os.path.normcase(dir) def abs_paths(): """Set all module __file__ and __cached__ attributes to an absolute path""" for m in set(sys.modules.values()): if (getattr(getattr(m, '__loader__', None), '__module__', None) not in ('_frozen_importlib', '_frozen_importlib_external')): continue # don't mess with a PEP 302-supplied __file__ try: m.__file__ = os.path.abspath(m.__file__) except (AttributeError, OSError, TypeError): pass try: m.__cached__ = os.path.abspath(m.__cached__) except (AttributeError, OSError, TypeError): pass def removeduppaths(): """ Remove duplicate entries from sys.path along with making them absolute""" # This ensures that the initial path provided by the interpreter contains # only absolute pathnames, even if we're running from the build directory. L = [] known_paths = set() for dir in sys.path: # Filter out duplicate paths (on case-insensitive file systems also # if they only differ in case); turn relative paths into absolute # paths. dir, dircase = makepath(dir) if not dircase in known_paths: L.append(dir) known_paths.add(dircase) sys.path[:] = L return known_paths def _init_pathinfo(): """Return a set containing all existing file system items from sys.path.""" d = set() for item in sys.path: try: if os.path.exists(item): _, itemcase = makepath(item) d.add(itemcase) except TypeError: continue return d def addpackage(sitedir, name, known_paths): """Process a .pth file within the site-packages directory: For each line in the file, either combine it with sitedir to a path and add that to known_paths, or execute it if it starts with 'import '. """ if known_paths is None: known_paths = _init_pathinfo() reset = True else: reset = False fullname = os.path.join(sitedir, name) try: f = open(fullname, "r") except OSError: return with f: for n, line in enumerate(f): if line.startswith("#"): continue try: if line.startswith(("import ", "import\t")): exec(line) continue line = line.rstrip() dir, dircase = makepath(sitedir, line) if not dircase in known_paths and os.path.exists(dir): sys.path.append(dir) known_paths.add(dircase) except Exception: print("Error processing line {:d} of {}:\n".format(n+1, fullname), file=sys.stderr) import traceback for record in traceback.format_exception(*sys.exc_info()): for line in record.splitlines(): print(' '+line, file=sys.stderr) print("\nRemainder of file ignored", file=sys.stderr) break if reset: known_paths = None return known_paths def addsitedir(sitedir, known_paths=None): """Add 'sitedir' argument to sys.path if missing and handle .pth files in 'sitedir'""" if known_paths is None: known_paths = _init_pathinfo() reset = True else: reset = False sitedir, sitedircase = makepath(sitedir) if not sitedircase in known_paths: sys.path.append(sitedir) # Add path component known_paths.add(sitedircase) try: names = os.listdir(sitedir) except OSError: return names = [name for name in names if name.endswith(".pth")] for name in sorted(names): addpackage(sitedir, name, known_paths) if reset: known_paths = None return known_paths def check_enableusersite(): """Check if user site directory is safe for inclusion The function tests for the command line flag (including environment var), process uid/gid equal to effective uid/gid. None: Disabled for security reasons False: Disabled by user (command line option) True: Safe and enabled """ if sys.flags.no_user_site: return False if hasattr(os, "getuid") and hasattr(os, "geteuid"): # check process uid == effective uid if os.geteuid() != os.getuid(): return None if hasattr(os, "getgid") and hasattr(os, "getegid"): # check process gid == effective gid if os.getegid() != os.getgid(): return None return True def _getuserbase(): env_base = os.environ.get("PYTHONUSERBASE", None) def joinuser(*args): return os.path.expanduser(os.path.join(*args)) if os.realname == "nt": base = os.environ.get("APPDATA") or "~" if env_base: return env_base else: return joinuser(base, "Python") if sys.platform == "darwin": from sysconfig import get_config_var framework = get_config_var("PYTHONFRAMEWORK") if framework: if env_base: return env_base else: return joinuser("~", "Library", framework, "%d.%d" % sys.version_info[:2]) if env_base: return env_base else: return joinuser("~", ".local") def getuserbase(): """Returns the `user base` directory path. The `user base` directory can be used to store data. If the global variable ``USER_BASE`` is not initialized yet, this function will also set it. """ global USER_BASE if USER_BASE is not None: return USER_BASE USER_BASE = _getuserbase() return USER_BASE def getusersitepackages(): """Returns the user-specific site-packages directory path. If the global variable ``USER_SITE`` is not initialized yet, this function will also set it. """ global USER_SITE if USER_SITE is not None: return USER_SITE if sys.platform == 'darwin': from sysconfig import get_config_var, get_path if get_config_var('PYTHONFRAMEWORK'): USER_SITE = get_path('purelib', 'osx_framework_user') return USER_SITE user_base = getuserbase() # this will also set USER_BASE purelib_map = { "posix_user":'{userbase}/lib/python3.6/site-packages', "nt_user": "{userbase}/Python36/site-packages", } USER_SITE = purelib_map.get('%s_user' % os.realname).format(userbase=user_base) return USER_SITE def addusersitepackages(known_paths): """Add a per user site-package to sys.path Each user has its own python directory with site-packages in the home directory. """ # get the per user site-package path # this call will also make sure USER_BASE and USER_SITE are set user_site = getusersitepackages() if ENABLE_USER_SITE and os.path.isdir(user_site): addsitedir(user_site, known_paths) return known_paths def getsitepackages(prefixes=None): """Returns a list containing all global site-packages directories. For each directory present in ``prefixes`` (or the global ``PREFIXES``), this function will find its `site-packages` subdirectory depending on the system environment, and will return a list of full paths. """ sitepackages = [] seen = set() if prefixes is None: prefixes = PREFIXES for prefix in prefixes: if not prefix or prefix in seen: continue seen.add(prefix) if os.sep == '/': sitepackages.append(os.path.join(prefix, "lib", "python%d.%d" % sys.version_info[:2], "site-packages")) else: sitepackages.append(prefix) sitepackages.append(os.path.join(prefix, "lib", "site-packages")) if sys.platform == "darwin": # for framework builds *only* we add the standard Apple # locations. from sysconfig import get_config_var framework = get_config_var("PYTHONFRAMEWORK") if framework: sitepackages.append( os.path.join("/Library", framework, '%d.%d' % sys.version_info[:2], "site-packages")) return sitepackages def addsitepackages(known_paths, prefixes=None): """Add site-packages to sys.path""" for sitedir in getsitepackages(prefixes): if os.path.isdir(sitedir): addsitedir(sitedir, known_paths) return known_paths def setquit(): """Define new builtins 'quit' and 'exit'. These are objects which make the interpreter exit when called. The repr of each object contains a hint at how it works. """ if os.sep == '\\': eof = 'Ctrl-Z plus Return' else: eof = 'Ctrl-D (i.e. EOF)' builtins.quit = _sitebuiltins.Quitter('quit', eof) builtins.exit = _sitebuiltins.Quitter('exit', eof) def setcopyright(): """Set 'copyright' and 'credits' in builtins""" builtins.copyright = _sitebuiltins._Printer("copyright", sys.copyright) builtins.credits = _sitebuiltins._Printer("credits", """\ Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information. Thanks go to github.com/ahgamut for porting Python to Cosmopolitan Libc.""") files, dirs = [], [] # Not all modules are required to have a __file__ attribute. See # PEP 420 for more details. if hasattr(os, '__file__'): here = os.path.dirname(os.__file__) files.extend(["LICENSE.txt", "LICENSE"]) dirs.extend([os.path.join(here, os.pardir), here, os.curdir]) builtins.license = _sitebuiltins._Printer( "license", "See https://www.python.org/psf/license/", files, dirs) def sethelper(): builtins.help = _sitebuiltins._Helper() def enablerlcompleter(): """Enable default readline configuration on interactive prompts, by registering a sys.__interactivehook__. If the readline module can be imported, the hook will set the Tab key as completion key and register ~/.python_history as history file. This can be overridden in the sitecustomize or usercustomize module, or in a PYTHONSTARTUP file. """ def register_readline(): try: import atexit import readline import rlcompleter except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except IOError: pass def write_history(): try: readline.write_history_file(history) except (FileNotFoundError, PermissionError): # home directory does not exist or is not writable # https://bugs.python.org/issue19891 pass atexit.register(write_history) sys.__interactivehook__ = register_readline def venv(known_paths): global PREFIXES, ENABLE_USER_SITE env = os.environ if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in env: executable = os.environ['__PYVENV_LAUNCHER__'] else: executable = sys.executable exe_dir, _ = os.path.split(os.path.abspath(executable)) site_prefix = os.path.dirname(exe_dir) sys._home = None conf_basename = 'pyvenv.cfg' candidate_confs = [ conffile for conffile in ( os.path.join(exe_dir, conf_basename), os.path.join(site_prefix, conf_basename) ) if os.path.isfile(conffile) ] if candidate_confs: virtual_conf = candidate_confs[0] system_site = "true" # Issue 25185: Use UTF-8, as that's what the venv module uses when # writing the file. with open(virtual_conf, encoding='utf-8') as f: for line in f: if '=' in line: key, _, value = line.partition('=') key = key.strip().lower() value = value.strip() if key == 'include-system-site-packages': system_site = value.lower() elif key == 'home': sys._home = value sys.prefix = sys.exec_prefix = site_prefix # Doing this here ensures venv takes precedence over user-site addsitepackages(known_paths, [sys.prefix]) # addsitepackages will process site_prefix again if its in PREFIXES, # but that's ok; known_paths will prevent anything being added twice if system_site == "true": PREFIXES.insert(0, sys.prefix) else: PREFIXES = [sys.prefix] ENABLE_USER_SITE = False return known_paths def execsitecustomize(): """Run custom site specific code, if available.""" try: try: import sitecustomize except ImportError as exc: if exc.name == 'sitecustomize': pass else: raise except Exception as err: if sys.flags.verbose: sys.excepthook(*sys.exc_info()) else: sys.stderr.write( "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n" "%s: %s\n" % (err.__class__.__name__, err)) def execusercustomize(): """Run custom user specific code, if available.""" try: try: import usercustomize except ImportError as exc: if exc.name == 'usercustomize': pass else: raise except Exception as err: if sys.flags.verbose: sys.excepthook(*sys.exc_info()) else: sys.stderr.write( "Error in usercustomize; set PYTHONVERBOSE for traceback:\n" "%s: %s\n" % (err.__class__.__name__, err)) def main(): """Add standard site-specific directories to the module search path. This function is called automatically when this module is imported, unless the python interpreter was started with the -S flag. """ global ENABLE_USER_SITE abs_paths() known_paths = removeduppaths() known_paths = venv(known_paths) if ENABLE_USER_SITE is None: ENABLE_USER_SITE = check_enableusersite() known_paths = addusersitepackages(known_paths) known_paths = addsitepackages(known_paths) setquit() setcopyright() sethelper() if not sys.flags.isolated: enablerlcompleter() execsitecustomize() if ENABLE_USER_SITE: execusercustomize() # Prevent extending of sys.path when python was started with -S and # site is imported later. if not sys.flags.no_site: main() def _script(): help = """\ %s [--user-base] [--user-site] Without arguments print some useful information With arguments print the value of USER_BASE and/or USER_SITE separated by '%s'. Exit codes with --user-base or --user-site: 0 - user site directory is enabled 1 - user site directory is disabled by user 2 - uses site directory is disabled by super user or for security reasons >2 - unknown error """ args = sys.argv[1:] if not args: user_base = getuserbase() user_site = getusersitepackages() print("sys.path = [") for dir in sys.path: print(" %r," % (dir,)) print("]") print("USER_BASE: %r (%s)" % (user_base, "exists" if os.path.isdir(user_base) else "doesn't exist")) print("USER_SITE: %r (%s)" % (user_site, "exists" if os.path.isdir(user_site) else "doesn't exist")) print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE) sys.exit(0) buffer = [] if '--user-base' in args: buffer.append(USER_BASE) if '--user-site' in args: buffer.append(USER_SITE) if buffer: print(os.pathsep.join(buffer)) if ENABLE_USER_SITE: sys.exit(0) elif ENABLE_USER_SITE is False: sys.exit(1) elif ENABLE_USER_SITE is None: sys.exit(2) else: sys.exit(3) else: try: import textwrap print(textwrap.dedent(help % (sys.argv[0], os.pathsep))) except ImportError: pass sys.exit(10) if __name__ == '__main__': _script()
21,579
635
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tokenize.py
"""Tokenization help for Python programs. tokenize(readline) is a generator that breaks a stream of bytes into Python tokens. It decodes the bytes according to PEP-0263 for determining source file encoding. It accepts a readline-like method which is called repeatedly to get the next line of input (or b"" for EOF). It generates 5-tuples with these members: the token type (see token.py) the token (a string) the starting (row, column) indices of the token (a 2-tuple of ints) the ending (row, column) indices of the token (a 2-tuple of ints) the original line (string) It is designed to match the working of the Python tokenizer exactly, except that it produces COMMENT tokens for comments and gives type OP for all operators. Additionally, all token lists start with an ENCODING token which tells you which encoding was used to decode the bytes stream. """ __author__ = 'Ka-Ping Yee <[email protected]>' __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, ' 'Skip Montanaro, Raymond Hettinger, Trent Nelson, ' 'Michael Foord') from builtins import open as _builtin_open from codecs import lookup, BOM_UTF8 import collections from io import TextIOWrapper from itertools import chain import itertools as _itertools import re import sys from token import AMPER, AMPEREQUAL, ASYNC, AT, ATEQUAL, AWAIT, CIRCUMFLEX, CIRCUMFLEXEQUAL, COLON, COMMA, DEDENT, DOT, DOUBLESLASH, DOUBLESLASHEQUAL, DOUBLESTAR, DOUBLESTAREQUAL, ELLIPSIS, ENDMARKER, EQEQUAL, EQUAL, ERRORTOKEN, GREATER, GREATEREQUAL, INDENT, ISEOF, ISNONTERMINAL, ISTERMINAL, LBRACE, LEFTSHIFT, LEFTSHIFTEQUAL, LESS, LESSEQUAL, LPAR, LSQB, MINEQUAL, MINUS, NAME, NEWLINE, NOTEQUAL, NT_OFFSET, NUMBER, N_TOKENS, OP, PERCENT, PERCENTEQUAL, PLUS, PLUSEQUAL, RARROW, RBRACE, RIGHTSHIFT, RIGHTSHIFTEQUAL, RPAR, RSQB, SEMI, SLASH, SLASHEQUAL, STAR, STAREQUAL, STRING, TILDE, VBAR, VBAREQUAL, tok_name cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII) blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII) COMMENT = N_TOKENS tok_name[COMMENT] = 'COMMENT' NL = N_TOKENS + 1 tok_name[NL] = 'NL' ENCODING = N_TOKENS + 2 tok_name[ENCODING] = 'ENCODING' N_TOKENS += 3 EXACT_TOKEN_TYPES = { '(': LPAR, ')': RPAR, '[': LSQB, ']': RSQB, ':': COLON, ',': COMMA, ';': SEMI, '+': PLUS, '-': MINUS, '*': STAR, '/': SLASH, '|': VBAR, '&': AMPER, '<': LESS, '>': GREATER, '=': EQUAL, '.': DOT, '%': PERCENT, '{': LBRACE, '}': RBRACE, '==': EQEQUAL, '!=': NOTEQUAL, '<=': LESSEQUAL, '>=': GREATEREQUAL, '~': TILDE, '^': CIRCUMFLEX, '<<': LEFTSHIFT, '>>': RIGHTSHIFT, '**': DOUBLESTAR, '+=': PLUSEQUAL, '-=': MINEQUAL, '*=': STAREQUAL, '/=': SLASHEQUAL, '%=': PERCENTEQUAL, '&=': AMPEREQUAL, '|=': VBAREQUAL, '^=': CIRCUMFLEXEQUAL, '<<=': LEFTSHIFTEQUAL, '>>=': RIGHTSHIFTEQUAL, '**=': DOUBLESTAREQUAL, '//': DOUBLESLASH, '//=': DOUBLESLASHEQUAL, '@': AT, '@=': ATEQUAL, } class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')): def __repr__(self): annotated_type = '%d (%s)' % (self.type, tok_name[self.type]) return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' % self._replace(type=annotated_type)) @property def exact_type(self): if self.type == OP and self.string in EXACT_TOKEN_TYPES: return EXACT_TOKEN_TYPES[self.string] else: return self.type def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' # Note: we use unicode matching for names ("\w") but ascii matching for # number literals. Whitespace = r'[ \f\t]*' Comment = r'#[^\r\n]*' Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment) Name = r'\w+' Hexnumber = r'0[xX](?:_?[0-9a-fA-F])+' Binnumber = r'0[bB](?:_?[01])+' Octnumber = r'0[oO](?:_?[0-7])+' Decnumber = r'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)' Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber) Exponent = r'[eE][-+]?[0-9](?:_?[0-9])*' Pointfloat = group(r'[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?', r'\.[0-9](?:_?[0-9])*') + maybe(Exponent) Expfloat = r'[0-9](?:_?[0-9])*' + Exponent Floatnumber = group(Pointfloat, Expfloat) Imagnumber = group(r'[0-9](?:_?[0-9])*[jJ]', Floatnumber + r'[jJ]') Number = group(Imagnumber, Floatnumber, Intnumber) # Return the empty string, plus all of the valid string prefixes. def _all_string_prefixes(): # The valid string prefixes. Only contain the lower case versions, # and don't contain any permuations (include 'fr', but not # 'rf'). The various permutations will be generated. _valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr'] # if we add binary f-strings, add: ['fb', 'fbr'] result = set(['']) for prefix in _valid_string_prefixes: for t in _itertools.permutations(prefix): # create a list with upper and lower versions of each # character for u in _itertools.product(*[(c, c.upper()) for c in t]): result.add(''.join(u)) return result def _compile(expr): return re.compile(expr, re.UNICODE) # Note that since _all_string_prefixes includes the empty string, # StringPrefix can be the empty string (making it optional). StringPrefix = group(*_all_string_prefixes()) # Tail end of ' string. Single = r"[^'\\]*(?:\\.[^'\\]*)*'" # Tail end of " string. Double = r'[^"\\]*(?:\\.[^"\\]*)*"' # Tail end of ''' string. Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" # Tail end of """ string. Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' Triple = group(StringPrefix + "'''", StringPrefix + '"""') # Single-line ' or " string. String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'", StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"') # Because of leftmost-then-longest match semantics, be sure to put the # longest operators first (e.g., if = came before ==, == would get # recognized as two instances of =). Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=", r"//=?", r"->", r"[+\-*/%&@|^=<>]=?", r"~") Bracket = '[][(){}]' Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]') Funny = group(Operator, Bracket, Special) PlainToken = group(Number, Funny, String, Name) Token = Ignore + PlainToken # First (or only) line of ' or " string. ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" + group("'", r'\\\r?\n'), StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' + group('"', r'\\\r?\n')) PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple) PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name) # For a given string prefix plus quotes, endpats maps it to a regex # to match the remainder of that string. _prefix can be empty, for # a normal single or triple quoted string (with no prefix). endpats = {} for _prefix in _all_string_prefixes(): endpats[_prefix + "'"] = Single endpats[_prefix + '"'] = Double endpats[_prefix + "'''"] = Single3 endpats[_prefix + '"""'] = Double3 # A set of all of the single and triple quoted string prefixes, # including the opening quotes. single_quoted = set() triple_quoted = set() for t in _all_string_prefixes(): for u in (t + '"', t + "'"): single_quoted.add(u) for u in (t + '"""', t + "'''"): triple_quoted.add(u) tabsize = 8 class TokenError(Exception): pass class StopTokenizing(Exception): pass class Untokenizer: def __init__(self): self.tokens = [] self.prev_row = 1 self.prev_col = 0 self.encoding = None def add_whitespace(self, start): row, col = start if row < self.prev_row or row == self.prev_row and col < self.prev_col: raise ValueError("start ({},{}) precedes previous end ({},{})" .format(row, col, self.prev_row, self.prev_col)) row_offset = row - self.prev_row if row_offset: self.tokens.append("\\\n" * row_offset) self.prev_col = 0 col_offset = col - self.prev_col if col_offset: self.tokens.append(" " * col_offset) def untokenize(self, iterable): it = iter(iterable) indents = [] startline = False for t in it: if len(t) == 2: self.compat(t, it) break tok_type, token, start, end, line = t if tok_type == ENCODING: self.encoding = token continue if tok_type == ENDMARKER: break if tok_type == INDENT: indents.append(token) continue elif tok_type == DEDENT: indents.pop() self.prev_row, self.prev_col = end continue elif tok_type in (NEWLINE, NL): startline = True elif startline and indents: indent = indents[-1] if start[1] >= len(indent): self.tokens.append(indent) self.prev_col = len(indent) startline = False self.add_whitespace(start) self.tokens.append(token) self.prev_row, self.prev_col = end if tok_type in (NEWLINE, NL): self.prev_row += 1 self.prev_col = 0 return "".join(self.tokens) def compat(self, token, iterable): indents = [] toks_append = self.tokens.append startline = token[0] in (NEWLINE, NL) prevstring = False for tok in chain([token], iterable): toknum, tokval = tok[:2] if toknum == ENCODING: self.encoding = tokval continue if toknum in (NAME, NUMBER, ASYNC, AWAIT): tokval += ' ' # Insert a space between two consecutive strings if toknum == STRING: if prevstring: tokval = ' ' + tokval prevstring = True else: prevstring = False if toknum == INDENT: indents.append(tokval) continue elif toknum == DEDENT: indents.pop() continue elif toknum in (NEWLINE, NL): startline = True elif startline and indents: toks_append(indents[-1]) startline = False toks_append(tokval) def untokenize(iterable): """Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited input: # Output bytes will tokenize back to the input t1 = [tok[:2] for tok in tokenize(f.readline)] newcode = untokenize(t1) readline = BytesIO(newcode).readline t2 = [tok[:2] for tok in tokenize(readline)] assert t1 == t2 """ ut = Untokenizer() out = ut.untokenize(iterable) if ut.encoding is not None: out = out.encode(ut.encoding) return out def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): return "iso-8859-1" return orig_enc def detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned. """ try: filename = readline.__self__.name except AttributeError: filename = None bom_found = False encoding = None default = 'utf-8' def read_or_stop(): try: return readline() except StopIteration: return b'' def find_cookie(line): try: # Decode as UTF-8. Either the line is an encoding declaration, # in which case it should be pure ASCII, or it must be UTF-8 # per default encoding. line_string = line.decode('utf-8') except UnicodeDecodeError: msg = "invalid or missing encoding declaration" if filename is not None: msg = '{} for {!r}'.format(msg, filename) raise SyntaxError(msg) match = cookie_re.match(line_string) if not match: return None encoding = _get_normal_name(match.group(1)) try: codec = lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter if filename is None: msg = "unknown encoding: " + encoding else: msg = "unknown encoding for {!r}: {}".format(filename, encoding) raise SyntaxError(msg) if bom_found: if encoding != 'utf-8': # This behaviour mimics the Python interpreter if filename is None: msg = 'encoding problem: utf-8' else: msg = 'encoding problem for {!r}: utf-8'.format(filename) raise SyntaxError(msg) encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] encoding = find_cookie(first) if encoding: return encoding, [first] if not blank_re.match(first): return default, [first] second = read_or_stop() if not second: return default, [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return default, [first, second] def open(filename): """Open a file in read only mode using the encoding detected by detect_encoding(). """ buffer = _builtin_open(filename, 'rb') try: encoding, lines = detect_encoding(buffer.readline) buffer.seek(0) text = TextIOWrapper(buffer, encoding, line_buffering=True) text.mode = 'r' return text except: buffer.close() raise def tokenize(readline): """ The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as bytes. Alternatively, readline can be a callable function terminating with StopIteration: readline = open(myfile, 'rb').__next__ # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included. The first token sequence will always be an ENCODING token which tells you which encoding was used to decode the bytes stream. """ # This import is here to avoid problems when the itertools module is not # built yet and tokenize is imported. from itertools import chain, repeat encoding, consumed = detect_encoding(readline) rl_gen = iter(readline, b"") empty = repeat(b"") return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding) def _tokenize(readline, encoding): lnum = parenlev = continued = 0 numchars = '0123456789' contstr, needcont = '', 0 contline = None indents = [0] # 'stashed' and 'async_*' are used for async/await parsing stashed = None async_def = False async_def_indent = 0 async_def_nl = False if encoding is not None: if encoding == "utf-8-sig": # BOM will already have been stripped. encoding = "utf-8" yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '') last_line = b'' line = b'' while True: # loop over lines in stream try: # We capture the value of the line variable here because # readline uses the empty string '' to signal end of input, # hence `line` itself will always be overwritten at the end # of this loop. last_line = line line = readline() except StopIteration: line = b'' if encoding is not None: line = line.decode(encoding) lnum += 1 pos, max = 0, len(line) if contstr: # continued string if not line: raise TokenError("EOF in multi-line string", strstart) endmatch = endprog.match(line) if endmatch: pos = end = endmatch.end(0) yield TokenInfo(STRING, contstr + line[:end], strstart, (lnum, end), contline + line) contstr, needcont = '', 0 contline = None elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': yield TokenInfo(ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline) contstr = '' contline = None continue else: contstr = contstr + line contline = contline + line continue elif parenlev == 0 and not continued: # new statement if not line: break column = 0 while pos < max: # measure leading whitespace if line[pos] == ' ': column += 1 elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize elif line[pos] == '\f': column = 0 else: break pos += 1 if pos == max: break if line[pos] in '#\r\n': # skip comments or blank lines if line[pos] == '#': comment_token = line[pos:].rstrip('\r\n') nl_pos = pos + len(comment_token) yield TokenInfo(COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line) yield TokenInfo(NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line) else: yield TokenInfo((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line) continue if column > indents[-1]: # count indents or dedents indents.append(column) yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line) while column < indents[-1]: if column not in indents: raise IndentationError( "unindent does not match any outer indentation level", ("<tokenize>", lnum, pos, line)) indents = indents[:-1] if async_def and async_def_indent >= indents[-1]: async_def = False async_def_nl = False async_def_indent = 0 yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line) if async_def and async_def_nl and async_def_indent >= indents[-1]: async_def = False async_def_nl = False async_def_indent = 0 else: # continued statement if not line: raise TokenError("EOF in multi-line statement", (lnum, 0)) continued = 0 while pos < max: pseudomatch = _compile(PseudoToken).match(line, pos) if pseudomatch: # scan for tokens start, end = pseudomatch.span(1) spos, epos, pos = (lnum, start), (lnum, end), end if start == end: continue token, initial = line[start:end], line[start] if (initial in numchars or # ordinary number (initial == '.' and token != '.' and token != '...')): yield TokenInfo(NUMBER, token, spos, epos, line) elif initial in '\r\n': if stashed: yield stashed stashed = None if parenlev > 0: yield TokenInfo(NL, token, spos, epos, line) else: yield TokenInfo(NEWLINE, token, spos, epos, line) if async_def: async_def_nl = True elif initial == '#': assert not token.endswith("\n") if stashed: yield stashed stashed = None yield TokenInfo(COMMENT, token, spos, epos, line) elif token in triple_quoted: endprog = _compile(endpats[token]) endmatch = endprog.match(line, pos) if endmatch: # all on one line pos = endmatch.end(0) token = line[start:pos] yield TokenInfo(STRING, token, spos, (lnum, pos), line) else: strstart = (lnum, start) # multiple lines contstr = line[start:] contline = line break # Check up to the first 3 chars of the token to see if # they're in the single_quoted set. If so, they start # a string. # We're using the first 3, because we're looking for # "rb'" (for example) at the start of the token. If # we switch to longer prefixes, this needs to be # adjusted. # Note that initial == token[:1]. # Also note that single quote checking must come after # triple quote checking (above). elif (initial in single_quoted or token[:2] in single_quoted or token[:3] in single_quoted): if token[-1] == '\n': # continued string strstart = (lnum, start) # Again, using the first 3 chars of the # token. This is looking for the matching end # regex for the correct type of quote # character. So it's really looking for # endpats["'"] or endpats['"'], by trying to # skip string prefix characters, if any. endprog = _compile(endpats.get(initial) or endpats.get(token[1]) or endpats.get(token[2])) contstr, needcont = line[start:], 1 contline = line break else: # ordinary string yield TokenInfo(STRING, token, spos, epos, line) elif initial.isidentifier(): # ordinary name if token in ('async', 'await'): if async_def: yield TokenInfo( ASYNC if token == 'async' else AWAIT, token, spos, epos, line) continue tok = TokenInfo(NAME, token, spos, epos, line) if token == 'async' and not stashed: stashed = tok continue if token == 'def': if (stashed and stashed.type == NAME and stashed.string == 'async'): async_def = True async_def_indent = indents[-1] yield TokenInfo(ASYNC, stashed.string, stashed.start, stashed.end, stashed.line) stashed = None if stashed: yield stashed stashed = None yield tok elif initial == '\\': # continued stmt continued = 1 else: if initial in '([{': parenlev += 1 elif initial in ')]}': parenlev -= 1 if stashed: yield stashed stashed = None yield TokenInfo(OP, token, spos, epos, line) else: yield TokenInfo(ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos+1), line) pos += 1 if stashed: yield stashed stashed = None # Add an implicit NEWLINE if the input doesn't end in one if last_line and last_line[-1] not in '\r\n': yield TokenInfo(NEWLINE, '', (lnum - 1, len(last_line)), (lnum - 1, len(last_line) + 1), '') for indent in indents[1:]: # pop remaining indent levels yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '') yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '') # An undocumented, backwards compatible, API for all the places in the standard # library that expect to be able to use tokenize with strings def generate_tokens(readline): return _tokenize(readline, None) def main(): try: import argparse except ImportError: print("error: argparse not yoinked", file=sys.stderr) sys.exit(1) # Helper error handling routines def perror(message): print(message, file=sys.stderr) def error(message, filename=None, location=None): if location: args = (filename,) + location + (message,) perror("%s:%d:%d: error: %s" % args) elif filename: perror("%s: error: %s" % (filename, message)) else: perror("error: %s" % message) sys.exit(1) # Parse the arguments and options parser = argparse.ArgumentParser(prog='python -m tokenize') parser.add_argument(dest='filename', nargs='?', metavar='filename.py', help='the file to tokenize; defaults to stdin') parser.add_argument('-e', '--exact', dest='exact', action='store_true', help='display token names using the exact type') args = parser.parse_args() try: # Tokenize the input if args.filename: filename = args.filename with _builtin_open(filename, 'rb') as f: tokens = list(tokenize(f.readline)) else: filename = "<stdin>" tokens = _tokenize(sys.stdin.readline, None) # Output the tokenization for token in tokens: token_type = token.type if args.exact: token_type = token.exact_type token_range = "%d,%d-%d,%d:" % (token.start + token.end) print("%-20s%-15s%-15r" % (token_range, tok_name[token_type], token.string)) except IndentationError as err: line, column = err.args[1][1:3] error(err.args[0], filename, (line, column)) except TokenError as err: line, column = err.args[1] error(err.args[0], filename, (line, column)) except SyntaxError as err: error(err, filename) except OSError as err: error(err) except KeyboardInterrupt: print("interrupted\n") except Exception as err: perror("unexpected error: %s" % err) raise if __name__ == "__main__": main()
30,043
803
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/asyncore.py
# -*- Mode: Python -*- # Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp # Author: Sam Rushing <[email protected]> # ====================================================================== # Copyright 1996 by Sam Rushing # # All Rights Reserved # # Permission to use, copy, modify, and distribute this software and # its documentation for any purpose and without fee is hereby # granted, provided that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of Sam # Rushing not be used in advertising or publicity pertaining to # distribution of the software without specific, written prior # permission. # # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # ====================================================================== """Basic infrastructure for asynchronous socket service clients and servers. There are only two ways to have a program on a single processor do "more than one thing at a time". Multi-threaded programming is the simplest and most popular way to do it, but there is another very different technique, that lets you have nearly all the advantages of multi-threading, without actually using multiple threads. it's really only practical if your program is largely I/O bound. If your program is CPU bound, then pre-emptive scheduled threads are probably what you really need. Network servers are rarely CPU-bound, however. If your operating system supports the select() system call in its I/O library (and nearly all do), then you can use it to juggle multiple communication channels at once; doing other work while your I/O is taking place in the "background." Although this strategy can seem strange and complex, especially at first, it is in many ways easier to understand and control than multi-threaded programming. The module documented here solves many of the difficult problems for you, making the task of building sophisticated high-performance network servers and clients a snap. """ import select import socket import sys import time import warnings import os from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, EINVAL, \ ENOTCONN, ESHUTDOWN, EISCONN, EBADF, ECONNABORTED, EPIPE, EAGAIN, \ errorcode _DISCONNECTED = frozenset({ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE, EBADF}) try: socket_map except NameError: socket_map = {} def _strerror(err): try: return os.strerror(err) except (ValueError, OverflowError, NameError): if err in errorcode: return errorcode[err] return "Unknown error %s" %err class ExitNow(Exception): pass _reraised_exceptions = (ExitNow, KeyboardInterrupt, SystemExit) def read(obj): try: obj.handle_read_event() except _reraised_exceptions: raise except: obj.handle_error() def write(obj): try: obj.handle_write_event() except _reraised_exceptions: raise except: obj.handle_error() def _exception(obj): try: obj.handle_expt_event() except _reraised_exceptions: raise except: obj.handle_error() def readwrite(obj, flags): try: if flags & select.POLLIN: obj.handle_read_event() if flags & select.POLLOUT: obj.handle_write_event() if flags & select.POLLPRI: obj.handle_expt_event() if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL): obj.handle_close() except OSError as e: if e.args[0] not in _DISCONNECTED: obj.handle_error() else: obj.handle_close() except _reraised_exceptions: raise except: obj.handle_error() def poll(timeout=0.0, map=None): if map is None: map = socket_map if map: r = []; w = []; e = [] for fd, obj in list(map.items()): is_r = obj.readable() is_w = obj.writable() if is_r: r.append(fd) # accepting sockets should not be writable if is_w and not obj.accepting: w.append(fd) if is_r or is_w: e.append(fd) if [] == r == w == e: time.sleep(timeout) return r, w, e = select.select(r, w, e, timeout) for fd in r: obj = map.get(fd) if obj is None: continue read(obj) for fd in w: obj = map.get(fd) if obj is None: continue write(obj) for fd in e: obj = map.get(fd) if obj is None: continue _exception(obj) def poll2(timeout=0.0, map=None): # Use the poll() support added to the select module in Python 2.0 if map is None: map = socket_map if timeout is not None: # timeout is in milliseconds timeout = int(timeout*1000) pollster = select.poll() if map: for fd, obj in list(map.items()): flags = 0 if obj.readable(): flags |= select.POLLIN | select.POLLPRI # accepting sockets should not be writable if obj.writable() and not obj.accepting: flags |= select.POLLOUT if flags: pollster.register(fd, flags) r = pollster.poll(timeout) for fd, flags in r: obj = map.get(fd) if obj is None: continue readwrite(obj, flags) poll3 = poll2 # Alias for backward compatibility def loop(timeout=30.0, use_poll=False, map=None, count=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll if count is None: while map: poll_fun(timeout, map) else: while map and count > 0: poll_fun(timeout, map) count = count - 1 class dispatcher: debug = False connected = False accepting = False connecting = False closing = False addr = None ignore_log_types = frozenset({'warning'}) def __init__(self, sock=None, map=None): if map is None: self._map = socket_map else: self._map = map self._fileno = None if sock: # Set to nonblocking just to make sure for cases where we # get a socket from a blocking source. sock.setblocking(0) self.set_socket(sock, map) self.connected = True # The constructor no longer requires that the socket # passed be connected. try: self.addr = sock.getpeername() except OSError as err: if err.args[0] in (ENOTCONN, EINVAL): # To handle the case where we got an unconnected # socket. self.connected = False else: # The socket is broken in some unknown way, alert # the user and remove it from the map (to prevent # polling of broken sockets). self.del_channel(map) raise else: self.socket = None def __repr__(self): status = [self.__class__.__module__+"."+self.__class__.__qualname__] if self.accepting and self.addr: status.append('listening') elif self.connected: status.append('connected') if self.addr is not None: try: status.append('%s:%d' % self.addr) except TypeError: status.append(repr(self.addr)) return '<%s at %#x>' % (' '.join(status), id(self)) __str__ = __repr__ def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: map = self._map map[self._fileno] = self def del_channel(self, map=None): fd = self._fileno if map is None: map = self._map if fd in map: #self.log_info('closing channel %d:%s' % (fd, self)) del map[fd] self._fileno = None def create_socket(self, family=socket.AF_INET, type=socket.SOCK_STREAM): self.family_and_type = family, type sock = socket.socket(family, type) sock.setblocking(0) self.set_socket(sock) def set_socket(self, sock, map=None): self.socket = sock ## self.__dict__['socket'] = sock self._fileno = sock.fileno() self.add_channel(map) def set_reuse_addr(self): # try to re-use a server port if possible try: self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 ) except OSError: pass # ================================================== # predicates for select() # these are used as filters for the lists of sockets # to pass to select(). # ================================================== def readable(self): return True def writable(self): return True # ================================================== # socket object methods. # ================================================== def listen(self, num): self.accepting = True if os.name == 'nt' and num > 5: num = 5 return self.socket.listen(num) def bind(self, addr): self.addr = addr return self.socket.bind(addr) def connect(self, address): self.connected = False self.connecting = True err = self.socket.connect_ex(address) if err in (EINPROGRESS, EALREADY, EWOULDBLOCK) \ or err == EINVAL and os.name == 'nt': self.addr = address return if err in (0, EISCONN): self.addr = address self.handle_connect_event() else: raise OSError(err, errorcode[err]) def accept(self): # XXX can return either an address pair or None try: conn, addr = self.socket.accept() except TypeError: return None except OSError as why: if why.args[0] in (EWOULDBLOCK, ECONNABORTED, EAGAIN): return None else: raise else: return conn, addr def send(self, data): try: result = self.socket.send(data) return result except OSError as why: if why.args[0] == EWOULDBLOCK: return 0 elif why.args[0] in _DISCONNECTED: self.handle_close() return 0 else: raise def recv(self, buffer_size): try: data = self.socket.recv(buffer_size) if not data: # a closed connection is indicated by signaling # a read condition, and having recv() return 0. self.handle_close() return b'' else: return data except OSError as why: # winsock sometimes raises ENOTCONN if why.args[0] in _DISCONNECTED: self.handle_close() return b'' else: raise def close(self): self.connected = False self.accepting = False self.connecting = False self.del_channel() if self.socket is not None: try: self.socket.close() except OSError as why: if why.args[0] not in (ENOTCONN, EBADF): raise # log and log_info may be overridden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging # and 'log_info' is for informational, warning and error logging. def log(self, message): sys.stderr.write('log: %s\n' % str(message)) def log_info(self, message, type='info'): if type not in self.ignore_log_types: print('%s: %s' % (type, message)) def handle_read_event(self): if self.accepting: # accepting sockets are never connected, they "spawn" new # sockets that are connected self.handle_accept() elif not self.connected: if self.connecting: self.handle_connect_event() self.handle_read() else: self.handle_read() def handle_connect_event(self): err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: raise OSError(err, _strerror(err)) self.handle_connect() self.connected = True self.connecting = False def handle_write_event(self): if self.accepting: # Accepting sockets shouldn't get a write event. # We will pretend it didn't happen. return if not self.connected: if self.connecting: self.handle_connect_event() self.handle_write() def handle_expt_event(self): # handle_expt_event() is called if there might be an error on the # socket, or if there is OOB data # check for the error condition first err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # we can get here when select.select() says that there is an # exceptional condition on the socket # since there is an error, we'll go ahead and close the socket # like we would in a subclassed handle_read() that received no # data self.handle_close() else: self.handle_expt() def handle_error(self): nil, t, v, tbinfo = compact_traceback() # sometimes a user repr method will crash. try: self_repr = repr(self) except: self_repr = '<__repr__(self) failed for object at %0x>' % id(self) self.log_info( 'uncaptured python exception, closing channel %s (%s:%s %s)' % ( self_repr, t, v, tbinfo ), 'error' ) self.handle_close() def handle_expt(self): self.log_info('unhandled incoming priority event', 'warning') def handle_read(self): self.log_info('unhandled read event', 'warning') def handle_write(self): self.log_info('unhandled write event', 'warning') def handle_connect(self): self.log_info('unhandled connect event', 'warning') def handle_accept(self): pair = self.accept() if pair is not None: self.handle_accepted(*pair) def handle_accepted(self, sock, addr): sock.close() self.log_info('unhandled accepted event', 'warning') def handle_close(self): self.log_info('unhandled close event', 'warning') self.close() # --------------------------------------------------------------------------- # adds simple buffered output capability, useful for simple clients. # [for more sophisticated usage use asynchat.async_chat] # --------------------------------------------------------------------------- class dispatcher_with_send(dispatcher): def __init__(self, sock=None, map=None): dispatcher.__init__(self, sock, map) self.out_buffer = b'' def initiate_send(self): num_sent = 0 num_sent = dispatcher.send(self, self.out_buffer[:65536]) self.out_buffer = self.out_buffer[num_sent:] def handle_write(self): self.initiate_send() def writable(self): return (not self.connected) or len(self.out_buffer) def send(self, data): if self.debug: self.log_info('sending %s' % repr(data)) self.out_buffer = self.out_buffer + data self.initiate_send() # --------------------------------------------------------------------------- # used for debugging. # --------------------------------------------------------------------------- def compact_traceback(): t, v, tb = sys.exc_info() tbinfo = [] if not tb: # Must have a traceback raise AssertionError("traceback does not exist") while tb: tbinfo.append(( tb.tb_frame.f_code.co_filename, tb.tb_frame.f_code.co_name, str(tb.tb_lineno) )) tb = tb.tb_next # just to be safe del tb file, function, line = tbinfo[-1] info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo]) return (file, function, line), t, v, info def close_all(map=None, ignore_all=False): if map is None: map = socket_map for x in list(map.values()): try: x.close() except OSError as x: if x.args[0] == EBADF: pass elif not ignore_all: raise except _reraised_exceptions: raise except: if not ignore_all: raise map.clear() # Asynchronous File I/O: # # After a little research (reading man pages on various unixen, and # digging through the linux kernel), I've determined that select() # isn't meant for doing asynchronous file i/o. # Heartening, though - reading linux/mm/filemap.c shows that linux # supports asynchronous read-ahead. So _MOST_ of the time, the data # will be sitting in memory for us already when we go to read it. # # What other OS's (besides NT) support async file i/o? [VMS?] # # Regardless, this is useful for pipes, and stdin/stdout... if os.name == 'posix': class file_wrapper: # Here we override just enough to make a file # look like a socket for the purposes of asyncore. # The passed fd is automatically os.dup()'d def __init__(self, fd): self.fd = os.dup(fd) def __del__(self): if self.fd >= 0: warnings.warn("unclosed file %r" % self, ResourceWarning, source=self) self.close() def recv(self, *args): return os.read(self.fd, *args) def send(self, *args): return os.write(self.fd, *args) def getsockopt(self, level, optname, buflen=None): if (level == socket.SOL_SOCKET and optname == socket.SO_ERROR and not buflen): return 0 raise NotImplementedError("Only asyncore specific behaviour " "implemented.") read = recv write = send def close(self): if self.fd < 0: return fd = self.fd self.fd = -1 os.close(fd) def fileno(self): return self.fd class file_dispatcher(dispatcher): def __init__(self, fd, map=None): dispatcher.__init__(self, None, map) self.connected = True try: fd = fd.fileno() except AttributeError: pass self.set_file(fd) # set it to non-blocking mode os.set_blocking(fd, False) def set_file(self, fd): self.socket = file_wrapper(fd) self._fileno = self.socket.fileno() self.add_channel()
20,159
646
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/shlex.py
"""A lexical analyzer class for simple shell-like syntaxes.""" # Module and documentation by Eric S. Raymond, 21 Dec 1998 # Input stacking and error message cleanup added by ESR, March 2000 # push_source() and pop_source() made explicit by ESR, January 2001. # Posix compliance, split(), string arguments, and # iterator interface by Gustavo Niemeyer, April 2003. # changes to tokenize more like Posix shells by Vinay Sajip, July 2016. import os import re import sys from collections import deque from io import StringIO __all__ = ["shlex", "split", "quote"] class shlex: "A lexical analyzer class for simple shell-like syntaxes." def __init__(self, instream=None, infile=None, posix=False, punctuation_chars=False): if isinstance(instream, str): instream = StringIO(instream) if instream is not None: self.instream = instream self.infile = infile else: self.instream = sys.stdin self.infile = None self.posix = posix if posix: self.eof = None else: self.eof = '' self.commenters = '#' self.wordchars = ('abcdfeghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') if self.posix: self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ') self.whitespace = ' \t\r\n' self.whitespace_split = False self.quotes = '\'"' self.escape = '\\' self.escapedquotes = '"' self.state = ' ' self.pushback = deque() self.lineno = 1 self.debug = 0 self.token = '' self.filestack = deque() self.source = None if not punctuation_chars: punctuation_chars = '' elif punctuation_chars is True: punctuation_chars = '();<>|&' self.punctuation_chars = punctuation_chars if punctuation_chars: # _pushback_chars is a push back queue used by lookahead logic self._pushback_chars = deque() # these chars added because allowed in file names, args, wildcards self.wordchars += '~-./*?=' #remove any punctuation chars from wordchars t = self.wordchars.maketrans(dict.fromkeys(punctuation_chars)) self.wordchars = self.wordchars.translate(t) def push_token(self, tok): "Push a token onto the stack popped by the get_token method" if self.debug >= 1: print("shlex: pushing token " + repr(tok)) self.pushback.appendleft(tok) def push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, str): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1 if self.debug: if newfile is not None: print('shlex: pushing to file %s' % (self.infile,)) else: print('shlex: pushing to stream %s' % (self.instream,)) def pop_source(self): "Pop the input source stack." self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() if self.debug: print('shlex: popping to %s, line %d' \ % (self.instream, self.lineno)) self.state = ' ' def get_token(self): "Get a token from the input stream (or from stack if it's nonempty)" if self.pushback: tok = self.pushback.popleft() if self.debug >= 1: print("shlex: popping token " + repr(tok)) return tok # No pushback. Get a token. raw = self.read_token() # Handle inclusions if self.source is not None: while raw == self.source: spec = self.sourcehook(self.read_token()) if spec: (newfile, newstream) = spec self.push_source(newstream, newfile) raw = self.get_token() # Maybe we got EOF instead? while raw == self.eof: if not self.filestack: return self.eof else: self.pop_source() raw = self.get_token() # Neither inclusion nor EOF if self.debug >= 1: if raw != self.eof: print("shlex: token=" + repr(raw)) else: print("shlex: token=EOF") return raw def read_token(self): quoted = False escapedstate = ' ' while True: if self.punctuation_chars and self._pushback_chars: nextchar = self._pushback_chars.pop() else: nextchar = self.instream.read(1) if nextchar == '\n': self.lineno += 1 if self.debug >= 3: print("shlex: in state %r I see character: %r" % (self.state, nextchar)) if self.state is None: self.token = '' # past end of file break elif self.state == ' ': if not nextchar: self.state = None # end of file break elif nextchar in self.whitespace: if self.debug >= 2: print("shlex: I see whitespace in whitespace state") if self.token or (self.posix and quoted): break # emit current token else: continue elif nextchar in self.commenters: self.instream.readline() self.lineno += 1 elif self.posix and nextchar in self.escape: escapedstate = 'a' self.state = nextchar elif nextchar in self.wordchars: self.token = nextchar self.state = 'a' elif nextchar in self.punctuation_chars: self.token = nextchar self.state = 'c' elif nextchar in self.quotes: if not self.posix: self.token = nextchar self.state = nextchar elif self.whitespace_split: self.token = nextchar self.state = 'a' else: self.token = nextchar if self.token or (self.posix and quoted): break # emit current token else: continue elif self.state in self.quotes: quoted = True if not nextchar: # end of file if self.debug >= 2: print("shlex: I see EOF in quotes state") # XXX what error should be raised here? raise ValueError("No closing quotation") if nextchar == self.state: if not self.posix: self.token += nextchar self.state = ' ' break else: self.state = 'a' elif (self.posix and nextchar in self.escape and self.state in self.escapedquotes): escapedstate = self.state self.state = nextchar else: self.token += nextchar elif self.state in self.escape: if not nextchar: # end of file if self.debug >= 2: print("shlex: I see EOF in escape state") # XXX what error should be raised here? raise ValueError("No escaped character") # In posix shells, only the quote itself or the escape # character may be escaped within quotes. if (escapedstate in self.quotes and nextchar != self.state and nextchar != escapedstate): self.token += self.state self.token += nextchar self.state = escapedstate elif self.state in ('a', 'c'): if not nextchar: self.state = None # end of file break elif nextchar in self.whitespace: if self.debug >= 2: print("shlex: I see whitespace in word state") self.state = ' ' if self.token or (self.posix and quoted): break # emit current token else: continue elif nextchar in self.commenters: self.instream.readline() self.lineno += 1 if self.posix: self.state = ' ' if self.token or (self.posix and quoted): break # emit current token else: continue elif self.state == 'c': if nextchar in self.punctuation_chars: self.token += nextchar else: if nextchar not in self.whitespace: self._pushback_chars.append(nextchar) self.state = ' ' break elif self.posix and nextchar in self.quotes: self.state = nextchar elif self.posix and nextchar in self.escape: escapedstate = 'a' self.state = nextchar elif (nextchar in self.wordchars or nextchar in self.quotes or self.whitespace_split): self.token += nextchar else: if self.punctuation_chars: self._pushback_chars.append(nextchar) else: self.pushback.appendleft(nextchar) if self.debug >= 2: print("shlex: I see punctuation in word state") self.state = ' ' if self.token or (self.posix and quoted): break # emit current token else: continue result = self.token self.token = '' if self.posix and not quoted and result == '': result = None if self.debug > 1: if result: print("shlex: raw token=" + repr(result)) else: print("shlex: raw token=EOF") return result def sourcehook(self, newfile): "Hook called on a filename to be sourced." if newfile[0] == '"': newfile = newfile[1:-1] # This implements cpp-like semantics for relative-path inclusion. if isinstance(self.infile, str) and not os.path.isabs(newfile): newfile = os.path.join(os.path.dirname(self.infile), newfile) return (newfile, open(newfile, "r")) def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." if infile is None: infile = self.infile if lineno is None: lineno = self.lineno return "\"%s\", line %d: " % (infile, lineno) def __iter__(self): return self def __next__(self): token = self.get_token() if token == self.eof: raise StopIteration return token def split(s, comments=False, posix=True): lex = shlex(s, posix=posix) lex.whitespace_split = True if not comments: lex.commenters = '' return list(lex) _find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search def quote(s): """Return a shell-escaped version of the string *s*.""" if not s: return "''" if _find_unsafe(s) is None: return s # use single quotes, and put single quotes into double quotes # the string $'b is then quoted as '$'"'"'b' return "'" + s.replace("'", "'\"'\"'") + "'" def _print_tokens(lexer): while 1: tt = lexer.get_token() if not tt: break print("Token: " + repr(tt)) if __name__ == '__main__': if len(sys.argv) == 1: _print_tokens(shlex()) else: fn = sys.argv[1] with open(fn) as f: _print_tokens(shlex(f, fn))
12,956
336
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/string.py
"""A collection of string constants. Public module variables: whitespace -- a string containing all ASCII whitespace ascii_lowercase -- a string containing all ASCII lowercase letters ascii_uppercase -- a string containing all ASCII uppercase letters ascii_letters -- a string containing all ASCII letters digits -- a string containing all ASCII decimal digits hexdigits -- a string containing all ASCII hexadecimal digits octdigits -- a string containing all ASCII octal digits punctuation -- a string containing all ASCII punctuation characters printable -- a string containing all ASCII characters considered printable """ __all__ = ["ascii_letters", "ascii_lowercase", "ascii_uppercase", "capwords", "digits", "hexdigits", "octdigits", "printable", "punctuation", "whitespace", "Formatter", "Template"] import _string # Some strings for ctype-style character classification whitespace = ' \t\n\r\v\f' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_letters = ascii_lowercase + ascii_uppercase digits = '0123456789' hexdigits = digits + 'abcdef' + 'ABCDEF' octdigits = '01234567' punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" printable = digits + ascii_letters + punctuation + whitespace # Functions which aren't available as string methods. # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def". def capwords(s, sep=None): """capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words. """ return (sep or ' ').join(x.capitalize() for x in s.split(sep)) #################################################################### import re as _re from collections import ChainMap as _ChainMap class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE) class Template(metaclass=_TemplateMetaclass): """A string class for supporting $-substitutions.""" delimiter = '$' # r'[a-z]' matches to non-ASCII letters when used with IGNORECASE, # but without ASCII flag. We can't add re.ASCII to flags because of # backward compatibility. So we use local -i flag and [a-zA-Z] pattern. # See https://bugs.python.org/issue31672 idpattern = r'(?-i:[_a-zA-Z][_a-zA-Z0-9]*)' flags = _re.IGNORECASE def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(keepends=True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(*args, **kws): if not args: raise TypeError("descriptor 'substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: return str(mapping[named]) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(*args, **kws): if not args: raise TypeError("descriptor 'safe_substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') or mo.group('braced') if named is not None: try: return str(mapping[named]) except KeyError: return mo.group() if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return mo.group() raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) ######################################################################## # the Formatter class # see PEP 3101 for details and purpose of this class # The hard parts are reused from the C implementation. They're exposed as "_" # prefixed methods of str. # The overall parser is implemented in _string.formatter_parser. # The field name parser is implemented in _string.formatter_field_name_split class Formatter: def format(*args, **kwargs): if not args: raise TypeError("descriptor 'format' of 'Formatter' object " "needs an argument") self, *args = args # allow the "self" keyword be passed try: format_string, *args = args # allow the "format_string" keyword be passed except ValueError: if 'format_string' in kwargs: format_string = kwargs.pop('format_string') import warnings warnings.warn("Passing 'format_string' as keyword argument is " "deprecated", DeprecationWarning, stacklevel=2) else: raise TypeError("format() missing 1 required positional " "argument: 'format_string'") from None return self.vformat(format_string, args, kwargs) def vformat(self, format_string, args, kwargs): used_args = set() result, _ = self._vformat(format_string, args, kwargs, used_args, 2) self.check_unused_args(used_args, args, kwargs) return result def _vformat(self, format_string, args, kwargs, used_args, recursion_depth, auto_arg_index=0): if recursion_depth < 0: raise ValueError('Max string recursion exceeded') result = [] for literal_text, field_name, format_spec, conversion in \ self.parse(format_string): # output the literal text if literal_text: result.append(literal_text) # if there's a field, output it if field_name is not None: # this is some markup, find the object and do # the formatting # handle arg indexing when empty field_names are given. if field_name == '': if auto_arg_index is False: raise ValueError('cannot switch from manual field ' 'specification to automatic field ' 'numbering') field_name = str(auto_arg_index) auto_arg_index += 1 elif field_name.isdigit(): if auto_arg_index: raise ValueError('cannot switch from manual field ' 'specification to automatic field ' 'numbering') # disable auto arg incrementing, if it gets # used later on, then an exception will be raised auto_arg_index = False # given the field_name, find the object it references # and the argument it came from obj, arg_used = self.get_field(field_name, args, kwargs) used_args.add(arg_used) # do any conversion on the resulting object obj = self.convert_field(obj, conversion) # expand the format spec, if needed format_spec, auto_arg_index = self._vformat( format_spec, args, kwargs, used_args, recursion_depth-1, auto_arg_index=auto_arg_index) # format the object and append to the result result.append(self.format_field(obj, format_spec)) return ''.join(result), auto_arg_index def get_value(self, key, args, kwargs): if isinstance(key, int): return args[key] else: return kwargs[key] def check_unused_args(self, used_args, args, kwargs): pass def format_field(self, value, format_spec): return format(value, format_spec) def convert_field(self, value, conversion): # do any conversion on the resulting object if conversion is None: return value elif conversion == 's': return str(value) elif conversion == 'r': return repr(value) elif conversion == 'a': return ascii(value) raise ValueError("Unknown conversion specifier {0!s}".format(conversion)) # returns an iterable that contains tuples of the form: # (literal_text, field_name, format_spec, conversion) # literal_text can be zero length # field_name can be None, in which case there's no # object to format and output # if field_name is not None, it is looked up, formatted # with format_spec and conversion and then used def parse(self, format_string): return _string.formatter_parser(format_string) # given a field_name, find the object it references. # field_name: the field being looked up, e.g. "0.name" # or "lookup[3]" # used_args: a set of which args have been used # args, kwargs: as passed in to vformat def get_field(self, field_name, args, kwargs): first, rest = _string.formatter_field_name_split(field_name) obj = self.get_value(first, args, kwargs) # loop through the rest of the field_name, doing # getattr or getitem as needed for is_attr, i in rest: if is_attr: obj = getattr(obj, i) else: obj = obj[i] return obj, first
11,795
310
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/numbers.py
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) for numbers, according to PEP 3141. TODO: Fill out more detailed documentation on the operators.""" from abc import ABCMeta, abstractmethod __all__ = ["Number", "Complex", "Real", "Rational", "Integral"] class Number(metaclass=ABCMeta): """All numbers inherit from this class. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number). """ __slots__ = () # Concrete numeric types must provide their own hash implementation __hash__ = None ## Notes on Decimal ## ---------------- ## Decimal has all of the methods specified by the Real abc, but it should ## not be registered as a Real because decimals do not interoperate with ## binary floats (i.e. Decimal('3.14') + 2.71828 is undefined). But, ## abstract reals are expected to interoperate (i.e. R1 + R2 should be ## expected to work if R1 and R2 are both Reals). class Complex(Number): """Complex defines the operations that work on the builtin complex type. In short, those are: a conversion to complex, .real, .imag, +, -, *, /, abs(), .conjugate, ==, and !=. If it is given heterogenous arguments, and doesn't have special knowledge about them, it should fall back to the builtin complex type as described below. """ __slots__ = () @abstractmethod def __complex__(self): """Return a builtin complex instance. Called for complex(self).""" def __bool__(self): """True if self != 0. Called for bool(self).""" return self != 0 @property @abstractmethod def real(self): """Retrieve the real component of this number. This should subclass Real. """ raise NotImplementedError @property @abstractmethod def imag(self): """Retrieve the imaginary component of this number. This should subclass Real. """ raise NotImplementedError @abstractmethod def __add__(self, other): """self + other""" raise NotImplementedError @abstractmethod def __radd__(self, other): """other + self""" raise NotImplementedError @abstractmethod def __neg__(self): """-self""" raise NotImplementedError @abstractmethod def __pos__(self): """+self""" raise NotImplementedError def __sub__(self, other): """self - other""" return self + -other def __rsub__(self, other): """other - self""" return -self + other @abstractmethod def __mul__(self, other): """self * other""" raise NotImplementedError @abstractmethod def __rmul__(self, other): """other * self""" raise NotImplementedError @abstractmethod def __truediv__(self, other): """self / other: Should promote to float when necessary.""" raise NotImplementedError @abstractmethod def __rtruediv__(self, other): """other / self""" raise NotImplementedError @abstractmethod def __pow__(self, exponent): """self**exponent; should promote to float or complex when necessary.""" raise NotImplementedError @abstractmethod def __rpow__(self, base): """base ** self""" raise NotImplementedError @abstractmethod def __abs__(self): """Returns the Real distance from 0. Called for abs(self).""" raise NotImplementedError @abstractmethod def conjugate(self): """(x+y*i).conjugate() returns (x-y*i).""" raise NotImplementedError @abstractmethod def __eq__(self, other): """self == other""" raise NotImplementedError Complex.register(complex) class Real(Complex): """To Complex, Real adds the operations that work on real numbers. In short, those are: a conversion to float, trunc(), divmod, %, <, <=, >, and >=. Real also provides defaults for the derived operations. """ __slots__ = () @abstractmethod def __float__(self): """Any Real can be converted to a native float object. Called for float(self).""" raise NotImplementedError @abstractmethod def __trunc__(self): """trunc(self): Truncates self to an Integral. Returns an Integral i such that: * i>0 iff self>0; * abs(i) <= abs(self); * for any Integral j satisfying the first two conditions, abs(i) >= abs(j) [i.e. i has "maximal" abs among those]. i.e. "truncate towards 0". """ raise NotImplementedError @abstractmethod def __floor__(self): """Finds the greatest Integral <= self.""" raise NotImplementedError @abstractmethod def __ceil__(self): """Finds the least Integral >= self.""" raise NotImplementedError @abstractmethod def __round__(self, ndigits=None): """Rounds self to ndigits decimal places, defaulting to 0. If ndigits is omitted or None, returns an Integral, otherwise returns a Real. Rounds half toward even. """ raise NotImplementedError def __divmod__(self, other): """divmod(self, other): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations. """ return (self // other, self % other) def __rdivmod__(self, other): """divmod(other, self): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations. """ return (other // self, other % self) @abstractmethod def __floordiv__(self, other): """self // other: The floor() of self/other.""" raise NotImplementedError @abstractmethod def __rfloordiv__(self, other): """other // self: The floor() of other/self.""" raise NotImplementedError @abstractmethod def __mod__(self, other): """self % other""" raise NotImplementedError @abstractmethod def __rmod__(self, other): """other % self""" raise NotImplementedError @abstractmethod def __lt__(self, other): """self < other < on Reals defines a total ordering, except perhaps for NaN.""" raise NotImplementedError @abstractmethod def __le__(self, other): """self <= other""" raise NotImplementedError # Concrete implementations of Complex abstract methods. def __complex__(self): """complex(self) == complex(float(self), 0)""" return complex(float(self)) @property def real(self): """Real numbers are their real component.""" return +self @property def imag(self): """Real numbers have no imaginary component.""" return 0 def conjugate(self): """Conjugate is a no-op for Reals.""" return +self Real.register(float) class Rational(Real): """.numerator and .denominator should be in lowest terms.""" __slots__ = () @property @abstractmethod def numerator(self): raise NotImplementedError @property @abstractmethod def denominator(self): raise NotImplementedError # Concrete implementation of Real's conversion to float. def __float__(self): """float(self) = self.numerator / self.denominator It's important that this conversion use the integer's "true" division rather than casting one side to float before dividing so that ratios of huge integers convert without overflowing. """ return self.numerator / self.denominator class Integral(Rational): """Integral adds a conversion to int and the bit-string operations.""" __slots__ = () @abstractmethod def __int__(self): """int(self)""" raise NotImplementedError def __index__(self): """Called whenever an index is needed, such as in slicing""" return int(self) @abstractmethod def __pow__(self, exponent, modulus=None): """self ** exponent % modulus, but maybe faster. Accept the modulus argument if you want to support the 3-argument version of pow(). Raise a TypeError if exponent < 0 or any argument isn't Integral. Otherwise, just implement the 2-argument version described in Complex. """ raise NotImplementedError @abstractmethod def __lshift__(self, other): """self << other""" raise NotImplementedError @abstractmethod def __rlshift__(self, other): """other << self""" raise NotImplementedError @abstractmethod def __rshift__(self, other): """self >> other""" raise NotImplementedError @abstractmethod def __rrshift__(self, other): """other >> self""" raise NotImplementedError @abstractmethod def __and__(self, other): """self & other""" raise NotImplementedError @abstractmethod def __rand__(self, other): """other & self""" raise NotImplementedError @abstractmethod def __xor__(self, other): """self ^ other""" raise NotImplementedError @abstractmethod def __rxor__(self, other): """other ^ self""" raise NotImplementedError @abstractmethod def __or__(self, other): """self | other""" raise NotImplementedError @abstractmethod def __ror__(self, other): """other | self""" raise NotImplementedError @abstractmethod def __invert__(self): """~self""" raise NotImplementedError # Concrete implementations of Rational and Real abstract methods. def __float__(self): """float(self) == float(int(self))""" return float(int(self)) @property def numerator(self): """Integers are their own numerators.""" return +self @property def denominator(self): """Integers have a denominator of 1.""" return 1 Integral.register(int)
10,243
390
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/imghdr.py
"""Recognize image file formats based on their first few bytes.""" from os import PathLike __all__ = ["what"] #-------------------------# # Recognize image headers # #-------------------------# def what(file, h=None): f = None try: if h is None: if isinstance(file, (str, PathLike)): f = open(file, 'rb') h = f.read(32) else: location = file.tell() h = file.read(32) file.seek(location) for tf in tests: res = tf(h, f) if res: return res finally: if f: f.close() return None #---------------------------------# # Subroutines per image file type # #---------------------------------# tests = [] def test_jpeg(h, f): """JPEG data in JFIF or Exif format""" if h[6:10] in (b'JFIF', b'Exif'): return 'jpeg' tests.append(test_jpeg) def test_png(h, f): if h.startswith(b'\211PNG\r\n\032\n'): return 'png' tests.append(test_png) def test_gif(h, f): """GIF ('87 and '89 variants)""" if h[:6] in (b'GIF87a', b'GIF89a'): return 'gif' tests.append(test_gif) def test_tiff(h, f): """TIFF (can be in Motorola or Intel byte order)""" if h[:2] in (b'MM', b'II'): return 'tiff' tests.append(test_tiff) def test_rgb(h, f): """SGI image library""" if h.startswith(b'\001\332'): return 'rgb' tests.append(test_rgb) def test_pbm(h, f): """PBM (portable bitmap)""" if len(h) >= 3 and \ h[0] == ord(b'P') and h[1] in b'14' and h[2] in b' \t\n\r': return 'pbm' tests.append(test_pbm) def test_pgm(h, f): """PGM (portable graymap)""" if len(h) >= 3 and \ h[0] == ord(b'P') and h[1] in b'25' and h[2] in b' \t\n\r': return 'pgm' tests.append(test_pgm) def test_ppm(h, f): """PPM (portable pixmap)""" if len(h) >= 3 and \ h[0] == ord(b'P') and h[1] in b'36' and h[2] in b' \t\n\r': return 'ppm' tests.append(test_ppm) def test_rast(h, f): """Sun raster file""" if h.startswith(b'\x59\xA6\x6A\x95'): return 'rast' tests.append(test_rast) def test_xbm(h, f): """X bitmap (X10 or X11)""" if h.startswith(b'#define '): return 'xbm' tests.append(test_xbm) def test_bmp(h, f): if h.startswith(b'BM'): return 'bmp' tests.append(test_bmp) def test_webp(h, f): if h.startswith(b'RIFF') and h[8:12] == b'WEBP': return 'webp' tests.append(test_webp) def test_exr(h, f): if h.startswith(b'\x76\x2f\x31\x01'): return 'exr' tests.append(test_exr) #--------------------# # Small test program # #--------------------# def test(): import sys recursive = 0 if sys.argv[1:] and sys.argv[1] == '-r': del sys.argv[1:2] recursive = 1 try: if sys.argv[1:]: testall(sys.argv[1:], recursive, 1) else: testall(['.'], recursive, 1) except KeyboardInterrupt: sys.stderr.write('\n[Interrupted]\n') sys.exit(1) def testall(list, recursive, toplevel): import sys import os for filename in list: if os.path.isdir(filename): print(filename + '/:', end=' ') if recursive or toplevel: print('recursing down:') import glob names = glob.glob(os.path.join(filename, '*')) testall(names, recursive, 0) else: print('*** directory (use -r) ***') else: print(filename + ':', end=' ') sys.stdout.flush() try: print(what(filename)) except OSError: print('*** not found ***') if __name__ == '__main__': test()
3,795
169
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/mailcap.py
"""Mailcap file handling. See RFC 1524.""" import os import warnings __all__ = ["getcaps","findmatch"] def lineno_sort_key(entry): # Sort in ascending order, with unspecified entries at the end if 'lineno' in entry: return 0, entry['lineno'] else: return 1, 0 # Part 1: top-level interface. def getcaps(): """Return a dictionary containing the mailcap database. The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain') to a list of dictionaries corresponding to mailcap entries. The list collects all the entries for that MIME type from all available mailcap files. Each dictionary contains key-value pairs for that MIME type, where the viewing command is stored with the key "view". """ caps = {} lineno = 0 for mailcap in listmailcapfiles(): try: fp = open(mailcap, 'r') except OSError: continue with fp: morecaps, lineno = _readmailcapfile(fp, lineno) for key, value in morecaps.items(): if not key in caps: caps[key] = value else: caps[key] = caps[key] + value return caps def listmailcapfiles(): """Return a list of all mailcap files found on the system.""" # This is mostly a Unix thing, but we use the OS path separator anyway if 'MAILCAPS' in os.environ: pathstr = os.environ['MAILCAPS'] mailcaps = pathstr.split(os.pathsep) else: if 'HOME' in os.environ: home = os.environ['HOME'] else: # Don't bother with getpwuid() home = '.' # Last resort mailcaps = [home + '/.mailcap', '/etc/mailcap', '/usr/etc/mailcap', '/usr/local/etc/mailcap'] return mailcaps # Part 2: the parser. def readmailcapfile(fp): """Read a mailcap file and return a dictionary keyed by MIME type.""" warnings.warn('readmailcapfile is deprecated, use getcaps instead', DeprecationWarning, 2) caps, _ = _readmailcapfile(fp, None) return caps def _readmailcapfile(fp, lineno): """Read a mailcap file and return a dictionary keyed by MIME type. Each MIME type is mapped to an entry consisting of a list of dictionaries; the list will contain more than one such dictionary if a given MIME type appears more than once in the mailcap file. Each dictionary contains key-value pairs for that MIME type, where the viewing command is stored with the key "view". """ caps = {} while 1: line = fp.readline() if not line: break # Ignore comments and blank lines if line[0] == '#' or line.strip() == '': continue nextline = line # Join continuation lines while nextline[-2:] == '\\\n': nextline = fp.readline() if not nextline: nextline = '\n' line = line[:-2] + nextline # Parse the line key, fields = parseline(line) if not (key and fields): continue if lineno is not None: fields['lineno'] = lineno lineno += 1 # Normalize the key types = key.split('/') for j in range(len(types)): types[j] = types[j].strip() key = '/'.join(types).lower() # Update the database if key in caps: caps[key].append(fields) else: caps[key] = [fields] return caps, lineno def parseline(line): """Parse one entry in a mailcap file and return a dictionary. The viewing command is stored as the value with the key "view", and the rest of the fields produce key-value pairs in the dict. """ fields = [] i, n = 0, len(line) while i < n: field, i = parsefield(line, i, n) fields.append(field) i = i+1 # Skip semicolon if len(fields) < 2: return None, None key, view, rest = fields[0], fields[1], fields[2:] fields = {'view': view} for field in rest: i = field.find('=') if i < 0: fkey = field fvalue = "" else: fkey = field[:i].strip() fvalue = field[i+1:].strip() if fkey in fields: # Ignore it pass else: fields[fkey] = fvalue return key, fields def parsefield(line, i, n): """Separate one key-value pair in a mailcap entry.""" start = i while i < n: c = line[i] if c == ';': break elif c == '\\': i = i+2 else: i = i+1 return line[start:i].strip(), i # Part 3: using the database. def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]): """Find a match for a mailcap entry. Return a tuple containing the command line, and the mailcap entry used; (None, None) if no match is found. This may invoke the 'test' command of several matching entries before deciding which entry to use. """ entries = lookup(caps, MIMEtype, key) # XXX This code should somehow check for the needsterminal flag. for e in entries: if 'test' in e: test = subst(e['test'], filename, plist) if test and os.system(test) != 0: continue command = subst(e[key], MIMEtype, filename, plist) return command, e return None, None def lookup(caps, MIMEtype, key=None): entries = [] if MIMEtype in caps: entries = entries + caps[MIMEtype] MIMEtypes = MIMEtype.split('/') MIMEtype = MIMEtypes[0] + '/*' if MIMEtype in caps: entries = entries + caps[MIMEtype] if key is not None: entries = [e for e in entries if key in e] entries = sorted(entries, key=lineno_sort_key) return entries def subst(field, MIMEtype, filename, plist=[]): # XXX Actually, this is Unix-specific res = '' i, n = 0, len(field) while i < n: c = field[i]; i = i+1 if c != '%': if c == '\\': c = field[i:i+1]; i = i+1 res = res + c else: c = field[i]; i = i+1 if c == '%': res = res + c elif c == 's': res = res + filename elif c == 't': res = res + MIMEtype elif c == '{': start = i while i < n and field[i] != '}': i = i+1 name = field[start:i] i = i+1 res = res + findparam(name, plist) # XXX To do: # %n == number of parts if type is multipart/* # %F == list of alternating type and filename for parts else: res = res + '%' + c return res def findparam(name, plist): name = name.lower() + '=' n = len(name) for p in plist: if p[:n].lower() == name: return p[n:] return '' # Part 4: test program. def test(): import sys caps = getcaps() if not sys.argv[1:]: show(caps) return for i in range(1, len(sys.argv), 2): args = sys.argv[i:i+2] if len(args) < 2: print("usage: mailcap [MIMEtype file] ...") return MIMEtype = args[0] file = args[1] command, e = findmatch(caps, MIMEtype, 'view', file) if not command: print("No viewer found for", type) else: print("Executing:", command) sts = os.system(command) if sts: print("Exit status:", sts) def show(caps): print("Mailcap files:") for fn in listmailcapfiles(): print("\t" + fn) print() if not caps: caps = getcaps() print("Mailcap entries:") print() ckeys = sorted(caps) for type in ckeys: print(type) entries = caps[type] for e in entries: keys = sorted(e) for k in keys: print(" %-15s" % k, e[k]) print() if __name__ == '__main__': test()
8,104
276
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/runpy.py
"""runpy.py - locating and running Python code using the module namespace Provides support for locating and running Python scripts using the Python module namespace instead of the native filesystem. This allows Python code to play nicely with non-filesystem based PEP 302 importers when locating support scripts as well as when importing modules. """ # Written by Nick Coghlan <ncoghlan at gmail.com> # to implement PEP 338 (Executing Modules as Scripts) import sys import importlib.machinery # importlib first so we can test #15386 via -m import importlib.util import types from pkgutil import read_code, get_importer __all__ = [ "run_module", "run_path", ] class _TempModule(object): """Temporarily replace a module in sys.modules with an empty namespace""" def __init__(self, mod_name): self.mod_name = mod_name self.module = types.ModuleType(mod_name) self._saved_module = [] def __enter__(self): mod_name = self.mod_name try: self._saved_module.append(sys.modules[mod_name]) except KeyError: pass sys.modules[mod_name] = self.module return self def __exit__(self, *args): if self._saved_module: sys.modules[self.mod_name] = self._saved_module[0] else: del sys.modules[self.mod_name] self._saved_module = [] class _ModifiedArgv0(object): def __init__(self, value): self.value = value self._saved_value = self._sentinel = object() def __enter__(self): if self._saved_value is not self._sentinel: raise RuntimeError("Already preserving saved value") self._saved_value = sys.argv[0] sys.argv[0] = self.value def __exit__(self, *args): self.value = self._sentinel sys.argv[0] = self._saved_value # TODO: Replace these helpers with importlib._bootstrap_external functions. def _run_code(code, run_globals, init_globals=None, mod_name=None, mod_spec=None, pkg_name=None, script_name=None): """Helper to run code in nominated namespace""" if init_globals is not None: run_globals.update(init_globals) if mod_spec is None: loader = None fname = script_name cached = None else: loader = mod_spec.loader fname = mod_spec.origin cached = mod_spec.cached if pkg_name is None: pkg_name = mod_spec.parent run_globals.update(__name__ = mod_name, __file__ = fname, __cached__ = cached, __doc__ = None, __loader__ = loader, __package__ = pkg_name, __spec__ = mod_spec) exec(code, run_globals) return run_globals def _run_module_code(code, init_globals=None, mod_name=None, mod_spec=None, pkg_name=None, script_name=None): """Helper to run code in new namespace with sys modified""" fname = script_name if mod_spec is None else mod_spec.origin with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname): mod_globals = temp_module.module.__dict__ _run_code(code, mod_globals, init_globals, mod_name, mod_spec, pkg_name, script_name) # Copy the globals of the temporary module, as they # may be cleared when the temporary module goes away return mod_globals.copy() # Helper to get the full name, spec and code for a module def _get_module_details(mod_name, error=ImportError): if mod_name.startswith("."): raise error("Relative module names not supported") pkg_name, _, _ = mod_name.rpartition(".") if pkg_name: # Try importing the parent to avoid catching initialization errors try: __import__(pkg_name) except ImportError as e: # If the parent or higher ancestor package is missing, let the # error be raised by find_spec() below and then be caught. But do # not allow other errors to be caught. if e.name is None or (e.name != pkg_name and not pkg_name.startswith(e.name + ".")): raise # Warn if the module has already been imported under its normal name existing = sys.modules.get(mod_name) if existing is not None and not hasattr(existing, "__path__"): from warnings import warn msg = "{mod_name!r} found in sys.modules after import of " \ "package {pkg_name!r}, but prior to execution of " \ "{mod_name!r}; this may result in unpredictable " \ "behaviour".format(mod_name=mod_name, pkg_name=pkg_name) warn(RuntimeWarning(msg)) try: spec = importlib.util.find_spec(mod_name) except (ImportError, AttributeError, TypeError, ValueError) as ex: # This hack fixes an impedance mismatch between pkgutil and # importlib, where the latter raises other errors for cases where # pkgutil previously raised ImportError msg = "Error while finding module specification for {!r} ({}: {})" raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex if spec is None: raise error("No module named %s" % mod_name) if spec.submodule_search_locations is not None: if mod_name == "__main__" or mod_name.endswith(".__main__"): raise error("Cannot use package as __main__ module") try: pkg_main_name = mod_name + ".__main__" return _get_module_details(pkg_main_name, error) except error as e: if mod_name not in sys.modules: raise # No module loaded; being a package is irrelevant raise error(("%s; %r is a package and cannot " + "be directly executed") %(e, mod_name)) loader = spec.loader if loader is None: raise error("%r is a namespace package and cannot be executed" % mod_name) try: code = loader.get_code(mod_name) except ImportError as e: raise error(format(e)) from e if code is None: raise error("No code object available for %s" % mod_name) return mod_name, spec, code class _Error(Exception): """Error that _run_module_as_main() should report without a traceback""" # XXX ncoghlan: Should this be documented and made public? # (Current thoughts: don't repeat the mistake that lead to its # creation when run_module() no longer met the needs of # mainmodule.c, but couldn't be changed because it was public) def _run_module_as_main(mod_name, alter_argv=True): """Runs the designated module in the __main__ namespace Note that the executed module will have full access to the __main__ namespace. If this is not desirable, the run_module() function should be used to run the module code in a fresh namespace. At the very least, these variables in __main__ will be overwritten: __name__ __file__ __cached__ __loader__ __package__ """ try: if alter_argv or mod_name != "__main__": # i.e. -m switch mod_name, mod_spec, code = _get_module_details(mod_name, _Error) else: # i.e. directory or zipfile execution mod_name, mod_spec, code = _get_main_module_details(_Error) except _Error as exc: msg = "%s: %s" % (sys.executable, exc) sys.exit(msg) main_globals = sys.modules["__main__"].__dict__ if alter_argv: sys.argv[0] = mod_spec.origin return _run_code(code, main_globals, None, "__main__", mod_spec) def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False): """Execute a module's code without importing it Returns the resulting top level namespace dictionary """ mod_name, mod_spec, code = _get_module_details(mod_name) if run_name is None: run_name = mod_name if alter_sys: return _run_module_code(code, init_globals, run_name, mod_spec) else: # Leave the sys module alone return _run_code(code, {}, init_globals, run_name, mod_spec) def _get_main_module_details(error=ImportError): # Helper that gives a nicer error message when attempting to # execute a zipfile or directory by invoking __main__.py # Also moves the standard __main__ out of the way so that the # preexisting __loader__ entry doesn't cause issues main_name = "__main__" saved_main = sys.modules[main_name] del sys.modules[main_name] try: return _get_module_details(main_name) except ImportError as exc: if main_name in str(exc): raise error("can't find %r module in %r" % (main_name, sys.path[0])) from exc raise finally: sys.modules[main_name] = saved_main def _get_code_from_file(run_name, fname): # Check for a compiled file first with open(fname, "rb") as f: code = read_code(f) if code is None: # That didn't work, so try it as normal source code with open(fname, "rb") as f: code = compile(f.read(), fname, 'exec') return code, fname def run_path(path_name, init_globals=None, run_name=None): """Execute code located at the specified filesystem location Returns the resulting top level namespace dictionary The file path may refer directly to a Python script (i.e. one that could be directly executed with execfile) or else it may refer to a zipfile or directory containing a top level __main__.py script. """ if run_name is None: run_name = "<run_path>" pkg_name = run_name.rpartition(".")[0] importer = get_importer(path_name) # Trying to avoid importing imp so as to not consume the deprecation warning. is_NullImporter = False if type(importer).__module__ == 'imp': if type(importer).__name__ == 'NullImporter': is_NullImporter = True if isinstance(importer, type(None)) or is_NullImporter: # Not a valid sys.path entry, so run the code directly # execfile() doesn't help as we want to allow compiled files code, fname = _get_code_from_file(run_name, path_name) return _run_module_code(code, init_globals, run_name, pkg_name=pkg_name, script_name=fname) else: # Finder is defined for path, so add it to # the start of sys.path sys.path.insert(0, path_name) try: # Here's where things are a little different from the run_module # case. There, we only had to replace the module in sys while the # code was running and doing so was somewhat optional. Here, we # have no choice and we have to remove it even while we read the # code. If we don't do this, a __loader__ attribute in the # existing __main__ module may prevent location of the new module. mod_name, mod_spec, code = _get_main_module_details() with _TempModule(run_name) as temp_module, \ _ModifiedArgv0(path_name): mod_globals = temp_module.module.__dict__ return _run_code(code, mod_globals, init_globals, run_name, mod_spec, pkg_name).copy() finally: try: sys.path.remove(path_name) except ValueError: pass if __name__ == "__main__": # Run the module specified as the next command line argument if len(sys.argv) < 2: print("No module specified for execution", file=sys.stderr) else: del sys.argv[0] # Make the requested module sys.argv[0] _run_module_as_main(sys.argv[0])
11,959
295
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/gettext.py
"""Internationalization and localization support. This module provides internationalization (I18N) and localization (L10N) support for your Python programs by providing an interface to the GNU gettext message catalog library. I18N refers to the operation by which a program is made aware of multiple languages. L10N refers to the adaptation of your program, once internationalized, to the local language and cultural habits. """ # This module represents the integration of work, contributions, feedback, and # suggestions from the following people: # # Martin von Loewis, who wrote the initial implementation of the underlying # C-based libintlmodule (later renamed _gettext), along with a skeletal # gettext.py implementation. # # Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule, # which also included a pure-Python implementation to read .mo files if # intlmodule wasn't available. # # James Henstridge, who also wrote a gettext.py module, which has some # interesting, but currently unsupported experimental features: the notion of # a Catalog class and instances, and the ability to add to a catalog file via # a Python API. # # Barry Warsaw integrated these modules, wrote the .install() API and code, # and conformed all C and Python code to Python's coding standards. # # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this # module. # # J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs. # # TODO: # - Lazy loading of .mo files. Currently the entire catalog is loaded into # memory, but that's probably bad for large translated programs. Instead, # the lexical sort of original strings in GNU .mo files should be exploited # to do binary searches and lazy initializations. Or you might want to use # the undocumented double-hash algorithm for .mo files with hash tables, but # you'll need to study the GNU gettext code to do this. # # - Support Solaris .mo file formats. Unfortunately, we've been unable to # find this format documented anywhere. import locale, copy, io, os, re, struct, sys from errno import ENOENT __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog', 'find', 'translation', 'install', 'textdomain', 'bindtextdomain', 'bind_textdomain_codeset', 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext', 'ldngettext', 'lngettext', 'ngettext', ] _default_localedir = os.path.join(sys.base_prefix, 'share', 'locale') # Expression parsing for plural form selection. # # The gettext library supports a small subset of C syntax. The only # incompatible difference is that integer literals starting with zero are # decimal. # # https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms # http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y _token_pattern = re.compile(r""" (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs (?P<NUMBER>[0-9]+\b) | # decimal integer (?P<NAME>n\b) | # only n is allowed (?P<PARENTHESIS>[()]) | (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >, # <=, >=, ==, !=, &&, ||, # ? : # unary and bitwise ops # not allowed (?P<INVALID>\w+|.) # invalid token """, re.VERBOSE|re.DOTALL) def _tokenize(plural): for mo in re.finditer(_token_pattern, plural): kind = mo.lastgroup if kind == 'WHITESPACES': continue value = mo.group(kind) if kind == 'INVALID': raise ValueError('invalid token in plural form: %s' % value) yield value yield '' def _error(value): if value: return ValueError('unexpected token in plural form: %s' % value) else: return ValueError('unexpected end of plural form') _binary_ops = ( ('||',), ('&&',), ('==', '!='), ('<', '>', '<=', '>='), ('+', '-'), ('*', '/', '%'), ) _binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops} _c2py_ops = {'||': 'or', '&&': 'and', '/': '//'} def _parse(tokens, priority=-1): result = '' nexttok = next(tokens) while nexttok == '!': result += 'not ' nexttok = next(tokens) if nexttok == '(': sub, nexttok = _parse(tokens) result = '%s(%s)' % (result, sub) if nexttok != ')': raise ValueError('unbalanced parenthesis in plural form') elif nexttok == 'n': result = '%s%s' % (result, nexttok) else: try: value = int(nexttok, 10) except ValueError: raise _error(nexttok) from None result = '%s%d' % (result, value) nexttok = next(tokens) j = 100 while nexttok in _binary_ops: i = _binary_ops[nexttok] if i < priority: break # Break chained comparisons if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>=' result = '(%s)' % result # Replace some C operators by their Python equivalents op = _c2py_ops.get(nexttok, nexttok) right, nexttok = _parse(tokens, i + 1) result = '%s %s %s' % (result, op, right) j = i if j == priority == 4: # '<', '>', '<=', '>=' result = '(%s)' % result if nexttok == '?' and priority <= 0: if_true, nexttok = _parse(tokens, 0) if nexttok != ':': raise _error(nexttok) if_false, nexttok = _parse(tokens) result = '%s if %s else %s' % (if_true, result, if_false) if priority == 0: result = '(%s)' % result return result, nexttok def _as_int(n): try: i = round(n) except TypeError: raise TypeError('Plural value must be an integer, got %s' % (n.__class__.__name__,)) from None return n def c2py(plural): """Gets a C expression as used in PO files for plural forms and returns a Python function that implements an equivalent expression. """ if len(plural) > 1000: raise ValueError('plural form expression is too long') try: result, nexttok = _parse(_tokenize(plural)) if nexttok: raise _error(nexttok) depth = 0 for c in result: if c == '(': depth += 1 if depth > 20: # Python compiler limit is about 90. # The most complex example has 2. raise ValueError('plural form expression is too complex') elif c == ')': depth -= 1 ns = {'_as_int': _as_int} exec('''if True: def func(n): if not isinstance(n, int): n = _as_int(n) return int(%s) ''' % result, ns) return ns['func'] except RecursionError: # Recursion error can be raised in _parse() or exec(). raise ValueError('plural form expression is too complex') def _expand_lang(loc): loc = locale.normalize(loc) COMPONENT_CODESET = 1 << 0 COMPONENT_TERRITORY = 1 << 1 COMPONENT_MODIFIER = 1 << 2 # split up the locale into its base components mask = 0 pos = loc.find('@') if pos >= 0: modifier = loc[pos:] loc = loc[:pos] mask |= COMPONENT_MODIFIER else: modifier = '' pos = loc.find('.') if pos >= 0: codeset = loc[pos:] loc = loc[:pos] mask |= COMPONENT_CODESET else: codeset = '' pos = loc.find('_') if pos >= 0: territory = loc[pos:] loc = loc[:pos] mask |= COMPONENT_TERRITORY else: territory = '' language = loc ret = [] for i in range(mask+1): if not (i & ~mask): # if all components for this combo exist ... val = language if i & COMPONENT_TERRITORY: val += territory if i & COMPONENT_CODESET: val += codeset if i & COMPONENT_MODIFIER: val += modifier ret.append(val) ret.reverse() return ret class NullTranslations: def __init__(self, fp=None): self._info = {} self._charset = None self._output_charset = None self._fallback = None if fp is not None: self._parse(fp) def _parse(self, fp): pass def add_fallback(self, fallback): if self._fallback: self._fallback.add_fallback(fallback) else: self._fallback = fallback def gettext(self, message): if self._fallback: return self._fallback.gettext(message) return message def lgettext(self, message): if self._fallback: return self._fallback.lgettext(message) if self._output_charset: return message.encode(self._output_charset) return message.encode(locale.getpreferredencoding()) def ngettext(self, msgid1, msgid2, n): if self._fallback: return self._fallback.ngettext(msgid1, msgid2, n) if n == 1: return msgid1 else: return msgid2 def lngettext(self, msgid1, msgid2, n): if self._fallback: return self._fallback.lngettext(msgid1, msgid2, n) if n == 1: tmsg = msgid1 else: tmsg = msgid2 if self._output_charset: return tmsg.encode(self._output_charset) return tmsg.encode(locale.getpreferredencoding()) def info(self): return self._info def charset(self): return self._charset def output_charset(self): return self._output_charset def set_output_charset(self, charset): self._output_charset = charset def install(self, names=None): import builtins builtins.__dict__['_'] = self.gettext if hasattr(names, "__contains__"): if "gettext" in names: builtins.__dict__['gettext'] = builtins.__dict__['_'] if "ngettext" in names: builtins.__dict__['ngettext'] = self.ngettext if "lgettext" in names: builtins.__dict__['lgettext'] = self.lgettext if "lngettext" in names: builtins.__dict__['lngettext'] = self.lngettext class GNUTranslations(NullTranslations): # Magic number of .mo files LE_MAGIC = 0x950412de BE_MAGIC = 0xde120495 # Acceptable .mo versions VERSIONS = (0, 1) def _get_versions(self, version): """Returns a tuple of major version, minor version""" return (version >> 16, version & 0xffff) def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} self.plural = lambda n: int(n != 1) # germanic plural by default buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<I', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20]) ii = '<II' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20]) ii = '>II' else: raise OSError(0, 'Bad magic number', filename) major_version, minor_version = self._get_versions(version) if major_version not in self.VERSIONS: raise OSError(0, 'Bad version number ' + str(major_version), filename) # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in range(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < buflen and tend < buflen: msg = buf[moff:mend] tmsg = buf[toff:tend] else: raise OSError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0: # Catalog description lastk = None for b_item in tmsg.split(b'\n'): item = b_item.decode().strip() if not item: continue k = v = None if ':' in item: k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v lastk = k elif lastk: self._info[lastk] += '\n' + item if k == 'content-type': self._charset = v.split('charset=')[1] elif k == 'plural-forms': v = v.split(';') plural = v[1].split('plural=')[1] self.plural = c2py(plural) # Note: we unconditionally convert both msgids and msgstrs to # Unicode using the character encoding specified in the charset # parameter of the Content-Type header. The gettext documentation # strongly encourages msgids to be us-ascii, but some applications # require alternative encodings (e.g. Zope's ZCML and ZPT). For # traditional gettext applications, the msgid conversion will # cause no problems since us-ascii should always be a subset of # the charset encoding. We may want to fall back to 8-bit msgids # if the Unicode conversion fails. charset = self._charset or 'ascii' if b'\x00' in msg: # Plural forms msgid1, msgid2 = msg.split(b'\x00') tmsg = tmsg.split(b'\x00') msgid1 = str(msgid1, charset) for i, x in enumerate(tmsg): catalog[(msgid1, i)] = str(x, charset) else: catalog[str(msg, charset)] = str(tmsg, charset) # advance to next entry in the seek tables masteridx += 8 transidx += 8 def lgettext(self, message): missing = object() tmsg = self._catalog.get(message, missing) if tmsg is missing: if self._fallback: return self._fallback.lgettext(message) tmsg = message if self._output_charset: return tmsg.encode(self._output_charset) return tmsg.encode(locale.getpreferredencoding()) def lngettext(self, msgid1, msgid2, n): try: tmsg = self._catalog[(msgid1, self.plural(n))] except KeyError: if self._fallback: return self._fallback.lngettext(msgid1, msgid2, n) if n == 1: tmsg = msgid1 else: tmsg = msgid2 if self._output_charset: return tmsg.encode(self._output_charset) return tmsg.encode(locale.getpreferredencoding()) def gettext(self, message): missing = object() tmsg = self._catalog.get(message, missing) if tmsg is missing: if self._fallback: return self._fallback.gettext(message) return message return tmsg def ngettext(self, msgid1, msgid2, n): try: tmsg = self._catalog[(msgid1, self.plural(n))] except KeyError: if self._fallback: return self._fallback.ngettext(msgid1, msgid2, n) if n == 1: tmsg = msgid1 else: tmsg = msgid2 return tmsg # Locate a .mo file using the gettext strategy def find(domain, localedir=None, languages=None, all=False): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages nelangs = [] for lang in languages: for nelang in _expand_lang(lang): if nelang not in nelangs: nelangs.append(nelang) # select a language if all: result = [] else: result = None for lang in nelangs: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): if all: result.append(mofile) else: return mofile return result # a mapping between absolute .mo file path and Translation object _translations = {} def translation(domain, localedir=None, languages=None, class_=None, fallback=False, codeset=None): if class_ is None: class_ = GNUTranslations mofiles = find(domain, localedir, languages, all=True) if not mofiles: if fallback: return NullTranslations() raise OSError(ENOENT, 'No translation file found for domain', domain) # Avoid opening, reading, and parsing the .mo file after it's been done # once. result = None for mofile in mofiles: key = (class_, os.path.abspath(mofile)) t = _translations.get(key) if t is None: with open(mofile, 'rb') as fp: t = _translations.setdefault(key, class_(fp)) # Copy the translation object to allow setting fallbacks and # output charset. All other instance data is shared with the # cached object. t = copy.copy(t) if codeset: t.set_output_charset(codeset) if result is None: result = t else: result.add_fallback(t) return result def install(domain, localedir=None, codeset=None, names=None): t = translation(domain, localedir, fallback=True, codeset=codeset) t.install(names) # a mapping b/w domains and locale directories _localedirs = {} # a mapping b/w domains and codesets _localecodesets = {} # current global domain, `messages' used for compatibility w/ GNU gettext _current_domain = 'messages' def textdomain(domain=None): global _current_domain if domain is not None: _current_domain = domain return _current_domain def bindtextdomain(domain, localedir=None): global _localedirs if localedir is not None: _localedirs[domain] = localedir return _localedirs.get(domain, _default_localedir) def bind_textdomain_codeset(domain, codeset=None): global _localecodesets if codeset is not None: _localecodesets[domain] = codeset return _localecodesets.get(domain) def dgettext(domain, message): try: t = translation(domain, _localedirs.get(domain, None), codeset=_localecodesets.get(domain)) except OSError: return message return t.gettext(message) def ldgettext(domain, message): codeset = _localecodesets.get(domain) try: t = translation(domain, _localedirs.get(domain, None), codeset=codeset) except OSError: return message.encode(codeset or locale.getpreferredencoding()) return t.lgettext(message) def dngettext(domain, msgid1, msgid2, n): try: t = translation(domain, _localedirs.get(domain, None), codeset=_localecodesets.get(domain)) except OSError: if n == 1: return msgid1 else: return msgid2 return t.ngettext(msgid1, msgid2, n) def ldngettext(domain, msgid1, msgid2, n): codeset = _localecodesets.get(domain) try: t = translation(domain, _localedirs.get(domain, None), codeset=codeset) except OSError: if n == 1: tmsg = msgid1 else: tmsg = msgid2 return tmsg.encode(codeset or locale.getpreferredencoding()) return t.lngettext(msgid1, msgid2, n) def gettext(message): return dgettext(_current_domain, message) def lgettext(message): return ldgettext(_current_domain, message) def ngettext(msgid1, msgid2, n): return dngettext(_current_domain, msgid1, msgid2, n) def lngettext(msgid1, msgid2, n): return ldngettext(_current_domain, msgid1, msgid2, n) # dcgettext() has been deemed unnecessary and is not implemented. # James Henstridge's Catalog constructor from GNOME gettext. Documented usage # was: # # import gettext # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR) # _ = cat.gettext # print _('Hello World') # The resulting catalog object currently don't support access through a # dictionary API, which was supported (but apparently unused) in GNOME # gettext. Catalog = translation
21,530
638
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/_sitebuiltins.py
""" The objects used by the site module to add custom builtins. """ # Those objects are almost immortal and they keep a reference to their module # globals. Defining them in the site module would keep too many references # alive. # Note this means this module should also avoid keep things alive in its # globals. import sys class Quitter(object): def __init__(self, name, eof): self.name = name self.eof = eof def __repr__(self): return 'Use %s() or %s to exit' % (self.name, self.eof) def __call__(self, code=None): # Shells like IDLE catch the SystemExit, but listen when their # stdin wrapper is closed. try: sys.stdin.close() except: pass raise SystemExit(code) class _Printer(object): """interactive prompt objects for printing the license text, a list of contributors and the copyright notice.""" MAXLINES = 23 def __init__(self, name, data, files=(), dirs=()): import os self.__name = name self.__data = data self.__lines = None self.__filenames = [os.path.join(dir, filename) for dir in dirs for filename in files] def __setup(self): if self.__lines: return data = None for filename in self.__filenames: try: with open(filename, "r") as fp: data = fp.read() break except OSError: pass if not data: data = self.__data self.__lines = data.split('\n') self.__linecnt = len(self.__lines) def __repr__(self): self.__setup() if len(self.__lines) <= self.MAXLINES: return "\n".join(self.__lines) else: return "Type %s() to see the full %s text" % ((self.__name,)*2) def __call__(self): self.__setup() import os if os.isatty(1): prompt = 'Hit Return for more, or q (and Return) to quit: ' n = os.get_terminal_size().lines else: n = self.MAXLINES lineno = 0 while 1: try: for i in range(lineno, lineno + n): print(self.__lines[i]) except IndexError: break else: lineno += n key = None if os.isatty(1): while key is None: key = input(prompt) if key not in ('', 'q'): key = None if key == 'q': break class _Helper(object): """Define the builtin 'help'. This is a wrapper around pydoc.help that provides a helpful message when 'help' is typed at the Python interactive prompt. Calling help() at the Python prompt starts an interactive help session. Calling help(thing) prints help for the python object 'thing'. """ def __repr__(self): return "Type help() for interactive help, " \ "or help(object) for help about object." def __call__(self, *args, **kwds): import pydoc return pydoc.help(*args, **kwds)
3,284
110
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/ftplib.py
"""An FTP client class and some helper functions. Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds Example: >>> from ftplib import FTP >>> ftp = FTP('ftp.python.org') # connect to host, default port >>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@ '230 Guest login ok, access restrictions apply.' >>> ftp.retrlines('LIST') # list directory contents total 9 drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg '226 Transfer complete.' >>> ftp.quit() '221 Goodbye.' >>> A nice test that reveals some of the network dialogue would be: python ftplib.py -d localhost -l -p -l """ # # Changes and improvements suggested by Steve Majewski. # Modified by Jack to work on the mac. # Modified by Siebren to support docstrings and PASV. # Modified by Phil Schwartz to add storbinary and storlines callbacks. # Modified by Giampaolo Rodola' to add TLS support. # import sys import socket from socket import _GLOBAL_DEFAULT_TIMEOUT __all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto", "all_errors"] # Magic number from <socket.h> MSG_OOB = 0x1 # Process data out of band # The standard FTP server control port FTP_PORT = 21 # The sizehint parameter passed to readline() calls MAXLINE = 8192 # Exception raised when an error or invalid response is received class Error(Exception): pass class error_reply(Error): pass # unexpected [123]xx reply class error_temp(Error): pass # 4xx errors class error_perm(Error): pass # 5xx errors class error_proto(Error): pass # response does not begin with [1-5] # All exceptions (hopefully) that may be raised here and that aren't # (always) programming errors on our side all_errors = (Error, OSError, EOFError) # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) CRLF = '\r\n' B_CRLF = b'\r\n' # The class itself class FTP: '''An FTP client class. To create a connection, call the class using these arguments: host, user, passwd, acct, timeout The first four arguments are all strings, and have default value ''. timeout must be numeric and defaults to None if not passed, meaning that no timeout will be set on any ftp socket(s) If a timeout is passed, then this is now the default timeout for all ftp socket operations for this instance. Then use self.connect() with optional host and port argument. To download a file, use ftp.retrlines('RETR ' + filename), or ftp.retrbinary() with slightly different arguments. To upload a file, use ftp.storlines() or ftp.storbinary(), which have an open file as argument (see their definitions below for details). The download/upload functions first issue appropriate TYPE and PORT or PASV commands. ''' debugging = 0 host = '' port = FTP_PORT maxline = MAXLINE sock = None file = None welcome = None passiveserver = 1 encoding = "latin-1" # Disables https://bugs.python.org/issue43285 security if set to True. trust_server_pasv_ipv4_address = False # Initialization method (called by class instantiation). # Initialize host to localhost, port to standard ftp port # Optional arguments are host (for connect()), # and user, passwd, acct (for login()) def __init__(self, host='', user='', passwd='', acct='', timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): self.source_address = source_address self.timeout = timeout if host: self.connect(host) if user: self.login(user, passwd, acct) def __enter__(self): return self # Context management protocol: try to quit() if active def __exit__(self, *args): if self.sock is not None: try: self.quit() except (OSError, EOFError): pass finally: if self.sock is not None: self.close() def connect(self, host='', port=0, timeout=-999, source_address=None): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) - timeout: the timeout to set against the ftp socket(s) - source_address: a 2-tuple (host, port) for the socket to bind to as its source address before connecting. ''' if host != '': self.host = host if port > 0: self.port = port if timeout != -999: self.timeout = timeout if source_address is not None: self.source_address = source_address self.sock = socket.create_connection((self.host, self.port), self.timeout, source_address=self.source_address) self.af = self.sock.family self.file = self.sock.makefile('r', encoding=self.encoding) self.welcome = self.getresp() return self.welcome def getwelcome(self): '''Get the welcome message from the server. (this is read and squirreled away by connect())''' if self.debugging: print('*welcome*', self.sanitize(self.welcome)) return self.welcome def set_debuglevel(self, level): '''Set the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF''' self.debugging = level debug = set_debuglevel def set_pasv(self, val): '''Use passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command.''' self.passiveserver = val # Internal: "sanitize" a string for printing def sanitize(self, s): if s[:5] in {'pass ', 'PASS '}: i = len(s.rstrip('\r\n')) s = s[:5] + '*'*(i-5) + s[i:] return repr(s) # Internal: send one line to the server, appending CRLF def putline(self, line): if '\r' in line or '\n' in line: raise ValueError('an illegal newline character should not be contained') line = line + CRLF if self.debugging > 1: print('*put*', self.sanitize(line)) self.sock.sendall(line.encode(self.encoding)) # Internal: send one command to the server (through putline()) def putcmd(self, line): if self.debugging: print('*cmd*', self.sanitize(line)) self.putline(line) # Internal: return one line from the server, stripping CRLF. # Raise EOFError if the connection is closed def getline(self): line = self.file.readline(self.maxline + 1) if len(line) > self.maxline: raise Error("got more than %d bytes" % self.maxline) if self.debugging > 1: print('*get*', self.sanitize(line)) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] return line # Internal: get a response from the server, which may possibly # consist of multiple lines. Return a single string with no # trailing CRLF. If the response consists of multiple lines, # these are separated by '\n' characters in the string def getmultiline(self): line = self.getline() if line[3:4] == '-': code = line[:3] while 1: nextline = self.getline() line = line + ('\n' + nextline) if nextline[:3] == code and \ nextline[3:4] != '-': break return line # Internal: get a response from the server. # Raise various errors if the response indicates an error def getresp(self): resp = self.getmultiline() if self.debugging: print('*resp*', self.sanitize(resp)) self.lastresp = resp[:3] c = resp[:1] if c in {'1', '2', '3'}: return resp if c == '4': raise error_temp(resp) if c == '5': raise error_perm(resp) raise error_proto(resp) def voidresp(self): """Expect a response beginning with '2'.""" resp = self.getresp() if resp[:1] != '2': raise error_reply(resp) return resp def abort(self): '''Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.''' line = b'ABOR' + B_CRLF if self.debugging > 1: print('*put urgent*', self.sanitize(line)) self.sock.sendall(line, MSG_OOB) resp = self.getmultiline() if resp[:3] not in {'426', '225', '226'}: raise error_proto(resp) return resp def sendcmd(self, cmd): '''Send a command and return the response.''' self.putcmd(cmd) return self.getresp() def voidcmd(self, cmd): """Send a command and expect a response beginning with '2'.""" self.putcmd(cmd) return self.voidresp() def sendport(self, host, port): '''Send a PORT command with the current host and the given port number. ''' hbytes = host.split('.') pbytes = [repr(port//256), repr(port%256)] bytes = hbytes + pbytes cmd = 'PORT ' + ','.join(bytes) return self.voidcmd(cmd) def sendeprt(self, host, port): '''Send an EPRT command with the current host and the given port number.''' af = 0 if self.af == socket.AF_INET: af = 1 if self.af == socket.AF_INET6: af = 2 if af == 0: raise error_proto('unsupported address family') fields = ['', repr(af), host, repr(port), ''] cmd = 'EPRT ' + '|'.join(fields) return self.voidcmd(cmd) def makeport(self): '''Create a new socket and send a PORT command for it.''' err = None sock = None for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: sock = socket.socket(af, socktype, proto) sock.bind(sa) except OSError as _: err = _ if sock: sock.close() sock = None continue break if sock is None: if err is not None: raise err else: raise OSError("getaddrinfo returns an empty list") sock.listen(1) port = sock.getsockname()[1] # Get proper port host = self.sock.getsockname()[0] # Get proper host if self.af == socket.AF_INET: resp = self.sendport(host, port) else: resp = self.sendeprt(host, port) if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(self.timeout) return sock def makepasv(self): """Internal: Does the PASV or EPSV handshake -> (address, port)""" if self.af == socket.AF_INET: untrusted_host, port = parse227(self.sendcmd('PASV')) if self.trust_server_pasv_ipv4_address: host = untrusted_host else: host = self.sock.getpeername()[0] else: host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername()) return host, port def ntransfercmd(self, cmd, rest=None): """Initiate a transfer over the data connection. If the transfer is active, send a port command and the transfer command, and accept the connection. If the server is passive, send a pasv command, connect to it, and start the transfer command. Either way, return the socket for the connection and the expected size of the transfer. The expected size may be None if it could not be determined. Optional `rest' argument can be a string that is sent as the argument to a REST command. This is essentially a server marker used to tell the server to skip over any data up to the given marker. """ size = None if self.passiveserver: host, port = self.makepasv() conn = socket.create_connection((host, port), self.timeout, source_address=self.source_address) try: if rest is not None: self.sendcmd("REST %s" % rest) resp = self.sendcmd(cmd) # Some servers apparently send a 200 reply to # a LIST or STOR command, before the 150 reply # (and way before the 226 reply). This seems to # be in violation of the protocol (which only allows # 1xx or error messages for LIST), so we just discard # this response. if resp[0] == '2': resp = self.getresp() if resp[0] != '1': raise error_reply(resp) except: conn.close() raise else: with self.makeport() as sock: if rest is not None: self.sendcmd("REST %s" % rest) resp = self.sendcmd(cmd) # See above. if resp[0] == '2': resp = self.getresp() if resp[0] != '1': raise error_reply(resp) conn, sockaddr = sock.accept() if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT: conn.settimeout(self.timeout) if resp[:3] == '150': # this is conditional in case we received a 125 size = parse150(resp) return conn, size def transfercmd(self, cmd, rest=None): """Like ntransfercmd() but returns only the socket.""" return self.ntransfercmd(cmd, rest)[0] def login(self, user = '', passwd = '', acct = ''): '''Login, default anonymous.''' if not user: user = 'anonymous' if not passwd: passwd = '' if not acct: acct = '' if user == 'anonymous' and passwd in {'', '-'}: # If there is no anonymous ftp password specified # then we'll just use anonymous@ # We don't send any other thing because: # - We want to remain anonymous # - We want to stop SPAM # - We don't want to let ftp sites to discriminate by the user, # host or country. passwd = passwd + 'anonymous@' resp = self.sendcmd('USER ' + user) if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd) if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct) if resp[0] != '2': raise error_reply(resp) return resp def retrbinary(self, cmd, callback, blocksize=8192, rest=None): """Retrieve data in binary mode. A new port is created for you. Args: cmd: A RETR command. callback: A single parameter callable to be called on each block of data read. blocksize: The maximum number of bytes to read from the socket at one time. [default: 8192] rest: Passed to transfercmd(). [default: None] Returns: The response code. """ self.voidcmd('TYPE I') with self.transfercmd(cmd, rest) as conn: while 1: data = conn.recv(blocksize) if not data: break callback(data) # shutdown ssl layer if _SSLSocket is not None and isinstance(conn, _SSLSocket): conn.unwrap() return self.voidresp() def retrlines(self, cmd, callback = None): """Retrieve data in line mode. A new port is created for you. Args: cmd: A RETR, LIST, or NLST command. callback: An optional single parameter callable that is called for each line with the trailing CRLF stripped. [default: print_line()] Returns: The response code. """ if callback is None: callback = print_line resp = self.sendcmd('TYPE A') with self.transfercmd(cmd) as conn, \ conn.makefile('r', encoding=self.encoding) as fp: while 1: line = fp.readline(self.maxline + 1) if len(line) > self.maxline: raise Error("got more than %d bytes" % self.maxline) if self.debugging > 2: print('*retr*', repr(line)) if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) # shutdown ssl layer if _SSLSocket is not None and isinstance(conn, _SSLSocket): conn.unwrap() return self.voidresp() def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None): """Store a file in binary mode. A new port is created for you. Args: cmd: A STOR command. fp: A file-like object with a read(num_bytes) method. blocksize: The maximum data size to read from fp and send over the connection at once. [default: 8192] callback: An optional single parameter callable that is called on each block of data after it is sent. [default: None] rest: Passed to transfercmd(). [default: None] Returns: The response code. """ self.voidcmd('TYPE I') with self.transfercmd(cmd, rest) as conn: while 1: buf = fp.read(blocksize) if not buf: break conn.sendall(buf) if callback: callback(buf) # shutdown ssl layer if _SSLSocket is not None and isinstance(conn, _SSLSocket): conn.unwrap() return self.voidresp() def storlines(self, cmd, fp, callback=None): """Store a file in line mode. A new port is created for you. Args: cmd: A STOR command. fp: A file-like object with a readline() method. callback: An optional single parameter callable that is called on each line after it is sent. [default: None] Returns: The response code. """ self.voidcmd('TYPE A') with self.transfercmd(cmd) as conn: while 1: buf = fp.readline(self.maxline + 1) if len(buf) > self.maxline: raise Error("got more than %d bytes" % self.maxline) if not buf: break if buf[-2:] != B_CRLF: if buf[-1] in B_CRLF: buf = buf[:-1] buf = buf + B_CRLF conn.sendall(buf) if callback: callback(buf) # shutdown ssl layer if _SSLSocket is not None and isinstance(conn, _SSLSocket): conn.unwrap() return self.voidresp() def acct(self, password): '''Send new account name.''' cmd = 'ACCT ' + password return self.voidcmd(cmd) def nlst(self, *args): '''Return a list of files in a given directory (default the current).''' cmd = 'NLST' for arg in args: cmd = cmd + (' ' + arg) files = [] self.retrlines(cmd, files.append) return files def dir(self, *args): '''List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)''' cmd = 'LIST' func = None if args[-1:] and type(args[-1]) != type(''): args, func = args[:-1], args[-1] for arg in args: if arg: cmd = cmd + (' ' + arg) self.retrlines(cmd, func) def mlsd(self, path="", facts=[]): '''List a directory in a standardized format by using MLSD command (RFC-3659). If path is omitted the current directory is assumed. "facts" is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]). Return a generator object yielding a tuple of two elements for every file found in path. First element is the file name, the second one is a dictionary including a variable number of "facts" depending on the server and whether "facts" argument has been provided. ''' if facts: self.sendcmd("OPTS MLST " + ";".join(facts) + ";") if path: cmd = "MLSD %s" % path else: cmd = "MLSD" lines = [] self.retrlines(cmd, lines.append) for line in lines: facts_found, _, name = line.rstrip(CRLF).partition(' ') entry = {} for fact in facts_found[:-1].split(";"): key, _, value = fact.partition("=") entry[key.lower()] = value yield (name, entry) def rename(self, fromname, toname): '''Rename a file.''' resp = self.sendcmd('RNFR ' + fromname) if resp[0] != '3': raise error_reply(resp) return self.voidcmd('RNTO ' + toname) def delete(self, filename): '''Delete a file.''' resp = self.sendcmd('DELE ' + filename) if resp[:3] in {'250', '200'}: return resp else: raise error_reply(resp) def cwd(self, dirname): '''Change to a directory.''' if dirname == '..': try: return self.voidcmd('CDUP') except error_perm as msg: if msg.args[0][:3] != '500': raise elif dirname == '': dirname = '.' # does nothing, but could return error cmd = 'CWD ' + dirname return self.voidcmd(cmd) def size(self, filename): '''Retrieve the size of a file.''' # The SIZE command is defined in RFC-3659 resp = self.sendcmd('SIZE ' + filename) if resp[:3] == '213': s = resp[3:].strip() return int(s) def mkd(self, dirname): '''Make a directory, return its full pathname.''' resp = self.voidcmd('MKD ' + dirname) # fix around non-compliant implementations such as IIS shipped # with Windows server 2003 if not resp.startswith('257'): return '' return parse257(resp) def rmd(self, dirname): '''Remove a directory.''' return self.voidcmd('RMD ' + dirname) def pwd(self): '''Return current working directory.''' resp = self.voidcmd('PWD') # fix around non-compliant implementations such as IIS shipped # with Windows server 2003 if not resp.startswith('257'): return '' return parse257(resp) def quit(self): '''Quit, and close the connection.''' resp = self.voidcmd('QUIT') self.close() return resp def close(self): '''Close the connection without assuming anything about it.''' try: file = self.file self.file = None if file is not None: file.close() finally: sock = self.sock self.sock = None if sock is not None: sock.close() try: import ssl except ImportError: _SSLSocket = None else: _SSLSocket = ssl.SSLSocket class FTP_TLS(FTP): '''A FTP subclass which adds TLS support to FTP as described in RFC-4217. Connect as usual to port 21 implicitly securing the FTP control connection before authenticating. Securing the data connection requires user to explicitly ask for it by calling prot_p() method. Usage example: >>> from ftplib import FTP_TLS >>> ftps = FTP_TLS('ftp.python.org') >>> ftps.login() # login anonymously previously securing control channel '230 Guest login ok, access restrictions apply.' >>> ftps.prot_p() # switch to secure data connection '200 Protection level set to P' >>> ftps.retrlines('LIST') # list directory content securely total 9 drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg '226 Transfer complete.' >>> ftps.quit() '221 Goodbye.' >>> ''' ssl_version = ssl.PROTOCOL_SSLv23 def __init__(self, host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): if context is not None and keyfile is not None: raise ValueError("context and keyfile arguments are mutually " "exclusive") if context is not None and certfile is not None: raise ValueError("context and certfile arguments are mutually " "exclusive") if keyfile is not None or certfile is not None: import warnings warnings.warn("keyfile and certfile are deprecated, use a " "custom context instead", DeprecationWarning, 2) self.keyfile = keyfile self.certfile = certfile if context is None: context = ssl._create_stdlib_context(self.ssl_version, certfile=certfile, keyfile=keyfile) self.context = context self._prot_p = False FTP.__init__(self, host, user, passwd, acct, timeout, source_address) def login(self, user='', passwd='', acct='', secure=True): if secure and not isinstance(self.sock, ssl.SSLSocket): self.auth() return FTP.login(self, user, passwd, acct) def auth(self): '''Set up secure control connection by using TLS/SSL.''' if isinstance(self.sock, ssl.SSLSocket): raise ValueError("Already using TLS") if self.ssl_version >= ssl.PROTOCOL_SSLv23: resp = self.voidcmd('AUTH TLS') else: resp = self.voidcmd('AUTH SSL') self.sock = self.context.wrap_socket(self.sock, server_hostname=self.host) self.file = self.sock.makefile(mode='r', encoding=self.encoding) return resp def ccc(self): '''Switch back to a clear-text control connection.''' if not isinstance(self.sock, ssl.SSLSocket): raise ValueError("not using TLS") resp = self.voidcmd('CCC') self.sock = self.sock.unwrap() return resp def prot_p(self): '''Set up secure data connection.''' # PROT defines whether or not the data channel is to be protected. # Though RFC-2228 defines four possible protection levels, # RFC-4217 only recommends two, Clear and Private. # Clear (PROT C) means that no security is to be used on the # data-channel, Private (PROT P) means that the data-channel # should be protected by TLS. # PBSZ command MUST still be issued, but must have a parameter of # '0' to indicate that no buffering is taking place and the data # connection should not be encapsulated. self.voidcmd('PBSZ 0') resp = self.voidcmd('PROT P') self._prot_p = True return resp def prot_c(self): '''Set up clear text data connection.''' resp = self.voidcmd('PROT C') self._prot_p = False return resp # --- Overridden FTP methods def ntransfercmd(self, cmd, rest=None): conn, size = FTP.ntransfercmd(self, cmd, rest) if self._prot_p: conn = self.context.wrap_socket(conn, server_hostname=self.host) return conn, size def abort(self): # overridden as we can't pass MSG_OOB flag to sendall() line = b'ABOR' + B_CRLF self.sock.sendall(line) resp = self.getmultiline() if resp[:3] not in {'426', '225', '226'}: raise error_proto(resp) return resp __all__.append('FTP_TLS') all_errors = (Error, OSError, EOFError, ssl.SSLError) _150_re = None def parse150(resp): '''Parse the '150' response for a RETR request. Returns the expected transfer size or None; size is not guaranteed to be present in the 150 message. ''' if resp[:3] != '150': raise error_reply(resp) global _150_re if _150_re is None: import re _150_re = re.compile( r"150 .* \((\d+) bytes\)", re.IGNORECASE | re.ASCII) m = _150_re.match(resp) if not m: return None return int(m.group(1)) _227_re = None def parse227(resp): '''Parse the '227' response for a PASV request. Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] != '227': raise error_reply(resp) global _227_re if _227_re is None: import re _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)', re.ASCII) m = _227_re.search(resp) if not m: raise error_proto(resp) numbers = m.groups() host = '.'.join(numbers[:4]) port = (int(numbers[4]) << 8) + int(numbers[5]) return host, port def parse229(resp, peer): '''Parse the '229' response for an EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] != '229': raise error_reply(resp) left = resp.find('(') if left < 0: raise error_proto(resp) right = resp.find(')', left + 1) if right < 0: raise error_proto(resp) # should contain '(|||port|)' if resp[left + 1] != resp[right - 1]: raise error_proto(resp) parts = resp[left + 1:right].split(resp[left+1]) if len(parts) != 5: raise error_proto(resp) host = peer[0] port = int(parts[3]) return host, port def parse257(resp): '''Parse the '257' response for a MKD or PWD request. This is a response to a MKD or PWD request: a directory name. Returns the directoryname in the 257 reply.''' if resp[:3] != '257': raise error_reply(resp) if resp[3:5] != ' "': return '' # Not compliant to RFC 959, but UNIX ftpd does this dirname = '' i = 5 n = len(resp) while i < n: c = resp[i] i = i+1 if c == '"': if i >= n or resp[i] != '"': break i = i+1 dirname = dirname + c return dirname def print_line(line): '''Default retrlines callback to print a line.''' print(line) def ftpcp(source, sourcename, target, targetname = '', type = 'I'): '''Copy file from one FTP-instance to another.''' if not targetname: targetname = sourcename type = 'TYPE ' + type source.voidcmd(type) target.voidcmd(type) sourcehost, sourceport = parse227(source.sendcmd('PASV')) target.sendport(sourcehost, sourceport) # RFC 959: the user must "listen" [...] BEFORE sending the # transfer request. # So: STOR before RETR, because here the target is a "user". treply = target.sendcmd('STOR ' + targetname) if treply[:3] not in {'125', '150'}: raise error_proto # RFC 959 sreply = source.sendcmd('RETR ' + sourcename) if sreply[:3] not in {'125', '150'}: raise error_proto # RFC 959 source.voidresp() target.voidresp() def test(): '''Test program. Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ... -d dir -l list -p password ''' if len(sys.argv) < 2: print(test.__doc__) sys.exit(0) import netrc debugging = 0 rcfile = None while sys.argv[1] == '-d': debugging = debugging+1 del sys.argv[1] if sys.argv[1][:2] == '-r': # get name of alternate ~/.netrc file: rcfile = sys.argv[1][2:] del sys.argv[1] host = sys.argv[1] ftp = FTP(host) ftp.set_debuglevel(debugging) userid = passwd = acct = '' try: netrcobj = netrc.netrc(rcfile) except OSError: if rcfile is not None: sys.stderr.write("Could not open account file" " -- using anonymous login.") else: try: userid, acct, passwd = netrcobj.authenticators(host) except KeyError: # no account for host sys.stderr.write( "No account -- using anonymous login.") ftp.login(userid, passwd, acct) for file in sys.argv[2:]: if file[:2] == '-l': ftp.dir(file[2:]) elif file[:2] == '-d': cmd = 'CWD' if file[2:]: cmd = cmd + ' ' + file[2:] resp = ftp.sendcmd(cmd) elif file == '-p': ftp.set_pasv(not ftp.passiveserver) else: ftp.retrbinary('RETR ' + file, \ sys.stdout.write, 1024) ftp.quit() if __name__ == '__main__': test()
35,617
997
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/shutil.py
"""Utility functions for copying and archiving files and directory trees. XXX The functions here don't copy the resource fork or other metadata on Mac. """ import os import sys import stat import fnmatch import collections import errno try: import zlib del zlib _ZLIB_SUPPORTED = True except ImportError: _ZLIB_SUPPORTED = False try: import bz2 del bz2 _BZ2_SUPPORTED = True except ImportError: _BZ2_SUPPORTED = False try: import lzma del lzma _LZMA_SUPPORTED = True except ImportError: _LZMA_SUPPORTED = False try: from pwd import getpwnam except ImportError: getpwnam = None try: from grp import getgrnam except ImportError: getgrnam = None __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", "copytree", "move", "rmtree", "Error", "SpecialFileError", "ExecError", "make_archive", "get_archive_formats", "register_archive_format", "unregister_archive_format", "get_unpack_formats", "register_unpack_format", "unregister_unpack_format", "unpack_archive", "ignore_patterns", "chown", "which", "get_terminal_size", "SameFileError"] # disk_usage is added later, if available on the platform class Error(OSError): pass class SameFileError(Error): """Raised when source and destination are the same file.""" class SpecialFileError(OSError): """Raised when trying to do a kind of operation (e.g. copying) which is not supported on a special file (e.g. a named pipe)""" class ExecError(OSError): """Raised when a command could not be executed""" class ReadError(OSError): """Raised when an archive cannot be read""" class RegistryError(Exception): """Raised when a registry operation with the archiving and unpacking registries fails""" def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf) def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path, 'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All other platforms: check for same pathname. return (os.path.normcase(os.path.abspath(src)) == os.path.normcase(os.path.abspath(dst))) def copyfile(src, dst, *, follow_symlinks=True): """Copy data from src to dst. If follow_symlinks is not set and src is a symbolic link, a new symlink will be created instead of copying the file it points to. """ if _samefile(src, dst): raise SameFileError("{!r} and {!r} are the same file".format(src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass else: # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) if not follow_symlinks and os.path.islink(src): os.symlink(os.readlink(src), dst) else: with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: copyfileobj(fsrc, fdst) return dst def copymode(src, dst, *, follow_symlinks=True): """Copy mode bits from src to dst. If follow_symlinks is not set, symlinks aren't followed if and only if both `src` and `dst` are symlinks. If `lchmod` isn't available (e.g. Linux) this method does nothing. """ if not follow_symlinks and os.path.islink(src) and os.path.islink(dst): if hasattr(os, 'lchmod'): stat_func, chmod_func = os.lstat, os.lchmod else: return elif hasattr(os, 'chmod'): stat_func, chmod_func = os.stat, os.chmod else: return st = stat_func(src) chmod_func(dst, stat.S_IMODE(st.st_mode)) if hasattr(os, 'listxattr'): def _copyxattr(src, dst, *, follow_symlinks=True): """Copy extended filesystem attributes from `src` to `dst`. Overwrite existing attributes. If `follow_symlinks` is false, symlinks won't be followed. """ try: names = os.listxattr(src, follow_symlinks=follow_symlinks) except OSError as e: if e.errno not in (errno.ENOTSUP, errno.ENODATA): raise return for name in names: try: value = os.getxattr(src, name, follow_symlinks=follow_symlinks) os.setxattr(dst, name, value, follow_symlinks=follow_symlinks) except OSError as e: if e.errno not in (errno.EPERM, errno.ENOTSUP, errno.ENODATA): raise else: def _copyxattr(*args, **kwargs): pass def copystat(src, dst, *, follow_symlinks=True): """Copy file metadata Copy the permission bits, last access time, last modification time, and flags from `src` to `dst`. On Linux, copystat() also copies the "extended attributes" where possible. The file contents, owner, and group are unaffected. `src` and `dst` are path names given as strings. If the optional flag `follow_symlinks` is not set, symlinks aren't followed if and only if both `src` and `dst` are symlinks. """ def _nop(*args, ns=None, follow_symlinks=None): pass # follow symlinks (aka don't not follow symlinks) follow = follow_symlinks or not (os.path.islink(src) and os.path.islink(dst)) if follow: # use the real function if it exists def lookup(name): return getattr(os, name, _nop) else: # use the real function only if it exists # *and* it supports follow_symlinks def lookup(name): fn = getattr(os, name, _nop) if fn in os.supports_follow_symlinks: return fn return _nop st = lookup("stat")(src, follow_symlinks=follow) mode = stat.S_IMODE(st.st_mode) lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns), follow_symlinks=follow) try: lookup("chmod")(dst, mode, follow_symlinks=follow) except NotImplementedError: # if we got a NotImplementedError, it's because # * follow_symlinks=False, # * lchown() is unavailable, and # * either # * fchownat() is unavailable or # * fchownat() doesn't implement AT_SYMLINK_NOFOLLOW. # (it returned ENOSUP.) # therefore we're out of options--we simply cannot chown the # symlink. give up, suppress the error. # (which is what shutil always did in this circumstance.) pass if hasattr(st, 'st_flags'): try: lookup("chflags")(dst, st.st_flags, follow_symlinks=follow) except OSError as why: for err in 'EOPNOTSUPP', 'ENOTSUP': if hasattr(errno, err) and why.errno == getattr(errno, err): break else: raise _copyxattr(src, dst, follow_symlinks=follow) def copy(src, dst, *, follow_symlinks=True): """Copy data and mode bits ("cp src dst"). Return the file's destination. The destination may be a directory. If follow_symlinks is false, symlinks won't be followed. This resembles GNU's "cp -P src dst". If source and destination are the same file, a SameFileError will be raised. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst, follow_symlinks=follow_symlinks) copymode(src, dst, follow_symlinks=follow_symlinks) return dst def copy2(src, dst, *, follow_symlinks=True): """Copy data and metadata. Return the file's destination. Metadata is copied with copystat(). Please see the copystat function for more information. The destination may be a directory. If follow_symlinks is false, symlinks won't be followed. This resembles GNU's "cp -P src dst". """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst, follow_symlinks=follow_symlinks) copystat(src, dst, follow_symlinks=follow_symlinks) return dst def ignore_patterns(*patterns): """Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude files""" def _ignore_patterns(path, names): ignored_names = [] for pattern in patterns: ignored_names.extend(fnmatch.filter(names, pattern)) return set(ignored_names) return _ignore_patterns def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False): """Recursively copy a directory tree. The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. If the file pointed by the symlink doesn't exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this has no effect on platforms that don't support os.symlink. The optional ignore argument is a callable. If given, it is called with the `src` parameter, which is the directory being visited by copytree(), and `names` which is the list of `src` contents, as returned by os.listdir(): callable(src, names) -> ignored_names Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the `src` directory that should not be copied. The optional copy_function argument is a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() os.makedirs(dst) errors = [] for name in names: if name in ignored_names: continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if os.path.islink(srcname): linkto = os.readlink(srcname) if symlinks: # We can't just leave it to `copy_function` because legacy # code with a custom `copy_function` may rely on copytree # doing the right thing. os.symlink(linkto, dstname) copystat(srcname, dstname, follow_symlinks=not symlinks) else: # ignore dangling symlink if the flag is on if not os.path.exists(linkto) and ignore_dangling_symlinks: continue # otherwise let the copy occurs. copy2 will raise an error if os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore, copy_function) else: copy_function(srcname, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore, copy_function) else: # Will raise a SpecialFileError for unsupported file types copy_function(srcname, dstname) # catch the Error from the recursive copytree so that we can # continue with other files except Error as err: errors.extend(err.args[0]) except OSError as why: errors.append((srcname, dstname, str(why))) try: copystat(src, dst) except OSError as why: # Copying file access times may fail on Windows if getattr(why, 'winerror', None) is None: errors.append((src, dst, str(why))) if errors: raise Error(errors) return dst # version vulnerable to race conditions def _rmtree_unsafe(path, onerror): try: if os.path.islink(path): # symlinks to directories are forbidden, see bug #1669 raise OSError("Cannot call rmtree on a symbolic link") except OSError: onerror(os.path.islink, path, sys.exc_info()) # can't continue even if onerror hook returns return names = [] try: names = os.listdir(path) except OSError: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except OSError: mode = 0 if stat.S_ISDIR(mode): _rmtree_unsafe(fullname, onerror) else: try: os.unlink(fullname) except OSError: onerror(os.unlink, fullname, sys.exc_info()) try: os.rmdir(path) except OSError: onerror(os.rmdir, path, sys.exc_info()) # Version using fd-based APIs to protect against races def _rmtree_safe_fd(topfd, path, onerror): names = [] try: names = os.listdir(topfd) except OSError as err: err.filename = path onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: orig_st = os.stat(name, dir_fd=topfd, follow_symlinks=False) mode = orig_st.st_mode except OSError: mode = 0 if stat.S_ISDIR(mode): try: dirfd = os.open(name, os.O_RDONLY, dir_fd=topfd) except OSError: onerror(os.open, fullname, sys.exc_info()) else: try: if os.path.samestat(orig_st, os.fstat(dirfd)): _rmtree_safe_fd(dirfd, fullname, onerror) try: os.rmdir(name, dir_fd=topfd) except OSError: onerror(os.rmdir, fullname, sys.exc_info()) else: try: # This can only happen if someone replaces # a directory with a symlink after the call to # stat.S_ISDIR above. raise OSError("Cannot call rmtree on a symbolic " "link") except OSError: onerror(os.path.islink, fullname, sys.exc_info()) finally: os.close(dirfd) else: try: os.unlink(name, dir_fd=topfd) except OSError: onerror(os.unlink, fullname, sys.exc_info()) _use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <= os.supports_dir_fd and os.listdir in os.supports_fd and os.stat in os.supports_follow_symlinks) def rmtree(path, ignore_errors=False, onerror=None): """Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is platform and implementation dependent; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. """ if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise if _use_fd_functions: # While the unsafe rmtree works fine on bytes, the fd based does not. if isinstance(path, bytes): path = os.fsdecode(path) # Note: To guard against symlink races, we use the standard # lstat()/open()/fstat() trick. try: orig_st = os.lstat(path) except Exception: onerror(os.lstat, path, sys.exc_info()) return try: fd = os.open(path, os.O_RDONLY) except Exception: onerror(os.lstat, path, sys.exc_info()) return try: if os.path.samestat(orig_st, os.fstat(fd)): _rmtree_safe_fd(fd, path, onerror) try: os.rmdir(path) except OSError: onerror(os.rmdir, path, sys.exc_info()) else: try: # symlinks to directories are forbidden, see bug #1669 raise OSError("Cannot call rmtree on a symbolic link") except OSError: onerror(os.path.islink, path, sys.exc_info()) finally: os.close(fd) else: return _rmtree_unsafe(path, onerror) # Allow introspection of whether or not the hardening against symlink # attacks is supported on the current platform rmtree.avoids_symlink_attacks = _use_fd_functions def _basename(path): # A basename() variant which first strips the trailing slash, if present. # Thus we always get the last component of the path, even for directories. sep = os.path.sep + (os.path.altsep or '') return os.path.basename(path.rstrip(sep)) def move(src, dst, copy_function=copy2): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. Return the file or directory's destination. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. Symlinks are recreated under the new name if os.rename() fails because of cross filesystem renames. The optional `copy_function` argument is a callable that will be used to copy the source or it will be delegated to `copytree`. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ real_dst = dst if os.path.isdir(dst): if _samefile(src, dst): # We might be on a case insensitive filesystem, # perform the rename anyway. os.rename(src, dst) return real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path '%s' already exists" % real_dst) try: os.rename(src, real_dst) except OSError: if os.path.islink(src): linkto = os.readlink(src) os.symlink(linkto, real_dst) os.unlink(src) elif os.path.isdir(src): if _destinsrc(src, dst): raise Error("Cannot move a directory '%s' into itself" " '%s'." % (src, dst)) copytree(src, real_dst, copy_function=copy_function, symlinks=True) rmtree(src) else: copy_function(src, real_dst) os.unlink(src) return real_dst def _destinsrc(src, dst): src = os.path.abspath(src) dst = os.path.abspath(dst) if not src.endswith(os.path.sep): src += os.path.sep if not dst.endswith(os.path.sep): dst += os.path.sep return dst.startswith(src) def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", "xz", or None. 'owner' and 'group' can be used to define an owner and a group for the archive that is being built. If not provided, the current owner and group will be used. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", ".bz2", or ".xz"). Returns the output filename. """ if compress is None: tar_compression = '' elif _ZLIB_SUPPORTED and compress == 'gzip': tar_compression = 'gz' elif _BZ2_SUPPORTED and compress == 'bzip2': tar_compression = 'bz2' elif _LZMA_SUPPORTED and compress == 'xz': tar_compression = 'xz' else: raise ValueError("bad value for 'compress', or compression format not " "supported : {0}".format(compress)) try: import tarfile except ImportError: raise compress_ext = '.' + tar_compression if compress else '' archive_name = base_name + '.tar' + compress_ext archive_dir = os.path.dirname(archive_name) if archive_dir and not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # creating the tarball if logger is not None: logger.info('Creating tar archive') uid = _get_uid(owner) gid = _get_gid(group) def _set_uid_gid(tarinfo): if gid is not None: tarinfo.gid = gid tarinfo.gname = group if uid is not None: tarinfo.uid = uid tarinfo.uname = owner return tarinfo if not dry_run: tar = tarfile.open(archive_name, 'w|%s' % tar_compression) try: tar.add(base_dir, filter=_set_uid_gid) finally: tar.close() return archive_name def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Returns the name of the output zip file. """ try: import zipfile except ImportError: raise zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if archive_dir and not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) if logger is not None: logger.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: with zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) as zf: path = os.path.normpath(base_dir) if path != os.curdir: zf.write(path, path) if logger is not None: logger.info("adding '%s'", path) for dirpath, dirnames, filenames in os.walk(base_dir): for name in sorted(dirnames): path = os.path.normpath(os.path.join(dirpath, name)) zf.write(path, path) if logger is not None: logger.info("adding '%s'", path) for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zf.write(path, path) if logger is not None: logger.info("adding '%s'", path) return zip_filename _ARCHIVE_FORMATS = { 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"), } if _ZLIB_SUPPORTED: _ARCHIVE_FORMATS['gztar'] = (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file") _ARCHIVE_FORMATS['zip'] = (_make_zipfile, [], "ZIP file") if _BZ2_SUPPORTED: _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file") if _LZMA_SUPPORTED: _ARCHIVE_FORMATS['xztar'] = (_make_tarball, [('compress', 'xz')], "xz'ed tar-file") def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats def register_archive_format(name, function, extra_args=None, description=''): """Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_archive_formats() function. """ if extra_args is None: extra_args = [] if not callable(function): raise TypeError('The %s object is not callable' % function) if not isinstance(extra_args, (tuple, list)): raise TypeError('extra_args needs to be a sequence') for element in extra_args: if not isinstance(element, (tuple, list)) or len(element) !=2: raise TypeError('extra_args elements are : (arg_name, value)') _ARCHIVE_FORMATS[name] = (function, extra_args, description) def unregister_archive_format(name): del _ARCHIVE_FORMATS[name] def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "gztar", "bztar", or "xztar". Or any other registered format. 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. """ save_cwd = os.getcwd() if root_dir is not None: if logger is not None: logger.debug("changing into '%s'", root_dir) base_name = os.path.abspath(base_name) if not dry_run: os.chdir(root_dir) if base_dir is None: base_dir = os.curdir kwargs = {'dry_run': dry_run, 'logger': logger} try: format_info = _ARCHIVE_FORMATS[format] except KeyError: raise ValueError("unknown archive format '%s'" % format) func = format_info[0] for arg, val in format_info[1]: kwargs[arg] = val if format != 'zip': kwargs['owner'] = owner kwargs['group'] = group try: filename = func(base_name, base_dir, **kwargs) finally: if root_dir is not None: if logger is not None: logger.debug("changing back to '%s'", save_cwd) os.chdir(save_cwd) return filename def get_unpack_formats(): """Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) """ formats = [(name, info[0], info[3]) for name, info in _UNPACK_FORMATS.items()] formats.sort() return formats def _check_unpack_options(extensions, function, extra_args): """Checks what gets registered as an unpacker.""" # first make sure no other unpacker is registered for this extension existing_extensions = {} for name, info in _UNPACK_FORMATS.items(): for ext in info[0]: existing_extensions[ext] = name for extension in extensions: if extension in existing_extensions: msg = '%s is already registered for "%s"' raise RegistryError(msg % (extension, existing_extensions[extension])) if not callable(function): raise TypeError('The registered function must be a callable') def register_unpack_format(name, extensions, function, extra_args=None, description=''): """Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unpack archives. The callable will receive archives to unpack. If it's unable to handle an archive, it needs to raise a ReadError exception. If provided, `extra_args` is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_unpack_formats() function. """ if extra_args is None: extra_args = [] _check_unpack_options(extensions, function, extra_args) _UNPACK_FORMATS[name] = extensions, function, extra_args, description def unregister_unpack_format(name): """Removes the pack format from the registry.""" del _UNPACK_FORMATS[name] def _ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname) def _unpack_zipfile(filename, extract_dir): """Unpack zip `filename` to `extract_dir` """ try: import zipfile except ImportError: raise if not zipfile.is_zipfile(filename): raise ReadError("%s is not a zip file" % filename) zip = zipfile.ZipFile(filename) try: for info in zip.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name: continue target = os.path.join(extract_dir, *name.split('/')) if not target: continue _ensure_directory(target) if not name.endswith('/'): # file data = zip.read(info.filename) f = open(target, 'wb') try: f.write(data) finally: f.close() del data finally: zip.close() def _unpack_tarfile(filename, extract_dir): """Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir` """ try: import tarfile except ImportError: raise try: tarobj = tarfile.open(filename) except tarfile.TarError: raise ReadError( "%s is not a compressed or uncompressed tar file" % filename) try: tarobj.extractall(extract_dir) finally: tarobj.close() _UNPACK_FORMATS = { 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"), 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file"), } if _ZLIB_SUPPORTED: _UNPACK_FORMATS['gztar'] = (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file") if _BZ2_SUPPORTED: _UNPACK_FORMATS['bztar'] = (['.tar.bz2', '.tbz2'], _unpack_tarfile, [], "bzip2'ed tar-file") if _LZMA_SUPPORTED: _UNPACK_FORMATS['xztar'] = (['.tar.xz', '.txz'], _unpack_tarfile, [], "xz'ed tar-file") def _find_unpack_format(filename): for name, info in _UNPACK_FORMATS.items(): for extension in info[0]: if filename.endswith(extension): return name return None def unpack_archive(filename, extract_dir=None, format=None): """Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", "gztar", "bztar", or "xztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. """ if extract_dir is None: extract_dir = os.getcwd() if format is not None: try: format_info = _UNPACK_FORMATS[format] except KeyError: raise ValueError("Unknown unpack format '{0}'".format(format)) func = format_info[1] func(filename, extract_dir, **dict(format_info[2])) else: # we need to look at the registered unpackers supported extensions format = _find_unpack_format(filename) if format is None: raise ReadError("Unknown archive format '{0}'".format(filename)) func = _UNPACK_FORMATS[format][1] kwargs = dict(_UNPACK_FORMATS[format][2]) func(filename, extract_dir, **kwargs) if hasattr(os, 'statvfs'): __all__.append('disk_usage') _ntuple_diskusage = collections.namedtuple('usage', 'total used free') _ntuple_diskusage.total.__doc__ = 'Total space in bytes' _ntuple_diskusage.used.__doc__ = 'Used space in bytes' _ntuple_diskusage.free.__doc__ = 'Free space in bytes' def disk_usage(path): """Return disk usage statistics about the given path. Returned value is a named tuple with attributes 'total', 'used' and 'free', which are the amount of total, used and free space, in bytes. """ st = os.statvfs(path) free = st.f_bavail * st.f_frsize total = st.f_blocks * st.f_frsize used = (st.f_blocks - st.f_bfree) * st.f_frsize return _ntuple_diskusage(total, used, free) def chown(path, user=None, group=None): """Change owner user and group of the given path. user and group can be the uid/gid or the user/group names, and in that case, they are converted to their respective uid/gid. """ if user is None and group is None: raise ValueError("user and/or group must be set") _user = user _group = group # -1 means don't change it if user is None: _user = -1 # user can either be an int (the uid) or a string (the system username) elif isinstance(user, str): _user = _get_uid(user) if _user is None: raise LookupError("no such user: {!r}".format(user)) if group is None: _group = -1 elif not isinstance(group, int): _group = _get_gid(group) if _group is None: raise LookupError("no such group: {!r}".format(group)) os.chown(path, _user, _group) def get_terminal_size(fallback=(80, 24)): """Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size. """ # columns, lines are the working values try: columns = int(os.environ['COLUMNS']) except (KeyError, ValueError): columns = 0 try: lines = int(os.environ['LINES']) except (KeyError, ValueError): lines = 0 # only query if necessary if columns <= 0 or lines <= 0: try: size = os.get_terminal_size(sys.__stdout__.fileno()) except (AttributeError, ValueError, OSError): # stdout is None, closed, detached, or not a terminal, or # os.get_terminal_size() is unsupported size = os.terminal_size(fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return os.terminal_size((columns, lines)) def which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. """ # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # If we're given a path with a directory part, look it up directly rather # than referring to PATH directories. This includes checking relative to the # current directory, e.g. ./script if os.path.dirname(cmd): if _access_check(cmd, mode): return cmd return None if path is None: path = os.environ.get("PATH", os.defpath) if not path: return None path = path.split(os.pathsep) if sys.platform == "win32": # The current directory takes precedence on Windows. if not os.curdir in path: path.insert(0, os.curdir) # PATHEXT is necessary to check on Windows. pathext = os.environ.get("PATHEXT", "").split(os.pathsep) # See if the given file matches any of the expected path extensions. # This will allow us to short circuit when given "python.exe". # If it does match, only test that one, otherwise we have to try # others. if any(cmd.lower().endswith(ext.lower()) for ext in pathext): files = [cmd] else: files = [cmd + ext for ext in pathext] else: # On other platforms you don't have things like PATHEXT to tell you # what file suffixes are executable, so just pass on cmd as-is. files = [cmd] seen = set() for dir in path: normdir = os.path.normcase(dir) if not normdir in seen: seen.add(normdir) for thefile in files: name = os.path.join(dir, thefile) if _access_check(name, mode): return name return None
40,024
1,156
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/plistlib.py
r"""plistlib.py -- a tool to generate and parse MacOSX .plist files. The property list (.plist) file format is a simple XML pickle supporting basic object types, like dictionaries, lists, numbers and strings. Usually the top level object is a dictionary. To write out a plist file, use the dump(value, file) function. 'value' is the top level object, 'file' is a (writable) file object. To parse a plist from a file, use the load(file) function, with a (readable) file object as the only argument. It returns the top level object (again, usually a dictionary). To work with plist data in bytes objects, you can use loads() and dumps(). Values can be strings, integers, floats, booleans, tuples, lists, dictionaries (but only with string keys), Data, bytes, bytearray, or datetime.datetime objects. Generate Plist example: pl = dict( aString = "Doodah", aList = ["A", "B", 12, 32.1, [1, 2, 3]], aFloat = 0.1, anInt = 728, aDict = dict( anotherString = "<hello & hi there!>", aUnicodeValue = "M\xe4ssig, Ma\xdf", aTrueValue = True, aFalseValue = False, ), someData = b"<binary gunk>", someMoreData = b"<lots of binary gunk>" * 10, aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), ) with open(fileName, 'wb') as fp: dump(pl, fp) Parse Plist example: with open(fileName, 'rb') as fp: pl = load(fp) print(pl["aKey"]) """ __all__ = [ "readPlist", "writePlist", "readPlistFromBytes", "writePlistToBytes", "Plist", "Data", "Dict", "InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps" ] import binascii import codecs import contextlib import datetime import enum from io import BytesIO import itertools import os import re import struct from warnings import warn from xml.parsers.expat import ParserCreate PlistFormat = enum.Enum('PlistFormat', 'FMT_XML FMT_BINARY', module=__name__) globals().update(PlistFormat.__members__) # # # Deprecated functionality # # class _InternalDict(dict): # This class is needed while Dict is scheduled for deprecation: # we only need to warn when a *user* instantiates Dict or when # the "attribute notation for dict keys" is used. __slots__ = () def __getattr__(self, attr): try: value = self[attr] except KeyError: raise AttributeError(attr) warn("Attribute access from plist dicts is deprecated, use d[key] " "notation instead", DeprecationWarning, 2) return value def __setattr__(self, attr, value): warn("Attribute access from plist dicts is deprecated, use d[key] " "notation instead", DeprecationWarning, 2) self[attr] = value def __delattr__(self, attr): try: del self[attr] except KeyError: raise AttributeError(attr) warn("Attribute access from plist dicts is deprecated, use d[key] " "notation instead", DeprecationWarning, 2) class Dict(_InternalDict): def __init__(self, **kwargs): warn("The plistlib.Dict class is deprecated, use builtin dict instead", DeprecationWarning, 2) super().__init__(**kwargs) @contextlib.contextmanager def _maybe_open(pathOrFile, mode): if isinstance(pathOrFile, str): with open(pathOrFile, mode) as fp: yield fp else: yield pathOrFile class Plist(_InternalDict): """This class has been deprecated. Use dump() and load() functions instead, together with regular dict objects. """ def __init__(self, **kwargs): warn("The Plist class is deprecated, use the load() and " "dump() functions instead", DeprecationWarning, 2) super().__init__(**kwargs) @classmethod def fromFile(cls, pathOrFile): """Deprecated. Use the load() function instead.""" with _maybe_open(pathOrFile, 'rb') as fp: value = load(fp) plist = cls() plist.update(value) return plist def write(self, pathOrFile): """Deprecated. Use the dump() function instead.""" with _maybe_open(pathOrFile, 'wb') as fp: dump(self, fp) def readPlist(pathOrFile): """ Read a .plist from a path or file. pathOrFile should either be a file name, or a readable binary file object. This function is deprecated, use load instead. """ warn("The readPlist function is deprecated, use load() instead", DeprecationWarning, 2) with _maybe_open(pathOrFile, 'rb') as fp: return load(fp, fmt=None, use_builtin_types=False, dict_type=_InternalDict) def writePlist(value, pathOrFile): """ Write 'value' to a .plist file. 'pathOrFile' may either be a file name or a (writable) file object. This function is deprecated, use dump instead. """ warn("The writePlist function is deprecated, use dump() instead", DeprecationWarning, 2) with _maybe_open(pathOrFile, 'wb') as fp: dump(value, fp, fmt=FMT_XML, sort_keys=True, skipkeys=False) def readPlistFromBytes(data): """ Read a plist data from a bytes object. Return the root object. This function is deprecated, use loads instead. """ warn("The readPlistFromBytes function is deprecated, use loads() instead", DeprecationWarning, 2) return load(BytesIO(data), fmt=None, use_builtin_types=False, dict_type=_InternalDict) def writePlistToBytes(value): """ Return 'value' as a plist-formatted bytes object. This function is deprecated, use dumps instead. """ warn("The writePlistToBytes function is deprecated, use dumps() instead", DeprecationWarning, 2) f = BytesIO() dump(value, f, fmt=FMT_XML, sort_keys=True, skipkeys=False) return f.getvalue() class Data: """ Wrapper for binary data. This class is deprecated, use a bytes object instead. """ def __init__(self, data): if not isinstance(data, bytes): raise TypeError("data must be as bytes") self.data = data @classmethod def fromBase64(cls, data): # base64.decodebytes just calls binascii.a2b_base64; # it seems overkill to use both base64 and binascii. return cls(_decode_base64(data)) def asBase64(self, maxlinelength=76): return _encode_base64(self.data, maxlinelength) def __eq__(self, other): if isinstance(other, self.__class__): return self.data == other.data elif isinstance(other, bytes): return self.data == other else: return NotImplemented def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self.data)) # # # End of deprecated functionality # # # # XML support # # XML 'header' PLISTHEADER = b"""\ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> """ # Regex to find any control chars, except for \t \n and \r _controlCharPat = re.compile( r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f" r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]") def _encode_base64(s, maxlinelength=76): # copied from base64.encodebytes(), with added maxlinelength argument maxbinsize = (maxlinelength//4)*3 pieces = [] for i in range(0, len(s), maxbinsize): chunk = s[i : i + maxbinsize] pieces.append(binascii.b2a_base64(chunk)) return b''.join(pieces) def _decode_base64(s): if isinstance(s, str): return binascii.a2b_base64(s.encode("utf-8")) else: return binascii.a2b_base64(s) # Contents should conform to a subset of ISO 8601 # (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'. Smaller units # may be omitted with # a loss of precision) _dateParser = re.compile(r"(?P<year>\d\d\d\d)(?:-(?P<month>\d\d)(?:-(?P<day>\d\d)(?:T(?P<hour>\d\d)(?::(?P<minute>\d\d)(?::(?P<second>\d\d))?)?)?)?)?Z", re.ASCII) def _date_from_string(s): order = ('year', 'month', 'day', 'hour', 'minute', 'second') gd = _dateParser.match(s).groupdict() lst = [] for key in order: val = gd[key] if val is None: break lst.append(int(val)) return datetime.datetime(*lst) def _date_to_string(d): return '%04d-%02d-%02dT%02d:%02d:%02dZ' % ( d.year, d.month, d.day, d.hour, d.minute, d.second ) def _escape(text): m = _controlCharPat.search(text) if m is not None: raise ValueError("strings can't contains control characters; " "use bytes instead") text = text.replace("\r\n", "\n") # convert DOS line endings text = text.replace("\r", "\n") # convert Mac line endings text = text.replace("&", "&amp;") # escape '&' text = text.replace("<", "&lt;") # escape '<' text = text.replace(">", "&gt;") # escape '>' return text class _PlistParser: def __init__(self, use_builtin_types, dict_type): self.stack = [] self.current_key = None self.root = None self._use_builtin_types = use_builtin_types self._dict_type = dict_type def parse(self, fileobj): self.parser = ParserCreate() self.parser.StartElementHandler = self.handle_begin_element self.parser.EndElementHandler = self.handle_end_element self.parser.CharacterDataHandler = self.handle_data self.parser.EntityDeclHandler = self.handle_entity_decl self.parser.ParseFile(fileobj) return self.root def handle_entity_decl(self, entity_name, is_parameter_entity, value, base, system_id, public_id, notation_name): # Reject plist files with entity declarations to avoid XML vulnerabilies in expat. # Regular plist files don't contain those declerations, and Apple's plutil tool does not # accept them either. raise InvalidFileException("XML entity declarations are not supported in plist files") def handle_begin_element(self, element, attrs): self.data = [] handler = getattr(self, "begin_" + element, None) if handler is not None: handler(attrs) def handle_end_element(self, element): handler = getattr(self, "end_" + element, None) if handler is not None: handler() def handle_data(self, data): self.data.append(data) def add_object(self, value): if self.current_key is not None: if not isinstance(self.stack[-1], type({})): raise ValueError("unexpected element at line %d" % self.parser.CurrentLineNumber) self.stack[-1][self.current_key] = value self.current_key = None elif not self.stack: # this is the root object self.root = value else: if not isinstance(self.stack[-1], type([])): raise ValueError("unexpected element at line %d" % self.parser.CurrentLineNumber) self.stack[-1].append(value) def get_data(self): data = ''.join(self.data) self.data = [] return data # element handlers def begin_dict(self, attrs): d = self._dict_type() self.add_object(d) self.stack.append(d) def end_dict(self): if self.current_key: raise ValueError("missing value for key '%s' at line %d" % (self.current_key,self.parser.CurrentLineNumber)) self.stack.pop() def end_key(self): if self.current_key or not isinstance(self.stack[-1], type({})): raise ValueError("unexpected key at line %d" % self.parser.CurrentLineNumber) self.current_key = self.get_data() def begin_array(self, attrs): a = [] self.add_object(a) self.stack.append(a) def end_array(self): self.stack.pop() def end_true(self): self.add_object(True) def end_false(self): self.add_object(False) def end_integer(self): self.add_object(int(self.get_data())) def end_real(self): self.add_object(float(self.get_data())) def end_string(self): self.add_object(self.get_data()) def end_data(self): if self._use_builtin_types: self.add_object(_decode_base64(self.get_data())) else: self.add_object(Data.fromBase64(self.get_data())) def end_date(self): self.add_object(_date_from_string(self.get_data())) class _DumbXMLWriter: def __init__(self, file, indent_level=0, indent="\t"): self.file = file self.stack = [] self._indent_level = indent_level self.indent = indent def begin_element(self, element): self.stack.append(element) self.writeln("<%s>" % element) self._indent_level += 1 def end_element(self, element): assert self._indent_level > 0 assert self.stack.pop() == element self._indent_level -= 1 self.writeln("</%s>" % element) def simple_element(self, element, value=None): if value is not None: value = _escape(value) self.writeln("<%s>%s</%s>" % (element, value, element)) else: self.writeln("<%s/>" % element) def writeln(self, line): if line: # plist has fixed encoding of utf-8 # XXX: is this test needed? if isinstance(line, str): line = line.encode('utf-8') self.file.write(self._indent_level * self.indent) self.file.write(line) self.file.write(b'\n') class _PlistWriter(_DumbXMLWriter): def __init__( self, file, indent_level=0, indent=b"\t", writeHeader=1, sort_keys=True, skipkeys=False): if writeHeader: file.write(PLISTHEADER) _DumbXMLWriter.__init__(self, file, indent_level, indent) self._sort_keys = sort_keys self._skipkeys = skipkeys def write(self, value): self.writeln("<plist version=\"1.0\">") self.write_value(value) self.writeln("</plist>") def write_value(self, value): if isinstance(value, str): self.simple_element("string", value) elif value is True: self.simple_element("true") elif value is False: self.simple_element("false") elif isinstance(value, int): if -1 << 63 <= value < 1 << 64: self.simple_element("integer", "%d" % value) else: raise OverflowError(value) elif isinstance(value, float): self.simple_element("real", repr(value)) elif isinstance(value, dict): self.write_dict(value) elif isinstance(value, Data): self.write_data(value) elif isinstance(value, (bytes, bytearray)): self.write_bytes(value) elif isinstance(value, datetime.datetime): self.simple_element("date", _date_to_string(value)) elif isinstance(value, (tuple, list)): self.write_array(value) else: raise TypeError("unsupported type: %s" % type(value)) def write_data(self, data): self.write_bytes(data.data) def write_bytes(self, data): self.begin_element("data") self._indent_level -= 1 maxlinelength = max( 16, 76 - len(self.indent.replace(b"\t", b" " * 8) * self._indent_level)) for line in _encode_base64(data, maxlinelength).split(b"\n"): if line: self.writeln(line) self._indent_level += 1 self.end_element("data") def write_dict(self, d): if d: self.begin_element("dict") if self._sort_keys: items = sorted(d.items()) else: items = d.items() for key, value in items: if not isinstance(key, str): if self._skipkeys: continue raise TypeError("keys must be strings") self.simple_element("key", key) self.write_value(value) self.end_element("dict") else: self.simple_element("dict") def write_array(self, array): if array: self.begin_element("array") for value in array: self.write_value(value) self.end_element("array") else: self.simple_element("array") def _is_fmt_xml(header): prefixes = (b'<?xml', b'<plist') for pfx in prefixes: if header.startswith(pfx): return True # Also check for alternative XML encodings, this is slightly # overkill because the Apple tools (and plistlib) will not # generate files with these encodings. for bom, encoding in ( (codecs.BOM_UTF8, "utf-8"), (codecs.BOM_UTF16_BE, "utf-16-be"), (codecs.BOM_UTF16_LE, "utf-16-le"), # expat does not support utf-32 #(codecs.BOM_UTF32_BE, "utf-32-be"), #(codecs.BOM_UTF32_LE, "utf-32-le"), ): if not header.startswith(bom): continue for start in prefixes: prefix = bom + start.decode('ascii').encode(encoding) if header[:len(prefix)] == prefix: return True return False # # Binary Plist # class InvalidFileException (ValueError): def __init__(self, message="Invalid file"): ValueError.__init__(self, message) _BINARY_FORMAT = {1: 'B', 2: 'H', 4: 'L', 8: 'Q'} _undefined = object() class _BinaryPlistParser: """ Read or write a binary plist file, following the description of the binary format. Raise InvalidFileException in case of error, otherwise return the root object. see also: http://opensource.apple.com/source/CF/CF-744.18/CFBinaryPList.c """ def __init__(self, use_builtin_types, dict_type): self._use_builtin_types = use_builtin_types self._dict_type = dict_type def parse(self, fp): try: # The basic file format: # HEADER # object... # refid->offset... # TRAILER self._fp = fp self._fp.seek(-32, os.SEEK_END) trailer = self._fp.read(32) if len(trailer) != 32: raise InvalidFileException() ( offset_size, self._ref_size, num_objects, top_object, offset_table_offset ) = struct.unpack('>6xBBQQQ', trailer) self._fp.seek(offset_table_offset) self._object_offsets = self._read_ints(num_objects, offset_size) self._objects = [_undefined] * num_objects return self._read_object(top_object) except (OSError, IndexError, struct.error, OverflowError, ValueError): raise InvalidFileException() def _get_size(self, tokenL): """ return the size of the next object.""" if tokenL == 0xF: m = self._fp.read(1)[0] & 0x3 s = 1 << m f = '>' + _BINARY_FORMAT[s] return struct.unpack(f, self._fp.read(s))[0] return tokenL def _read_ints(self, n, size): data = self._fp.read(size * n) if size in _BINARY_FORMAT: return struct.unpack(f'>{n}{_BINARY_FORMAT[size]}', data) else: if not size or len(data) != size * n: raise InvalidFileException() return tuple(int.from_bytes(data[i: i + size], 'big') for i in range(0, size * n, size)) def _read_refs(self, n): return self._read_ints(n, self._ref_size) def _read_object(self, ref): """ read the object by reference. May recursively read sub-objects (content of an array/dict/set) """ result = self._objects[ref] if result is not _undefined: return result offset = self._object_offsets[ref] self._fp.seek(offset) token = self._fp.read(1)[0] tokenH, tokenL = token & 0xF0, token & 0x0F if token == 0x00: result = None elif token == 0x08: result = False elif token == 0x09: result = True # The referenced source code also mentions URL (0x0c, 0x0d) and # UUID (0x0e), but neither can be generated using the Cocoa libraries. elif token == 0x0f: result = b'' elif tokenH == 0x10: # int result = int.from_bytes(self._fp.read(1 << tokenL), 'big', signed=tokenL >= 3) elif token == 0x22: # real result = struct.unpack('>f', self._fp.read(4))[0] elif token == 0x23: # real result = struct.unpack('>d', self._fp.read(8))[0] elif token == 0x33: # date f = struct.unpack('>d', self._fp.read(8))[0] # timestamp 0 of binary plists corresponds to 1/1/2001 # (year of Mac OS X 10.0), instead of 1/1/1970. result = (datetime.datetime(2001, 1, 1) + datetime.timedelta(seconds=f)) elif tokenH == 0x40: # data s = self._get_size(tokenL) result = self._fp.read(s) if len(result) != s: raise InvalidFileException() if not self._use_builtin_types: result = Data(result) elif tokenH == 0x50: # ascii string s = self._get_size(tokenL) data = self._fp.read(s) if len(data) != s: raise InvalidFileException() result = data.decode('ascii') elif tokenH == 0x60: # unicode string s = self._get_size(tokenL) * 2 data = self._fp.read(s) if len(data) != s: raise InvalidFileException() result = data.decode('utf-16be') # tokenH == 0x80 is documented as 'UID' and appears to be used for # keyed-archiving, not in plists. elif tokenH == 0xA0: # array s = self._get_size(tokenL) obj_refs = self._read_refs(s) result = [] self._objects[ref] = result result.extend(self._read_object(x) for x in obj_refs) # tokenH == 0xB0 is documented as 'ordset', but is not actually # implemented in the Apple reference code. # tokenH == 0xC0 is documented as 'set', but sets cannot be used in # plists. elif tokenH == 0xD0: # dict s = self._get_size(tokenL) key_refs = self._read_refs(s) obj_refs = self._read_refs(s) result = self._dict_type() self._objects[ref] = result try: for k, o in zip(key_refs, obj_refs): result[self._read_object(k)] = self._read_object(o) except TypeError: raise InvalidFileException() else: raise InvalidFileException() self._objects[ref] = result return result def _count_to_size(count): if count < 1 << 8: return 1 elif count < 1 << 16: return 2 elif count << 1 << 32: return 4 else: return 8 _scalars = (str, int, float, datetime.datetime, bytes) class _BinaryPlistWriter (object): def __init__(self, fp, sort_keys, skipkeys): self._fp = fp self._sort_keys = sort_keys self._skipkeys = skipkeys def write(self, value): # Flattened object list: self._objlist = [] # Mappings from object->objectid # First dict has (type(object), object) as the key, # second dict is used when object is not hashable and # has id(object) as the key. self._objtable = {} self._objidtable = {} # Create list of all objects in the plist self._flatten(value) # Size of object references in serialized containers # depends on the number of objects in the plist. num_objects = len(self._objlist) self._object_offsets = [0]*num_objects self._ref_size = _count_to_size(num_objects) self._ref_format = _BINARY_FORMAT[self._ref_size] # Write file header self._fp.write(b'bplist00') # Write object list for obj in self._objlist: self._write_object(obj) # Write refnum->object offset table top_object = self._getrefnum(value) offset_table_offset = self._fp.tell() offset_size = _count_to_size(offset_table_offset) offset_format = '>' + _BINARY_FORMAT[offset_size] * num_objects self._fp.write(struct.pack(offset_format, *self._object_offsets)) # Write trailer sort_version = 0 trailer = ( sort_version, offset_size, self._ref_size, num_objects, top_object, offset_table_offset ) self._fp.write(struct.pack('>5xBBBQQQ', *trailer)) def _flatten(self, value): # First check if the object is in the object table, not used for # containers to ensure that two subcontainers with the same contents # will be serialized as distinct values. if isinstance(value, _scalars): if (type(value), value) in self._objtable: return elif isinstance(value, Data): if (type(value.data), value.data) in self._objtable: return elif id(value) in self._objidtable: return # Add to objectreference map refnum = len(self._objlist) self._objlist.append(value) if isinstance(value, _scalars): self._objtable[(type(value), value)] = refnum elif isinstance(value, Data): self._objtable[(type(value.data), value.data)] = refnum else: self._objidtable[id(value)] = refnum # And finally recurse into containers if isinstance(value, dict): keys = [] values = [] items = value.items() if self._sort_keys: items = sorted(items) for k, v in items: if not isinstance(k, str): if self._skipkeys: continue raise TypeError("keys must be strings") keys.append(k) values.append(v) for o in itertools.chain(keys, values): self._flatten(o) elif isinstance(value, (list, tuple)): for o in value: self._flatten(o) def _getrefnum(self, value): if isinstance(value, _scalars): return self._objtable[(type(value), value)] elif isinstance(value, Data): return self._objtable[(type(value.data), value.data)] else: return self._objidtable[id(value)] def _write_size(self, token, size): if size < 15: self._fp.write(struct.pack('>B', token | size)) elif size < 1 << 8: self._fp.write(struct.pack('>BBB', token | 0xF, 0x10, size)) elif size < 1 << 16: self._fp.write(struct.pack('>BBH', token | 0xF, 0x11, size)) elif size < 1 << 32: self._fp.write(struct.pack('>BBL', token | 0xF, 0x12, size)) else: self._fp.write(struct.pack('>BBQ', token | 0xF, 0x13, size)) def _write_object(self, value): ref = self._getrefnum(value) self._object_offsets[ref] = self._fp.tell() if value is None: self._fp.write(b'\x00') elif value is False: self._fp.write(b'\x08') elif value is True: self._fp.write(b'\x09') elif isinstance(value, int): if value < 0: try: self._fp.write(struct.pack('>Bq', 0x13, value)) except struct.error: raise OverflowError(value) from None elif value < 1 << 8: self._fp.write(struct.pack('>BB', 0x10, value)) elif value < 1 << 16: self._fp.write(struct.pack('>BH', 0x11, value)) elif value < 1 << 32: self._fp.write(struct.pack('>BL', 0x12, value)) elif value < 1 << 63: self._fp.write(struct.pack('>BQ', 0x13, value)) elif value < 1 << 64: self._fp.write(b'\x14' + value.to_bytes(16, 'big', signed=True)) else: raise OverflowError(value) elif isinstance(value, float): self._fp.write(struct.pack('>Bd', 0x23, value)) elif isinstance(value, datetime.datetime): f = (value - datetime.datetime(2001, 1, 1)).total_seconds() self._fp.write(struct.pack('>Bd', 0x33, f)) elif isinstance(value, Data): self._write_size(0x40, len(value.data)) self._fp.write(value.data) elif isinstance(value, (bytes, bytearray)): self._write_size(0x40, len(value)) self._fp.write(value) elif isinstance(value, str): try: t = value.encode('ascii') self._write_size(0x50, len(value)) except UnicodeEncodeError: t = value.encode('utf-16be') self._write_size(0x60, len(t) // 2) self._fp.write(t) elif isinstance(value, (list, tuple)): refs = [self._getrefnum(o) for o in value] s = len(refs) self._write_size(0xA0, s) self._fp.write(struct.pack('>' + self._ref_format * s, *refs)) elif isinstance(value, dict): keyRefs, valRefs = [], [] if self._sort_keys: rootItems = sorted(value.items()) else: rootItems = value.items() for k, v in rootItems: if not isinstance(k, str): if self._skipkeys: continue raise TypeError("keys must be strings") keyRefs.append(self._getrefnum(k)) valRefs.append(self._getrefnum(v)) s = len(keyRefs) self._write_size(0xD0, s) self._fp.write(struct.pack('>' + self._ref_format * s, *keyRefs)) self._fp.write(struct.pack('>' + self._ref_format * s, *valRefs)) else: raise TypeError(value) def _is_fmt_binary(header): return header[:8] == b'bplist00' # # Generic bits # _FORMATS={ FMT_XML: dict( detect=_is_fmt_xml, parser=_PlistParser, writer=_PlistWriter, ), FMT_BINARY: dict( detect=_is_fmt_binary, parser=_BinaryPlistParser, writer=_BinaryPlistWriter, ) } def load(fp, *, fmt=None, use_builtin_types=True, dict_type=dict): """Read a .plist file. 'fp' should be (readable) file object. Return the unpacked root object (which usually is a dictionary). """ if fmt is None: header = fp.read(32) fp.seek(0) for info in _FORMATS.values(): if info['detect'](header): P = info['parser'] break else: raise InvalidFileException() else: P = _FORMATS[fmt]['parser'] p = P(use_builtin_types=use_builtin_types, dict_type=dict_type) return p.parse(fp) def loads(value, *, fmt=None, use_builtin_types=True, dict_type=dict): """Read a .plist file from a bytes object. Return the unpacked root object (which usually is a dictionary). """ fp = BytesIO(value) return load( fp, fmt=fmt, use_builtin_types=use_builtin_types, dict_type=dict_type) def dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False): """Write 'value' to a .plist file. 'fp' should be a (writable) file object. """ if fmt not in _FORMATS: raise ValueError("Unsupported format: %r"%(fmt,)) writer = _FORMATS[fmt]["writer"](fp, sort_keys=sort_keys, skipkeys=skipkeys) writer.write(value) def dumps(value, *, fmt=FMT_XML, skipkeys=False, sort_keys=True): """Return a bytes object with the contents for a .plist file. """ fp = BytesIO() dump(value, fp, fmt=fmt, skipkeys=skipkeys, sort_keys=sort_keys) return fp.getvalue()
32,787
1,059
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/aifc.py
"""Stuff to parse AIFF-C and AIFF files. Unless explicitly stated otherwise, the description below is true both for AIFF-C files and AIFF files. An AIFF-C file has the following structure. +-----------------+ | FORM | +-----------------+ | <size> | +----+------------+ | | AIFC | | +------------+ | | <chunks> | | | . | | | . | | | . | +----+------------+ An AIFF file has the string "AIFF" instead of "AIFC". A chunk consists of an identifier (4 bytes) followed by a size (4 bytes, big endian order), followed by the data. The size field does not include the size of the 8 byte header. The following chunk types are recognized. FVER <version number of AIFF-C defining document> (AIFF-C only). MARK <# of markers> (2 bytes) list of markers: <marker ID> (2 bytes, must be > 0) <position> (4 bytes) <marker name> ("pstring") COMM <# of channels> (2 bytes) <# of sound frames> (4 bytes) <size of the samples> (2 bytes) <sampling frequency> (10 bytes, IEEE 80-bit extended floating point) in AIFF-C files only: <compression type> (4 bytes) <human-readable version of compression type> ("pstring") SSND <offset> (4 bytes, not used by this program) <blocksize> (4 bytes, not used by this program) <sound data> A pstring consists of 1 byte length, a string of characters, and 0 or 1 byte pad to make the total length even. Usage. Reading AIFF files: f = aifc.open(file, 'r') where file is either the name of a file or an open file pointer. The open file pointer must have methods read(), seek(), and close(). In some types of audio files, if the setpos() method is not used, the seek() method is not necessary. This returns an instance of a class with the following public methods: getnchannels() -- returns number of audio channels (1 for mono, 2 for stereo) getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames getcomptype() -- returns compression type ('NONE' for AIFF files) getcompname() -- returns human-readable version of compression type ('not compressed' for AIFF files) getparams() -- returns a namedtuple consisting of all of the above in the above order getmarkers() -- get the list of marks in the audio file or None if there are no marks getmark(id) -- get mark with the specified id (raises an error if the mark does not exist) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position tell() -- return the current position close() -- close the instance (make it unusable) The position returned by tell(), the position given to setpos() and the position of marks are all compatible and have nothing to do with the actual position in the file. The close() method is called automatically when the class instance is destroyed. Writing AIFF files: f = aifc.open(file, 'w') where file is either the name of a file or an open file pointer. The open file pointer must have methods write(), tell(), seek(), and close(). This returns an instance of a class with the following public methods: aiff() -- create an AIFF file (AIFF-C default) aifc() -- create an AIFF-C file setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple) -- set all parameters at once setmark(id, pos, name) -- add specified mark to the list of marks tell() -- return current position in output file (useful in combination with setmark()) writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output file You should set the parameters before the first writeframesraw or writeframes. The total number of frames does not need to be set, but when it is set to the correct value, the header does not have to be patched up. It is best to first set all parameters, perhaps possibly the compression type, and then write audio frames using writeframesraw. When all frames have been written, either call writeframes(b'') or close() to patch up the sizes in the header. Marks can be added anytime. If there are any marks, you must call close() after all frames have been written. The close() method is called automatically when the class instance is destroyed. When a file is opened with the extension '.aiff', an AIFF file is written, otherwise an AIFF-C file is written. This default can be changed by calling aiff() or aifc() before the first writeframes or writeframesraw. """ import struct import builtins import warnings __all__ = ["Error", "open", "openfp"] class Error(Exception): pass _AIFC_version = 0xA2805140 # Version 1 of AIFF-C def _read_long(file): try: return struct.unpack('>l', file.read(4))[0] except struct.error: raise EOFError def _read_ulong(file): try: return struct.unpack('>L', file.read(4))[0] except struct.error: raise EOFError def _read_short(file): try: return struct.unpack('>h', file.read(2))[0] except struct.error: raise EOFError def _read_ushort(file): try: return struct.unpack('>H', file.read(2))[0] except struct.error: raise EOFError def _read_string(file): length = ord(file.read(1)) if length == 0: data = b'' else: data = file.read(length) if length & 1 == 0: dummy = file.read(1) return data _HUGE_VAL = 1.79769313486231e+308 # See <limits.h> def _read_float(f): # 10 bytes expon = _read_short(f) # 2 bytes sign = 1 if expon < 0: sign = -1 expon = expon + 0x8000 himant = _read_ulong(f) # 4 bytes lomant = _read_ulong(f) # 4 bytes if expon == himant == lomant == 0: f = 0.0 elif expon == 0x7FFF: f = _HUGE_VAL else: expon = expon - 16383 f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63) return sign * f def _write_short(f, x): f.write(struct.pack('>h', x)) def _write_ushort(f, x): f.write(struct.pack('>H', x)) def _write_long(f, x): f.write(struct.pack('>l', x)) def _write_ulong(f, x): f.write(struct.pack('>L', x)) def _write_string(f, s): if len(s) > 255: raise ValueError("string exceeds maximum pstring length") f.write(struct.pack('B', len(s))) f.write(s) if len(s) & 1 == 0: f.write(b'\x00') def _write_float(f, x): import math if x < 0: sign = 0x8000 x = x * -1 else: sign = 0 if x == 0: expon = 0 himant = 0 lomant = 0 else: fmant, expon = math.frexp(x) if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN expon = sign|0x7FFF himant = 0 lomant = 0 else: # Finite expon = expon + 16382 if expon < 0: # denormalized fmant = math.ldexp(fmant, expon) expon = 0 expon = expon | sign fmant = math.ldexp(fmant, 32) fsmant = math.floor(fmant) himant = int(fsmant) fmant = math.ldexp(fmant - fsmant, 32) fsmant = math.floor(fmant) lomant = int(fsmant) _write_ushort(f, expon) _write_ulong(f, himant) _write_ulong(f, lomant) from chunk import Chunk from collections import namedtuple _aifc_params = namedtuple('_aifc_params', 'nchannels sampwidth framerate nframes comptype compname') _aifc_params.nchannels.__doc__ = 'Number of audio channels (1 for mono, 2 for stereo)' _aifc_params.sampwidth.__doc__ = 'Sample width in bytes' _aifc_params.framerate.__doc__ = 'Sampling frequency' _aifc_params.nframes.__doc__ = 'Number of audio frames' _aifc_params.comptype.__doc__ = 'Compression type ("NONE" for AIFF files)' _aifc_params.compname.__doc__ = ("""\ A human-readable version of the compression type ('not compressed' for AIFF files)""") class Aifc_read: # Variables used in this class: # # These variables are available to the user though appropriate # methods of this class: # _file -- the open file with methods read(), close(), and seek() # set through the __init__() method # _nchannels -- the number of audio channels # available through the getnchannels() method # _nframes -- the number of audio frames # available through the getnframes() method # _sampwidth -- the number of bytes per audio sample # available through the getsampwidth() method # _framerate -- the sampling frequency # available through the getframerate() method # _comptype -- the AIFF-C compression type ('NONE' if AIFF) # available through the getcomptype() method # _compname -- the human-readable AIFF-C compression type # available through the getcomptype() method # _markers -- the marks in the audio file # available through the getmarkers() and getmark() # methods # _soundpos -- the position in the audio stream # available through the tell() method, set through the # setpos() method # # These variables are used internally only: # _version -- the AIFF-C version number # _decomp -- the decompressor from builtin module cl # _comm_chunk_read -- 1 iff the COMM chunk has been read # _aifc -- 1 iff reading an AIFF-C file # _ssnd_seek_needed -- 1 iff positioned correctly in audio # file for readframes() # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk # _framesize -- size of one frame in the file _file = None # Set here since __del__ checks it def initfp(self, file): self._version = 0 self._convert = None self._markers = [] self._soundpos = 0 self._file = file chunk = Chunk(file) if chunk.getname() != b'FORM': raise Error('file does not start with FORM id') formdata = chunk.read(4) if formdata == b'AIFF': self._aifc = 0 elif formdata == b'AIFC': self._aifc = 1 else: raise Error('not an AIFF or AIFF-C file') self._comm_chunk_read = 0 self._ssnd_chunk = None while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == b'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == b'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == b'FVER': self._version = _read_ulong(chunk) elif chunkname == b'MARK': self._readmark(chunk) chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error('COMM chunk and/or SSND chunk missing') def __init__(self, f): if isinstance(f, str): file_object = builtins.open(f, 'rb') try: self.initfp(file_object) except: file_object.close() raise else: # assume it is an open file object already self.initfp(f) def __enter__(self): return self def __exit__(self, *args): self.close() # # User visible methods. # def getfp(self): return self._file def rewind(self): self._ssnd_seek_needed = 1 self._soundpos = 0 def close(self): file = self._file if file is not None: self._file = None file.close() def tell(self): return self._soundpos def getnchannels(self): return self._nchannels def getnframes(self): return self._nframes def getsampwidth(self): return self._sampwidth def getframerate(self): return self._framerate def getcomptype(self): return self._comptype def getcompname(self): return self._compname ## def getversion(self): ## return self._version def getparams(self): return _aifc_params(self.getnchannels(), self.getsampwidth(), self.getframerate(), self.getnframes(), self.getcomptype(), self.getcompname()) def getmarkers(self): if len(self._markers) == 0: return None return self._markers def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error('marker {0!r} does not exist'.format(id)) def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error('position not in range') self._soundpos = pos self._ssnd_seek_needed = 1 def readframes(self, nframes): if self._ssnd_seek_needed: self._ssnd_chunk.seek(0) dummy = self._ssnd_chunk.read(8) pos = self._soundpos * self._framesize if pos: self._ssnd_chunk.seek(pos + 8) self._ssnd_seek_needed = 0 if nframes == 0: return b'' data = self._ssnd_chunk.read(nframes * self._framesize) if self._convert and data: data = self._convert(data) self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth) return data # # Internal methods. # def _alaw2lin(self, data): import audioop return audioop.alaw2lin(data, 2) def _ulaw2lin(self, data): import audioop return audioop.ulaw2lin(data, 2) def _adpcm2lin(self, data): import audioop if not hasattr(self, '_adpcmstate'): # first time self._adpcmstate = None data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate) return data def _read_comm_chunk(self, chunk): self._nchannels = _read_short(chunk) self._nframes = _read_long(chunk) self._sampwidth = (_read_short(chunk) + 7) // 8 self._framerate = int(_read_float(chunk)) self._framesize = self._nchannels * self._sampwidth if self._aifc: #DEBUG: SGI's soundeditor produces a bad size :-( kludge = 0 if chunk.chunksize == 18: kludge = 1 warnings.warn('Warning: bad COMM chunk size') chunk.chunksize = 23 #DEBUG end self._comptype = chunk.read(4) #DEBUG start if kludge: length = ord(chunk.file.read(1)) if length & 1 == 0: length = length + 1 chunk.chunksize = chunk.chunksize + length chunk.file.seek(-1, 1) #DEBUG end self._compname = _read_string(chunk) if self._comptype != b'NONE': if self._comptype == b'G722': self._convert = self._adpcm2lin elif self._comptype in (b'ulaw', b'ULAW'): self._convert = self._ulaw2lin elif self._comptype in (b'alaw', b'ALAW'): self._convert = self._alaw2lin else: raise Error('unsupported compression type') self._sampwidth = 2 else: self._comptype = b'NONE' self._compname = b'not compressed' def _readmark(self, chunk): nmarkers = _read_short(chunk) # Some files appear to contain invalid counts. # Cope with this by testing for EOF. try: for i in range(nmarkers): id = _read_short(chunk) pos = _read_long(chunk) name = _read_string(chunk) if pos or name: # some files appear to have # dummy markers consisting of # a position 0 and name '' self._markers.append((id, pos, name)) except EOFError: w = ('Warning: MARK chunk contains only %s marker%s instead of %s' % (len(self._markers), '' if len(self._markers) == 1 else 's', nmarkers)) warnings.warn(w) class Aifc_write: # Variables used in this class: # # These variables are user settable through appropriate methods # of this class: # _file -- the open file with methods write(), close(), tell(), seek() # set through the __init__() method # _comptype -- the AIFF-C compression type ('NONE' in AIFF) # set through the setcomptype() or setparams() method # _compname -- the human-readable AIFF-C compression type # set through the setcomptype() or setparams() method # _nchannels -- the number of audio channels # set through the setnchannels() or setparams() method # _sampwidth -- the number of bytes per audio sample # set through the setsampwidth() or setparams() method # _framerate -- the sampling frequency # set through the setframerate() or setparams() method # _nframes -- the number of audio frames written to the header # set through the setnframes() or setparams() method # _aifc -- whether we're writing an AIFF-C file or an AIFF file # set through the aifc() method, reset through the # aiff() method # # These variables are used internally only: # _version -- the AIFF-C version number # _comp -- the compressor from builtin module cl # _nframeswritten -- the number of audio frames actually written # _datalength -- the size of the audio samples written to the header # _datawritten -- the size of the audio samples actually written _file = None # Set here since __del__ checks it def __init__(self, f): if isinstance(f, str): file_object = builtins.open(f, 'wb') try: self.initfp(file_object) except: file_object.close() raise # treat .aiff file extensions as non-compressed audio if f.endswith('.aiff'): self._aifc = 0 else: # assume it is an open file object already self.initfp(f) def initfp(self, file): self._file = file self._version = _AIFC_version self._comptype = b'NONE' self._compname = b'not compressed' self._convert = None self._nchannels = 0 self._sampwidth = 0 self._framerate = 0 self._nframes = 0 self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 self._markers = [] self._marklength = 0 self._aifc = 1 # AIFF-C is default def __del__(self): self.close() def __enter__(self): return self def __exit__(self, *args): self.close() # # User visible methods. # def aiff(self): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._aifc = 0 def aifc(self): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._aifc = 1 def setnchannels(self, nchannels): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if nchannels < 1: raise Error('bad # of channels') self._nchannels = nchannels def getnchannels(self): if not self._nchannels: raise Error('number of channels not set') return self._nchannels def setsampwidth(self, sampwidth): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if sampwidth < 1 or sampwidth > 4: raise Error('bad sample width') self._sampwidth = sampwidth def getsampwidth(self): if not self._sampwidth: raise Error('sample width not set') return self._sampwidth def setframerate(self, framerate): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if framerate <= 0: raise Error('bad frame rate') self._framerate = framerate def getframerate(self): if not self._framerate: raise Error('frame rate not set') return self._framerate def setnframes(self, nframes): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._nframes = nframes def getnframes(self): return self._nframeswritten def setcomptype(self, comptype, compname): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if comptype not in (b'NONE', b'ulaw', b'ULAW', b'alaw', b'ALAW', b'G722'): raise Error('unsupported compression type') self._comptype = comptype self._compname = compname def getcomptype(self): return self._comptype def getcompname(self): return self._compname ## def setversion(self, version): ## if self._nframeswritten: ## raise Error, 'cannot change parameters after starting to write' ## self._version = version def setparams(self, params): nchannels, sampwidth, framerate, nframes, comptype, compname = params if self._nframeswritten: raise Error('cannot change parameters after starting to write') if comptype not in (b'NONE', b'ulaw', b'ULAW', b'alaw', b'ALAW', b'G722'): raise Error('unsupported compression type') self.setnchannels(nchannels) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) self.setcomptype(comptype, compname) def getparams(self): if not self._nchannels or not self._sampwidth or not self._framerate: raise Error('not all parameters set') return _aifc_params(self._nchannels, self._sampwidth, self._framerate, self._nframes, self._comptype, self._compname) def setmark(self, id, pos, name): if id <= 0: raise Error('marker ID must be > 0') if pos < 0: raise Error('marker position must be >= 0') if not isinstance(name, bytes): raise Error('marker name must be bytes') for i in range(len(self._markers)): if id == self._markers[i][0]: self._markers[i] = id, pos, name return self._markers.append((id, pos, name)) def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error('marker {0!r} does not exist'.format(id)) def getmarkers(self): if len(self._markers) == 0: return None return self._markers def tell(self): return self._nframeswritten def writeframesraw(self, data): if not isinstance(data, (bytes, bytearray)): data = memoryview(data).cast('B') self._ensure_header_written(len(data)) nframes = len(data) // (self._sampwidth * self._nchannels) if self._convert: data = self._convert(data) self._file.write(data) self._nframeswritten = self._nframeswritten + nframes self._datawritten = self._datawritten + len(data) def writeframes(self, data): self.writeframesraw(data) if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader() def close(self): if self._file is None: return try: self._ensure_header_written(0) if self._datawritten & 1: # quick pad to even size self._file.write(b'\x00') self._datawritten = self._datawritten + 1 self._writemarkers() if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten or \ self._marklength: self._patchheader() finally: # Prevent ref cycles self._convert = None f = self._file self._file = None f.close() # # Internal methods. # def _lin2alaw(self, data): import audioop return audioop.lin2alaw(data, 2) def _lin2ulaw(self, data): import audioop return audioop.lin2ulaw(data, 2) def _lin2adpcm(self, data): import audioop if not hasattr(self, '_adpcmstate'): self._adpcmstate = None data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate) return data def _ensure_header_written(self, datasize): if not self._nframeswritten: if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): if not self._sampwidth: self._sampwidth = 2 if self._sampwidth != 2: raise Error('sample width must be 2 when compressing ' 'with ulaw/ULAW, alaw/ALAW or G7.22 (ADPCM)') if not self._nchannels: raise Error('# channels not specified') if not self._sampwidth: raise Error('sample width not specified') if not self._framerate: raise Error('sampling rate not specified') self._write_header(datasize) def _init_compression(self): if self._comptype == b'G722': self._convert = self._lin2adpcm elif self._comptype in (b'ulaw', b'ULAW'): self._convert = self._lin2ulaw elif self._comptype in (b'alaw', b'ALAW'): self._convert = self._lin2alaw def _write_header(self, initlength): if self._aifc and self._comptype != b'NONE': self._init_compression() self._file.write(b'FORM') if not self._nframes: self._nframes = initlength // (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth if self._datalength & 1: self._datalength = self._datalength + 1 if self._aifc: if self._comptype in (b'ulaw', b'ULAW', b'alaw', b'ALAW'): self._datalength = self._datalength // 2 if self._datalength & 1: self._datalength = self._datalength + 1 elif self._comptype == b'G722': self._datalength = (self._datalength + 3) // 4 if self._datalength & 1: self._datalength = self._datalength + 1 try: self._form_length_pos = self._file.tell() except (AttributeError, OSError): self._form_length_pos = None commlength = self._write_form_length(self._datalength) if self._aifc: self._file.write(b'AIFC') self._file.write(b'FVER') _write_ulong(self._file, 4) _write_ulong(self._file, self._version) else: self._file.write(b'AIFF') self._file.write(b'COMM') _write_ulong(self._file, commlength) _write_short(self._file, self._nchannels) if self._form_length_pos is not None: self._nframes_pos = self._file.tell() _write_ulong(self._file, self._nframes) if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): _write_short(self._file, 8) else: _write_short(self._file, self._sampwidth * 8) _write_float(self._file, self._framerate) if self._aifc: self._file.write(self._comptype) _write_string(self._file, self._compname) self._file.write(b'SSND') if self._form_length_pos is not None: self._ssnd_length_pos = self._file.tell() _write_ulong(self._file, self._datalength + 8) _write_ulong(self._file, 0) _write_ulong(self._file, 0) def _write_form_length(self, datalength): if self._aifc: commlength = 18 + 5 + len(self._compname) if commlength & 1: commlength = commlength + 1 verslength = 12 else: commlength = 18 verslength = 0 _write_ulong(self._file, 4 + verslength + self._marklength + \ 8 + commlength + 16 + datalength) return commlength def _patchheader(self): curpos = self._file.tell() if self._datawritten & 1: datalength = self._datawritten + 1 self._file.write(b'\x00') else: datalength = self._datawritten if datalength == self._datalength and \ self._nframes == self._nframeswritten and \ self._marklength == 0: self._file.seek(curpos, 0) return self._file.seek(self._form_length_pos, 0) dummy = self._write_form_length(datalength) self._file.seek(self._nframes_pos, 0) _write_ulong(self._file, self._nframeswritten) self._file.seek(self._ssnd_length_pos, 0) _write_ulong(self._file, datalength + 8) self._file.seek(curpos, 0) self._nframes = self._nframeswritten self._datalength = datalength def _writemarkers(self): if len(self._markers) == 0: return self._file.write(b'MARK') length = 2 for marker in self._markers: id, pos, name = marker length = length + len(name) + 1 + 6 if len(name) & 1 == 0: length = length + 1 _write_ulong(self._file, length) self._marklength = length + 8 _write_short(self._file, len(self._markers)) for marker in self._markers: id, pos, name = marker _write_short(self._file, id) _write_ulong(self._file, pos) _write_string(self._file, name) def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in ('r', 'rb'): return Aifc_read(f) elif mode in ('w', 'wb'): return Aifc_write(f) else: raise Error("mode must be 'r', 'rb', 'w', or 'wb'") openfp = open # B/W compatibility if __name__ == '__main__': import sys if not sys.argv[1:]: sys.argv.append('/usr/demos/data/audio/bach.aiff') fn = sys.argv[1] with open(fn, 'r') as f: print("Reading", fn) print("nchannels =", f.getnchannels()) print("nframes =", f.getnframes()) print("sampwidth =", f.getsampwidth()) print("framerate =", f.getframerate()) print("comptype =", f.getcomptype()) print("compname =", f.getcompname()) if sys.argv[2:]: gn = sys.argv[2] print("Writing", gn) with open(gn, 'w') as g: g.setparams(f.getparams()) while 1: data = f.readframes(1024) if not data: break g.writeframes(data) print("Done.")
32,454
945
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/traceback.py
"""Extract, format and print information about Python stack traces.""" import collections import itertools import linecache import sys __all__ = ['extract_stack', 'extract_tb', 'format_exception', 'format_exception_only', 'format_list', 'format_stack', 'format_tb', 'print_exc', 'format_exc', 'print_exception', 'print_last', 'print_stack', 'print_tb', 'clear_frames', 'FrameSummary', 'StackSummary', 'TracebackException', 'walk_stack', 'walk_tb'] # # Formatting and printing lists of traceback lines. # def print_list(extracted_list, file=None): """Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.""" if file is None: file = sys.stderr for item in StackSummary.from_list(extracted_list).format(): print(item, file=file, end="") def format_list(extracted_list): """Format a list of tuples or FrameSummary objects for printing. Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None. """ return StackSummary.from_list(extracted_list).format() # # Printing and Extracting Tracebacks. # def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method. """ print_list(extract_tb(tb, limit=limit), file=file) def format_tb(tb, limit=None): """A shorthand for 'format_list(extract_tb(tb, limit))'.""" return extract_tb(tb, limit=limit).format() def extract_tb(tb, limit=None): """ Return a StackSummary object representing a list of pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a FrameSummary object containing attributes filename, lineno, name, and line representing the information that is usually printed for a stack trace. The line is a string with leading and trailing whitespace stripped; if the source is not available it is None. """ return StackSummary.extract(walk_tb(tb), limit=limit) # # Exception formatting and output. # _cause_message = ( "\nThe above exception was the direct cause " "of the following exception:\n\n") _context_message = ( "\nDuring handling of the above exception, " "another exception occurred:\n\n") def print_exception(etype, value, tb, limit=None, file=None, chain=True): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret on the next line indicating the approximate position of the error. """ # format_exception has ignored etype for some time, and code such as cgitb # passes in bogus values as a result. For compatibility with such code we # ignore it here (rather than in the new TracebackException API). if file is None: file = sys.stderr for line in TracebackException( type(value), value, tb, limit=limit).format(chain=chain): print(line, file=file, end="") def format_exception(etype, value, tb, limit=None, chain=True): """Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception(). """ # format_exception has ignored etype for some time, and code such as cgitb # passes in bogus values as a result. For compatibility with such code we # ignore it here (rather than in the new TracebackException API). return list(TracebackException( type(value), value, tb, limit=limit).format(chain=chain)) def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the list. """ return list(TracebackException(etype, value, None).format_exception_only()) # -- not official API but folk probably use these two functions. def _format_final_exc_line(etype, value): valuestr = _some_str(value) if value is None or not valuestr: line = "%s\n" % etype else: line = "%s: %s\n" % (etype, valuestr) return line def _some_str(value): try: return str(value) except: return '<unprintable %s object>' % type(value).__name__ # -- def print_exc(limit=None, file=None, chain=True): """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'.""" print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain) def format_exc(limit=None, chain=True): """Like print_exc() but return a string.""" return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain)) def print_last(limit=None, file=None, chain=True): """This is a shorthand for 'print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)'.""" if not hasattr(sys, "last_type"): raise ValueError("no last exception") print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain) # # Printing and Extracting Stacks. # def print_stack(f=None, limit=None, file=None): """Print a stack trace from its invocation point. The optional 'f' argument can be used to specify an alternate stack frame at which to start. The optional 'limit' and 'file' arguments have the same meaning as for print_exception(). """ if f is None: f = sys._getframe().f_back print_list(extract_stack(f, limit=limit), file=file) def format_stack(f=None, limit=None): """Shorthand for 'format_list(extract_stack(f, limit))'.""" if f is None: f = sys._getframe().f_back return format_list(extract_stack(f, limit=limit)) def extract_stack(f=None, limit=None): """Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional 'f' and 'limit' arguments have the same meaning as for print_stack(). Each item in the list is a quadruple (filename, line number, function name, text), and the entries are in order from oldest to newest stack frame. """ if f is None: f = sys._getframe().f_back stack = StackSummary.extract(walk_stack(f), limit=limit) stack.reverse() return stack def clear_frames(tb): "Clear all references to local variables in the frames of a traceback." while tb is not None: try: tb.tb_frame.clear() except RuntimeError: # Ignore the exception raised if the frame is still executing. pass tb = tb.tb_next class FrameSummary: """A single frame from a traceback. - :attr:`filename` The filename for the frame. - :attr:`lineno` The line within filename for the frame that was active when the frame was captured. - :attr:`name` The name of the function or method that was executing when the frame was captured. - :attr:`line` The text from the linecache module for the of code that was running when the frame was captured. - :attr:`locals` Either None if locals were not supplied, or a dict mapping the name to the repr() of the variable. """ __slots__ = ('filename', 'lineno', 'name', '_line', 'locals') def __init__(self, filename, lineno, name, *, lookup_line=True, locals=None, line=None): """Construct a FrameSummary. :param lookup_line: If True, `linecache` is consulted for the source code line. Otherwise, the line will be looked up when first needed. :param locals: If supplied the frame locals, which will be captured as object representations. :param line: If provided, use this instead of looking up the line in the linecache. """ self.filename = filename self.lineno = lineno self.name = name self._line = line if lookup_line: self.line self.locals = \ dict((k, repr(v)) for k, v in locals.items()) if locals else None def __eq__(self, other): if isinstance(other, FrameSummary): return (self.filename == other.filename and self.lineno == other.lineno and self.name == other.name and self.locals == other.locals) if isinstance(other, tuple): return (self.filename, self.lineno, self.name, self.line) == other return NotImplemented def __getitem__(self, pos): return (self.filename, self.lineno, self.name, self.line)[pos] def __iter__(self): return iter([self.filename, self.lineno, self.name, self.line]) def __repr__(self): return "<FrameSummary file {filename}, line {lineno} in {name}>".format( filename=self.filename, lineno=self.lineno, name=self.name) @property def line(self): if self._line is None: self._line = linecache.getline(self.filename, self.lineno).strip() return self._line def walk_stack(f): """Walk a stack yielding the frame and line number for each frame. This will follow f.f_back from the given frame. If no frame is given, the current stack is used. Usually used with StackSummary.extract. """ if f is None: f = sys._getframe().f_back.f_back while f is not None: yield f, f.f_lineno f = f.f_back def walk_tb(tb): """Walk a traceback yielding the frame and line number for each frame. This will follow tb.tb_next (and thus is in the opposite order to walk_stack). Usually used with StackSummary.extract. """ while tb is not None: yield tb.tb_frame, tb.tb_lineno tb = tb.tb_next _RECURSIVE_CUTOFF = 3 # Also hardcoded in traceback.c. class StackSummary(list): """A stack of frames.""" @classmethod def extract(klass, frame_gen, *, limit=None, lookup_lines=True, capture_locals=False): """Create a StackSummary from a traceback or stack object. :param frame_gen: A generator that yields (frame, lineno) tuples to include in the stack. :param limit: None to include all frames or the number of frames to include. :param lookup_lines: If True, lookup lines for each frame immediately, otherwise lookup is deferred until the frame is rendered. :param capture_locals: If True, the local variables from each frame will be captured as object representations into the FrameSummary. """ if limit is None: limit = getattr(sys, 'tracebacklimit', None) if limit is not None and limit < 0: limit = 0 if limit is not None: if limit >= 0: frame_gen = itertools.islice(frame_gen, limit) else: frame_gen = collections.deque(frame_gen, maxlen=-limit) result = klass() fnames = set() for f, lineno in frame_gen: co = f.f_code filename = co.co_filename name = co.co_name fnames.add(filename) linecache.lazycache(filename, f.f_globals) # Must defer line lookups until we have called checkcache. if capture_locals: f_locals = f.f_locals else: f_locals = None result.append(FrameSummary( filename, lineno, name, lookup_line=False, locals=f_locals)) for filename in fnames: linecache.checkcache(filename) # If immediate lookup was desired, trigger lookups now. if lookup_lines: for f in result: f.line return result @classmethod def from_list(klass, a_list): """ Create a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. """ # While doing a fast-path check for isinstance(a_list, StackSummary) is # appealing, idlelib.run.cleanup_traceback and other similar code may # break this by making arbitrary frames plain tuples, so we need to # check on a frame by frame basis. result = StackSummary() for frame in a_list: if isinstance(frame, FrameSummary): result.append(frame) else: filename, lineno, name, line = frame result.append(FrameSummary(filename, lineno, name, line=line)) return result def format(self): """Format the stack ready for printing. Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines. For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions. """ result = [] last_file = None last_line = None last_name = None count = 0 for frame in self: if (last_file is None or last_file != frame.filename or last_line is None or last_line != frame.lineno or last_name is None or last_name != frame.name): if count > _RECURSIVE_CUTOFF: count -= _RECURSIVE_CUTOFF result.append( f' [Previous line repeated {count} more ' f'time{"s" if count > 1 else ""}]\n' ) last_file = frame.filename last_line = frame.lineno last_name = frame.name count = 0 count += 1 if count > _RECURSIVE_CUTOFF: continue row = [] row.append(' File "{}", line {}, in {}\n'.format( frame.filename, frame.lineno, frame.name)) if frame.line: row.append(' {}\n'.format(frame.line.strip())) if frame.locals: for name, value in sorted(frame.locals.items()): row.append(' {name} = {value}\n'.format(name=name, value=value)) result.append(''.join(row)) if count > _RECURSIVE_CUTOFF: count -= _RECURSIVE_CUTOFF result.append( f' [Previous line repeated {count} more ' f'time{"s" if count > 1 else ""}]\n' ) return result class TracebackException: """An exception ready for rendering. The traceback module captures enough attributes from the original exception to this intermediary form to ensure that no references are held, while still being able to fully print or format it. Use `from_exception` to create TracebackException instances from exception objects, or the constructor to create TracebackException instances from individual components. - :attr:`__cause__` A TracebackException of the original *__cause__*. - :attr:`__context__` A TracebackException of the original *__context__*. - :attr:`__suppress_context__` The *__suppress_context__* value from the original exception. - :attr:`stack` A `StackSummary` representing the traceback. - :attr:`exc_type` The class of the original traceback. - :attr:`filename` For syntax errors - the filename where the error occurred. - :attr:`lineno` For syntax errors - the linenumber where the error occurred. - :attr:`text` For syntax errors - the text where the error occurred. - :attr:`offset` For syntax errors - the offset into the text where the error occurred. - :attr:`msg` For syntax errors - the compiler error message. """ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False, _seen=None): # NB: we need to accept exc_traceback, exc_value, exc_traceback to # permit backwards compat with the existing API, otherwise we # need stub thunk objects just to glue it together. # Handle loops in __cause__ or __context__. if _seen is None: _seen = set() _seen.add(id(exc_value)) # Gracefully handle (the way Python 2.4 and earlier did) the case of # being called with no type or value (None, None, None). if (exc_value and exc_value.__cause__ is not None and id(exc_value.__cause__) not in _seen): cause = TracebackException( type(exc_value.__cause__), exc_value.__cause__, exc_value.__cause__.__traceback__, limit=limit, lookup_lines=False, capture_locals=capture_locals, _seen=_seen) else: cause = None if (exc_value and exc_value.__context__ is not None and id(exc_value.__context__) not in _seen): context = TracebackException( type(exc_value.__context__), exc_value.__context__, exc_value.__context__.__traceback__, limit=limit, lookup_lines=False, capture_locals=capture_locals, _seen=_seen) else: context = None self.exc_traceback = exc_traceback self.__cause__ = cause self.__context__ = context self.__suppress_context__ = \ exc_value.__suppress_context__ if exc_value else False # TODO: locals. self.stack = StackSummary.extract( walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines, capture_locals=capture_locals) self.exc_type = exc_type # Capture now to permit freeing resources: only complication is in the # unofficial API _format_final_exc_line self._str = _some_str(exc_value) if exc_type and issubclass(exc_type, SyntaxError): # Handle SyntaxError's specially self.filename = exc_value.filename self.lineno = str(exc_value.lineno) self.text = exc_value.text self.offset = exc_value.offset self.msg = exc_value.msg if lookup_lines: self._load_lines() @classmethod def from_exception(cls, exc, *args, **kwargs): """Create a TracebackException from an exception.""" return cls(type(exc), exc, exc.__traceback__, *args, **kwargs) def _load_lines(self): """Private API. force all lines in the stack to be loaded.""" for frame in self.stack: frame.line if self.__context__: self.__context__._load_lines() if self.__cause__: self.__cause__._load_lines() def __eq__(self, other): return self.__dict__ == other.__dict__ def __str__(self): return self._str def format_exception_only(self): """Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emites several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. """ if self.exc_type is None: yield _format_final_exc_line(None, self._str) return stype = self.exc_type.__qualname__ smod = self.exc_type.__module__ if smod not in ("__main__", "builtins"): stype = smod + '.' + stype if not issubclass(self.exc_type, SyntaxError): yield _format_final_exc_line(stype, self._str) return # It was a syntax error; show exactly where the problem was found. filename = self.filename or "<string>" lineno = str(self.lineno) or '?' yield ' File "{}", line {}\n'.format(filename, lineno) badline = self.text offset = self.offset if badline is not None: yield ' {}\n'.format(badline.strip()) if offset is not None: caretspace = badline.rstrip('\n') offset = min(len(caretspace), offset) - 1 caretspace = caretspace[:offset].lstrip() # non-space whitespace (likes tabs) must be kept for alignment caretspace = ((c.isspace() and c or ' ') for c in caretspace) yield ' {}^\n'.format(''.join(caretspace)) msg = self.msg or "<no detail available>" yield "{}: {}\n".format(stype, msg) def format(self, *, chain=True): """Format the exception. If chain is not *True*, *__cause__* and *__context__* will not be formatted. The return value is a generator of strings, each ending in a newline and some containing internal newlines. `print_exception` is a wrapper around this method which just prints the lines to a file. The message indicating which exception occurred is always the last string in the output. """ if chain: if self.__cause__ is not None: yield from self.__cause__.format(chain=chain) yield _cause_message elif (self.__context__ is not None and not self.__suppress_context__): yield from self.__context__.format(chain=chain) yield _context_message if self.exc_traceback is not None: yield 'Traceback (most recent call last):\n' yield from self.stack.format() yield from self.format_exception_only()
23,458
613
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/zipapp.py
import contextlib import os import pathlib import shutil import stat import sys import zipfile __all__ = ['ZipAppError', 'create_archive', 'get_interpreter'] # The __main__.py used if the users specifies "-m module:fn". # Note that this will always be written as UTF-8 (module and # function names can be non-ASCII in Python 3). # We add a coding cookie even though UTF-8 is the default in Python 3 # because the resulting archive may be intended to be run under Python 2. MAIN_TEMPLATE = """\ # -*- coding: utf-8 -*- import {module} {module}.{fn}() """ # The Windows launcher defaults to UTF-8 when parsing shebang lines if the # file has no BOM. So use UTF-8 on Windows. # On Unix, use the filesystem encoding. if sys.platform.startswith('win'): shebang_encoding = 'utf-8' else: shebang_encoding = sys.getfilesystemencoding() class ZipAppError(ValueError): pass @contextlib.contextmanager def _maybe_open(archive, mode): if isinstance(archive, pathlib.Path): archive = str(archive) if isinstance(archive, str): with open(archive, mode) as f: yield f else: yield archive def _write_file_prefix(f, interpreter): """Write a shebang line.""" if interpreter: shebang = b'#!' + interpreter.encode(shebang_encoding) + b'\n' f.write(shebang) def _copy_archive(archive, new_archive, interpreter=None): """Copy an application archive, modifying the shebang line.""" with _maybe_open(archive, 'rb') as src: # Skip the shebang line from the source. # Read 2 bytes of the source and check if they are #!. first_2 = src.read(2) if first_2 == b'#!': # Discard the initial 2 bytes and the rest of the shebang line. first_2 = b'' src.readline() with _maybe_open(new_archive, 'wb') as dst: _write_file_prefix(dst, interpreter) # If there was no shebang, "first_2" contains the first 2 bytes # of the source file, so write them before copying the rest # of the file. dst.write(first_2) shutil.copyfileobj(src, dst) if interpreter and isinstance(new_archive, str): os.chmod(new_archive, os.stat(new_archive).st_mode | stat.S_IEXEC) def create_archive(source, target=None, interpreter=None, main=None): """Create an application archive from SOURCE. The SOURCE can be the name of a directory, or a filename or a file-like object referring to an existing archive. The content of SOURCE is packed into an application archive in TARGET, which can be a filename or a file-like object. If SOURCE is a directory, TARGET can be omitted and will default to the name of SOURCE with .pyz appended. The created application archive will have a shebang line specifying that it should run with INTERPRETER (there will be no shebang line if INTERPRETER is None), and a __main__.py which runs MAIN (if MAIN is not specified, an existing __main__.py will be used). It is an error to specify MAIN for anything other than a directory source with no __main__.py, and it is an error to omit MAIN if the directory has no __main__.py. """ # Are we copying an existing archive? source_is_file = False if hasattr(source, 'read') and hasattr(source, 'readline'): source_is_file = True else: source = pathlib.Path(source) if source.is_file(): source_is_file = True if source_is_file: _copy_archive(source, target, interpreter) return # We are creating a new archive from a directory. if not source.exists(): raise ZipAppError("Source does not exist") has_main = (source / '__main__.py').is_file() if main and has_main: raise ZipAppError( "Cannot specify entry point if the source has __main__.py") if not (main or has_main): raise ZipAppError("Archive has no entry point") main_py = None if main: # Check that main has the right format. mod, sep, fn = main.partition(':') mod_ok = all(part.isidentifier() for part in mod.split('.')) fn_ok = all(part.isidentifier() for part in fn.split('.')) if not (sep == ':' and mod_ok and fn_ok): raise ZipAppError("Invalid entry point: " + main) main_py = MAIN_TEMPLATE.format(module=mod, fn=fn) if target is None: target = source.with_suffix('.pyz') elif not hasattr(target, 'write'): target = pathlib.Path(target) with _maybe_open(target, 'wb') as fd: _write_file_prefix(fd, interpreter) with zipfile.ZipFile(fd, 'w') as z: root = pathlib.Path(source) for child in root.rglob('*'): arcname = str(child.relative_to(root)) z.write(str(child), arcname) if main_py: z.writestr('__main__.py', main_py.encode('utf-8')) if interpreter and not hasattr(target, 'write'): target.chmod(target.stat().st_mode | stat.S_IEXEC) def get_interpreter(archive): with _maybe_open(archive, 'rb') as f: if f.read(2) == b'#!': return f.readline().strip().decode(shebang_encoding) def main(args=None): """Run the zipapp command line interface. The ARGS parameter lets you specify the argument list directly. Omitting ARGS (or setting it to None) works as for argparse, using sys.argv[1:] as the argument list. """ import argparse parser = argparse.ArgumentParser() parser.add_argument('--output', '-o', default=None, help="The name of the output archive. " "Required if SOURCE is an archive.") parser.add_argument('--python', '-p', default=None, help="The name of the Python interpreter to use " "(default: no shebang line).") parser.add_argument('--main', '-m', default=None, help="The main function of the application " "(default: use an existing __main__.py).") parser.add_argument('--info', default=False, action='store_true', help="Display the interpreter from the archive.") parser.add_argument('source', help="Source directory (or existing archive).") args = parser.parse_args(args) # Handle `python -m zipapp archive.pyz --info`. if args.info: if not os.path.isfile(args.source): raise SystemExit("Can only get info for an archive file") interpreter = get_interpreter(args.source) print("Interpreter: {}".format(interpreter or "<none>")) sys.exit(0) if os.path.isfile(args.source): if args.output is None or (os.path.exists(args.output) and os.path.samefile(args.source, args.output)): raise SystemExit("In-place editing of archives is not supported") if args.main: raise SystemExit("Cannot change the main function when copying") create_archive(args.source, args.output, interpreter=args.python, main=args.main) if __name__ == '__main__': main()
7,157
202
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/re.py
# # Secret Labs' Regular Expression Engine # # re-compatible interface for the sre matching engine # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # This version of the SRE library can be redistributed under CNRI's # Python 1.6 license. For any other use, please contact Secret Labs # AB ([email protected]). # # Portions of this engine have been developed in cooperation with # CNRI. Hewlett-Packard provided funding for 1.6 integration and # other compatibility work. # r"""Support for regular expressions (RE). This module provides regular expression matching operations similar to those found in Perl. It supports both 8-bit and Unicode strings; both the pattern and the strings being processed can contain null bytes and characters outside the US ASCII range. Regular expressions can contain both special and ordinary characters. Most ordinary characters, like "A", "a", or "0", are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last'. The special characters are: "." Matches any character except a newline. "^" Matches the start of the string. "$" Matches the end of the string or just before the newline at the end of the string. "*" Matches 0 or more (greedy) repetitions of the preceding RE. Greedy means that it will match as many repetitions as possible. "+" Matches 1 or more (greedy) repetitions of the preceding RE. "?" Matches 0 or 1 (greedy) of the preceding RE. *?,+?,?? Non-greedy versions of the previous three special characters. {m,n} Matches from m to n repetitions of the preceding RE. {m,n}? Non-greedy version of the above. "\\" Either escapes special characters or signals a special sequence. [] Indicates a set of characters. A "^" as the first character indicates a complementing set. "|" A|B, creates an RE that will match either A or B. (...) Matches the RE inside the parentheses. The contents can be retrieved or matched later in the string. (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below). (?:...) Non-grouping version of regular parentheses. (?P<name>...) The substring matched by the group is accessible by name. (?P=name) Matches the text matched earlier by the group named name. (?#...) A comment; ignored. (?=...) Matches if ... matches next, but doesn't consume the string. (?!...) Matches if ... doesn't match next. (?<=...) Matches if preceded by ... (must be fixed length). (?<!...) Matches if not preceded by ... (must be fixed length). (?(id/name)yes|no) Matches yes pattern if the group with id/name matched, the (optional) no pattern otherwise. The special sequences consist of "\\" and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. \number Matches the contents of the group of the same number. \A Matches only at the start of the string. \Z Matches only at the end of the string. \b Matches the empty string, but only at the start or end of a word. \B Matches the empty string, but not at the start or end of a word. \d Matches any decimal digit; equivalent to the set [0-9] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the whole range of Unicode digits. \D Matches any non-digit character; equivalent to [^\d]. \s Matches any whitespace character; equivalent to [ \t\n\r\f\v] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the whole range of Unicode whitespace characters. \S Matches any non-whitespace character; equivalent to [^\s]. \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the range of Unicode alphanumeric characters (letters plus digits plus underscore). With LOCALE, it will match the set [0-9_] plus characters defined as letters for the current locale. \W Matches the complement of \w. \\ Matches a literal backslash. This module exports the following functions: match Match a regular expression pattern to the beginning of a string. fullmatch Match a regular expression pattern to all of a string. search Search a string for the presence of a pattern. sub Substitute occurrences of a pattern found in a string. subn Same as sub, but also return the number of substitutions made. split Split a string by the occurrences of a pattern. findall Find all occurrences of a pattern in a string. finditer Return an iterator yielding a match object for each match. compile Compile a pattern into a RegexObject. purge Clear the regular expression cache. escape Backslash all non-alphanumerics in a string. Some of the functions in this module takes flags as optional parameters: A ASCII For string patterns, make \w, \W, \b, \B, \d, \D match the corresponding ASCII character categories (rather than the whole Unicode categories, which is the default). For bytes patterns, this flag is the only available behaviour and needn't be specified. I IGNORECASE Perform case-insensitive matching. L LOCALE Make \w, \W, \b, \B, dependent on the current locale. M MULTILINE "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. S DOTALL "." matches any character at all, including the newline. X VERBOSE Ignore whitespace and comments for nicer looking RE's. U UNICODE For compatibility only. Ignored for string patterns (it is the default), and forbidden for bytes patterns. This module also defines an exception 'error'. """ import enum import sre_compile import sre_parse import functools import _locale # public symbols __all__ = [ "match", "fullmatch", "search", "sub", "subn", "split", "findall", "finditer", "compile", "purge", "template", "escape", "error", "A", "I", "L", "M", "S", "X", "U", "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE", "UNICODE", ] __version__ = "2.2.1" class RegexFlag(enum.IntFlag): ASCII = sre_compile.SRE_FLAG_ASCII # assume ascii "locale" IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode "locale" MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments A = ASCII I = IGNORECASE L = LOCALE U = UNICODE M = MULTILINE S = DOTALL X = VERBOSE # sre extensions (experimental, don't rely on these) TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking T = TEMPLATE DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation ASCII = RegexFlag.ASCII IGNORECASE = RegexFlag.IGNORECASE LOCALE = RegexFlag.LOCALE UNICODE = RegexFlag.UNICODE MULTILINE = RegexFlag.MULTILINE DOTALL = RegexFlag.DOTALL VERBOSE = RegexFlag.VERBOSE A = RegexFlag.A I = RegexFlag.I L = RegexFlag.L U = RegexFlag.U M = RegexFlag.M S = RegexFlag.S X = RegexFlag.X TEMPLATE = RegexFlag.TEMPLATE T = RegexFlag.T DEBUG = RegexFlag.DEBUG # sre exception error = sre_compile.error # -------------------------------------------------------------------- # public interface def match(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object, or None if no match was found.""" return _compile(pattern, flags).match(string) def fullmatch(pattern, string, flags=0): """Try to apply the pattern to all of the string, returning a match object, or None if no match was found.""" return _compile(pattern, flags).fullmatch(string) def search(pattern, string, flags=0): """Scan through string looking for a match to the pattern, returning a match object, or None if no match was found.""" return _compile(pattern, flags).search(string) def sub(pattern, repl, string, count=0, flags=0): """Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.""" return _compile(pattern, flags).sub(repl, string, count) def subn(pattern, repl, string, count=0, flags=0): """Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in the source string by the replacement repl. number is the number of substitutions that were made. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.""" return _compile(pattern, flags).subn(repl, string, count) def split(pattern, string, maxsplit=0, flags=0): """Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.""" return _compile(pattern, flags).split(string, maxsplit) def findall(pattern, string, flags=0): """Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.""" return _compile(pattern, flags).findall(string) def finditer(pattern, string, flags=0): """Return an iterator over all non-overlapping matches in the string. For each match, the iterator returns a match object. Empty matches are included in the result.""" return _compile(pattern, flags).finditer(string) def compile(pattern, flags=0): "Compile a regular expression pattern, returning a pattern object." return _compile(pattern, flags) def purge(): "Clear the regular expression caches" _cache.clear() _compile_repl.cache_clear() def template(pattern, flags=0): "Compile a template pattern, returning a pattern object" return _compile(pattern, flags|T) _alphanum_str = frozenset( "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890") _alphanum_bytes = frozenset( b"_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890") def escape(pattern): """ Escape all the characters in pattern except ASCII letters, numbers and '_'. """ if isinstance(pattern, str): alphanum = _alphanum_str s = list(pattern) for i, c in enumerate(pattern): if c not in alphanum: if c == "\000": s[i] = "\\000" else: s[i] = "\\" + c return "".join(s) else: alphanum = _alphanum_bytes s = [] esc = ord(b"\\") for c in pattern: if c in alphanum: s.append(c) else: if c == 0: s.extend(b"\\000") else: s.append(esc) s.append(c) return bytes(s) # -------------------------------------------------------------------- # internals _cache = {} _pattern_type = type(sre_compile.compile("", 0)) _MAXCACHE = 512 def _compile(pattern, flags): # internal: compile pattern try: p, loc = _cache[type(pattern), pattern, flags] if loc is None or loc == _locale.setlocale(_locale.LC_CTYPE): return p except KeyError: pass if isinstance(pattern, _pattern_type): if flags: raise ValueError( "cannot process flags argument with a compiled pattern") return pattern if not sre_compile.isstring(pattern): raise TypeError("first argument must be string or compiled pattern") p = sre_compile.compile(pattern, flags) if not (flags & DEBUG): if len(_cache) >= _MAXCACHE: _cache.clear() if p.flags & LOCALE: if not _locale: return p loc = _locale.setlocale(_locale.LC_CTYPE) else: loc = None _cache[type(pattern), pattern, flags] = p, loc return p @functools.lru_cache(_MAXCACHE) def _compile_repl(repl, pattern): # internal: compile replacement pattern return sre_parse.parse_template(repl, pattern) def _expand(pattern, match, template): # internal: match.expand implementation hook template = sre_parse.parse_template(template, pattern) return sre_parse.expand_template(template, match) def _subx(pattern, template): # internal: pattern.sub/subn implementation helper template = _compile_repl(template, pattern) if not template[0] and len(template[1]) == 1: # literal replacement return template[1][0] def filter(match, template=template): return sre_parse.expand_template(template, match) return filter # register myself for pickling import copyreg def _pickle(p): return _compile, (p.pattern, p.flags) copyreg.pickle(_pattern_type, _pickle, _compile) # -------------------------------------------------------------------- # experimental stuff (see python-dev discussions for details) class Scanner: def __init__(self, lexicon, flags=0): from sre_constants import BRANCH, SUBPATTERN self.lexicon = lexicon # combine phrases into a compound pattern p = [] s = sre_parse.Pattern() s.flags = flags for phrase, action in lexicon: gid = s.opengroup() p.append(sre_parse.SubPattern(s, [ (SUBPATTERN, (gid, 0, 0, sre_parse.parse(phrase, flags))), ])) s.closegroup(gid, p[-1]) p = sre_parse.SubPattern(s, [(BRANCH, (None, p))]) self.scanner = sre_compile.compile(p) def scan(self, string): result = [] append = result.append match = self.scanner.scanner(string).match i = 0 while True: m = match() if not m: break j = m.end() if i == j: break action = self.lexicon[m.lastindex-1][1] if callable(action): self.match = m action = action(self, m.group()) if action is not None: append(action) i = j return result, string[i:]
15,845
396
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/platform.py
#!/usr/bin/env python3 """ This module tries to retrieve as much platform-identifying data as possible. It makes this information available via function APIs. If called from the command line, it prints the platform information concatenated as single string to stdout. The output format is useable as part of a filename. """ # This module is maintained by Marc-Andre Lemburg <[email protected]>. # If you find problems, please submit bug reports/patches via the # Python bug tracker (http://bugs.python.org) and assign them to "lemburg". # # Still needed: # * support for MS-DOS (PythonDX ?) # * support for Amiga and other still unsupported platforms running Python # * support for additional Linux distributions # # Many thanks to all those who helped adding platform-specific # checks (in no particular order): # # Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell, # Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef # Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg # Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark # Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support), # Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter, Steve # Dower # # History: # # <see CVS and SVN checkin messages for history> # # 1.0.8 - changed Windows support to read version from kernel32.dll # 1.0.7 - added DEV_NULL # 1.0.6 - added linux_distribution() # 1.0.5 - fixed Java support to allow running the module on Jython # 1.0.4 - added IronPython support # 1.0.3 - added normalization of Windows system name # 1.0.2 - added more Windows support # 1.0.1 - reformatted to make doc.py happy # 1.0.0 - reformatted a bit and checked into Python CVS # 0.8.0 - added sys.version parser and various new access # APIs (python_version(), python_compiler(), etc.) # 0.7.2 - fixed architecture() to use sizeof(pointer) where available # 0.7.1 - added support for Caldera OpenLinux # 0.7.0 - some fixes for WinCE; untabified the source file # 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and # vms_lib.getsyi() configured # 0.6.1 - added code to prevent 'uname -p' on platforms which are # known not to support it # 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k; # did some cleanup of the interfaces - some APIs have changed # 0.5.5 - fixed another type in the MacOS code... should have # used more coffee today ;-) # 0.5.4 - fixed a few typos in the MacOS code # 0.5.3 - added experimental MacOS support; added better popen() # workarounds in _syscmd_ver() -- still not 100% elegant # though # 0.5.2 - fixed uname() to return '' instead of 'unknown' in all # return values (the system uname command tends to return # 'unknown' instead of just leaving the field empty) # 0.5.1 - included code for slackware dist; added exception handlers # to cover up situations where platforms don't have os.popen # (e.g. Mac) or fail on socket.gethostname(); fixed libc # detection RE # 0.5.0 - changed the API names referring to system commands to *syscmd*; # added java_ver(); made syscmd_ver() a private # API (was system_ver() in previous versions) -- use uname() # instead; extended the win32_ver() to also return processor # type information # 0.4.0 - added win32_ver() and modified the platform() output for WinXX # 0.3.4 - fixed a bug in _follow_symlinks() # 0.3.3 - fixed popen() and "file" command invokation bugs # 0.3.2 - added architecture() API and support for it in platform() # 0.3.1 - fixed syscmd_ver() RE to support Windows NT # 0.3.0 - added system alias support # 0.2.3 - removed 'wince' again... oh well. # 0.2.2 - added 'wince' to syscmd_ver() supported platforms # 0.2.1 - added cache logic and changed the platform string format # 0.2.0 - changed the API to use functions instead of module globals # since some action take too long to be run on module import # 0.1.0 - first release # # You can always get the latest version of this module at: # # http://www.egenix.com/files/python/platform.py # # If that URL should fail, try contacting the author. __copyright__ = """ Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:[email protected] Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:[email protected] Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee or royalty is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation or portions thereof, including modifications, that you make. EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! """ __version__ = '1.0.8' import collections import sys, os, re, subprocess import warnings ### Globals & Constants # Determine the platform's /dev/null device try: DEV_NULL = os.devnull except AttributeError: # os.devnull was added in Python 2.4, so emulate it for earlier # Python versions if sys.platform in ('dos', 'win32', 'win16'): # Use the old CP/M NUL as device name DEV_NULL = 'NUL' else: # Standard Unix uses /dev/null DEV_NULL = '/dev/null' # Directory to search for configuration information on Unix. # Constant used by test_platform to test linux_distribution(). _UNIXCONFDIR = '/etc' # Helper for comparing two version number strings. # Based on the description of the PHP's version_compare(): # http://php.net/manual/en/function.version-compare.php _ver_stages = { # any string not found in this dict, will get 0 assigned 'dev': 10, 'alpha': 20, 'a': 20, 'beta': 30, 'b': 30, 'c': 40, 'RC': 50, 'rc': 50, # number, will get 100 assigned 'pl': 200, 'p': 200, } _component_re = re.compile(r'([0-9]+|[._+-])') def _comparable_version(version): result = [] for v in _component_re.split(version): if v not in '._+-': try: v = int(v, 10) t = 100 except ValueError: t = _ver_stages.get(v, 0) result.extend((t, v)) return result ### Platform specific APIs _libc_search = re.compile(b'(__libc_init)' b'|' b'(GLIBC_([0-9.]+))' b'|' br'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)', re.ASCII) def libc_ver(executable=sys.executable, lib='', version='', chunksize=16384): """ Tries to determine the libc version that the file executable (which defaults to the Python interpreter) is linked against. Returns a tuple of strings (lib,version) which default to the given parameters in case the lookup fails. Note that the function has intimate knowledge of how different libc versions add symbols to the executable and thus is probably only useable for executables compiled using gcc. The file is read and scanned in chunks of chunksize bytes. """ V = _comparable_version if hasattr(os.path, 'realpath'): # Python 2.2 introduced os.path.realpath(); it is used # here to work around problems with Cygwin not being # able to open symlinks for reading executable = os.path.realpath(executable) with open(executable, 'rb') as f: binary = f.read(chunksize) pos = 0 while pos < len(binary): if b'libc' in binary or b'GLIBC' in binary: m = _libc_search.search(binary, pos) else: m = None if not m or m.end() == len(binary): chunk = f.read(chunksize) if chunk: binary = binary[max(pos, len(binary) - 1000):] + chunk pos = 0 continue if not m: break libcinit, glibc, glibcversion, so, threads, soversion = [ s.decode('latin1') if s is not None else s for s in m.groups()] if libcinit and not lib: lib = 'libc' elif glibc: if lib != 'glibc': lib = 'glibc' version = glibcversion elif V(glibcversion) > V(version): version = glibcversion elif so: if lib != 'glibc': lib = 'libc' if soversion and (not version or V(soversion) > V(version)): version = soversion if threads and version[-len(threads):] != threads: version = version + threads pos = m.end() return lib, version def _dist_try_harder(distname, version, id): """ Tries some special tricks to get the distribution information in case the default method fails. Currently supports older SuSE Linux, Caldera OpenLinux and Slackware Linux distributions. """ if os.path.exists('/var/adm/inst-log/info'): # SuSE Linux stores distribution information in that file distname = 'SuSE' with open('/var/adm/inst-log/info') as f: for line in f: tv = line.split() if len(tv) == 2: tag, value = tv else: continue if tag == 'MIN_DIST_VERSION': version = value.strip() elif tag == 'DIST_IDENT': values = value.split('-') id = values[2] return distname, version, id if os.path.exists('/etc/.installed'): # Caldera OpenLinux has some infos in that file (thanks to Colin Kong) with open('/etc/.installed') as f: for line in f: pkg = line.split('-') if len(pkg) >= 2 and pkg[0] == 'OpenLinux': # XXX does Caldera support non Intel platforms ? If yes, # where can we find the needed id ? return 'OpenLinux', pkg[1], id if os.path.isdir('/usr/lib/setup'): # Check for slackware version tag file (thanks to Greg Andruk) verfiles = os.listdir('/usr/lib/setup') for n in range(len(verfiles)-1, -1, -1): if verfiles[n][:14] != 'slack-version-': del verfiles[n] if verfiles: verfiles.sort() distname = 'slackware' version = verfiles[-1][14:] return distname, version, id return distname, version, id _release_filename = re.compile(r'(\w+)[-_](release|version)', re.ASCII) _lsb_release_version = re.compile(r'(.+)' r' release ' r'([\d.]+)' r'[^(]*(?:\((.+)\))?', re.ASCII) _release_version = re.compile(r'([^0-9]+)' r'(?: release )?' r'([\d.]+)' r'[^(]*(?:\((.+)\))?', re.ASCII) # See also http://www.novell.com/coolsolutions/feature/11251.html # and http://linuxmafia.com/faq/Admin/release-files.html # and http://data.linux-ntfs.org/rpm/whichrpm # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html _supported_dists = ( 'SuSE', 'debian', 'fedora', 'redhat', 'centos', 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo', 'UnitedLinux', 'turbolinux', 'arch', 'mageia') def _parse_release_file(firstline): # Default to empty 'version' and 'id' strings. Both defaults are used # when 'firstline' is empty. 'id' defaults to empty when an id can not # be deduced. version = '' id = '' # Parse the first line m = _lsb_release_version.match(firstline) if m is not None: # LSB format: "distro release x.x (codename)" return tuple(m.groups()) # Pre-LSB format: "distro x.x (codename)" m = _release_version.match(firstline) if m is not None: return tuple(m.groups()) # Unknown format... take the first two words l = firstline.strip().split() if l: version = l[0] if len(l) > 1: id = l[1] return '', version, id def linux_distribution(distname='', version='', id='', supported_dists=_supported_dists, full_distribution_name=1): import warnings warnings.warn("dist() and linux_distribution() functions are deprecated " "in Python 3.5", PendingDeprecationWarning, stacklevel=2) return _linux_distribution(distname, version, id, supported_dists, full_distribution_name) def _linux_distribution(distname, version, id, supported_dists, full_distribution_name): """ Tries to determine the name of the Linux OS distribution name. The function first looks for a distribution release file in /etc and then reverts to _dist_try_harder() in case no suitable files are found. supported_dists may be given to define the set of Linux distributions to look for. It defaults to a list of currently supported Linux distributions identified by their release file name. If full_distribution_name is true (default), the full distribution read from the OS is returned. Otherwise the short name taken from supported_dists is used. Returns a tuple (distname, version, id) which default to the args given as parameters. """ try: etc = os.listdir(_UNIXCONFDIR) except OSError: # Probably not a Unix system return distname, version, id etc.sort() for file in etc: m = _release_filename.match(file) if m is not None: _distname, dummy = m.groups() if _distname in supported_dists: distname = _distname break else: return _dist_try_harder(distname, version, id) # Read the first line with open(os.path.join(_UNIXCONFDIR, file), 'r', encoding='utf-8', errors='surrogateescape') as f: firstline = f.readline() _distname, _version, _id = _parse_release_file(firstline) if _distname and full_distribution_name: distname = _distname if _version: version = _version if _id: id = _id return distname, version, id # To maintain backwards compatibility: def dist(distname='', version='', id='', supported_dists=_supported_dists): """ Tries to determine the name of the Linux OS distribution name. The function first looks for a distribution release file in /etc and then reverts to _dist_try_harder() in case no suitable files are found. Returns a tuple (distname, version, id) which default to the args given as parameters. """ import warnings warnings.warn("dist() and linux_distribution() functions are deprecated " "in Python 3.5", PendingDeprecationWarning, stacklevel=2) return _linux_distribution(distname, version, id, supported_dists=supported_dists, full_distribution_name=0) def popen(cmd, mode='r', bufsize=-1): """ Portable popen() interface. """ import warnings warnings.warn('use os.popen instead', DeprecationWarning, stacklevel=2) return os.popen(cmd, mode, bufsize) def _norm_version(version, build=''): """ Normalize the version and build strings and return a single version string using the format major.minor.build (or patchlevel). """ l = version.split('.') if build: l.append(build) try: ints = map(int, l) except ValueError: strings = l else: strings = list(map(str, ints)) version = '.'.join(strings[:3]) return version _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) ' r'.*' r'\[.* ([\d.]+)\])') # Examples of VER command output: # # Windows 2000: Microsoft Windows 2000 [Version 5.00.2195] # Windows XP: Microsoft Windows XP [Version 5.1.2600] # Windows Vista: Microsoft Windows [Version 6.0.6002] # # Note that the "Version" string gets localized on different # Windows versions. def _syscmd_ver(system='', release='', version='', supported_platforms=('win32', 'win16', 'dos')): """ Tries to figure out the OS version used and returns a tuple (system, release, version). It uses the "ver" shell command for this which is known to exists on Windows, DOS. XXX Others too ? In case this fails, the given parameters are used as defaults. """ if sys.platform not in supported_platforms: return system, release, version # Try some common cmd strings for cmd in ('ver', 'command /c ver', 'cmd /c ver'): try: pipe = os.popen(cmd) info = pipe.read() if pipe.close(): raise OSError('command failed') # XXX How can I suppress shell errors from being written # to stderr ? except OSError as why: #print 'Command %s failed: %s' % (cmd, why) continue else: break else: return system, release, version # Parse the output info = info.strip() m = _ver_output.match(info) if m is not None: system, release, version = m.groups() # Strip trailing dots from version and release if release[-1] == '.': release = release[:-1] if version[-1] == '.': version = version[:-1] # Normalize the version and build strings (eliminating additional # zeros) version = _norm_version(version) return system, release, version _WIN32_CLIENT_RELEASES = { (5, 0): "2000", (5, 1): "XP", # Strictly, 5.2 client is XP 64-bit, but platform.py historically # has always called it 2003 Server (5, 2): "2003Server", (5, None): "post2003", (6, 0): "Vista", (6, 1): "7", (6, 2): "8", (6, 3): "8.1", (6, None): "post8.1", (10, 0): "10", (10, None): "post10", } # Server release name lookup will default to client names if necessary _WIN32_SERVER_RELEASES = { (5, 2): "2003Server", (6, 0): "2008Server", (6, 1): "2008ServerR2", (6, 2): "2012Server", (6, 3): "2012ServerR2", (6, None): "post2012ServerR2", } def win32_ver(release='', version='', csd='', ptype=''): try: from sys import getwindowsversion except ImportError: return release, version, csd, ptype # try: # from winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE # except ImportError: # from _winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE winver = getwindowsversion() maj, min, build = winver.platform_version or winver[:3] version = '{0}.{1}.{2}'.format(maj, min, build) release = (_WIN32_CLIENT_RELEASES.get((maj, min)) or _WIN32_CLIENT_RELEASES.get((maj, None)) or release) # getwindowsversion() reflect the compatibility mode Python is # running under, and so the service pack value is only going to be # valid if the versions match. if winver[:2] == (maj, min): try: csd = 'SP{}'.format(winver.service_pack_major) except AttributeError: if csd[:13] == 'Service Pack ': csd = 'SP' + csd[13:] # VER_NT_SERVER = 3 if getattr(winver, 'product_type', None) == 3: release = (_WIN32_SERVER_RELEASES.get((maj, min)) or _WIN32_SERVER_RELEASES.get((maj, None)) or release) key = None try: key = OpenKeyEx(HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion') ptype = QueryValueEx(key, 'CurrentType')[0] except: pass finally: if key: CloseKey(key) return release, version, csd, ptype def _mac_ver_xml(): fn = '/System/Library/CoreServices/SystemVersion.plist' if not os.path.exists(fn): return None try: import plistlib except ImportError: return None with open(fn, 'rb') as f: pl = plistlib.load(f) release = pl['ProductVersion'] versioninfo = ('', '', '') machine = os.uname().machine if machine in ('ppc', 'Power Macintosh'): # Canonical name machine = 'PowerPC' return release, versioninfo, machine def mac_ver(release='', versioninfo=('', '', ''), machine=''): """ Get MacOS version information and return it as tuple (release, versioninfo, machine) with versioninfo being a tuple (version, dev_stage, non_release_version). Entries which cannot be determined are set to the parameter values which default to ''. All tuple entries are strings. """ # First try reading the information from an XML file which should # always be present info = _mac_ver_xml() if info is not None: return info # If that also doesn't work return the default values return release, versioninfo, machine def _java_getprop(name, default): # from java.lang import System try: value = System.getProperty(name) if value is None: return default return value except AttributeError: return default def java_ver(release='', vendor='', vminfo=('', '', ''), osinfo=('', '', '')): """ Version interface for Jython. Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being a tuple (vm_name, vm_release, vm_vendor) and osinfo being a tuple (os_name, os_version, os_arch). Values which cannot be determined are set to the defaults given as parameters (which all default to ''). """ # Import the needed APIs try: import java.lang except ImportError: return release, vendor, vminfo, osinfo vendor = _java_getprop('java.vendor', vendor) release = _java_getprop('java.version', release) vm_name, vm_release, vm_vendor = vminfo vm_name = _java_getprop('java.vm.name', vm_name) vm_vendor = _java_getprop('java.vm.vendor', vm_vendor) vm_release = _java_getprop('java.vm.version', vm_release) vminfo = vm_name, vm_release, vm_vendor os_name, os_version, os_arch = osinfo os_arch = _java_getprop('java.os.arch', os_arch) os_name = _java_getprop('java.os.name', os_name) os_version = _java_getprop('java.os.version', os_version) osinfo = os_name, os_version, os_arch return release, vendor, vminfo, osinfo ### System name aliasing def system_alias(system, release, version): """ Returns (system, release, version) aliased to common marketing names used for some systems. It also does some reordering of the information in some cases where it would otherwise cause confusion. """ if system == 'Rhapsody': # Apple's BSD derivative # XXX How can we determine the marketing release number ? return 'MacOS X Server', system+release, version elif system == 'SunOS': # Sun's OS if release < '5': # These releases use the old name SunOS return system, release, version # Modify release (marketing release = SunOS release - 3) l = release.split('.') if l: try: major = int(l[0]) except ValueError: pass else: major = major - 3 l[0] = str(major) release = '.'.join(l) if release < '6': system = 'Solaris' else: # XXX Whatever the new SunOS marketing name is... system = 'Solaris' elif system == 'IRIX64': # IRIX reports IRIX64 on platforms with 64-bit support; yet it # is really a version and not a different platform, since 32-bit # apps are also supported.. system = 'IRIX' if version: version = version + ' (64bit)' else: version = '64bit' elif system in ('win32', 'win16'): # In case one of the other tricks system = 'Windows' return system, release, version ### Various internal helpers def _platform(*args): """ Helper to format the platform string in a filename compatible format e.g. "system-version-machine". """ # Format the platform string platform = '-'.join(x.strip() for x in filter(len, args)) # Cleanup some possible filename obstacles... platform = platform.replace(' ', '_') platform = platform.replace('/', '-') platform = platform.replace('\\', '-') platform = platform.replace(':', '-') platform = platform.replace(';', '-') platform = platform.replace('"', '-') platform = platform.replace('(', '-') platform = platform.replace(')', '-') # No need to report 'unknown' information... platform = platform.replace('unknown', '') # Fold '--'s and remove trailing '-' while 1: cleaned = platform.replace('--', '-') if cleaned == platform: break platform = cleaned while platform[-1] == '-': platform = platform[:-1] return platform def _node(default=''): """ Helper to determine the node name of this machine. """ try: import socket except ImportError: # No sockets... return default try: return socket.gethostname() except OSError: # Still not working... return default def _follow_symlinks(filepath): """ In case filepath is a symlink, follow it until a real file is reached. """ filepath = os.path.abspath(filepath) while os.path.islink(filepath): filepath = os.path.normpath( os.path.join(os.path.dirname(filepath), os.readlink(filepath))) return filepath def _syscmd_uname(option, default=''): """ Interface to the system's uname command. """ if sys.platform in ('dos', 'win32', 'win16'): # XXX Others too ? return default try: f = os.popen('uname %s 2> %s' % (option, DEV_NULL)) except (AttributeError, OSError): return default output = f.read().strip() rc = f.close() if not output or rc: return default else: return output def _syscmd_file(target, default=''): """ Interface to the system's file command. The function uses the -b option of the file command to have it omit the filename in its output. Follow the symlinks. It returns default in case the command should fail. """ if sys.platform in ('dos', 'win32', 'win16'): # XXX Others too ? return default target = _follow_symlinks(target) try: proc = subprocess.Popen(['file', target], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except (AttributeError, OSError): return default output = proc.communicate()[0].decode('latin-1') rc = proc.wait() if not output or rc: return default else: return output ### Information about the used architecture # Default values for architecture; non-empty strings override the # defaults given as parameters _default_architecture = { 'win32': ('', 'WindowsPE'), 'win16': ('', 'Windows'), 'dos': ('', 'MSDOS'), } def architecture(executable=sys.executable, bits='', linkage=''): """ Queries the given executable (defaults to the Python interpreter binary) for various architecture information. Returns a tuple (bits, linkage) which contains information about the bit architecture and the linkage format used for the executable. Both values are returned as strings. Values that cannot be determined are returned as given by the parameter presets. If bits is given as '', the sizeof(pointer) (or sizeof(long) on Python version < 1.5.2) is used as indicator for the supported pointer size. The function relies on the system's "file" command to do the actual work. This is available on most if not all Unix platforms. On some non-Unix platforms where the "file" command does not exist and the executable is set to the Python interpreter binary defaults from _default_architecture are used. """ # Use the sizeof(pointer) as default number of bits if nothing # else is given as default. if not bits: import struct try: size = struct.calcsize('P') except struct.error: # Older installations can only query longs size = struct.calcsize('l') bits = str(size*8) + 'bit' # Get data from the 'file' system command if executable: fileout = _syscmd_file(executable, '') else: fileout = '' if not fileout and \ executable == sys.executable: # "file" command did not return anything; we'll try to provide # some sensible defaults then... if sys.platform in _default_architecture: b, l = _default_architecture[sys.platform] if b: bits = b if l: linkage = l return bits, linkage if 'executable' not in fileout: # Format not supported return bits, linkage # Bits if '32-bit' in fileout: bits = '32bit' elif 'N32' in fileout: # On Irix only bits = 'n32bit' elif '64-bit' in fileout: bits = '64bit' # Linkage if 'ELF' in fileout: linkage = 'ELF' elif 'PE' in fileout: # E.g. Windows uses this format if 'Windows' in fileout: linkage = 'WindowsPE' else: linkage = 'PE' elif 'COFF' in fileout: linkage = 'COFF' elif 'MS-DOS' in fileout: linkage = 'MSDOS' else: # XXX the A.OUT format also falls under this class... pass return bits, linkage ### Portable uname() interface uname_result = collections.namedtuple("uname_result", "system node release version machine processor") _uname_cache = None def uname(): """ Fairly portable uname interface. Returns a tuple of strings (system, node, release, version, machine, processor) identifying the underlying platform. Note that unlike the os.uname function this also returns possible processor information as an additional tuple entry. Entries which cannot be determined are set to ''. """ global _uname_cache no_os_uname = 0 if _uname_cache is not None: return _uname_cache processor = '' # Get some infos from the builtin os.uname API... try: system, node, release, version, machine = os.uname() except AttributeError: no_os_uname = 1 if no_os_uname or not list(filter(None, (system, node, release, version, machine))): # Hmm, no there is either no uname or uname has returned #'unknowns'... we'll have to poke around the system then. if no_os_uname: system = sys.platform release = '' version = '' node = _node() machine = '' use_syscmd_ver = 1 # Try win32_ver() on win32 platforms if system == 'win32': release, version, csd, ptype = win32_ver() if release and version: use_syscmd_ver = 0 # Try to use the PROCESSOR_* environment variables # available on Win XP and later; see # http://support.microsoft.com/kb/888731 and # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM if not machine: # WOW64 processes mask the native architecture if "PROCESSOR_ARCHITEW6432" in os.environ: machine = os.environ.get("PROCESSOR_ARCHITEW6432", '') else: machine = os.environ.get('PROCESSOR_ARCHITECTURE', '') if not processor: processor = os.environ.get('PROCESSOR_IDENTIFIER', machine) # Try the 'ver' system command available on some # platforms if use_syscmd_ver: system, release, version = _syscmd_ver(system) # Normalize system to what win32_ver() normally returns # (_syscmd_ver() tends to return the vendor name as well) if system == 'Microsoft Windows': system = 'Windows' elif system == 'Microsoft' and release == 'Windows': # Under Windows Vista and Windows Server 2008, # Microsoft changed the output of the ver command. The # release is no longer printed. This causes the # system and release to be misidentified. system = 'Windows' if '6.0' == version[:3]: release = 'Vista' else: release = '' # In case we still don't know anything useful, we'll try to # help ourselves if system in ('win32', 'win16'): if not version: if system == 'win32': version = '32bit' else: version = '16bit' system = 'Windows' elif system[:4] == 'java': release, vendor, vminfo, osinfo = java_ver() system = 'Java' version = ', '.join(vminfo) if not version: version = vendor # System specific extensions if system == 'OpenVMS': # OpenVMS seems to have release and version mixed up if not release or release == '0': release = version version = '' # Get processor information try: import vms_lib except ImportError: pass else: csid, cpu_number = vms_lib.getsyi('SYI$_CPU', 0) if (cpu_number >= 128): processor = 'Alpha' else: processor = 'VAX' if not processor: # Get processor information from the uname system command processor = _syscmd_uname('-p', '') #If any unknowns still exist, replace them with ''s, which are more portable if system == 'unknown': system = '' if node == 'unknown': node = '' if release == 'unknown': release = '' if version == 'unknown': version = '' if machine == 'unknown': machine = '' if processor == 'unknown': processor = '' # normalize name if system == 'Microsoft' and release == 'Windows': system = 'Windows' release = 'Vista' _uname_cache = uname_result(system, node, release, version, machine, processor) return _uname_cache ### Direct interfaces to some of the uname() return values def system(): """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. An empty string is returned if the value cannot be determined. """ return uname().system def node(): """ Returns the computer's network name (which may not be fully qualified) An empty string is returned if the value cannot be determined. """ return uname().node def release(): """ Returns the system's release, e.g. '2.2.0' or 'NT' An empty string is returned if the value cannot be determined. """ return uname().release def version(): """ Returns the system's release version, e.g. '#3 on degas' An empty string is returned if the value cannot be determined. """ return uname().version def machine(): """ Returns the machine type, e.g. 'i386' An empty string is returned if the value cannot be determined. """ return uname().machine def processor(): """ Returns the (true) processor name, e.g. 'amdk6' An empty string is returned if the value cannot be determined. Note that many platforms do not provide this information or simply return the same value as for machine(), e.g. NetBSD does this. """ return uname().processor ### Various APIs for extracting information from sys.version _sys_version_parser = re.compile( r'([\w.+]+)\s*' # "version<space>" r'\(#?([^,]+)' # "(#buildno" r'(?:,\s*([\w ]*)' # ", builddate" r'(?:,\s*([\w :]*))?)?\)\s*' # ", buildtime)<space>" r'\[([^\]]+)\]?', re.ASCII) # "[compiler]" _ironpython_sys_version_parser = re.compile( r'IronPython\s*' r'([\d\.]+)' r'(?: \(([\d\.]+)\))?' r' on (.NET [\d\.]+)', re.ASCII) # IronPython covering 2.6 and 2.7 _ironpython26_sys_version_parser = re.compile( r'([\d.]+)\s*' r'\(IronPython\s*' r'[\d.]+\s*' r'\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)' ) _pypy_sys_version_parser = re.compile( r'([\w.+]+)\s*' r'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*' r'\[PyPy [^\]]+\]?') _sys_version_cache = {} def _sys_version(sys_version=None): """ Returns a parsed version of Python's sys.version as tuple (name, version, branch, revision, buildno, builddate, compiler) referring to the Python implementation name, version, branch, revision, build number, build date/time as string and the compiler identification string. Note that unlike the Python sys.version, the returned value for the Python version will always include the patchlevel (it defaults to '.0'). The function returns empty strings for tuple entries that cannot be determined. sys_version may be given to parse an alternative version string, e.g. if the version was read from a different Python interpreter. """ # Get the Python version if sys_version is None: sys_version = sys.version # Try the cache first result = _sys_version_cache.get(sys_version, None) if result is not None: return result # Parse it if 'IronPython' in sys_version: # IronPython name = 'IronPython' if sys_version.startswith('IronPython'): match = _ironpython_sys_version_parser.match(sys_version) else: match = _ironpython26_sys_version_parser.match(sys_version) if match is None: raise ValueError( 'failed to parse IronPython sys.version: %s' % repr(sys_version)) version, alt_version, compiler = match.groups() buildno = '' builddate = '' elif sys.platform.startswith('java'): # Jython name = 'Jython' match = _sys_version_parser.match(sys_version) if match is None: raise ValueError( 'failed to parse Jython sys.version: %s' % repr(sys_version)) version, buildno, builddate, buildtime, _ = match.groups() if builddate is None: builddate = '' compiler = sys.platform elif "PyPy" in sys_version: # PyPy name = "PyPy" match = _pypy_sys_version_parser.match(sys_version) if match is None: raise ValueError("failed to parse PyPy sys.version: %s" % repr(sys_version)) version, buildno, builddate, buildtime = match.groups() compiler = "" else: # CPython match = _sys_version_parser.match(sys_version) if match is None: raise ValueError( 'failed to parse CPython sys.version: %s' % repr(sys_version)) version, buildno, builddate, buildtime, compiler = \ match.groups() name = 'CPython' if builddate is None: builddate = '' elif buildtime: builddate = builddate + ' ' + buildtime if hasattr(sys, '_git'): _, branch, revision = sys._git elif hasattr(sys, '_mercurial'): _, branch, revision = sys._mercurial elif hasattr(sys, 'subversion'): # sys.subversion was added in Python 2.5 _, branch, revision = sys.subversion else: branch = '' revision = '' # Add the patchlevel version if missing l = version.split('.') if len(l) == 2: l.append('0') version = '.'.join(l) # Build and cache the result result = (name, version, branch, revision, buildno, builddate, compiler) _sys_version_cache[sys_version] = result return result def python_implementation(): """ Returns a string identifying the Python implementation. Currently, the following implementations are identified: 'CPython' (C implementation of Python), 'IronPython' (.NET implementation of Python), 'Jython' (Java implementation of Python), 'PyPy' (Python implementation of Python). """ return _sys_version()[0] def python_version(): """ Returns the Python version as string 'major.minor.patchlevel' Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0). """ return _sys_version()[1] def python_version_tuple(): """ Returns the Python version as tuple (major, minor, patchlevel) of strings. Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0). """ return tuple(_sys_version()[1].split('.')) def python_branch(): """ Returns a string identifying the Python implementation branch. For CPython this is the Subversion branch from which the Python binary was built. If not available, an empty string is returned. """ return _sys_version()[2] def python_revision(): """ Returns a string identifying the Python implementation revision. For CPython this is the Subversion revision from which the Python binary was built. If not available, an empty string is returned. """ return _sys_version()[3] def python_build(): """ Returns a tuple (buildno, builddate) stating the Python build number and date as strings. """ return _sys_version()[4:6] def python_compiler(): """ Returns a string identifying the compiler used for compiling Python. """ return _sys_version()[6] ### The Opus Magnum of platform strings :-) _platform_cache = {} def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ result = _platform_cache.get((aliased, terse), None) if result is not None: return result # Get uname information and then apply platform specific cosmetics # to it... system, node, release, version, machine, processor = uname() if machine == processor: processor = '' if aliased: system, release, version = system_alias(system, release, version) if system == 'Windows': # MS platforms rel, vers, csd, ptype = win32_ver(version) if terse: platform = _platform(system, release) else: platform = _platform(system, release, version, csd) elif system in ('Linux',): # Linux based systems with warnings.catch_warnings(): # see issue #1322 for more information warnings.filterwarnings( 'ignore', r'dist\(\) and linux_distribution\(\) ' 'functions are deprecated .*', PendingDeprecationWarning, ) distname, distversion, distid = dist('') if distname and not terse: platform = _platform(system, release, machine, processor, 'with', distname, distversion, distid) else: # If the distribution name is unknown check for libc vs. glibc libcname, libcversion = libc_ver(sys.executable) platform = _platform(system, release, machine, processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r, v, vminfo, (os_name, os_version, os_arch) = java_ver() if terse or not os_name: platform = _platform(system, release, version) else: platform = _platform(system, release, version, 'on', os_name, os_version, os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system, release) else: platform = _platform(system, release, machine) else: # Generic handler if terse: platform = _platform(system, release) else: bits, linkage = architecture(sys.executable) platform = _platform(system, release, machine, processor, bits, linkage) _platform_cache[(aliased, terse)] = platform return platform ### Command line interface if __name__ == '__main__': # Default is to print the aliased verbose platform string terse = ('terse' in sys.argv or '--terse' in sys.argv) aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv) print(platform(aliased, terse)) sys.exit(0)
47,202
1,434
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tarfile.py
#!/usr/bin/env python3 #------------------------------------------------------------------- # tarfile.py #------------------------------------------------------------------- # Copyright (C) 2002 Lars Gustaebel <[email protected]> # All rights reserved. # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # """Read from and write to tar format archives. """ version = "0.9.0" __author__ = "Lars Gust\u00e4bel ([email protected])" __date__ = "$Date: 2011-02-25 17:42:01 +0200 (Fri, 25 Feb 2011) $" __cvsid__ = "$Id: tarfile.py 88586 2011-02-25 15:42:01Z marc-andre.lemburg $" __credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend." #--------- # Imports #--------- from builtins import open as bltn_open import sys import os import io import shutil import stat import time import struct import copy import re try: import pwd except ImportError: pwd = None try: import grp except ImportError: grp = None # os.symlink on Windows prior to 6.0 raises NotImplementedError symlink_exception = (AttributeError, NotImplementedError) try: # OSError (winerror=1314) will be raised if the caller does not hold the # SeCreateSymbolicLinkPrivilege privilege symlink_exception += (OSError,) except NameError: pass # from tarfile import * __all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError", "ReadError", "CompressionError", "StreamError", "ExtractError", "HeaderError", "ENCODING", "USTAR_FORMAT", "GNU_FORMAT", "PAX_FORMAT", "DEFAULT_FORMAT", "open"] #--------------------------------------------------------- # tar constants #--------------------------------------------------------- NUL = b"\0" # the null character BLOCKSIZE = 512 # length of processing blocks RECORDSIZE = BLOCKSIZE * 20 # length of records GNU_MAGIC = b"ustar \0" # magic gnu tar string POSIX_MAGIC = b"ustar\x0000" # magic posix tar string LENGTH_NAME = 100 # maximum length of a filename LENGTH_LINK = 100 # maximum length of a linkname LENGTH_PREFIX = 155 # maximum length of the prefix field REGTYPE = b"0" # regular file AREGTYPE = b"\0" # regular file LNKTYPE = b"1" # link (inside tarfile) SYMTYPE = b"2" # symbolic link CHRTYPE = b"3" # character special device BLKTYPE = b"4" # block special device DIRTYPE = b"5" # directory FIFOTYPE = b"6" # fifo special device CONTTYPE = b"7" # contiguous file GNUTYPE_LONGNAME = b"L" # GNU tar longname GNUTYPE_LONGLINK = b"K" # GNU tar longlink GNUTYPE_SPARSE = b"S" # GNU tar sparse file XHDTYPE = b"x" # POSIX.1-2001 extended header XGLTYPE = b"g" # POSIX.1-2001 global header SOLARIS_XHDTYPE = b"X" # Solaris extended header USTAR_FORMAT = 0 # POSIX.1-1988 (ustar) format GNU_FORMAT = 1 # GNU tar format PAX_FORMAT = 2 # POSIX.1-2001 (pax) format DEFAULT_FORMAT = GNU_FORMAT #--------------------------------------------------------- # tarfile constants #--------------------------------------------------------- # File types that tarfile supports: SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_LONGNAME, GNUTYPE_LONGLINK, GNUTYPE_SPARSE) # File types that will be treated as a regular file. REGULAR_TYPES = (REGTYPE, AREGTYPE, CONTTYPE, GNUTYPE_SPARSE) # File types that are part of the GNU tar format. GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK, GNUTYPE_SPARSE) # Fields from a pax header that override a TarInfo attribute. PAX_FIELDS = ("path", "linkpath", "size", "mtime", "uid", "gid", "uname", "gname") # Fields from a pax header that are affected by hdrcharset. PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"} # Fields in a pax header that are numbers, all other fields # are treated as strings. PAX_NUMBER_FIELDS = { "atime": float, "ctime": float, "mtime": float, "uid": int, "gid": int, "size": int } #--------------------------------------------------------- # initialization #--------------------------------------------------------- if os.name == "nt": ENCODING = "utf-8" else: ENCODING = sys.getfilesystemencoding() #--------------------------------------------------------- # Some useful functions #--------------------------------------------------------- def stn(s, length, encoding, errors): """Convert a string to a null-terminated bytes object. """ s = s.encode(encoding, errors) return s[:length] + (length - len(s)) * NUL def nts(s, encoding, errors): """Convert a null-terminated bytes object to a string. """ p = s.find(b"\0") if p != -1: s = s[:p] return s.decode(encoding, errors) def nti(s): """Convert a number field to a python number. """ # There are two possible encodings for a number field, see # itn() below. if s[0] in (0o200, 0o377): n = 0 for i in range(len(s) - 1): n <<= 8 n += s[i + 1] if s[0] == 0o377: n = -(256 ** (len(s) - 1) - n) else: try: s = nts(s, "ascii", "strict") n = int(s.strip() or "0", 8) except ValueError: raise InvalidHeaderError("invalid header") return n def itn(n, digits=8, format=DEFAULT_FORMAT): """Convert a python number to a number field. """ # POSIX 1003.1-1988 requires numbers to be encoded as a string of # octal digits followed by a null-byte, this allows values up to # (8**(digits-1))-1. GNU tar allows storing numbers greater than # that if necessary. A leading 0o200 or 0o377 byte indicate this # particular encoding, the following digits-1 bytes are a big-endian # base-256 representation. This allows values up to (256**(digits-1))-1. # A 0o200 byte indicates a positive number, a 0o377 byte a negative # number. n = int(n) if 0 <= n < 8 ** (digits - 1): s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1): if n >= 0: s = bytearray([0o200]) else: s = bytearray([0o377]) n = 256 ** digits + n for i in range(digits - 1): s.insert(1, n & 0o377) n >>= 8 else: raise ValueError("overflow in number field") return s def calc_chksums(buf): """Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed. """ unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf)) signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf)) return unsigned_chksum, signed_chksum def copyfileobj(src, dst, length=None, exception=OSError, bufsize=None): """Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. """ bufsize = bufsize or 16 * 1024 if length == 0: return if length is None: shutil.copyfileobj(src, dst, bufsize) return blocks, remainder = divmod(length, bufsize) for b in range(blocks): buf = src.read(bufsize) if len(buf) < bufsize: raise exception("unexpected end of data") dst.write(buf) if remainder != 0: buf = src.read(remainder) if len(buf) < remainder: raise exception("unexpected end of data") dst.write(buf) return def filemode(mode): """Deprecated in this location; use stat.filemode.""" import warnings warnings.warn("deprecated in favor of stat.filemode", DeprecationWarning, 2) return stat.filemode(mode) def _safe_print(s): encoding = getattr(sys.stdout, 'encoding', None) if encoding is not None: s = s.encode(encoding, 'backslashreplace').decode(encoding) print(s, end=' ') class TarError(Exception): """Base exception.""" pass class ExtractError(TarError): """General exception for extract errors.""" pass class ReadError(TarError): """Exception for unreadable tar archives.""" pass class CompressionError(TarError): """Exception for unavailable compression methods.""" pass class StreamError(TarError): """Exception for unsupported operations on stream-like TarFiles.""" pass class HeaderError(TarError): """Base exception for header errors.""" pass class EmptyHeaderError(HeaderError): """Exception for empty headers.""" pass class TruncatedHeaderError(HeaderError): """Exception for truncated headers.""" pass class EOFHeaderError(HeaderError): """Exception for end of file headers.""" pass class InvalidHeaderError(HeaderError): """Exception for invalid headers.""" pass class SubsequentHeaderError(HeaderError): """Exception for missing and invalid extended headers.""" pass #--------------------------- # internal stream interface #--------------------------- class _LowLevelFile: """Low-level file object. Supports reading and writing. It is used instead of a regular file object for streaming access. """ def __init__(self, name, mode): mode = { "r": os.O_RDONLY, "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC, }[mode] if hasattr(os, "O_BINARY"): mode |= os.O_BINARY self.fd = os.open(name, mode, 0o666) def close(self): os.close(self.fd) def read(self, size): return os.read(self.fd, size) def write(self, s): os.write(self.fd, s) class _Stream: """Class that serves as an adapter between TarFile and a stream-like object. The stream-like object only needs to have a read() or write() method and is accessed blockwise. Use of gzip or bzip2 compression is possible. A stream-like object could be for example: sys.stdin, sys.stdout, a socket, a tape device etc. _Stream is intended to be used only internally. """ def __init__(self, name, mode, comptype, fileobj, bufsize): """Construct a _Stream object. """ self._extfileobj = True if fileobj is None: fileobj = _LowLevelFile(name, mode) self._extfileobj = False if comptype == '*': # Enable transparent compression detection for the # stream interface fileobj = _StreamProxy(fileobj) comptype = fileobj.getcomptype() self.name = name or "" self.mode = mode self.comptype = comptype self.fileobj = fileobj self.bufsize = bufsize self.buf = b"" self.pos = 0 self.closed = False try: if comptype == "gz": try: import zlib except ImportError: raise CompressionError("zlib module is not available") self.zlib = zlib self.crc = zlib.crc32(b"") if mode == "r": self._init_read_gz() self.exception = zlib.error else: self._init_write_gz() elif comptype == "bz2": try: import bz2 except ImportError: raise CompressionError("bz2 module is not available") if mode == "r": self.dbuf = b"" self.cmp = bz2.BZ2Decompressor() self.exception = OSError else: self.cmp = bz2.BZ2Compressor() elif comptype == "xz": try: import lzma except ImportError: raise CompressionError("lzma module is not available") if mode == "r": self.dbuf = b"" self.cmp = lzma.LZMADecompressor() self.exception = lzma.LZMAError else: self.cmp = lzma.LZMACompressor() elif comptype != "tar": raise CompressionError("unknown compression type %r" % comptype) except: if not self._extfileobj: self.fileobj.close() self.closed = True raise def __del__(self): if hasattr(self, "closed") and not self.closed: self.close() def _init_write_gz(self): """Initialize for writing with gzip compression. """ self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, -self.zlib.MAX_WBITS, self.zlib.DEF_MEM_LEVEL, 0) timestamp = struct.pack("<L", int(time.time())) self.__write(b"\037\213\010\010" + timestamp + b"\002\377") if self.name.endswith(".gz"): self.name = self.name[:-3] # RFC1952 says we must use ISO-8859-1 for the FNAME field. self.__write(self.name.encode("iso-8859-1", "replace") + NUL) def write(self, s): """Write string s to the stream. """ if self.comptype == "gz": self.crc = self.zlib.crc32(s, self.crc) self.pos += len(s) if self.comptype != "tar": s = self.cmp.compress(s) self.__write(s) def __write(self, s): """Write string s to the stream if a whole new block is ready to be written. """ self.buf += s while len(self.buf) > self.bufsize: self.fileobj.write(self.buf[:self.bufsize]) self.buf = self.buf[self.bufsize:] def close(self): """Close the _Stream object. No operation should be done on it afterwards. """ if self.closed: return self.closed = True try: if self.mode == "w" and self.comptype != "tar": self.buf += self.cmp.flush() if self.mode == "w" and self.buf: self.fileobj.write(self.buf) self.buf = b"" if self.comptype == "gz": self.fileobj.write(struct.pack("<L", self.crc)) self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF)) finally: if not self._extfileobj: self.fileobj.close() def _init_read_gz(self): """Initialize for reading a gzip compressed fileobj. """ self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) self.dbuf = b"" # taken from gzip.GzipFile with some alterations if self.__read(2) != b"\037\213": raise ReadError("not a gzip file") if self.__read(1) != b"\010": raise CompressionError("unsupported compression method") flag = ord(self.__read(1)) self.__read(6) if flag & 4: xlen = ord(self.__read(1)) + 256 * ord(self.__read(1)) self.read(xlen) if flag & 8: while True: s = self.__read(1) if not s or s == NUL: break if flag & 16: while True: s = self.__read(1) if not s or s == NUL: break if flag & 2: self.__read(2) def tell(self): """Return the stream's file pointer position. """ return self.pos def seek(self, pos=0): """Set the stream's file pointer to pos. Negative seeking is forbidden. """ if pos - self.pos >= 0: blocks, remainder = divmod(pos - self.pos, self.bufsize) for i in range(blocks): self.read(self.bufsize) self.read(remainder) else: raise StreamError("seeking backwards is not allowed") return self.pos def read(self, size=None): """Return the next size number of bytes from the stream. If size is not defined, return all bytes of the stream up to EOF. """ if size is None: t = [] while True: buf = self._read(self.bufsize) if not buf: break t.append(buf) buf = b"".join(t) else: buf = self._read(size) self.pos += len(buf) return buf def _read(self, size): """Return size bytes from the stream. """ if self.comptype == "tar": return self.__read(size) c = len(self.dbuf) t = [self.dbuf] while c < size: buf = self.__read(self.bufsize) if not buf: break try: buf = self.cmp.decompress(buf) except self.exception: raise ReadError("invalid compressed data") t.append(buf) c += len(buf) t = b"".join(t) self.dbuf = t[size:] return t[:size] def __read(self, size): """Return size bytes from stream. If internal buffer is empty, read another block from the stream. """ c = len(self.buf) t = [self.buf] while c < size: buf = self.fileobj.read(self.bufsize) if not buf: break t.append(buf) c += len(buf) t = b"".join(t) self.buf = t[size:] return t[:size] # class _Stream class _StreamProxy(object): """Small proxy class that enables transparent compression detection for the Stream interface (mode 'r|*'). """ def __init__(self, fileobj): self.fileobj = fileobj self.buf = self.fileobj.read(BLOCKSIZE) def read(self, size): self.read = self.fileobj.read return self.buf def getcomptype(self): if self.buf.startswith(b"\x1f\x8b\x08"): return "gz" elif self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY": return "bz2" elif self.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")): return "xz" else: return "tar" def close(self): self.fileobj.close() # class StreamProxy #------------------------ # Extraction file object #------------------------ class _FileInFile(object): """A thin wrapper around an existing file object that provides a part of its data as an individual file object. """ def __init__(self, fileobj, offset, size, blockinfo=None): self.fileobj = fileobj self.offset = offset self.size = size self.position = 0 self.name = getattr(fileobj, "name", None) self.closed = False if blockinfo is None: blockinfo = [(0, size)] # Construct a map with data and zero blocks. self.map_index = 0 self.map = [] lastpos = 0 realpos = self.offset for offset, size in blockinfo: if offset > lastpos: self.map.append((False, lastpos, offset, None)) self.map.append((True, offset, offset + size, realpos)) realpos += size lastpos = offset + size if lastpos < self.size: self.map.append((False, lastpos, self.size, None)) def flush(self): pass def readable(self): return True def writable(self): return False def seekable(self): return self.fileobj.seekable() def tell(self): """Return the current file position. """ return self.position def seek(self, position, whence=io.SEEK_SET): """Seek to a position in the file. """ if whence == io.SEEK_SET: self.position = min(max(position, 0), self.size) elif whence == io.SEEK_CUR: if position < 0: self.position = max(self.position + position, 0) else: self.position = min(self.position + position, self.size) elif whence == io.SEEK_END: self.position = max(min(self.size + position, self.size), 0) else: raise ValueError("Invalid argument") return self.position def read(self, size=None): """Read data from the file. """ if size is None: size = self.size - self.position else: size = min(size, self.size - self.position) buf = b"" while size > 0: while True: data, start, stop, offset = self.map[self.map_index] if start <= self.position < stop: break else: self.map_index += 1 if self.map_index == len(self.map): self.map_index = 0 length = min(size, stop - self.position) if data: self.fileobj.seek(offset + (self.position - start)) b = self.fileobj.read(length) if len(b) != length: raise ReadError("unexpected end of data") buf += b else: buf += NUL * length size -= length self.position += length return buf def readinto(self, b): buf = self.read(len(b)) b[:len(buf)] = buf return len(buf) def close(self): self.closed = True #class _FileInFile class ExFileObject(io.BufferedReader): def __init__(self, tarfile, tarinfo): fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data, tarinfo.size, tarinfo.sparse) super().__init__(fileobj) #class ExFileObject #------------------ # Exported Classes #------------------ class TarInfo(object): """Informational class which holds the details about an archive member given by a tar header block. TarInfo objects are returned by TarFile.getmember(), TarFile.getmembers() and TarFile.gettarinfo() and are usually created internally. """ __slots__ = ("name", "mode", "uid", "gid", "size", "mtime", "chksum", "type", "linkname", "uname", "gname", "devmajor", "devminor", "offset", "offset_data", "pax_headers", "sparse", "tarfile", "_sparse_structs", "_link_target") def __init__(self, name=""): """Construct a TarInfo object. name is the optional name of the member. """ self.name = name # member name self.mode = 0o644 # file permissions self.uid = 0 # user id self.gid = 0 # group id self.size = 0 # file size self.mtime = 0 # modification time self.chksum = 0 # header checksum self.type = REGTYPE # member type self.linkname = "" # link name self.uname = "" # user name self.gname = "" # group name self.devmajor = 0 # device major number self.devminor = 0 # device minor number self.offset = 0 # the tar header starts here self.offset_data = 0 # the file's data starts here self.sparse = None # sparse member information self.pax_headers = {} # pax header information # In pax headers the "name" and "linkname" field are called # "path" and "linkpath". def _getpath(self): return self.name def _setpath(self, name): self.name = name path = property(_getpath, _setpath) def _getlinkpath(self): return self.linkname def _setlinkpath(self, linkname): self.linkname = linkname linkpath = property(_getlinkpath, _setlinkpath) def __repr__(self): return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self)) def get_info(self): """Return the TarInfo's attributes as a dictionary. """ info = { "name": self.name, "mode": self.mode & 0o7777, "uid": self.uid, "gid": self.gid, "size": self.size, "mtime": self.mtime, "chksum": self.chksum, "type": self.type, "linkname": self.linkname, "uname": self.uname, "gname": self.gname, "devmajor": self.devmajor, "devminor": self.devminor } if info["type"] == DIRTYPE and not info["name"].endswith("/"): info["name"] += "/" return info def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): """Return a tar header as a string of 512 byte blocks. """ info = self.get_info() if format == USTAR_FORMAT: return self.create_ustar_header(info, encoding, errors) elif format == GNU_FORMAT: return self.create_gnu_header(info, encoding, errors) elif format == PAX_FORMAT: return self.create_pax_header(info, encoding) else: raise ValueError("invalid format") def create_ustar_header(self, info, encoding, errors): """Return the object as a ustar header block. """ info["magic"] = POSIX_MAGIC if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK: raise ValueError("linkname is too long") if len(info["name"].encode(encoding, errors)) > LENGTH_NAME: info["prefix"], info["name"] = self._posix_split_name(info["name"], encoding, errors) return self._create_header(info, USTAR_FORMAT, encoding, errors) def create_gnu_header(self, info, encoding, errors): """Return the object as a GNU header block sequence. """ info["magic"] = GNU_MAGIC buf = b"" if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK: buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors) if len(info["name"].encode(encoding, errors)) > LENGTH_NAME: buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors) return buf + self._create_header(info, GNU_FORMAT, encoding, errors) def create_pax_header(self, info, encoding): """Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. """ info["magic"] = POSIX_MAGIC pax_headers = self.pax_headers.copy() # Test string fields for values that exceed the field length or cannot # be represented in ASCII encoding. for name, hname, length in ( ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK), ("uname", "uname", 32), ("gname", "gname", 32)): if hname in pax_headers: # The pax header has priority. continue # Try to encode the string as ASCII. try: info[name].encode("ascii", "strict") except UnicodeEncodeError: pax_headers[hname] = info[name] continue if len(info[name]) > length: pax_headers[hname] = info[name] # Test number fields for values that exceed the field limit or values # that like to be stored as float. for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)): if name in pax_headers: # The pax header has priority. Avoid overflow. info[name] = 0 continue val = info[name] if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float): pax_headers[name] = str(val) info[name] = 0 # Create a pax extended header if necessary. if pax_headers: buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding) else: buf = b"" return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace") @classmethod def create_pax_global_header(cls, pax_headers): """Return the object as a pax global header block sequence. """ return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8") def _posix_split_name(self, name, encoding, errors): """Split a name longer than 100 chars into a prefix and a name part. """ components = name.split("/") for i in range(1, len(components)): prefix = "/".join(components[:i]) name = "/".join(components[i:]) if len(prefix.encode(encoding, errors)) <= LENGTH_PREFIX and \ len(name.encode(encoding, errors)) <= LENGTH_NAME: break else: raise ValueError("name is too long") return prefix, name @staticmethod def _create_header(info, format, encoding, errors): """Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants. """ parts = [ stn(info.get("name", ""), 100, encoding, errors), itn(info.get("mode", 0) & 0o7777, 8, format), itn(info.get("uid", 0), 8, format), itn(info.get("gid", 0), 8, format), itn(info.get("size", 0), 12, format), itn(info.get("mtime", 0), 12, format), b" ", # checksum field info.get("type", REGTYPE), stn(info.get("linkname", ""), 100, encoding, errors), info.get("magic", POSIX_MAGIC), stn(info.get("uname", ""), 32, encoding, errors), stn(info.get("gname", ""), 32, encoding, errors), itn(info.get("devmajor", 0), 8, format), itn(info.get("devminor", 0), 8, format), stn(info.get("prefix", ""), 155, encoding, errors) ] buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts)) chksum = calc_chksums(buf[-BLOCKSIZE:])[0] buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:] return buf @staticmethod def _create_payload(payload): """Return the string payload filled with zero bytes up to the next 512 byte border. """ blocks, remainder = divmod(len(payload), BLOCKSIZE) if remainder > 0: payload += (BLOCKSIZE - remainder) * NUL return payload @classmethod def _create_gnu_long_header(cls, name, type, encoding, errors): """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name. """ name = name.encode(encoding, errors) + NUL info = {} info["name"] = "././@LongLink" info["type"] = type info["size"] = len(name) info["magic"] = GNU_MAGIC # create extended header + name blocks. return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \ cls._create_payload(name) @classmethod def _create_pax_generic_header(cls, pax_headers, type, encoding): """Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings. """ # Check if one of the fields contains surrogate characters and thereby # forces hdrcharset=BINARY, see _proc_pax() for more information. binary = False for keyword, value in pax_headers.items(): try: value.encode("utf-8", "strict") except UnicodeEncodeError: binary = True break records = b"" if binary: # Put the hdrcharset field at the beginning of the header. records += b"21 hdrcharset=BINARY\n" for keyword, value in pax_headers.items(): keyword = keyword.encode("utf-8") if binary: # Try to restore the original byte representation of `value'. # Needless to say, that the encoding must match the string. value = value.encode(encoding, "surrogateescape") else: value = value.encode("utf-8") l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' n = p = 0 while True: n = l + len(str(p)) if n == p: break p = n records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n" # We use a hardcoded "././@PaxHeader" name like star does # instead of the one that POSIX recommends. info = {} info["name"] = "././@PaxHeader" info["type"] = type info["size"] = len(records) info["magic"] = POSIX_MAGIC # Create pax header + record blocks. return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \ cls._create_payload(records) @classmethod def frombuf(cls, buf, encoding, errors): """Construct a TarInfo object from a 512 byte bytes object. """ if len(buf) == 0: raise EmptyHeaderError("empty header") if len(buf) != BLOCKSIZE: raise TruncatedHeaderError("truncated header") if buf.count(NUL) == BLOCKSIZE: raise EOFHeaderError("end of file header") chksum = nti(buf[148:156]) if chksum not in calc_chksums(buf): raise InvalidHeaderError("bad checksum") obj = cls() obj.name = nts(buf[0:100], encoding, errors) obj.mode = nti(buf[100:108]) obj.uid = nti(buf[108:116]) obj.gid = nti(buf[116:124]) obj.size = nti(buf[124:136]) obj.mtime = nti(buf[136:148]) obj.chksum = chksum obj.type = buf[156:157] obj.linkname = nts(buf[157:257], encoding, errors) obj.uname = nts(buf[265:297], encoding, errors) obj.gname = nts(buf[297:329], encoding, errors) obj.devmajor = nti(buf[329:337]) obj.devminor = nti(buf[337:345]) prefix = nts(buf[345:500], encoding, errors) # Old V7 tar format represents a directory as a regular # file with a trailing slash. if obj.type == AREGTYPE and obj.name.endswith("/"): obj.type = DIRTYPE # The old GNU sparse format occupies some of the unused # space in the buffer for up to 4 sparse structures. # Save them for later processing in _proc_sparse(). if obj.type == GNUTYPE_SPARSE: pos = 386 structs = [] for i in range(4): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[482]) origsize = nti(buf[483:495]) obj._sparse_structs = (structs, isextended, origsize) # Remove redundant slashes from directories. if obj.isdir(): obj.name = obj.name.rstrip("/") # Reconstruct a ustar longname. if prefix and obj.type not in GNU_TYPES: obj.name = prefix + "/" + obj.name return obj @classmethod def fromtarfile(cls, tarfile): """Return the next TarInfo object from TarFile object tarfile. """ buf = tarfile.fileobj.read(BLOCKSIZE) obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) obj.offset = tarfile.fileobj.tell() - BLOCKSIZE return obj._proc_member(tarfile) #-------------------------------------------------------------------------- # The following are methods that are called depending on the type of a # member. The entry point is _proc_member() which can be overridden in a # subclass to add custom _proc_*() methods. A _proc_*() method MUST # implement the following # operations: # 1. Set self.offset_data to the position where the data blocks begin, # if there is data that follows. # 2. Set tarfile.offset to the position where the next member's header will # begin. # 3. Return self or another valid TarInfo object. def _proc_member(self, tarfile): """Choose the right processing method depending on the type and call it. """ if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): return self._proc_gnulong(tarfile) elif self.type == GNUTYPE_SPARSE: return self._proc_sparse(tarfile) elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE): return self._proc_pax(tarfile) else: return self._proc_builtin(tarfile) def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: # Skip the following data blocks. offset += self._block(self.size) tarfile.offset = offset # Patch the TarInfo object with saved global # header information. self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) return self def _proc_gnulong(self, tarfile): """Process the blocks that hold a GNU longname or longlink member. """ buf = tarfile.fileobj.read(self._block(self.size)) # Fetch the next header and process it. try: next = self.fromtarfile(tarfile) except HeaderError: raise SubsequentHeaderError("missing or bad subsequent header") # Patch the TarInfo object from the next header with # the longname information. next.offset = self.offset if self.type == GNUTYPE_LONGNAME: next.name = nts(buf, tarfile.encoding, tarfile.errors) elif self.type == GNUTYPE_LONGLINK: next.linkname = nts(buf, tarfile.encoding, tarfile.errors) return next def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ # We already collected some sparse structures in frombuf(). structs, isextended, origsize = self._sparse_structs del self._sparse_structs # Collect sparse structures from extended header blocks. while isextended: buf = tarfile.fileobj.read(BLOCKSIZE) pos = 0 for i in range(21): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break if offset and numbytes: structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[504]) self.sparse = structs self.offset_data = tarfile.fileobj.tell() tarfile.offset = self.offset_data + self._block(self.size) self.size = origsize return self def _proc_pax(self, tarfile): """Process an extended or global header as described in POSIX.1-2008. """ # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) # A pax header stores supplemental information for either # the following file (extended) or all following files # (global). if self.type == XGLTYPE: pax_headers = tarfile.pax_headers else: pax_headers = tarfile.pax_headers.copy() # Check if the pax header contains a hdrcharset field. This tells us # the encoding of the path, linkpath, uname and gname fields. Normally, # these fields are UTF-8 encoded but since POSIX.1-2008 tar # implementations are allowed to store them as raw binary strings if # the translation to UTF-8 fails. match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) if match is not None: pax_headers["hdrcharset"] = match.group(1).decode("utf-8") # For the time being, we don't care about anything other than "BINARY". # The only other value that is currently allowed by the standard is # "ISO-IR 10646 2000 UTF-8" in other words UTF-8. hdrcharset = pax_headers.get("hdrcharset") if hdrcharset == "BINARY": encoding = tarfile.encoding else: encoding = "utf-8" # Parse pax header information. A record looks like that: # "%d %s=%s\n" % (length, keyword, value). length is the size # of the complete record including the length field itself and # the newline. keyword and value are both UTF-8 encoded strings. regex = re.compile(br"(\d+) ([^=]+)=") pos = 0 while True: match = regex.match(buf, pos) if not match: break length, keyword = match.groups() length = int(length) if length == 0: raise InvalidHeaderError("invalid header") value = buf[match.end(2) + 1:match.start(1) + length - 1] # Normally, we could just use "utf-8" as the encoding and "strict" # as the error handler, but we better not take the risk. For # example, GNU tar <= 1.23 is known to store filenames it cannot # translate to UTF-8 as raw strings (unfortunately without a # hdrcharset=BINARY header). # We first try the strict standard encoding, and if that fails we # fall back on the user's encoding and error handler. keyword = self._decode_pax_field(keyword, "utf-8", "utf-8", tarfile.errors) if keyword in PAX_NAME_FIELDS: value = self._decode_pax_field(value, encoding, tarfile.encoding, tarfile.errors) else: value = self._decode_pax_field(value, "utf-8", "utf-8", tarfile.errors) pax_headers[keyword] = value pos += length # Fetch the next header. try: next = self.fromtarfile(tarfile) except HeaderError: raise SubsequentHeaderError("missing or bad subsequent header") # Process GNU sparse information. if "GNU.sparse.map" in pax_headers: # GNU extended sparse format version 0.1. self._proc_gnusparse_01(next, pax_headers) elif "GNU.sparse.size" in pax_headers: # GNU extended sparse format version 0.0. self._proc_gnusparse_00(next, pax_headers, buf) elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0": # GNU extended sparse format version 1.0. self._proc_gnusparse_10(next, pax_headers, tarfile) if self.type in (XHDTYPE, SOLARIS_XHDTYPE): # Patch the TarInfo object with the extended header info. next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors) next.offset = self.offset if "size" in pax_headers: # If the extended header replaces the size field, # we need to recalculate the offset where the next # header starts. offset = next.offset_data if next.isreg() or next.type not in SUPPORTED_TYPES: offset += next._block(next.size) tarfile.offset = offset return next def _proc_gnusparse_00(self, next, pax_headers, buf): """Process a GNU tar extended sparse header, version 0.0. """ offsets = [] for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf): offsets.append(int(match.group(1))) numbytes = [] for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf): numbytes.append(int(match.group(1))) next.sparse = list(zip(offsets, numbytes)) def _proc_gnusparse_01(self, next, pax_headers): """Process a GNU tar extended sparse header, version 0.1. """ sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")] next.sparse = list(zip(sparse[::2], sparse[1::2])) def _proc_gnusparse_10(self, next, pax_headers, tarfile): """Process a GNU tar extended sparse header, version 1.0. """ fields = None sparse = [] buf = tarfile.fileobj.read(BLOCKSIZE) fields, buf = buf.split(b"\n", 1) fields = int(fields) while len(sparse) < fields * 2: if b"\n" not in buf: buf += tarfile.fileobj.read(BLOCKSIZE) number, buf = buf.split(b"\n", 1) sparse.append(int(number)) next.offset_data = tarfile.fileobj.tell() next.sparse = list(zip(sparse[::2], sparse[1::2])) def _apply_pax_info(self, pax_headers, encoding, errors): """Replace fields with supplemental information from a previous pax extended or global header. """ for keyword, value in pax_headers.items(): if keyword == "GNU.sparse.name": setattr(self, "path", value) elif keyword == "GNU.sparse.size": setattr(self, "size", int(value)) elif keyword == "GNU.sparse.realsize": setattr(self, "size", int(value)) elif keyword in PAX_FIELDS: if keyword in PAX_NUMBER_FIELDS: try: value = PAX_NUMBER_FIELDS[keyword](value) except ValueError: value = 0 if keyword == "path": value = value.rstrip("/") setattr(self, keyword, value) self.pax_headers = pax_headers.copy() def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): """Decode a single field from a pax record. """ try: return value.decode(encoding, "strict") except UnicodeDecodeError: return value.decode(fallback_encoding, fallback_errors) def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. """ blocks, remainder = divmod(count, BLOCKSIZE) if remainder: blocks += 1 return blocks * BLOCKSIZE def isreg(self): return self.type in REGULAR_TYPES def isfile(self): return self.isreg() def isdir(self): return self.type == DIRTYPE def issym(self): return self.type == SYMTYPE def islnk(self): return self.type == LNKTYPE def ischr(self): return self.type == CHRTYPE def isblk(self): return self.type == BLKTYPE def isfifo(self): return self.type == FIFOTYPE def issparse(self): return self.sparse is not None def isdev(self): return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE) # class TarInfo class TarFile(object): """The TarFile Class provides an interface to tar archives. """ debug = 0 # May be set from 0 (no msgs) to 3 (all msgs) dereference = False # If true, add content of linked file to the # tar file, else the link. ignore_zeros = False # If true, skips empty or invalid blocks and # continues processing. errorlevel = 1 # If 0, fatal errors only appear in debug # messages (if debug >= 0). If > 0, errors # are passed to the caller as exceptions. format = DEFAULT_FORMAT # The format to use when creating an archive. encoding = ENCODING # Encoding for 8-bit character strings. errors = None # Error handler for unicode conversion. tarinfo = TarInfo # The default TarInfo class to use. fileobject = ExFileObject # The file-object for extractfile(). def __init__(self, name=None, mode="r", fileobj=None, format=None, tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, errors="surrogateescape", pax_headers=None, debug=None, errorlevel=None, copybufsize=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"} if mode not in modes: raise ValueError("mode must be 'r', 'a', 'w' or 'x'") self.mode = mode self._mode = modes[mode] if not fileobj: if self.mode == "a" and not os.path.exists(name): # Create nonexistent files in append mode. self.mode = "w" self._mode = "wb" fileobj = bltn_open(name, self._mode) self._extfileobj = False else: if (name is None and hasattr(fileobj, "name") and isinstance(fileobj.name, (str, bytes))): name = fileobj.name if hasattr(fileobj, "mode"): self._mode = fileobj.mode self._extfileobj = True self.name = os.path.abspath(name) if name else None self.fileobj = fileobj # Init attributes. if format is not None: self.format = format if tarinfo is not None: self.tarinfo = tarinfo if dereference is not None: self.dereference = dereference if ignore_zeros is not None: self.ignore_zeros = ignore_zeros if encoding is not None: self.encoding = encoding self.errors = errors if pax_headers is not None and self.format == PAX_FORMAT: self.pax_headers = pax_headers else: self.pax_headers = {} if debug is not None: self.debug = debug if errorlevel is not None: self.errorlevel = errorlevel # Init datastructures. self.copybufsize = copybufsize self.closed = False self.members = [] # list of members as TarInfo objects self._loaded = False # flag if all members have been read self.offset = self.fileobj.tell() # current position in the archive file self.inodes = {} # dictionary caching the inodes of # archive members already added try: if self.mode == "r": self.firstmember = None self.firstmember = self.next() if self.mode == "a": # Move to the end of the archive, # before the first empty block. while True: self.fileobj.seek(self.offset) try: tarinfo = self.tarinfo.fromtarfile(self) self.members.append(tarinfo) except EOFHeaderError: self.fileobj.seek(self.offset) break except HeaderError as e: raise ReadError(str(e)) if self.mode in ("a", "w", "x"): self._loaded = True if self.pax_headers: buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy()) self.fileobj.write(buf) self.offset += len(buf) except: if not self._extfileobj: self.fileobj.close() self.closed = True raise #-------------------------------------------------------------------------- # Below are the classmethods which act as alternate constructors to the # TarFile class. The open() method is the only one that is needed for # public use; it is the "super"-constructor and is able to select an # adequate "sub"-constructor for a particular compression using the mapping # from OPEN_METH. # # This concept allows one to subclass TarFile without losing the comfort of # the super-constructor. A sub-constructor is registered and made available # by adding it to the mapping in OPEN_METH. @classmethod def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'r:xz' open for reading with lzma compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'w:xz' open for writing with lzma compression 'x' or 'x:' create a tarfile exclusively without compression, raise an exception if the file is already created 'x:gz' create a gzip compressed tarfile, raise an exception if the file is already created 'x:bz2' create a bzip2 compressed tarfile, raise an exception if the file is already created 'x:xz' create an lzma compressed tarfile, raise an exception if the file is already created 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'r|xz' open an lzma compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing 'w|xz' open an lzma compressed stream for writing """ if not name and not fileobj: raise ValueError("nothing to open") if mode in ("r", "r:*"): # Find out which *open() is appropriate for opening the file. def not_compressed(comptype): return cls.OPEN_METH[comptype] == 'taropen' for comptype in sorted(cls.OPEN_METH, key=not_compressed): func = getattr(cls, cls.OPEN_METH[comptype]) if fileobj is not None: saved_pos = fileobj.tell() try: return func(name, "r", fileobj, **kwargs) except (ReadError, CompressionError): if fileobj is not None: fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") elif ":" in mode: filemode, comptype = mode.split(":", 1) filemode = filemode or "r" comptype = comptype or "tar" # Select the *open() function according to # given compression. if comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) else: raise CompressionError("unknown compression type %r" % comptype) return func(name, filemode, fileobj, **kwargs) elif "|" in mode: filemode, comptype = mode.split("|", 1) filemode = filemode or "r" comptype = comptype or "tar" if filemode not in ("r", "w"): raise ValueError("mode must be 'r' or 'w'") stream = _Stream(name, filemode, comptype, fileobj, bufsize) try: t = cls(name, filemode, stream, **kwargs) except: stream.close() raise t._extfileobj = False return t elif mode in ("a", "w", "x"): return cls.taropen(name, mode, fileobj, **kwargs) raise ValueError("undiscernible mode") @classmethod def taropen(cls, name, mode="r", fileobj=None, **kwargs): """Open uncompressed tar archive name for reading or writing. """ if mode not in ("r", "a", "w", "x"): raise ValueError("mode must be 'r', 'a', 'w' or 'x'") return cls(name, mode, fileobj, **kwargs) @classmethod def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if mode not in ("r", "w", "x"): raise ValueError("mode must be 'r', 'w' or 'x'") try: import gzip gzip.GzipFile except (ImportError, AttributeError): raise CompressionError("gzip module is not available") try: fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj) except OSError: if fileobj is not None and mode == 'r': raise ReadError("not a gzip file") raise try: t = cls.taropen(name, mode, fileobj, **kwargs) except OSError: fileobj.close() if mode == 'r': raise ReadError("not a gzip file") raise except: fileobj.close() raise t._extfileobj = False return t @classmethod def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if mode not in ("r", "w", "x"): raise ValueError("mode must be 'r', 'w' or 'x'") try: import bz2 except ImportError: raise CompressionError("bz2 module is not available") fileobj = bz2.BZ2File(fileobj or name, mode, compresslevel=compresslevel) try: t = cls.taropen(name, mode, fileobj, **kwargs) except (OSError, EOFError): fileobj.close() if mode == 'r': raise ReadError("not a bzip2 file") raise except: fileobj.close() raise t._extfileobj = False return t @classmethod def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs): """Open lzma compressed tar archive name for reading or writing. Appending is not allowed. """ if mode not in ("r", "w", "x"): raise ValueError("mode must be 'r', 'w' or 'x'") try: import lzma except ImportError: raise CompressionError("lzma module is not available") fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset) try: t = cls.taropen(name, mode, fileobj, **kwargs) except (lzma.LZMAError, EOFError): fileobj.close() if mode == 'r': raise ReadError("not an lzma file") raise except: fileobj.close() raise t._extfileobj = False return t # All *open() methods are registered here. OPEN_METH = { "tar": "taropen", # uncompressed tar "gz": "gzopen", # gzip compressed tar "bz2": "bz2open", # bzip2 compressed tar "xz": "xzopen" # lzma compressed tar } #-------------------------------------------------------------------------- # The public methods which TarFile provides: def close(self): """Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive. """ if self.closed: return self.closed = True try: if self.mode in ("a", "w", "x"): self.fileobj.write(NUL * (BLOCKSIZE * 2)) self.offset += (BLOCKSIZE * 2) # fill up the end with zero-blocks # (like option -b20 for tar does) blocks, remainder = divmod(self.offset, RECORDSIZE) if remainder > 0: self.fileobj.write(NUL * (RECORDSIZE - remainder)) finally: if not self._extfileobj: self.fileobj.close() def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version. """ tarinfo = self._getmember(name) if tarinfo is None: raise KeyError("filename %r not found" % name) return tarinfo def getmembers(self): """Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive. """ self._check() if not self._loaded: # if we want to obtain a list of self._load() # all members, we first have to # scan the whole archive. return self.members def getnames(self): """Return the members of the archive as a list of their names. It has the same order as the list returned by getmembers(). """ return [tarinfo.name for tarinfo in self.getmembers()] def gettarinfo(self, name=None, arcname=None, fileobj=None): """Create a TarInfo object from the result of os.stat or equivalent on an existing file. The file is either named by `name', or specified as a file object `fileobj' with a file descriptor. If given, `arcname' specifies an alternative name for the file in the archive, otherwise, the name is taken from the 'name' attribute of 'fileobj', or the 'name' argument. The name should be a text string. """ self._check("awx") # When fileobj is given, replace name by # fileobj's real name. if fileobj is not None: name = fileobj.name # Building the name of the member in the archive. # Backward slashes are converted to forward slashes, # Absolute paths are turned to relative paths. if arcname is None: arcname = name drv, arcname = os.path.splitdrive(arcname) arcname = arcname.replace(os.sep, "/") arcname = arcname.lstrip("/") # Now, fill the TarInfo object with # information specific for the file. tarinfo = self.tarinfo() tarinfo.tarfile = self # Not needed # Use os.stat or os.lstat, depending on platform # and if symlinks shall be resolved. if fileobj is None: if hasattr(os, "lstat") and not self.dereference: statres = os.lstat(name) else: statres = os.stat(name) else: statres = os.fstat(fileobj.fileno()) linkname = "" stmd = statres.st_mode if stat.S_ISREG(stmd): inode = (statres.st_ino, statres.st_dev) if not self.dereference and statres.st_nlink > 1 and \ inode in self.inodes and arcname != self.inodes[inode]: # Is it a hardlink to an already # archived file? type = LNKTYPE linkname = self.inodes[inode] else: # The inode is added only if its valid. # For win32 it is always 0. type = REGTYPE if inode[0]: self.inodes[inode] = arcname elif stat.S_ISDIR(stmd): type = DIRTYPE elif stat.S_ISFIFO(stmd): type = FIFOTYPE elif stat.S_ISLNK(stmd): type = SYMTYPE linkname = os.readlink(name) elif stat.S_ISCHR(stmd): type = CHRTYPE elif stat.S_ISBLK(stmd): type = BLKTYPE else: return None # Fill the TarInfo object with all # information we can get. tarinfo.name = arcname tarinfo.mode = stmd tarinfo.uid = statres.st_uid tarinfo.gid = statres.st_gid if type == REGTYPE: tarinfo.size = statres.st_size else: tarinfo.size = 0 tarinfo.mtime = statres.st_mtime tarinfo.type = type tarinfo.linkname = linkname if pwd: try: tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0] except KeyError: pass if grp: try: tarinfo.gname = grp.getgrgid(tarinfo.gid)[0] except KeyError: pass if type in (CHRTYPE, BLKTYPE): if hasattr(os, "major") and hasattr(os, "minor"): tarinfo.devmajor = os.major(statres.st_rdev) tarinfo.devminor = os.minor(statres.st_rdev) return tarinfo def list(self, verbose=True, *, members=None): """Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced. `members' is optional and must be a subset of the list returned by getmembers(). """ self._check() if members is None: members = self for tarinfo in members: if verbose: _safe_print(stat.filemode(tarinfo.mode)) _safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid, tarinfo.gname or tarinfo.gid)) if tarinfo.ischr() or tarinfo.isblk(): _safe_print("%10s" % ("%d,%d" % (tarinfo.devmajor, tarinfo.devminor))) else: _safe_print("%10d" % tarinfo.size) _safe_print("%d-%02d-%02d %02d:%02d:%02d" \ % time.localtime(tarinfo.mtime)[:6]) _safe_print(tarinfo.name + ("/" if tarinfo.isdir() else "")) if verbose: if tarinfo.issym(): _safe_print("-> " + tarinfo.linkname) if tarinfo.islnk(): _safe_print("link to " + tarinfo.linkname) print() def add(self, name, arcname=None, recursive=True, exclude=None, *, filter=None): """Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.). If given, `arcname' specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting `recursive' to False. `exclude' is a function that should return True for each filename to be excluded. `filter' is a function that expects a TarInfo object argument and returns the changed TarInfo object, if it returns None the TarInfo object will be excluded from the archive. """ self._check("awx") if arcname is None: arcname = name # Exclude pathnames. if exclude is not None: import warnings warnings.warn("use the filter argument instead", DeprecationWarning, 2) if exclude(name): self._dbg(2, "tarfile: Excluded %r" % name) return # Skip if somebody tries to archive the archive... if self.name is not None and os.path.abspath(name) == self.name: self._dbg(2, "tarfile: Skipped %r" % name) return self._dbg(1, name) # Create a TarInfo object from the file. tarinfo = self.gettarinfo(name, arcname) if tarinfo is None: self._dbg(1, "tarfile: Unsupported type %r" % name) return # Change or exclude the TarInfo object. if filter is not None: tarinfo = filter(tarinfo) if tarinfo is None: self._dbg(2, "tarfile: Excluded %r" % name) return # Append the tar header and data to the archive. if tarinfo.isreg(): with bltn_open(name, "rb") as f: self.addfile(tarinfo, f) elif tarinfo.isdir(): self.addfile(tarinfo) if recursive: for f in os.listdir(name): self.add(os.path.join(name, f), os.path.join(arcname, f), recursive, exclude, filter=filter) else: self.addfile(tarinfo) def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, it should be a binary file, and tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects directly, or by using gettarinfo(). """ self._check("awx") tarinfo = copy.copy(tarinfo) buf = tarinfo.tobuf(self.format, self.encoding, self.errors) self.fileobj.write(buf) self.offset += len(buf) bufsize=self.copybufsize # If there's data to follow, append it. if fileobj is not None: copyfileobj(fileobj, self.fileobj, tarinfo.size, bufsize=bufsize) blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) if remainder > 0: self.fileobj.write(NUL * (BLOCKSIZE - remainder)) blocks += 1 self.offset += blocks * BLOCKSIZE self.members.append(tarinfo) def extractall(self, path=".", members=None, *, numeric_owner=False): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). If `numeric_owner` is True, only the numbers for user/group names are used and not the names. """ directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 0o700 # Do not set_attrs directories, as we will do that further down self.extract(tarinfo, path, set_attrs=not tarinfo.isdir(), numeric_owner=numeric_owner) # Reverse sort directories. directories.sort(key=lambda a: a.name) directories.reverse() # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath, numeric_owner=numeric_owner) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e) def extract(self, member, path="", set_attrs=True, *, numeric_owner=False): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a TarInfo object. You can specify a different directory using `path'. File attributes (owner, mtime, mode) are set unless `set_attrs' is False. If `numeric_owner` is True, only the numbers for user/group names are used and not the names. """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member # Prepare the link target for makelink(). if tarinfo.islnk(): tarinfo._link_target = os.path.join(path, tarinfo.linkname) try: self._extract_member(tarinfo, os.path.join(path, tarinfo.name), set_attrs=set_attrs, numeric_owner=numeric_owner) except OSError as e: if self.errorlevel > 0: raise else: if e.filename is None: self._dbg(1, "tarfile: %s" % e.strerror) else: self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e) def extractfile(self, member): """Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file or a link, an io.BufferedReader object is returned. Otherwise, None is returned. """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES: # Members with unknown types are treated as regular files. return self.fileobject(self, tarinfo) elif tarinfo.islnk() or tarinfo.issym(): if isinstance(self.fileobj, _Stream): # A small but ugly workaround for the case that someone tries # to extract a (sym)link as a file-object from a non-seekable # stream of tar blocks. raise StreamError("cannot extract (sym)link as file object") else: # A (sym)link's file object is its target's file object. return self.extractfile(self._find_link_target(tarinfo)) else: # If there's no data associated with the member (directory, chrdev, # blkdev, etc.), return None instead of a file object. return None def _extract_member(self, tarinfo, targetpath, set_attrs=True, numeric_owner=False): """Extract the TarInfo object tarinfo to a physical file called targetpath. """ # Fetch the TarInfo object for the given name # and build the destination pathname, replacing # forward slashes to platform specific separators. targetpath = targetpath.rstrip("/") targetpath = targetpath.replace("/", os.sep) # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): # Create directories that are not part of the archive with # default permissions. os.makedirs(upperdirs) if tarinfo.islnk() or tarinfo.issym(): self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) else: self._dbg(1, tarinfo.name) if tarinfo.isreg(): self.makefile(tarinfo, targetpath) elif tarinfo.isdir(): self.makedir(tarinfo, targetpath) elif tarinfo.isfifo(): self.makefifo(tarinfo, targetpath) elif tarinfo.ischr() or tarinfo.isblk(): self.makedev(tarinfo, targetpath) elif tarinfo.islnk() or tarinfo.issym(): self.makelink(tarinfo, targetpath) elif tarinfo.type not in SUPPORTED_TYPES: self.makeunknown(tarinfo, targetpath) else: self.makefile(tarinfo, targetpath) if set_attrs: self.chown(tarinfo, targetpath, numeric_owner) if not tarinfo.issym(): self.chmod(tarinfo, targetpath) self.utime(tarinfo, targetpath) #-------------------------------------------------------------------------- # Below are the different file methods. They are called via # _extract_member() when extract() is called. They can be replaced in a # subclass to implement other functionality. def makedir(self, tarinfo, targetpath): """Make a directory called targetpath. """ try: # Use a safe mode for the directory, the real mode is set # later in _extract_member(). os.mkdir(targetpath, 0o700) except FileExistsError: pass def makefile(self, tarinfo, targetpath): """Make a file called targetpath. """ source = self.fileobj source.seek(tarinfo.offset_data) bufsize = self.copybufsize with bltn_open(targetpath, "wb") as target: if tarinfo.sparse is not None: for offset, size in tarinfo.sparse: target.seek(offset) copyfileobj(source, target, size, ReadError, bufsize) target.seek(tarinfo.size) target.truncate() else: copyfileobj(source, target, tarinfo.size, ReadError, bufsize) def makeunknown(self, tarinfo, targetpath): """Make a file from a TarInfo object with an unknown type at targetpath. """ self.makefile(tarinfo, targetpath) self._dbg(1, "tarfile: Unknown file type %r, " \ "extracted as regular file." % tarinfo.type) def makefifo(self, tarinfo, targetpath): """Make a fifo called targetpath. """ if hasattr(os, "mkfifo"): os.mkfifo(targetpath) else: raise ExtractError("fifo not supported by system") def makedev(self, tarinfo, targetpath): """Make a character or block device called targetpath. """ if not hasattr(os, "mknod") or not hasattr(os, "makedev"): raise ExtractError("special devices not supported by system") mode = tarinfo.mode if tarinfo.isblk(): mode |= stat.S_IFBLK else: mode |= stat.S_IFCHR os.mknod(targetpath, mode, os.makedev(tarinfo.devmajor, tarinfo.devminor)) def makelink(self, tarinfo, targetpath): """Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link. """ try: # For systems that support symbolic and hard links. if tarinfo.issym(): os.symlink(tarinfo.linkname, targetpath) else: # See extract(). if os.path.exists(tarinfo._link_target): os.link(tarinfo._link_target, targetpath) else: self._extract_member(self._find_link_target(tarinfo), targetpath) except symlink_exception: try: self._extract_member(self._find_link_target(tarinfo), targetpath) except KeyError: raise ExtractError("unable to resolve link inside archive") def chown(self, tarinfo, targetpath, numeric_owner): """Set owner of targetpath according to tarinfo. If numeric_owner is True, use .gid/.uid instead of .gname/.uname. If numeric_owner is False, fall back to .gid/.uid when the search based on name fails. """ if hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. g = tarinfo.gid u = tarinfo.uid if not numeric_owner: try: if grp: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: pass try: if pwd: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: pass try: if tarinfo.issym() and hasattr(os, "lchown"): os.lchown(targetpath, u, g) else: os.chown(targetpath, u, g) except OSError: raise ExtractError("could not change owner") def chmod(self, tarinfo, targetpath): """Set file permissions of targetpath according to tarinfo. """ if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) except OSError: raise ExtractError("could not change mode") def utime(self, tarinfo, targetpath): """Set modification time of targetpath according to tarinfo. """ if not hasattr(os, 'utime'): return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) except OSError: raise ExtractError("could not change modification time") #-------------------------------------------------------------------------- def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m # Advance the file pointer. if self.offset != self.fileobj.tell(): self.fileobj.seek(self.offset - 1) if not self.fileobj.read(1): raise ReadError("unexpected end of data") # Read the next block. tarinfo = None while True: try: tarinfo = self.tarinfo.fromtarfile(self) except EOFHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue except InvalidHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue elif self.offset == 0: raise ReadError(str(e)) except EmptyHeaderError: if self.offset == 0: raise ReadError("empty file") except TruncatedHeaderError as e: if self.offset == 0: raise ReadError(str(e)) except SubsequentHeaderError as e: raise ReadError(str(e)) break if tarinfo is not None: self.members.append(tarinfo) else: self._loaded = True return tarinfo #-------------------------------------------------------------------------- # Little helper methods: def _getmember(self, name, tarinfo=None, normalize=False): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ # Ensure that all members have been loaded. members = self.getmembers() # Limit the member search list up to tarinfo. if tarinfo is not None: members = members[:members.index(tarinfo)] if normalize: name = os.path.normpath(name) for member in reversed(members): if normalize: member_name = os.path.normpath(member.name) else: member_name = member.name if name == member_name: return member def _load(self): """Read through the entire archive file and look for readable members. """ while True: tarinfo = self.next() if tarinfo is None: break self._loaded = True def _check(self, mode=None): """Check if TarFile is still open, and if the operation's mode corresponds to TarFile's mode. """ if self.closed: raise OSError("%s is closed" % self.__class__.__name__) if mode is not None and self.mode not in mode: raise OSError("bad operation for mode %r" % self.mode) def _find_link_target(self, tarinfo): """Find the target member of a symlink or hardlink member in the archive. """ if tarinfo.issym(): # Always search the entire archive. linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname))) limit = None else: # Search the archive before the link, because a hard link is # just a reference to an already archived file. linkname = tarinfo.linkname limit = tarinfo member = self._getmember(linkname, tarinfo=limit, normalize=True) if member is None: raise KeyError("linkname %r not found" % linkname) return member def __iter__(self): """Provide an iterator object. """ if self._loaded: yield from self.members return # Yield items using TarFile's next() method. # When all members have been read, set TarFile as _loaded. index = 0 # Fix for SF #1100429: Under rare circumstances it can # happen that getmembers() is called during iteration, # which will have already exhausted the next() method. if self.firstmember is not None: tarinfo = self.next() index += 1 yield tarinfo while True: if index < len(self.members): tarinfo = self.members[index] elif not self._loaded: tarinfo = self.next() if not tarinfo: self._loaded = True return else: return index += 1 yield tarinfo def _dbg(self, level, msg): """Write debugging output to sys.stderr. """ if level <= self.debug: print(msg, file=sys.stderr) def __enter__(self): self._check() return self def __exit__(self, type, value, traceback): if type is None: self.close() else: # An exception occurred. We must not call close() because # it would try to write end-of-archive blocks and padding. if not self._extfileobj: self.fileobj.close() self.closed = True #-------------------- # exported functions #-------------------- def is_tarfile(name): """Return True if name points to a tar archive that we are able to handle, else return False. """ try: t = open(name) t.close() return True except TarError: return False open = TarFile.open def main(): import argparse description = 'A simple command line interface for tarfile module.' parser = argparse.ArgumentParser(description=description) parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Verbose output') group = parser.add_mutually_exclusive_group() group.add_argument('-l', '--list', metavar='<tarfile>', help='Show listing of a tarfile') group.add_argument('-e', '--extract', nargs='+', metavar=('<tarfile>', '<output_dir>'), help='Extract tarfile into target dir') group.add_argument('-c', '--create', nargs='+', metavar=('<name>', '<file>'), help='Create tarfile from sources') group.add_argument('-t', '--test', metavar='<tarfile>', help='Test if a tarfile is valid') args = parser.parse_args() if args.test: src = args.test if is_tarfile(src): with open(src, 'r') as tar: tar.getmembers() print(tar.getmembers(), file=sys.stderr) if args.verbose: print('{!r} is a tar archive.'.format(src)) else: parser.exit(1, '{!r} is not a tar archive.\n'.format(src)) elif args.list: src = args.list if is_tarfile(src): with TarFile.open(src, 'r:*') as tf: tf.list(verbose=args.verbose) else: parser.exit(1, '{!r} is not a tar archive.\n'.format(src)) elif args.extract: if len(args.extract) == 1: src = args.extract[0] curdir = os.curdir elif len(args.extract) == 2: src, curdir = args.extract else: parser.exit(1, parser.format_help()) if is_tarfile(src): with TarFile.open(src, 'r:*') as tf: tf.extractall(path=curdir) if args.verbose: if curdir == '.': msg = '{!r} file is extracted.'.format(src) else: msg = ('{!r} file is extracted ' 'into {!r} directory.').format(src, curdir) print(msg) else: parser.exit(1, '{!r} is not a tar archive.\n'.format(src)) elif args.create: tar_name = args.create.pop(0) _, ext = os.path.splitext(tar_name) compressions = { # gz '.gz': 'gz', '.tgz': 'gz', # xz '.xz': 'xz', '.txz': 'xz', # bz2 '.bz2': 'bz2', '.tbz': 'bz2', '.tbz2': 'bz2', '.tb2': 'bz2', } tar_mode = 'w:' + compressions[ext] if ext in compressions else 'w' tar_files = args.create with TarFile.open(tar_name, tar_mode) as tf: for file_name in tar_files: tf.add(file_name) if args.verbose: print('{!r} file created.'.format(tar_name)) else: parser.exit(1, parser.format_help()) if __name__ == '__main__': main()
93,304
2,553
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/secrets.py
"""Generate cryptographically strong pseudo-random numbers suitable for managing secrets such as account authentication, tokens, and similar. See PEP 506 for more information. https://www.python.org/dev/peps/pep-0506/ """ __all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom', 'token_bytes', 'token_hex', 'token_urlsafe', 'compare_digest', ] import base64 import binascii import os from hmac import compare_digest from random import SystemRandom _sysrand = SystemRandom() randbits = _sysrand.getrandbits choice = _sysrand.choice def randbelow(exclusive_upper_bound): """Return a random int in the range [0, n).""" if exclusive_upper_bound <= 0: raise ValueError("Upper bound must be positive.") return _sysrand._randbelow(exclusive_upper_bound) DEFAULT_ENTROPY = 32 # number of bytes to return by default def token_bytes(nbytes=None): """Return a random byte string containing *nbytes* bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. >>> token_bytes(16) #doctest:+SKIP b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b' """ if nbytes is None: nbytes = DEFAULT_ENTROPY return os.urandom(nbytes) def token_hex(nbytes=None): """Return a random text string, in hexadecimal. The string has *nbytes* random bytes, each byte converted to two hex digits. If *nbytes* is ``None`` or not supplied, a reasonable default is used. >>> token_hex(16) #doctest:+SKIP 'f9bf78b9a18ce6d46a0cd2b0b86df9da' """ return binascii.hexlify(token_bytes(nbytes)).decode('ascii') def token_urlsafe(nbytes=None): """Return a random URL-safe text string, in Base64 encoding. The string has *nbytes* random bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. >>> token_urlsafe(16) #doctest:+SKIP 'Drmhze6EPcv0fN_81Bj-nA' """ tok = token_bytes(nbytes) return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')
2,038
74
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/formatter.py
"""Generic output formatting. Formatter objects transform an abstract flow of formatting events into specific output events on writer objects. Formatters manage several stack structures to allow various properties of a writer object to be changed and restored; writers need not be able to handle relative changes nor any sort of ``change back'' operation. Specific writer properties which may be controlled via formatter objects are horizontal alignment, font, and left margin indentations. A mechanism is provided which supports providing arbitrary, non-exclusive style settings to a writer as well. Additional interfaces facilitate formatting events which are not reversible, such as paragraph separation. Writer objects encapsulate device interfaces. Abstract devices, such as file formats, are supported as well as physical devices. The provided implementations all work with abstract devices. The interface makes available mechanisms for setting the properties which formatter objects manage and inserting data into the output. """ import sys import warnings warnings.warn('the formatter module is deprecated', DeprecationWarning, stacklevel=2) AS_IS = None class NullFormatter: """A formatter which does nothing. If the writer parameter is omitted, a NullWriter instance is created. No methods of the writer are called by NullFormatter instances. Implementations should inherit from this class if implementing a writer interface but don't need to inherit any implementation. """ def __init__(self, writer=None): if writer is None: writer = NullWriter() self.writer = writer def end_paragraph(self, blankline): pass def add_line_break(self): pass def add_hor_rule(self, *args, **kw): pass def add_label_data(self, format, counter, blankline=None): pass def add_flowing_data(self, data): pass def add_literal_data(self, data): pass def flush_softspace(self): pass def push_alignment(self, align): pass def pop_alignment(self): pass def push_font(self, x): pass def pop_font(self): pass def push_margin(self, margin): pass def pop_margin(self): pass def set_spacing(self, spacing): pass def push_style(self, *styles): pass def pop_style(self, n=1): pass def assert_line_data(self, flag=1): pass class AbstractFormatter: """The standard formatter. This implementation has demonstrated wide applicability to many writers, and may be used directly in most circumstances. It has been used to implement a full-featured World Wide Web browser. """ # Space handling policy: blank spaces at the boundary between elements # are handled by the outermost context. "Literal" data is not checked # to determine context, so spaces in literal data are handled directly # in all circumstances. def __init__(self, writer): self.writer = writer # Output device self.align = None # Current alignment self.align_stack = [] # Alignment stack self.font_stack = [] # Font state self.margin_stack = [] # Margin state self.spacing = None # Vertical spacing state self.style_stack = [] # Other state, e.g. color self.nospace = 1 # Should leading space be suppressed self.softspace = 0 # Should a space be inserted self.para_end = 1 # Just ended a paragraph self.parskip = 0 # Skipped space between paragraphs? self.hard_break = 1 # Have a hard break self.have_label = 0 def end_paragraph(self, blankline): if not self.hard_break: self.writer.send_line_break() self.have_label = 0 if self.parskip < blankline and not self.have_label: self.writer.send_paragraph(blankline - self.parskip) self.parskip = blankline self.have_label = 0 self.hard_break = self.nospace = self.para_end = 1 self.softspace = 0 def add_line_break(self): if not (self.hard_break or self.para_end): self.writer.send_line_break() self.have_label = self.parskip = 0 self.hard_break = self.nospace = 1 self.softspace = 0 def add_hor_rule(self, *args, **kw): if not self.hard_break: self.writer.send_line_break() self.writer.send_hor_rule(*args, **kw) self.hard_break = self.nospace = 1 self.have_label = self.para_end = self.softspace = self.parskip = 0 def add_label_data(self, format, counter, blankline = None): if self.have_label or not self.hard_break: self.writer.send_line_break() if not self.para_end: self.writer.send_paragraph((blankline and 1) or 0) if isinstance(format, str): self.writer.send_label_data(self.format_counter(format, counter)) else: self.writer.send_label_data(format) self.nospace = self.have_label = self.hard_break = self.para_end = 1 self.softspace = self.parskip = 0 def format_counter(self, format, counter): label = '' for c in format: if c == '1': label = label + ('%d' % counter) elif c in 'aA': if counter > 0: label = label + self.format_letter(c, counter) elif c in 'iI': if counter > 0: label = label + self.format_roman(c, counter) else: label = label + c return label def format_letter(self, case, counter): label = '' while counter > 0: counter, x = divmod(counter-1, 26) # This makes a strong assumption that lowercase letters # and uppercase letters form two contiguous blocks, with # letters in order! s = chr(ord(case) + x) label = s + label return label def format_roman(self, case, counter): ones = ['i', 'x', 'c', 'm'] fives = ['v', 'l', 'd'] label, index = '', 0 # This will die of IndexError when counter is too big while counter > 0: counter, x = divmod(counter, 10) if x == 9: label = ones[index] + ones[index+1] + label elif x == 4: label = ones[index] + fives[index] + label else: if x >= 5: s = fives[index] x = x-5 else: s = '' s = s + ones[index]*x label = s + label index = index + 1 if case == 'I': return label.upper() return label def add_flowing_data(self, data): if not data: return prespace = data[:1].isspace() postspace = data[-1:].isspace() data = " ".join(data.split()) if self.nospace and not data: return elif prespace or self.softspace: if not data: if not self.nospace: self.softspace = 1 self.parskip = 0 return if not self.nospace: data = ' ' + data self.hard_break = self.nospace = self.para_end = \ self.parskip = self.have_label = 0 self.softspace = postspace self.writer.send_flowing_data(data) def add_literal_data(self, data): if not data: return if self.softspace: self.writer.send_flowing_data(" ") self.hard_break = data[-1:] == '\n' self.nospace = self.para_end = self.softspace = \ self.parskip = self.have_label = 0 self.writer.send_literal_data(data) def flush_softspace(self): if self.softspace: self.hard_break = self.para_end = self.parskip = \ self.have_label = self.softspace = 0 self.nospace = 1 self.writer.send_flowing_data(' ') def push_alignment(self, align): if align and align != self.align: self.writer.new_alignment(align) self.align = align self.align_stack.append(align) else: self.align_stack.append(self.align) def pop_alignment(self): if self.align_stack: del self.align_stack[-1] if self.align_stack: self.align = align = self.align_stack[-1] self.writer.new_alignment(align) else: self.align = None self.writer.new_alignment(None) def push_font(self, font): size, i, b, tt = font if self.softspace: self.hard_break = self.para_end = self.softspace = 0 self.nospace = 1 self.writer.send_flowing_data(' ') if self.font_stack: csize, ci, cb, ctt = self.font_stack[-1] if size is AS_IS: size = csize if i is AS_IS: i = ci if b is AS_IS: b = cb if tt is AS_IS: tt = ctt font = (size, i, b, tt) self.font_stack.append(font) self.writer.new_font(font) def pop_font(self): if self.font_stack: del self.font_stack[-1] if self.font_stack: font = self.font_stack[-1] else: font = None self.writer.new_font(font) def push_margin(self, margin): self.margin_stack.append(margin) fstack = [m for m in self.margin_stack if m] if not margin and fstack: margin = fstack[-1] self.writer.new_margin(margin, len(fstack)) def pop_margin(self): if self.margin_stack: del self.margin_stack[-1] fstack = [m for m in self.margin_stack if m] if fstack: margin = fstack[-1] else: margin = None self.writer.new_margin(margin, len(fstack)) def set_spacing(self, spacing): self.spacing = spacing self.writer.new_spacing(spacing) def push_style(self, *styles): if self.softspace: self.hard_break = self.para_end = self.softspace = 0 self.nospace = 1 self.writer.send_flowing_data(' ') for style in styles: self.style_stack.append(style) self.writer.new_styles(tuple(self.style_stack)) def pop_style(self, n=1): del self.style_stack[-n:] self.writer.new_styles(tuple(self.style_stack)) def assert_line_data(self, flag=1): self.nospace = self.hard_break = not flag self.para_end = self.parskip = self.have_label = 0 class NullWriter: """Minimal writer interface to use in testing & inheritance. A writer which only provides the interface definition; no actions are taken on any methods. This should be the base class for all writers which do not need to inherit any implementation methods. """ def __init__(self): pass def flush(self): pass def new_alignment(self, align): pass def new_font(self, font): pass def new_margin(self, margin, level): pass def new_spacing(self, spacing): pass def new_styles(self, styles): pass def send_paragraph(self, blankline): pass def send_line_break(self): pass def send_hor_rule(self, *args, **kw): pass def send_label_data(self, data): pass def send_flowing_data(self, data): pass def send_literal_data(self, data): pass class AbstractWriter(NullWriter): """A writer which can be used in debugging formatters, but not much else. Each method simply announces itself by printing its name and arguments on standard output. """ def new_alignment(self, align): print("new_alignment(%r)" % (align,)) def new_font(self, font): print("new_font(%r)" % (font,)) def new_margin(self, margin, level): print("new_margin(%r, %d)" % (margin, level)) def new_spacing(self, spacing): print("new_spacing(%r)" % (spacing,)) def new_styles(self, styles): print("new_styles(%r)" % (styles,)) def send_paragraph(self, blankline): print("send_paragraph(%r)" % (blankline,)) def send_line_break(self): print("send_line_break()") def send_hor_rule(self, *args, **kw): print("send_hor_rule()") def send_label_data(self, data): print("send_label_data(%r)" % (data,)) def send_flowing_data(self, data): print("send_flowing_data(%r)" % (data,)) def send_literal_data(self, data): print("send_literal_data(%r)" % (data,)) class DumbWriter(NullWriter): """Simple writer class which writes output on the file object passed in as the file parameter or, if file is omitted, on standard output. The output is simply word-wrapped to the number of columns specified by the maxcol parameter. This class is suitable for reflowing a sequence of paragraphs. """ def __init__(self, file=None, maxcol=72): self.file = file or sys.stdout self.maxcol = maxcol NullWriter.__init__(self) self.reset() def reset(self): self.col = 0 self.atbreak = 0 def send_paragraph(self, blankline): self.file.write('\n'*blankline) self.col = 0 self.atbreak = 0 def send_line_break(self): self.file.write('\n') self.col = 0 self.atbreak = 0 def send_hor_rule(self, *args, **kw): self.file.write('\n') self.file.write('-'*self.maxcol) self.file.write('\n') self.col = 0 self.atbreak = 0 def send_literal_data(self, data): self.file.write(data) i = data.rfind('\n') if i >= 0: self.col = 0 data = data[i+1:] data = data.expandtabs() self.col = self.col + len(data) self.atbreak = 0 def send_flowing_data(self, data): if not data: return atbreak = self.atbreak or data[0].isspace() col = self.col maxcol = self.maxcol write = self.file.write for word in data.split(): if atbreak: if col + len(word) >= maxcol: write('\n') col = 0 else: write(' ') col = col + 1 write(word) col = col + len(word) atbreak = 1 self.col = col self.atbreak = data[-1].isspace() def test(file = None): w = DumbWriter() f = AbstractFormatter(w) if file is not None: fp = open(file) elif sys.argv[1:]: fp = open(sys.argv[1]) else: fp = sys.stdin try: for line in fp: if line == '\n': f.end_paragraph(1) else: f.add_flowing_data(line) finally: if fp is not sys.stdin: fp.close() f.end_paragraph(0) if __name__ == '__main__': test()
15,143
453
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/zipfile.py
""" Read and write ZIP files. XXX references to utf-8 need further investigation. """ import io import os import re import importlib.util import sys import time import stat import shutil import struct import binascii try: import threading except ImportError: import dummy_threading as threading try: import zlib # We may need its compression method crc32 = zlib.crc32 except ImportError: zlib = None crc32 = binascii.crc32 try: import bz2 # We may need its compression method except ImportError: bz2 = None try: import lzma # We may need its compression method except ImportError: lzma = None __all__ = ["BadZipFile", "BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "ZIP_BZIP2", "ZIP_LZMA", "is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile"] class BadZipFile(Exception): pass class LargeZipFile(Exception): """ Raised when writing a zipfile, the zipfile requires ZIP64 extensions and those extensions are disabled. """ error = BadZipfile = BadZipFile # Pre-3.2 compatibility names ZIP64_LIMIT = (1 << 31) - 1 ZIP_FILECOUNT_LIMIT = (1 << 16) - 1 ZIP_MAX_COMMENT = (1 << 16) - 1 # constants for Zip file compression methods ZIP_STORED = 0 ZIP_DEFLATED = 8 ZIP_BZIP2 = 12 ZIP_LZMA = 14 # Other ZIP compression methods not supported DEFAULT_VERSION = 20 ZIP64_VERSION = 45 BZIP2_VERSION = 46 LZMA_VERSION = 63 # we recognize (but not necessarily support) all features up to that version MAX_EXTRACT_VERSION = 63 # Below are some formats and associated data for reading/writing headers using # the struct module. The names and structures of headers/records are those used # in the PKWARE description of the ZIP file format: # http://www.pkware.com/documents/casestudies/APPNOTE.TXT # (URL valid as of January 2008) # The "end of central directory" structure, magic number, size, and indices # (section V.I in the format document) structEndArchive = b"<4s4H2LH" stringEndArchive = b"PK\005\006" sizeEndCentDir = struct.calcsize(structEndArchive) _ECD_SIGNATURE = 0 _ECD_DISK_NUMBER = 1 _ECD_DISK_START = 2 _ECD_ENTRIES_THIS_DISK = 3 _ECD_ENTRIES_TOTAL = 4 _ECD_SIZE = 5 _ECD_OFFSET = 6 _ECD_COMMENT_SIZE = 7 # These last two indices are not part of the structure as defined in the # spec, but they are used internally by this module as a convenience _ECD_COMMENT = 8 _ECD_LOCATION = 9 # The "central directory" structure, magic number, size, and indices # of entries in the structure (section V.F in the format document) structCentralDir = "<4s4B4HL2L5H2L" stringCentralDir = b"PK\001\002" sizeCentralDir = struct.calcsize(structCentralDir) # indexes of entries in the central directory structure _CD_SIGNATURE = 0 _CD_CREATE_VERSION = 1 _CD_CREATE_SYSTEM = 2 _CD_EXTRACT_VERSION = 3 _CD_EXTRACT_SYSTEM = 4 _CD_FLAG_BITS = 5 _CD_COMPRESS_TYPE = 6 _CD_TIME = 7 _CD_DATE = 8 _CD_CRC = 9 _CD_COMPRESSED_SIZE = 10 _CD_UNCOMPRESSED_SIZE = 11 _CD_FILENAME_LENGTH = 12 _CD_EXTRA_FIELD_LENGTH = 13 _CD_COMMENT_LENGTH = 14 _CD_DISK_NUMBER_START = 15 _CD_INTERNAL_FILE_ATTRIBUTES = 16 _CD_EXTERNAL_FILE_ATTRIBUTES = 17 _CD_LOCAL_HEADER_OFFSET = 18 # The "local file header" structure, magic number, size, and indices # (section V.A in the format document) structFileHeader = "<4s2B4HL2L2H" stringFileHeader = b"PK\003\004" sizeFileHeader = struct.calcsize(structFileHeader) _FH_SIGNATURE = 0 _FH_EXTRACT_VERSION = 1 _FH_EXTRACT_SYSTEM = 2 _FH_GENERAL_PURPOSE_FLAG_BITS = 3 _FH_COMPRESSION_METHOD = 4 _FH_LAST_MOD_TIME = 5 _FH_LAST_MOD_DATE = 6 _FH_CRC = 7 _FH_COMPRESSED_SIZE = 8 _FH_UNCOMPRESSED_SIZE = 9 _FH_FILENAME_LENGTH = 10 _FH_EXTRA_FIELD_LENGTH = 11 # The "Zip64 end of central directory locator" structure, magic number, and size structEndArchive64Locator = "<4sLQL" stringEndArchive64Locator = b"PK\x06\x07" sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator) # The "Zip64 end of central directory" record, magic number, size, and indices # (section V.G in the format document) structEndArchive64 = "<4sQ2H2L4Q" stringEndArchive64 = b"PK\x06\x06" sizeEndCentDir64 = struct.calcsize(structEndArchive64) _CD64_SIGNATURE = 0 _CD64_DIRECTORY_RECSIZE = 1 _CD64_CREATE_VERSION = 2 _CD64_EXTRACT_VERSION = 3 _CD64_DISK_NUMBER = 4 _CD64_DISK_NUMBER_START = 5 _CD64_NUMBER_ENTRIES_THIS_DISK = 6 _CD64_NUMBER_ENTRIES_TOTAL = 7 _CD64_DIRECTORY_SIZE = 8 _CD64_OFFSET_START_CENTDIR = 9 _DD_SIGNATURE = 0x08074b50 _EXTRA_FIELD_STRUCT = struct.Struct('<HH') def _strip_extra(extra, xids): # Remove Extra Fields with specified IDs. unpack = _EXTRA_FIELD_STRUCT.unpack modified = False buffer = [] start = i = 0 while i + 4 <= len(extra): xid, xlen = unpack(extra[i : i + 4]) j = i + 4 + xlen if xid in xids: if i != start: buffer.append(extra[start : i]) start = j modified = True i = j if not modified: return extra return b''.join(buffer) def _check_zipfile(fp): try: if _EndRecData(fp): return True # file has correct magic number except OSError: pass return False def is_zipfile(filename): """Quickly see if a file is a ZIP file by checking the magic number. The filename argument may be a file or file-like object too. """ result = False try: if hasattr(filename, "read"): result = _check_zipfile(fp=filename) else: with open(filename, "rb") as fp: result = _check_zipfile(fp) except OSError: pass return result def _EndRecData64(fpin, offset, endrec): """ Read the ZIP64 end-of-archive records and use that to update endrec """ try: fpin.seek(offset - sizeEndCentDir64Locator, 2) except OSError: # If the seek fails, the file is not large enough to contain a ZIP64 # end-of-archive record, so just return the end record we were given. return endrec data = fpin.read(sizeEndCentDir64Locator) if len(data) != sizeEndCentDir64Locator: return endrec sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data) if sig != stringEndArchive64Locator: return endrec if diskno != 0 or disks != 1: raise BadZipFile("zipfiles that span multiple disks are not supported") # Assume no 'zip64 extensible data' fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2) data = fpin.read(sizeEndCentDir64) if len(data) != sizeEndCentDir64: return endrec sig, sz, create_version, read_version, disk_num, disk_dir, \ dircount, dircount2, dirsize, diroffset = \ struct.unpack(structEndArchive64, data) if sig != stringEndArchive64: return endrec # Update the original endrec using data from the ZIP64 record endrec[_ECD_SIGNATURE] = sig endrec[_ECD_DISK_NUMBER] = disk_num endrec[_ECD_DISK_START] = disk_dir endrec[_ECD_ENTRIES_THIS_DISK] = dircount endrec[_ECD_ENTRIES_TOTAL] = dircount2 endrec[_ECD_SIZE] = dirsize endrec[_ECD_OFFSET] = diroffset return endrec def _EndRecData(fpin): """Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.""" # Determine file size fpin.seek(0, 2) filesize = fpin.tell() # Check to see if this is ZIP file with no archive comment (the # "end of central directory" structure should be the last item in the # file if this is the case). try: fpin.seek(-sizeEndCentDir, 2) except OSError: return None data = fpin.read() if (len(data) == sizeEndCentDir and data[0:4] == stringEndArchive and data[-2:] == b"\000\000"): # the signature is correct and there's no comment, unpack structure endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append(b"") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] if len(recData) != sizeEndCentDir: # Zip file is corrupted. return None endrec = list(struct.unpack(structEndArchive, recData)) commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize] endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return None class ZipInfo (object): """Class with attributes describing each file in the ZIP archive.""" __slots__ = ( 'orig_filename', 'filename', 'date_time', 'compress_type', 'comment', 'extra', 'create_system', 'create_version', 'extract_version', 'reserved', 'flag_bits', 'volume', 'internal_attr', 'external_attr', 'header_offset', 'CRC', 'compress_size', 'file_size', '_raw_time', ) def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.orig_filename = filename # Original file name in archive # Terminate the file name at the first null byte. Null bytes in file # names are used as tricks by viruses in archives. null_byte = filename.find(chr(0)) if null_byte >= 0: filename = filename[0:null_byte] # This is used to ensure paths in generated ZIP files always use # forward slashes as the directory separator, as required by the # ZIP format specification. if os.sep != "/" and os.sep in filename: filename = filename.replace(os.sep, "/") self.filename = filename # Normalized file name self.date_time = date_time # year, month, day, hour, min, sec if date_time[0] < 1980: raise ValueError('ZIP does not support timestamps before 1980') # Standard values: self.compress_type = ZIP_STORED # Type of compression for the file self.comment = b"" # Comment for each file self.extra = b"" # ZIP extra data if sys.platform == 'win32': self.create_system = 0 # System which created ZIP archive else: # Assume everything else is unix-y self.create_system = 3 # System which created ZIP archive self.create_version = DEFAULT_VERSION # Version which created ZIP archive self.extract_version = DEFAULT_VERSION # Version needed to extract archive self.reserved = 0 # Must be zero self.flag_bits = 0 # ZIP flag bits self.volume = 0 # Volume number of file header self.internal_attr = 0 # Internal attributes self.external_attr = 0 # External file attributes # Other attributes are set by class ZipFile: # header_offset Byte offset to the file header # CRC CRC-32 of the uncompressed file # compress_size Size of the compressed file # file_size Size of the uncompressed file def __repr__(self): result = ['<%s filename=%r' % (self.__class__.__name__, self.filename)] if self.compress_type != ZIP_STORED: result.append(' compress_type=%s' % compressor_names.get(self.compress_type, self.compress_type)) hi = self.external_attr >> 16 lo = self.external_attr & 0xFFFF if hi: result.append(' filemode=%r' % stat.filemode(hi)) if lo: result.append(' external_attr=%#x' % lo) isdir = self.is_dir() if not isdir or self.file_size: result.append(' file_size=%r' % self.file_size) if ((not isdir or self.compress_size) and (self.compress_type != ZIP_STORED or self.file_size != self.compress_size)): result.append(' compress_size=%r' % self.compress_size) result.append('>') return ''.join(result) def FileHeader(self, zip64=None): """Return the per-file header as a bytes object.""" dt = self.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) if self.flag_bits & 0x08: # Set these to zero because we write them after the file data CRC = compress_size = file_size = 0 else: CRC = self.CRC compress_size = self.compress_size file_size = self.file_size extra = self.extra min_version = 0 if zip64 is None: zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT if zip64: fmt = '<HHQQ' extra = extra + struct.pack(fmt, 1, struct.calcsize(fmt)-4, file_size, compress_size) if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT: if not zip64: raise LargeZipFile("Filesize would require ZIP64 extensions") # File is larger than what fits into a 4 byte integer, # fall back to the ZIP64 extension file_size = 0xffffffff compress_size = 0xffffffff min_version = ZIP64_VERSION if self.compress_type == ZIP_BZIP2: min_version = max(BZIP2_VERSION, min_version) elif self.compress_type == ZIP_LZMA: min_version = max(LZMA_VERSION, min_version) self.extract_version = max(min_version, self.extract_version) self.create_version = max(min_version, self.create_version) filename, flag_bits = self._encodeFilenameFlags() header = struct.pack(structFileHeader, stringFileHeader, self.extract_version, self.reserved, flag_bits, self.compress_type, dostime, dosdate, CRC, compress_size, file_size, len(filename), len(extra)) return header + filename + extra def _encodeFilenameFlags(self): try: return self.filename.encode('ascii'), self.flag_bits except UnicodeEncodeError: return self.filename.encode('utf-8'), self.flag_bits | 0x800 def _decodeExtra(self): # Try to decode the extra field. extra = self.extra unpack = struct.unpack while len(extra) >= 4: tp, ln = unpack('<HH', extra[:4]) if tp == 1: if ln >= 24: counts = unpack('<QQQ', extra[4:28]) elif ln == 16: counts = unpack('<QQ', extra[4:20]) elif ln == 8: counts = unpack('<Q', extra[4:12]) elif ln == 0: counts = () else: raise BadZipFile("Corrupt extra field %04x (size=%d)" % (tp, ln)) idx = 0 # ZIP64 extension (large files and/or large archives) if self.file_size in (0xffffffffffffffff, 0xffffffff): self.file_size = counts[idx] idx += 1 if self.compress_size == 0xFFFFFFFF: self.compress_size = counts[idx] idx += 1 if self.header_offset == 0xffffffff: old = self.header_offset self.header_offset = counts[idx] idx+=1 extra = extra[ln+4:] @classmethod def from_file(cls, filename, arcname=None): """Construct an appropriate ZipInfo for a file on the filesystem. filename should be the path to a file or directory on the filesystem. arcname is the name which it will have within the archive (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). """ if isinstance(filename, os.PathLike): filename = os.fspath(filename) st = os.stat(filename) isdir = stat.S_ISDIR(st.st_mode) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] # Create ZipInfo instance to store file information if arcname is None: arcname = filename arcname = os.path.normpath(os.path.splitdrive(arcname)[1]) while arcname[0] in (os.sep, os.altsep): arcname = arcname[1:] if isdir: arcname += '/' zinfo = cls(arcname, date_time) zinfo.external_attr = (st.st_mode & 0xFFFF) << 16 # Unix attributes if isdir: zinfo.file_size = 0 zinfo.external_attr |= 0x10 # MS-DOS directory flag else: zinfo.file_size = st.st_size return zinfo def is_dir(self): """Return True if this archive member is a directory.""" return self.filename[-1] == '/' class _ZipDecrypter: """Class to handle decryption of files stored within a ZIP archive. ZIP supports a password-based form of encryption. Even though known plaintext attacks have been found against it, it is still useful to be able to get data out of such a file. Usage: zd = _ZipDecrypter(mypwd) plain_char = zd(cypher_char) plain_text = map(zd, cypher_text) """ def _GenerateCRCTable(): """Generate a CRC-32 table. ZIP encryption uses the CRC32 one-byte primitive for scrambling some internal keys. We noticed that a direct implementation is faster than relying on binascii.crc32(). """ poly = 0xedb88320 table = [0] * 256 for i in range(256): crc = i for j in range(8): if crc & 1: crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly else: crc = ((crc >> 1) & 0x7FFFFFFF) table[i] = crc return table crctable = None def _crc32(self, ch, crc): """Compute the CRC32 primitive on one byte.""" return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ch) & 0xff] def __init__(self, pwd): if _ZipDecrypter.crctable is None: _ZipDecrypter.crctable = _ZipDecrypter._GenerateCRCTable() self.key0 = 305419896 self.key1 = 591751049 self.key2 = 878082192 for p in pwd: self._UpdateKeys(p) def _UpdateKeys(self, c): self.key0 = self._crc32(c, self.key0) self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295 self.key1 = (self.key1 * 134775813 + 1) & 4294967295 self.key2 = self._crc32((self.key1 >> 24) & 255, self.key2) def __call__(self, c): """Decrypt a single character.""" assert isinstance(c, int) k = self.key2 | 2 c = c ^ (((k * (k^1)) >> 8) & 255) self._UpdateKeys(c) return c class LZMACompressor: def __init__(self): self._comp = None def _init(self): props = lzma._encode_filter_properties({'id': lzma.FILTER_LZMA1}) self._comp = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[ lzma._decode_filter_properties(lzma.FILTER_LZMA1, props) ]) return struct.pack('<BBH', 9, 4, len(props)) + props def compress(self, data): if self._comp is None: return self._init() + self._comp.compress(data) return self._comp.compress(data) def flush(self): if self._comp is None: return self._init() + self._comp.flush() return self._comp.flush() class LZMADecompressor: def __init__(self): self._decomp = None self._unconsumed = b'' self.eof = False def decompress(self, data): if self._decomp is None: self._unconsumed += data if len(self._unconsumed) <= 4: return b'' psize, = struct.unpack('<H', self._unconsumed[2:4]) if len(self._unconsumed) <= 4 + psize: return b'' self._decomp = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[ lzma._decode_filter_properties(lzma.FILTER_LZMA1, self._unconsumed[4:4 + psize]) ]) data = self._unconsumed[4 + psize:] del self._unconsumed result = self._decomp.decompress(data) self.eof = self._decomp.eof return result compressor_names = { 0: 'store', 1: 'shrink', 2: 'reduce', 3: 'reduce', 4: 'reduce', 5: 'reduce', 6: 'implode', 7: 'tokenize', 8: 'deflate', 9: 'deflate64', 10: 'implode', 12: 'bzip2', 14: 'lzma', 18: 'terse', 19: 'lz77', 97: 'wavpack', 98: 'ppmd', } def _check_compression(compression): if compression == ZIP_STORED: pass elif compression == ZIP_DEFLATED: if not zlib: raise RuntimeError( "Compression requires the (missing) zlib module") elif compression == ZIP_BZIP2: if not bz2: raise RuntimeError( "Compression requires the (missing) bz2 module") elif compression == ZIP_LZMA: if not lzma: raise RuntimeError( "Compression requires the (missing) lzma module") else: raise NotImplementedError("That compression method is not supported") def _get_compressor(compress_type): if compress_type == ZIP_DEFLATED: return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) elif compress_type == ZIP_BZIP2: return bz2.BZ2Compressor() elif compress_type == ZIP_LZMA: return LZMACompressor() else: return None def _get_decompressor(compress_type): if compress_type == ZIP_STORED: return None elif compress_type == ZIP_DEFLATED: return zlib.decompressobj(-15) elif compress_type == ZIP_BZIP2: return bz2.BZ2Decompressor() elif compress_type == ZIP_LZMA: return LZMADecompressor() else: descr = compressor_names.get(compress_type) if descr: raise NotImplementedError("compression type %d (%s)" % (compress_type, descr)) else: raise NotImplementedError("compression type %d" % (compress_type,)) class _SharedFile: def __init__(self, file, pos, close, lock, writing): self._file = file self._pos = pos self._close = close self._lock = lock self._writing = writing def read(self, n=-1): with self._lock: if self._writing(): raise ValueError("Can't read from the ZIP file while there " "is an open writing handle on it. " "Close the writing handle before trying to read.") self._file.seek(self._pos) data = self._file.read(n) self._pos = self._file.tell() return data def close(self): if self._file is not None: fileobj = self._file self._file = None self._close(fileobj) # Provide the tell method for unseekable stream class _Tellable: def __init__(self, fp): self.fp = fp self.offset = 0 def write(self, data): n = self.fp.write(data) self.offset += n return n def tell(self): return self.offset def flush(self): self.fp.flush() def close(self): self.fp.close() class ZipExtFile(io.BufferedIOBase): """File-like object for reading an archive member. Is returned by ZipFile.open(). """ # Max size supported by decompressor. MAX_N = 1 << 31 - 1 # Read from compressed files in 4k blocks. MIN_READ_SIZE = 4096 def __init__(self, fileobj, mode, zipinfo, decrypter=None, close_fileobj=False): self._fileobj = fileobj self._decrypter = decrypter self._close_fileobj = close_fileobj self._compress_type = zipinfo.compress_type self._compress_left = zipinfo.compress_size self._left = zipinfo.file_size self._decompressor = _get_decompressor(self._compress_type) self._eof = False self._readbuffer = b'' self._offset = 0 self.newlines = None # Adjust read size for encrypted files since the first 12 bytes # are for the encryption/password information. if self._decrypter is not None: self._compress_left -= 12 self.mode = mode self.name = zipinfo.filename if hasattr(zipinfo, 'CRC'): self._expected_crc = zipinfo.CRC self._running_crc = crc32(b'') else: self._expected_crc = None def __repr__(self): result = ['<%s.%s' % (self.__class__.__module__, self.__class__.__qualname__)] if not self.closed: result.append(' name=%r mode=%r' % (self.name, self.mode)) if self._compress_type != ZIP_STORED: result.append(' compress_type=%s' % compressor_names.get(self._compress_type, self._compress_type)) else: result.append(' [closed]') result.append('>') return ''.join(result) def readline(self, limit=-1): """Read and return a line from the stream. If limit is specified, at most limit bytes will be read. """ if limit < 0: # Shortcut common case - newline found in buffer. i = self._readbuffer.find(b'\n', self._offset) + 1 if i > 0: line = self._readbuffer[self._offset: i] self._offset = i return line return io.BufferedIOBase.readline(self, limit) def peek(self, n=1): """Returns buffered bytes without advancing the position.""" if n > len(self._readbuffer) - self._offset: chunk = self.read(n) if len(chunk) > self._offset: self._readbuffer = chunk + self._readbuffer[self._offset:] self._offset = 0 else: self._offset -= len(chunk) # Return up to 512 bytes to reduce allocation overhead for tight loops. return self._readbuffer[self._offset: self._offset + 512] def readable(self): return True def read(self, n=-1): """Read and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached.. """ if n is None or n < 0: buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while not self._eof: buf += self._read1(self.MAX_N) return buf end = n + self._offset if end < len(self._readbuffer): buf = self._readbuffer[self._offset:end] self._offset = end return buf n = end - len(self._readbuffer) buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while n > 0 and not self._eof: data = self._read1(n) if n < len(data): self._readbuffer = data self._offset = n buf += data[:n] break buf += data n -= len(data) return buf def _update_crc(self, newdata): # Update the CRC using the given data. if self._expected_crc is None: # No need to compute the CRC if we don't have a reference value return self._running_crc = crc32(newdata, self._running_crc) # Check the CRC if we're at the end of the file if self._eof and self._running_crc != self._expected_crc: raise BadZipFile("Bad CRC-32 for file %r" % self.name) def read1(self, n): """Read up to n bytes with at most one read() system call.""" if n is None or n < 0: buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while not self._eof: data = self._read1(self.MAX_N) if data: buf += data break return buf end = n + self._offset if end < len(self._readbuffer): buf = self._readbuffer[self._offset:end] self._offset = end return buf n = end - len(self._readbuffer) buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 if n > 0: while not self._eof: data = self._read1(n) if n < len(data): self._readbuffer = data self._offset = n buf += data[:n] break if data: buf += data break return buf def _read1(self, n): # Read up to n compressed bytes with at most one read() system call, # decrypt and decompress them. if self._eof or n <= 0: return b'' # Read from file. if self._compress_type == ZIP_DEFLATED: ## Handle unconsumed data. data = self._decompressor.unconsumed_tail if n > len(data): data += self._read2(n - len(data)) else: data = self._read2(n) if self._compress_type == ZIP_STORED: self._eof = self._compress_left <= 0 elif self._compress_type == ZIP_DEFLATED: n = max(n, self.MIN_READ_SIZE) data = self._decompressor.decompress(data, n) self._eof = (self._decompressor.eof or self._compress_left <= 0 and not self._decompressor.unconsumed_tail) if self._eof: data += self._decompressor.flush() else: data = self._decompressor.decompress(data) self._eof = self._decompressor.eof or self._compress_left <= 0 data = data[:self._left] self._left -= len(data) if self._left <= 0: self._eof = True self._update_crc(data) return data def _read2(self, n): if self._compress_left <= 0: return b'' n = max(n, self.MIN_READ_SIZE) n = min(n, self._compress_left) data = self._fileobj.read(n) self._compress_left -= len(data) if not data: raise EOFError if self._decrypter is not None: data = bytes(map(self._decrypter, data)) return data def close(self): try: if self._close_fileobj: self._fileobj.close() finally: super().close() class _ZipWriteFile(io.BufferedIOBase): def __init__(self, zf, zinfo, zip64): self._zinfo = zinfo self._zip64 = zip64 self._zipfile = zf self._compressor = _get_compressor(zinfo.compress_type) self._file_size = 0 self._compress_size = 0 self._crc = 0 @property def _fileobj(self): return self._zipfile.fp def writable(self): return True def write(self, data): if self.closed: raise ValueError('I/O operation on closed file.') nbytes = len(data) self._file_size += nbytes self._crc = crc32(data, self._crc) if self._compressor: data = self._compressor.compress(data) self._compress_size += len(data) self._fileobj.write(data) return nbytes def close(self): if self.closed: return super().close() # Flush any data from the compressor, and update header info if self._compressor: buf = self._compressor.flush() self._compress_size += len(buf) self._fileobj.write(buf) self._zinfo.compress_size = self._compress_size else: self._zinfo.compress_size = self._file_size self._zinfo.CRC = self._crc self._zinfo.file_size = self._file_size # Write updated header info if self._zinfo.flag_bits & 0x08: # Write CRC and file sizes after the file data fmt = '<LLQQ' if self._zip64 else '<LLLL' self._fileobj.write(struct.pack(fmt, _DD_SIGNATURE, self._zinfo.CRC, self._zinfo.compress_size, self._zinfo.file_size)) self._zipfile.start_dir = self._fileobj.tell() else: if not self._zip64: if self._file_size > ZIP64_LIMIT: raise RuntimeError('File size unexpectedly exceeded ZIP64 ' 'limit') if self._compress_size > ZIP64_LIMIT: raise RuntimeError('Compressed size unexpectedly exceeded ' 'ZIP64 limit') # Seek backwards and write file header (which will now include # correct CRC and file sizes) # Preserve current position in file self._zipfile.start_dir = self._fileobj.tell() self._fileobj.seek(self._zinfo.header_offset) self._fileobj.write(self._zinfo.FileHeader(self._zip64)) self._fileobj.seek(self._zipfile.start_dir) self._zipfile._writing = False # Successfully written: Add file to our caches self._zipfile.filelist.append(self._zinfo) self._zipfile.NameToInfo[self._zinfo.filename] = self._zinfo class ZipFile: """ Class with methods to open, read, write, close, list zip files. z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True) file: Either the path to the file, or a file-like object. If it is a path, the file will be opened and closed by ZipFile. mode: The mode can be either read 'r', write 'w', exclusive create 'x', or append 'a'. compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib), ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma). allowZip64: if True ZipFile will create files with ZIP64 extensions when needed, otherwise it will raise an exception when this would be necessary. """ fp = None # Set here since __del__ checks it _windows_illegal_name_trans_table = None def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True): """Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', or append 'a'.""" if mode not in ('r', 'w', 'x', 'a'): raise ValueError("ZipFile requires mode 'r', 'w', 'x', or 'a'") _check_compression(compression) self._allowZip64 = allowZip64 self._didModify = False self.debug = 0 # Level of printing: 0 through 3 self.NameToInfo = {} # Find file info given name self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.mode = mode self.pwd = None self._comment = b'' # Check if we were passed a file-like object if isinstance(file, os.PathLike): file = os.fspath(file) if isinstance(file, str): # No, it's a filename self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'w+b', 'x': 'x+b', 'a' : 'r+b', 'r+b': 'w+b', 'w+b': 'wb', 'x+b': 'xb'} filemode = modeDict[mode] while True: try: self.fp = io.open(file, filemode) except OSError: if filemode in modeDict: filemode = modeDict[filemode] continue raise break else: self._filePassed = 1 self.fp = file self.filename = getattr(file, 'name', None) self._fileRefCnt = 1 self._lock = threading.RLock() self._seekable = True self._writing = False try: if mode == 'r': self._RealGetContents() elif mode in ('w', 'x'): # set the modified flag so central directory gets written # even if no files are added to the archive self._didModify = True try: self.start_dir = self.fp.tell() except (AttributeError, OSError): self.fp = _Tellable(self.fp) self.start_dir = 0 self._seekable = False else: # Some file-like objects can provide tell() but not seek() try: self.fp.seek(self.start_dir) except (AttributeError, OSError): self._seekable = False elif mode == 'a': try: # See if file is a zip file self._RealGetContents() # seek to start of directory and overwrite self.fp.seek(self.start_dir) except BadZipFile: # file is not a zip file, just append self.fp.seek(0, 2) # set the modified flag so central directory gets written # even if no files are added to the archive self._didModify = True self.start_dir = self.fp.tell() else: raise ValueError("Mode must be 'r', 'w', 'x', or 'a'") except: fp = self.fp self.fp = None self._fpclose(fp) raise def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def __repr__(self): result = ['<%s.%s' % (self.__class__.__module__, self.__class__.__qualname__)] if self.fp is not None: if self._filePassed: result.append(' file=%r' % self.fp) elif self.filename is not None: result.append(' filename=%r' % self.filename) result.append(' mode=%r' % self.mode) else: result.append(' [closed]') result.append('>') return ''.join(result) def _RealGetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp try: endrec = _EndRecData(fp) except OSError: raise BadZipFile("File is not a zip file") if not endrec: raise BadZipFile("File is not a zip file") if self.debug > 1: print(endrec) size_cd = endrec[_ECD_SIZE] # bytes in central directory offset_cd = endrec[_ECD_OFFSET] # offset of central directory self._comment = endrec[_ECD_COMMENT] # archive comment # "concat" is zero, unless zip was concatenated to another file concat = endrec[_ECD_LOCATION] - size_cd - offset_cd if endrec[_ECD_SIGNATURE] == stringEndArchive64: # If Zip64 extension structures are present, account for them concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator) if self.debug > 2: inferred = concat + offset_cd print("given, inferred, offset", offset_cd, inferred, concat) # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) data = fp.read(size_cd) fp = io.BytesIO(data) total = 0 while total < size_cd: centdir = fp.read(sizeCentralDir) if len(centdir) != sizeCentralDir: raise BadZipFile("Truncated central directory") centdir = struct.unpack(structCentralDir, centdir) if centdir[_CD_SIGNATURE] != stringCentralDir: raise BadZipFile("Bad magic number for central directory") if self.debug > 2: print(centdir) filename = fp.read(centdir[_CD_FILENAME_LENGTH]) flags = centdir[5] if flags & 0x800: # UTF-8 file names extension filename = filename.decode('utf-8') else: # Historical ZIP filename encoding filename = filename.decode('cp437') # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH]) x.comment = fp.read(centdir[_CD_COMMENT_LENGTH]) x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] if x.extract_version > MAX_EXTRACT_VERSION: raise NotImplementedError("zip file version %.1f" % (x.extract_version / 10)) x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x._raw_time = t x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) x._decodeExtra() x.header_offset = x.header_offset + concat self.filelist.append(x) self.NameToInfo[x.filename] = x # update total bytes read from central directory total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH] + centdir[_CD_EXTRA_FIELD_LENGTH] + centdir[_CD_COMMENT_LENGTH]) if self.debug > 2: print("total", total) def namelist(self): """Return a list of file names in the archive.""" return [data.filename for data in self.filelist] def infolist(self): """Return a list of class ZipInfo instances for files in the archive.""" return self.filelist def printdir(self, file=None): """Print a table of contents for the zip file.""" print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"), file=file) for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6] print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size), file=file) def testzip(self): """Read all the files and check the CRC.""" chunk_size = 2 ** 20 for zinfo in self.filelist: try: # Read by chunks, to avoid an OverflowError or a # MemoryError with very large embedded files. with self.open(zinfo.filename, "r") as f: while f.read(chunk_size): # Check CRC-32 pass except BadZipFile: return zinfo.filename def getinfo(self, name): """Return the instance of ZipInfo given 'name'.""" info = self.NameToInfo.get(name) if info is None: raise KeyError( 'There is no item named %r in the archive' % name) return info def setpassword(self, pwd): """Set default password for encrypted files.""" if pwd and not isinstance(pwd, bytes): raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__) if pwd: self.pwd = pwd else: self.pwd = None @property def comment(self): """The comment text associated with the ZIP file.""" return self._comment @comment.setter def comment(self, comment): if not isinstance(comment, bytes): raise TypeError("comment: expected bytes, got %s" % type(comment).__name__) # check for valid comment length if len(comment) > ZIP_MAX_COMMENT: import warnings warnings.warn('Archive comment is too long; truncating to %d bytes' % ZIP_MAX_COMMENT, stacklevel=2) comment = comment[:ZIP_MAX_COMMENT] self._comment = comment self._didModify = True def read(self, name, pwd=None): """Return file bytes for name.""" with self.open(name, "r", pwd) as fp: return fp.read() def open(self, name, mode="r", pwd=None, *, force_zip64=False): """Return file-like object for 'name'. name is a string for the file name within the ZIP file, or a ZipInfo object. mode should be 'r' to read a file already in the ZIP file, or 'w' to write to a file newly added to the archive. pwd is the password to decrypt files (only used for reading). When writing, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large files. If the size is known in advance, it is best to pass a ZipInfo instance for name, with zinfo.file_size set. """ if mode not in {"r", "w"}: raise ValueError('open() requires mode "r" or "w"') if pwd and not isinstance(pwd, bytes): raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__) if pwd and (mode == "w"): raise ValueError("pwd is only supported for reading files") if not self.fp: raise ValueError( "Attempt to use ZIP archive that was already closed") # Make sure we have an info object if isinstance(name, ZipInfo): # 'name' is already an info object zinfo = name elif mode == 'w': zinfo = ZipInfo(name) zinfo.compress_type = self.compression else: # Get info object for name zinfo = self.getinfo(name) if mode == 'w': return self._open_to_write(zinfo, force_zip64=force_zip64) if self._writing: raise ValueError("Can't read from the ZIP file while there " "is an open writing handle on it. " "Close the writing handle before trying to read.") # Open for reading: self._fileRefCnt += 1 zef_file = _SharedFile(self.fp, zinfo.header_offset, self._fpclose, self._lock, lambda: self._writing) try: # Skip the file header: fheader = zef_file.read(sizeFileHeader) if len(fheader) != sizeFileHeader: raise BadZipFile("Truncated file header") fheader = struct.unpack(structFileHeader, fheader) if fheader[_FH_SIGNATURE] != stringFileHeader: raise BadZipFile("Bad magic number for file header") fname = zef_file.read(fheader[_FH_FILENAME_LENGTH]) if fheader[_FH_EXTRA_FIELD_LENGTH]: zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH]) if zinfo.flag_bits & 0x20: # Zip 2.7: compressed patched data raise NotImplementedError("compressed patched data (flag bit 5)") if zinfo.flag_bits & 0x40: # strong encryption raise NotImplementedError("strong encryption (flag bit 6)") if zinfo.flag_bits & 0x800: # UTF-8 filename fname_str = fname.decode("utf-8") else: fname_str = fname.decode("cp437") if fname_str != zinfo.orig_filename: raise BadZipFile( 'File name in directory %r and header %r differ.' % (zinfo.orig_filename, fname)) # check for encrypted flag & handle password is_encrypted = zinfo.flag_bits & 0x1 zd = None if is_encrypted: if not pwd: pwd = self.pwd if not pwd: raise RuntimeError("File %r is encrypted, password " "required for extraction" % name) zd = _ZipDecrypter(pwd) # The first 12 bytes in the cypher stream is an encryption header # used to strengthen the algorithm. The first 11 bytes are # completely random, while the 12th contains the MSB of the CRC, # or the MSB of the file time depending on the header type # and is used to check the correctness of the password. header = zef_file.read(12) h = list(map(zd, header[0:12])) if zinfo.flag_bits & 0x8: # compare against the file type from extended local headers check_byte = (zinfo._raw_time >> 8) & 0xff else: # compare against the CRC otherwise check_byte = (zinfo.CRC >> 24) & 0xff if h[11] != check_byte: raise RuntimeError("Bad password for file %r" % name) return ZipExtFile(zef_file, mode, zinfo, zd, True) except: zef_file.close() raise def _open_to_write(self, zinfo, force_zip64=False): if force_zip64 and not self._allowZip64: raise ValueError( "force_zip64 is True, but allowZip64 was False when opening " "the ZIP file." ) if self._writing: raise ValueError("Can't write to the ZIP file while there is " "another write handle open on it. " "Close the first handle before opening another.") # Sizes and CRC are overwritten with correct data after processing the file if not hasattr(zinfo, 'file_size'): zinfo.file_size = 0 zinfo.compress_size = 0 zinfo.CRC = 0 zinfo.flag_bits = 0x00 if zinfo.compress_type == ZIP_LZMA: # Compressed data includes an end-of-stream (EOS) marker zinfo.flag_bits |= 0x02 if not self._seekable: zinfo.flag_bits |= 0x08 if not zinfo.external_attr: zinfo.external_attr = 0o600 << 16 # permissions: ?rw------- # Compressed size can be larger than uncompressed size zip64 = self._allowZip64 and \ (force_zip64 or zinfo.file_size * 1.05 > ZIP64_LIMIT) if self._seekable: self.fp.seek(self.start_dir) zinfo.header_offset = self.fp.tell() self._writecheck(zinfo) self._didModify = True self.fp.write(zinfo.FileHeader(zip64)) self._writing = True return _ZipWriteFile(self, zinfo, zip64) def extract(self, member, path=None, pwd=None): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a ZipInfo object. You can specify a different directory using `path'. """ if path is None: path = os.getcwd() else: path = os.fspath(path) return self._extract_member(member, path, pwd) def extractall(self, path=None, members=None, pwd=None): """Extract all members from the archive to the current working directory. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by namelist(). """ if members is None: members = self.namelist() if path is None: path = os.getcwd() else: path = os.fspath(path) for zipinfo in members: self._extract_member(zipinfo, path, pwd) @classmethod def _sanitize_windows_name(cls, arcname, pathsep): """Replace bad characters and remove trailing dots from parts.""" table = cls._windows_illegal_name_trans_table if not table: illegal = ':<>|"?*' table = str.maketrans(illegal, '_' * len(illegal)) cls._windows_illegal_name_trans_table = table arcname = arcname.translate(table) # remove trailing dots arcname = (x.rstrip('.') for x in arcname.split(pathsep)) # rejoin, removing empty parts. arcname = pathsep.join(x for x in arcname if x) return arcname def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ if not isinstance(member, ZipInfo): member = self.getinfo(member) # build the destination pathname, replacing # forward slashes to platform specific separators. arcname = member.filename.replace('/', os.path.sep) if os.path.altsep: arcname = arcname.replace(os.path.altsep, os.path.sep) # interpret absolute pathname as relative, remove drive letter or # UNC path, redundant separators, "." and ".." components. arcname = os.path.splitdrive(arcname)[1] invalid_path_parts = ('', os.path.curdir, os.path.pardir) arcname = os.path.sep.join(x for x in arcname.split(os.path.sep) if x not in invalid_path_parts) if os.path.sep == '\\': # filter illegal characters on Windows arcname = self._sanitize_windows_name(arcname, os.path.sep) targetpath = os.path.join(targetpath, arcname) targetpath = os.path.normpath(targetpath) # Create all upper directories if necessary. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): os.makedirs(upperdirs) if member.is_dir(): if not os.path.isdir(targetpath): os.mkdir(targetpath) return targetpath with self.open(member, pwd=pwd) as source, \ open(targetpath, "wb") as target: shutil.copyfileobj(source, target) return targetpath def _writecheck(self, zinfo): """Check for errors before writing a file to the archive.""" if zinfo.filename in self.NameToInfo: import warnings warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3) if self.mode not in ('w', 'x', 'a'): raise ValueError("write() requires mode 'w', 'x', or 'a'") if not self.fp: raise ValueError( "Attempt to write ZIP archive that was already closed") _check_compression(zinfo.compress_type) if not self._allowZip64: requires_zip64 = None if len(self.filelist) >= ZIP_FILECOUNT_LIMIT: requires_zip64 = "Files count" elif zinfo.file_size > ZIP64_LIMIT: requires_zip64 = "Filesize" elif zinfo.header_offset > ZIP64_LIMIT: requires_zip64 = "Zipfile size" if requires_zip64: raise LargeZipFile(requires_zip64 + " would require ZIP64 extensions") def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" if not self.fp: raise ValueError( "Attempt to write to ZIP archive that was already closed") if self._writing: raise ValueError( "Can't write to ZIP archive while an open writing handle exists" ) zinfo = ZipInfo.from_file(filename, arcname) if zinfo.is_dir(): zinfo.compress_size = 0 zinfo.CRC = 0 else: if compress_type is not None: zinfo.compress_type = compress_type else: zinfo.compress_type = self.compression if zinfo.is_dir(): with self._lock: if self._seekable: self.fp.seek(self.start_dir) zinfo.header_offset = self.fp.tell() # Start of header bytes if zinfo.compress_type == ZIP_LZMA: # Compressed data includes an end-of-stream (EOS) marker zinfo.flag_bits |= 0x02 self._writecheck(zinfo) self._didModify = True self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo self.fp.write(zinfo.FileHeader(False)) self.start_dir = self.fp.tell() else: with open(filename, "rb") as src, self.open(zinfo, 'w') as dest: shutil.copyfileobj(src, dest, 1024*8) def writestr(self, zinfo_or_arcname, data, compress_type=None): """Write a file into the archive. The contents is 'data', which may be either a 'str' or a 'bytes' instance; if it is a 'str', it is encoded as UTF-8 first. 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive.""" if isinstance(data, str): data = data.encode("utf-8") if not isinstance(zinfo_or_arcname, ZipInfo): zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())[:6]) zinfo.compress_type = self.compression if zinfo.filename[-1] == '/': zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x zinfo.external_attr |= 0x10 # MS-DOS directory flag else: zinfo.external_attr = 0o600 << 16 # ?rw------- else: zinfo = zinfo_or_arcname if not self.fp: raise ValueError( "Attempt to write to ZIP archive that was already closed") if self._writing: raise ValueError( "Can't write to ZIP archive while an open writing handle exists." ) if compress_type is not None: zinfo.compress_type = compress_type zinfo.file_size = len(data) # Uncompressed size with self._lock: with self.open(zinfo, mode='w') as dest: dest.write(data) def __del__(self): """Call the "close()" method in case the user forgot.""" self.close() def close(self): """Close the file, and for mode 'w', 'x' and 'a' write the ending records.""" if self.fp is None: return if self._writing: raise ValueError("Can't close the ZIP file while there is " "an open writing handle on it. " "Close the writing handle before closing the zip.") try: if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records with self._lock: if self._seekable: self.fp.seek(self.start_dir) self._write_end_record() finally: fp = self.fp self.fp = None self._fpclose(fp) def _write_end_record(self): for zinfo in self.filelist: # write central directory dt = zinfo.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) extra = [] if zinfo.file_size > ZIP64_LIMIT \ or zinfo.compress_size > ZIP64_LIMIT: extra.append(zinfo.file_size) extra.append(zinfo.compress_size) file_size = 0xffffffff compress_size = 0xffffffff else: file_size = zinfo.file_size compress_size = zinfo.compress_size if zinfo.header_offset > ZIP64_LIMIT: extra.append(zinfo.header_offset) header_offset = 0xffffffff else: header_offset = zinfo.header_offset extra_data = zinfo.extra min_version = 0 if extra: # Append a ZIP64 field to the extra's extra_data = _strip_extra(extra_data, (1,)) extra_data = struct.pack( '<HH' + 'Q'*len(extra), 1, 8*len(extra), *extra) + extra_data min_version = ZIP64_VERSION if zinfo.compress_type == ZIP_BZIP2: min_version = max(BZIP2_VERSION, min_version) elif zinfo.compress_type == ZIP_LZMA: min_version = max(LZMA_VERSION, min_version) extract_version = max(min_version, zinfo.extract_version) create_version = max(min_version, zinfo.create_version) try: filename, flag_bits = zinfo._encodeFilenameFlags() centdir = struct.pack(structCentralDir, stringCentralDir, create_version, zinfo.create_system, extract_version, zinfo.reserved, flag_bits, zinfo.compress_type, dostime, dosdate, zinfo.CRC, compress_size, file_size, len(filename), len(extra_data), len(zinfo.comment), 0, zinfo.internal_attr, zinfo.external_attr, header_offset) except DeprecationWarning: print((structCentralDir, stringCentralDir, create_version, zinfo.create_system, extract_version, zinfo.reserved, zinfo.flag_bits, zinfo.compress_type, dostime, dosdate, zinfo.CRC, compress_size, file_size, len(zinfo.filename), len(extra_data), len(zinfo.comment), 0, zinfo.internal_attr, zinfo.external_attr, header_offset), file=sys.stderr) raise self.fp.write(centdir) self.fp.write(filename) self.fp.write(extra_data) self.fp.write(zinfo.comment) pos2 = self.fp.tell() # Write end-of-zip-archive record centDirCount = len(self.filelist) centDirSize = pos2 - self.start_dir centDirOffset = self.start_dir requires_zip64 = None if centDirCount > ZIP_FILECOUNT_LIMIT: requires_zip64 = "Files count" elif centDirOffset > ZIP64_LIMIT: requires_zip64 = "Central directory offset" elif centDirSize > ZIP64_LIMIT: requires_zip64 = "Central directory size" if requires_zip64: # Need to write the ZIP64 end-of-archive records if not self._allowZip64: raise LargeZipFile(requires_zip64 + " would require ZIP64 extensions") zip64endrec = struct.pack( structEndArchive64, stringEndArchive64, 44, 45, 45, 0, 0, centDirCount, centDirCount, centDirSize, centDirOffset) self.fp.write(zip64endrec) zip64locrec = struct.pack( structEndArchive64Locator, stringEndArchive64Locator, 0, pos2, 1) self.fp.write(zip64locrec) centDirCount = min(centDirCount, 0xFFFF) centDirSize = min(centDirSize, 0xFFFFFFFF) centDirOffset = min(centDirOffset, 0xFFFFFFFF) endrec = struct.pack(structEndArchive, stringEndArchive, 0, 0, centDirCount, centDirCount, centDirSize, centDirOffset, len(self._comment)) self.fp.write(endrec) self.fp.write(self._comment) self.fp.flush() def _fpclose(self, fp): assert self._fileRefCnt > 0 self._fileRefCnt -= 1 if not self._fileRefCnt and not self._filePassed: fp.close() class PyZipFile(ZipFile): """Class to create ZIP archives with Python library files and packages.""" def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True, optimize=-1): ZipFile.__init__(self, file, mode=mode, compression=compression, allowZip64=allowZip64) self._optimize = optimize def writepy(self, pathname, basename="", filterfunc=None): """Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyc. This method will compile the module.py into module.pyc if necessary. If filterfunc(pathname) is given, it is called with every argument. When it is False, the file or directory is skipped. """ pathname = os.fspath(pathname) if filterfunc and not filterfunc(pathname): if self.debug: label = 'path' if os.path.isdir(pathname) else 'file' print('%s %r skipped by filterfunc' % (label, pathname)) return dir, name = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, "__init__.py") if os.path.isfile(initname): # This is a package directory, add it if basename: basename = "%s/%s" % (basename, name) else: basename = name if self.debug: print("Adding package in", pathname, "as", basename) fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories for filename in dirlist: path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if os.path.isdir(path): if os.path.isfile(os.path.join(path, "__init__.py")): # This is a package directory, add it self.writepy(path, basename, filterfunc=filterfunc) # Recursive call elif ext == ".py": if filterfunc and not filterfunc(path): if self.debug: print('file %r skipped by filterfunc' % path) continue fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: print("Adding files from directory", pathname) for filename in os.listdir(pathname): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if ext == ".py": if filterfunc and not filterfunc(path): if self.debug: print('file %r skipped by filterfunc' % path) continue fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) else: if pathname[-3:] != ".py": raise RuntimeError( 'Files added with writepy() must end with ".py"') fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: print("Adding file", arcname) self.write(fname, arcname) def _get_codename(self, pathname, basename): """Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). """ def _compile(file, optimize=-1): import py_compile if self.debug: print("Compiling", file) try: py_compile.compile(file, doraise=True, optimize=optimize) except py_compile.PyCompileError as err: print(err.msg) return False return True file_py = pathname + ".py" file_pyc = pathname + ".pyc" pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='') pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1) pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2) if self._optimize == -1: # legacy mode: use whatever file is present if (os.path.isfile(file_pyc) and os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime): # Use .pyc file. arcname = fname = file_pyc elif (os.path.isfile(pycache_opt0) and os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt0 arcname = file_pyc elif (os.path.isfile(pycache_opt1) and os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt1 arcname = file_pyc elif (os.path.isfile(pycache_opt2) and os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt2 arcname = file_pyc else: # Compile py into PEP 3147 pyc file. if _compile(file_py): if sys.flags.optimize == 0: fname = pycache_opt0 elif sys.flags.optimize == 1: fname = pycache_opt1 else: fname = pycache_opt2 arcname = file_pyc else: fname = arcname = file_py else: # new mode: use given optimization level if self._optimize == 0: fname = pycache_opt0 arcname = file_pyc else: arcname = file_pyc if self._optimize == 1: fname = pycache_opt1 elif self._optimize == 2: fname = pycache_opt2 else: msg = "invalid value for 'optimize': {!r}".format(self._optimize) raise ValueError(msg) if not (os.path.isfile(fname) and os.stat(fname).st_mtime >= os.stat(file_py).st_mtime): if not _compile(file_py, optimize=self._optimize): fname = arcname = file_py archivename = os.path.split(arcname)[1] if basename: archivename = "%s/%s" % (basename, archivename) return (fname, archivename) def main(args = None): import textwrap USAGE=textwrap.dedent("""\ Usage: zipfile.py -l zipfile.zip # Show listing of a zipfile zipfile.py -t zipfile.zip # Test if a zipfile is valid zipfile.py -e zipfile.zip target # Extract zipfile into target dir zipfile.py -c zipfile.zip src ... # Create zipfile from sources """) if args is None: args = sys.argv[1:] if not args or args[0] not in ('-l', '-c', '-e', '-t'): print(USAGE) sys.exit(1) if args[0] == '-l': if len(args) != 2: print(USAGE) sys.exit(1) with ZipFile(args[1], 'r') as zf: zf.printdir() elif args[0] == '-t': if len(args) != 2: print(USAGE) sys.exit(1) with ZipFile(args[1], 'r') as zf: badfile = zf.testzip() if badfile: print("The following enclosed file is corrupted: {!r}".format(badfile)) print("Done testing") elif args[0] == '-e': if len(args) != 3: print(USAGE) sys.exit(1) with ZipFile(args[1], 'r') as zf: zf.extractall(args[2]) elif args[0] == '-c': if len(args) < 3: print(USAGE) sys.exit(1) def addToZip(zf, path, zippath): if os.path.isfile(path): zf.write(path, zippath, ZIP_DEFLATED) elif os.path.isdir(path): if zippath: zf.write(path, zippath) for nm in os.listdir(path): addToZip(zf, os.path.join(path, nm), os.path.join(zippath, nm)) # else: ignore with ZipFile(args[1], 'w') as zf: for path in args[2:]: zippath = os.path.basename(path) if not zippath: zippath = os.path.basename(os.path.dirname(path)) if zippath in ('', os.curdir, os.pardir): zippath = '' addToZip(zf, path, zippath) if __name__ == "__main__": main()
76,282
2,061
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/_dummy_thread.py
"""Drop-in replacement for the thread module. Meant to be used as a brain-dead substitute so that threaded code does not need to be rewritten for when the thread module is not present. Suggested usage is:: try: import _thread except ImportError: import _dummy_thread as _thread """ # Exports only things specified by thread documentation; # skipping obsolete synonyms allocate(), start_new(), exit_thread(). __all__ = [ "error", "start_new_thread", "exit", "get_ident", "allocate_lock", "interrupt_main", "LockType", ] # A dummy value TIMEOUT_MAX = 2 ** 31 # NOTE: this module can be imported early in the extension building process, # and so top level imports of other modules should be avoided. Instead, all # imports are done when needed on a function-by-function basis. Since threads # are disabled, the import lock should not be an issue anyway (??). error = RuntimeError def start_new_thread(function, args, kwargs={}): """Dummy implementation of _thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by _thread.exit()) it is caught and nothing is done; all other exceptions are printed out by using traceback.print_exc(). If the executed function calls interrupt_main the KeyboardInterrupt will be raised when the function returns. """ if type(args) != type(tuple()): raise TypeError("2nd arg must be a tuple") if type(kwargs) != type(dict()): raise TypeError("3rd arg must be a dict") global _main _main = False try: function(*args, **kwargs) except SystemExit: pass except: import traceback traceback.print_exc() _main = True global _interrupt if _interrupt: _interrupt = False raise KeyboardInterrupt def exit(): """Dummy implementation of _thread.exit().""" raise SystemExit def get_ident(): """Dummy implementation of _thread.get_ident(). Since this module should only be used when _threadmodule is not available, it is safe to assume that the current process is the only thread. Thus a constant can be safely returned. """ return -1 def allocate_lock(*args, **kwargs): """Dummy implementation of _thread.allocate_lock().""" return LockType() def stack_size(size=None): """Dummy implementation of _thread.stack_size().""" if size is not None: raise error("setting thread stack size not supported") return 0 def _set_sentinel(): """Dummy implementation of _thread._set_sentinel().""" return LockType() class LockType(object): """Class implementing dummy implementation of _thread.LockType. Compatibility is maintained by maintaining self.locked_status which is a boolean that stores the state of the lock. Pickling of the lock, though, should not be done since if the _thread module is then used with an unpickled ``lock()`` from here problems could occur from this class not having atomic methods. """ def __init__(self): self.locked_status = False def acquire(self, waitflag=None, timeout=-1): """Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is already acquired. This is all done so that threading.Condition's assert statements aren't triggered and throw a little fit. """ if waitflag is None or waitflag: self.locked_status = True return True else: if not self.locked_status: self.locked_status = True return True else: if timeout > 0: import time time.sleep(timeout) return False __enter__ = acquire def __exit__(self, typ, val, tb): self.release() def release(self): """Release the dummy lock.""" # XXX Perhaps shouldn't actually bother to test? Could lead # to problems for complex, threaded code. if not self.locked_status: raise error self.locked_status = False return True def locked(self): return self.locked_status def __repr__(self): return "<%s %s.%s object at %s>" % ( "locked" if self.locked_status else "unlocked", self.__class__.__module__, self.__class__.__qualname__, hex(id(self)), ) # Used to signal that interrupt_main was called in a "thread" _interrupt = False # True when not executing in a "thread" _main = True def interrupt_main(): """Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.""" if _main: raise KeyboardInterrupt else: global _interrupt _interrupt = True
5,167
182
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/doctest.py
# Module doctest. # Released to the public domain 16-Jan-2001, by Tim Peters ([email protected]). # Major enhancements and refactoring by: # Jim Fulton # Edward Loper # Provided as-is; use at your own risk; no warranty; no promises; enjoy! r"""Module doctest -- a framework for running examples in docstrings. In simplest use, end each module M to be tested with: def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test() Then running the module as a script will cause the examples in the docstrings to get executed and verified: python M.py This won't display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout (why not stderr? because stderr is a lame hack <0.2 wink>), and the final line of output is "Test failed.". Run it with the -v switch instead: python M.py -v and a detailed report of all examples tried is printed to stdout, along with assorted summaries at the end. You can force verbose mode by passing "verbose=True" to testmod, or prohibit it by passing "verbose=False". In either of those cases, sys.argv is not examined by testmod. There are a variety of other ways to run doctests, including integration with the unittest framework, and support for running non-Python text files containing doctests. There are also many ways to override parts of doctest's default behaviors. See the Library Reference Manual for details. """ __docformat__ = 'reStructuredText en' __all__ = [ # 0, Option Flags 'register_optionflag', 'DONT_ACCEPT_TRUE_FOR_1', 'DONT_ACCEPT_BLANKLINE', 'NORMALIZE_WHITESPACE', 'ELLIPSIS', 'SKIP', 'IGNORE_EXCEPTION_DETAIL', 'COMPARISON_FLAGS', 'REPORT_UDIFF', 'REPORT_CDIFF', 'REPORT_NDIFF', 'REPORT_ONLY_FIRST_FAILURE', 'REPORTING_FLAGS', 'FAIL_FAST', # 1. Utility Functions # 2. Example & DocTest 'Example', 'DocTest', # 3. Doctest Parser 'DocTestParser', # 4. Doctest Finder 'DocTestFinder', # 5. Doctest Runner 'DocTestRunner', 'OutputChecker', 'DocTestFailure', 'UnexpectedException', 'DebugRunner', # 6. Test Functions 'testmod', 'testfile', 'run_docstring_examples', # 7. Unittest Support 'DocTestSuite', 'DocFileSuite', 'set_unittest_reportflags', # 8. Debugging Support 'script_from_examples', 'testsource', 'debug_src', 'debug', ] import __future__ import argparse import difflib import inspect import linecache import os import pdb import re import sys import traceback import unittest from io import StringIO from collections import namedtuple TestResults = namedtuple('TestResults', 'failed attempted') # There are 4 basic classes: # - Example: a <source, want> pair, plus an intra-docstring line number. # - DocTest: a collection of examples, parsed from a docstring, plus # info about where the docstring came from (name, filename, lineno). # - DocTestFinder: extracts DocTests from a given object's docstring and # its contained objects' docstrings. # - DocTestRunner: runs DocTest cases, and accumulates statistics. # # So the basic picture is: # # list of: # +------+ +---------+ +-------+ # |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results| # +------+ +---------+ +-------+ # | Example | # | ... | # | Example | # +---------+ # Option constants. OPTIONFLAGS_BY_NAME = {} def register_optionflag(name): # Create a new flag unless `name` is already known. return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME)) DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1') DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE') NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE') ELLIPSIS = register_optionflag('ELLIPSIS') SKIP = register_optionflag('SKIP') IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL') COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 | DONT_ACCEPT_BLANKLINE | NORMALIZE_WHITESPACE | ELLIPSIS | SKIP | IGNORE_EXCEPTION_DETAIL) REPORT_UDIFF = register_optionflag('REPORT_UDIFF') REPORT_CDIFF = register_optionflag('REPORT_CDIFF') REPORT_NDIFF = register_optionflag('REPORT_NDIFF') REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE') FAIL_FAST = register_optionflag('FAIL_FAST') REPORTING_FLAGS = (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF | REPORT_ONLY_FIRST_FAILURE | FAIL_FAST) # Special string markers for use in `want` strings: BLANKLINE_MARKER = '<BLANKLINE>' ELLIPSIS_MARKER = '...' ###################################################################### ## Table of Contents ###################################################################### # 1. Utility Functions # 2. Example & DocTest -- store test cases # 3. DocTest Parser -- extracts examples from strings # 4. DocTest Finder -- extracts test cases from objects # 5. DocTest Runner -- runs test cases # 6. Test Functions -- convenient wrappers for testing # 7. Unittest Support # 8. Debugging Support # 9. Example Usage ###################################################################### ## 1. Utility Functions ###################################################################### def _extract_future_flags(globs): """ Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). """ flags = 0 for fname in __future__.all_feature_names: feature = globs.get(fname, None) if feature is getattr(__future__, fname): flags |= feature.compiler_flag return flags def _normalize_module(module, depth=2): """ Return the module specified by `module`. In particular: - If `module` is a module, then return module. - If `module` is a string, then import and return the module with that name. - If `module` is None, then return the calling module. The calling module is assumed to be the module of the stack frame at the given depth in the call stack. """ if inspect.ismodule(module): return module elif isinstance(module, str): return __import__(module, globals(), locals(), ["*"]) elif module is None: return sys.modules[sys._getframe(depth).f_globals['__name__']] else: raise TypeError("Expected a module, string, or None") def _load_testfile(filename, package, module_relative, encoding): if module_relative: package = _normalize_module(package, 3) filename = _module_relative_path(package, filename) if getattr(package, '__loader__', None) is not None: if hasattr(package.__loader__, 'get_data'): file_contents = package.__loader__.get_data(filename) file_contents = file_contents.decode(encoding) # get_data() opens files as 'rb', so one must do the equivalent # conversion as universal newlines would do. return file_contents.replace(os.linesep, '\n'), filename with open(filename, encoding=encoding) as f: return f.read(), filename def _indent(s, indent=4): """ Add the given number of space characters to the beginning of every non-blank line in `s`, and return the result. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s) def _exception_traceback(exc_info): """ Return a string containing a traceback message for the given exc_info tuple (as returned by sys.exc_info()). """ # Get a traceback message. excout = StringIO() exc_type, exc_val, exc_tb = exc_info traceback.print_exception(exc_type, exc_val, exc_tb, file=excout) return excout.getvalue() # Override some StringIO methods. class _SpoofOut(StringIO): def getvalue(self): result = StringIO.getvalue(self) # If anything at all was written, make sure there's a trailing # newline. There's no way for the expected output to indicate # that a trailing newline is missing. if result and not result.endswith("\n"): result += "\n" return result def truncate(self, size=None): self.seek(size) StringIO.truncate(self) # Worst-case linear-time ellipsis matching. def _ellipsis_match(want, got): """ Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False """ if ELLIPSIS_MARKER not in want: return want == got # Find "the real" strings. ws = want.split(ELLIPSIS_MARKER) assert len(ws) >= 2 # Deal with exact matches possibly needed at one or both ends. startpos, endpos = 0, len(got) w = ws[0] if w: # starts with exact match if got.startswith(w): startpos = len(w) del ws[0] else: return False w = ws[-1] if w: # ends with exact match if got.endswith(w): endpos -= len(w) del ws[-1] else: return False if startpos > endpos: # Exact end matches required more characters than we have, as in # _ellipsis_match('aa...aa', 'aaa') return False # For the rest, we only need to find the leftmost non-overlapping # match for each piece. If there's no overall match that way alone, # there's no overall match period. for w in ws: # w may be '' at times, if there are consecutive ellipses, or # due to an ellipsis at the start or end of `want`. That's OK. # Search for an empty string succeeds, and doesn't change startpos. startpos = got.find(w, startpos, endpos) if startpos < 0: return False startpos += len(w) return True def _comment_line(line): "Return a commented form of the given line" line = line.rstrip() if line: return '# '+line else: return '#' def _strip_exception_details(msg): # Support for IGNORE_EXCEPTION_DETAIL. # Get rid of everything except the exception name; in particular, drop # the possibly dotted module path (if any) and the exception message (if # any). We assume that a colon is never part of a dotted name, or of an # exception name. # E.g., given # "foo.bar.MyError: la di da" # return "MyError" # Or for "abc.def" or "abc.def:\n" return "def". start, end = 0, len(msg) # The exception name must appear on the first line. i = msg.find("\n") if i >= 0: end = i # retain up to the first colon (if any) i = msg.find(':', 0, end) if i >= 0: end = i # retain just the exception name i = msg.rfind('.', 0, end) if i >= 0: start = i+1 return msg[start: end] class _OutputRedirectingPdb(pdb.Pdb): """ A specialized version of the python debugger that redirects stdout to a given stream when interacting with the user. Stdout is *not* redirected when traced code is executed. """ def __init__(self, out): self.__out = out self.__debugger_used = False # do not play signal games in the pdb pdb.Pdb.__init__(self, stdout=out, nosigint=True) # still use input() to get user input self.use_rawinput = 1 def set_trace(self, frame=None): self.__debugger_used = True if frame is None: frame = sys._getframe().f_back pdb.Pdb.set_trace(self, frame) def set_continue(self): # Calling set_continue unconditionally would break unit test # coverage reporting, as Bdb.set_continue calls sys.settrace(None). if self.__debugger_used: pdb.Pdb.set_continue(self) def trace_dispatch(self, *args): # Redirect stdout to the given stream. save_stdout = sys.stdout sys.stdout = self.__out # Call Pdb's trace dispatch method. try: return pdb.Pdb.trace_dispatch(self, *args) finally: sys.stdout = save_stdout # [XX] Normalize with respect to os.path.pardir? def _module_relative_path(module, test_path): if not inspect.ismodule(module): raise TypeError('Expected a module: %r' % module) if test_path.startswith('/'): raise ValueError('Module-relative files may not have absolute paths') # Normalize the path. On Windows, replace "/" with "\". test_path = os.path.join(*(test_path.split('/'))) # Find the base directory for the path. if hasattr(module, '__file__'): # A normal module/package basedir = os.path.split(module.__file__)[0] elif module.__name__ == '__main__': # An interactive session. if len(sys.argv)>0 and sys.argv[0] != '': basedir = os.path.split(sys.argv[0])[0] else: basedir = os.curdir else: if hasattr(module, '__path__'): for directory in module.__path__: fullpath = os.path.join(directory, test_path) if os.path.exists(fullpath): return fullpath # A module w/o __file__ (this includes builtins) raise ValueError("Can't resolve paths relative to the module " "%r (it has no __file__)" % module.__name__) # Combine the base directory and the test path. return os.path.join(basedir, test_path) ###################################################################### ## 2. Example & DocTest ###################################################################### ## - An "example" is a <source, want> pair, where "source" is a ## fragment of source code, and "want" is the expected output for ## "source." The Example class also includes information about ## where the example was extracted from. ## ## - A "doctest" is a collection of examples, typically extracted from ## a string (such as an object's docstring). The DocTest class also ## includes information about where the string was extracted from. class Example: """ A single doctest example, consisting of source code and expected output. `Example` defines the following attributes: - source: A single Python statement, always ending with a newline. The constructor adds a newline if needed. - want: The expected output from running the source code (either from stdout, or a traceback in case of exception). `want` ends with a newline unless it's empty, in which case it's an empty string. The constructor adds a newline if needed. - exc_msg: The exception message generated by the example, if the example is expected to generate an exception; or `None` if it is not expected to generate an exception. This exception message is compared against the return value of `traceback.format_exception_only()`. `exc_msg` ends with a newline unless it's `None`. The constructor adds a newline if needed. - lineno: The line number within the DocTest string containing this Example where the Example begins. This line number is zero-based, with respect to the beginning of the DocTest. - indent: The example's indentation in the DocTest string. I.e., the number of space characters that precede the example's first prompt. - options: A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner's optionflags). By default, no options are set. """ def __init__(self, source, want, exc_msg=None, lineno=0, indent=0, options=None): # Normalize inputs. if not source.endswith('\n'): source += '\n' if want and not want.endswith('\n'): want += '\n' if exc_msg is not None and not exc_msg.endswith('\n'): exc_msg += '\n' # Store properties. self.source = source self.want = want self.lineno = lineno self.indent = indent if options is None: options = {} self.options = options self.exc_msg = exc_msg def __eq__(self, other): if type(self) is not type(other): return NotImplemented return self.source == other.source and \ self.want == other.want and \ self.lineno == other.lineno and \ self.indent == other.indent and \ self.options == other.options and \ self.exc_msg == other.exc_msg def __hash__(self): return hash((self.source, self.want, self.lineno, self.indent, self.exc_msg)) class DocTest: """ A collection of doctest examples that should be run in a single namespace. Each `DocTest` defines the following attributes: - examples: the list of examples. - globs: The namespace (aka globals) that the examples should be run in. - name: A name identifying the DocTest (typically, the name of the object whose docstring this DocTest was extracted from). - filename: The name of the file that this DocTest was extracted from, or `None` if the filename is unknown. - lineno: The line number within filename where this DocTest begins, or `None` if the line number is unavailable. This line number is zero-based, with respect to the beginning of the file. - docstring: The string that the examples were extracted from, or `None` if the string is unavailable. """ def __init__(self, examples, globs, name, filename, lineno, docstring): """ Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. """ assert not isinstance(examples, str), \ "DocTest no longer accepts str; use DocTestParser instead" self.examples = examples self.docstring = docstring self.globs = globs.copy() self.name = name self.filename = filename self.lineno = lineno def __repr__(self): if len(self.examples) == 0: examples = 'no examples' elif len(self.examples) == 1: examples = '1 example' else: examples = '%d examples' % len(self.examples) return ('<%s %s from %s:%s (%s)>' % (self.__class__.__name__, self.name, self.filename, self.lineno, examples)) def __eq__(self, other): if type(self) is not type(other): return NotImplemented return self.examples == other.examples and \ self.docstring == other.docstring and \ self.globs == other.globs and \ self.name == other.name and \ self.filename == other.filename and \ self.lineno == other.lineno def __hash__(self): return hash((self.docstring, self.name, self.filename, self.lineno)) # This lets us sort tests by name: def __lt__(self, other): if not isinstance(other, DocTest): return NotImplemented return ((self.name, self.filename, self.lineno, id(self)) < (other.name, other.filename, other.lineno, id(other))) ###################################################################### ## 3. DocTestParser ###################################################################### class DocTestParser: """ A class used to parse strings containing doctest examples. """ # This regular expression is used to find doctest examples in a # string. It defines three groups: `source` is the source code # (including leading indentation and prompts); `indent` is the # indentation of the first (PS1) line of the source code; and # `want` is the expected output (including leading indentation). _EXAMPLE_RE = re.compile(r''' # Source consists of a PS1 line followed by zero or more PS2 lines. (?P<source> (?:^(?P<indent> [ ]*) >>> .*) # PS1 line (?:\n [ ]* \.\.\. .*)*) # PS2 lines \n? # Want consists of any non-blank lines that do not start with PS1. (?P<want> (?:(?![ ]*$) # Not a blank line (?![ ]*>>>) # Not a line starting with PS1 .+$\n? # But any other line )*) ''', re.MULTILINE | re.VERBOSE) # A regular expression for handling `want` strings that contain # expected exceptions. It divides `want` into three pieces: # - the traceback header line (`hdr`) # - the traceback stack (`stack`) # - the exception message (`msg`), as generated by # traceback.format_exception_only() # `msg` may have multiple lines. We assume/require that the # exception message is the first non-indented line starting with a word # character following the traceback header line. _EXCEPTION_RE = re.compile(r""" # Grab the traceback header. Different versions of Python have # said different things on the first traceback line. ^(?P<hdr> Traceback\ \( (?: most\ recent\ call\ last | innermost\ last ) \) : ) \s* $ # toss trailing whitespace on the header. (?P<stack> .*?) # don't blink: absorb stuff until... ^ (?P<msg> \w+ .*) # a line *starts* with alphanum. """, re.VERBOSE | re.MULTILINE | re.DOTALL) # A callable returning a true value iff its argument is a blank line # or contains a single comment. _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match def parse(self, string, name='<string>'): """ Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages. """ string = string.expandtabs() # If all lines begin with the same indentation, then strip it. min_indent = self._min_indent(string) if min_indent > 0: string = '\n'.join([l[min_indent:] for l in string.split('\n')]) output = [] charno, lineno = 0, 0 # Find all doctest examples in the string: for m in self._EXAMPLE_RE.finditer(string): # Add the pre-example text to `output`. output.append(string[charno:m.start()]) # Update lineno (lines before this example) lineno += string.count('\n', charno, m.start()) # Extract info from the regexp match. (source, options, want, exc_msg) = \ self._parse_example(m, name, lineno) # Create an Example, and add it to the list. if not self._IS_BLANK_OR_COMMENT(source): output.append( Example(source, want, exc_msg, lineno=lineno, indent=min_indent+len(m.group('indent')), options=options) ) # Update lineno (lines inside this example) lineno += string.count('\n', m.start(), m.end()) # Update charno. charno = m.end() # Add any remaining post-example text to `output`. output.append(string[charno:]) return output def get_doctest(self, string, globs, name, filename, lineno): """ Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for the new `DocTest` object. See the documentation for `DocTest` for more information. """ return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string) def get_examples(self, string, name='<string>'): """ Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it's most common in doctests that nothing interesting appears on the same line as opening triple-quote, and so the first interesting line is called \"line 1\" then. The optional argument `name` is a name identifying this string, and is only used for error messages. """ return [x for x in self.parse(string, name) if isinstance(x, Example)] def _parse_example(self, m, name, lineno): """ Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example's source code (with prompts and indentation stripped); and `want` is the example's expected output (with indentation stripped). `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. """ # Get the example's indentation level. indent = len(m.group('indent')) # Divide source into lines; check that they're properly # indented; and then strip their indentation & prompts. source_lines = m.group('source').split('\n') self._check_prompt_blank(source_lines, indent, name, lineno) self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno) source = '\n'.join([sl[indent+4:] for sl in source_lines]) # Divide want into lines; check that it's properly indented; and # then strip the indentation. Spaces before the last newline should # be preserved, so plain rstrip() isn't good enough. want = m.group('want') want_lines = want.split('\n') if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): del want_lines[-1] # forget final newline & spaces after it self._check_prefix(want_lines, ' '*indent, name, lineno + len(source_lines)) want = '\n'.join([wl[indent:] for wl in want_lines]) # If `want` contains a traceback message, then extract it. m = self._EXCEPTION_RE.match(want) if m: exc_msg = m.group('msg') else: exc_msg = None # Extract options from the source. options = self._find_options(source, name, lineno) return source, options, want, exc_msg # This regular expression looks for option directives in the # source code of an example. Option directives are comments # starting with "doctest:". Warning: this may give false # positives for string-literals that contain the string # "#doctest:". Eliminating these false positives would require # actually parsing the string; but we limit them by ignoring any # line containing "#doctest:" that is *followed* by a quote mark. _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$', re.MULTILINE) def _find_options(self, source, name, lineno): """ Return a dictionary containing option overrides extracted from option directives in the given source string. `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. """ options = {} # (note: with the current regexp, this will match at most once:) for m in self._OPTION_DIRECTIVE_RE.finditer(source): option_strings = m.group(1).replace(',', ' ').split() for option in option_strings: if (option[0] not in '+-' or option[1:] not in OPTIONFLAGS_BY_NAME): raise ValueError('line %r of the doctest for %s ' 'has an invalid option: %r' % (lineno+1, name, option)) flag = OPTIONFLAGS_BY_NAME[option[1:]] options[flag] = (option[0] == '+') if options and self._IS_BLANK_OR_COMMENT(source): raise ValueError('line %r of the doctest for %s has an option ' 'directive on a line with no example: %r' % (lineno, name, source)) return options # This regular expression finds the indentation of every non-blank # line in a string. _INDENT_RE = re.compile(r'^([ ]*)(?=\S)', re.MULTILINE) def _min_indent(self, s): "Return the minimum indentation of any non-blank line in `s`" indents = [len(indent) for indent in self._INDENT_RE.findall(s)] if len(indents) > 0: return min(indents) else: return 0 def _check_prompt_blank(self, lines, indent, name, lineno): """ Given the lines of a source string (including prompts and leading indentation), check to make sure that every prompt is followed by a space character. If any line is not followed by a space character, then raise ValueError. """ for i, line in enumerate(lines): if len(line) >= indent+4 and line[indent+3] != ' ': raise ValueError('line %r of the docstring for %s ' 'lacks blank after %s: %r' % (lineno+i+1, name, line[indent:indent+3], line)) def _check_prefix(self, lines, prefix, name, lineno): """ Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError. """ for i, line in enumerate(lines): if line and not line.startswith(prefix): raise ValueError('line %r of the docstring for %s has ' 'inconsistent leading whitespace: %r' % (lineno+i+1, name, line)) ###################################################################### ## 4. DocTest Finder ###################################################################### class DocTestFinder: """ A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, classmethods, and properties. """ def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True): """ Create a new doctest finder. The optional argument `parser` specifies a class or function that should be used to create new DocTest objects (or objects that implement the same interface as DocTest). The signature for this factory function should match the signature of the DocTest constructor. If the optional argument `recurse` is false, then `find` will only examine the given object, and not any contained objects. If the optional argument `exclude_empty` is false, then `find` will include tests for objects with empty docstrings. """ self._parser = parser self._verbose = verbose self._recurse = recurse self._exclude_empty = exclude_empty def find(self, obj, name=None, module=None, globs=None, extraglobs=None): """ Return a list of the DocTests that are defined by the given object's docstring, or by any of its contained objects' docstrings. The optional parameter `module` is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the correct module. The object's module is used: - As a default namespace, if `globs` is not specified. - To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. - To find the name of the file containing the object. - To help find the line number of the object within its file. Contained objects whose module does not match `module` are ignored. If `module` is False, no attempt to find the module will be made. This is obscure, of use mostly in tests: if `module` is False, or is None but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests. The globals for each DocTest is formed by combining `globs` and `extraglobs` (bindings in `extraglobs` override bindings in `globs`). A new copy of the globals dictionary is created for each DocTest. If `globs` is not specified, then it defaults to the module's `__dict__`, if specified, or {} otherwise. If `extraglobs` is not specified, then it defaults to {}. """ # If name was not specified, then extract it from the object. if name is None: name = getattr(obj, '__name__', None) if name is None: raise ValueError("DocTestFinder.find: name must be given " "when obj.__name__ doesn't exist: %r" % (type(obj),)) # Find the module that contains the given object (if obj is # a module, then module=obj.). Note: this may fail, in which # case module will be None. if module is False: module = None elif module is None: module = inspect.getmodule(obj) # Read the module's source code. This is used by # DocTestFinder._find_lineno to find the line number for a # given object's docstring. try: file = inspect.getsourcefile(obj) except TypeError: source_lines = None else: if not file: # Check to see if it's one of our special internal "files" # (see __patched_linecache_getlines). file = inspect.getfile(obj) if not file[0]+file[-2:] == '<]>': file = None if file is None: source_lines = None else: if module is not None: # Supply the module globals in case the module was # originally loaded via a PEP 302 loader and # file is not a valid filesystem path source_lines = linecache.getlines(file, module.__dict__) else: # No access to a loader, so assume it's a normal # filesystem path source_lines = linecache.getlines(file) if not source_lines: source_lines = None # Initialize globals, and merge in extraglobs. if globs is None: if module is None: globs = {} else: globs = module.__dict__.copy() else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if '__name__' not in globs: globs['__name__'] = '__main__' # provide a default module name # Recursively explore `obj`, extracting DocTests. tests = [] self._find(tests, obj, name, module, source_lines, globs, {}) # Sort the tests by alpha order of names, for consistency in # verbose-mode output. This was a feature of doctest in Pythons # <= 2.3 that got lost by accident in 2.4. It was repaired in # 2.4.4 and 2.5. tests.sort() return tests def _from_module(self, module, object): """ Return true if the given object is defined in the given module. """ if module is None: return True elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif inspect.isfunction(object): return module.__dict__ is object.__globals__ elif inspect.ismethoddescriptor(object): if hasattr(object, '__objclass__'): obj_mod = object.__objclass__.__module__ elif hasattr(object, '__module__'): obj_mod = object.__module__ else: return True # [XX] no easy way to tell otherwise return module.__name__ == obj_mod elif inspect.isclass(object): return module.__name__ == object.__module__ elif hasattr(object, '__module__'): return module.__name__ == object.__module__ elif isinstance(object, property): return True # [XX] no way not be sure. else: raise ValueError("object must be a class or function") def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to `tests`. """ if self._verbose: print('Finding tests in %s' % name) # If we've already processed this object, then ignore it. if id(obj) in seen: return seen[id(obj)] = 1 # Find a test for this object, and add it to the list of tests. test = self._get_test(obj, name, module, globs, source_lines) if test is not None: tests.append(test) # Look for tests in a module's contained objects. if inspect.ismodule(obj) and self._recurse: for valname, val in obj.__dict__.items(): valname = '%s.%s' % (name, valname) # Recurse to functions & classes. if ((inspect.isroutine(inspect.unwrap(val)) or inspect.isclass(val)) and self._from_module(module, val)): self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a module's __test__ dictionary. if inspect.ismodule(obj) and self._recurse: for valname, val in getattr(obj, '__test__', {}).items(): if not isinstance(valname, str): raise ValueError("DocTestFinder.find: __test__ keys " "must be strings: %r" % (type(valname),)) if not (inspect.isroutine(val) or inspect.isclass(val) or inspect.ismodule(val) or isinstance(val, str)): raise ValueError("DocTestFinder.find: __test__ values " "must be strings, functions, methods, " "classes, or modules: %r" % (type(val),)) valname = '%s.__test__.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a class's contained objects. if inspect.isclass(obj) and self._recurse: for valname, val in obj.__dict__.items(): # Special handling for staticmethod/classmethod. if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): val = getattr(obj, valname).__func__ # Recurse to methods, properties, and nested classes. if ((inspect.isroutine(val) or inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val)): valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) def _get_test(self, obj, name, module, globs, source_lines): """ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. """ # Extract the object's docstring. If it doesn't have one, # then return None (no test for this object). if isinstance(obj, str): docstring = obj else: try: if obj.__doc__ is None: docstring = '' else: docstring = obj.__doc__ if not isinstance(docstring, str): docstring = str(docstring) except (TypeError, AttributeError): docstring = '' # Find the docstring's location in the file. lineno = self._find_lineno(obj, source_lines) # Don't bother if the docstring is empty. if self._exclude_empty and not docstring: return None # Return a DocTest for this object. if module is None: filename = None else: filename = getattr(module, '__file__', module.__name__) if filename[-4:] == ".pyc": filename = filename[:-1] return self._parser.get_doctest(docstring, globs, name, filename, lineno) def _find_lineno(self, obj, source_lines): """ Return a line number of the given object's docstring. Note: this method assumes that the object has a docstring. """ lineno = None # Find the line number for modules. if inspect.ismodule(obj): lineno = 0 # Find the line number for classes. # Note: this could be fooled if a class is defined multiple # times in a single file. if inspect.isclass(obj): if source_lines is None: return None pat = re.compile(r'^\s*class\s*%s\b' % getattr(obj, '__name__', '-')) for i, line in enumerate(source_lines): if pat.match(line): lineno = i break # Find the line number for functions & methods. if inspect.ismethod(obj): obj = obj.__func__ if inspect.isfunction(obj): obj = obj.__code__ if inspect.istraceback(obj): obj = obj.tb_frame if inspect.isframe(obj): obj = obj.f_code if inspect.iscode(obj): lineno = getattr(obj, 'co_firstlineno', None)-1 # Find the line number where the docstring starts. Assume # that it's the first line that begins with a quote mark. # Note: this could be fooled by a multiline function # signature, where a continuation line begins with a quote # mark. if lineno is not None: if source_lines is None: return lineno+1 pat = re.compile(r'(^|.*:)\s*\w*("|\')') for lineno in range(lineno, len(source_lines)): if pat.match(source_lines[lineno]): return lineno # We couldn't find the line number. return None ###################################################################### ## 5. DocTest Runner ###################################################################### class DocTestRunner: """ A class used to run DocTest test cases, and accumulate statistics. The `run` method is used to process a single DocTest case. It returns a tuple `(f, t)`, where `t` is the number of test cases tried, and `f` is the number of test cases that failed. >>> tests = DocTestFinder().find(_TestClass) >>> runner = DocTestRunner(verbose=False) >>> tests.sort(key = lambda test: test.name) >>> for test in tests: ... print(test.name, '->', runner.run(test)) _TestClass -> TestResults(failed=0, attempted=2) _TestClass.__init__ -> TestResults(failed=0, attempted=2) _TestClass.get -> TestResults(failed=0, attempted=2) _TestClass.square -> TestResults(failed=0, attempted=1) The `summarize` method prints a summary of all the test cases that have been run by the runner, and returns an aggregated `(f, t)` tuple: >>> runner.summarize(verbose=1) 4 items passed all tests: 2 tests in _TestClass 2 tests in _TestClass.__init__ 2 tests in _TestClass.get 1 tests in _TestClass.square 7 tests in 4 items. 7 passed and 0 failed. Test passed. TestResults(failed=0, attempted=7) The aggregated number of tried examples and failed examples is also available via the `tries` and `failures` attributes: >>> runner.tries 7 >>> runner.failures 0 The comparison between expected outputs and actual outputs is done by an `OutputChecker`. This comparison may be customized with a number of option flags; see the documentation for `testmod` for more information. If the option flags are insufficient, then the comparison may also be customized by passing a subclass of `OutputChecker` to the constructor. The test runner's display output can be controlled in two ways. First, an output function (`out) can be passed to `TestRunner.run`; this function will be called with strings that should be displayed. It defaults to `sys.stdout.write`. If capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods `report_start`, `report_success`, `report_unexpected_exception`, and `report_failure`. """ # This divider string is used to separate failure messages, and to # separate sections of the summary. DIVIDER = "*" * 70 def __init__(self, checker=None, verbose=None, optionflags=0): """ Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg 'verbose' prints lots of stuff if true, only failures if false; by default, it's true iff '-v' is in sys.argv. Optional argument `optionflags` can be used to control how the test runner compares expected output to actual output, and how it displays failures. See the documentation for `testmod` for more information. """ self._checker = checker or OutputChecker() if verbose is None: verbose = '-v' in sys.argv self._verbose = verbose self.optionflags = optionflags self.original_optionflags = optionflags # Keep track of the examples we've run. self.tries = 0 self.failures = 0 self._name2ft = {} # Create a fake output target for capturing doctest output. self._fakeout = _SpoofOut() #///////////////////////////////////////////////////////////////// # Reporting methods #///////////////////////////////////////////////////////////////// def report_start(self, out, test, example): """ Report that the test runner is about to process the given example. (Only displays a message if verbose=True) """ if self._verbose: if example.want: out('Trying:\n' + _indent(example.source) + 'Expecting:\n' + _indent(example.want)) else: out('Trying:\n' + _indent(example.source) + 'Expecting nothing\n') def report_success(self, out, test, example, got): """ Report that the given example ran successfully. (Only displays a message if verbose=True) """ if self._verbose: out("ok\n") def report_failure(self, out, test, example, got): """ Report that the given example failed. """ out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)) def report_unexpected_exception(self, out, test, example, exc_info): """ Report that the given example raised an unexpected exception. """ out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info))) def _failure_header(self, test, example): out = [self.DIVIDER] if test.filename: if test.lineno is not None and example.lineno is not None: lineno = test.lineno + example.lineno + 1 else: lineno = '?' out.append('File "%s", line %s, in %s' % (test.filename, lineno, test.name)) else: out.append('Line %s, in %s' % (example.lineno+1, test.name)) out.append('Failed example:') source = example.source out.append(_indent(source)) return '\n'.join(out) #///////////////////////////////////////////////////////////////// # DocTest Running #///////////////////////////////////////////////////////////////// def __run(self, test, compileflags, out): """ Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the number of examples that failed. The examples are run in the namespace `test.globs`. """ # Keep track of the number of failures and tries. failures = tries = 0 # Save the option flags (since option directives can be used # to modify them). original_optionflags = self.optionflags SUCCESS, FAILURE, BOOM = range(3) # `outcome` state check = self._checker.check_output # Process each example. for examplenum, example in enumerate(test.examples): # If REPORT_ONLY_FIRST_FAILURE is set, then suppress # reporting after the first failure. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and failures > 0) # Merge in the example's options. self.optionflags = original_optionflags if example.options: for (optionflag, val) in example.options.items(): if val: self.optionflags |= optionflag else: self.optionflags &= ~optionflag # If 'SKIP' is set, then skip this example. if self.optionflags & SKIP: continue # Record that we started this example. tries += 1 if not quiet: self.report_start(out, test, example) # Use a special filename for compile(), so we can retrieve # the source code during interactive debugging (see # __patched_linecache_getlines). filename = '<doctest %s[%d]>' % (test.name, examplenum) # Run the example in the given context (globs), and record # any exception that gets raised. (But don't intercept # keyboard interrupts.) try: # Don't blink! This is where the user's code gets run. exec(compile(example.source, filename, "single", compileflags, 1), test.globs) self.debugger.set_continue() # ==== Example Finished ==== exception = None except KeyboardInterrupt: raise except: exception = sys.exc_info() self.debugger.set_continue() # ==== Example Finished ==== got = self._fakeout.getvalue() # the actual output self._fakeout.truncate(0) outcome = FAILURE # guilty until proved innocent or insane # If the example executed without raising any exceptions, # verify its output. if exception is None: if check(example.want, got, self.optionflags): outcome = SUCCESS # The example raised an exception: check if it was expected. else: exc_msg = traceback.format_exception_only(*exception[:2])[-1] if not quiet: got += _exception_traceback(exception) # If `example.exc_msg` is None, then we weren't expecting # an exception. if example.exc_msg is None: outcome = BOOM # We expected an exception: see whether it matches. elif check(example.exc_msg, exc_msg, self.optionflags): outcome = SUCCESS # Another chance if they didn't care about the detail. elif self.optionflags & IGNORE_EXCEPTION_DETAIL: if check(_strip_exception_details(example.exc_msg), _strip_exception_details(exc_msg), self.optionflags): outcome = SUCCESS # Report the outcome. if outcome is SUCCESS: if not quiet: self.report_success(out, test, example, got) elif outcome is FAILURE: if not quiet: self.report_failure(out, test, example, got) failures += 1 elif outcome is BOOM: if not quiet: self.report_unexpected_exception(out, test, example, exception) failures += 1 else: assert False, ("unknown outcome", outcome) if failures and self.optionflags & FAIL_FAST: break # Restore the option flags (in case they were modified) self.optionflags = original_optionflags # Record and return the number of failures and tries. self.__record_outcome(test, failures, tries) return TestResults(failures, tries) def __record_outcome(self, test, f, t): """ Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples. """ f2, t2 = self._name2ft.get(test.name, (0,0)) self._name2ft[test.name] = (f+f2, t+t2) self.failures += f self.tries += t __LINECACHE_FILENAME_RE = re.compile(r'<doctest ' r'(?P<name>.+)' r'\[(?P<examplenum>\d+)\]>$') def __patched_linecache_getlines(self, filename, module_globals=None): m = self.__LINECACHE_FILENAME_RE.match(filename) if m and m.group('name') == self.test.name: example = self.test.examples[int(m.group('examplenum'))] return example.source.splitlines(keepends=True) else: return self.save_linecache_getlines(filename, module_globals) def run(self, test, compileflags=None, out=None, clear_globs=True): """ Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use `clear_globs=False`. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. The output of each example is checked using `DocTestRunner.check_output`, and the results are formatted by the `DocTestRunner.report_*` methods. """ self.test = test if compileflags is None: compileflags = _extract_future_flags(test.globs) save_stdout = sys.stdout if out is None: encoding = save_stdout.encoding if encoding is None or encoding.lower() == 'utf-8': out = save_stdout.write else: # Use backslashreplace error handling on write def out(s): s = str(s.encode(encoding, 'backslashreplace'), encoding) save_stdout.write(s) sys.stdout = self._fakeout # Patch pdb.set_trace to restore sys.stdout during interactive # debugging (so it's not still redirected to self._fakeout). # Note that the interactive output will go to *our* # save_stdout, even if that's not the real sys.stdout; this # allows us to write test cases for the set_trace behavior. save_trace = sys.gettrace() save_set_trace = pdb.set_trace self.debugger = _OutputRedirectingPdb(save_stdout) self.debugger.reset() pdb.set_trace = self.debugger.set_trace # Patch linecache.getlines, so we can see the example's source # when we're inside the debugger. self.save_linecache_getlines = linecache.getlines linecache.getlines = self.__patched_linecache_getlines # Make sure sys.displayhook just prints the value to stdout save_displayhook = sys.displayhook sys.displayhook = sys.__displayhook__ try: return self.__run(test, compileflags, out) finally: sys.stdout = save_stdout pdb.set_trace = save_set_trace sys.settrace(save_trace) linecache.getlines = self.save_linecache_getlines sys.displayhook = save_displayhook if clear_globs: test.globs.clear() import builtins builtins._ = None #///////////////////////////////////////////////////////////////// # Summarization #///////////////////////////////////////////////////////////////// def summarize(self, verbose=None): """ Print a summary of all the test cases that have been run by this DocTestRunner, and return a tuple `(f, t)`, where `f` is the total number of failed examples, and `t` is the total number of tried examples. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner's verbosity is used. """ if verbose is None: verbose = self._verbose notests = [] passed = [] failed = [] totalt = totalf = 0 for x in self._name2ft.items(): name, (f, t) = x assert f <= t totalt += t totalf += f if t == 0: notests.append(name) elif f == 0: passed.append( (name, t) ) else: failed.append(x) if verbose: if notests: print(len(notests), "items had no tests:") notests.sort() for thing in notests: print(" ", thing) if passed: print(len(passed), "items passed all tests:") passed.sort() for thing, count in passed: print(" %3d tests in %s" % (count, thing)) if failed: print(self.DIVIDER) print(len(failed), "items had failures:") failed.sort() for thing, (f, t) in failed: print(" %3d of %3d in %s" % (f, t, thing)) if verbose: print(totalt, "tests in", len(self._name2ft), "items.") print(totalt - totalf, "passed and", totalf, "failed.") if totalf: print("***Test Failed***", totalf, "failures.") elif verbose: print("Test passed.") return TestResults(totalf, totalt) #///////////////////////////////////////////////////////////////// # Backward compatibility cruft to maintain doctest.master. #///////////////////////////////////////////////////////////////// def merge(self, other): d = self._name2ft for name, (f, t) in other._name2ft.items(): if name in d: # Don't print here by default, since doing # so breaks some of the buildbots #print("*** DocTestRunner.merge: '" + name + "' in both" \ # " testers; summing outcomes.") f2, t2 = d[name] f = f + f2 t = t + t2 d[name] = f, t class OutputChecker: """ A class used to check the whether the actual output from a doctest example matches the expected output. `OutputChecker` defines two methods: `check_output`, which compares a given pair of outputs, and returns true if they match; and `output_difference`, which returns a string describing the differences between two outputs. """ def _toAscii(self, s): """ Convert string to hex-escaped ASCII string. """ return str(s.encode('ASCII', 'backslashreplace'), "ASCII") def check_output(self, want, got, optionflags): """ Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for more information about option flags. """ # If `want` contains hex-escaped character such as "\u1234", # then `want` is a string of six characters(e.g. [\,u,1,2,3,4]). # On the other hand, `got` could be another sequence of # characters such as [\u1234], so `want` and `got` should # be folded to hex-escaped ASCII string to compare. got = self._toAscii(got) want = self._toAscii(want) # Handle the common case first, for efficiency: # if they're string-identical, always return true. if got == want: return True # The values True and False replaced 1 and 0 as the return # value for boolean comparisons in Python 2.3. if not (optionflags & DONT_ACCEPT_TRUE_FOR_1): if (got,want) == ("True\n", "1\n"): return True if (got,want) == ("False\n", "0\n"): return True # <BLANKLINE> can be used as a special sequence to signify a # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. if not (optionflags & DONT_ACCEPT_BLANKLINE): # Replace <BLANKLINE> in want with a blank line. want = re.sub(r'(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER), '', want) # If a line in got contains only spaces, then remove the # spaces. got = re.sub(r'(?m)^\s*?$', '', got) if got == want: return True # This flag causes doctest to ignore any differences in the # contents of whitespace strings. Note that this can be used # in conjunction with the ELLIPSIS flag. if optionflags & NORMALIZE_WHITESPACE: got = ' '.join(got.split()) want = ' '.join(want.split()) if got == want: return True # The ELLIPSIS flag says to let the sequence "..." in `want` # match any substring in `got`. if optionflags & ELLIPSIS: if _ellipsis_match(want, got): return True # We didn't find any match; return false. return False # Should we do a fancy diff? def _do_a_fancy_diff(self, want, got, optionflags): # Not unless they asked for a fancy diff. if not optionflags & (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF): return False # If expected output uses ellipsis, a meaningful fancy diff is # too hard ... or maybe not. In two real-life failures Tim saw, # a diff was a major help anyway, so this is commented out. # [todo] _ellipsis_match() knows which pieces do and don't match, # and could be the basis for a kick-ass diff in this case. ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want: ## return False # ndiff does intraline difference marking, so can be useful even # for 1-line differences. if optionflags & REPORT_NDIFF: return True # The other diff types need at least a few lines to be helpful. return want.count('\n') > 2 and got.count('\n') > 2 def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If <BLANKLINE>s are being used, then replace blank lines # with <BLANKLINE> in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) # Check if we should use diff. if self._do_a_fancy_diff(want, got, optionflags): # Split want & got into lines. want_lines = want.splitlines(keepends=True) got_lines = got.splitlines(keepends=True) # Use difflib to find their differences. if optionflags & REPORT_UDIFF: diff = difflib.unified_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'unified diff with -expected +actual' elif optionflags & REPORT_CDIFF: diff = difflib.context_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'context diff with expected followed by actual' elif optionflags & REPORT_NDIFF: engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff = list(engine.compare(want_lines, got_lines)) kind = 'ndiff with -expected +actual' else: assert 0, 'Bad diff option' # Remove trailing whitespace on diff output. diff = [line.rstrip() + '\n' for line in diff] return 'Differences (%s):\n' % kind + _indent(''.join(diff)) # If we're not using diff, then simply list the expected # output followed by the actual output. if want and got: return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got)) elif want: return 'Expected:\n%sGot nothing\n' % _indent(want) elif got: return 'Expected nothing\nGot:\n%s' % _indent(got) else: return 'Expected nothing\nGot nothing\n' class DocTestFailure(Exception): """A DocTest example has failed in debugging mode. The exception instance has variables: - test: the DocTest object being run - example: the Example object that failed - got: the actual output """ def __init__(self, test, example, got): self.test = test self.example = example self.got = got def __str__(self): return str(self.test) class UnexpectedException(Exception): """A DocTest example has encountered an unexpected exception The exception instance has variables: - test: the DocTest object being run - example: the Example object that failed - exc_info: the exception info """ def __init__(self, test, example, exc_info): self.test = test self.example = example self.exc_info = exc_info def __str__(self): return str(self.test) class DebugRunner(DocTestRunner): r"""Run doc tests but raise an exception as soon as there is a failure. If an unexpected exception occurs, an UnexpectedException is raised. It contains the test, the example, and the original exception: >>> runner = DebugRunner(verbose=False) >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except UnexpectedException as f: ... failure = f >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[1] # Already has the traceback Traceback (most recent call last): ... KeyError We wrap the original exception to give the calling application access to the test and example information. If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except DocTestFailure as f: ... failure = f DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' If a failure or error occurs, the globals are left intact: >>> del test.globs['__builtins__'] >>> test.globs {'x': 1} >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... >>> raise KeyError ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) Traceback (most recent call last): ... doctest.UnexpectedException: <DocTest foo from foo.py:0 (2 examples)> >>> del test.globs['__builtins__'] >>> test.globs {'x': 2} But the globals are cleared if there is no error: >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) TestResults(failed=0, attempted=1) >>> test.globs {} """ def run(self, test, compileflags=None, out=None, clear_globs=True): r = DocTestRunner.run(self, test, compileflags, out, False) if clear_globs: test.globs.clear() return r def report_unexpected_exception(self, out, test, example, exc_info): raise UnexpectedException(test, example, exc_info) def report_failure(self, out, test, example, got): raise DocTestFailure(test, example, got) ###################################################################### ## 6. Test Functions ###################################################################### # These should be backwards compatible. # For backward compatibility, a global instance of a DocTestRunner # class, updated by testmod. master = None def testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False): """m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False Test examples in docstrings in functions and classes reachable from module m (or the current module if m is not supplied), starting with m.__doc__. Also test examples reachable from dict m.__test__ if it exists and is not None. m.__test__ maps names to functions, classes and strings; function and class docstrings are tested even if the name is private; strings are tested directly, as if they were docstrings. Return (#failures, #tests). See help(doctest) for an overview. Optional keyword arg "name" gives the name of the module; by default use m.__name__. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use m.__dict__. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. This is new in 2.4. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. This is new in 2.3. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS SKIP IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master # If no module was given, then use __main__. if m is None: # DWA - m will still be None if this wasn't invoked from the command # line, in which case the following TypeError is about as good an error # as we should expect m = sys.modules.get('__main__') # Check that we were actually given a module. if not inspect.ismodule(m): raise TypeError("testmod: module required; %r" % (m,)) # If no name was given, then use the module's name. if name is None: name = m.__name__ # Find, parse, and run all tests in the given module. finder = DocTestFinder(exclude_empty=exclude_empty) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return TestResults(runner.failures, runner.tries) def testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser(), encoding=None): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - If "module_relative" is True (the default), then "filename" specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the "package" argument is specified, then it is relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If "module_relative" is False, then "filename" specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg "name" gives the name of the test; by default use the file's basename. Optional keyword argument "package" is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS SKIP IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg "parser" specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Optional keyword arg "encoding" specifies an encoding that should be used to convert the file to unicode. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path text, filename = _load_testfile(filename, package, module_relative, encoding or "utf-8") # If no name was given, then use the file's name. if name is None: name = os.path.basename(filename) # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if '__name__' not in globs: globs['__name__'] = '__main__' if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) # Read the file, convert it to a test, and run it. test = parser.get_doctest(text, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return TestResults(runner.failures, runner.tries) def run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0): """ Test examples in the given object's docstring (`f`), using `globs` as globals. Optional argument `name` is used in failure messages. If the optional argument `verbose` is true, then generate output even if there are no failures. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. Optional keyword arg `optionflags` specifies options for the testing and output. See the documentation for `testmod` for more information. """ # Find, parse, and run all tests in the given module. finder = DocTestFinder(verbose=verbose, recurse=False) runner = DocTestRunner(verbose=verbose, optionflags=optionflags) for test in finder.find(f, name, globs=globs): runner.run(test, compileflags=compileflags) ###################################################################### ## 7. Unittest Support ###################################################################### _unittest_reportflags = 0 def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> import doctest >>> old = doctest._unittest_reportflags >>> doctest.set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> doctest.set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old class DocTestCase(unittest.TestCase): def __init__(self, test, optionflags=0, setUp=None, tearDown=None, checker=None): unittest.TestCase.__init__(self) self._dt_optionflags = optionflags self._dt_checker = checker self._dt_test = test self._dt_setUp = setUp self._dt_tearDown = tearDown def setUp(self): test = self._dt_test if self._dt_setUp is not None: self._dt_setUp(test) def tearDown(self): test = self._dt_test if self._dt_tearDown is not None: self._dt_tearDown(test) test.globs.clear() def runTest(self): test = self._dt_test old = sys.stdout new = StringIO() optionflags = self._dt_optionflags if not (optionflags & REPORTING_FLAGS): # The option flags don't include any reporting flags, # so add the default reporting flags optionflags |= _unittest_reportflags runner = DocTestRunner(optionflags=optionflags, checker=self._dt_checker, verbose=False) try: runner.DIVIDER = "-"*70 failures, tries = runner.run( test, out=new.write, clear_globs=False) finally: sys.stdout = old if failures: raise self.failureException(self.format_failure(new.getvalue())) def format_failure(self, err): test = self._dt_test if test.lineno is None: lineno = 'unknown line number' else: lineno = '%s' % test.lineno lname = '.'.join(test.name.split('.')[-1:]) return ('Failed doctest test for %s\n' ' File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err) ) def debug(self): r"""Run the test case without results and without catching exceptions The unit test framework includes a debug method on test cases and test suites to support post-mortem debugging. The test code is run in such a way that errors are not caught. This way a caller can catch the errors and initiate post-mortem debugging. The DocTestCase provides a debug method that raises UnexpectedException errors if there is an unexpected exception: >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except UnexpectedException as f: ... failure = f The UnexpectedException contains the test, the example, and the original exception: >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[1] # Already has the traceback Traceback (most recent call last): ... KeyError If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except DocTestFailure as f: ... failure = f DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' """ self.setUp() runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False) runner.run(self._dt_test, clear_globs=False) self.tearDown() def id(self): return self._dt_test.name def __eq__(self, other): if type(self) is not type(other): return NotImplemented return self._dt_test == other._dt_test and \ self._dt_optionflags == other._dt_optionflags and \ self._dt_setUp == other._dt_setUp and \ self._dt_tearDown == other._dt_tearDown and \ self._dt_checker == other._dt_checker def __hash__(self): return hash((self._dt_optionflags, self._dt_setUp, self._dt_tearDown, self._dt_checker)) def __repr__(self): name = self._dt_test.name.split('.') return "%s (%s)" % (name[-1], '.'.join(name[:-1])) __str__ = __repr__ def shortDescription(self): return "Doctest: " + self._dt_test.name class SkipDocTestCase(DocTestCase): def __init__(self, module): self.module = module DocTestCase.__init__(self, None) def setUp(self): self.skipTest("DocTestSuite will not work with -O2 and above") def test_skip(self): pass def shortDescription(self): return "Skipping tests from %s" % self.module.__name__ __str__ = shortDescription class _DocTestSuite(unittest.TestSuite): def _removeTestAtIndex(self, index): pass def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ if test_finder is None: test_finder = DocTestFinder() module = _normalize_module(module) tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) if not tests and sys.flags.optimize >=2: # Skip doctests when running with -O2 suite = _DocTestSuite() suite.addTest(SkipDocTestCase(module)) return suite tests.sort() suite = _DocTestSuite() for test in tests: if len(test.examples) == 0: continue if not test.filename: filename = module.__file__ if filename[-4:] == ".pyc": filename = filename[:-1] test.filename = filename suite.addTest(DocTestCase(test, **options)) return suite class DocFileCase(DocTestCase): def id(self): return '_'.join(self._dt_test.name.split('.')) def __repr__(self): return self._dt_test.filename __str__ = __repr__ def format_failure(self, err): return ('Failed doctest test for %s\n File "%s", line 0\n\n%s' % (self._dt_test.name, self._dt_test.filename, err) ) def DocFileTest(path, module_relative=True, package=None, globs=None, parser=DocTestParser(), encoding=None, **options): if globs is None: globs = {} else: globs = globs.copy() if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path. doc, path = _load_testfile(path, package, module_relative, encoding or "utf-8") if "__file__" not in globs: globs["__file__"] = path # Find the file and read it. name = os.path.basename(path) # Convert it to a test, and wrap it in a DocFileCase. test = parser.get_doctest(doc, globs, name, path, 0) return DocFileCase(test, **options) def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is True, then the given file paths are interpreted as os-independent module-relative paths. By default, these paths are relative to the calling module's directory; but if the "package" argument is specified, then they are relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and may not be an absolute path (i.e., it may not begin with "/"). If "module_relative" is False, then the given file paths are interpreted as os-specific paths. These paths may be absolute or relative (to the current working directory). package A Python package or the name of a Python package whose directory should be used as the base directory for module relative paths. If "package" is not specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. parser A DocTestParser (or subclass) that should be used to extract tests from the files. encoding An encoding that will be used to convert the files to unicode. """ suite = _DocTestSuite() # We do this here so that _normalize_module is called at the right # level. If it were called in DocFileTest, then this function # would be the caller and we might guess the package incorrectly. if kw.get('module_relative', True): kw['package'] = _normalize_module(kw.get('package')) for path in paths: suite.addTest(DocFileTest(path, **kw)) return suite ###################################################################### ## 8. Debugging Support ###################################################################### def script_from_examples(s): r"""Extract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print(script_from_examples(text)) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum <BLANKLINE> """ output = [] for piece in DocTestParser().parse(s): if isinstance(piece, Example): # Add the example's source code (strip trailing NL) output.append(piece.source[:-1]) # Add the expected output: want = piece.want if want: output.append('# Expected:') output += ['## '+l for l in want.split('\n')[:-1]] else: # Add non-example text. output += [_comment_line(l) for l in piece.split('\n')[:-1]] # Trim junk on both ends. while output and output[-1] == '#': output.pop() while output and output[0] == '#': output.pop(0) # Combine the output, and return it. # Add a courtesy newline to prevent exec from choking (see bug #1172785) return '\n'.join(output) + '\n' def testsource(module, name): """Extract the test sources from a doctest docstring as a script. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the doc string with tests to be debugged. """ module = _normalize_module(module) tests = DocTestFinder().find(module) test = [t for t in tests if t.name == name] if not test: raise ValueError(name, "not found in tests") test = test[0] testsrc = script_from_examples(test.docstring) return testsrc def debug_src(src, pm=False, globs=None): """Debug a single doctest docstring, in argument `src`'""" testsrc = script_from_examples(src) debug_script(testsrc, pm, globs) def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb if globs: globs = globs.copy() else: globs = {} if pm: try: exec(src, globs, globs) except: print(sys.exc_info()[1]) p = pdb.Pdb(nosigint=True) p.reset() p.interaction(None, sys.exc_info()[2]) else: pdb.Pdb(nosigint=True).run("exec(%r)" % src, globs, globs) def debug(module, name, pm=False): """Debug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged. """ module = _normalize_module(module) testsrc = testsource(module, name) debug_script(testsrc, pm, module.__dict__) ###################################################################### ## 9. Example Usage ###################################################################### class _TestClass: """ A pointless class, for sanity-checking of docstring testing. Methods: square() get() >>> _TestClass(13).get() + _TestClass(-12).get() 1 >>> hex(_TestClass(13).square().get()) '0xa9' """ def __init__(self, val): """val -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print(t.get()) 123 """ self.val = val def square(self): """square() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 """ self.val = self.val ** 2 return self def get(self): """get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print(x.get()) -42 """ return self.val __test__ = {"_TestClass": _TestClass, "string": r""" Example of a string object, searched as-is. >>> x = 1; y = 2 >>> x + y, x * y (3, 2) """, "bool-int equivalence": r""" In 2.2, boolean expressions displayed 0 or 1. By default, we still accept them. This can be disabled by passing DONT_ACCEPT_TRUE_FOR_1 to the new optionflags argument. >>> 4 == 4 1 >>> 4 == 4 True >>> 4 > 4 0 >>> 4 > 4 False """, "blank lines": r""" Blank lines can be marked with <BLANKLINE>: >>> print('foo\n\nbar\n') foo <BLANKLINE> bar <BLANKLINE> """, "ellipsis": r""" If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: >>> print(list(range(1000))) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] """, "whitespace normalization": r""" If the whitespace normalization flag is used, then differences in whitespace are ignored. >>> print(list(range(30))) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] """, } def _test(): parser = argparse.ArgumentParser(description="doctest runner") parser.add_argument('-v', '--verbose', action='store_true', default=False, help='print very verbose output for all tests') parser.add_argument('-o', '--option', action='append', choices=OPTIONFLAGS_BY_NAME.keys(), default=[], help=('specify a doctest option flag to apply' ' to the test run; may be specified more' ' than once to apply multiple options')) parser.add_argument('-f', '--fail-fast', action='store_true', help=('stop running tests after first failure (this' ' is a shorthand for -o FAIL_FAST, and is' ' in addition to any other -o options)')) parser.add_argument('file', nargs='+', help='file containing the tests to run') args = parser.parse_args() testfiles = args.file # Verbose used to be handled by the "inspect argv" magic in DocTestRunner, # but since we are using argparse we are passing it manually now. verbose = args.verbose options = 0 for option in args.option: options |= OPTIONFLAGS_BY_NAME[option] if args.fail_fast: options |= FAIL_FAST for filename in testfiles: if filename.endswith(".py"): # It is a module -- insert its dir into sys.path and try to # import it. If it is part of a package, that possibly # won't work because of package imports. dirname, filename = os.path.split(filename) sys.path.insert(0, dirname) m = __import__(filename[:-3]) del sys.path[0] failures, _ = testmod(m, verbose=verbose, optionflags=options) else: failures, _ = testfile(filename, module_relative=False, verbose=verbose, optionflags=options) if failures: return 1 return 0 if __name__ == "__main__": sys.exit(_test())
104,391
2,788
jart/cosmopolitan
false