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.

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