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.

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