You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2280 lines
61 KiB

13 years ago
  1. #include "Python.h"
  2. #include "pycore_fileutils.h" // fileutils definitions
  3. #include "pycore_runtime.h" // _PyRuntime
  4. #include "osdefs.h" // SEP
  5. #include <locale.h>
  6. #ifdef MS_WINDOWS
  7. # include <malloc.h>
  8. # include <windows.h>
  9. extern int winerror_to_errno(int);
  10. #endif
  11. #ifdef HAVE_LANGINFO_H
  12. #include <langinfo.h>
  13. #endif
  14. #ifdef HAVE_SYS_IOCTL_H
  15. #include <sys/ioctl.h>
  16. #endif
  17. #ifdef HAVE_FCNTL_H
  18. #include <fcntl.h>
  19. #endif /* HAVE_FCNTL_H */
  20. #ifdef O_CLOEXEC
  21. /* Does open() support the O_CLOEXEC flag? Possible values:
  22. -1: unknown
  23. 0: open() ignores O_CLOEXEC flag, ex: Linux kernel older than 2.6.23
  24. 1: open() supports O_CLOEXEC flag, close-on-exec is set
  25. The flag is used by _Py_open(), _Py_open_noraise(), io.FileIO
  26. and os.open(). */
  27. int _Py_open_cloexec_works = -1;
  28. #endif
  29. // The value must be the same in unicodeobject.c.
  30. #define MAX_UNICODE 0x10ffff
  31. // mbstowcs() and mbrtowc() errors
  32. static const size_t DECODE_ERROR = ((size_t)-1);
  33. static const size_t INCOMPLETE_CHARACTER = (size_t)-2;
  34. static int
  35. get_surrogateescape(_Py_error_handler errors, int *surrogateescape)
  36. {
  37. switch (errors)
  38. {
  39. case _Py_ERROR_STRICT:
  40. *surrogateescape = 0;
  41. return 0;
  42. case _Py_ERROR_SURROGATEESCAPE:
  43. *surrogateescape = 1;
  44. return 0;
  45. default:
  46. return -1;
  47. }
  48. }
  49. PyObject *
  50. _Py_device_encoding(int fd)
  51. {
  52. int valid;
  53. _Py_BEGIN_SUPPRESS_IPH
  54. valid = isatty(fd);
  55. _Py_END_SUPPRESS_IPH
  56. if (!valid)
  57. Py_RETURN_NONE;
  58. #if defined(MS_WINDOWS)
  59. UINT cp;
  60. if (fd == 0)
  61. cp = GetConsoleCP();
  62. else if (fd == 1 || fd == 2)
  63. cp = GetConsoleOutputCP();
  64. else
  65. cp = 0;
  66. /* GetConsoleCP() and GetConsoleOutputCP() return 0 if the application
  67. has no console */
  68. if (cp == 0) {
  69. Py_RETURN_NONE;
  70. }
  71. return PyUnicode_FromFormat("cp%u", (unsigned int)cp);
  72. #else
  73. return _Py_GetLocaleEncodingObject();
  74. #endif
  75. }
  76. static size_t
  77. is_valid_wide_char(wchar_t ch)
  78. {
  79. if (Py_UNICODE_IS_SURROGATE(ch)) {
  80. // Reject lone surrogate characters
  81. return 0;
  82. }
  83. if (ch > MAX_UNICODE) {
  84. // bpo-35883: Reject characters outside [U+0000; U+10ffff] range.
  85. // The glibc mbstowcs() UTF-8 decoder does not respect the RFC 3629,
  86. // it creates characters outside the [U+0000; U+10ffff] range:
  87. // https://sourceware.org/bugzilla/show_bug.cgi?id=2373
  88. return 0;
  89. }
  90. return 1;
  91. }
  92. static size_t
  93. _Py_mbstowcs(wchar_t *dest, const char *src, size_t n)
  94. {
  95. size_t count = mbstowcs(dest, src, n);
  96. if (dest != NULL && count != DECODE_ERROR) {
  97. for (size_t i=0; i < count; i++) {
  98. wchar_t ch = dest[i];
  99. if (!is_valid_wide_char(ch)) {
  100. return DECODE_ERROR;
  101. }
  102. }
  103. }
  104. return count;
  105. }
  106. #ifdef HAVE_MBRTOWC
  107. static size_t
  108. _Py_mbrtowc(wchar_t *pwc, const char *str, size_t len, mbstate_t *pmbs)
  109. {
  110. assert(pwc != NULL);
  111. size_t count = mbrtowc(pwc, str, len, pmbs);
  112. if (count != 0 && count != DECODE_ERROR && count != INCOMPLETE_CHARACTER) {
  113. if (!is_valid_wide_char(*pwc)) {
  114. return DECODE_ERROR;
  115. }
  116. }
  117. return count;
  118. }
  119. #endif
  120. #if !defined(_Py_FORCE_UTF8_FS_ENCODING) && !defined(MS_WINDOWS)
  121. #define USE_FORCE_ASCII
  122. extern int _Py_normalize_encoding(const char *, char *, size_t);
  123. /* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale
  124. and POSIX locale. nl_langinfo(CODESET) announces an alias of the
  125. ASCII encoding, whereas mbstowcs() and wcstombs() functions use the
  126. ISO-8859-1 encoding. The problem is that os.fsencode() and os.fsdecode() use
  127. locale.getpreferredencoding() codec. For example, if command line arguments
  128. are decoded by mbstowcs() and encoded back by os.fsencode(), we get a
  129. UnicodeEncodeError instead of retrieving the original byte string.
  130. The workaround is enabled if setlocale(LC_CTYPE, NULL) returns "C",
  131. nl_langinfo(CODESET) announces "ascii" (or an alias to ASCII), and at least
  132. one byte in range 0x80-0xff can be decoded from the locale encoding. The
  133. workaround is also enabled on error, for example if getting the locale
  134. failed.
  135. On HP-UX with the C locale or the POSIX locale, nl_langinfo(CODESET)
  136. announces "roman8" but mbstowcs() uses Latin1 in practice. Force also the
  137. ASCII encoding in this case.
  138. Values of force_ascii:
  139. 1: the workaround is used: Py_EncodeLocale() uses
  140. encode_ascii_surrogateescape() and Py_DecodeLocale() uses
  141. decode_ascii()
  142. 0: the workaround is not used: Py_EncodeLocale() uses wcstombs() and
  143. Py_DecodeLocale() uses mbstowcs()
  144. -1: unknown, need to call check_force_ascii() to get the value
  145. */
  146. static int force_ascii = -1;
  147. static int
  148. check_force_ascii(void)
  149. {
  150. char *loc = setlocale(LC_CTYPE, NULL);
  151. if (loc == NULL) {
  152. goto error;
  153. }
  154. if (strcmp(loc, "C") != 0 && strcmp(loc, "POSIX") != 0) {
  155. /* the LC_CTYPE locale is different than C and POSIX */
  156. return 0;
  157. }
  158. #if defined(HAVE_LANGINFO_H) && defined(CODESET)
  159. const char *codeset = nl_langinfo(CODESET);
  160. if (!codeset || codeset[0] == '\0') {
  161. /* CODESET is not set or empty */
  162. goto error;
  163. }
  164. char encoding[20]; /* longest name: "iso_646.irv_1991\0" */
  165. if (!_Py_normalize_encoding(codeset, encoding, sizeof(encoding))) {
  166. goto error;
  167. }
  168. #ifdef __hpux
  169. if (strcmp(encoding, "roman8") == 0) {
  170. unsigned char ch;
  171. wchar_t wch;
  172. size_t res;
  173. ch = (unsigned char)0xA7;
  174. res = _Py_mbstowcs(&wch, (char*)&ch, 1);
  175. if (res != DECODE_ERROR && wch == L'\xA7') {
  176. /* On HP-UX withe C locale or the POSIX locale,
  177. nl_langinfo(CODESET) announces "roman8", whereas mbstowcs() uses
  178. Latin1 encoding in practice. Force ASCII in this case.
  179. Roman8 decodes 0xA7 to U+00CF. Latin1 decodes 0xA7 to U+00A7. */
  180. return 1;
  181. }
  182. }
  183. #else
  184. const char* ascii_aliases[] = {
  185. "ascii",
  186. /* Aliases from Lib/encodings/aliases.py */
  187. "646",
  188. "ansi_x3.4_1968",
  189. "ansi_x3.4_1986",
  190. "ansi_x3_4_1968",
  191. "cp367",
  192. "csascii",
  193. "ibm367",
  194. "iso646_us",
  195. "iso_646.irv_1991",
  196. "iso_ir_6",
  197. "us",
  198. "us_ascii",
  199. NULL
  200. };
  201. int is_ascii = 0;
  202. for (const char **alias=ascii_aliases; *alias != NULL; alias++) {
  203. if (strcmp(encoding, *alias) == 0) {
  204. is_ascii = 1;
  205. break;
  206. }
  207. }
  208. if (!is_ascii) {
  209. /* nl_langinfo(CODESET) is not "ascii" or an alias of ASCII */
  210. return 0;
  211. }
  212. for (unsigned int i=0x80; i<=0xff; i++) {
  213. char ch[1];
  214. wchar_t wch[1];
  215. size_t res;
  216. unsigned uch = (unsigned char)i;
  217. ch[0] = (char)uch;
  218. res = _Py_mbstowcs(wch, ch, 1);
  219. if (res != DECODE_ERROR) {
  220. /* decoding a non-ASCII character from the locale encoding succeed:
  221. the locale encoding is not ASCII, force ASCII */
  222. return 1;
  223. }
  224. }
  225. /* None of the bytes in the range 0x80-0xff can be decoded from the locale
  226. encoding: the locale encoding is really ASCII */
  227. #endif /* !defined(__hpux) */
  228. return 0;
  229. #else
  230. /* nl_langinfo(CODESET) is not available: always force ASCII */
  231. return 1;
  232. #endif /* defined(HAVE_LANGINFO_H) && defined(CODESET) */
  233. error:
  234. /* if an error occurred, force the ASCII encoding */
  235. return 1;
  236. }
  237. int
  238. _Py_GetForceASCII(void)
  239. {
  240. if (force_ascii == -1) {
  241. force_ascii = check_force_ascii();
  242. }
  243. return force_ascii;
  244. }
  245. void
  246. _Py_ResetForceASCII(void)
  247. {
  248. force_ascii = -1;
  249. }
  250. static int
  251. encode_ascii(const wchar_t *text, char **str,
  252. size_t *error_pos, const char **reason,
  253. int raw_malloc, _Py_error_handler errors)
  254. {
  255. char *result = NULL, *out;
  256. size_t len, i;
  257. wchar_t ch;
  258. int surrogateescape;
  259. if (get_surrogateescape(errors, &surrogateescape) < 0) {
  260. return -3;
  261. }
  262. len = wcslen(text);
  263. /* +1 for NULL byte */
  264. if (raw_malloc) {
  265. result = PyMem_RawMalloc(len + 1);
  266. }
  267. else {
  268. result = PyMem_Malloc(len + 1);
  269. }
  270. if (result == NULL) {
  271. return -1;
  272. }
  273. out = result;
  274. for (i=0; i<len; i++) {
  275. ch = text[i];
  276. if (ch <= 0x7f) {
  277. /* ASCII character */
  278. *out++ = (char)ch;
  279. }
  280. else if (surrogateescape && 0xdc80 <= ch && ch <= 0xdcff) {
  281. /* UTF-8b surrogate */
  282. *out++ = (char)(ch - 0xdc00);
  283. }
  284. else {
  285. if (raw_malloc) {
  286. PyMem_RawFree(result);
  287. }
  288. else {
  289. PyMem_Free(result);
  290. }
  291. if (error_pos != NULL) {
  292. *error_pos = i;
  293. }
  294. if (reason) {
  295. *reason = "encoding error";
  296. }
  297. return -2;
  298. }
  299. }
  300. *out = '\0';
  301. *str = result;
  302. return 0;
  303. }
  304. #else
  305. int
  306. _Py_GetForceASCII(void)
  307. {
  308. return 0;
  309. }
  310. void
  311. _Py_ResetForceASCII(void)
  312. {
  313. /* nothing to do */
  314. }
  315. #endif /* !defined(_Py_FORCE_UTF8_FS_ENCODING) && !defined(MS_WINDOWS) */
  316. #if !defined(HAVE_MBRTOWC) || defined(USE_FORCE_ASCII)
  317. static int
  318. decode_ascii(const char *arg, wchar_t **wstr, size_t *wlen,
  319. const char **reason, _Py_error_handler errors)
  320. {
  321. wchar_t *res;
  322. unsigned char *in;
  323. wchar_t *out;
  324. size_t argsize = strlen(arg) + 1;
  325. int surrogateescape;
  326. if (get_surrogateescape(errors, &surrogateescape) < 0) {
  327. return -3;
  328. }
  329. if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  330. return -1;
  331. }
  332. res = PyMem_RawMalloc(argsize * sizeof(wchar_t));
  333. if (!res) {
  334. return -1;
  335. }
  336. out = res;
  337. for (in = (unsigned char*)arg; *in; in++) {
  338. unsigned char ch = *in;
  339. if (ch < 128) {
  340. *out++ = ch;
  341. }
  342. else {
  343. if (!surrogateescape) {
  344. PyMem_RawFree(res);
  345. if (wlen) {
  346. *wlen = in - (unsigned char*)arg;
  347. }
  348. if (reason) {
  349. *reason = "decoding error";
  350. }
  351. return -2;
  352. }
  353. *out++ = 0xdc00 + ch;
  354. }
  355. }
  356. *out = 0;
  357. if (wlen != NULL) {
  358. *wlen = out - res;
  359. }
  360. *wstr = res;
  361. return 0;
  362. }
  363. #endif /* !HAVE_MBRTOWC */
  364. static int
  365. decode_current_locale(const char* arg, wchar_t **wstr, size_t *wlen,
  366. const char **reason, _Py_error_handler errors)
  367. {
  368. wchar_t *res;
  369. size_t argsize;
  370. size_t count;
  371. #ifdef HAVE_MBRTOWC
  372. unsigned char *in;
  373. wchar_t *out;
  374. mbstate_t mbs;
  375. #endif
  376. int surrogateescape;
  377. if (get_surrogateescape(errors, &surrogateescape) < 0) {
  378. return -3;
  379. }
  380. #ifdef HAVE_BROKEN_MBSTOWCS
  381. /* Some platforms have a broken implementation of
  382. * mbstowcs which does not count the characters that
  383. * would result from conversion. Use an upper bound.
  384. */
  385. argsize = strlen(arg);
  386. #else
  387. argsize = _Py_mbstowcs(NULL, arg, 0);
  388. #endif
  389. if (argsize != DECODE_ERROR) {
  390. if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
  391. return -1;
  392. }
  393. res = (wchar_t *)PyMem_RawMalloc((argsize + 1) * sizeof(wchar_t));
  394. if (!res) {
  395. return -1;
  396. }
  397. count = _Py_mbstowcs(res, arg, argsize + 1);
  398. if (count != DECODE_ERROR) {
  399. *wstr = res;
  400. if (wlen != NULL) {
  401. *wlen = count;
  402. }
  403. return 0;
  404. }
  405. PyMem_RawFree(res);
  406. }
  407. /* Conversion failed. Fall back to escaping with surrogateescape. */
  408. #ifdef HAVE_MBRTOWC
  409. /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
  410. /* Overallocate; as multi-byte characters are in the argument, the
  411. actual output could use less memory. */
  412. argsize = strlen(arg) + 1;
  413. if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  414. return -1;
  415. }
  416. res = (wchar_t*)PyMem_RawMalloc(argsize * sizeof(wchar_t));
  417. if (!res) {
  418. return -1;
  419. }
  420. in = (unsigned char*)arg;
  421. out = res;
  422. memset(&mbs, 0, sizeof mbs);
  423. while (argsize) {
  424. size_t converted = _Py_mbrtowc(out, (char*)in, argsize, &mbs);
  425. if (converted == 0) {
  426. /* Reached end of string; null char stored. */
  427. break;
  428. }
  429. if (converted == INCOMPLETE_CHARACTER) {
  430. /* Incomplete character. This should never happen,
  431. since we provide everything that we have -
  432. unless there is a bug in the C library, or I
  433. misunderstood how mbrtowc works. */
  434. goto decode_error;
  435. }
  436. if (converted == DECODE_ERROR) {
  437. if (!surrogateescape) {
  438. goto decode_error;
  439. }
  440. /* Decoding error. Escape as UTF-8b, and start over in the initial
  441. shift state. */
  442. *out++ = 0xdc00 + *in++;
  443. argsize--;
  444. memset(&mbs, 0, sizeof mbs);
  445. continue;
  446. }
  447. // _Py_mbrtowc() reject lone surrogate characters
  448. assert(!Py_UNICODE_IS_SURROGATE(*out));
  449. /* successfully converted some bytes */
  450. in += converted;
  451. argsize -= converted;
  452. out++;
  453. }
  454. if (wlen != NULL) {
  455. *wlen = out - res;
  456. }
  457. *wstr = res;
  458. return 0;
  459. decode_error:
  460. PyMem_RawFree(res);
  461. if (wlen) {
  462. *wlen = in - (unsigned char*)arg;
  463. }
  464. if (reason) {
  465. *reason = "decoding error";
  466. }
  467. return -2;
  468. #else /* HAVE_MBRTOWC */
  469. /* Cannot use C locale for escaping; manually escape as if charset
  470. is ASCII (i.e. escape all bytes > 128. This will still roundtrip
  471. correctly in the locale's charset, which must be an ASCII superset. */
  472. return decode_ascii(arg, wstr, wlen, reason, errors);
  473. #endif /* HAVE_MBRTOWC */
  474. }
  475. /* Decode a byte string from the locale encoding.
  476. Use the strict error handler if 'surrogateescape' is zero. Use the
  477. surrogateescape error handler if 'surrogateescape' is non-zero: undecodable
  478. bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence
  479. can be decoded as a surrogate character, escape the bytes using the
  480. surrogateescape error handler instead of decoding them.
  481. On success, return 0 and write the newly allocated wide character string into
  482. *wstr (use PyMem_RawFree() to free the memory). If wlen is not NULL, write
  483. the number of wide characters excluding the null character into *wlen.
  484. On memory allocation failure, return -1.
  485. On decoding error, return -2. If wlen is not NULL, write the start of
  486. invalid byte sequence in the input string into *wlen. If reason is not NULL,
  487. write the decoding error message into *reason.
  488. Return -3 if the error handler 'errors' is not supported.
  489. Use the Py_EncodeLocaleEx() function to encode the character string back to
  490. a byte string. */
  491. int
  492. _Py_DecodeLocaleEx(const char* arg, wchar_t **wstr, size_t *wlen,
  493. const char **reason,
  494. int current_locale, _Py_error_handler errors)
  495. {
  496. if (current_locale) {
  497. #ifdef _Py_FORCE_UTF8_LOCALE
  498. return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
  499. errors);
  500. #else
  501. return decode_current_locale(arg, wstr, wlen, reason, errors);
  502. #endif
  503. }
  504. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  505. return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
  506. errors);
  507. #else
  508. int use_utf8 = (Py_UTF8Mode == 1);
  509. #ifdef MS_WINDOWS
  510. use_utf8 |= !Py_LegacyWindowsFSEncodingFlag;
  511. #endif
  512. if (use_utf8) {
  513. return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
  514. errors);
  515. }
  516. #ifdef USE_FORCE_ASCII
  517. if (force_ascii == -1) {
  518. force_ascii = check_force_ascii();
  519. }
  520. if (force_ascii) {
  521. /* force ASCII encoding to workaround mbstowcs() issue */
  522. return decode_ascii(arg, wstr, wlen, reason, errors);
  523. }
  524. #endif
  525. return decode_current_locale(arg, wstr, wlen, reason, errors);
  526. #endif /* !_Py_FORCE_UTF8_FS_ENCODING */
  527. }
  528. /* Decode a byte string from the locale encoding with the
  529. surrogateescape error handler: undecodable bytes are decoded as characters
  530. in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate
  531. character, escape the bytes using the surrogateescape error handler instead
  532. of decoding them.
  533. Return a pointer to a newly allocated wide character string, use
  534. PyMem_RawFree() to free the memory. If size is not NULL, write the number of
  535. wide characters excluding the null character into *size
  536. Return NULL on decoding error or memory allocation error. If *size* is not
  537. NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on
  538. decoding error.
  539. Decoding errors should never happen, unless there is a bug in the C
  540. library.
  541. Use the Py_EncodeLocale() function to encode the character string back to a
  542. byte string. */
  543. wchar_t*
  544. Py_DecodeLocale(const char* arg, size_t *wlen)
  545. {
  546. wchar_t *wstr;
  547. int res = _Py_DecodeLocaleEx(arg, &wstr, wlen,
  548. NULL, 0,
  549. _Py_ERROR_SURROGATEESCAPE);
  550. if (res != 0) {
  551. assert(res != -3);
  552. if (wlen != NULL) {
  553. *wlen = (size_t)res;
  554. }
  555. return NULL;
  556. }
  557. return wstr;
  558. }
  559. static int
  560. encode_current_locale(const wchar_t *text, char **str,
  561. size_t *error_pos, const char **reason,
  562. int raw_malloc, _Py_error_handler errors)
  563. {
  564. const size_t len = wcslen(text);
  565. char *result = NULL, *bytes = NULL;
  566. size_t i, size, converted;
  567. wchar_t c, buf[2];
  568. int surrogateescape;
  569. if (get_surrogateescape(errors, &surrogateescape) < 0) {
  570. return -3;
  571. }
  572. /* The function works in two steps:
  573. 1. compute the length of the output buffer in bytes (size)
  574. 2. outputs the bytes */
  575. size = 0;
  576. buf[1] = 0;
  577. while (1) {
  578. for (i=0; i < len; i++) {
  579. c = text[i];
  580. if (c >= 0xdc80 && c <= 0xdcff) {
  581. if (!surrogateescape) {
  582. goto encode_error;
  583. }
  584. /* UTF-8b surrogate */
  585. if (bytes != NULL) {
  586. *bytes++ = c - 0xdc00;
  587. size--;
  588. }
  589. else {
  590. size++;
  591. }
  592. continue;
  593. }
  594. else {
  595. buf[0] = c;
  596. if (bytes != NULL) {
  597. converted = wcstombs(bytes, buf, size);
  598. }
  599. else {
  600. converted = wcstombs(NULL, buf, 0);
  601. }
  602. if (converted == DECODE_ERROR) {
  603. goto encode_error;
  604. }
  605. if (bytes != NULL) {
  606. bytes += converted;
  607. size -= converted;
  608. }
  609. else {
  610. size += converted;
  611. }
  612. }
  613. }
  614. if (result != NULL) {
  615. *bytes = '\0';
  616. break;
  617. }
  618. size += 1; /* nul byte at the end */
  619. if (raw_malloc) {
  620. result = PyMem_RawMalloc(size);
  621. }
  622. else {
  623. result = PyMem_Malloc(size);
  624. }
  625. if (result == NULL) {
  626. return -1;
  627. }
  628. bytes = result;
  629. }
  630. *str = result;
  631. return 0;
  632. encode_error:
  633. if (raw_malloc) {
  634. PyMem_RawFree(result);
  635. }
  636. else {
  637. PyMem_Free(result);
  638. }
  639. if (error_pos != NULL) {
  640. *error_pos = i;
  641. }
  642. if (reason) {
  643. *reason = "encoding error";
  644. }
  645. return -2;
  646. }
  647. /* Encode a string to the locale encoding.
  648. Parameters:
  649. * raw_malloc: if non-zero, allocate memory using PyMem_RawMalloc() instead
  650. of PyMem_Malloc().
  651. * current_locale: if non-zero, use the current LC_CTYPE, otherwise use
  652. Python filesystem encoding.
  653. * errors: error handler like "strict" or "surrogateescape".
  654. Return value:
  655. 0: success, *str is set to a newly allocated decoded string.
  656. -1: memory allocation failure
  657. -2: encoding error, set *error_pos and *reason (if set).
  658. -3: the error handler 'errors' is not supported.
  659. */
  660. static int
  661. encode_locale_ex(const wchar_t *text, char **str, size_t *error_pos,
  662. const char **reason,
  663. int raw_malloc, int current_locale, _Py_error_handler errors)
  664. {
  665. if (current_locale) {
  666. #ifdef _Py_FORCE_UTF8_LOCALE
  667. return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
  668. raw_malloc, errors);
  669. #else
  670. return encode_current_locale(text, str, error_pos, reason,
  671. raw_malloc, errors);
  672. #endif
  673. }
  674. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  675. return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
  676. raw_malloc, errors);
  677. #else
  678. int use_utf8 = (Py_UTF8Mode == 1);
  679. #ifdef MS_WINDOWS
  680. use_utf8 |= !Py_LegacyWindowsFSEncodingFlag;
  681. #endif
  682. if (use_utf8) {
  683. return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
  684. raw_malloc, errors);
  685. }
  686. #ifdef USE_FORCE_ASCII
  687. if (force_ascii == -1) {
  688. force_ascii = check_force_ascii();
  689. }
  690. if (force_ascii) {
  691. return encode_ascii(text, str, error_pos, reason,
  692. raw_malloc, errors);
  693. }
  694. #endif
  695. return encode_current_locale(text, str, error_pos, reason,
  696. raw_malloc, errors);
  697. #endif /* _Py_FORCE_UTF8_FS_ENCODING */
  698. }
  699. static char*
  700. encode_locale(const wchar_t *text, size_t *error_pos,
  701. int raw_malloc, int current_locale)
  702. {
  703. char *str;
  704. int res = encode_locale_ex(text, &str, error_pos, NULL,
  705. raw_malloc, current_locale,
  706. _Py_ERROR_SURROGATEESCAPE);
  707. if (res != -2 && error_pos) {
  708. *error_pos = (size_t)-1;
  709. }
  710. if (res != 0) {
  711. return NULL;
  712. }
  713. return str;
  714. }
  715. /* Encode a wide character string to the locale encoding with the
  716. surrogateescape error handler: surrogate characters in the range
  717. U+DC80..U+DCFF are converted to bytes 0x80..0xFF.
  718. Return a pointer to a newly allocated byte string, use PyMem_Free() to free
  719. the memory. Return NULL on encoding or memory allocation error.
  720. If error_pos is not NULL, *error_pos is set to (size_t)-1 on success, or set
  721. to the index of the invalid character on encoding error.
  722. Use the Py_DecodeLocale() function to decode the bytes string back to a wide
  723. character string. */
  724. char*
  725. Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
  726. {
  727. return encode_locale(text, error_pos, 0, 0);
  728. }
  729. /* Similar to Py_EncodeLocale(), but result must be freed by PyMem_RawFree()
  730. instead of PyMem_Free(). */
  731. char*
  732. _Py_EncodeLocaleRaw(const wchar_t *text, size_t *error_pos)
  733. {
  734. return encode_locale(text, error_pos, 1, 0);
  735. }
  736. int
  737. _Py_EncodeLocaleEx(const wchar_t *text, char **str,
  738. size_t *error_pos, const char **reason,
  739. int current_locale, _Py_error_handler errors)
  740. {
  741. return encode_locale_ex(text, str, error_pos, reason, 1,
  742. current_locale, errors);
  743. }
  744. // Get the current locale encoding name:
  745. //
  746. // - Return "UTF-8" if _Py_FORCE_UTF8_LOCALE macro is defined (ex: on Android)
  747. // - Return "UTF-8" if the UTF-8 Mode is enabled
  748. // - On Windows, return the ANSI code page (ex: "cp1250")
  749. // - Return "UTF-8" if nl_langinfo(CODESET) returns an empty string.
  750. // - Otherwise, return nl_langinfo(CODESET).
  751. //
  752. // Return NULL on memory allocation failure.
  753. //
  754. // See also config_get_locale_encoding()
  755. wchar_t*
  756. _Py_GetLocaleEncoding(void)
  757. {
  758. #ifdef _Py_FORCE_UTF8_LOCALE
  759. // On Android langinfo.h and CODESET are missing,
  760. // and UTF-8 is always used in mbstowcs() and wcstombs().
  761. return _PyMem_RawWcsdup(L"UTF-8");
  762. #else
  763. const PyPreConfig *preconfig = &_PyRuntime.preconfig;
  764. if (preconfig->utf8_mode) {
  765. return _PyMem_RawWcsdup(L"UTF-8");
  766. }
  767. #ifdef MS_WINDOWS
  768. wchar_t encoding[23];
  769. unsigned int ansi_codepage = GetACP();
  770. swprintf(encoding, Py_ARRAY_LENGTH(encoding), L"cp%u", ansi_codepage);
  771. encoding[Py_ARRAY_LENGTH(encoding) - 1] = 0;
  772. return _PyMem_RawWcsdup(encoding);
  773. #else
  774. const char *encoding = nl_langinfo(CODESET);
  775. if (!encoding || encoding[0] == '\0') {
  776. // Use UTF-8 if nl_langinfo() returns an empty string. It can happen on
  777. // macOS if the LC_CTYPE locale is not supported.
  778. return _PyMem_RawWcsdup(L"UTF-8");
  779. }
  780. wchar_t *wstr;
  781. int res = decode_current_locale(encoding, &wstr, NULL,
  782. NULL, _Py_ERROR_SURROGATEESCAPE);
  783. if (res < 0) {
  784. return NULL;
  785. }
  786. return wstr;
  787. #endif // !MS_WINDOWS
  788. #endif // !_Py_FORCE_UTF8_LOCALE
  789. }
  790. PyObject *
  791. _Py_GetLocaleEncodingObject(void)
  792. {
  793. wchar_t *encoding = _Py_GetLocaleEncoding();
  794. if (encoding == NULL) {
  795. PyErr_NoMemory();
  796. return NULL;
  797. }
  798. PyObject *str = PyUnicode_FromWideChar(encoding, -1);
  799. PyMem_RawFree(encoding);
  800. return str;
  801. }
  802. #ifdef MS_WINDOWS
  803. static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
  804. static void
  805. FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
  806. {
  807. /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
  808. /* Cannot simply cast and dereference in_ptr,
  809. since it might not be aligned properly */
  810. __int64 in;
  811. memcpy(&in, in_ptr, sizeof(in));
  812. *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
  813. *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
  814. }
  815. void
  816. _Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
  817. {
  818. /* XXX endianness */
  819. __int64 out;
  820. out = time_in + secs_between_epochs;
  821. out = out * 10000000 + nsec_in / 100;
  822. memcpy(out_ptr, &out, sizeof(out));
  823. }
  824. /* Below, we *know* that ugo+r is 0444 */
  825. #if _S_IREAD != 0400
  826. #error Unsupported C library
  827. #endif
  828. static int
  829. attributes_to_mode(DWORD attr)
  830. {
  831. int m = 0;
  832. if (attr & FILE_ATTRIBUTE_DIRECTORY)
  833. m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
  834. else
  835. m |= _S_IFREG;
  836. if (attr & FILE_ATTRIBUTE_READONLY)
  837. m |= 0444;
  838. else
  839. m |= 0666;
  840. return m;
  841. }
  842. void
  843. _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
  844. struct _Py_stat_struct *result)
  845. {
  846. memset(result, 0, sizeof(*result));
  847. result->st_mode = attributes_to_mode(info->dwFileAttributes);
  848. result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
  849. result->st_dev = info->dwVolumeSerialNumber;
  850. result->st_rdev = result->st_dev;
  851. FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
  852. FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  853. FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  854. result->st_nlink = info->nNumberOfLinks;
  855. result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow;
  856. /* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will
  857. open other name surrogate reparse points without traversing them. To
  858. detect/handle these, check st_file_attributes and st_reparse_tag. */
  859. result->st_reparse_tag = reparse_tag;
  860. if (info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
  861. reparse_tag == IO_REPARSE_TAG_SYMLINK) {
  862. /* first clear the S_IFMT bits */
  863. result->st_mode ^= (result->st_mode & S_IFMT);
  864. /* now set the bits that make this a symlink */
  865. result->st_mode |= S_IFLNK;
  866. }
  867. result->st_file_attributes = info->dwFileAttributes;
  868. }
  869. #endif
  870. /* Return information about a file.
  871. On POSIX, use fstat().
  872. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  873. files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
  874. than 2 GiB because the file size type is a signed 32-bit integer: see issue
  875. #23152.
  876. On Windows, set the last Windows error and return nonzero on error. On
  877. POSIX, set errno and return nonzero on error. Fill status and return 0 on
  878. success. */
  879. int
  880. _Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
  881. {
  882. #ifdef MS_WINDOWS
  883. BY_HANDLE_FILE_INFORMATION info;
  884. HANDLE h;
  885. int type;
  886. _Py_BEGIN_SUPPRESS_IPH
  887. h = (HANDLE)_get_osfhandle(fd);
  888. _Py_END_SUPPRESS_IPH
  889. if (h == INVALID_HANDLE_VALUE) {
  890. /* errno is already set by _get_osfhandle, but we also set
  891. the Win32 error for callers who expect that */
  892. SetLastError(ERROR_INVALID_HANDLE);
  893. return -1;
  894. }
  895. memset(status, 0, sizeof(*status));
  896. type = GetFileType(h);
  897. if (type == FILE_TYPE_UNKNOWN) {
  898. DWORD error = GetLastError();
  899. if (error != 0) {
  900. errno = winerror_to_errno(error);
  901. return -1;
  902. }
  903. /* else: valid but unknown file */
  904. }
  905. if (type != FILE_TYPE_DISK) {
  906. if (type == FILE_TYPE_CHAR)
  907. status->st_mode = _S_IFCHR;
  908. else if (type == FILE_TYPE_PIPE)
  909. status->st_mode = _S_IFIFO;
  910. return 0;
  911. }
  912. if (!GetFileInformationByHandle(h, &info)) {
  913. /* The Win32 error is already set, but we also set errno for
  914. callers who expect it */
  915. errno = winerror_to_errno(GetLastError());
  916. return -1;
  917. }
  918. _Py_attribute_data_to_stat(&info, 0, status);
  919. /* specific to fstat() */
  920. status->st_ino = (((uint64_t)info.nFileIndexHigh) << 32) + info.nFileIndexLow;
  921. return 0;
  922. #else
  923. return fstat(fd, status);
  924. #endif
  925. }
  926. /* Return information about a file.
  927. On POSIX, use fstat().
  928. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  929. files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
  930. than 2 GiB because the file size type is a signed 32-bit integer: see issue
  931. #23152.
  932. Raise an exception and return -1 on error. On Windows, set the last Windows
  933. error on error. On POSIX, set errno on error. Fill status and return 0 on
  934. success.
  935. Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
  936. to call fstat(). The caller must hold the GIL. */
  937. int
  938. _Py_fstat(int fd, struct _Py_stat_struct *status)
  939. {
  940. int res;
  941. assert(PyGILState_Check());
  942. Py_BEGIN_ALLOW_THREADS
  943. res = _Py_fstat_noraise(fd, status);
  944. Py_END_ALLOW_THREADS
  945. if (res != 0) {
  946. #ifdef MS_WINDOWS
  947. PyErr_SetFromWindowsErr(0);
  948. #else
  949. PyErr_SetFromErrno(PyExc_OSError);
  950. #endif
  951. return -1;
  952. }
  953. return 0;
  954. }
  955. /* Call _wstat() on Windows, or encode the path to the filesystem encoding and
  956. call stat() otherwise. Only fill st_mode attribute on Windows.
  957. Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
  958. raised. */
  959. int
  960. _Py_stat(PyObject *path, struct stat *statbuf)
  961. {
  962. #ifdef MS_WINDOWS
  963. int err;
  964. struct _stat wstatbuf;
  965. #if USE_UNICODE_WCHAR_CACHE
  966. const wchar_t *wpath = _PyUnicode_AsUnicode(path);
  967. #else /* USE_UNICODE_WCHAR_CACHE */
  968. wchar_t *wpath = PyUnicode_AsWideCharString(path, NULL);
  969. #endif /* USE_UNICODE_WCHAR_CACHE */
  970. if (wpath == NULL)
  971. return -2;
  972. err = _wstat(wpath, &wstatbuf);
  973. if (!err)
  974. statbuf->st_mode = wstatbuf.st_mode;
  975. #if !USE_UNICODE_WCHAR_CACHE
  976. PyMem_Free(wpath);
  977. #endif /* USE_UNICODE_WCHAR_CACHE */
  978. return err;
  979. #else
  980. int ret;
  981. PyObject *bytes;
  982. char *cpath;
  983. bytes = PyUnicode_EncodeFSDefault(path);
  984. if (bytes == NULL)
  985. return -2;
  986. /* check for embedded null bytes */
  987. if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
  988. Py_DECREF(bytes);
  989. return -2;
  990. }
  991. ret = stat(cpath, statbuf);
  992. Py_DECREF(bytes);
  993. return ret;
  994. #endif
  995. }
  996. /* This function MUST be kept async-signal-safe on POSIX when raise=0. */
  997. static int
  998. get_inheritable(int fd, int raise)
  999. {
  1000. #ifdef MS_WINDOWS
  1001. HANDLE handle;
  1002. DWORD flags;
  1003. _Py_BEGIN_SUPPRESS_IPH
  1004. handle = (HANDLE)_get_osfhandle(fd);
  1005. _Py_END_SUPPRESS_IPH
  1006. if (handle == INVALID_HANDLE_VALUE) {
  1007. if (raise)
  1008. PyErr_SetFromErrno(PyExc_OSError);
  1009. return -1;
  1010. }
  1011. if (!GetHandleInformation(handle, &flags)) {
  1012. if (raise)
  1013. PyErr_SetFromWindowsErr(0);
  1014. return -1;
  1015. }
  1016. return (flags & HANDLE_FLAG_INHERIT);
  1017. #else
  1018. int flags;
  1019. flags = fcntl(fd, F_GETFD, 0);
  1020. if (flags == -1) {
  1021. if (raise)
  1022. PyErr_SetFromErrno(PyExc_OSError);
  1023. return -1;
  1024. }
  1025. return !(flags & FD_CLOEXEC);
  1026. #endif
  1027. }
  1028. /* Get the inheritable flag of the specified file descriptor.
  1029. Return 1 if the file descriptor can be inherited, 0 if it cannot,
  1030. raise an exception and return -1 on error. */
  1031. int
  1032. _Py_get_inheritable(int fd)
  1033. {
  1034. return get_inheritable(fd, 1);
  1035. }
  1036. /* This function MUST be kept async-signal-safe on POSIX when raise=0. */
  1037. static int
  1038. set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
  1039. {
  1040. #ifdef MS_WINDOWS
  1041. HANDLE handle;
  1042. DWORD flags;
  1043. #else
  1044. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  1045. static int ioctl_works = -1;
  1046. int request;
  1047. int err;
  1048. #endif
  1049. int flags, new_flags;
  1050. int res;
  1051. #endif
  1052. /* atomic_flag_works can only be used to make the file descriptor
  1053. non-inheritable */
  1054. assert(!(atomic_flag_works != NULL && inheritable));
  1055. if (atomic_flag_works != NULL && !inheritable) {
  1056. if (*atomic_flag_works == -1) {
  1057. int isInheritable = get_inheritable(fd, raise);
  1058. if (isInheritable == -1)
  1059. return -1;
  1060. *atomic_flag_works = !isInheritable;
  1061. }
  1062. if (*atomic_flag_works)
  1063. return 0;
  1064. }
  1065. #ifdef MS_WINDOWS
  1066. _Py_BEGIN_SUPPRESS_IPH
  1067. handle = (HANDLE)_get_osfhandle(fd);
  1068. _Py_END_SUPPRESS_IPH
  1069. if (handle == INVALID_HANDLE_VALUE) {
  1070. if (raise)
  1071. PyErr_SetFromErrno(PyExc_OSError);
  1072. return -1;
  1073. }
  1074. if (inheritable)
  1075. flags = HANDLE_FLAG_INHERIT;
  1076. else
  1077. flags = 0;
  1078. /* This check can be removed once support for Windows 7 ends. */
  1079. #define CONSOLE_PSEUDOHANDLE(handle) (((ULONG_PTR)(handle) & 0x3) == 0x3 && \
  1080. GetFileType(handle) == FILE_TYPE_CHAR)
  1081. if (!CONSOLE_PSEUDOHANDLE(handle) &&
  1082. !SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
  1083. if (raise)
  1084. PyErr_SetFromWindowsErr(0);
  1085. return -1;
  1086. }
  1087. #undef CONSOLE_PSEUDOHANDLE
  1088. return 0;
  1089. #else
  1090. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  1091. if (ioctl_works != 0 && raise != 0) {
  1092. /* fast-path: ioctl() only requires one syscall */
  1093. /* caveat: raise=0 is an indicator that we must be async-signal-safe
  1094. * thus avoid using ioctl() so we skip the fast-path. */
  1095. if (inheritable)
  1096. request = FIONCLEX;
  1097. else
  1098. request = FIOCLEX;
  1099. err = ioctl(fd, request, NULL);
  1100. if (!err) {
  1101. ioctl_works = 1;
  1102. return 0;
  1103. }
  1104. #ifdef __linux__
  1105. if (errno == EBADF) {
  1106. // On Linux, ioctl(FIOCLEX) will fail with EBADF for O_PATH file descriptors
  1107. // Fall through to the fcntl() path
  1108. }
  1109. else
  1110. #endif
  1111. if (errno != ENOTTY && errno != EACCES) {
  1112. if (raise)
  1113. PyErr_SetFromErrno(PyExc_OSError);
  1114. return -1;
  1115. }
  1116. else {
  1117. /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
  1118. device". The ioctl is declared but not supported by the kernel.
  1119. Remember that ioctl() doesn't work. It is the case on
  1120. Illumos-based OS for example.
  1121. Issue #27057: When SELinux policy disallows ioctl it will fail
  1122. with EACCES. While FIOCLEX is safe operation it may be
  1123. unavailable because ioctl was denied altogether.
  1124. This can be the case on Android. */
  1125. ioctl_works = 0;
  1126. }
  1127. /* fallback to fcntl() if ioctl() does not work */
  1128. }
  1129. #endif
  1130. /* slow-path: fcntl() requires two syscalls */
  1131. flags = fcntl(fd, F_GETFD);
  1132. if (flags < 0) {
  1133. if (raise)
  1134. PyErr_SetFromErrno(PyExc_OSError);
  1135. return -1;
  1136. }
  1137. if (inheritable) {
  1138. new_flags = flags & ~FD_CLOEXEC;
  1139. }
  1140. else {
  1141. new_flags = flags | FD_CLOEXEC;
  1142. }
  1143. if (new_flags == flags) {
  1144. /* FD_CLOEXEC flag already set/cleared: nothing to do */
  1145. return 0;
  1146. }
  1147. res = fcntl(fd, F_SETFD, new_flags);
  1148. if (res < 0) {
  1149. if (raise)
  1150. PyErr_SetFromErrno(PyExc_OSError);
  1151. return -1;
  1152. }
  1153. return 0;
  1154. #endif
  1155. }
  1156. /* Make the file descriptor non-inheritable.
  1157. Return 0 on success, set errno and return -1 on error. */
  1158. static int
  1159. make_non_inheritable(int fd)
  1160. {
  1161. return set_inheritable(fd, 0, 0, NULL);
  1162. }
  1163. /* Set the inheritable flag of the specified file descriptor.
  1164. On success: return 0, on error: raise an exception and return -1.
  1165. If atomic_flag_works is not NULL:
  1166. * if *atomic_flag_works==-1, check if the inheritable is set on the file
  1167. descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
  1168. set the inheritable flag
  1169. * if *atomic_flag_works==1: do nothing
  1170. * if *atomic_flag_works==0: set inheritable flag to False
  1171. Set atomic_flag_works to NULL if no atomic flag was used to create the
  1172. file descriptor.
  1173. atomic_flag_works can only be used to make a file descriptor
  1174. non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
  1175. int
  1176. _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
  1177. {
  1178. return set_inheritable(fd, inheritable, 1, atomic_flag_works);
  1179. }
  1180. /* Same as _Py_set_inheritable() but on error, set errno and
  1181. don't raise an exception.
  1182. This function is async-signal-safe. */
  1183. int
  1184. _Py_set_inheritable_async_safe(int fd, int inheritable, int *atomic_flag_works)
  1185. {
  1186. return set_inheritable(fd, inheritable, 0, atomic_flag_works);
  1187. }
  1188. static int
  1189. _Py_open_impl(const char *pathname, int flags, int gil_held)
  1190. {
  1191. int fd;
  1192. int async_err = 0;
  1193. #ifndef MS_WINDOWS
  1194. int *atomic_flag_works;
  1195. #endif
  1196. #ifdef MS_WINDOWS
  1197. flags |= O_NOINHERIT;
  1198. #elif defined(O_CLOEXEC)
  1199. atomic_flag_works = &_Py_open_cloexec_works;
  1200. flags |= O_CLOEXEC;
  1201. #else
  1202. atomic_flag_works = NULL;
  1203. #endif
  1204. if (gil_held) {
  1205. PyObject *pathname_obj = PyUnicode_DecodeFSDefault(pathname);
  1206. if (pathname_obj == NULL) {
  1207. return -1;
  1208. }
  1209. if (PySys_Audit("open", "OOi", pathname_obj, Py_None, flags) < 0) {
  1210. Py_DECREF(pathname_obj);
  1211. return -1;
  1212. }
  1213. do {
  1214. Py_BEGIN_ALLOW_THREADS
  1215. fd = open(pathname, flags);
  1216. Py_END_ALLOW_THREADS
  1217. } while (fd < 0
  1218. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1219. if (async_err) {
  1220. Py_DECREF(pathname_obj);
  1221. return -1;
  1222. }
  1223. if (fd < 0) {
  1224. PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, pathname_obj, NULL);
  1225. Py_DECREF(pathname_obj);
  1226. return -1;
  1227. }
  1228. Py_DECREF(pathname_obj);
  1229. }
  1230. else {
  1231. fd = open(pathname, flags);
  1232. if (fd < 0)
  1233. return -1;
  1234. }
  1235. #ifndef MS_WINDOWS
  1236. if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
  1237. close(fd);
  1238. return -1;
  1239. }
  1240. #endif
  1241. return fd;
  1242. }
  1243. /* Open a file with the specified flags (wrapper to open() function).
  1244. Return a file descriptor on success. Raise an exception and return -1 on
  1245. error.
  1246. The file descriptor is created non-inheritable.
  1247. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  1248. except if the Python signal handler raises an exception.
  1249. Release the GIL to call open(). The caller must hold the GIL. */
  1250. int
  1251. _Py_open(const char *pathname, int flags)
  1252. {
  1253. /* _Py_open() must be called with the GIL held. */
  1254. assert(PyGILState_Check());
  1255. return _Py_open_impl(pathname, flags, 1);
  1256. }
  1257. /* Open a file with the specified flags (wrapper to open() function).
  1258. Return a file descriptor on success. Set errno and return -1 on error.
  1259. The file descriptor is created non-inheritable.
  1260. If interrupted by a signal, fail with EINTR. */
  1261. int
  1262. _Py_open_noraise(const char *pathname, int flags)
  1263. {
  1264. return _Py_open_impl(pathname, flags, 0);
  1265. }
  1266. /* Open a file. Use _wfopen() on Windows, encode the path to the locale
  1267. encoding and use fopen() otherwise.
  1268. The file descriptor is created non-inheritable.
  1269. If interrupted by a signal, fail with EINTR. */
  1270. FILE *
  1271. _Py_wfopen(const wchar_t *path, const wchar_t *mode)
  1272. {
  1273. FILE *f;
  1274. if (PySys_Audit("open", "uui", path, mode, 0) < 0) {
  1275. return NULL;
  1276. }
  1277. #ifndef MS_WINDOWS
  1278. char *cpath;
  1279. char cmode[10];
  1280. size_t r;
  1281. r = wcstombs(cmode, mode, 10);
  1282. if (r == DECODE_ERROR || r >= 10) {
  1283. errno = EINVAL;
  1284. return NULL;
  1285. }
  1286. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1287. if (cpath == NULL) {
  1288. return NULL;
  1289. }
  1290. f = fopen(cpath, cmode);
  1291. PyMem_RawFree(cpath);
  1292. #else
  1293. f = _wfopen(path, mode);
  1294. #endif
  1295. if (f == NULL)
  1296. return NULL;
  1297. if (make_non_inheritable(fileno(f)) < 0) {
  1298. fclose(f);
  1299. return NULL;
  1300. }
  1301. return f;
  1302. }
  1303. /* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
  1304. encoding and call fopen() otherwise.
  1305. Return the new file object on success. Raise an exception and return NULL
  1306. on error.
  1307. The file descriptor is created non-inheritable.
  1308. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  1309. except if the Python signal handler raises an exception.
  1310. Release the GIL to call _wfopen() or fopen(). The caller must hold
  1311. the GIL. */
  1312. FILE*
  1313. _Py_fopen_obj(PyObject *path, const char *mode)
  1314. {
  1315. FILE *f;
  1316. int async_err = 0;
  1317. #ifdef MS_WINDOWS
  1318. wchar_t wmode[10];
  1319. int usize;
  1320. assert(PyGILState_Check());
  1321. if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
  1322. return NULL;
  1323. }
  1324. if (!PyUnicode_Check(path)) {
  1325. PyErr_Format(PyExc_TypeError,
  1326. "str file path expected under Windows, got %R",
  1327. Py_TYPE(path));
  1328. return NULL;
  1329. }
  1330. #if USE_UNICODE_WCHAR_CACHE
  1331. const wchar_t *wpath = _PyUnicode_AsUnicode(path);
  1332. #else /* USE_UNICODE_WCHAR_CACHE */
  1333. wchar_t *wpath = PyUnicode_AsWideCharString(path, NULL);
  1334. #endif /* USE_UNICODE_WCHAR_CACHE */
  1335. if (wpath == NULL)
  1336. return NULL;
  1337. usize = MultiByteToWideChar(CP_ACP, 0, mode, -1,
  1338. wmode, Py_ARRAY_LENGTH(wmode));
  1339. if (usize == 0) {
  1340. PyErr_SetFromWindowsErr(0);
  1341. #if !USE_UNICODE_WCHAR_CACHE
  1342. PyMem_Free(wpath);
  1343. #endif /* USE_UNICODE_WCHAR_CACHE */
  1344. return NULL;
  1345. }
  1346. do {
  1347. Py_BEGIN_ALLOW_THREADS
  1348. f = _wfopen(wpath, wmode);
  1349. Py_END_ALLOW_THREADS
  1350. } while (f == NULL
  1351. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1352. #if !USE_UNICODE_WCHAR_CACHE
  1353. PyMem_Free(wpath);
  1354. #endif /* USE_UNICODE_WCHAR_CACHE */
  1355. #else
  1356. PyObject *bytes;
  1357. const char *path_bytes;
  1358. assert(PyGILState_Check());
  1359. if (!PyUnicode_FSConverter(path, &bytes))
  1360. return NULL;
  1361. path_bytes = PyBytes_AS_STRING(bytes);
  1362. if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
  1363. Py_DECREF(bytes);
  1364. return NULL;
  1365. }
  1366. do {
  1367. Py_BEGIN_ALLOW_THREADS
  1368. f = fopen(path_bytes, mode);
  1369. Py_END_ALLOW_THREADS
  1370. } while (f == NULL
  1371. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1372. Py_DECREF(bytes);
  1373. #endif
  1374. if (async_err)
  1375. return NULL;
  1376. if (f == NULL) {
  1377. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1378. return NULL;
  1379. }
  1380. if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
  1381. fclose(f);
  1382. return NULL;
  1383. }
  1384. return f;
  1385. }
  1386. /* Read count bytes from fd into buf.
  1387. On success, return the number of read bytes, it can be lower than count.
  1388. If the current file offset is at or past the end of file, no bytes are read,
  1389. and read() returns zero.
  1390. On error, raise an exception, set errno and return -1.
  1391. When interrupted by a signal (read() fails with EINTR), retry the syscall.
  1392. If the Python signal handler raises an exception, the function returns -1
  1393. (the syscall is not retried).
  1394. Release the GIL to call read(). The caller must hold the GIL. */
  1395. Py_ssize_t
  1396. _Py_read(int fd, void *buf, size_t count)
  1397. {
  1398. Py_ssize_t n;
  1399. int err;
  1400. int async_err = 0;
  1401. assert(PyGILState_Check());
  1402. /* _Py_read() must not be called with an exception set, otherwise the
  1403. * caller may think that read() was interrupted by a signal and the signal
  1404. * handler raised an exception. */
  1405. assert(!PyErr_Occurred());
  1406. if (count > _PY_READ_MAX) {
  1407. count = _PY_READ_MAX;
  1408. }
  1409. _Py_BEGIN_SUPPRESS_IPH
  1410. do {
  1411. Py_BEGIN_ALLOW_THREADS
  1412. errno = 0;
  1413. #ifdef MS_WINDOWS
  1414. n = read(fd, buf, (int)count);
  1415. #else
  1416. n = read(fd, buf, count);
  1417. #endif
  1418. /* save/restore errno because PyErr_CheckSignals()
  1419. * and PyErr_SetFromErrno() can modify it */
  1420. err = errno;
  1421. Py_END_ALLOW_THREADS
  1422. } while (n < 0 && err == EINTR &&
  1423. !(async_err = PyErr_CheckSignals()));
  1424. _Py_END_SUPPRESS_IPH
  1425. if (async_err) {
  1426. /* read() was interrupted by a signal (failed with EINTR)
  1427. * and the Python signal handler raised an exception */
  1428. errno = err;
  1429. assert(errno == EINTR && PyErr_Occurred());
  1430. return -1;
  1431. }
  1432. if (n < 0) {
  1433. PyErr_SetFromErrno(PyExc_OSError);
  1434. errno = err;
  1435. return -1;
  1436. }
  1437. return n;
  1438. }
  1439. static Py_ssize_t
  1440. _Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
  1441. {
  1442. Py_ssize_t n;
  1443. int err;
  1444. int async_err = 0;
  1445. _Py_BEGIN_SUPPRESS_IPH
  1446. #ifdef MS_WINDOWS
  1447. if (count > 32767 && isatty(fd)) {
  1448. /* Issue #11395: the Windows console returns an error (12: not
  1449. enough space error) on writing into stdout if stdout mode is
  1450. binary and the length is greater than 66,000 bytes (or less,
  1451. depending on heap usage). */
  1452. count = 32767;
  1453. }
  1454. #endif
  1455. if (count > _PY_WRITE_MAX) {
  1456. count = _PY_WRITE_MAX;
  1457. }
  1458. if (gil_held) {
  1459. do {
  1460. Py_BEGIN_ALLOW_THREADS
  1461. errno = 0;
  1462. #ifdef MS_WINDOWS
  1463. n = write(fd, buf, (int)count);
  1464. #else
  1465. n = write(fd, buf, count);
  1466. #endif
  1467. /* save/restore errno because PyErr_CheckSignals()
  1468. * and PyErr_SetFromErrno() can modify it */
  1469. err = errno;
  1470. Py_END_ALLOW_THREADS
  1471. } while (n < 0 && err == EINTR &&
  1472. !(async_err = PyErr_CheckSignals()));
  1473. }
  1474. else {
  1475. do {
  1476. errno = 0;
  1477. #ifdef MS_WINDOWS
  1478. n = write(fd, buf, (int)count);
  1479. #else
  1480. n = write(fd, buf, count);
  1481. #endif
  1482. err = errno;
  1483. } while (n < 0 && err == EINTR);
  1484. }
  1485. _Py_END_SUPPRESS_IPH
  1486. if (async_err) {
  1487. /* write() was interrupted by a signal (failed with EINTR)
  1488. and the Python signal handler raised an exception (if gil_held is
  1489. nonzero). */
  1490. errno = err;
  1491. assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
  1492. return -1;
  1493. }
  1494. if (n < 0) {
  1495. if (gil_held)
  1496. PyErr_SetFromErrno(PyExc_OSError);
  1497. errno = err;
  1498. return -1;
  1499. }
  1500. return n;
  1501. }
  1502. /* Write count bytes of buf into fd.
  1503. On success, return the number of written bytes, it can be lower than count
  1504. including 0. On error, raise an exception, set errno and return -1.
  1505. When interrupted by a signal (write() fails with EINTR), retry the syscall.
  1506. If the Python signal handler raises an exception, the function returns -1
  1507. (the syscall is not retried).
  1508. Release the GIL to call write(). The caller must hold the GIL. */
  1509. Py_ssize_t
  1510. _Py_write(int fd, const void *buf, size_t count)
  1511. {
  1512. assert(PyGILState_Check());
  1513. /* _Py_write() must not be called with an exception set, otherwise the
  1514. * caller may think that write() was interrupted by a signal and the signal
  1515. * handler raised an exception. */
  1516. assert(!PyErr_Occurred());
  1517. return _Py_write_impl(fd, buf, count, 1);
  1518. }
  1519. /* Write count bytes of buf into fd.
  1520. *
  1521. * On success, return the number of written bytes, it can be lower than count
  1522. * including 0. On error, set errno and return -1.
  1523. *
  1524. * When interrupted by a signal (write() fails with EINTR), retry the syscall
  1525. * without calling the Python signal handler. */
  1526. Py_ssize_t
  1527. _Py_write_noraise(int fd, const void *buf, size_t count)
  1528. {
  1529. return _Py_write_impl(fd, buf, count, 0);
  1530. }
  1531. #ifdef HAVE_READLINK
  1532. /* Read value of symbolic link. Encode the path to the locale encoding, decode
  1533. the result from the locale encoding.
  1534. Return -1 on encoding error, on readlink() error, if the internal buffer is
  1535. too short, on decoding error, or if 'buf' is too short. */
  1536. int
  1537. _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t buflen)
  1538. {
  1539. char *cpath;
  1540. char cbuf[MAXPATHLEN];
  1541. size_t cbuf_len = Py_ARRAY_LENGTH(cbuf);
  1542. wchar_t *wbuf;
  1543. Py_ssize_t res;
  1544. size_t r1;
  1545. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1546. if (cpath == NULL) {
  1547. errno = EINVAL;
  1548. return -1;
  1549. }
  1550. res = readlink(cpath, cbuf, cbuf_len);
  1551. PyMem_RawFree(cpath);
  1552. if (res == -1) {
  1553. return -1;
  1554. }
  1555. if ((size_t)res == cbuf_len) {
  1556. errno = EINVAL;
  1557. return -1;
  1558. }
  1559. cbuf[res] = '\0'; /* buf will be null terminated */
  1560. wbuf = Py_DecodeLocale(cbuf, &r1);
  1561. if (wbuf == NULL) {
  1562. errno = EINVAL;
  1563. return -1;
  1564. }
  1565. /* wbuf must have space to store the trailing NUL character */
  1566. if (buflen <= r1) {
  1567. PyMem_RawFree(wbuf);
  1568. errno = EINVAL;
  1569. return -1;
  1570. }
  1571. wcsncpy(buf, wbuf, buflen);
  1572. PyMem_RawFree(wbuf);
  1573. return (int)r1;
  1574. }
  1575. #endif
  1576. #ifdef HAVE_REALPATH
  1577. /* Return the canonicalized absolute pathname. Encode path to the locale
  1578. encoding, decode the result from the locale encoding.
  1579. Return NULL on encoding error, realpath() error, decoding error
  1580. or if 'resolved_path' is too short. */
  1581. wchar_t*
  1582. _Py_wrealpath(const wchar_t *path,
  1583. wchar_t *resolved_path, size_t resolved_path_len)
  1584. {
  1585. char *cpath;
  1586. char cresolved_path[MAXPATHLEN];
  1587. wchar_t *wresolved_path;
  1588. char *res;
  1589. size_t r;
  1590. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1591. if (cpath == NULL) {
  1592. errno = EINVAL;
  1593. return NULL;
  1594. }
  1595. res = realpath(cpath, cresolved_path);
  1596. PyMem_RawFree(cpath);
  1597. if (res == NULL)
  1598. return NULL;
  1599. wresolved_path = Py_DecodeLocale(cresolved_path, &r);
  1600. if (wresolved_path == NULL) {
  1601. errno = EINVAL;
  1602. return NULL;
  1603. }
  1604. /* wresolved_path must have space to store the trailing NUL character */
  1605. if (resolved_path_len <= r) {
  1606. PyMem_RawFree(wresolved_path);
  1607. errno = EINVAL;
  1608. return NULL;
  1609. }
  1610. wcsncpy(resolved_path, wresolved_path, resolved_path_len);
  1611. PyMem_RawFree(wresolved_path);
  1612. return resolved_path;
  1613. }
  1614. #endif
  1615. #ifndef MS_WINDOWS
  1616. int
  1617. _Py_isabs(const wchar_t *path)
  1618. {
  1619. return (path[0] == SEP);
  1620. }
  1621. #endif
  1622. /* Get an absolute path.
  1623. On error (ex: fail to get the current directory), return -1.
  1624. On memory allocation failure, set *abspath_p to NULL and return 0.
  1625. On success, return a newly allocated to *abspath_p to and return 0.
  1626. The string must be freed by PyMem_RawFree(). */
  1627. int
  1628. _Py_abspath(const wchar_t *path, wchar_t **abspath_p)
  1629. {
  1630. #ifdef MS_WINDOWS
  1631. wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
  1632. DWORD result;
  1633. result = GetFullPathNameW(path,
  1634. Py_ARRAY_LENGTH(woutbuf), woutbuf,
  1635. NULL);
  1636. if (!result) {
  1637. return -1;
  1638. }
  1639. if (result > Py_ARRAY_LENGTH(woutbuf)) {
  1640. if ((size_t)result <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  1641. woutbufp = PyMem_RawMalloc((size_t)result * sizeof(wchar_t));
  1642. }
  1643. else {
  1644. woutbufp = NULL;
  1645. }
  1646. if (!woutbufp) {
  1647. *abspath_p = NULL;
  1648. return 0;
  1649. }
  1650. result = GetFullPathNameW(path, result, woutbufp, NULL);
  1651. if (!result) {
  1652. PyMem_RawFree(woutbufp);
  1653. return -1;
  1654. }
  1655. }
  1656. if (woutbufp != woutbuf) {
  1657. *abspath_p = woutbufp;
  1658. return 0;
  1659. }
  1660. *abspath_p = _PyMem_RawWcsdup(woutbufp);
  1661. return 0;
  1662. #else
  1663. if (_Py_isabs(path)) {
  1664. *abspath_p = _PyMem_RawWcsdup(path);
  1665. return 0;
  1666. }
  1667. wchar_t cwd[MAXPATHLEN + 1];
  1668. cwd[Py_ARRAY_LENGTH(cwd) - 1] = 0;
  1669. if (!_Py_wgetcwd(cwd, Py_ARRAY_LENGTH(cwd) - 1)) {
  1670. /* unable to get the current directory */
  1671. return -1;
  1672. }
  1673. size_t cwd_len = wcslen(cwd);
  1674. size_t path_len = wcslen(path);
  1675. size_t len = cwd_len + 1 + path_len + 1;
  1676. if (len <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  1677. *abspath_p = PyMem_RawMalloc(len * sizeof(wchar_t));
  1678. }
  1679. else {
  1680. *abspath_p = NULL;
  1681. }
  1682. if (*abspath_p == NULL) {
  1683. return 0;
  1684. }
  1685. wchar_t *abspath = *abspath_p;
  1686. memcpy(abspath, cwd, cwd_len * sizeof(wchar_t));
  1687. abspath += cwd_len;
  1688. *abspath = (wchar_t)SEP;
  1689. abspath++;
  1690. memcpy(abspath, path, path_len * sizeof(wchar_t));
  1691. abspath += path_len;
  1692. *abspath = 0;
  1693. return 0;
  1694. #endif
  1695. }
  1696. /* Get the current directory. buflen is the buffer size in wide characters
  1697. including the null character. Decode the path from the locale encoding.
  1698. Return NULL on getcwd() error, on decoding error, or if 'buf' is
  1699. too short. */
  1700. wchar_t*
  1701. _Py_wgetcwd(wchar_t *buf, size_t buflen)
  1702. {
  1703. #ifdef MS_WINDOWS
  1704. int ibuflen = (int)Py_MIN(buflen, INT_MAX);
  1705. return _wgetcwd(buf, ibuflen);
  1706. #else
  1707. char fname[MAXPATHLEN];
  1708. wchar_t *wname;
  1709. size_t len;
  1710. if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
  1711. return NULL;
  1712. wname = Py_DecodeLocale(fname, &len);
  1713. if (wname == NULL)
  1714. return NULL;
  1715. /* wname must have space to store the trailing NUL character */
  1716. if (buflen <= len) {
  1717. PyMem_RawFree(wname);
  1718. return NULL;
  1719. }
  1720. wcsncpy(buf, wname, buflen);
  1721. PyMem_RawFree(wname);
  1722. return buf;
  1723. #endif
  1724. }
  1725. /* Duplicate a file descriptor. The new file descriptor is created as
  1726. non-inheritable. Return a new file descriptor on success, raise an OSError
  1727. exception and return -1 on error.
  1728. The GIL is released to call dup(). The caller must hold the GIL. */
  1729. int
  1730. _Py_dup(int fd)
  1731. {
  1732. #ifdef MS_WINDOWS
  1733. HANDLE handle;
  1734. #endif
  1735. assert(PyGILState_Check());
  1736. #ifdef MS_WINDOWS
  1737. _Py_BEGIN_SUPPRESS_IPH
  1738. handle = (HANDLE)_get_osfhandle(fd);
  1739. _Py_END_SUPPRESS_IPH
  1740. if (handle == INVALID_HANDLE_VALUE) {
  1741. PyErr_SetFromErrno(PyExc_OSError);
  1742. return -1;
  1743. }
  1744. Py_BEGIN_ALLOW_THREADS
  1745. _Py_BEGIN_SUPPRESS_IPH
  1746. fd = dup(fd);
  1747. _Py_END_SUPPRESS_IPH
  1748. Py_END_ALLOW_THREADS
  1749. if (fd < 0) {
  1750. PyErr_SetFromErrno(PyExc_OSError);
  1751. return -1;
  1752. }
  1753. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1754. _Py_BEGIN_SUPPRESS_IPH
  1755. close(fd);
  1756. _Py_END_SUPPRESS_IPH
  1757. return -1;
  1758. }
  1759. #elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
  1760. Py_BEGIN_ALLOW_THREADS
  1761. _Py_BEGIN_SUPPRESS_IPH
  1762. fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
  1763. _Py_END_SUPPRESS_IPH
  1764. Py_END_ALLOW_THREADS
  1765. if (fd < 0) {
  1766. PyErr_SetFromErrno(PyExc_OSError);
  1767. return -1;
  1768. }
  1769. #else
  1770. Py_BEGIN_ALLOW_THREADS
  1771. _Py_BEGIN_SUPPRESS_IPH
  1772. fd = dup(fd);
  1773. _Py_END_SUPPRESS_IPH
  1774. Py_END_ALLOW_THREADS
  1775. if (fd < 0) {
  1776. PyErr_SetFromErrno(PyExc_OSError);
  1777. return -1;
  1778. }
  1779. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1780. _Py_BEGIN_SUPPRESS_IPH
  1781. close(fd);
  1782. _Py_END_SUPPRESS_IPH
  1783. return -1;
  1784. }
  1785. #endif
  1786. return fd;
  1787. }
  1788. #ifndef MS_WINDOWS
  1789. /* Get the blocking mode of the file descriptor.
  1790. Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
  1791. raise an exception and return -1 on error. */
  1792. int
  1793. _Py_get_blocking(int fd)
  1794. {
  1795. int flags;
  1796. _Py_BEGIN_SUPPRESS_IPH
  1797. flags = fcntl(fd, F_GETFL, 0);
  1798. _Py_END_SUPPRESS_IPH
  1799. if (flags < 0) {
  1800. PyErr_SetFromErrno(PyExc_OSError);
  1801. return -1;
  1802. }
  1803. return !(flags & O_NONBLOCK);
  1804. }
  1805. /* Set the blocking mode of the specified file descriptor.
  1806. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
  1807. otherwise.
  1808. Return 0 on success, raise an exception and return -1 on error. */
  1809. int
  1810. _Py_set_blocking(int fd, int blocking)
  1811. {
  1812. /* bpo-41462: On VxWorks, ioctl(FIONBIO) only works on sockets.
  1813. Use fcntl() instead. */
  1814. #if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO) && !defined(__VXWORKS__)
  1815. int arg = !blocking;
  1816. if (ioctl(fd, FIONBIO, &arg) < 0)
  1817. goto error;
  1818. #else
  1819. int flags, res;
  1820. _Py_BEGIN_SUPPRESS_IPH
  1821. flags = fcntl(fd, F_GETFL, 0);
  1822. if (flags >= 0) {
  1823. if (blocking)
  1824. flags = flags & (~O_NONBLOCK);
  1825. else
  1826. flags = flags | O_NONBLOCK;
  1827. res = fcntl(fd, F_SETFL, flags);
  1828. } else {
  1829. res = -1;
  1830. }
  1831. _Py_END_SUPPRESS_IPH
  1832. if (res < 0)
  1833. goto error;
  1834. #endif
  1835. return 0;
  1836. error:
  1837. PyErr_SetFromErrno(PyExc_OSError);
  1838. return -1;
  1839. }
  1840. #endif
  1841. int
  1842. _Py_GetLocaleconvNumeric(struct lconv *lc,
  1843. PyObject **decimal_point, PyObject **thousands_sep)
  1844. {
  1845. assert(decimal_point != NULL);
  1846. assert(thousands_sep != NULL);
  1847. #ifndef MS_WINDOWS
  1848. int change_locale = 0;
  1849. if ((strlen(lc->decimal_point) > 1 || ((unsigned char)lc->decimal_point[0]) > 127)) {
  1850. change_locale = 1;
  1851. }
  1852. if ((strlen(lc->thousands_sep) > 1 || ((unsigned char)lc->thousands_sep[0]) > 127)) {
  1853. change_locale = 1;
  1854. }
  1855. /* Keep a copy of the LC_CTYPE locale */
  1856. char *oldloc = NULL, *loc = NULL;
  1857. if (change_locale) {
  1858. oldloc = setlocale(LC_CTYPE, NULL);
  1859. if (!oldloc) {
  1860. PyErr_SetString(PyExc_RuntimeWarning,
  1861. "failed to get LC_CTYPE locale");
  1862. return -1;
  1863. }
  1864. oldloc = _PyMem_Strdup(oldloc);
  1865. if (!oldloc) {
  1866. PyErr_NoMemory();
  1867. return -1;
  1868. }
  1869. loc = setlocale(LC_NUMERIC, NULL);
  1870. if (loc != NULL && strcmp(loc, oldloc) == 0) {
  1871. loc = NULL;
  1872. }
  1873. if (loc != NULL) {
  1874. /* Only set the locale temporarily the LC_CTYPE locale
  1875. if LC_NUMERIC locale is different than LC_CTYPE locale and
  1876. decimal_point and/or thousands_sep are non-ASCII or longer than
  1877. 1 byte */
  1878. setlocale(LC_CTYPE, loc);
  1879. }
  1880. }
  1881. #define GET_LOCALE_STRING(ATTR) PyUnicode_DecodeLocale(lc->ATTR, NULL)
  1882. #else /* MS_WINDOWS */
  1883. /* Use _W_* fields of Windows strcut lconv */
  1884. #define GET_LOCALE_STRING(ATTR) PyUnicode_FromWideChar(lc->_W_ ## ATTR, -1)
  1885. #endif /* MS_WINDOWS */
  1886. int res = -1;
  1887. *decimal_point = GET_LOCALE_STRING(decimal_point);
  1888. if (*decimal_point == NULL) {
  1889. goto done;
  1890. }
  1891. *thousands_sep = GET_LOCALE_STRING(thousands_sep);
  1892. if (*thousands_sep == NULL) {
  1893. goto done;
  1894. }
  1895. res = 0;
  1896. done:
  1897. #ifndef MS_WINDOWS
  1898. if (loc != NULL) {
  1899. setlocale(LC_CTYPE, oldloc);
  1900. }
  1901. PyMem_Free(oldloc);
  1902. #endif
  1903. return res;
  1904. #undef GET_LOCALE_STRING
  1905. }
  1906. /* Our selection logic for which function to use is as follows:
  1907. * 1. If close_range(2) is available, always prefer that; it's better for
  1908. * contiguous ranges like this than fdwalk(3) which entails iterating over
  1909. * the entire fd space and simply doing nothing for those outside the range.
  1910. * 2. If closefrom(2) is available, we'll attempt to use that next if we're
  1911. * closing up to sysconf(_SC_OPEN_MAX).
  1912. * 2a. Fallback to fdwalk(3) if we're not closing up to sysconf(_SC_OPEN_MAX),
  1913. * as that will be more performant if the range happens to have any chunk of
  1914. * non-opened fd in the middle.
  1915. * 2b. If fdwalk(3) isn't available, just do a plain close(2) loop.
  1916. */
  1917. #ifdef __FreeBSD__
  1918. # define USE_CLOSEFROM
  1919. #endif /* __FreeBSD__ */
  1920. #ifdef HAVE_FDWALK
  1921. # define USE_FDWALK
  1922. #endif /* HAVE_FDWALK */
  1923. #ifdef USE_FDWALK
  1924. static int
  1925. _fdwalk_close_func(void *lohi, int fd)
  1926. {
  1927. int lo = ((int *)lohi)[0];
  1928. int hi = ((int *)lohi)[1];
  1929. if (fd >= hi) {
  1930. return 1;
  1931. }
  1932. else if (fd >= lo) {
  1933. /* Ignore errors */
  1934. (void)close(fd);
  1935. }
  1936. return 0;
  1937. }
  1938. #endif /* USE_FDWALK */
  1939. /* Closes all file descriptors in [first, last], ignoring errors. */
  1940. void
  1941. _Py_closerange(int first, int last)
  1942. {
  1943. first = Py_MAX(first, 0);
  1944. _Py_BEGIN_SUPPRESS_IPH
  1945. #ifdef HAVE_CLOSE_RANGE
  1946. if (close_range(first, last, 0) == 0 || errno != ENOSYS) {
  1947. /* Any errors encountered while closing file descriptors are ignored;
  1948. * ENOSYS means no kernel support, though,
  1949. * so we'll fallback to the other methods. */
  1950. }
  1951. else
  1952. #endif /* HAVE_CLOSE_RANGE */
  1953. #ifdef USE_CLOSEFROM
  1954. if (last >= sysconf(_SC_OPEN_MAX)) {
  1955. /* Any errors encountered while closing file descriptors are ignored */
  1956. closefrom(first);
  1957. }
  1958. else
  1959. #endif /* USE_CLOSEFROM */
  1960. #ifdef USE_FDWALK
  1961. {
  1962. int lohi[2];
  1963. lohi[0] = first;
  1964. lohi[1] = last + 1;
  1965. fdwalk(_fdwalk_close_func, lohi);
  1966. }
  1967. #else
  1968. {
  1969. for (int i = first; i <= last; i++) {
  1970. /* Ignore errors */
  1971. (void)close(i);
  1972. }
  1973. }
  1974. #endif /* USE_FDWALK */
  1975. _Py_END_SUPPRESS_IPH
  1976. }