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.

1588 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 = (((__int64)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 = (((__int64)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. 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 = PyUnicode_EncodeFSDefault(path);
  646. if (bytes == NULL)
  647. return -2;
  648. ret = stat(PyBytes_AS_STRING(bytes), statbuf);
  649. Py_DECREF(bytes);
  650. return ret;
  651. #endif
  652. }
  653. static int
  654. get_inheritable(int fd, int raise)
  655. {
  656. #ifdef MS_WINDOWS
  657. HANDLE handle;
  658. DWORD flags;
  659. _Py_BEGIN_SUPPRESS_IPH
  660. handle = (HANDLE)_get_osfhandle(fd);
  661. _Py_END_SUPPRESS_IPH
  662. if (handle == INVALID_HANDLE_VALUE) {
  663. if (raise)
  664. PyErr_SetFromErrno(PyExc_OSError);
  665. return -1;
  666. }
  667. if (!GetHandleInformation(handle, &flags)) {
  668. if (raise)
  669. PyErr_SetFromWindowsErr(0);
  670. return -1;
  671. }
  672. return (flags & HANDLE_FLAG_INHERIT);
  673. #else
  674. int flags;
  675. flags = fcntl(fd, F_GETFD, 0);
  676. if (flags == -1) {
  677. if (raise)
  678. PyErr_SetFromErrno(PyExc_OSError);
  679. return -1;
  680. }
  681. return !(flags & FD_CLOEXEC);
  682. #endif
  683. }
  684. /* Get the inheritable flag of the specified file descriptor.
  685. Return 1 if the file descriptor can be inherited, 0 if it cannot,
  686. raise an exception and return -1 on error. */
  687. int
  688. _Py_get_inheritable(int fd)
  689. {
  690. return get_inheritable(fd, 1);
  691. }
  692. static int
  693. set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
  694. {
  695. #ifdef MS_WINDOWS
  696. HANDLE handle;
  697. DWORD flags;
  698. #else
  699. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  700. static int ioctl_works = -1;
  701. int request;
  702. int err;
  703. #endif
  704. int flags, new_flags;
  705. int res;
  706. #endif
  707. /* atomic_flag_works can only be used to make the file descriptor
  708. non-inheritable */
  709. assert(!(atomic_flag_works != NULL && inheritable));
  710. if (atomic_flag_works != NULL && !inheritable) {
  711. if (*atomic_flag_works == -1) {
  712. int isInheritable = get_inheritable(fd, raise);
  713. if (isInheritable == -1)
  714. return -1;
  715. *atomic_flag_works = !isInheritable;
  716. }
  717. if (*atomic_flag_works)
  718. return 0;
  719. }
  720. #ifdef MS_WINDOWS
  721. _Py_BEGIN_SUPPRESS_IPH
  722. handle = (HANDLE)_get_osfhandle(fd);
  723. _Py_END_SUPPRESS_IPH
  724. if (handle == INVALID_HANDLE_VALUE) {
  725. if (raise)
  726. PyErr_SetFromErrno(PyExc_OSError);
  727. return -1;
  728. }
  729. if (inheritable)
  730. flags = HANDLE_FLAG_INHERIT;
  731. else
  732. flags = 0;
  733. if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
  734. if (raise)
  735. PyErr_SetFromWindowsErr(0);
  736. return -1;
  737. }
  738. return 0;
  739. #else
  740. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  741. if (ioctl_works != 0) {
  742. /* fast-path: ioctl() only requires one syscall */
  743. if (inheritable)
  744. request = FIONCLEX;
  745. else
  746. request = FIOCLEX;
  747. err = ioctl(fd, request, NULL);
  748. if (!err) {
  749. ioctl_works = 1;
  750. return 0;
  751. }
  752. if (errno != ENOTTY && errno != EACCES) {
  753. if (raise)
  754. PyErr_SetFromErrno(PyExc_OSError);
  755. return -1;
  756. }
  757. else {
  758. /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
  759. device". The ioctl is declared but not supported by the kernel.
  760. Remember that ioctl() doesn't work. It is the case on
  761. Illumos-based OS for example.
  762. Issue #27057: When SELinux policy disallows ioctl it will fail
  763. with EACCES. While FIOCLEX is safe operation it may be
  764. unavailable because ioctl was denied altogether.
  765. This can be the case on Android. */
  766. ioctl_works = 0;
  767. }
  768. /* fallback to fcntl() if ioctl() does not work */
  769. }
  770. #endif
  771. /* slow-path: fcntl() requires two syscalls */
  772. flags = fcntl(fd, F_GETFD);
  773. if (flags < 0) {
  774. if (raise)
  775. PyErr_SetFromErrno(PyExc_OSError);
  776. return -1;
  777. }
  778. if (inheritable) {
  779. new_flags = flags & ~FD_CLOEXEC;
  780. }
  781. else {
  782. new_flags = flags | FD_CLOEXEC;
  783. }
  784. if (new_flags == flags) {
  785. /* FD_CLOEXEC flag already set/cleared: nothing to do */
  786. return 0;
  787. }
  788. res = fcntl(fd, F_SETFD, new_flags);
  789. if (res < 0) {
  790. if (raise)
  791. PyErr_SetFromErrno(PyExc_OSError);
  792. return -1;
  793. }
  794. return 0;
  795. #endif
  796. }
  797. /* Make the file descriptor non-inheritable.
  798. Return 0 on success, set errno and return -1 on error. */
  799. static int
  800. make_non_inheritable(int fd)
  801. {
  802. return set_inheritable(fd, 0, 0, NULL);
  803. }
  804. /* Set the inheritable flag of the specified file descriptor.
  805. On success: return 0, on error: raise an exception if raise is nonzero
  806. and return -1.
  807. If atomic_flag_works is not NULL:
  808. * if *atomic_flag_works==-1, check if the inheritable is set on the file
  809. descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
  810. set the inheritable flag
  811. * if *atomic_flag_works==1: do nothing
  812. * if *atomic_flag_works==0: set inheritable flag to False
  813. Set atomic_flag_works to NULL if no atomic flag was used to create the
  814. file descriptor.
  815. atomic_flag_works can only be used to make a file descriptor
  816. non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
  817. int
  818. _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
  819. {
  820. return set_inheritable(fd, inheritable, 1, atomic_flag_works);
  821. }
  822. static int
  823. _Py_open_impl(const char *pathname, int flags, int gil_held)
  824. {
  825. int fd;
  826. int async_err = 0;
  827. #ifndef MS_WINDOWS
  828. int *atomic_flag_works;
  829. #endif
  830. #ifdef MS_WINDOWS
  831. flags |= O_NOINHERIT;
  832. #elif defined(O_CLOEXEC)
  833. atomic_flag_works = &_Py_open_cloexec_works;
  834. flags |= O_CLOEXEC;
  835. #else
  836. atomic_flag_works = NULL;
  837. #endif
  838. if (gil_held) {
  839. do {
  840. Py_BEGIN_ALLOW_THREADS
  841. fd = open(pathname, flags);
  842. Py_END_ALLOW_THREADS
  843. } while (fd < 0
  844. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  845. if (async_err)
  846. return -1;
  847. if (fd < 0) {
  848. PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname);
  849. return -1;
  850. }
  851. }
  852. else {
  853. fd = open(pathname, flags);
  854. if (fd < 0)
  855. return -1;
  856. }
  857. #ifndef MS_WINDOWS
  858. if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
  859. close(fd);
  860. return -1;
  861. }
  862. #endif
  863. return fd;
  864. }
  865. /* Open a file with the specified flags (wrapper to open() function).
  866. Return a file descriptor on success. Raise an exception and return -1 on
  867. error.
  868. The file descriptor is created non-inheritable.
  869. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  870. except if the Python signal handler raises an exception.
  871. Release the GIL to call open(). The caller must hold the GIL. */
  872. int
  873. _Py_open(const char *pathname, int flags)
  874. {
  875. #ifdef WITH_THREAD
  876. /* _Py_open() must be called with the GIL held. */
  877. assert(PyGILState_Check());
  878. #endif
  879. return _Py_open_impl(pathname, flags, 1);
  880. }
  881. /* Open a file with the specified flags (wrapper to open() function).
  882. Return a file descriptor on success. Set errno and return -1 on error.
  883. The file descriptor is created non-inheritable.
  884. If interrupted by a signal, fail with EINTR. */
  885. int
  886. _Py_open_noraise(const char *pathname, int flags)
  887. {
  888. return _Py_open_impl(pathname, flags, 0);
  889. }
  890. /* Open a file. Use _wfopen() on Windows, encode the path to the locale
  891. encoding and use fopen() otherwise.
  892. The file descriptor is created non-inheritable.
  893. If interrupted by a signal, fail with EINTR. */
  894. FILE *
  895. _Py_wfopen(const wchar_t *path, const wchar_t *mode)
  896. {
  897. FILE *f;
  898. #ifndef MS_WINDOWS
  899. char *cpath;
  900. char cmode[10];
  901. size_t r;
  902. r = wcstombs(cmode, mode, 10);
  903. if (r == (size_t)-1 || r >= 10) {
  904. errno = EINVAL;
  905. return NULL;
  906. }
  907. cpath = Py_EncodeLocale(path, NULL);
  908. if (cpath == NULL)
  909. return NULL;
  910. f = fopen(cpath, cmode);
  911. PyMem_Free(cpath);
  912. #else
  913. f = _wfopen(path, mode);
  914. #endif
  915. if (f == NULL)
  916. return NULL;
  917. if (make_non_inheritable(fileno(f)) < 0) {
  918. fclose(f);
  919. return NULL;
  920. }
  921. return f;
  922. }
  923. /* Wrapper to fopen().
  924. The file descriptor is created non-inheritable.
  925. If interrupted by a signal, fail with EINTR. */
  926. FILE*
  927. _Py_fopen(const char *pathname, const char *mode)
  928. {
  929. FILE *f = fopen(pathname, mode);
  930. if (f == NULL)
  931. return NULL;
  932. if (make_non_inheritable(fileno(f)) < 0) {
  933. fclose(f);
  934. return NULL;
  935. }
  936. return f;
  937. }
  938. /* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
  939. encoding and call fopen() otherwise.
  940. Return the new file object on success. Raise an exception and return NULL
  941. on error.
  942. The file descriptor is created non-inheritable.
  943. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  944. except if the Python signal handler raises an exception.
  945. Release the GIL to call _wfopen() or fopen(). The caller must hold
  946. the GIL. */
  947. FILE*
  948. _Py_fopen_obj(PyObject *path, const char *mode)
  949. {
  950. FILE *f;
  951. int async_err = 0;
  952. #ifdef MS_WINDOWS
  953. wchar_t *wpath;
  954. wchar_t wmode[10];
  955. int usize;
  956. #ifdef WITH_THREAD
  957. assert(PyGILState_Check());
  958. #endif
  959. if (!PyUnicode_Check(path)) {
  960. PyErr_Format(PyExc_TypeError,
  961. "str file path expected under Windows, got %R",
  962. Py_TYPE(path));
  963. return NULL;
  964. }
  965. wpath = PyUnicode_AsUnicode(path);
  966. if (wpath == NULL)
  967. return NULL;
  968. usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
  969. if (usize == 0) {
  970. PyErr_SetFromWindowsErr(0);
  971. return NULL;
  972. }
  973. do {
  974. Py_BEGIN_ALLOW_THREADS
  975. f = _wfopen(wpath, wmode);
  976. Py_END_ALLOW_THREADS
  977. } while (f == NULL
  978. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  979. #else
  980. PyObject *bytes;
  981. char *path_bytes;
  982. #ifdef WITH_THREAD
  983. assert(PyGILState_Check());
  984. #endif
  985. if (!PyUnicode_FSConverter(path, &bytes))
  986. return NULL;
  987. path_bytes = PyBytes_AS_STRING(bytes);
  988. do {
  989. Py_BEGIN_ALLOW_THREADS
  990. f = fopen(path_bytes, mode);
  991. Py_END_ALLOW_THREADS
  992. } while (f == NULL
  993. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  994. Py_DECREF(bytes);
  995. #endif
  996. if (async_err)
  997. return NULL;
  998. if (f == NULL) {
  999. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1000. return NULL;
  1001. }
  1002. if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
  1003. fclose(f);
  1004. return NULL;
  1005. }
  1006. return f;
  1007. }
  1008. /* Read count bytes from fd into buf.
  1009. On success, return the number of read bytes, it can be lower than count.
  1010. If the current file offset is at or past the end of file, no bytes are read,
  1011. and read() returns zero.
  1012. On error, raise an exception, set errno and return -1.
  1013. When interrupted by a signal (read() fails with EINTR), retry the syscall.
  1014. If the Python signal handler raises an exception, the function returns -1
  1015. (the syscall is not retried).
  1016. Release the GIL to call read(). The caller must hold the GIL. */
  1017. Py_ssize_t
  1018. _Py_read(int fd, void *buf, size_t count)
  1019. {
  1020. Py_ssize_t n;
  1021. int err;
  1022. int async_err = 0;
  1023. #ifdef WITH_THREAD
  1024. assert(PyGILState_Check());
  1025. #endif
  1026. /* _Py_read() must not be called with an exception set, otherwise the
  1027. * caller may think that read() was interrupted by a signal and the signal
  1028. * handler raised an exception. */
  1029. assert(!PyErr_Occurred());
  1030. #ifdef MS_WINDOWS
  1031. if (count > INT_MAX) {
  1032. /* On Windows, the count parameter of read() is an int */
  1033. count = INT_MAX;
  1034. }
  1035. #else
  1036. if (count > PY_SSIZE_T_MAX) {
  1037. /* if count is greater than PY_SSIZE_T_MAX,
  1038. * read() result is undefined */
  1039. count = PY_SSIZE_T_MAX;
  1040. }
  1041. #endif
  1042. _Py_BEGIN_SUPPRESS_IPH
  1043. do {
  1044. Py_BEGIN_ALLOW_THREADS
  1045. errno = 0;
  1046. #ifdef MS_WINDOWS
  1047. n = read(fd, buf, (int)count);
  1048. #else
  1049. n = read(fd, buf, count);
  1050. #endif
  1051. /* save/restore errno because PyErr_CheckSignals()
  1052. * and PyErr_SetFromErrno() can modify it */
  1053. err = errno;
  1054. Py_END_ALLOW_THREADS
  1055. } while (n < 0 && err == EINTR &&
  1056. !(async_err = PyErr_CheckSignals()));
  1057. _Py_END_SUPPRESS_IPH
  1058. if (async_err) {
  1059. /* read() was interrupted by a signal (failed with EINTR)
  1060. * and the Python signal handler raised an exception */
  1061. errno = err;
  1062. assert(errno == EINTR && PyErr_Occurred());
  1063. return -1;
  1064. }
  1065. if (n < 0) {
  1066. PyErr_SetFromErrno(PyExc_OSError);
  1067. errno = err;
  1068. return -1;
  1069. }
  1070. return n;
  1071. }
  1072. static Py_ssize_t
  1073. _Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
  1074. {
  1075. Py_ssize_t n;
  1076. int err;
  1077. int async_err = 0;
  1078. _Py_BEGIN_SUPPRESS_IPH
  1079. #ifdef MS_WINDOWS
  1080. if (count > 32767 && isatty(fd)) {
  1081. /* Issue #11395: the Windows console returns an error (12: not
  1082. enough space error) on writing into stdout if stdout mode is
  1083. binary and the length is greater than 66,000 bytes (or less,
  1084. depending on heap usage). */
  1085. count = 32767;
  1086. }
  1087. else if (count > INT_MAX)
  1088. count = INT_MAX;
  1089. #else
  1090. if (count > PY_SSIZE_T_MAX) {
  1091. /* write() should truncate count to PY_SSIZE_T_MAX, but it's safer
  1092. * to do it ourself to have a portable behaviour. */
  1093. count = PY_SSIZE_T_MAX;
  1094. }
  1095. #endif
  1096. if (gil_held) {
  1097. do {
  1098. Py_BEGIN_ALLOW_THREADS
  1099. errno = 0;
  1100. #ifdef MS_WINDOWS
  1101. n = write(fd, buf, (int)count);
  1102. #else
  1103. n = write(fd, buf, count);
  1104. #endif
  1105. /* save/restore errno because PyErr_CheckSignals()
  1106. * and PyErr_SetFromErrno() can modify it */
  1107. err = errno;
  1108. Py_END_ALLOW_THREADS
  1109. } while (n < 0 && err == EINTR &&
  1110. !(async_err = PyErr_CheckSignals()));
  1111. }
  1112. else {
  1113. do {
  1114. errno = 0;
  1115. #ifdef MS_WINDOWS
  1116. n = write(fd, buf, (int)count);
  1117. #else
  1118. n = write(fd, buf, count);
  1119. #endif
  1120. err = errno;
  1121. } while (n < 0 && err == EINTR);
  1122. }
  1123. _Py_END_SUPPRESS_IPH
  1124. if (async_err) {
  1125. /* write() was interrupted by a signal (failed with EINTR)
  1126. and the Python signal handler raised an exception (if gil_held is
  1127. nonzero). */
  1128. errno = err;
  1129. assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
  1130. return -1;
  1131. }
  1132. if (n < 0) {
  1133. if (gil_held)
  1134. PyErr_SetFromErrno(PyExc_OSError);
  1135. errno = err;
  1136. return -1;
  1137. }
  1138. return n;
  1139. }
  1140. /* Write count bytes of buf into fd.
  1141. On success, return the number of written bytes, it can be lower than count
  1142. including 0. On error, raise an exception, set errno and return -1.
  1143. When interrupted by a signal (write() fails with EINTR), retry the syscall.
  1144. If the Python signal handler raises an exception, the function returns -1
  1145. (the syscall is not retried).
  1146. Release the GIL to call write(). The caller must hold the GIL. */
  1147. Py_ssize_t
  1148. _Py_write(int fd, const void *buf, size_t count)
  1149. {
  1150. #ifdef WITH_THREAD
  1151. assert(PyGILState_Check());
  1152. #endif
  1153. /* _Py_write() must not be called with an exception set, otherwise the
  1154. * caller may think that write() was interrupted by a signal and the signal
  1155. * handler raised an exception. */
  1156. assert(!PyErr_Occurred());
  1157. return _Py_write_impl(fd, buf, count, 1);
  1158. }
  1159. /* Write count bytes of buf into fd.
  1160. *
  1161. * On success, return the number of written bytes, it can be lower than count
  1162. * including 0. On error, set errno and return -1.
  1163. *
  1164. * When interrupted by a signal (write() fails with EINTR), retry the syscall
  1165. * without calling the Python signal handler. */
  1166. Py_ssize_t
  1167. _Py_write_noraise(int fd, const void *buf, size_t count)
  1168. {
  1169. return _Py_write_impl(fd, buf, count, 0);
  1170. }
  1171. #ifdef HAVE_READLINK
  1172. /* Read value of symbolic link. Encode the path to the locale encoding, decode
  1173. the result from the locale encoding. Return -1 on error. */
  1174. int
  1175. _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
  1176. {
  1177. char *cpath;
  1178. char cbuf[MAXPATHLEN];
  1179. wchar_t *wbuf;
  1180. int res;
  1181. size_t r1;
  1182. cpath = Py_EncodeLocale(path, NULL);
  1183. if (cpath == NULL) {
  1184. errno = EINVAL;
  1185. return -1;
  1186. }
  1187. res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf));
  1188. PyMem_Free(cpath);
  1189. if (res == -1)
  1190. return -1;
  1191. if (res == Py_ARRAY_LENGTH(cbuf)) {
  1192. errno = EINVAL;
  1193. return -1;
  1194. }
  1195. cbuf[res] = '\0'; /* buf will be null terminated */
  1196. wbuf = Py_DecodeLocale(cbuf, &r1);
  1197. if (wbuf == NULL) {
  1198. errno = EINVAL;
  1199. return -1;
  1200. }
  1201. if (bufsiz <= r1) {
  1202. PyMem_RawFree(wbuf);
  1203. errno = EINVAL;
  1204. return -1;
  1205. }
  1206. wcsncpy(buf, wbuf, bufsiz);
  1207. PyMem_RawFree(wbuf);
  1208. return (int)r1;
  1209. }
  1210. #endif
  1211. #ifdef HAVE_REALPATH
  1212. /* Return the canonicalized absolute pathname. Encode path to the locale
  1213. encoding, decode the result from the locale encoding.
  1214. Return NULL on error. */
  1215. wchar_t*
  1216. _Py_wrealpath(const wchar_t *path,
  1217. wchar_t *resolved_path, size_t resolved_path_size)
  1218. {
  1219. char *cpath;
  1220. char cresolved_path[MAXPATHLEN];
  1221. wchar_t *wresolved_path;
  1222. char *res;
  1223. size_t r;
  1224. cpath = Py_EncodeLocale(path, NULL);
  1225. if (cpath == NULL) {
  1226. errno = EINVAL;
  1227. return NULL;
  1228. }
  1229. res = realpath(cpath, cresolved_path);
  1230. PyMem_Free(cpath);
  1231. if (res == NULL)
  1232. return NULL;
  1233. wresolved_path = Py_DecodeLocale(cresolved_path, &r);
  1234. if (wresolved_path == NULL) {
  1235. errno = EINVAL;
  1236. return NULL;
  1237. }
  1238. if (resolved_path_size <= r) {
  1239. PyMem_RawFree(wresolved_path);
  1240. errno = EINVAL;
  1241. return NULL;
  1242. }
  1243. wcsncpy(resolved_path, wresolved_path, resolved_path_size);
  1244. PyMem_RawFree(wresolved_path);
  1245. return resolved_path;
  1246. }
  1247. #endif
  1248. /* Get the current directory. size is the buffer size in wide characters
  1249. including the null character. Decode the path from the locale encoding.
  1250. Return NULL on error. */
  1251. wchar_t*
  1252. _Py_wgetcwd(wchar_t *buf, size_t size)
  1253. {
  1254. #ifdef MS_WINDOWS
  1255. int isize = (int)Py_MIN(size, INT_MAX);
  1256. return _wgetcwd(buf, isize);
  1257. #else
  1258. char fname[MAXPATHLEN];
  1259. wchar_t *wname;
  1260. size_t len;
  1261. if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
  1262. return NULL;
  1263. wname = Py_DecodeLocale(fname, &len);
  1264. if (wname == NULL)
  1265. return NULL;
  1266. if (size <= len) {
  1267. PyMem_RawFree(wname);
  1268. return NULL;
  1269. }
  1270. wcsncpy(buf, wname, size);
  1271. PyMem_RawFree(wname);
  1272. return buf;
  1273. #endif
  1274. }
  1275. /* Duplicate a file descriptor. The new file descriptor is created as
  1276. non-inheritable. Return a new file descriptor on success, raise an OSError
  1277. exception and return -1 on error.
  1278. The GIL is released to call dup(). The caller must hold the GIL. */
  1279. int
  1280. _Py_dup(int fd)
  1281. {
  1282. #ifdef MS_WINDOWS
  1283. HANDLE handle;
  1284. DWORD ftype;
  1285. #endif
  1286. #ifdef WITH_THREAD
  1287. assert(PyGILState_Check());
  1288. #endif
  1289. #ifdef MS_WINDOWS
  1290. _Py_BEGIN_SUPPRESS_IPH
  1291. handle = (HANDLE)_get_osfhandle(fd);
  1292. _Py_END_SUPPRESS_IPH
  1293. if (handle == INVALID_HANDLE_VALUE) {
  1294. PyErr_SetFromErrno(PyExc_OSError);
  1295. return -1;
  1296. }
  1297. /* get the file type, ignore the error if it failed */
  1298. ftype = GetFileType(handle);
  1299. Py_BEGIN_ALLOW_THREADS
  1300. _Py_BEGIN_SUPPRESS_IPH
  1301. fd = dup(fd);
  1302. _Py_END_SUPPRESS_IPH
  1303. Py_END_ALLOW_THREADS
  1304. if (fd < 0) {
  1305. PyErr_SetFromErrno(PyExc_OSError);
  1306. return -1;
  1307. }
  1308. /* Character files like console cannot be make non-inheritable */
  1309. if (ftype != FILE_TYPE_CHAR) {
  1310. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1311. _Py_BEGIN_SUPPRESS_IPH
  1312. close(fd);
  1313. _Py_END_SUPPRESS_IPH
  1314. return -1;
  1315. }
  1316. }
  1317. #elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
  1318. Py_BEGIN_ALLOW_THREADS
  1319. _Py_BEGIN_SUPPRESS_IPH
  1320. fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
  1321. _Py_END_SUPPRESS_IPH
  1322. Py_END_ALLOW_THREADS
  1323. if (fd < 0) {
  1324. PyErr_SetFromErrno(PyExc_OSError);
  1325. return -1;
  1326. }
  1327. #else
  1328. Py_BEGIN_ALLOW_THREADS
  1329. _Py_BEGIN_SUPPRESS_IPH
  1330. fd = dup(fd);
  1331. _Py_END_SUPPRESS_IPH
  1332. Py_END_ALLOW_THREADS
  1333. if (fd < 0) {
  1334. PyErr_SetFromErrno(PyExc_OSError);
  1335. return -1;
  1336. }
  1337. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1338. _Py_BEGIN_SUPPRESS_IPH
  1339. close(fd);
  1340. _Py_END_SUPPRESS_IPH
  1341. return -1;
  1342. }
  1343. #endif
  1344. return fd;
  1345. }
  1346. #ifndef MS_WINDOWS
  1347. /* Get the blocking mode of the file descriptor.
  1348. Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
  1349. raise an exception and return -1 on error. */
  1350. int
  1351. _Py_get_blocking(int fd)
  1352. {
  1353. int flags;
  1354. _Py_BEGIN_SUPPRESS_IPH
  1355. flags = fcntl(fd, F_GETFL, 0);
  1356. _Py_END_SUPPRESS_IPH
  1357. if (flags < 0) {
  1358. PyErr_SetFromErrno(PyExc_OSError);
  1359. return -1;
  1360. }
  1361. return !(flags & O_NONBLOCK);
  1362. }
  1363. /* Set the blocking mode of the specified file descriptor.
  1364. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
  1365. otherwise.
  1366. Return 0 on success, raise an exception and return -1 on error. */
  1367. int
  1368. _Py_set_blocking(int fd, int blocking)
  1369. {
  1370. #if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)
  1371. int arg = !blocking;
  1372. if (ioctl(fd, FIONBIO, &arg) < 0)
  1373. goto error;
  1374. #else
  1375. int flags, res;
  1376. _Py_BEGIN_SUPPRESS_IPH
  1377. flags = fcntl(fd, F_GETFL, 0);
  1378. if (flags >= 0) {
  1379. if (blocking)
  1380. flags = flags & (~O_NONBLOCK);
  1381. else
  1382. flags = flags | O_NONBLOCK;
  1383. res = fcntl(fd, F_SETFL, flags);
  1384. } else {
  1385. res = -1;
  1386. }
  1387. _Py_END_SUPPRESS_IPH
  1388. if (res < 0)
  1389. goto error;
  1390. #endif
  1391. return 0;
  1392. error:
  1393. PyErr_SetFromErrno(PyExc_OSError);
  1394. return -1;
  1395. }
  1396. #endif