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.

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