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.

1957 lines
52 KiB

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