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.

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