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.

1702 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. #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) {
  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. ioctl_works = 0;
  776. }
  777. /* fallback to fcntl() if ioctl() does not work */
  778. }
  779. #endif
  780. /* slow-path: fcntl() requires two syscalls */
  781. flags = fcntl(fd, F_GETFD);
  782. if (flags < 0) {
  783. if (raise)
  784. PyErr_SetFromErrno(PyExc_OSError);
  785. return -1;
  786. }
  787. if (inheritable) {
  788. new_flags = flags & ~FD_CLOEXEC;
  789. }
  790. else {
  791. new_flags = flags | FD_CLOEXEC;
  792. }
  793. if (new_flags == flags) {
  794. /* FD_CLOEXEC flag already set/cleared: nothing to do */
  795. return 0;
  796. }
  797. res = fcntl(fd, F_SETFD, flags);
  798. if (res < 0) {
  799. if (raise)
  800. PyErr_SetFromErrno(PyExc_OSError);
  801. return -1;
  802. }
  803. return 0;
  804. #endif
  805. }
  806. /* Make the file descriptor non-inheritable.
  807. Return 0 on success, set errno and return -1 on error. */
  808. static int
  809. make_non_inheritable(int fd)
  810. {
  811. return set_inheritable(fd, 0, 0, NULL);
  812. }
  813. /* Set the inheritable flag of the specified file descriptor.
  814. On success: return 0, on error: raise an exception if raise is nonzero
  815. and return -1.
  816. If atomic_flag_works is not NULL:
  817. * if *atomic_flag_works==-1, check if the inheritable is set on the file
  818. descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
  819. set the inheritable flag
  820. * if *atomic_flag_works==1: do nothing
  821. * if *atomic_flag_works==0: set inheritable flag to False
  822. Set atomic_flag_works to NULL if no atomic flag was used to create the
  823. file descriptor.
  824. atomic_flag_works can only be used to make a file descriptor
  825. non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
  826. int
  827. _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
  828. {
  829. return set_inheritable(fd, inheritable, 1, atomic_flag_works);
  830. }
  831. static int
  832. _Py_open_impl(const char *pathname, int flags, int gil_held)
  833. {
  834. int fd;
  835. int async_err = 0;
  836. #ifndef MS_WINDOWS
  837. int *atomic_flag_works;
  838. #endif
  839. #ifdef MS_WINDOWS
  840. flags |= O_NOINHERIT;
  841. #elif defined(O_CLOEXEC)
  842. atomic_flag_works = &_Py_open_cloexec_works;
  843. flags |= O_CLOEXEC;
  844. #else
  845. atomic_flag_works = NULL;
  846. #endif
  847. if (gil_held) {
  848. do {
  849. Py_BEGIN_ALLOW_THREADS
  850. fd = open(pathname, flags);
  851. Py_END_ALLOW_THREADS
  852. } while (fd < 0
  853. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  854. if (async_err)
  855. return -1;
  856. if (fd < 0) {
  857. PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname);
  858. return -1;
  859. }
  860. }
  861. else {
  862. fd = open(pathname, flags);
  863. if (fd < 0)
  864. return -1;
  865. }
  866. #ifndef MS_WINDOWS
  867. if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
  868. close(fd);
  869. return -1;
  870. }
  871. #endif
  872. return fd;
  873. }
  874. /* Open a file with the specified flags (wrapper to open() function).
  875. Return a file descriptor on success. Raise an exception and return -1 on
  876. error.
  877. The file descriptor is created non-inheritable.
  878. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  879. except if the Python signal handler raises an exception.
  880. Release the GIL to call open(). The caller must hold the GIL. */
  881. int
  882. _Py_open(const char *pathname, int flags)
  883. {
  884. #ifdef WITH_THREAD
  885. /* _Py_open() must be called with the GIL held. */
  886. assert(PyGILState_Check());
  887. #endif
  888. return _Py_open_impl(pathname, flags, 1);
  889. }
  890. /* Open a file with the specified flags (wrapper to open() function).
  891. Return a file descriptor on success. Set errno and return -1 on error.
  892. The file descriptor is created non-inheritable.
  893. If interrupted by a signal, fail with EINTR. */
  894. int
  895. _Py_open_noraise(const char *pathname, int flags)
  896. {
  897. return _Py_open_impl(pathname, flags, 0);
  898. }
  899. /* Open a file. Use _wfopen() on Windows, encode the path to the locale
  900. encoding and use fopen() otherwise.
  901. The file descriptor is created non-inheritable.
  902. If interrupted by a signal, fail with EINTR. */
  903. FILE *
  904. _Py_wfopen(const wchar_t *path, const wchar_t *mode)
  905. {
  906. FILE *f;
  907. #ifndef MS_WINDOWS
  908. char *cpath;
  909. char cmode[10];
  910. size_t r;
  911. r = wcstombs(cmode, mode, 10);
  912. if (r == (size_t)-1 || r >= 10) {
  913. errno = EINVAL;
  914. return NULL;
  915. }
  916. cpath = Py_EncodeLocale(path, NULL);
  917. if (cpath == NULL)
  918. return NULL;
  919. f = fopen(cpath, cmode);
  920. PyMem_Free(cpath);
  921. #else
  922. f = _wfopen(path, mode);
  923. #endif
  924. if (f == NULL)
  925. return NULL;
  926. if (make_non_inheritable(fileno(f)) < 0) {
  927. fclose(f);
  928. return NULL;
  929. }
  930. return f;
  931. }
  932. /* Wrapper to fopen().
  933. The file descriptor is created non-inheritable.
  934. If interrupted by a signal, fail with EINTR. */
  935. FILE*
  936. _Py_fopen(const char *pathname, const char *mode)
  937. {
  938. FILE *f = fopen(pathname, mode);
  939. if (f == NULL)
  940. return NULL;
  941. if (make_non_inheritable(fileno(f)) < 0) {
  942. fclose(f);
  943. return NULL;
  944. }
  945. return f;
  946. }
  947. /* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
  948. encoding and call fopen() otherwise.
  949. Return the new file object on success. Raise an exception and return NULL
  950. on error.
  951. The file descriptor is created non-inheritable.
  952. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  953. except if the Python signal handler raises an exception.
  954. Release the GIL to call _wfopen() or fopen(). The caller must hold
  955. the GIL. */
  956. FILE*
  957. _Py_fopen_obj(PyObject *path, const char *mode)
  958. {
  959. FILE *f;
  960. int async_err = 0;
  961. #ifdef MS_WINDOWS
  962. wchar_t *wpath;
  963. wchar_t wmode[10];
  964. int usize;
  965. #ifdef WITH_THREAD
  966. assert(PyGILState_Check());
  967. #endif
  968. if (!PyUnicode_Check(path)) {
  969. PyErr_Format(PyExc_TypeError,
  970. "str file path expected under Windows, got %R",
  971. Py_TYPE(path));
  972. return NULL;
  973. }
  974. wpath = PyUnicode_AsUnicode(path);
  975. if (wpath == NULL)
  976. return NULL;
  977. usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
  978. if (usize == 0) {
  979. PyErr_SetFromWindowsErr(0);
  980. return NULL;
  981. }
  982. do {
  983. Py_BEGIN_ALLOW_THREADS
  984. f = _wfopen(wpath, wmode);
  985. Py_END_ALLOW_THREADS
  986. } while (f == NULL
  987. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  988. #else
  989. PyObject *bytes;
  990. char *path_bytes;
  991. #ifdef WITH_THREAD
  992. assert(PyGILState_Check());
  993. #endif
  994. if (!PyUnicode_FSConverter(path, &bytes))
  995. return NULL;
  996. path_bytes = PyBytes_AS_STRING(bytes);
  997. do {
  998. Py_BEGIN_ALLOW_THREADS
  999. f = fopen(path_bytes, mode);
  1000. Py_END_ALLOW_THREADS
  1001. } while (f == NULL
  1002. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1003. Py_DECREF(bytes);
  1004. #endif
  1005. if (async_err)
  1006. return NULL;
  1007. if (f == NULL) {
  1008. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1009. return NULL;
  1010. }
  1011. if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
  1012. fclose(f);
  1013. return NULL;
  1014. }
  1015. return f;
  1016. }
  1017. /* Read count bytes from fd into buf.
  1018. On success, return the number of read bytes, it can be lower than count.
  1019. If the current file offset is at or past the end of file, no bytes are read,
  1020. and read() returns zero.
  1021. On error, raise an exception, set errno and return -1.
  1022. When interrupted by a signal (read() fails with EINTR), retry the syscall.
  1023. If the Python signal handler raises an exception, the function returns -1
  1024. (the syscall is not retried).
  1025. Release the GIL to call read(). The caller must hold the GIL. */
  1026. Py_ssize_t
  1027. _Py_read(int fd, void *buf, size_t count)
  1028. {
  1029. Py_ssize_t n;
  1030. int err;
  1031. int async_err = 0;
  1032. #ifdef WITH_THREAD
  1033. assert(PyGILState_Check());
  1034. #endif
  1035. /* _Py_read() must not be called with an exception set, otherwise the
  1036. * caller may think that read() was interrupted by a signal and the signal
  1037. * handler raised an exception. */
  1038. assert(!PyErr_Occurred());
  1039. if (!_PyVerify_fd(fd)) {
  1040. /* save/restore errno because PyErr_SetFromErrno() can modify it */
  1041. err = errno;
  1042. PyErr_SetFromErrno(PyExc_OSError);
  1043. errno = err;
  1044. return -1;
  1045. }
  1046. #ifdef MS_WINDOWS
  1047. if (count > INT_MAX) {
  1048. /* On Windows, the count parameter of read() is an int */
  1049. count = INT_MAX;
  1050. }
  1051. #else
  1052. if (count > PY_SSIZE_T_MAX) {
  1053. /* if count is greater than PY_SSIZE_T_MAX,
  1054. * read() result is undefined */
  1055. count = PY_SSIZE_T_MAX;
  1056. }
  1057. #endif
  1058. _Py_BEGIN_SUPPRESS_IPH
  1059. do {
  1060. Py_BEGIN_ALLOW_THREADS
  1061. errno = 0;
  1062. #ifdef MS_WINDOWS
  1063. n = read(fd, buf, (int)count);
  1064. #else
  1065. n = read(fd, buf, count);
  1066. #endif
  1067. /* save/restore errno because PyErr_CheckSignals()
  1068. * and PyErr_SetFromErrno() can modify it */
  1069. err = errno;
  1070. Py_END_ALLOW_THREADS
  1071. } while (n < 0 && err == EINTR &&
  1072. !(async_err = PyErr_CheckSignals()));
  1073. _Py_END_SUPPRESS_IPH
  1074. if (async_err) {
  1075. /* read() was interrupted by a signal (failed with EINTR)
  1076. * and the Python signal handler raised an exception */
  1077. errno = err;
  1078. assert(errno == EINTR && PyErr_Occurred());
  1079. return -1;
  1080. }
  1081. if (n < 0) {
  1082. PyErr_SetFromErrno(PyExc_OSError);
  1083. errno = err;
  1084. return -1;
  1085. }
  1086. return n;
  1087. }
  1088. static Py_ssize_t
  1089. _Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
  1090. {
  1091. Py_ssize_t n;
  1092. int err;
  1093. int async_err = 0;
  1094. if (!_PyVerify_fd(fd)) {
  1095. if (gil_held) {
  1096. /* save/restore errno because PyErr_SetFromErrno() can modify it */
  1097. err = errno;
  1098. PyErr_SetFromErrno(PyExc_OSError);
  1099. errno = err;
  1100. }
  1101. return -1;
  1102. }
  1103. _Py_BEGIN_SUPPRESS_IPH
  1104. #ifdef MS_WINDOWS
  1105. if (count > 32767 && isatty(fd)) {
  1106. /* Issue #11395: the Windows console returns an error (12: not
  1107. enough space error) on writing into stdout if stdout mode is
  1108. binary and the length is greater than 66,000 bytes (or less,
  1109. depending on heap usage). */
  1110. count = 32767;
  1111. }
  1112. else if (count > INT_MAX)
  1113. count = INT_MAX;
  1114. #else
  1115. if (count > PY_SSIZE_T_MAX) {
  1116. /* write() should truncate count to PY_SSIZE_T_MAX, but it's safer
  1117. * to do it ourself to have a portable behaviour. */
  1118. count = PY_SSIZE_T_MAX;
  1119. }
  1120. #endif
  1121. if (gil_held) {
  1122. do {
  1123. Py_BEGIN_ALLOW_THREADS
  1124. errno = 0;
  1125. #ifdef MS_WINDOWS
  1126. n = write(fd, buf, (int)count);
  1127. #else
  1128. n = write(fd, buf, count);
  1129. #endif
  1130. /* save/restore errno because PyErr_CheckSignals()
  1131. * and PyErr_SetFromErrno() can modify it */
  1132. err = errno;
  1133. Py_END_ALLOW_THREADS
  1134. } while (n < 0 && err == EINTR &&
  1135. !(async_err = PyErr_CheckSignals()));
  1136. }
  1137. else {
  1138. do {
  1139. errno = 0;
  1140. #ifdef MS_WINDOWS
  1141. n = write(fd, buf, (int)count);
  1142. #else
  1143. n = write(fd, buf, count);
  1144. #endif
  1145. err = errno;
  1146. } while (n < 0 && err == EINTR);
  1147. }
  1148. _Py_END_SUPPRESS_IPH
  1149. if (async_err) {
  1150. /* write() was interrupted by a signal (failed with EINTR)
  1151. and the Python signal handler raised an exception (if gil_held is
  1152. nonzero). */
  1153. errno = err;
  1154. assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
  1155. return -1;
  1156. }
  1157. if (n < 0) {
  1158. if (gil_held)
  1159. PyErr_SetFromErrno(PyExc_OSError);
  1160. errno = err;
  1161. return -1;
  1162. }
  1163. return n;
  1164. }
  1165. /* Write count bytes of buf into fd.
  1166. On success, return the number of written bytes, it can be lower than count
  1167. including 0. On error, raise an exception, set errno and return -1.
  1168. When interrupted by a signal (write() fails with EINTR), retry the syscall.
  1169. If the Python signal handler raises an exception, the function returns -1
  1170. (the syscall is not retried).
  1171. Release the GIL to call write(). The caller must hold the GIL. */
  1172. Py_ssize_t
  1173. _Py_write(int fd, const void *buf, size_t count)
  1174. {
  1175. #ifdef WITH_THREAD
  1176. assert(PyGILState_Check());
  1177. #endif
  1178. /* _Py_write() must not be called with an exception set, otherwise the
  1179. * caller may think that write() was interrupted by a signal and the signal
  1180. * handler raised an exception. */
  1181. assert(!PyErr_Occurred());
  1182. return _Py_write_impl(fd, buf, count, 1);
  1183. }
  1184. /* Write count bytes of buf into fd.
  1185. *
  1186. * On success, return the number of written bytes, it can be lower than count
  1187. * including 0. On error, set errno and return -1.
  1188. *
  1189. * When interrupted by a signal (write() fails with EINTR), retry the syscall
  1190. * without calling the Python signal handler. */
  1191. Py_ssize_t
  1192. _Py_write_noraise(int fd, const void *buf, size_t count)
  1193. {
  1194. return _Py_write_impl(fd, buf, count, 0);
  1195. }
  1196. #ifdef HAVE_READLINK
  1197. /* Read value of symbolic link. Encode the path to the locale encoding, decode
  1198. the result from the locale encoding. Return -1 on error. */
  1199. int
  1200. _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
  1201. {
  1202. char *cpath;
  1203. char cbuf[MAXPATHLEN];
  1204. wchar_t *wbuf;
  1205. int res;
  1206. size_t r1;
  1207. cpath = Py_EncodeLocale(path, NULL);
  1208. if (cpath == NULL) {
  1209. errno = EINVAL;
  1210. return -1;
  1211. }
  1212. res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf));
  1213. PyMem_Free(cpath);
  1214. if (res == -1)
  1215. return -1;
  1216. if (res == Py_ARRAY_LENGTH(cbuf)) {
  1217. errno = EINVAL;
  1218. return -1;
  1219. }
  1220. cbuf[res] = '\0'; /* buf will be null terminated */
  1221. wbuf = Py_DecodeLocale(cbuf, &r1);
  1222. if (wbuf == NULL) {
  1223. errno = EINVAL;
  1224. return -1;
  1225. }
  1226. if (bufsiz <= r1) {
  1227. PyMem_RawFree(wbuf);
  1228. errno = EINVAL;
  1229. return -1;
  1230. }
  1231. wcsncpy(buf, wbuf, bufsiz);
  1232. PyMem_RawFree(wbuf);
  1233. return (int)r1;
  1234. }
  1235. #endif
  1236. #ifdef HAVE_REALPATH
  1237. /* Return the canonicalized absolute pathname. Encode path to the locale
  1238. encoding, decode the result from the locale encoding.
  1239. Return NULL on error. */
  1240. wchar_t*
  1241. _Py_wrealpath(const wchar_t *path,
  1242. wchar_t *resolved_path, size_t resolved_path_size)
  1243. {
  1244. char *cpath;
  1245. char cresolved_path[MAXPATHLEN];
  1246. wchar_t *wresolved_path;
  1247. char *res;
  1248. size_t r;
  1249. cpath = Py_EncodeLocale(path, NULL);
  1250. if (cpath == NULL) {
  1251. errno = EINVAL;
  1252. return NULL;
  1253. }
  1254. res = realpath(cpath, cresolved_path);
  1255. PyMem_Free(cpath);
  1256. if (res == NULL)
  1257. return NULL;
  1258. wresolved_path = Py_DecodeLocale(cresolved_path, &r);
  1259. if (wresolved_path == NULL) {
  1260. errno = EINVAL;
  1261. return NULL;
  1262. }
  1263. if (resolved_path_size <= r) {
  1264. PyMem_RawFree(wresolved_path);
  1265. errno = EINVAL;
  1266. return NULL;
  1267. }
  1268. wcsncpy(resolved_path, wresolved_path, resolved_path_size);
  1269. PyMem_RawFree(wresolved_path);
  1270. return resolved_path;
  1271. }
  1272. #endif
  1273. /* Get the current directory. size is the buffer size in wide characters
  1274. including the null character. Decode the path from the locale encoding.
  1275. Return NULL on error. */
  1276. wchar_t*
  1277. _Py_wgetcwd(wchar_t *buf, size_t size)
  1278. {
  1279. #ifdef MS_WINDOWS
  1280. int isize = (int)Py_MIN(size, INT_MAX);
  1281. return _wgetcwd(buf, isize);
  1282. #else
  1283. char fname[MAXPATHLEN];
  1284. wchar_t *wname;
  1285. size_t len;
  1286. if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
  1287. return NULL;
  1288. wname = Py_DecodeLocale(fname, &len);
  1289. if (wname == NULL)
  1290. return NULL;
  1291. if (size <= len) {
  1292. PyMem_RawFree(wname);
  1293. return NULL;
  1294. }
  1295. wcsncpy(buf, wname, size);
  1296. PyMem_RawFree(wname);
  1297. return buf;
  1298. #endif
  1299. }
  1300. /* Duplicate a file descriptor. The new file descriptor is created as
  1301. non-inheritable. Return a new file descriptor on success, raise an OSError
  1302. exception and return -1 on error.
  1303. The GIL is released to call dup(). The caller must hold the GIL. */
  1304. int
  1305. _Py_dup(int fd)
  1306. {
  1307. #ifdef MS_WINDOWS
  1308. HANDLE handle;
  1309. DWORD ftype;
  1310. #endif
  1311. #ifdef WITH_THREAD
  1312. assert(PyGILState_Check());
  1313. #endif
  1314. if (!_PyVerify_fd(fd)) {
  1315. PyErr_SetFromErrno(PyExc_OSError);
  1316. return -1;
  1317. }
  1318. #ifdef MS_WINDOWS
  1319. _Py_BEGIN_SUPPRESS_IPH
  1320. handle = (HANDLE)_get_osfhandle(fd);
  1321. _Py_END_SUPPRESS_IPH
  1322. if (handle == INVALID_HANDLE_VALUE) {
  1323. PyErr_SetFromErrno(PyExc_OSError);
  1324. return -1;
  1325. }
  1326. /* get the file type, ignore the error if it failed */
  1327. ftype = GetFileType(handle);
  1328. Py_BEGIN_ALLOW_THREADS
  1329. _Py_BEGIN_SUPPRESS_IPH
  1330. fd = dup(fd);
  1331. _Py_END_SUPPRESS_IPH
  1332. Py_END_ALLOW_THREADS
  1333. if (fd < 0) {
  1334. PyErr_SetFromErrno(PyExc_OSError);
  1335. return -1;
  1336. }
  1337. /* Character files like console cannot be make non-inheritable */
  1338. if (ftype != FILE_TYPE_CHAR) {
  1339. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1340. _Py_BEGIN_SUPPRESS_IPH
  1341. close(fd);
  1342. _Py_END_SUPPRESS_IPH
  1343. return -1;
  1344. }
  1345. }
  1346. #elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
  1347. Py_BEGIN_ALLOW_THREADS
  1348. _Py_BEGIN_SUPPRESS_IPH
  1349. fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
  1350. _Py_END_SUPPRESS_IPH
  1351. Py_END_ALLOW_THREADS
  1352. if (fd < 0) {
  1353. PyErr_SetFromErrno(PyExc_OSError);
  1354. return -1;
  1355. }
  1356. #else
  1357. Py_BEGIN_ALLOW_THREADS
  1358. _Py_BEGIN_SUPPRESS_IPH
  1359. fd = dup(fd);
  1360. _Py_END_SUPPRESS_IPH
  1361. Py_END_ALLOW_THREADS
  1362. if (fd < 0) {
  1363. PyErr_SetFromErrno(PyExc_OSError);
  1364. return -1;
  1365. }
  1366. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  1367. _Py_BEGIN_SUPPRESS_IPH
  1368. close(fd);
  1369. _Py_END_SUPPRESS_IPH
  1370. return -1;
  1371. }
  1372. #endif
  1373. return fd;
  1374. }
  1375. #ifndef MS_WINDOWS
  1376. /* Get the blocking mode of the file descriptor.
  1377. Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
  1378. raise an exception and return -1 on error. */
  1379. int
  1380. _Py_get_blocking(int fd)
  1381. {
  1382. int flags;
  1383. _Py_BEGIN_SUPPRESS_IPH
  1384. flags = fcntl(fd, F_GETFL, 0);
  1385. _Py_END_SUPPRESS_IPH
  1386. if (flags < 0) {
  1387. PyErr_SetFromErrno(PyExc_OSError);
  1388. return -1;
  1389. }
  1390. return !(flags & O_NONBLOCK);
  1391. }
  1392. /* Set the blocking mode of the specified file descriptor.
  1393. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
  1394. otherwise.
  1395. Return 0 on success, raise an exception and return -1 on error. */
  1396. int
  1397. _Py_set_blocking(int fd, int blocking)
  1398. {
  1399. #if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)
  1400. int arg = !blocking;
  1401. if (ioctl(fd, FIONBIO, &arg) < 0)
  1402. goto error;
  1403. #else
  1404. int flags, res;
  1405. _Py_BEGIN_SUPPRESS_IPH
  1406. flags = fcntl(fd, F_GETFL, 0);
  1407. if (flags >= 0) {
  1408. if (blocking)
  1409. flags = flags & (~O_NONBLOCK);
  1410. else
  1411. flags = flags | O_NONBLOCK;
  1412. res = fcntl(fd, F_SETFL, flags);
  1413. } else {
  1414. res = -1;
  1415. }
  1416. _Py_END_SUPPRESS_IPH
  1417. if (res < 0)
  1418. goto error;
  1419. #endif
  1420. return 0;
  1421. error:
  1422. PyErr_SetFromErrno(PyExc_OSError);
  1423. return -1;
  1424. }
  1425. #endif
  1426. #if defined _MSC_VER && _MSC_VER >= 1400 && _MSC_VER < 1900
  1427. /* Legacy implementation of _PyVerify_fd while transitioning to
  1428. * MSVC 14.0. This should eventually be removed. (issue23524)
  1429. */
  1430. /* Microsoft CRT in VS2005 and higher will verify that a filehandle is
  1431. * valid and raise an assertion if it isn't.
  1432. * Normally, an invalid fd is likely to be a C program error and therefore
  1433. * an assertion can be useful, but it does contradict the POSIX standard
  1434. * which for write(2) states:
  1435. * "Otherwise, -1 shall be returned and errno set to indicate the error."
  1436. * "[EBADF] The fildes argument is not a valid file descriptor open for
  1437. * writing."
  1438. * Furthermore, python allows the user to enter any old integer
  1439. * as a fd and should merely raise a python exception on error.
  1440. * The Microsoft CRT doesn't provide an official way to check for the
  1441. * validity of a file descriptor, but we can emulate its internal behaviour
  1442. * by using the exported __pinfo data member and knowledge of the
  1443. * internal structures involved.
  1444. * The structures below must be updated for each version of visual studio
  1445. * according to the file internal.h in the CRT source, until MS comes
  1446. * up with a less hacky way to do this.
  1447. * (all of this is to avoid globally modifying the CRT behaviour using
  1448. * _set_invalid_parameter_handler() and _CrtSetReportMode())
  1449. */
  1450. /* The actual size of the structure is determined at runtime.
  1451. * Only the first items must be present.
  1452. */
  1453. typedef struct {
  1454. intptr_t osfhnd;
  1455. char osfile;
  1456. } my_ioinfo;
  1457. extern __declspec(dllimport) char * __pioinfo[];
  1458. #define IOINFO_L2E 5
  1459. #define IOINFO_ARRAYS 64
  1460. #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
  1461. #define _NHANDLE_ (IOINFO_ARRAYS * IOINFO_ARRAY_ELTS)
  1462. #define FOPEN 0x01
  1463. #define _NO_CONSOLE_FILENO (intptr_t)-2
  1464. /* This function emulates what the windows CRT does to validate file handles */
  1465. int
  1466. _PyVerify_fd(int fd)
  1467. {
  1468. const int i1 = fd >> IOINFO_L2E;
  1469. const int i2 = fd & ((1 << IOINFO_L2E) - 1);
  1470. static size_t sizeof_ioinfo = 0;
  1471. /* Determine the actual size of the ioinfo structure,
  1472. * as used by the CRT loaded in memory
  1473. */
  1474. if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) {
  1475. sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS;
  1476. }
  1477. if (sizeof_ioinfo == 0) {
  1478. /* This should not happen... */
  1479. goto fail;
  1480. }
  1481. /* See that it isn't a special CLEAR fileno */
  1482. if (fd != _NO_CONSOLE_FILENO) {
  1483. /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead
  1484. * we check pointer validity and other info
  1485. */
  1486. if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) {
  1487. /* finally, check that the file is open */
  1488. my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo);
  1489. if (info->osfile & FOPEN) {
  1490. return 1;
  1491. }
  1492. }
  1493. }
  1494. fail:
  1495. errno = EBADF;
  1496. return 0;
  1497. }
  1498. #endif /* defined _MSC_VER && _MSC_VER >= 1400 && _MSC_VER < 1900 */