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.

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