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.

1615 lines
43 KiB

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