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.

2077 lines
55 KiB

13 years ago
  1. #include "Python.h"
  2. #include "pycore_fileutils.h"
  3. #include "osdefs.h" // SEP
  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(_Py_FORCE_UTF8_FS_ENCODING) && !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(_Py_FORCE_UTF8_FS_ENCODING) && !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. #ifdef _Py_FORCE_UTF8_LOCALE
  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. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  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 /* !_Py_FORCE_UTF8_FS_ENCODING */
  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 _Py_FORCE_UTF8_LOCALE
  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. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  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 /* _Py_FORCE_UTF8_FS_ENCODING */
  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. /* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will
  772. open other name surrogate reparse points without traversing them. To
  773. detect/handle these, check st_file_attributes and st_reparse_tag. */
  774. result->st_reparse_tag = reparse_tag;
  775. if (info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
  776. reparse_tag == IO_REPARSE_TAG_SYMLINK) {
  777. /* first clear the S_IFMT bits */
  778. result->st_mode ^= (result->st_mode & S_IFMT);
  779. /* now set the bits that make this a symlink */
  780. result->st_mode |= S_IFLNK;
  781. }
  782. result->st_file_attributes = info->dwFileAttributes;
  783. }
  784. #endif
  785. /* Return information about a file.
  786. On POSIX, use fstat().
  787. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  788. files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
  789. than 2 GiB because the file size type is a signed 32-bit integer: see issue
  790. #23152.
  791. On Windows, set the last Windows error and return nonzero on error. On
  792. POSIX, set errno and return nonzero on error. Fill status and return 0 on
  793. success. */
  794. int
  795. _Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
  796. {
  797. #ifdef MS_WINDOWS
  798. BY_HANDLE_FILE_INFORMATION info;
  799. HANDLE h;
  800. int type;
  801. _Py_BEGIN_SUPPRESS_IPH
  802. h = (HANDLE)_get_osfhandle(fd);
  803. _Py_END_SUPPRESS_IPH
  804. if (h == INVALID_HANDLE_VALUE) {
  805. /* errno is already set by _get_osfhandle, but we also set
  806. the Win32 error for callers who expect that */
  807. SetLastError(ERROR_INVALID_HANDLE);
  808. return -1;
  809. }
  810. memset(status, 0, sizeof(*status));
  811. type = GetFileType(h);
  812. if (type == FILE_TYPE_UNKNOWN) {
  813. DWORD error = GetLastError();
  814. if (error != 0) {
  815. errno = winerror_to_errno(error);
  816. return -1;
  817. }
  818. /* else: valid but unknown file */
  819. }
  820. if (type != FILE_TYPE_DISK) {
  821. if (type == FILE_TYPE_CHAR)
  822. status->st_mode = _S_IFCHR;
  823. else if (type == FILE_TYPE_PIPE)
  824. status->st_mode = _S_IFIFO;
  825. return 0;
  826. }
  827. if (!GetFileInformationByHandle(h, &info)) {
  828. /* The Win32 error is already set, but we also set errno for
  829. callers who expect it */
  830. errno = winerror_to_errno(GetLastError());
  831. return -1;
  832. }
  833. _Py_attribute_data_to_stat(&info, 0, status);
  834. /* specific to fstat() */
  835. status->st_ino = (((uint64_t)info.nFileIndexHigh) << 32) + info.nFileIndexLow;
  836. return 0;
  837. #else
  838. return fstat(fd, status);
  839. #endif
  840. }
  841. /* Return information about a file.
  842. On POSIX, use fstat().
  843. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  844. files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
  845. than 2 GiB because the file size type is a signed 32-bit integer: see issue
  846. #23152.
  847. Raise an exception and return -1 on error. On Windows, set the last Windows
  848. error on error. On POSIX, set errno on error. Fill status and return 0 on
  849. success.
  850. Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
  851. to call fstat(). The caller must hold the GIL. */
  852. int
  853. _Py_fstat(int fd, struct _Py_stat_struct *status)
  854. {
  855. int res;
  856. assert(PyGILState_Check());
  857. Py_BEGIN_ALLOW_THREADS
  858. res = _Py_fstat_noraise(fd, status);
  859. Py_END_ALLOW_THREADS
  860. if (res != 0) {
  861. #ifdef MS_WINDOWS
  862. PyErr_SetFromWindowsErr(0);
  863. #else
  864. PyErr_SetFromErrno(PyExc_OSError);
  865. #endif
  866. return -1;
  867. }
  868. return 0;
  869. }
  870. /* Call _wstat() on Windows, or encode the path to the filesystem encoding and
  871. call stat() otherwise. Only fill st_mode attribute on Windows.
  872. Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
  873. raised. */
  874. int
  875. _Py_stat(PyObject *path, struct stat *statbuf)
  876. {
  877. #ifdef MS_WINDOWS
  878. int err;
  879. struct _stat wstatbuf;
  880. const wchar_t *wpath;
  881. wpath = _PyUnicode_AsUnicode(path);
  882. if (wpath == NULL)
  883. return -2;
  884. err = _wstat(wpath, &wstatbuf);
  885. if (!err)
  886. statbuf->st_mode = wstatbuf.st_mode;
  887. return err;
  888. #else
  889. int ret;
  890. PyObject *bytes;
  891. char *cpath;
  892. bytes = PyUnicode_EncodeFSDefault(path);
  893. if (bytes == NULL)
  894. return -2;
  895. /* check for embedded null bytes */
  896. if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
  897. Py_DECREF(bytes);
  898. return -2;
  899. }
  900. ret = stat(cpath, statbuf);
  901. Py_DECREF(bytes);
  902. return ret;
  903. #endif
  904. }
  905. /* This function MUST be kept async-signal-safe on POSIX when raise=0. */
  906. static int
  907. get_inheritable(int fd, int raise)
  908. {
  909. #ifdef MS_WINDOWS
  910. HANDLE handle;
  911. DWORD flags;
  912. _Py_BEGIN_SUPPRESS_IPH
  913. handle = (HANDLE)_get_osfhandle(fd);
  914. _Py_END_SUPPRESS_IPH
  915. if (handle == INVALID_HANDLE_VALUE) {
  916. if (raise)
  917. PyErr_SetFromErrno(PyExc_OSError);
  918. return -1;
  919. }
  920. if (!GetHandleInformation(handle, &flags)) {
  921. if (raise)
  922. PyErr_SetFromWindowsErr(0);
  923. return -1;
  924. }
  925. return (flags & HANDLE_FLAG_INHERIT);
  926. #else
  927. int flags;
  928. flags = fcntl(fd, F_GETFD, 0);
  929. if (flags == -1) {
  930. if (raise)
  931. PyErr_SetFromErrno(PyExc_OSError);
  932. return -1;
  933. }
  934. return !(flags & FD_CLOEXEC);
  935. #endif
  936. }
  937. /* Get the inheritable flag of the specified file descriptor.
  938. Return 1 if the file descriptor can be inherited, 0 if it cannot,
  939. raise an exception and return -1 on error. */
  940. int
  941. _Py_get_inheritable(int fd)
  942. {
  943. return get_inheritable(fd, 1);
  944. }
  945. /* This function MUST be kept async-signal-safe on POSIX when raise=0. */
  946. static int
  947. set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
  948. {
  949. #ifdef MS_WINDOWS
  950. HANDLE handle;
  951. DWORD flags;
  952. #else
  953. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  954. static int ioctl_works = -1;
  955. int request;
  956. int err;
  957. #endif
  958. int flags, new_flags;
  959. int res;
  960. #endif
  961. /* atomic_flag_works can only be used to make the file descriptor
  962. non-inheritable */
  963. assert(!(atomic_flag_works != NULL && inheritable));
  964. if (atomic_flag_works != NULL && !inheritable) {
  965. if (*atomic_flag_works == -1) {
  966. int isInheritable = get_inheritable(fd, raise);
  967. if (isInheritable == -1)
  968. return -1;
  969. *atomic_flag_works = !isInheritable;
  970. }
  971. if (*atomic_flag_works)
  972. return 0;
  973. }
  974. #ifdef MS_WINDOWS
  975. _Py_BEGIN_SUPPRESS_IPH
  976. handle = (HANDLE)_get_osfhandle(fd);
  977. _Py_END_SUPPRESS_IPH
  978. if (handle == INVALID_HANDLE_VALUE) {
  979. if (raise)
  980. PyErr_SetFromErrno(PyExc_OSError);
  981. return -1;
  982. }
  983. if (inheritable)
  984. flags = HANDLE_FLAG_INHERIT;
  985. else
  986. flags = 0;
  987. /* This check can be removed once support for Windows 7 ends. */
  988. #define CONSOLE_PSEUDOHANDLE(handle) (((ULONG_PTR)(handle) & 0x3) == 0x3 && \
  989. GetFileType(handle) == FILE_TYPE_CHAR)
  990. if (!CONSOLE_PSEUDOHANDLE(handle) &&
  991. !SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
  992. if (raise)
  993. PyErr_SetFromWindowsErr(0);
  994. return -1;
  995. }
  996. #undef CONSOLE_PSEUDOHANDLE
  997. return 0;
  998. #else
  999. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  1000. if (ioctl_works != 0 && raise != 0) {
  1001. /* fast-path: ioctl() only requires one syscall */
  1002. /* caveat: raise=0 is an indicator that we must be async-signal-safe
  1003. * thus avoid using ioctl() so we skip the fast-path. */
  1004. if (inheritable)
  1005. request = FIONCLEX;
  1006. else
  1007. request = FIOCLEX;
  1008. err = ioctl(fd, request, NULL);
  1009. if (!err) {
  1010. ioctl_works = 1;
  1011. return 0;
  1012. }
  1013. if (errno != ENOTTY && errno != EACCES) {
  1014. if (raise)
  1015. PyErr_SetFromErrno(PyExc_OSError);
  1016. return -1;
  1017. }
  1018. else {
  1019. /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
  1020. device". The ioctl is declared but not supported by the kernel.
  1021. Remember that ioctl() doesn't work. It is the case on
  1022. Illumos-based OS for example.
  1023. Issue #27057: When SELinux policy disallows ioctl it will fail
  1024. with EACCES. While FIOCLEX is safe operation it may be
  1025. unavailable because ioctl was denied altogether.
  1026. This can be the case on Android. */
  1027. ioctl_works = 0;
  1028. }
  1029. /* fallback to fcntl() if ioctl() does not work */
  1030. }
  1031. #endif
  1032. /* slow-path: fcntl() requires two syscalls */
  1033. flags = fcntl(fd, F_GETFD);
  1034. if (flags < 0) {
  1035. if (raise)
  1036. PyErr_SetFromErrno(PyExc_OSError);
  1037. return -1;
  1038. }
  1039. if (inheritable) {
  1040. new_flags = flags & ~FD_CLOEXEC;
  1041. }
  1042. else {
  1043. new_flags = flags | FD_CLOEXEC;
  1044. }
  1045. if (new_flags == flags) {
  1046. /* FD_CLOEXEC flag already set/cleared: nothing to do */
  1047. return 0;
  1048. }
  1049. res = fcntl(fd, F_SETFD, new_flags);
  1050. if (res < 0) {
  1051. if (raise)
  1052. PyErr_SetFromErrno(PyExc_OSError);
  1053. return -1;
  1054. }
  1055. return 0;
  1056. #endif
  1057. }
  1058. /* Make the file descriptor non-inheritable.
  1059. Return 0 on success, set errno and return -1 on error. */
  1060. static int
  1061. make_non_inheritable(int fd)
  1062. {
  1063. return set_inheritable(fd, 0, 0, NULL);
  1064. }
  1065. /* Set the inheritable flag of the specified file descriptor.
  1066. On success: return 0, on error: raise an exception and return -1.
  1067. If atomic_flag_works is not NULL:
  1068. * if *atomic_flag_works==-1, check if the inheritable is set on the file
  1069. descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
  1070. set the inheritable flag
  1071. * if *atomic_flag_works==1: do nothing
  1072. * if *atomic_flag_works==0: set inheritable flag to False
  1073. Set atomic_flag_works to NULL if no atomic flag was used to create the
  1074. file descriptor.
  1075. atomic_flag_works can only be used to make a file descriptor
  1076. non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
  1077. int
  1078. _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
  1079. {
  1080. return set_inheritable(fd, inheritable, 1, atomic_flag_works);
  1081. }
  1082. /* Same as _Py_set_inheritable() but on error, set errno and
  1083. don't raise an exception.
  1084. This function is async-signal-safe. */
  1085. int
  1086. _Py_set_inheritable_async_safe(int fd, int inheritable, int *atomic_flag_works)
  1087. {
  1088. return set_inheritable(fd, inheritable, 0, atomic_flag_works);
  1089. }
  1090. static int
  1091. _Py_open_impl(const char *pathname, int flags, int gil_held)
  1092. {
  1093. int fd;
  1094. int async_err = 0;
  1095. #ifndef MS_WINDOWS
  1096. int *atomic_flag_works;
  1097. #endif
  1098. #ifdef MS_WINDOWS
  1099. flags |= O_NOINHERIT;
  1100. #elif defined(O_CLOEXEC)
  1101. atomic_flag_works = &_Py_open_cloexec_works;
  1102. flags |= O_CLOEXEC;
  1103. #else
  1104. atomic_flag_works = NULL;
  1105. #endif
  1106. if (gil_held) {
  1107. if (PySys_Audit("open", "sOi", pathname, Py_None, flags) < 0) {
  1108. return -1;
  1109. }
  1110. do {
  1111. Py_BEGIN_ALLOW_THREADS
  1112. fd = open(pathname, flags);
  1113. Py_END_ALLOW_THREADS
  1114. } while (fd < 0
  1115. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1116. if (async_err)
  1117. return -1;
  1118. if (fd < 0) {
  1119. PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname);
  1120. return -1;
  1121. }
  1122. }
  1123. else {
  1124. fd = open(pathname, flags);
  1125. if (fd < 0)
  1126. return -1;
  1127. }
  1128. #ifndef MS_WINDOWS
  1129. if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
  1130. close(fd);
  1131. return -1;
  1132. }
  1133. #endif
  1134. return fd;
  1135. }
  1136. /* Open a file with the specified flags (wrapper to open() function).
  1137. Return a file descriptor on success. Raise an exception and return -1 on
  1138. error.
  1139. The file descriptor is created non-inheritable.
  1140. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  1141. except if the Python signal handler raises an exception.
  1142. Release the GIL to call open(). The caller must hold the GIL. */
  1143. int
  1144. _Py_open(const char *pathname, int flags)
  1145. {
  1146. /* _Py_open() must be called with the GIL held. */
  1147. assert(PyGILState_Check());
  1148. return _Py_open_impl(pathname, flags, 1);
  1149. }
  1150. /* Open a file with the specified flags (wrapper to open() function).
  1151. Return a file descriptor on success. Set errno and return -1 on error.
  1152. The file descriptor is created non-inheritable.
  1153. If interrupted by a signal, fail with EINTR. */
  1154. int
  1155. _Py_open_noraise(const char *pathname, int flags)
  1156. {
  1157. return _Py_open_impl(pathname, flags, 0);
  1158. }
  1159. /* Open a file. Use _wfopen() on Windows, encode the path to the locale
  1160. encoding and use fopen() otherwise.
  1161. The file descriptor is created non-inheritable.
  1162. If interrupted by a signal, fail with EINTR. */
  1163. FILE *
  1164. _Py_wfopen(const wchar_t *path, const wchar_t *mode)
  1165. {
  1166. FILE *f;
  1167. if (PySys_Audit("open", "uui", path, mode, 0) < 0) {
  1168. return NULL;
  1169. }
  1170. #ifndef MS_WINDOWS
  1171. char *cpath;
  1172. char cmode[10];
  1173. size_t r;
  1174. r = wcstombs(cmode, mode, 10);
  1175. if (r == (size_t)-1 || r >= 10) {
  1176. errno = EINVAL;
  1177. return NULL;
  1178. }
  1179. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1180. if (cpath == NULL) {
  1181. return NULL;
  1182. }
  1183. f = fopen(cpath, cmode);
  1184. PyMem_RawFree(cpath);
  1185. #else
  1186. f = _wfopen(path, mode);
  1187. #endif
  1188. if (f == NULL)
  1189. return NULL;
  1190. if (make_non_inheritable(fileno(f)) < 0) {
  1191. fclose(f);
  1192. return NULL;
  1193. }
  1194. return f;
  1195. }
  1196. /* Wrapper to fopen().
  1197. The file descriptor is created non-inheritable.
  1198. If interrupted by a signal, fail with EINTR. */
  1199. FILE*
  1200. _Py_fopen(const char *pathname, const char *mode)
  1201. {
  1202. if (PySys_Audit("open", "ssi", pathname, mode, 0) < 0) {
  1203. return NULL;
  1204. }
  1205. FILE *f = fopen(pathname, mode);
  1206. if (f == NULL)
  1207. return NULL;
  1208. if (make_non_inheritable(fileno(f)) < 0) {
  1209. fclose(f);
  1210. return NULL;
  1211. }
  1212. return f;
  1213. }
  1214. /* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
  1215. encoding and call fopen() otherwise.
  1216. Return the new file object on success. Raise an exception and return NULL
  1217. on error.
  1218. The file descriptor is created non-inheritable.
  1219. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  1220. except if the Python signal handler raises an exception.
  1221. Release the GIL to call _wfopen() or fopen(). The caller must hold
  1222. the GIL. */
  1223. FILE*
  1224. _Py_fopen_obj(PyObject *path, const char *mode)
  1225. {
  1226. FILE *f;
  1227. int async_err = 0;
  1228. #ifdef MS_WINDOWS
  1229. const wchar_t *wpath;
  1230. wchar_t wmode[10];
  1231. int usize;
  1232. assert(PyGILState_Check());
  1233. if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
  1234. return NULL;
  1235. }
  1236. if (!PyUnicode_Check(path)) {
  1237. PyErr_Format(PyExc_TypeError,
  1238. "str file path expected under Windows, got %R",
  1239. Py_TYPE(path));
  1240. return NULL;
  1241. }
  1242. wpath = _PyUnicode_AsUnicode(path);
  1243. if (wpath == NULL)
  1244. return NULL;
  1245. usize = MultiByteToWideChar(CP_ACP, 0, mode, -1,
  1246. wmode, Py_ARRAY_LENGTH(wmode));
  1247. if (usize == 0) {
  1248. PyErr_SetFromWindowsErr(0);
  1249. return NULL;
  1250. }
  1251. do {
  1252. Py_BEGIN_ALLOW_THREADS
  1253. f = _wfopen(wpath, wmode);
  1254. Py_END_ALLOW_THREADS
  1255. } while (f == NULL
  1256. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1257. #else
  1258. PyObject *bytes;
  1259. const char *path_bytes;
  1260. assert(PyGILState_Check());
  1261. if (!PyUnicode_FSConverter(path, &bytes))
  1262. return NULL;
  1263. path_bytes = PyBytes_AS_STRING(bytes);
  1264. if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
  1265. return NULL;
  1266. }
  1267. do {
  1268. Py_BEGIN_ALLOW_THREADS
  1269. f = fopen(path_bytes, mode);
  1270. Py_END_ALLOW_THREADS
  1271. } while (f == NULL
  1272. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1273. Py_DECREF(bytes);
  1274. #endif
  1275. if (async_err)
  1276. return NULL;
  1277. if (f == NULL) {
  1278. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1279. return NULL;
  1280. }
  1281. if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
  1282. fclose(f);
  1283. return NULL;
  1284. }
  1285. return f;
  1286. }
  1287. /* Read count bytes from fd into buf.
  1288. On success, return the number of read bytes, it can be lower than count.
  1289. If the current file offset is at or past the end of file, no bytes are read,
  1290. and read() returns zero.
  1291. On error, raise an exception, set errno and return -1.
  1292. When interrupted by a signal (read() fails with EINTR), retry the syscall.
  1293. If the Python signal handler raises an exception, the function returns -1
  1294. (the syscall is not retried).
  1295. Release the GIL to call read(). The caller must hold the GIL. */
  1296. Py_ssize_t
  1297. _Py_read(int fd, void *buf, size_t count)
  1298. {
  1299. Py_ssize_t n;
  1300. int err;
  1301. int async_err = 0;
  1302. assert(PyGILState_Check());
  1303. /* _Py_read() must not be called with an exception set, otherwise the
  1304. * caller may think that read() was interrupted by a signal and the signal
  1305. * handler raised an exception. */
  1306. assert(!PyErr_Occurred());
  1307. if (count > _PY_READ_MAX) {
  1308. count = _PY_READ_MAX;
  1309. }
  1310. _Py_BEGIN_SUPPRESS_IPH
  1311. do {
  1312. Py_BEGIN_ALLOW_THREADS
  1313. errno = 0;
  1314. #ifdef MS_WINDOWS
  1315. n = read(fd, buf, (int)count);
  1316. #else
  1317. n = read(fd, buf, count);
  1318. #endif
  1319. /* save/restore errno because PyErr_CheckSignals()
  1320. * and PyErr_SetFromErrno() can modify it */
  1321. err = errno;
  1322. Py_END_ALLOW_THREADS
  1323. } while (n < 0 && err == EINTR &&
  1324. !(async_err = PyErr_CheckSignals()));
  1325. _Py_END_SUPPRESS_IPH
  1326. if (async_err) {
  1327. /* read() was interrupted by a signal (failed with EINTR)
  1328. * and the Python signal handler raised an exception */
  1329. errno = err;
  1330. assert(errno == EINTR && PyErr_Occurred());
  1331. return -1;
  1332. }
  1333. if (n < 0) {
  1334. PyErr_SetFromErrno(PyExc_OSError);
  1335. errno = err;
  1336. return -1;
  1337. }
  1338. return n;
  1339. }
  1340. static Py_ssize_t
  1341. _Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
  1342. {
  1343. Py_ssize_t n;
  1344. int err;
  1345. int async_err = 0;
  1346. _Py_BEGIN_SUPPRESS_IPH
  1347. #ifdef MS_WINDOWS
  1348. if (count > 32767 && isatty(fd)) {
  1349. /* Issue #11395: the Windows console returns an error (12: not
  1350. enough space error) on writing into stdout if stdout mode is
  1351. binary and the length is greater than 66,000 bytes (or less,
  1352. depending on heap usage). */
  1353. count = 32767;
  1354. }
  1355. #endif
  1356. if (count > _PY_WRITE_MAX) {
  1357. count = _PY_WRITE_MAX;
  1358. }
  1359. if (gil_held) {
  1360. do {
  1361. Py_BEGIN_ALLOW_THREADS
  1362. errno = 0;
  1363. #ifdef MS_WINDOWS
  1364. n = write(fd, buf, (int)count);
  1365. #else
  1366. n = write(fd, buf, count);
  1367. #endif
  1368. /* save/restore errno because PyErr_CheckSignals()
  1369. * and PyErr_SetFromErrno() can modify it */
  1370. err = errno;
  1371. Py_END_ALLOW_THREADS
  1372. } while (n < 0 && err == EINTR &&
  1373. !(async_err = PyErr_CheckSignals()));
  1374. }
  1375. else {
  1376. do {
  1377. errno = 0;
  1378. #ifdef MS_WINDOWS
  1379. n = write(fd, buf, (int)count);
  1380. #else
  1381. n = write(fd, buf, count);
  1382. #endif
  1383. err = errno;
  1384. } while (n < 0 && err == EINTR);
  1385. }
  1386. _Py_END_SUPPRESS_IPH
  1387. if (async_err) {
  1388. /* write() was interrupted by a signal (failed with EINTR)
  1389. and the Python signal handler raised an exception (if gil_held is
  1390. nonzero). */
  1391. errno = err;
  1392. assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
  1393. return -1;
  1394. }
  1395. if (n < 0) {
  1396. if (gil_held)
  1397. PyErr_SetFromErrno(PyExc_OSError);
  1398. errno = err;
  1399. return -1;
  1400. }
  1401. return n;
  1402. }
  1403. /* Write count bytes of buf into fd.
  1404. On success, return the number of written bytes, it can be lower than count
  1405. including 0. On error, raise an exception, set errno and return -1.
  1406. When interrupted by a signal (write() fails with EINTR), retry the syscall.
  1407. If the Python signal handler raises an exception, the function returns -1
  1408. (the syscall is not retried).
  1409. Release the GIL to call write(). The caller must hold the GIL. */
  1410. Py_ssize_t
  1411. _Py_write(int fd, const void *buf, size_t count)
  1412. {
  1413. assert(PyGILState_Check());
  1414. /* _Py_write() must not be called with an exception set, otherwise the
  1415. * caller may think that write() was interrupted by a signal and the signal
  1416. * handler raised an exception. */
  1417. assert(!PyErr_Occurred());
  1418. return _Py_write_impl(fd, buf, count, 1);
  1419. }
  1420. /* Write count bytes of buf into fd.
  1421. *
  1422. * On success, return the number of written bytes, it can be lower than count
  1423. * including 0. On error, set errno and return -1.
  1424. *
  1425. * When interrupted by a signal (write() fails with EINTR), retry the syscall
  1426. * without calling the Python signal handler. */
  1427. Py_ssize_t
  1428. _Py_write_noraise(int fd, const void *buf, size_t count)
  1429. {
  1430. return _Py_write_impl(fd, buf, count, 0);
  1431. }
  1432. #ifdef HAVE_READLINK
  1433. /* Read value of symbolic link. Encode the path to the locale encoding, decode
  1434. the result from the locale encoding.
  1435. Return -1 on encoding error, on readlink() error, if the internal buffer is
  1436. too short, on decoding error, or if 'buf' is too short. */
  1437. int
  1438. _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t buflen)
  1439. {
  1440. char *cpath;
  1441. char cbuf[MAXPATHLEN];
  1442. size_t cbuf_len = Py_ARRAY_LENGTH(cbuf);
  1443. wchar_t *wbuf;
  1444. Py_ssize_t res;
  1445. size_t r1;
  1446. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1447. if (cpath == NULL) {
  1448. errno = EINVAL;
  1449. return -1;
  1450. }
  1451. res = readlink(cpath, cbuf, cbuf_len);
  1452. PyMem_RawFree(cpath);
  1453. if (res == -1) {
  1454. return -1;
  1455. }
  1456. if ((size_t)res == cbuf_len) {
  1457. errno = EINVAL;
  1458. return -1;
  1459. }
  1460. cbuf[res] = '\0'; /* buf will be null terminated */
  1461. wbuf = Py_DecodeLocale(cbuf, &r1);
  1462. if (wbuf == NULL) {
  1463. errno = EINVAL;
  1464. return -1;
  1465. }
  1466. /* wbuf must have space to store the trailing NUL character */
  1467. if (buflen <= r1) {
  1468. PyMem_RawFree(wbuf);
  1469. errno = EINVAL;
  1470. return -1;
  1471. }
  1472. wcsncpy(buf, wbuf, buflen);
  1473. PyMem_RawFree(wbuf);
  1474. return (int)r1;
  1475. }
  1476. #endif
  1477. #ifdef HAVE_REALPATH
  1478. /* Return the canonicalized absolute pathname. Encode path to the locale
  1479. encoding, decode the result from the locale encoding.
  1480. Return NULL on encoding error, realpath() error, decoding error
  1481. or if 'resolved_path' is too short. */
  1482. wchar_t*
  1483. _Py_wrealpath(const wchar_t *path,
  1484. wchar_t *resolved_path, size_t resolved_path_len)
  1485. {
  1486. char *cpath;
  1487. char cresolved_path[MAXPATHLEN];
  1488. wchar_t *wresolved_path;
  1489. char *res;
  1490. size_t r;
  1491. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1492. if (cpath == NULL) {
  1493. errno = EINVAL;
  1494. return NULL;
  1495. }
  1496. res = realpath(cpath, cresolved_path);
  1497. PyMem_RawFree(cpath);
  1498. if (res == NULL)
  1499. return NULL;
  1500. wresolved_path = Py_DecodeLocale(cresolved_path, &r);
  1501. if (wresolved_path == NULL) {
  1502. errno = EINVAL;
  1503. return NULL;
  1504. }
  1505. /* wresolved_path must have space to store the trailing NUL character */
  1506. if (resolved_path_len <= r) {
  1507. PyMem_RawFree(wresolved_path);
  1508. errno = EINVAL;
  1509. return NULL;
  1510. }
  1511. wcsncpy(resolved_path, wresolved_path, resolved_path_len);
  1512. PyMem_RawFree(wresolved_path);
  1513. return resolved_path;
  1514. }
  1515. #endif
  1516. #ifndef MS_WINDOWS
  1517. int
  1518. _Py_isabs(const wchar_t *path)
  1519. {
  1520. return (path[0] == SEP);
  1521. }
  1522. #endif
  1523. /* Get an absolute path.
  1524. On error (ex: fail to get the current directory), return -1.
  1525. On memory allocation failure, set *abspath_p to NULL and return 0.
  1526. On success, return a newly allocated to *abspath_p to and return 0.
  1527. The string must be freed by PyMem_RawFree(). */
  1528. int
  1529. _Py_abspath(const wchar_t *path, wchar_t **abspath_p)
  1530. {
  1531. #ifdef MS_WINDOWS
  1532. wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
  1533. DWORD result;
  1534. result = GetFullPathNameW(path,
  1535. Py_ARRAY_LENGTH(woutbuf), woutbuf,
  1536. NULL);
  1537. if (!result) {
  1538. return -1;
  1539. }
  1540. if (result > Py_ARRAY_LENGTH(woutbuf)) {
  1541. if ((size_t)result <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  1542. woutbufp = PyMem_RawMalloc((size_t)result * sizeof(wchar_t));
  1543. }
  1544. else {
  1545. woutbufp = NULL;
  1546. }
  1547. if (!woutbufp) {
  1548. *abspath_p = NULL;
  1549. return 0;
  1550. }
  1551. result = GetFullPathNameW(path, result, woutbufp, NULL);
  1552. if (!result) {
  1553. PyMem_RawFree(woutbufp);
  1554. return -1;
  1555. }
  1556. }
  1557. if (woutbufp != woutbuf) {
  1558. *abspath_p = woutbufp;
  1559. return 0;
  1560. }
  1561. *abspath_p = _PyMem_RawWcsdup(woutbufp);
  1562. return 0;
  1563. #else
  1564. if (_Py_isabs(path)) {
  1565. *abspath_p = _PyMem_RawWcsdup(path);
  1566. return 0;
  1567. }
  1568. wchar_t cwd[MAXPATHLEN + 1];
  1569. cwd[Py_ARRAY_LENGTH(cwd) - 1] = 0;
  1570. if (!_Py_wgetcwd(cwd, Py_ARRAY_LENGTH(cwd) - 1)) {
  1571. /* unable to get the current directory */
  1572. return -1;
  1573. }
  1574. size_t cwd_len = wcslen(cwd);
  1575. size_t path_len = wcslen(path);
  1576. size_t len = cwd_len + 1 + path_len + 1;
  1577. if (len <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  1578. *abspath_p = PyMem_RawMalloc(len * sizeof(wchar_t));
  1579. }
  1580. else {
  1581. *abspath_p = NULL;
  1582. }
  1583. if (*abspath_p == NULL) {
  1584. return 0;
  1585. }
  1586. wchar_t *abspath = *abspath_p;
  1587. memcpy(abspath, cwd, cwd_len * sizeof(wchar_t));
  1588. abspath += cwd_len;
  1589. *abspath = (wchar_t)SEP;
  1590. abspath++;
  1591. memcpy(abspath, path, path_len * sizeof(wchar_t));
  1592. abspath += path_len;
  1593. *abspath = 0;
  1594. return 0;
  1595. #endif
  1596. }
  1597. /* Get the current directory. buflen is the buffer size in wide characters
  1598. including the null character. Decode the path from the locale encoding.
  1599. Return NULL on getcwd() error, on decoding error, or if 'buf' is
  1600. too short. */
  1601. wchar_t*
  1602. _Py_wgetcwd(wchar_t *buf, size_t buflen)
  1603. {
  1604. #ifdef MS_WINDOWS
  1605. int ibuflen = (int)Py_MIN(buflen, INT_MAX);
  1606. return _wgetcwd(buf, ibuflen);
  1607. #else
  1608. char fname[MAXPATHLEN];
  1609. wchar_t *wname;
  1610. size_t len;
  1611. if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
  1612. return NULL;
  1613. wname = Py_DecodeLocale(fname, &len);
  1614. if (wname == NULL)
  1615. return NULL;
  1616. /* wname must have space to store the trailing NUL character */
  1617. if (buflen <= len) {
  1618. PyMem_RawFree(wname);
  1619. return NULL;
  1620. }
  1621. wcsncpy(buf, wname, buflen);
  1622. PyMem_RawFree(wname);
  1623. return buf;
  1624. #endif
  1625. }
  1626. /* Duplicate a file descriptor. The new file descriptor is created as
  1627. non-inheritable. Return a new file descriptor on success, raise an OSError
  1628. exception and return -1 on error.
  1629. The GIL is released to call dup(). The caller must hold the GIL. */
  1630. int
  1631. _Py_dup(int fd)
  1632. {
  1633. #ifdef MS_WINDOWS
  1634. HANDLE handle;
  1635. #endif
  1636. assert(PyGILState_Check());
  1637. #ifdef MS_WINDOWS
  1638. _Py_BEGIN_SUPPRESS_IPH
  1639. handle = (HANDLE)_get_osfhandle(fd);
  1640. _Py_END_SUPPRESS_IPH
  1641. if (handle == INVALID_HANDLE_VALUE) {
  1642. PyErr_SetFromErrno(PyExc_OSError);
  1643. return -1;
  1644. }
  1645. Py_BEGIN_ALLOW_THREADS
  1646. _Py_BEGIN_SUPPRESS_IPH
  1647. fd = dup(fd);
  1648. _Py_END_SUPPRESS_IPH
  1649. Py_END_ALLOW_THREADS
  1650. if (fd < 0) {
  1651. PyErr_SetFromErrno(PyExc_OSError);
  1652. return -1;
  1653. }
  1654. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1655. _Py_BEGIN_SUPPRESS_IPH
  1656. close(fd);
  1657. _Py_END_SUPPRESS_IPH
  1658. return -1;
  1659. }
  1660. #elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
  1661. Py_BEGIN_ALLOW_THREADS
  1662. _Py_BEGIN_SUPPRESS_IPH
  1663. fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
  1664. _Py_END_SUPPRESS_IPH
  1665. Py_END_ALLOW_THREADS
  1666. if (fd < 0) {
  1667. PyErr_SetFromErrno(PyExc_OSError);
  1668. return -1;
  1669. }
  1670. #else
  1671. Py_BEGIN_ALLOW_THREADS
  1672. _Py_BEGIN_SUPPRESS_IPH
  1673. fd = dup(fd);
  1674. _Py_END_SUPPRESS_IPH
  1675. Py_END_ALLOW_THREADS
  1676. if (fd < 0) {
  1677. PyErr_SetFromErrno(PyExc_OSError);
  1678. return -1;
  1679. }
  1680. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1681. _Py_BEGIN_SUPPRESS_IPH
  1682. close(fd);
  1683. _Py_END_SUPPRESS_IPH
  1684. return -1;
  1685. }
  1686. #endif
  1687. return fd;
  1688. }
  1689. #ifndef MS_WINDOWS
  1690. /* Get the blocking mode of the file descriptor.
  1691. Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
  1692. raise an exception and return -1 on error. */
  1693. int
  1694. _Py_get_blocking(int fd)
  1695. {
  1696. int flags;
  1697. _Py_BEGIN_SUPPRESS_IPH
  1698. flags = fcntl(fd, F_GETFL, 0);
  1699. _Py_END_SUPPRESS_IPH
  1700. if (flags < 0) {
  1701. PyErr_SetFromErrno(PyExc_OSError);
  1702. return -1;
  1703. }
  1704. return !(flags & O_NONBLOCK);
  1705. }
  1706. /* Set the blocking mode of the specified file descriptor.
  1707. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
  1708. otherwise.
  1709. Return 0 on success, raise an exception and return -1 on error. */
  1710. int
  1711. _Py_set_blocking(int fd, int blocking)
  1712. {
  1713. #if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)
  1714. int arg = !blocking;
  1715. if (ioctl(fd, FIONBIO, &arg) < 0)
  1716. goto error;
  1717. #else
  1718. int flags, res;
  1719. _Py_BEGIN_SUPPRESS_IPH
  1720. flags = fcntl(fd, F_GETFL, 0);
  1721. if (flags >= 0) {
  1722. if (blocking)
  1723. flags = flags & (~O_NONBLOCK);
  1724. else
  1725. flags = flags | O_NONBLOCK;
  1726. res = fcntl(fd, F_SETFL, flags);
  1727. } else {
  1728. res = -1;
  1729. }
  1730. _Py_END_SUPPRESS_IPH
  1731. if (res < 0)
  1732. goto error;
  1733. #endif
  1734. return 0;
  1735. error:
  1736. PyErr_SetFromErrno(PyExc_OSError);
  1737. return -1;
  1738. }
  1739. #endif
  1740. int
  1741. _Py_GetLocaleconvNumeric(struct lconv *lc,
  1742. PyObject **decimal_point, PyObject **thousands_sep)
  1743. {
  1744. assert(decimal_point != NULL);
  1745. assert(thousands_sep != NULL);
  1746. int change_locale = 0;
  1747. if ((strlen(lc->decimal_point) > 1 || ((unsigned char)lc->decimal_point[0]) > 127)) {
  1748. change_locale = 1;
  1749. }
  1750. if ((strlen(lc->thousands_sep) > 1 || ((unsigned char)lc->thousands_sep[0]) > 127)) {
  1751. change_locale = 1;
  1752. }
  1753. /* Keep a copy of the LC_CTYPE locale */
  1754. char *oldloc = NULL, *loc = NULL;
  1755. if (change_locale) {
  1756. oldloc = setlocale(LC_CTYPE, NULL);
  1757. if (!oldloc) {
  1758. PyErr_SetString(PyExc_RuntimeWarning,
  1759. "failed to get LC_CTYPE locale");
  1760. return -1;
  1761. }
  1762. oldloc = _PyMem_Strdup(oldloc);
  1763. if (!oldloc) {
  1764. PyErr_NoMemory();
  1765. return -1;
  1766. }
  1767. loc = setlocale(LC_NUMERIC, NULL);
  1768. if (loc != NULL && strcmp(loc, oldloc) == 0) {
  1769. loc = NULL;
  1770. }
  1771. if (loc != NULL) {
  1772. /* Only set the locale temporarily the LC_CTYPE locale
  1773. if LC_NUMERIC locale is different than LC_CTYPE locale and
  1774. decimal_point and/or thousands_sep are non-ASCII or longer than
  1775. 1 byte */
  1776. setlocale(LC_CTYPE, loc);
  1777. }
  1778. }
  1779. int res = -1;
  1780. *decimal_point = PyUnicode_DecodeLocale(lc->decimal_point, NULL);
  1781. if (*decimal_point == NULL) {
  1782. goto done;
  1783. }
  1784. *thousands_sep = PyUnicode_DecodeLocale(lc->thousands_sep, NULL);
  1785. if (*thousands_sep == NULL) {
  1786. goto done;
  1787. }
  1788. res = 0;
  1789. done:
  1790. if (loc != NULL) {
  1791. setlocale(LC_CTYPE, oldloc);
  1792. }
  1793. PyMem_Free(oldloc);
  1794. return res;
  1795. }