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.

1678 lines
45 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 = _PyVerify_fd(fd) && 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 occured, 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. if (!_PyVerify_fd(fd))
  554. h = INVALID_HANDLE_VALUE;
  555. else {
  556. _Py_BEGIN_SUPPRESS_IPH
  557. h = (HANDLE)_get_osfhandle(fd);
  558. _Py_END_SUPPRESS_IPH
  559. }
  560. if (h == INVALID_HANDLE_VALUE) {
  561. /* errno is already set by _get_osfhandle, but we also set
  562. the Win32 error for callers who expect that */
  563. SetLastError(ERROR_INVALID_HANDLE);
  564. return -1;
  565. }
  566. memset(status, 0, sizeof(*status));
  567. type = GetFileType(h);
  568. if (type == FILE_TYPE_UNKNOWN) {
  569. DWORD error = GetLastError();
  570. if (error != 0) {
  571. errno = winerror_to_errno(error);
  572. return -1;
  573. }
  574. /* else: valid but unknown file */
  575. }
  576. if (type != FILE_TYPE_DISK) {
  577. if (type == FILE_TYPE_CHAR)
  578. status->st_mode = _S_IFCHR;
  579. else if (type == FILE_TYPE_PIPE)
  580. status->st_mode = _S_IFIFO;
  581. return 0;
  582. }
  583. if (!GetFileInformationByHandle(h, &info)) {
  584. /* The Win32 error is already set, but we also set errno for
  585. callers who expect it */
  586. errno = winerror_to_errno(GetLastError());
  587. return -1;
  588. }
  589. _Py_attribute_data_to_stat(&info, 0, status);
  590. /* specific to fstat() */
  591. status->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
  592. return 0;
  593. #else
  594. return fstat(fd, status);
  595. #endif
  596. }
  597. /* Return information about a file.
  598. On POSIX, use fstat().
  599. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  600. files larger than 2 GB. fstat() may fail with EOVERFLOW on files larger
  601. than 2 GB because the file size type is a signed 32-bit integer: see issue
  602. #23152.
  603. Raise an exception and return -1 on error. On Windows, set the last Windows
  604. error on error. On POSIX, set errno on error. Fill status and return 0 on
  605. success.
  606. Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
  607. to call fstat(). The caller must hold the GIL. */
  608. int
  609. _Py_fstat(int fd, struct _Py_stat_struct *status)
  610. {
  611. int res;
  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. if (!_PyVerify_fd(fd)) {
  660. if (raise)
  661. PyErr_SetFromErrno(PyExc_OSError);
  662. return -1;
  663. }
  664. _Py_BEGIN_SUPPRESS_IPH
  665. handle = (HANDLE)_get_osfhandle(fd);
  666. _Py_END_SUPPRESS_IPH
  667. if (handle == INVALID_HANDLE_VALUE) {
  668. if (raise)
  669. PyErr_SetFromErrno(PyExc_OSError);
  670. return -1;
  671. }
  672. if (!GetHandleInformation(handle, &flags)) {
  673. if (raise)
  674. PyErr_SetFromWindowsErr(0);
  675. return -1;
  676. }
  677. return (flags & HANDLE_FLAG_INHERIT);
  678. #else
  679. int flags;
  680. flags = fcntl(fd, F_GETFD, 0);
  681. if (flags == -1) {
  682. if (raise)
  683. PyErr_SetFromErrno(PyExc_OSError);
  684. return -1;
  685. }
  686. return !(flags & FD_CLOEXEC);
  687. #endif
  688. }
  689. /* Get the inheritable flag of the specified file descriptor.
  690. Return 1 if the file descriptor can be inherited, 0 if it cannot,
  691. raise an exception and return -1 on error. */
  692. int
  693. _Py_get_inheritable(int fd)
  694. {
  695. return get_inheritable(fd, 1);
  696. }
  697. static int
  698. set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
  699. {
  700. #ifdef MS_WINDOWS
  701. HANDLE handle;
  702. DWORD flags;
  703. #else
  704. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  705. static int ioctl_works = -1;
  706. int request;
  707. int err;
  708. #endif
  709. int flags;
  710. int res;
  711. #endif
  712. /* atomic_flag_works can only be used to make the file descriptor
  713. non-inheritable */
  714. assert(!(atomic_flag_works != NULL && inheritable));
  715. if (atomic_flag_works != NULL && !inheritable) {
  716. if (*atomic_flag_works == -1) {
  717. int isInheritable = get_inheritable(fd, raise);
  718. if (isInheritable == -1)
  719. return -1;
  720. *atomic_flag_works = !isInheritable;
  721. }
  722. if (*atomic_flag_works)
  723. return 0;
  724. }
  725. #ifdef MS_WINDOWS
  726. if (!_PyVerify_fd(fd)) {
  727. if (raise)
  728. PyErr_SetFromErrno(PyExc_OSError);
  729. return -1;
  730. }
  731. _Py_BEGIN_SUPPRESS_IPH
  732. handle = (HANDLE)_get_osfhandle(fd);
  733. _Py_END_SUPPRESS_IPH
  734. if (handle == INVALID_HANDLE_VALUE) {
  735. if (raise)
  736. PyErr_SetFromErrno(PyExc_OSError);
  737. return -1;
  738. }
  739. if (inheritable)
  740. flags = HANDLE_FLAG_INHERIT;
  741. else
  742. flags = 0;
  743. if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
  744. if (raise)
  745. PyErr_SetFromWindowsErr(0);
  746. return -1;
  747. }
  748. return 0;
  749. #else
  750. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  751. if (ioctl_works != 0) {
  752. /* fast-path: ioctl() only requires one syscall */
  753. if (inheritable)
  754. request = FIONCLEX;
  755. else
  756. request = FIOCLEX;
  757. err = ioctl(fd, request, NULL);
  758. if (!err) {
  759. ioctl_works = 1;
  760. return 0;
  761. }
  762. if (errno != ENOTTY) {
  763. if (raise)
  764. PyErr_SetFromErrno(PyExc_OSError);
  765. return -1;
  766. }
  767. else {
  768. /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
  769. device". The ioctl is declared but not supported by the kernel.
  770. Remember that ioctl() doesn't work. It is the case on
  771. Illumos-based OS for example. */
  772. ioctl_works = 0;
  773. }
  774. /* fallback to fcntl() if ioctl() does not work */
  775. }
  776. #endif
  777. /* slow-path: fcntl() requires two syscalls */
  778. flags = fcntl(fd, F_GETFD);
  779. if (flags < 0) {
  780. if (raise)
  781. PyErr_SetFromErrno(PyExc_OSError);
  782. return -1;
  783. }
  784. if (inheritable)
  785. flags &= ~FD_CLOEXEC;
  786. else
  787. flags |= FD_CLOEXEC;
  788. res = fcntl(fd, F_SETFD, 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. /* _Py_read() must not be called with an exception set, otherwise the
  1024. * caller may think that read() was interrupted by a signal and the signal
  1025. * handler raised an exception. */
  1026. assert(!PyErr_Occurred());
  1027. if (!_PyVerify_fd(fd)) {
  1028. /* save/restore errno because PyErr_SetFromErrno() can modify it */
  1029. err = errno;
  1030. PyErr_SetFromErrno(PyExc_OSError);
  1031. errno = err;
  1032. return -1;
  1033. }
  1034. #ifdef MS_WINDOWS
  1035. if (count > INT_MAX) {
  1036. /* On Windows, the count parameter of read() is an int */
  1037. count = INT_MAX;
  1038. }
  1039. #else
  1040. if (count > PY_SSIZE_T_MAX) {
  1041. /* if count is greater than PY_SSIZE_T_MAX,
  1042. * read() result is undefined */
  1043. count = PY_SSIZE_T_MAX;
  1044. }
  1045. #endif
  1046. _Py_BEGIN_SUPPRESS_IPH
  1047. do {
  1048. Py_BEGIN_ALLOW_THREADS
  1049. errno = 0;
  1050. #ifdef MS_WINDOWS
  1051. n = read(fd, buf, (int)count);
  1052. #else
  1053. n = read(fd, buf, count);
  1054. #endif
  1055. /* save/restore errno because PyErr_CheckSignals()
  1056. * and PyErr_SetFromErrno() can modify it */
  1057. err = errno;
  1058. Py_END_ALLOW_THREADS
  1059. } while (n < 0 && err == EINTR &&
  1060. !(async_err = PyErr_CheckSignals()));
  1061. _Py_END_SUPPRESS_IPH
  1062. if (async_err) {
  1063. /* read() was interrupted by a signal (failed with EINTR)
  1064. * and the Python signal handler raised an exception */
  1065. errno = err;
  1066. assert(errno == EINTR && PyErr_Occurred());
  1067. return -1;
  1068. }
  1069. if (n < 0) {
  1070. PyErr_SetFromErrno(PyExc_OSError);
  1071. errno = err;
  1072. return -1;
  1073. }
  1074. return n;
  1075. }
  1076. static Py_ssize_t
  1077. _Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
  1078. {
  1079. Py_ssize_t n;
  1080. int err;
  1081. int async_err = 0;
  1082. if (!_PyVerify_fd(fd)) {
  1083. if (gil_held) {
  1084. /* save/restore errno because PyErr_SetFromErrno() can modify it */
  1085. err = errno;
  1086. PyErr_SetFromErrno(PyExc_OSError);
  1087. errno = err;
  1088. }
  1089. return -1;
  1090. }
  1091. _Py_BEGIN_SUPPRESS_IPH
  1092. #ifdef MS_WINDOWS
  1093. if (count > 32767 && isatty(fd)) {
  1094. /* Issue #11395: the Windows console returns an error (12: not
  1095. enough space error) on writing into stdout if stdout mode is
  1096. binary and the length is greater than 66,000 bytes (or less,
  1097. depending on heap usage). */
  1098. count = 32767;
  1099. }
  1100. else if (count > INT_MAX)
  1101. count = INT_MAX;
  1102. #else
  1103. if (count > PY_SSIZE_T_MAX) {
  1104. /* write() should truncate count to PY_SSIZE_T_MAX, but it's safer
  1105. * to do it ourself to have a portable behaviour. */
  1106. count = PY_SSIZE_T_MAX;
  1107. }
  1108. #endif
  1109. if (gil_held) {
  1110. do {
  1111. Py_BEGIN_ALLOW_THREADS
  1112. errno = 0;
  1113. #ifdef MS_WINDOWS
  1114. n = write(fd, buf, (int)count);
  1115. #else
  1116. n = write(fd, buf, count);
  1117. #endif
  1118. /* save/restore errno because PyErr_CheckSignals()
  1119. * and PyErr_SetFromErrno() can modify it */
  1120. err = errno;
  1121. Py_END_ALLOW_THREADS
  1122. } while (n < 0 && err == EINTR &&
  1123. !(async_err = PyErr_CheckSignals()));
  1124. }
  1125. else {
  1126. do {
  1127. errno = 0;
  1128. #ifdef MS_WINDOWS
  1129. n = write(fd, buf, (int)count);
  1130. #else
  1131. n = write(fd, buf, count);
  1132. #endif
  1133. err = errno;
  1134. } while (n < 0 && err == EINTR);
  1135. }
  1136. _Py_END_SUPPRESS_IPH
  1137. if (async_err) {
  1138. /* write() was interrupted by a signal (failed with EINTR)
  1139. and the Python signal handler raised an exception (if gil_held is
  1140. nonzero). */
  1141. errno = err;
  1142. assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
  1143. return -1;
  1144. }
  1145. if (n < 0) {
  1146. if (gil_held)
  1147. PyErr_SetFromErrno(PyExc_OSError);
  1148. errno = err;
  1149. return -1;
  1150. }
  1151. return n;
  1152. }
  1153. /* Write count bytes of buf into fd.
  1154. On success, return the number of written bytes, it can be lower than count
  1155. including 0. On error, raise an exception, set errno and return -1.
  1156. When interrupted by a signal (write() fails with EINTR), retry the syscall.
  1157. If the Python signal handler raises an exception, the function returns -1
  1158. (the syscall is not retried).
  1159. Release the GIL to call write(). The caller must hold the GIL. */
  1160. Py_ssize_t
  1161. _Py_write(int fd, const void *buf, size_t count)
  1162. {
  1163. /* _Py_write() must not be called with an exception set, otherwise the
  1164. * caller may think that write() was interrupted by a signal and the signal
  1165. * handler raised an exception. */
  1166. assert(!PyErr_Occurred());
  1167. return _Py_write_impl(fd, buf, count, 1);
  1168. }
  1169. /* Write count bytes of buf into fd.
  1170. *
  1171. * On success, return the number of written bytes, it can be lower than count
  1172. * including 0. On error, set errno and return -1.
  1173. *
  1174. * When interrupted by a signal (write() fails with EINTR), retry the syscall
  1175. * without calling the Python signal handler. */
  1176. Py_ssize_t
  1177. _Py_write_noraise(int fd, const void *buf, size_t count)
  1178. {
  1179. return _Py_write_impl(fd, buf, count, 0);
  1180. }
  1181. #ifdef HAVE_READLINK
  1182. /* Read value of symbolic link. Encode the path to the locale encoding, decode
  1183. the result from the locale encoding. Return -1 on error. */
  1184. int
  1185. _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
  1186. {
  1187. char *cpath;
  1188. char cbuf[MAXPATHLEN];
  1189. wchar_t *wbuf;
  1190. int res;
  1191. size_t r1;
  1192. cpath = Py_EncodeLocale(path, NULL);
  1193. if (cpath == NULL) {
  1194. errno = EINVAL;
  1195. return -1;
  1196. }
  1197. res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf));
  1198. PyMem_Free(cpath);
  1199. if (res == -1)
  1200. return -1;
  1201. if (res == Py_ARRAY_LENGTH(cbuf)) {
  1202. errno = EINVAL;
  1203. return -1;
  1204. }
  1205. cbuf[res] = '\0'; /* buf will be null terminated */
  1206. wbuf = Py_DecodeLocale(cbuf, &r1);
  1207. if (wbuf == NULL) {
  1208. errno = EINVAL;
  1209. return -1;
  1210. }
  1211. if (bufsiz <= r1) {
  1212. PyMem_RawFree(wbuf);
  1213. errno = EINVAL;
  1214. return -1;
  1215. }
  1216. wcsncpy(buf, wbuf, bufsiz);
  1217. PyMem_RawFree(wbuf);
  1218. return (int)r1;
  1219. }
  1220. #endif
  1221. #ifdef HAVE_REALPATH
  1222. /* Return the canonicalized absolute pathname. Encode path to the locale
  1223. encoding, decode the result from the locale encoding.
  1224. Return NULL on error. */
  1225. wchar_t*
  1226. _Py_wrealpath(const wchar_t *path,
  1227. wchar_t *resolved_path, size_t resolved_path_size)
  1228. {
  1229. char *cpath;
  1230. char cresolved_path[MAXPATHLEN];
  1231. wchar_t *wresolved_path;
  1232. char *res;
  1233. size_t r;
  1234. cpath = Py_EncodeLocale(path, NULL);
  1235. if (cpath == NULL) {
  1236. errno = EINVAL;
  1237. return NULL;
  1238. }
  1239. res = realpath(cpath, cresolved_path);
  1240. PyMem_Free(cpath);
  1241. if (res == NULL)
  1242. return NULL;
  1243. wresolved_path = Py_DecodeLocale(cresolved_path, &r);
  1244. if (wresolved_path == NULL) {
  1245. errno = EINVAL;
  1246. return NULL;
  1247. }
  1248. if (resolved_path_size <= r) {
  1249. PyMem_RawFree(wresolved_path);
  1250. errno = EINVAL;
  1251. return NULL;
  1252. }
  1253. wcsncpy(resolved_path, wresolved_path, resolved_path_size);
  1254. PyMem_RawFree(wresolved_path);
  1255. return resolved_path;
  1256. }
  1257. #endif
  1258. /* Get the current directory. size is the buffer size in wide characters
  1259. including the null character. Decode the path from the locale encoding.
  1260. Return NULL on error. */
  1261. wchar_t*
  1262. _Py_wgetcwd(wchar_t *buf, size_t size)
  1263. {
  1264. #ifdef MS_WINDOWS
  1265. int isize = (int)Py_MIN(size, INT_MAX);
  1266. return _wgetcwd(buf, isize);
  1267. #else
  1268. char fname[MAXPATHLEN];
  1269. wchar_t *wname;
  1270. size_t len;
  1271. if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
  1272. return NULL;
  1273. wname = Py_DecodeLocale(fname, &len);
  1274. if (wname == NULL)
  1275. return NULL;
  1276. if (size <= len) {
  1277. PyMem_RawFree(wname);
  1278. return NULL;
  1279. }
  1280. wcsncpy(buf, wname, size);
  1281. PyMem_RawFree(wname);
  1282. return buf;
  1283. #endif
  1284. }
  1285. /* Duplicate a file descriptor. The new file descriptor is created as
  1286. non-inheritable. Return a new file descriptor on success, raise an OSError
  1287. exception and return -1 on error.
  1288. The GIL is released to call dup(). The caller must hold the GIL. */
  1289. int
  1290. _Py_dup(int fd)
  1291. {
  1292. #ifdef MS_WINDOWS
  1293. HANDLE handle;
  1294. DWORD ftype;
  1295. #endif
  1296. if (!_PyVerify_fd(fd)) {
  1297. PyErr_SetFromErrno(PyExc_OSError);
  1298. return -1;
  1299. }
  1300. #ifdef MS_WINDOWS
  1301. _Py_BEGIN_SUPPRESS_IPH
  1302. handle = (HANDLE)_get_osfhandle(fd);
  1303. _Py_END_SUPPRESS_IPH
  1304. if (handle == INVALID_HANDLE_VALUE) {
  1305. PyErr_SetFromErrno(PyExc_OSError);
  1306. return -1;
  1307. }
  1308. /* get the file type, ignore the error if it failed */
  1309. ftype = GetFileType(handle);
  1310. Py_BEGIN_ALLOW_THREADS
  1311. _Py_BEGIN_SUPPRESS_IPH
  1312. fd = dup(fd);
  1313. _Py_END_SUPPRESS_IPH
  1314. Py_END_ALLOW_THREADS
  1315. if (fd < 0) {
  1316. PyErr_SetFromErrno(PyExc_OSError);
  1317. return -1;
  1318. }
  1319. /* Character files like console cannot be make non-inheritable */
  1320. if (ftype != FILE_TYPE_CHAR) {
  1321. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1322. _Py_BEGIN_SUPPRESS_IPH
  1323. close(fd);
  1324. _Py_END_SUPPRESS_IPH
  1325. return -1;
  1326. }
  1327. }
  1328. #elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
  1329. Py_BEGIN_ALLOW_THREADS
  1330. _Py_BEGIN_SUPPRESS_IPH
  1331. fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
  1332. _Py_END_SUPPRESS_IPH
  1333. Py_END_ALLOW_THREADS
  1334. if (fd < 0) {
  1335. PyErr_SetFromErrno(PyExc_OSError);
  1336. return -1;
  1337. }
  1338. #else
  1339. Py_BEGIN_ALLOW_THREADS
  1340. _Py_BEGIN_SUPPRESS_IPH
  1341. fd = dup(fd);
  1342. _Py_END_SUPPRESS_IPH
  1343. Py_END_ALLOW_THREADS
  1344. if (fd < 0) {
  1345. PyErr_SetFromErrno(PyExc_OSError);
  1346. return -1;
  1347. }
  1348. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1349. _Py_BEGIN_SUPPRESS_IPH
  1350. close(fd);
  1351. _Py_END_SUPPRESS_IPH
  1352. return -1;
  1353. }
  1354. #endif
  1355. return fd;
  1356. }
  1357. #ifndef MS_WINDOWS
  1358. /* Get the blocking mode of the file descriptor.
  1359. Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
  1360. raise an exception and return -1 on error. */
  1361. int
  1362. _Py_get_blocking(int fd)
  1363. {
  1364. int flags;
  1365. _Py_BEGIN_SUPPRESS_IPH
  1366. flags = fcntl(fd, F_GETFL, 0);
  1367. _Py_END_SUPPRESS_IPH
  1368. if (flags < 0) {
  1369. PyErr_SetFromErrno(PyExc_OSError);
  1370. return -1;
  1371. }
  1372. return !(flags & O_NONBLOCK);
  1373. }
  1374. /* Set the blocking mode of the specified file descriptor.
  1375. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
  1376. otherwise.
  1377. Return 0 on success, raise an exception and return -1 on error. */
  1378. int
  1379. _Py_set_blocking(int fd, int blocking)
  1380. {
  1381. #if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)
  1382. int arg = !blocking;
  1383. if (ioctl(fd, FIONBIO, &arg) < 0)
  1384. goto error;
  1385. #else
  1386. int flags, res;
  1387. _Py_BEGIN_SUPPRESS_IPH
  1388. flags = fcntl(fd, F_GETFL, 0);
  1389. if (flags >= 0) {
  1390. if (blocking)
  1391. flags = flags & (~O_NONBLOCK);
  1392. else
  1393. flags = flags | O_NONBLOCK;
  1394. res = fcntl(fd, F_SETFL, flags);
  1395. } else {
  1396. res = -1;
  1397. }
  1398. _Py_END_SUPPRESS_IPH
  1399. if (res < 0)
  1400. goto error;
  1401. #endif
  1402. return 0;
  1403. error:
  1404. PyErr_SetFromErrno(PyExc_OSError);
  1405. return -1;
  1406. }
  1407. #endif
  1408. #if defined _MSC_VER && _MSC_VER >= 1400 && _MSC_VER < 1900
  1409. /* Legacy implementation of _PyVerify_fd while transitioning to
  1410. * MSVC 14.0. This should eventually be removed. (issue23524)
  1411. */
  1412. /* Microsoft CRT in VS2005 and higher will verify that a filehandle is
  1413. * valid and raise an assertion if it isn't.
  1414. * Normally, an invalid fd is likely to be a C program error and therefore
  1415. * an assertion can be useful, but it does contradict the POSIX standard
  1416. * which for write(2) states:
  1417. * "Otherwise, -1 shall be returned and errno set to indicate the error."
  1418. * "[EBADF] The fildes argument is not a valid file descriptor open for
  1419. * writing."
  1420. * Furthermore, python allows the user to enter any old integer
  1421. * as a fd and should merely raise a python exception on error.
  1422. * The Microsoft CRT doesn't provide an official way to check for the
  1423. * validity of a file descriptor, but we can emulate its internal behaviour
  1424. * by using the exported __pinfo data member and knowledge of the
  1425. * internal structures involved.
  1426. * The structures below must be updated for each version of visual studio
  1427. * according to the file internal.h in the CRT source, until MS comes
  1428. * up with a less hacky way to do this.
  1429. * (all of this is to avoid globally modifying the CRT behaviour using
  1430. * _set_invalid_parameter_handler() and _CrtSetReportMode())
  1431. */
  1432. /* The actual size of the structure is determined at runtime.
  1433. * Only the first items must be present.
  1434. */
  1435. typedef struct {
  1436. intptr_t osfhnd;
  1437. char osfile;
  1438. } my_ioinfo;
  1439. extern __declspec(dllimport) char * __pioinfo[];
  1440. #define IOINFO_L2E 5
  1441. #define IOINFO_ARRAYS 64
  1442. #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
  1443. #define _NHANDLE_ (IOINFO_ARRAYS * IOINFO_ARRAY_ELTS)
  1444. #define FOPEN 0x01
  1445. #define _NO_CONSOLE_FILENO (intptr_t)-2
  1446. /* This function emulates what the windows CRT does to validate file handles */
  1447. int
  1448. _PyVerify_fd(int fd)
  1449. {
  1450. const int i1 = fd >> IOINFO_L2E;
  1451. const int i2 = fd & ((1 << IOINFO_L2E) - 1);
  1452. static size_t sizeof_ioinfo = 0;
  1453. /* Determine the actual size of the ioinfo structure,
  1454. * as used by the CRT loaded in memory
  1455. */
  1456. if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) {
  1457. sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS;
  1458. }
  1459. if (sizeof_ioinfo == 0) {
  1460. /* This should not happen... */
  1461. goto fail;
  1462. }
  1463. /* See that it isn't a special CLEAR fileno */
  1464. if (fd != _NO_CONSOLE_FILENO) {
  1465. /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead
  1466. * we check pointer validity and other info
  1467. */
  1468. if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) {
  1469. /* finally, check that the file is open */
  1470. my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo);
  1471. if (info->osfile & FOPEN) {
  1472. return 1;
  1473. }
  1474. }
  1475. }
  1476. fail:
  1477. errno = EBADF;
  1478. return 0;
  1479. }
  1480. #endif /* defined _MSC_VER && _MSC_VER >= 1400 && _MSC_VER < 1900 */