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.

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