#include "Python.h" #include "pycore_fileutils.h" // fileutils definitions #include "pycore_runtime.h" // _PyRuntime #include "osdefs.h" // SEP #include <stdlib.h> // mbstowcs() #ifdef HAVE_UNISTD_H # include <unistd.h> // getcwd() #endif #ifdef MS_WINDOWS # include <malloc.h> # include <windows.h> # include <winioctl.h> // FILE_DEVICE_* constants # include "pycore_fileutils_windows.h" // FILE_STAT_BASIC_INFORMATION # if defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP) #define PATHCCH_ALLOW_LONG_PATHS … # else # include <pathcch.h> // PathCchCombineEx # endif extern int winerror_to_errno(int); #endif #ifdef HAVE_LANGINFO_H # include <langinfo.h> // nl_langinfo(CODESET) #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION # include <iconv.h> // iconv_open() #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> // fcntl(F_GETFD) #endif #ifdef O_CLOEXEC /* Does open() support the O_CLOEXEC flag? Possible values: -1: unknown 0: open() ignores O_CLOEXEC flag, ex: Linux kernel older than 2.6.23 1: open() supports O_CLOEXEC flag, close-on-exec is set The flag is used by _Py_open(), _Py_open_noraise(), io.FileIO and os.open(). */ int _Py_open_cloexec_works = …; #endif // The value must be the same in unicodeobject.c. #define MAX_UNICODE … // mbstowcs() and mbrtowc() errors static const size_t DECODE_ERROR = …; static const size_t INCOMPLETE_CHARACTER = …; static int get_surrogateescape(_Py_error_handler errors, int *surrogateescape) { … } PyObject * _Py_device_encoding(int fd) { … } static int is_valid_wide_char(wchar_t ch) { … } static size_t _Py_mbstowcs(wchar_t *dest, const char *src, size_t n) { … } #ifdef HAVE_MBRTOWC static size_t _Py_mbrtowc(wchar_t *pwc, const char *str, size_t len, mbstate_t *pmbs) { … } #endif #if !defined(_Py_FORCE_UTF8_FS_ENCODING) && !defined(MS_WINDOWS) #define USE_FORCE_ASCII extern int _Py_normalize_encoding(const char *, char *, size_t); /* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale and POSIX locale. nl_langinfo(CODESET) announces an alias of the ASCII encoding, whereas mbstowcs() and wcstombs() functions use the ISO-8859-1 encoding. The problem is that os.fsencode() and os.fsdecode() use locale.getpreferredencoding() codec. For example, if command line arguments are decoded by mbstowcs() and encoded back by os.fsencode(), we get a UnicodeEncodeError instead of retrieving the original byte string. The workaround is enabled if setlocale(LC_CTYPE, NULL) returns "C", nl_langinfo(CODESET) announces "ascii" (or an alias to ASCII), and at least one byte in range 0x80-0xff can be decoded from the locale encoding. The workaround is also enabled on error, for example if getting the locale failed. On HP-UX with the C locale or the POSIX locale, nl_langinfo(CODESET) announces "roman8" but mbstowcs() uses Latin1 in practice. Force also the ASCII encoding in this case. Values of force_ascii: 1: the workaround is used: Py_EncodeLocale() uses encode_ascii_surrogateescape() and Py_DecodeLocale() uses decode_ascii() 0: the workaround is not used: Py_EncodeLocale() uses wcstombs() and Py_DecodeLocale() uses mbstowcs() -1: unknown, need to call check_force_ascii() to get the value */ #define force_ascii … static int check_force_ascii(void) { … } int _Py_GetForceASCII(void) { … } void _Py_ResetForceASCII(void) { … } static int encode_ascii(const wchar_t *text, char **str, size_t *error_pos, const char **reason, int raw_malloc, _Py_error_handler errors) { … } #else int _Py_GetForceASCII(void) { return 0; } void _Py_ResetForceASCII(void) { /* nothing to do */ } #endif /* !defined(_Py_FORCE_UTF8_FS_ENCODING) && !defined(MS_WINDOWS) */ #if !defined(HAVE_MBRTOWC) || defined(USE_FORCE_ASCII) static int decode_ascii(const char *arg, wchar_t **wstr, size_t *wlen, const char **reason, _Py_error_handler errors) { … } #endif /* !HAVE_MBRTOWC */ static int decode_current_locale(const char* arg, wchar_t **wstr, size_t *wlen, const char **reason, _Py_error_handler errors) { … } /* Decode a byte string from the locale encoding. Use the strict error handler if 'surrogateescape' is zero. Use the surrogateescape error handler if 'surrogateescape' is non-zero: 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. On success, return 0 and write the newly allocated wide character string into *wstr (use PyMem_RawFree() to free the memory). If wlen is not NULL, write the number of wide characters excluding the null character into *wlen. On memory allocation failure, return -1. On decoding error, return -2. If wlen is not NULL, write the start of invalid byte sequence in the input string into *wlen. If reason is not NULL, write the decoding error message into *reason. Return -3 if the error handler 'errors' is not supported. Use the Py_EncodeLocaleEx() function to encode the character string back to a byte string. */ int _Py_DecodeLocaleEx(const char* arg, wchar_t **wstr, size_t *wlen, const char **reason, int current_locale, _Py_error_handler errors) { … } /* 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 *wlen) { … } static int encode_current_locale(const wchar_t *text, char **str, size_t *error_pos, const char **reason, int raw_malloc, _Py_error_handler errors) { … } /* Encode a string to the locale encoding. Parameters: * raw_malloc: if non-zero, allocate memory using PyMem_RawMalloc() instead of PyMem_Malloc(). * current_locale: if non-zero, use the current LC_CTYPE, otherwise use Python filesystem encoding. * errors: error handler like "strict" or "surrogateescape". Return value: 0: success, *str is set to a newly allocated decoded string. -1: memory allocation failure -2: encoding error, set *error_pos and *reason (if set). -3: the error handler 'errors' is not supported. */ static int encode_locale_ex(const wchar_t *text, char **str, size_t *error_pos, const char **reason, int raw_malloc, int current_locale, _Py_error_handler errors) { … } static char* encode_locale(const wchar_t *text, size_t *error_pos, int raw_malloc, int current_locale) { … } /* 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 (size_t)-1 on success, or set to the index of the invalid character on encoding error. 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) { … } /* Similar to Py_EncodeLocale(), but result must be freed by PyMem_RawFree() instead of PyMem_Free(). */ char* _Py_EncodeLocaleRaw(const wchar_t *text, size_t *error_pos) { … } int _Py_EncodeLocaleEx(const wchar_t *text, char **str, size_t *error_pos, const char **reason, int current_locale, _Py_error_handler errors) { … } // Get the current locale encoding name: // // - Return "utf-8" if _Py_FORCE_UTF8_LOCALE macro is defined (ex: on Android) // - Return "utf-8" if the UTF-8 Mode is enabled // - On Windows, return the ANSI code page (ex: "cp1250") // - Return "utf-8" if nl_langinfo(CODESET) returns an empty string. // - Otherwise, return nl_langinfo(CODESET). // // Return NULL on memory allocation failure. // // See also config_get_locale_encoding() wchar_t* _Py_GetLocaleEncoding(void) { … } PyObject * _Py_GetLocaleEncodingObject(void) { … } #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION /* Check whether current locale uses Unicode as internal wchar_t form. */ int _Py_LocaleUsesNonUnicodeWchar(void) { /* Oracle Solaris uses non-Unicode internal wchar_t form for non-Unicode locales and hence needs conversion to UTF first. */ char* codeset = nl_langinfo(CODESET); if (!codeset) { return 0; } /* 646 refers to ISO/IEC 646 standard that corresponds to ASCII encoding */ return (strcmp(codeset, "UTF-8") != 0 && strcmp(codeset, "646") != 0); } static wchar_t * _Py_ConvertWCharForm(const wchar_t *source, Py_ssize_t size, const char *tocode, const char *fromcode) { static_assert(sizeof(wchar_t) == 4, "wchar_t must be 32-bit"); /* Ensure we won't overflow the size. */ if (size > (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t))) { PyErr_NoMemory(); return NULL; } /* the string doesn't have to be NULL terminated */ wchar_t* target = PyMem_Malloc(size * sizeof(wchar_t)); if (target == NULL) { PyErr_NoMemory(); return NULL; } iconv_t cd = iconv_open(tocode, fromcode); if (cd == (iconv_t)-1) { PyErr_Format(PyExc_ValueError, "iconv_open() failed"); PyMem_Free(target); return NULL; } char *inbuf = (char *) source; char *outbuf = (char *) target; size_t inbytesleft = sizeof(wchar_t) * size; size_t outbytesleft = inbytesleft; size_t ret = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft); if (ret == DECODE_ERROR) { PyErr_Format(PyExc_ValueError, "iconv() failed"); PyMem_Free(target); iconv_close(cd); return NULL; } iconv_close(cd); return target; } /* Convert a wide character string to the UCS-4 encoded string. This is necessary on systems where internal form of wchar_t are not Unicode code points (e.g. Oracle Solaris). Return a pointer to a newly allocated string, use PyMem_Free() to free the memory. Return NULL and raise exception on conversion or memory allocation error. */ wchar_t * _Py_DecodeNonUnicodeWchar(const wchar_t *native, Py_ssize_t size) { return _Py_ConvertWCharForm(native, size, "UCS-4-INTERNAL", "wchar_t"); } /* Convert a UCS-4 encoded string to native wide character string. This is necessary on systems where internal form of wchar_t are not Unicode code points (e.g. Oracle Solaris). The conversion is done in place. This can be done because both wchar_t and UCS-4 use 4-byte encoding, and one wchar_t symbol always correspond to a single UCS-4 symbol and vice versa. (This is true for Oracle Solaris, which is currently the only system using these functions; it doesn't have to be for other systems). Return 0 on success. Return -1 and raise exception on conversion or memory allocation error. */ int _Py_EncodeNonUnicodeWchar_InPlace(wchar_t *unicode, Py_ssize_t size) { wchar_t* result = _Py_ConvertWCharForm(unicode, size, "wchar_t", "UCS-4-INTERNAL"); if (!result) { return -1; } memcpy(unicode, result, size * sizeof(wchar_t)); PyMem_Free(result); return 0; } #endif /* HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION */ #ifdef MS_WINDOWS static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */ static void FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out) { /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ /* Cannot simply cast and dereference in_ptr, since it might not be aligned properly */ __int64 in; memcpy(&in, in_ptr, sizeof(in)); *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t); } static void LARGE_INTEGER_to_time_t_nsec(LARGE_INTEGER *in_ptr, time_t *time_out, int* nsec_out) { *nsec_out = (int)(in_ptr->QuadPart % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ *time_out = Py_SAFE_DOWNCAST((in_ptr->QuadPart / 10000000) - secs_between_epochs, __int64, time_t); } void _Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr) { /* XXX endianness */ __int64 out; out = time_in + secs_between_epochs; out = out * 10000000 + nsec_in / 100; memcpy(out_ptr, &out, sizeof(out)); } /* Below, we *know* that ugo+r is 0444 */ #if _S_IREAD != 0400 #error Unsupported C library #endif static int attributes_to_mode(DWORD attr) { int m = 0; if (attr & FILE_ATTRIBUTE_DIRECTORY) m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ else m |= _S_IFREG; if (attr & FILE_ATTRIBUTE_READONLY) m |= 0444; else m |= 0666; return m; } typedef union { FILE_ID_128 id; struct { uint64_t st_ino; uint64_t st_ino_high; }; } id_128_to_ino; void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag, FILE_BASIC_INFO *basic_info, FILE_ID_INFO *id_info, struct _Py_stat_struct *result) { memset(result, 0, sizeof(*result)); result->st_mode = attributes_to_mode(info->dwFileAttributes); result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; result->st_dev = id_info ? id_info->VolumeSerialNumber : info->dwVolumeSerialNumber; result->st_rdev = 0; /* st_ctime is deprecated, but we preserve the legacy value in our caller, not here */ if (basic_info) { LARGE_INTEGER_to_time_t_nsec(&basic_info->CreationTime, &result->st_birthtime, &result->st_birthtime_nsec); LARGE_INTEGER_to_time_t_nsec(&basic_info->ChangeTime, &result->st_ctime, &result->st_ctime_nsec); LARGE_INTEGER_to_time_t_nsec(&basic_info->LastWriteTime, &result->st_mtime, &result->st_mtime_nsec); LARGE_INTEGER_to_time_t_nsec(&basic_info->LastAccessTime, &result->st_atime, &result->st_atime_nsec); } else { FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_birthtime, &result->st_birthtime_nsec); FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); } result->st_nlink = info->nNumberOfLinks; if (id_info) { id_128_to_ino file_id; file_id.id = id_info->FileId; result->st_ino = file_id.st_ino; result->st_ino_high = file_id.st_ino_high; } if (!result->st_ino && !result->st_ino_high) { /* should only occur for DirEntry_from_find_data, in which case the index is likely to be zero anyway. */ result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow; } /* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will open other name surrogate reparse points without traversing them. To detect/handle these, check st_file_attributes and st_reparse_tag. */ result->st_reparse_tag = reparse_tag; if (info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT && reparse_tag == IO_REPARSE_TAG_SYMLINK) { /* set the bits that make this a symlink */ result->st_mode = (result->st_mode & ~S_IFMT) | S_IFLNK; } result->st_file_attributes = info->dwFileAttributes; } void _Py_stat_basic_info_to_stat(FILE_STAT_BASIC_INFORMATION *info, struct _Py_stat_struct *result) { memset(result, 0, sizeof(*result)); result->st_mode = attributes_to_mode(info->FileAttributes); result->st_size = info->EndOfFile.QuadPart; LARGE_INTEGER_to_time_t_nsec(&info->CreationTime, &result->st_birthtime, &result->st_birthtime_nsec); LARGE_INTEGER_to_time_t_nsec(&info->ChangeTime, &result->st_ctime, &result->st_ctime_nsec); LARGE_INTEGER_to_time_t_nsec(&info->LastWriteTime, &result->st_mtime, &result->st_mtime_nsec); LARGE_INTEGER_to_time_t_nsec(&info->LastAccessTime, &result->st_atime, &result->st_atime_nsec); result->st_nlink = info->NumberOfLinks; result->st_dev = info->VolumeSerialNumber.QuadPart; /* File systems with less than 128-bits zero pad into this field */ id_128_to_ino file_id; file_id.id = info->FileId128; result->st_ino = file_id.st_ino; result->st_ino_high = file_id.st_ino_high; /* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will open other name surrogate reparse points without traversing them. To detect/handle these, check st_file_attributes and st_reparse_tag. */ result->st_reparse_tag = info->ReparseTag; if (info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT && info->ReparseTag == IO_REPARSE_TAG_SYMLINK) { /* set the bits that make this a symlink */ result->st_mode = (result->st_mode & ~S_IFMT) | S_IFLNK; } result->st_file_attributes = info->FileAttributes; switch (info->DeviceType) { case FILE_DEVICE_DISK: case FILE_DEVICE_VIRTUAL_DISK: case FILE_DEVICE_DFS: case FILE_DEVICE_CD_ROM: case FILE_DEVICE_CONTROLLER: case FILE_DEVICE_DATALINK: break; case FILE_DEVICE_DISK_FILE_SYSTEM: case FILE_DEVICE_CD_ROM_FILE_SYSTEM: case FILE_DEVICE_NETWORK_FILE_SYSTEM: result->st_mode = (result->st_mode & ~S_IFMT) | 0x6000; /* _S_IFBLK */ break; case FILE_DEVICE_CONSOLE: case FILE_DEVICE_NULL: case FILE_DEVICE_KEYBOARD: case FILE_DEVICE_MODEM: case FILE_DEVICE_MOUSE: case FILE_DEVICE_PARALLEL_PORT: case FILE_DEVICE_PRINTER: case FILE_DEVICE_SCREEN: case FILE_DEVICE_SERIAL_PORT: case FILE_DEVICE_SOUND: result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFCHR; break; case FILE_DEVICE_NAMED_PIPE: result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFIFO; break; default: if (info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) { result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFDIR; } break; } } #endif /* Return information about a file. On POSIX, use fstat(). On Windows, use GetFileType() and GetFileInformationByHandle() which support files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger than 2 GiB 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 information about a file. On POSIX, use fstat(). On Windows, use GetFileType() and GetFileInformationByHandle() which support files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger than 2 GiB 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) { … } /* Like _Py_stat() but with a raw filename. */ int _Py_wstat(const wchar_t* path, struct stat *buf) { … } /* 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) { … } #ifdef MS_WINDOWS // For some Windows API partitions, SetHandleInformation() is declared // but none of the handle flags are defined. #ifndef HANDLE_FLAG_INHERIT #define HANDLE_FLAG_INHERIT … #endif #endif /* This function MUST be kept async-signal-safe on POSIX when raise=0. */ static int get_inheritable(int fd, int raise) { … } /* 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) { … } /* 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) { … } /* Make the file descriptor non-inheritable. Return 0 on success, set errno and return -1 on error. */ static int make_non_inheritable(int fd) { … } /* 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) { … } /* 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) { … } static int _Py_open_impl(const char *pathname, int flags, int gil_held) { … } /* 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) { … } /* 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) { … } /* 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) { … } /* 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) { … } /* 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) { … } static Py_ssize_t _Py_write_impl(int fd, const void *buf, size_t count, int gil_held) { … } /* 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) { … } /* 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) { … } #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 encoding error, on readlink() error, if the internal buffer is too short, on decoding error, or if 'buf' is too short. */ int _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t buflen) { … } #endif #ifdef HAVE_REALPATH /* Return the canonicalized absolute pathname. Encode path to the locale encoding, decode the result from the locale encoding. Return NULL on encoding error, realpath() error, decoding error or if 'resolved_path' is too short. */ wchar_t* _Py_wrealpath(const wchar_t *path, wchar_t *resolved_path, size_t resolved_path_len) { … } #endif int _Py_isabs(const wchar_t *path) { … } /* Get an absolute path. On error (ex: fail to get the current directory), return -1. On memory allocation failure, set *abspath_p to NULL and return 0. On success, return a newly allocated to *abspath_p to and return 0. The string must be freed by PyMem_RawFree(). */ int _Py_abspath(const wchar_t *path, wchar_t **abspath_p) { … } // The Windows Games API family implements the PathCch* APIs in the Xbox OS, // but does not expose them yet. Load them dynamically until // 1) they are officially exposed // 2) we stop supporting older versions of the GDK which do not expose them #if defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP) HRESULT PathCchSkipRoot(const wchar_t *path, const wchar_t **rootEnd) { static int initialized = 0; typedef HRESULT(__stdcall *PPathCchSkipRoot) (PCWSTR pszPath, PCWSTR *ppszRootEnd); static PPathCchSkipRoot _PathCchSkipRoot; if (initialized == 0) { HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); if (pathapi) { _PathCchSkipRoot = (PPathCchSkipRoot)GetProcAddress( pathapi, "PathCchSkipRoot"); } else { _PathCchSkipRoot = NULL; } initialized = 1; } if (!_PathCchSkipRoot) { return E_NOINTERFACE; } return _PathCchSkipRoot(path, rootEnd); } static HRESULT PathCchCombineEx(wchar_t *buffer, size_t bufsize, const wchar_t *dirname, const wchar_t *relfile, unsigned long flags) { static int initialized = 0; typedef HRESULT(__stdcall *PPathCchCombineEx) (PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFlags); static PPathCchCombineEx _PathCchCombineEx; if (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; } initialized = 1; } if (!_PathCchCombineEx) { return E_NOINTERFACE; } return _PathCchCombineEx(buffer, bufsize, dirname, relfile, flags); } #endif /* defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP) */ void _Py_skiproot(const wchar_t *path, Py_ssize_t size, Py_ssize_t *drvsize, Py_ssize_t *rootsize) { … } // The caller must ensure "buffer" is big enough. static int join_relfile(wchar_t *buffer, size_t bufsize, const wchar_t *dirname, const wchar_t *relfile) { … } /* Join the two paths together, like os.path.join(). Return NULL if memory could not be allocated. The caller is responsible for calling PyMem_RawFree() on the result. */ wchar_t * _Py_join_relfile(const wchar_t *dirname, const wchar_t *relfile) { … } /* Join the two paths together, like os.path.join(). dirname: the target buffer with the dirname already in place, including trailing NUL relfile: this must be a relative path bufsize: total allocated size of the buffer Return -1 if anything is wrong with the path lengths. */ int _Py_add_relfile(wchar_t *dirname, const wchar_t *relfile, size_t bufsize) { … } size_t _Py_find_basename(const wchar_t *filename) { … } /* In-place path normalisation. Returns the start of the normalized path, which will be within the original buffer. Guaranteed to not make the path longer, and will not fail. 'size' is the length of the path, if known. If -1, the first null character will be assumed to be the end of the path. 'normsize' will be set to contain the length of the resulting normalized path. */ wchar_t * _Py_normpath_and_size(wchar_t *path, Py_ssize_t size, Py_ssize_t *normsize) { … } /* In-place path normalisation. Returns the start of the normalized path, which will be within the original buffer. Guaranteed to not make the path longer, and will not fail. 'size' is the length of the path, if known. If -1, the first null character will be assumed to be the end of the path. */ wchar_t * _Py_normpath(wchar_t *path, Py_ssize_t size) { … } /* Get the current directory. buflen is the buffer size in wide characters including the null character. Decode the path from the locale encoding. Return NULL on getcwd() error, on decoding error, or if 'buf' is too short. */ wchar_t* _Py_wgetcwd(wchar_t *buf, size_t buflen) { … } /* 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) { … } #ifndef MS_WINDOWS /* 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) { … } /* 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) { … } #else /* MS_WINDOWS */ int _Py_get_blocking(int fd) { HANDLE handle; DWORD mode; BOOL success; handle = _Py_get_osfhandle(fd); if (handle == INVALID_HANDLE_VALUE) { return -1; } Py_BEGIN_ALLOW_THREADS success = GetNamedPipeHandleStateW(handle, &mode, NULL, NULL, NULL, NULL, 0); Py_END_ALLOW_THREADS if (!success) { PyErr_SetFromWindowsErr(0); return -1; } return !(mode & PIPE_NOWAIT); } int _Py_set_blocking(int fd, int blocking) { HANDLE handle; DWORD mode; BOOL success; handle = _Py_get_osfhandle(fd); if (handle == INVALID_HANDLE_VALUE) { return -1; } Py_BEGIN_ALLOW_THREADS success = GetNamedPipeHandleStateW(handle, &mode, NULL, NULL, NULL, NULL, 0); if (success) { if (blocking) { mode &= ~PIPE_NOWAIT; } else { mode |= PIPE_NOWAIT; } success = SetNamedPipeHandleState(handle, &mode, NULL, NULL); } Py_END_ALLOW_THREADS if (!success) { PyErr_SetFromWindowsErr(0); return -1; } return 0; } void* _Py_get_osfhandle_noraise(int fd) { void *handle; _Py_BEGIN_SUPPRESS_IPH handle = (void*)_get_osfhandle(fd); _Py_END_SUPPRESS_IPH return handle; } void* _Py_get_osfhandle(int fd) { void *handle = _Py_get_osfhandle_noraise(fd); if (handle == INVALID_HANDLE_VALUE) PyErr_SetFromErrno(PyExc_OSError); return handle; } int _Py_open_osfhandle_noraise(void *handle, int flags) { int fd; _Py_BEGIN_SUPPRESS_IPH fd = _open_osfhandle((intptr_t)handle, flags); _Py_END_SUPPRESS_IPH return fd; } int _Py_open_osfhandle(void *handle, int flags) { int fd = _Py_open_osfhandle_noraise(handle, flags); if (fd == -1) PyErr_SetFromErrno(PyExc_OSError); return fd; } #endif /* MS_WINDOWS */ int _Py_GetLocaleconvNumeric(struct lconv *lc, PyObject **decimal_point, PyObject **thousands_sep) { … } /* Our selection logic for which function to use is as follows: * 1. If close_range(2) is available, always prefer that; it's better for * contiguous ranges like this than fdwalk(3) which entails iterating over * the entire fd space and simply doing nothing for those outside the range. * 2. If closefrom(2) is available, we'll attempt to use that next if we're * closing up to sysconf(_SC_OPEN_MAX). * 2a. Fallback to fdwalk(3) if we're not closing up to sysconf(_SC_OPEN_MAX), * as that will be more performant if the range happens to have any chunk of * non-opened fd in the middle. * 2b. If fdwalk(3) isn't available, just do a plain close(2) loop. */ #ifdef HAVE_CLOSEFROM #define USE_CLOSEFROM #endif /* HAVE_CLOSEFROM */ #ifdef HAVE_FDWALK #define USE_FDWALK #endif /* HAVE_FDWALK */ #ifdef USE_FDWALK static int _fdwalk_close_func(void *lohi, int fd) { int lo = ((int *)lohi)[0]; int hi = ((int *)lohi)[1]; if (fd >= hi) { return 1; } else if (fd >= lo) { /* Ignore errors */ (void)close(fd); } return 0; } #endif /* USE_FDWALK */ /* Closes all file descriptors in [first, last], ignoring errors. */ void _Py_closerange(int first, int last) { … } #ifndef MS_WINDOWS // Ticks per second used by clock() and times() functions. // See os.times() and time.process_time() implementations. int _Py_GetTicksPerSecond(long *ticks_per_second) { … } #endif /* Check if a file descriptor is valid or not. Return 0 if the file descriptor is invalid, return non-zero otherwise. */ int _Py_IsValidFD(int fd) { … }