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.

1948 lines
51 KiB

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