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.

1825 lines
48 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. return decode_current_locale(arg, wstr, wlen, reason, surrogateescape);
  401. }
  402. #if defined(__APPLE__) || defined(__ANDROID__)
  403. return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
  404. surrogateescape);
  405. #else
  406. if (Py_UTF8Mode == 1) {
  407. return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
  408. surrogateescape);
  409. }
  410. #ifdef USE_FORCE_ASCII
  411. if (force_ascii == -1) {
  412. force_ascii = check_force_ascii();
  413. }
  414. if (force_ascii) {
  415. /* force ASCII encoding to workaround mbstowcs() issue */
  416. return decode_ascii(arg, wstr, wlen, reason, surrogateescape);
  417. }
  418. #endif
  419. return decode_current_locale(arg, wstr, wlen, reason, surrogateescape);
  420. #endif /* __APPLE__ or __ANDROID__ */
  421. }
  422. /* Decode a byte string from the locale encoding with the
  423. surrogateescape error handler: undecodable bytes are decoded as characters
  424. in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate
  425. character, escape the bytes using the surrogateescape error handler instead
  426. of decoding them.
  427. Return a pointer to a newly allocated wide character string, use
  428. PyMem_RawFree() to free the memory. If size is not NULL, write the number of
  429. wide characters excluding the null character into *size
  430. Return NULL on decoding error or memory allocation error. If *size* is not
  431. NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on
  432. decoding error.
  433. Decoding errors should never happen, unless there is a bug in the C
  434. library.
  435. Use the Py_EncodeLocale() function to encode the character string back to a
  436. byte string. */
  437. wchar_t*
  438. Py_DecodeLocale(const char* arg, size_t *wlen)
  439. {
  440. wchar_t *wstr;
  441. int res = _Py_DecodeLocaleEx(arg, &wstr, wlen, NULL, 0, 1);
  442. if (res != 0) {
  443. if (wlen != NULL) {
  444. *wlen = (size_t)res;
  445. }
  446. return NULL;
  447. }
  448. return wstr;
  449. }
  450. static int
  451. encode_current_locale(const wchar_t *text, char **str,
  452. size_t *error_pos, const char **reason,
  453. int raw_malloc, int surrogateescape)
  454. {
  455. const size_t len = wcslen(text);
  456. char *result = NULL, *bytes = NULL;
  457. size_t i, size, converted;
  458. wchar_t c, buf[2];
  459. /* The function works in two steps:
  460. 1. compute the length of the output buffer in bytes (size)
  461. 2. outputs the bytes */
  462. size = 0;
  463. buf[1] = 0;
  464. while (1) {
  465. for (i=0; i < len; i++) {
  466. c = text[i];
  467. if (c >= 0xdc80 && c <= 0xdcff) {
  468. if (!surrogateescape) {
  469. goto encode_error;
  470. }
  471. /* UTF-8b surrogate */
  472. if (bytes != NULL) {
  473. *bytes++ = c - 0xdc00;
  474. size--;
  475. }
  476. else {
  477. size++;
  478. }
  479. continue;
  480. }
  481. else {
  482. buf[0] = c;
  483. if (bytes != NULL) {
  484. converted = wcstombs(bytes, buf, size);
  485. }
  486. else {
  487. converted = wcstombs(NULL, buf, 0);
  488. }
  489. if (converted == (size_t)-1) {
  490. goto encode_error;
  491. }
  492. if (bytes != NULL) {
  493. bytes += converted;
  494. size -= converted;
  495. }
  496. else {
  497. size += converted;
  498. }
  499. }
  500. }
  501. if (result != NULL) {
  502. *bytes = '\0';
  503. break;
  504. }
  505. size += 1; /* nul byte at the end */
  506. if (raw_malloc) {
  507. result = PyMem_RawMalloc(size);
  508. }
  509. else {
  510. result = PyMem_Malloc(size);
  511. }
  512. if (result == NULL) {
  513. return -1;
  514. }
  515. bytes = result;
  516. }
  517. *str = result;
  518. return 0;
  519. encode_error:
  520. if (raw_malloc) {
  521. PyMem_RawFree(result);
  522. }
  523. else {
  524. PyMem_Free(result);
  525. }
  526. if (error_pos != NULL) {
  527. *error_pos = i;
  528. }
  529. if (reason) {
  530. *reason = "encoding error";
  531. }
  532. return -2;
  533. }
  534. static int
  535. encode_locale_ex(const wchar_t *text, char **str, size_t *error_pos,
  536. const char **reason,
  537. int raw_malloc, int current_locale, int surrogateescape)
  538. {
  539. if (current_locale) {
  540. return encode_current_locale(text, str, error_pos, reason,
  541. raw_malloc, surrogateescape);
  542. }
  543. #if defined(__APPLE__) || defined(__ANDROID__)
  544. return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
  545. raw_malloc, surrogateescape);
  546. #else /* __APPLE__ */
  547. if (Py_UTF8Mode == 1) {
  548. return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
  549. raw_malloc, surrogateescape);
  550. }
  551. #ifdef USE_FORCE_ASCII
  552. if (force_ascii == -1) {
  553. force_ascii = check_force_ascii();
  554. }
  555. if (force_ascii) {
  556. return encode_ascii(text, str, error_pos, reason,
  557. raw_malloc, surrogateescape);
  558. }
  559. #endif
  560. return encode_current_locale(text, str, error_pos, reason,
  561. raw_malloc, surrogateescape);
  562. #endif /* __APPLE__ or __ANDROID__ */
  563. }
  564. static char*
  565. encode_locale(const wchar_t *text, size_t *error_pos,
  566. int raw_malloc, int current_locale)
  567. {
  568. char *str;
  569. int res = encode_locale_ex(text, &str, error_pos, NULL,
  570. raw_malloc, current_locale, 1);
  571. if (res != -2 && error_pos) {
  572. *error_pos = (size_t)-1;
  573. }
  574. if (res != 0) {
  575. return NULL;
  576. }
  577. return str;
  578. }
  579. /* Encode a wide character string to the locale encoding with the
  580. surrogateescape error handler: surrogate characters in the range
  581. U+DC80..U+DCFF are converted to bytes 0x80..0xFF.
  582. Return a pointer to a newly allocated byte string, use PyMem_Free() to free
  583. the memory. Return NULL on encoding or memory allocation error.
  584. If error_pos is not NULL, *error_pos is set to (size_t)-1 on success, or set
  585. to the index of the invalid character on encoding error.
  586. Use the Py_DecodeLocale() function to decode the bytes string back to a wide
  587. character string. */
  588. char*
  589. Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
  590. {
  591. return encode_locale(text, error_pos, 0, 0);
  592. }
  593. /* Similar to Py_EncodeLocale(), but result must be freed by PyMem_RawFree()
  594. instead of PyMem_Free(). */
  595. char*
  596. _Py_EncodeLocaleRaw(const wchar_t *text, size_t *error_pos)
  597. {
  598. return encode_locale(text, error_pos, 1, 0);
  599. }
  600. int
  601. _Py_EncodeLocaleEx(const wchar_t *text, char **str,
  602. size_t *error_pos, const char **reason,
  603. int current_locale, int surrogateescape)
  604. {
  605. return encode_locale_ex(text, str, error_pos, reason, 1,
  606. current_locale, surrogateescape);
  607. }
  608. #ifdef MS_WINDOWS
  609. static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
  610. static void
  611. FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
  612. {
  613. /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
  614. /* Cannot simply cast and dereference in_ptr,
  615. since it might not be aligned properly */
  616. __int64 in;
  617. memcpy(&in, in_ptr, sizeof(in));
  618. *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
  619. *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
  620. }
  621. void
  622. _Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
  623. {
  624. /* XXX endianness */
  625. __int64 out;
  626. out = time_in + secs_between_epochs;
  627. out = out * 10000000 + nsec_in / 100;
  628. memcpy(out_ptr, &out, sizeof(out));
  629. }
  630. /* Below, we *know* that ugo+r is 0444 */
  631. #if _S_IREAD != 0400
  632. #error Unsupported C library
  633. #endif
  634. static int
  635. attributes_to_mode(DWORD attr)
  636. {
  637. int m = 0;
  638. if (attr & FILE_ATTRIBUTE_DIRECTORY)
  639. m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
  640. else
  641. m |= _S_IFREG;
  642. if (attr & FILE_ATTRIBUTE_READONLY)
  643. m |= 0444;
  644. else
  645. m |= 0666;
  646. return m;
  647. }
  648. void
  649. _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
  650. struct _Py_stat_struct *result)
  651. {
  652. memset(result, 0, sizeof(*result));
  653. result->st_mode = attributes_to_mode(info->dwFileAttributes);
  654. result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
  655. result->st_dev = info->dwVolumeSerialNumber;
  656. result->st_rdev = result->st_dev;
  657. FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
  658. FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  659. FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  660. result->st_nlink = info->nNumberOfLinks;
  661. result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow;
  662. if (reparse_tag == IO_REPARSE_TAG_SYMLINK) {
  663. /* first clear the S_IFMT bits */
  664. result->st_mode ^= (result->st_mode & S_IFMT);
  665. /* now set the bits that make this a symlink */
  666. result->st_mode |= S_IFLNK;
  667. }
  668. result->st_file_attributes = info->dwFileAttributes;
  669. }
  670. #endif
  671. /* Return information about a file.
  672. On POSIX, use fstat().
  673. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  674. files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
  675. than 2 GiB because the file size type is a signed 32-bit integer: see issue
  676. #23152.
  677. On Windows, set the last Windows error and return nonzero on error. On
  678. POSIX, set errno and return nonzero on error. Fill status and return 0 on
  679. success. */
  680. int
  681. _Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
  682. {
  683. #ifdef MS_WINDOWS
  684. BY_HANDLE_FILE_INFORMATION info;
  685. HANDLE h;
  686. int type;
  687. _Py_BEGIN_SUPPRESS_IPH
  688. h = (HANDLE)_get_osfhandle(fd);
  689. _Py_END_SUPPRESS_IPH
  690. if (h == INVALID_HANDLE_VALUE) {
  691. /* errno is already set by _get_osfhandle, but we also set
  692. the Win32 error for callers who expect that */
  693. SetLastError(ERROR_INVALID_HANDLE);
  694. return -1;
  695. }
  696. memset(status, 0, sizeof(*status));
  697. type = GetFileType(h);
  698. if (type == FILE_TYPE_UNKNOWN) {
  699. DWORD error = GetLastError();
  700. if (error != 0) {
  701. errno = winerror_to_errno(error);
  702. return -1;
  703. }
  704. /* else: valid but unknown file */
  705. }
  706. if (type != FILE_TYPE_DISK) {
  707. if (type == FILE_TYPE_CHAR)
  708. status->st_mode = _S_IFCHR;
  709. else if (type == FILE_TYPE_PIPE)
  710. status->st_mode = _S_IFIFO;
  711. return 0;
  712. }
  713. if (!GetFileInformationByHandle(h, &info)) {
  714. /* The Win32 error is already set, but we also set errno for
  715. callers who expect it */
  716. errno = winerror_to_errno(GetLastError());
  717. return -1;
  718. }
  719. _Py_attribute_data_to_stat(&info, 0, status);
  720. /* specific to fstat() */
  721. status->st_ino = (((uint64_t)info.nFileIndexHigh) << 32) + info.nFileIndexLow;
  722. return 0;
  723. #else
  724. return fstat(fd, status);
  725. #endif
  726. }
  727. /* Return information about a file.
  728. On POSIX, use fstat().
  729. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  730. files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
  731. than 2 GiB because the file size type is a signed 32-bit integer: see issue
  732. #23152.
  733. Raise an exception and return -1 on error. On Windows, set the last Windows
  734. error on error. On POSIX, set errno on error. Fill status and return 0 on
  735. success.
  736. Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
  737. to call fstat(). The caller must hold the GIL. */
  738. int
  739. _Py_fstat(int fd, struct _Py_stat_struct *status)
  740. {
  741. int res;
  742. assert(PyGILState_Check());
  743. Py_BEGIN_ALLOW_THREADS
  744. res = _Py_fstat_noraise(fd, status);
  745. Py_END_ALLOW_THREADS
  746. if (res != 0) {
  747. #ifdef MS_WINDOWS
  748. PyErr_SetFromWindowsErr(0);
  749. #else
  750. PyErr_SetFromErrno(PyExc_OSError);
  751. #endif
  752. return -1;
  753. }
  754. return 0;
  755. }
  756. /* Call _wstat() on Windows, or encode the path to the filesystem encoding and
  757. call stat() otherwise. Only fill st_mode attribute on Windows.
  758. Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
  759. raised. */
  760. int
  761. _Py_stat(PyObject *path, struct stat *statbuf)
  762. {
  763. #ifdef MS_WINDOWS
  764. int err;
  765. struct _stat wstatbuf;
  766. const wchar_t *wpath;
  767. wpath = _PyUnicode_AsUnicode(path);
  768. if (wpath == NULL)
  769. return -2;
  770. err = _wstat(wpath, &wstatbuf);
  771. if (!err)
  772. statbuf->st_mode = wstatbuf.st_mode;
  773. return err;
  774. #else
  775. int ret;
  776. PyObject *bytes;
  777. char *cpath;
  778. bytes = PyUnicode_EncodeFSDefault(path);
  779. if (bytes == NULL)
  780. return -2;
  781. /* check for embedded null bytes */
  782. if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
  783. Py_DECREF(bytes);
  784. return -2;
  785. }
  786. ret = stat(cpath, statbuf);
  787. Py_DECREF(bytes);
  788. return ret;
  789. #endif
  790. }
  791. static int
  792. get_inheritable(int fd, int raise)
  793. {
  794. #ifdef MS_WINDOWS
  795. HANDLE handle;
  796. DWORD flags;
  797. _Py_BEGIN_SUPPRESS_IPH
  798. handle = (HANDLE)_get_osfhandle(fd);
  799. _Py_END_SUPPRESS_IPH
  800. if (handle == INVALID_HANDLE_VALUE) {
  801. if (raise)
  802. PyErr_SetFromErrno(PyExc_OSError);
  803. return -1;
  804. }
  805. if (!GetHandleInformation(handle, &flags)) {
  806. if (raise)
  807. PyErr_SetFromWindowsErr(0);
  808. return -1;
  809. }
  810. return (flags & HANDLE_FLAG_INHERIT);
  811. #else
  812. int flags;
  813. flags = fcntl(fd, F_GETFD, 0);
  814. if (flags == -1) {
  815. if (raise)
  816. PyErr_SetFromErrno(PyExc_OSError);
  817. return -1;
  818. }
  819. return !(flags & FD_CLOEXEC);
  820. #endif
  821. }
  822. /* Get the inheritable flag of the specified file descriptor.
  823. Return 1 if the file descriptor can be inherited, 0 if it cannot,
  824. raise an exception and return -1 on error. */
  825. int
  826. _Py_get_inheritable(int fd)
  827. {
  828. return get_inheritable(fd, 1);
  829. }
  830. static int
  831. set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
  832. {
  833. #ifdef MS_WINDOWS
  834. HANDLE handle;
  835. DWORD flags;
  836. #else
  837. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  838. static int ioctl_works = -1;
  839. int request;
  840. int err;
  841. #endif
  842. int flags, new_flags;
  843. int res;
  844. #endif
  845. /* atomic_flag_works can only be used to make the file descriptor
  846. non-inheritable */
  847. assert(!(atomic_flag_works != NULL && inheritable));
  848. if (atomic_flag_works != NULL && !inheritable) {
  849. if (*atomic_flag_works == -1) {
  850. int isInheritable = get_inheritable(fd, raise);
  851. if (isInheritable == -1)
  852. return -1;
  853. *atomic_flag_works = !isInheritable;
  854. }
  855. if (*atomic_flag_works)
  856. return 0;
  857. }
  858. #ifdef MS_WINDOWS
  859. _Py_BEGIN_SUPPRESS_IPH
  860. handle = (HANDLE)_get_osfhandle(fd);
  861. _Py_END_SUPPRESS_IPH
  862. if (handle == INVALID_HANDLE_VALUE) {
  863. if (raise)
  864. PyErr_SetFromErrno(PyExc_OSError);
  865. return -1;
  866. }
  867. if (inheritable)
  868. flags = HANDLE_FLAG_INHERIT;
  869. else
  870. flags = 0;
  871. if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
  872. if (raise)
  873. PyErr_SetFromWindowsErr(0);
  874. return -1;
  875. }
  876. return 0;
  877. #else
  878. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  879. if (ioctl_works != 0) {
  880. /* fast-path: ioctl() only requires one syscall */
  881. if (inheritable)
  882. request = FIONCLEX;
  883. else
  884. request = FIOCLEX;
  885. err = ioctl(fd, request, NULL);
  886. if (!err) {
  887. ioctl_works = 1;
  888. return 0;
  889. }
  890. if (errno != ENOTTY && errno != EACCES) {
  891. if (raise)
  892. PyErr_SetFromErrno(PyExc_OSError);
  893. return -1;
  894. }
  895. else {
  896. /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
  897. device". The ioctl is declared but not supported by the kernel.
  898. Remember that ioctl() doesn't work. It is the case on
  899. Illumos-based OS for example.
  900. Issue #27057: When SELinux policy disallows ioctl it will fail
  901. with EACCES. While FIOCLEX is safe operation it may be
  902. unavailable because ioctl was denied altogether.
  903. This can be the case on Android. */
  904. ioctl_works = 0;
  905. }
  906. /* fallback to fcntl() if ioctl() does not work */
  907. }
  908. #endif
  909. /* slow-path: fcntl() requires two syscalls */
  910. flags = fcntl(fd, F_GETFD);
  911. if (flags < 0) {
  912. if (raise)
  913. PyErr_SetFromErrno(PyExc_OSError);
  914. return -1;
  915. }
  916. if (inheritable) {
  917. new_flags = flags & ~FD_CLOEXEC;
  918. }
  919. else {
  920. new_flags = flags | FD_CLOEXEC;
  921. }
  922. if (new_flags == flags) {
  923. /* FD_CLOEXEC flag already set/cleared: nothing to do */
  924. return 0;
  925. }
  926. res = fcntl(fd, F_SETFD, new_flags);
  927. if (res < 0) {
  928. if (raise)
  929. PyErr_SetFromErrno(PyExc_OSError);
  930. return -1;
  931. }
  932. return 0;
  933. #endif
  934. }
  935. /* Make the file descriptor non-inheritable.
  936. Return 0 on success, set errno and return -1 on error. */
  937. static int
  938. make_non_inheritable(int fd)
  939. {
  940. return set_inheritable(fd, 0, 0, NULL);
  941. }
  942. /* Set the inheritable flag of the specified file descriptor.
  943. On success: return 0, on error: raise an exception if raise is nonzero
  944. and return -1.
  945. If atomic_flag_works is not NULL:
  946. * if *atomic_flag_works==-1, check if the inheritable is set on the file
  947. descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
  948. set the inheritable flag
  949. * if *atomic_flag_works==1: do nothing
  950. * if *atomic_flag_works==0: set inheritable flag to False
  951. Set atomic_flag_works to NULL if no atomic flag was used to create the
  952. file descriptor.
  953. atomic_flag_works can only be used to make a file descriptor
  954. non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
  955. int
  956. _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
  957. {
  958. return set_inheritable(fd, inheritable, 1, atomic_flag_works);
  959. }
  960. static int
  961. _Py_open_impl(const char *pathname, int flags, int gil_held)
  962. {
  963. int fd;
  964. int async_err = 0;
  965. #ifndef MS_WINDOWS
  966. int *atomic_flag_works;
  967. #endif
  968. #ifdef MS_WINDOWS
  969. flags |= O_NOINHERIT;
  970. #elif defined(O_CLOEXEC)
  971. atomic_flag_works = &_Py_open_cloexec_works;
  972. flags |= O_CLOEXEC;
  973. #else
  974. atomic_flag_works = NULL;
  975. #endif
  976. if (gil_held) {
  977. do {
  978. Py_BEGIN_ALLOW_THREADS
  979. fd = open(pathname, flags);
  980. Py_END_ALLOW_THREADS
  981. } while (fd < 0
  982. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  983. if (async_err)
  984. return -1;
  985. if (fd < 0) {
  986. PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname);
  987. return -1;
  988. }
  989. }
  990. else {
  991. fd = open(pathname, flags);
  992. if (fd < 0)
  993. return -1;
  994. }
  995. #ifndef MS_WINDOWS
  996. if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
  997. close(fd);
  998. return -1;
  999. }
  1000. #endif
  1001. return fd;
  1002. }
  1003. /* Open a file with the specified flags (wrapper to open() function).
  1004. Return a file descriptor on success. Raise an exception and return -1 on
  1005. error.
  1006. The file descriptor is created non-inheritable.
  1007. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  1008. except if the Python signal handler raises an exception.
  1009. Release the GIL to call open(). The caller must hold the GIL. */
  1010. int
  1011. _Py_open(const char *pathname, int flags)
  1012. {
  1013. /* _Py_open() must be called with the GIL held. */
  1014. assert(PyGILState_Check());
  1015. return _Py_open_impl(pathname, flags, 1);
  1016. }
  1017. /* Open a file with the specified flags (wrapper to open() function).
  1018. Return a file descriptor on success. Set errno and return -1 on error.
  1019. The file descriptor is created non-inheritable.
  1020. If interrupted by a signal, fail with EINTR. */
  1021. int
  1022. _Py_open_noraise(const char *pathname, int flags)
  1023. {
  1024. return _Py_open_impl(pathname, flags, 0);
  1025. }
  1026. /* Open a file. Use _wfopen() on Windows, encode the path to the locale
  1027. encoding and use fopen() otherwise.
  1028. The file descriptor is created non-inheritable.
  1029. If interrupted by a signal, fail with EINTR. */
  1030. FILE *
  1031. _Py_wfopen(const wchar_t *path, const wchar_t *mode)
  1032. {
  1033. FILE *f;
  1034. #ifndef MS_WINDOWS
  1035. char *cpath;
  1036. char cmode[10];
  1037. size_t r;
  1038. r = wcstombs(cmode, mode, 10);
  1039. if (r == (size_t)-1 || r >= 10) {
  1040. errno = EINVAL;
  1041. return NULL;
  1042. }
  1043. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1044. if (cpath == NULL) {
  1045. return NULL;
  1046. }
  1047. f = fopen(cpath, cmode);
  1048. PyMem_RawFree(cpath);
  1049. #else
  1050. f = _wfopen(path, mode);
  1051. #endif
  1052. if (f == NULL)
  1053. return NULL;
  1054. if (make_non_inheritable(fileno(f)) < 0) {
  1055. fclose(f);
  1056. return NULL;
  1057. }
  1058. return f;
  1059. }
  1060. /* Wrapper to fopen().
  1061. The file descriptor is created non-inheritable.
  1062. If interrupted by a signal, fail with EINTR. */
  1063. FILE*
  1064. _Py_fopen(const char *pathname, const char *mode)
  1065. {
  1066. FILE *f = fopen(pathname, mode);
  1067. if (f == NULL)
  1068. return NULL;
  1069. if (make_non_inheritable(fileno(f)) < 0) {
  1070. fclose(f);
  1071. return NULL;
  1072. }
  1073. return f;
  1074. }
  1075. /* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
  1076. encoding and call fopen() otherwise.
  1077. Return the new file object on success. Raise an exception and return NULL
  1078. on error.
  1079. The file descriptor is created non-inheritable.
  1080. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  1081. except if the Python signal handler raises an exception.
  1082. Release the GIL to call _wfopen() or fopen(). The caller must hold
  1083. the GIL. */
  1084. FILE*
  1085. _Py_fopen_obj(PyObject *path, const char *mode)
  1086. {
  1087. FILE *f;
  1088. int async_err = 0;
  1089. #ifdef MS_WINDOWS
  1090. const wchar_t *wpath;
  1091. wchar_t wmode[10];
  1092. int usize;
  1093. assert(PyGILState_Check());
  1094. if (!PyUnicode_Check(path)) {
  1095. PyErr_Format(PyExc_TypeError,
  1096. "str file path expected under Windows, got %R",
  1097. Py_TYPE(path));
  1098. return NULL;
  1099. }
  1100. wpath = _PyUnicode_AsUnicode(path);
  1101. if (wpath == NULL)
  1102. return NULL;
  1103. usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
  1104. if (usize == 0) {
  1105. PyErr_SetFromWindowsErr(0);
  1106. return NULL;
  1107. }
  1108. do {
  1109. Py_BEGIN_ALLOW_THREADS
  1110. f = _wfopen(wpath, wmode);
  1111. Py_END_ALLOW_THREADS
  1112. } while (f == NULL
  1113. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1114. #else
  1115. PyObject *bytes;
  1116. char *path_bytes;
  1117. assert(PyGILState_Check());
  1118. if (!PyUnicode_FSConverter(path, &bytes))
  1119. return NULL;
  1120. path_bytes = PyBytes_AS_STRING(bytes);
  1121. do {
  1122. Py_BEGIN_ALLOW_THREADS
  1123. f = fopen(path_bytes, mode);
  1124. Py_END_ALLOW_THREADS
  1125. } while (f == NULL
  1126. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1127. Py_DECREF(bytes);
  1128. #endif
  1129. if (async_err)
  1130. return NULL;
  1131. if (f == NULL) {
  1132. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1133. return NULL;
  1134. }
  1135. if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
  1136. fclose(f);
  1137. return NULL;
  1138. }
  1139. return f;
  1140. }
  1141. /* Read count bytes from fd into buf.
  1142. On success, return the number of read bytes, it can be lower than count.
  1143. If the current file offset is at or past the end of file, no bytes are read,
  1144. and read() returns zero.
  1145. On error, raise an exception, set errno and return -1.
  1146. When interrupted by a signal (read() fails with EINTR), retry the syscall.
  1147. If the Python signal handler raises an exception, the function returns -1
  1148. (the syscall is not retried).
  1149. Release the GIL to call read(). The caller must hold the GIL. */
  1150. Py_ssize_t
  1151. _Py_read(int fd, void *buf, size_t count)
  1152. {
  1153. Py_ssize_t n;
  1154. int err;
  1155. int async_err = 0;
  1156. assert(PyGILState_Check());
  1157. /* _Py_read() must not be called with an exception set, otherwise the
  1158. * caller may think that read() was interrupted by a signal and the signal
  1159. * handler raised an exception. */
  1160. assert(!PyErr_Occurred());
  1161. #ifdef MS_WINDOWS
  1162. if (count > INT_MAX) {
  1163. /* On Windows, the count parameter of read() is an int */
  1164. count = INT_MAX;
  1165. }
  1166. #else
  1167. if (count > PY_SSIZE_T_MAX) {
  1168. /* if count is greater than PY_SSIZE_T_MAX,
  1169. * read() result is undefined */
  1170. count = PY_SSIZE_T_MAX;
  1171. }
  1172. #endif
  1173. _Py_BEGIN_SUPPRESS_IPH
  1174. do {
  1175. Py_BEGIN_ALLOW_THREADS
  1176. errno = 0;
  1177. #ifdef MS_WINDOWS
  1178. n = read(fd, buf, (int)count);
  1179. #else
  1180. n = read(fd, buf, count);
  1181. #endif
  1182. /* save/restore errno because PyErr_CheckSignals()
  1183. * and PyErr_SetFromErrno() can modify it */
  1184. err = errno;
  1185. Py_END_ALLOW_THREADS
  1186. } while (n < 0 && err == EINTR &&
  1187. !(async_err = PyErr_CheckSignals()));
  1188. _Py_END_SUPPRESS_IPH
  1189. if (async_err) {
  1190. /* read() was interrupted by a signal (failed with EINTR)
  1191. * and the Python signal handler raised an exception */
  1192. errno = err;
  1193. assert(errno == EINTR && PyErr_Occurred());
  1194. return -1;
  1195. }
  1196. if (n < 0) {
  1197. PyErr_SetFromErrno(PyExc_OSError);
  1198. errno = err;
  1199. return -1;
  1200. }
  1201. return n;
  1202. }
  1203. static Py_ssize_t
  1204. _Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
  1205. {
  1206. Py_ssize_t n;
  1207. int err;
  1208. int async_err = 0;
  1209. _Py_BEGIN_SUPPRESS_IPH
  1210. #ifdef MS_WINDOWS
  1211. if (count > 32767 && isatty(fd)) {
  1212. /* Issue #11395: the Windows console returns an error (12: not
  1213. enough space error) on writing into stdout if stdout mode is
  1214. binary and the length is greater than 66,000 bytes (or less,
  1215. depending on heap usage). */
  1216. count = 32767;
  1217. }
  1218. else if (count > INT_MAX)
  1219. count = INT_MAX;
  1220. #else
  1221. if (count > PY_SSIZE_T_MAX) {
  1222. /* write() should truncate count to PY_SSIZE_T_MAX, but it's safer
  1223. * to do it ourself to have a portable behaviour. */
  1224. count = PY_SSIZE_T_MAX;
  1225. }
  1226. #endif
  1227. if (gil_held) {
  1228. do {
  1229. Py_BEGIN_ALLOW_THREADS
  1230. errno = 0;
  1231. #ifdef MS_WINDOWS
  1232. n = write(fd, buf, (int)count);
  1233. #else
  1234. n = write(fd, buf, count);
  1235. #endif
  1236. /* save/restore errno because PyErr_CheckSignals()
  1237. * and PyErr_SetFromErrno() can modify it */
  1238. err = errno;
  1239. Py_END_ALLOW_THREADS
  1240. } while (n < 0 && err == EINTR &&
  1241. !(async_err = PyErr_CheckSignals()));
  1242. }
  1243. else {
  1244. do {
  1245. errno = 0;
  1246. #ifdef MS_WINDOWS
  1247. n = write(fd, buf, (int)count);
  1248. #else
  1249. n = write(fd, buf, count);
  1250. #endif
  1251. err = errno;
  1252. } while (n < 0 && err == EINTR);
  1253. }
  1254. _Py_END_SUPPRESS_IPH
  1255. if (async_err) {
  1256. /* write() was interrupted by a signal (failed with EINTR)
  1257. and the Python signal handler raised an exception (if gil_held is
  1258. nonzero). */
  1259. errno = err;
  1260. assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
  1261. return -1;
  1262. }
  1263. if (n < 0) {
  1264. if (gil_held)
  1265. PyErr_SetFromErrno(PyExc_OSError);
  1266. errno = err;
  1267. return -1;
  1268. }
  1269. return n;
  1270. }
  1271. /* Write count bytes of buf into fd.
  1272. On success, return the number of written bytes, it can be lower than count
  1273. including 0. On error, raise an exception, set errno and return -1.
  1274. When interrupted by a signal (write() fails with EINTR), retry the syscall.
  1275. If the Python signal handler raises an exception, the function returns -1
  1276. (the syscall is not retried).
  1277. Release the GIL to call write(). The caller must hold the GIL. */
  1278. Py_ssize_t
  1279. _Py_write(int fd, const void *buf, size_t count)
  1280. {
  1281. assert(PyGILState_Check());
  1282. /* _Py_write() must not be called with an exception set, otherwise the
  1283. * caller may think that write() was interrupted by a signal and the signal
  1284. * handler raised an exception. */
  1285. assert(!PyErr_Occurred());
  1286. return _Py_write_impl(fd, buf, count, 1);
  1287. }
  1288. /* Write count bytes of buf into fd.
  1289. *
  1290. * On success, return the number of written bytes, it can be lower than count
  1291. * including 0. On error, set errno and return -1.
  1292. *
  1293. * When interrupted by a signal (write() fails with EINTR), retry the syscall
  1294. * without calling the Python signal handler. */
  1295. Py_ssize_t
  1296. _Py_write_noraise(int fd, const void *buf, size_t count)
  1297. {
  1298. return _Py_write_impl(fd, buf, count, 0);
  1299. }
  1300. #ifdef HAVE_READLINK
  1301. /* Read value of symbolic link. Encode the path to the locale encoding, decode
  1302. the result from the locale encoding. Return -1 on error. */
  1303. int
  1304. _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
  1305. {
  1306. char *cpath;
  1307. char cbuf[MAXPATHLEN];
  1308. wchar_t *wbuf;
  1309. int res;
  1310. size_t r1;
  1311. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1312. if (cpath == NULL) {
  1313. errno = EINVAL;
  1314. return -1;
  1315. }
  1316. res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf));
  1317. PyMem_RawFree(cpath);
  1318. if (res == -1)
  1319. return -1;
  1320. if (res == Py_ARRAY_LENGTH(cbuf)) {
  1321. errno = EINVAL;
  1322. return -1;
  1323. }
  1324. cbuf[res] = '\0'; /* buf will be null terminated */
  1325. wbuf = Py_DecodeLocale(cbuf, &r1);
  1326. if (wbuf == NULL) {
  1327. errno = EINVAL;
  1328. return -1;
  1329. }
  1330. if (bufsiz <= r1) {
  1331. PyMem_RawFree(wbuf);
  1332. errno = EINVAL;
  1333. return -1;
  1334. }
  1335. wcsncpy(buf, wbuf, bufsiz);
  1336. PyMem_RawFree(wbuf);
  1337. return (int)r1;
  1338. }
  1339. #endif
  1340. #ifdef HAVE_REALPATH
  1341. /* Return the canonicalized absolute pathname. Encode path to the locale
  1342. encoding, decode the result from the locale encoding.
  1343. Return NULL on error. */
  1344. wchar_t*
  1345. _Py_wrealpath(const wchar_t *path,
  1346. wchar_t *resolved_path, size_t resolved_path_size)
  1347. {
  1348. char *cpath;
  1349. char cresolved_path[MAXPATHLEN];
  1350. wchar_t *wresolved_path;
  1351. char *res;
  1352. size_t r;
  1353. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1354. if (cpath == NULL) {
  1355. errno = EINVAL;
  1356. return NULL;
  1357. }
  1358. res = realpath(cpath, cresolved_path);
  1359. PyMem_RawFree(cpath);
  1360. if (res == NULL)
  1361. return NULL;
  1362. wresolved_path = Py_DecodeLocale(cresolved_path, &r);
  1363. if (wresolved_path == NULL) {
  1364. errno = EINVAL;
  1365. return NULL;
  1366. }
  1367. if (resolved_path_size <= r) {
  1368. PyMem_RawFree(wresolved_path);
  1369. errno = EINVAL;
  1370. return NULL;
  1371. }
  1372. wcsncpy(resolved_path, wresolved_path, resolved_path_size);
  1373. PyMem_RawFree(wresolved_path);
  1374. return resolved_path;
  1375. }
  1376. #endif
  1377. /* Get the current directory. size is the buffer size in wide characters
  1378. including the null character. Decode the path from the locale encoding.
  1379. Return NULL on error. */
  1380. wchar_t*
  1381. _Py_wgetcwd(wchar_t *buf, size_t size)
  1382. {
  1383. #ifdef MS_WINDOWS
  1384. int isize = (int)Py_MIN(size, INT_MAX);
  1385. return _wgetcwd(buf, isize);
  1386. #else
  1387. char fname[MAXPATHLEN];
  1388. wchar_t *wname;
  1389. size_t len;
  1390. if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
  1391. return NULL;
  1392. wname = Py_DecodeLocale(fname, &len);
  1393. if (wname == NULL)
  1394. return NULL;
  1395. if (size <= len) {
  1396. PyMem_RawFree(wname);
  1397. return NULL;
  1398. }
  1399. wcsncpy(buf, wname, size);
  1400. PyMem_RawFree(wname);
  1401. return buf;
  1402. #endif
  1403. }
  1404. /* Duplicate a file descriptor. The new file descriptor is created as
  1405. non-inheritable. Return a new file descriptor on success, raise an OSError
  1406. exception and return -1 on error.
  1407. The GIL is released to call dup(). The caller must hold the GIL. */
  1408. int
  1409. _Py_dup(int fd)
  1410. {
  1411. #ifdef MS_WINDOWS
  1412. HANDLE handle;
  1413. DWORD ftype;
  1414. #endif
  1415. assert(PyGILState_Check());
  1416. #ifdef MS_WINDOWS
  1417. _Py_BEGIN_SUPPRESS_IPH
  1418. handle = (HANDLE)_get_osfhandle(fd);
  1419. _Py_END_SUPPRESS_IPH
  1420. if (handle == INVALID_HANDLE_VALUE) {
  1421. PyErr_SetFromErrno(PyExc_OSError);
  1422. return -1;
  1423. }
  1424. /* get the file type, ignore the error if it failed */
  1425. ftype = GetFileType(handle);
  1426. Py_BEGIN_ALLOW_THREADS
  1427. _Py_BEGIN_SUPPRESS_IPH
  1428. fd = dup(fd);
  1429. _Py_END_SUPPRESS_IPH
  1430. Py_END_ALLOW_THREADS
  1431. if (fd < 0) {
  1432. PyErr_SetFromErrno(PyExc_OSError);
  1433. return -1;
  1434. }
  1435. /* Character files like console cannot be make non-inheritable */
  1436. if (ftype != FILE_TYPE_CHAR) {
  1437. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1438. _Py_BEGIN_SUPPRESS_IPH
  1439. close(fd);
  1440. _Py_END_SUPPRESS_IPH
  1441. return -1;
  1442. }
  1443. }
  1444. #elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
  1445. Py_BEGIN_ALLOW_THREADS
  1446. _Py_BEGIN_SUPPRESS_IPH
  1447. fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
  1448. _Py_END_SUPPRESS_IPH
  1449. Py_END_ALLOW_THREADS
  1450. if (fd < 0) {
  1451. PyErr_SetFromErrno(PyExc_OSError);
  1452. return -1;
  1453. }
  1454. #else
  1455. Py_BEGIN_ALLOW_THREADS
  1456. _Py_BEGIN_SUPPRESS_IPH
  1457. fd = dup(fd);
  1458. _Py_END_SUPPRESS_IPH
  1459. Py_END_ALLOW_THREADS
  1460. if (fd < 0) {
  1461. PyErr_SetFromErrno(PyExc_OSError);
  1462. return -1;
  1463. }
  1464. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1465. _Py_BEGIN_SUPPRESS_IPH
  1466. close(fd);
  1467. _Py_END_SUPPRESS_IPH
  1468. return -1;
  1469. }
  1470. #endif
  1471. return fd;
  1472. }
  1473. #ifndef MS_WINDOWS
  1474. /* Get the blocking mode of the file descriptor.
  1475. Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
  1476. raise an exception and return -1 on error. */
  1477. int
  1478. _Py_get_blocking(int fd)
  1479. {
  1480. int flags;
  1481. _Py_BEGIN_SUPPRESS_IPH
  1482. flags = fcntl(fd, F_GETFL, 0);
  1483. _Py_END_SUPPRESS_IPH
  1484. if (flags < 0) {
  1485. PyErr_SetFromErrno(PyExc_OSError);
  1486. return -1;
  1487. }
  1488. return !(flags & O_NONBLOCK);
  1489. }
  1490. /* Set the blocking mode of the specified file descriptor.
  1491. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
  1492. otherwise.
  1493. Return 0 on success, raise an exception and return -1 on error. */
  1494. int
  1495. _Py_set_blocking(int fd, int blocking)
  1496. {
  1497. #if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)
  1498. int arg = !blocking;
  1499. if (ioctl(fd, FIONBIO, &arg) < 0)
  1500. goto error;
  1501. #else
  1502. int flags, res;
  1503. _Py_BEGIN_SUPPRESS_IPH
  1504. flags = fcntl(fd, F_GETFL, 0);
  1505. if (flags >= 0) {
  1506. if (blocking)
  1507. flags = flags & (~O_NONBLOCK);
  1508. else
  1509. flags = flags | O_NONBLOCK;
  1510. res = fcntl(fd, F_SETFL, flags);
  1511. } else {
  1512. res = -1;
  1513. }
  1514. _Py_END_SUPPRESS_IPH
  1515. if (res < 0)
  1516. goto error;
  1517. #endif
  1518. return 0;
  1519. error:
  1520. PyErr_SetFromErrno(PyExc_OSError);
  1521. return -1;
  1522. }
  1523. #endif
  1524. int
  1525. _Py_GetLocaleconvNumeric(PyObject **decimal_point, PyObject **thousands_sep,
  1526. const char **grouping)
  1527. {
  1528. int res = -1;
  1529. struct lconv *lc = localeconv();
  1530. int change_locale = 0;
  1531. if (decimal_point != NULL &&
  1532. (strlen(lc->decimal_point) > 1 || ((unsigned char)lc->decimal_point[0]) > 127))
  1533. {
  1534. change_locale = 1;
  1535. }
  1536. if (thousands_sep != NULL &&
  1537. (strlen(lc->thousands_sep) > 1 || ((unsigned char)lc->thousands_sep[0]) > 127))
  1538. {
  1539. change_locale = 1;
  1540. }
  1541. /* Keep a copy of the LC_CTYPE locale */
  1542. char *oldloc = NULL, *loc = NULL;
  1543. if (change_locale) {
  1544. oldloc = setlocale(LC_CTYPE, NULL);
  1545. if (!oldloc) {
  1546. PyErr_SetString(PyExc_RuntimeWarning, "faild to get LC_CTYPE locale");
  1547. return -1;
  1548. }
  1549. oldloc = _PyMem_Strdup(oldloc);
  1550. if (!oldloc) {
  1551. PyErr_NoMemory();
  1552. return -1;
  1553. }
  1554. loc = setlocale(LC_NUMERIC, NULL);
  1555. if (loc != NULL && strcmp(loc, oldloc) == 0) {
  1556. loc = NULL;
  1557. }
  1558. if (loc != NULL) {
  1559. /* Only set the locale temporarilty the LC_CTYPE locale
  1560. if LC_NUMERIC locale is different than LC_CTYPE locale and
  1561. decimal_point and/or thousands_sep are non-ASCII or longer than
  1562. 1 byte */
  1563. setlocale(LC_CTYPE, loc);
  1564. }
  1565. }
  1566. if (decimal_point != NULL) {
  1567. *decimal_point = PyUnicode_DecodeLocale(lc->decimal_point, NULL);
  1568. if (*decimal_point == NULL) {
  1569. goto error;
  1570. }
  1571. }
  1572. if (thousands_sep != NULL) {
  1573. *thousands_sep = PyUnicode_DecodeLocale(lc->thousands_sep, NULL);
  1574. if (*thousands_sep == NULL) {
  1575. goto error;
  1576. }
  1577. }
  1578. if (grouping != NULL) {
  1579. *grouping = lc->grouping;
  1580. }
  1581. res = 0;
  1582. error:
  1583. if (loc != NULL) {
  1584. setlocale(LC_CTYPE, oldloc);
  1585. }
  1586. PyMem_Free(oldloc);
  1587. return res;
  1588. }