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.

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