blob: eab58c5056147a72c9110de160124eca15458024 [file] [log] [blame]
Victor Stinner4e314432010-10-07 21:45:39 +00001#include "Python.h"
Stefan Krah6df5cae2012-11-12 20:14:36 +01002#include "osdefs.h"
Stefan Krah6c01e382014-01-20 15:31:08 +01003#include <locale.h>
4
Victor Stinnerb306d752010-10-07 22:09:40 +00005#ifdef MS_WINDOWS
Steve Dowerd81431f2015-03-06 14:47:02 -08006# include <malloc.h>
Victor Stinnerb306d752010-10-07 22:09:40 +00007# include <windows.h>
Steve Dower8fc89802015-04-12 00:26:27 -04008extern int winerror_to_errno(int);
Victor Stinnerb306d752010-10-07 22:09:40 +00009#endif
Victor Stinner4e314432010-10-07 21:45:39 +000010
Brett Cannonefb00c02012-02-29 18:31:31 -050011#ifdef HAVE_LANGINFO_H
12#include <langinfo.h>
13#endif
14
Victor Stinnerdaf45552013-08-28 00:53:59 +020015#ifdef HAVE_SYS_IOCTL_H
16#include <sys/ioctl.h>
17#endif
18
19#ifdef HAVE_FCNTL_H
20#include <fcntl.h>
21#endif /* HAVE_FCNTL_H */
22
Xavier de Gaye76febd02016-12-15 20:59:58 +010023#if defined(__APPLE__) || defined(__ANDROID__)
Victor Stinnere2623772012-11-12 23:04:02 +010024extern wchar_t* _Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size);
25#endif
26
Victor Stinnerdaf45552013-08-28 00:53:59 +020027#ifdef O_CLOEXEC
Victor Stinnerb034eee2013-09-07 10:36:04 +020028/* Does open() support the O_CLOEXEC flag? Possible values:
Victor Stinnerdaf45552013-08-28 00:53:59 +020029
30 -1: unknown
31 0: open() ignores O_CLOEXEC flag, ex: Linux kernel older than 2.6.23
32 1: open() supports O_CLOEXEC flag, close-on-exec is set
33
Victor Stinnera555cfc2015-03-18 00:22:14 +010034 The flag is used by _Py_open(), _Py_open_noraise(), io.FileIO
35 and os.open(). */
Victor Stinnerdaf45552013-08-28 00:53:59 +020036int _Py_open_cloexec_works = -1;
37#endif
38
Brett Cannonefb00c02012-02-29 18:31:31 -050039PyObject *
40_Py_device_encoding(int fd)
41{
Victor Stinner14b9b112013-06-25 00:37:25 +020042#if defined(MS_WINDOWS)
Brett Cannonefb00c02012-02-29 18:31:31 -050043 UINT cp;
44#endif
Steve Dower8fc89802015-04-12 00:26:27 -040045 int valid;
46 _Py_BEGIN_SUPPRESS_IPH
Steve Dower940f33a2016-09-08 11:21:54 -070047 valid = isatty(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040048 _Py_END_SUPPRESS_IPH
49 if (!valid)
Brett Cannonefb00c02012-02-29 18:31:31 -050050 Py_RETURN_NONE;
Steve Dower8fc89802015-04-12 00:26:27 -040051
Victor Stinner14b9b112013-06-25 00:37:25 +020052#if defined(MS_WINDOWS)
Brett Cannonefb00c02012-02-29 18:31:31 -050053 if (fd == 0)
54 cp = GetConsoleCP();
55 else if (fd == 1 || fd == 2)
56 cp = GetConsoleOutputCP();
57 else
58 cp = 0;
59 /* GetConsoleCP() and GetConsoleOutputCP() return 0 if the application
60 has no console */
61 if (cp != 0)
62 return PyUnicode_FromFormat("cp%u", (unsigned int)cp);
63#elif defined(CODESET)
64 {
65 char *codeset = nl_langinfo(CODESET);
66 if (codeset != NULL && codeset[0] != 0)
67 return PyUnicode_FromString(codeset);
68 }
69#endif
70 Py_RETURN_NONE;
71}
72
Victor Stinnerd45c7f82012-12-04 01:34:47 +010073#if !defined(__APPLE__) && !defined(MS_WINDOWS)
74extern int _Py_normalize_encoding(const char *, char *, size_t);
75
76/* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale.
77 On these operating systems, nl_langinfo(CODESET) announces an alias of the
78 ASCII encoding, whereas mbstowcs() and wcstombs() functions use the
79 ISO-8859-1 encoding. The problem is that os.fsencode() and os.fsdecode() use
80 locale.getpreferredencoding() codec. For example, if command line arguments
81 are decoded by mbstowcs() and encoded back by os.fsencode(), we get a
82 UnicodeEncodeError instead of retrieving the original byte string.
83
84 The workaround is enabled if setlocale(LC_CTYPE, NULL) returns "C",
85 nl_langinfo(CODESET) announces "ascii" (or an alias to ASCII), and at least
86 one byte in range 0x80-0xff can be decoded from the locale encoding. The
87 workaround is also enabled on error, for example if getting the locale
88 failed.
89
Philip Jenvey215c49a2013-01-15 13:24:12 -080090 Values of force_ascii:
Victor Stinnerd45c7f82012-12-04 01:34:47 +010091
Victor Stinnerf6a271a2014-08-01 12:28:48 +020092 1: the workaround is used: Py_EncodeLocale() uses
93 encode_ascii_surrogateescape() and Py_DecodeLocale() uses
Victor Stinnerd45c7f82012-12-04 01:34:47 +010094 decode_ascii_surrogateescape()
Victor Stinnerf6a271a2014-08-01 12:28:48 +020095 0: the workaround is not used: Py_EncodeLocale() uses wcstombs() and
96 Py_DecodeLocale() uses mbstowcs()
Victor Stinnerd45c7f82012-12-04 01:34:47 +010097 -1: unknown, need to call check_force_ascii() to get the value
98*/
99static int force_ascii = -1;
100
101static int
102check_force_ascii(void)
103{
104 char *loc;
105#if defined(HAVE_LANGINFO_H) && defined(CODESET)
106 char *codeset, **alias;
Victor Stinner54de2b12016-09-09 23:11:52 -0700107 char encoding[20]; /* longest name: "iso_646.irv_1991\0" */
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100108 int is_ascii;
109 unsigned int i;
110 char* ascii_aliases[] = {
111 "ascii",
Victor Stinner54de2b12016-09-09 23:11:52 -0700112 /* Aliases from Lib/encodings/aliases.py */
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100113 "646",
Victor Stinner54de2b12016-09-09 23:11:52 -0700114 "ansi_x3.4_1968",
115 "ansi_x3.4_1986",
116 "ansi_x3_4_1968",
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100117 "cp367",
118 "csascii",
119 "ibm367",
Victor Stinner54de2b12016-09-09 23:11:52 -0700120 "iso646_us",
121 "iso_646.irv_1991",
122 "iso_ir_6",
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100123 "us",
Victor Stinner54de2b12016-09-09 23:11:52 -0700124 "us_ascii",
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100125 NULL
126 };
127#endif
128
129 loc = setlocale(LC_CTYPE, NULL);
130 if (loc == NULL)
131 goto error;
132 if (strcmp(loc, "C") != 0) {
133 /* the LC_CTYPE locale is different than C */
134 return 0;
135 }
136
137#if defined(HAVE_LANGINFO_H) && defined(CODESET)
138 codeset = nl_langinfo(CODESET);
139 if (!codeset || codeset[0] == '\0') {
140 /* CODESET is not set or empty */
141 goto error;
142 }
143 if (!_Py_normalize_encoding(codeset, encoding, sizeof(encoding)))
144 goto error;
145
146 is_ascii = 0;
147 for (alias=ascii_aliases; *alias != NULL; alias++) {
148 if (strcmp(encoding, *alias) == 0) {
149 is_ascii = 1;
150 break;
151 }
152 }
153 if (!is_ascii) {
154 /* nl_langinfo(CODESET) is not "ascii" or an alias of ASCII */
155 return 0;
156 }
157
158 for (i=0x80; i<0xff; i++) {
159 unsigned char ch;
160 wchar_t wch;
161 size_t res;
162
163 ch = (unsigned char)i;
164 res = mbstowcs(&wch, (char*)&ch, 1);
165 if (res != (size_t)-1) {
166 /* decoding a non-ASCII character from the locale encoding succeed:
167 the locale encoding is not ASCII, force ASCII */
168 return 1;
169 }
170 }
171 /* None of the bytes in the range 0x80-0xff can be decoded from the locale
172 encoding: the locale encoding is really ASCII */
173 return 0;
174#else
175 /* nl_langinfo(CODESET) is not available: always force ASCII */
176 return 1;
177#endif
178
179error:
Martin Panter46f50722016-05-26 05:35:26 +0000180 /* if an error occurred, force the ASCII encoding */
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100181 return 1;
182}
183
184static char*
185encode_ascii_surrogateescape(const wchar_t *text, size_t *error_pos)
186{
187 char *result = NULL, *out;
188 size_t len, i;
189 wchar_t ch;
190
191 if (error_pos != NULL)
192 *error_pos = (size_t)-1;
193
194 len = wcslen(text);
195
196 result = PyMem_Malloc(len + 1); /* +1 for NUL byte */
197 if (result == NULL)
198 return NULL;
199
200 out = result;
201 for (i=0; i<len; i++) {
202 ch = text[i];
203
204 if (ch <= 0x7f) {
205 /* ASCII character */
206 *out++ = (char)ch;
207 }
208 else if (0xdc80 <= ch && ch <= 0xdcff) {
209 /* UTF-8b surrogate */
210 *out++ = (char)(ch - 0xdc00);
211 }
212 else {
213 if (error_pos != NULL)
214 *error_pos = i;
215 PyMem_Free(result);
216 return NULL;
217 }
218 }
219 *out = '\0';
220 return result;
221}
222#endif /* !defined(__APPLE__) && !defined(MS_WINDOWS) */
223
224#if !defined(__APPLE__) && (!defined(MS_WINDOWS) || !defined(HAVE_MBRTOWC))
225static wchar_t*
226decode_ascii_surrogateescape(const char *arg, size_t *size)
227{
228 wchar_t *res;
229 unsigned char *in;
230 wchar_t *out;
Benjamin Petersonf18bf6f2015-01-04 16:03:17 -0600231 size_t argsize = strlen(arg) + 1;
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100232
Benjamin Petersonf18bf6f2015-01-04 16:03:17 -0600233 if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
234 return NULL;
Benjamin Peterson10ecaa22015-01-04 16:05:39 -0600235 res = PyMem_RawMalloc(argsize*sizeof(wchar_t));
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100236 if (!res)
237 return NULL;
238
239 in = (unsigned char*)arg;
240 out = res;
241 while(*in)
242 if(*in < 128)
243 *out++ = *in++;
244 else
245 *out++ = 0xdc00 + *in++;
246 *out = 0;
247 if (size != NULL)
248 *size = out - res;
249 return res;
250}
251#endif
252
Victor Stinner4e314432010-10-07 21:45:39 +0000253
254/* Decode a byte string from the locale encoding with the
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200255 surrogateescape error handler: undecodable bytes are decoded as characters
256 in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate
Victor Stinner4e314432010-10-07 21:45:39 +0000257 character, escape the bytes using the surrogateescape error handler instead
258 of decoding them.
259
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200260 Return a pointer to a newly allocated wide character string, use
261 PyMem_RawFree() to free the memory. If size is not NULL, write the number of
262 wide characters excluding the null character into *size
Victor Stinner4e314432010-10-07 21:45:39 +0000263
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200264 Return NULL on decoding error or memory allocation error. If *size* is not
265 NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on
266 decoding error.
Victor Stinner19de4c32010-11-08 23:30:46 +0000267
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200268 Decoding errors should never happen, unless there is a bug in the C
269 library.
270
271 Use the Py_EncodeLocale() function to encode the character string back to a
272 byte string. */
Victor Stinner4e314432010-10-07 21:45:39 +0000273wchar_t*
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200274Py_DecodeLocale(const char* arg, size_t *size)
Victor Stinner4e314432010-10-07 21:45:39 +0000275{
Xavier de Gaye76febd02016-12-15 20:59:58 +0100276#if defined(__APPLE__) || defined(__ANDROID__)
Victor Stinnere2623772012-11-12 23:04:02 +0100277 wchar_t *wstr;
278 wstr = _Py_DecodeUTF8_surrogateescape(arg, strlen(arg));
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100279 if (size != NULL) {
280 if (wstr != NULL)
281 *size = wcslen(wstr);
282 else
283 *size = (size_t)-1;
284 }
Victor Stinnere2623772012-11-12 23:04:02 +0100285 return wstr;
286#else
Victor Stinner4e314432010-10-07 21:45:39 +0000287 wchar_t *res;
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100288 size_t argsize;
Victor Stinner4e314432010-10-07 21:45:39 +0000289 size_t count;
Victor Stinner313f10c2013-05-07 23:48:56 +0200290#ifdef HAVE_MBRTOWC
Victor Stinner4e314432010-10-07 21:45:39 +0000291 unsigned char *in;
292 wchar_t *out;
Victor Stinner4e314432010-10-07 21:45:39 +0000293 mbstate_t mbs;
294#endif
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100295
296#ifndef MS_WINDOWS
297 if (force_ascii == -1)
298 force_ascii = check_force_ascii();
299
300 if (force_ascii) {
301 /* force ASCII encoding to workaround mbstowcs() issue */
302 res = decode_ascii_surrogateescape(arg, size);
303 if (res == NULL)
304 goto oom;
305 return res;
306 }
307#endif
308
309#ifdef HAVE_BROKEN_MBSTOWCS
310 /* Some platforms have a broken implementation of
311 * mbstowcs which does not count the characters that
312 * would result from conversion. Use an upper bound.
313 */
314 argsize = strlen(arg);
315#else
316 argsize = mbstowcs(NULL, arg, 0);
317#endif
Victor Stinner4e314432010-10-07 21:45:39 +0000318 if (argsize != (size_t)-1) {
Benjamin Petersonf18bf6f2015-01-04 16:03:17 -0600319 if (argsize == PY_SSIZE_T_MAX)
320 goto oom;
321 argsize += 1;
322 if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
323 goto oom;
Benjamin Peterson10ecaa22015-01-04 16:05:39 -0600324 res = (wchar_t *)PyMem_RawMalloc(argsize*sizeof(wchar_t));
Victor Stinner4e314432010-10-07 21:45:39 +0000325 if (!res)
326 goto oom;
Benjamin Petersonf18bf6f2015-01-04 16:03:17 -0600327 count = mbstowcs(res, arg, argsize);
Victor Stinner4e314432010-10-07 21:45:39 +0000328 if (count != (size_t)-1) {
329 wchar_t *tmp;
330 /* Only use the result if it contains no
331 surrogate characters. */
332 for (tmp = res; *tmp != 0 &&
Victor Stinner76df43d2012-10-30 01:42:39 +0100333 !Py_UNICODE_IS_SURROGATE(*tmp); tmp++)
Victor Stinner4e314432010-10-07 21:45:39 +0000334 ;
Victor Stinner168e1172010-10-16 23:16:16 +0000335 if (*tmp == 0) {
336 if (size != NULL)
337 *size = count;
Victor Stinner4e314432010-10-07 21:45:39 +0000338 return res;
Victor Stinner168e1172010-10-16 23:16:16 +0000339 }
Victor Stinner4e314432010-10-07 21:45:39 +0000340 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200341 PyMem_RawFree(res);
Victor Stinner4e314432010-10-07 21:45:39 +0000342 }
343 /* Conversion failed. Fall back to escaping with surrogateescape. */
344#ifdef HAVE_MBRTOWC
345 /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
346
347 /* Overallocate; as multi-byte characters are in the argument, the
348 actual output could use less memory. */
349 argsize = strlen(arg) + 1;
Benjamin Petersonf18bf6f2015-01-04 16:03:17 -0600350 if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
351 goto oom;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200352 res = (wchar_t*)PyMem_RawMalloc(argsize*sizeof(wchar_t));
Victor Stinner19de4c32010-11-08 23:30:46 +0000353 if (!res)
354 goto oom;
Victor Stinner4e314432010-10-07 21:45:39 +0000355 in = (unsigned char*)arg;
356 out = res;
357 memset(&mbs, 0, sizeof mbs);
358 while (argsize) {
359 size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
360 if (converted == 0)
361 /* Reached end of string; null char stored. */
362 break;
363 if (converted == (size_t)-2) {
364 /* Incomplete character. This should never happen,
365 since we provide everything that we have -
366 unless there is a bug in the C library, or I
367 misunderstood how mbrtowc works. */
Victor Stinner1a7425f2013-07-07 16:25:15 +0200368 PyMem_RawFree(res);
Victor Stinneraf02e1c2011-12-16 23:56:01 +0100369 if (size != NULL)
370 *size = (size_t)-2;
Victor Stinner4e314432010-10-07 21:45:39 +0000371 return NULL;
372 }
373 if (converted == (size_t)-1) {
374 /* Conversion error. Escape as UTF-8b, and start over
375 in the initial shift state. */
376 *out++ = 0xdc00 + *in++;
377 argsize--;
378 memset(&mbs, 0, sizeof mbs);
379 continue;
380 }
Victor Stinner76df43d2012-10-30 01:42:39 +0100381 if (Py_UNICODE_IS_SURROGATE(*out)) {
Victor Stinner4e314432010-10-07 21:45:39 +0000382 /* Surrogate character. Escape the original
383 byte sequence with surrogateescape. */
384 argsize -= converted;
385 while (converted--)
386 *out++ = 0xdc00 + *in++;
387 continue;
388 }
389 /* successfully converted some bytes */
390 in += converted;
391 argsize -= converted;
392 out++;
393 }
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100394 if (size != NULL)
395 *size = out - res;
Victor Stinnere2623772012-11-12 23:04:02 +0100396#else /* HAVE_MBRTOWC */
Victor Stinner4e314432010-10-07 21:45:39 +0000397 /* Cannot use C locale for escaping; manually escape as if charset
398 is ASCII (i.e. escape all bytes > 128. This will still roundtrip
399 correctly in the locale's charset, which must be an ASCII superset. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100400 res = decode_ascii_surrogateescape(arg, size);
401 if (res == NULL)
Victor Stinneraf02e1c2011-12-16 23:56:01 +0100402 goto oom;
Victor Stinnere2623772012-11-12 23:04:02 +0100403#endif /* HAVE_MBRTOWC */
Victor Stinner4e314432010-10-07 21:45:39 +0000404 return res;
405oom:
Victor Stinneraf02e1c2011-12-16 23:56:01 +0100406 if (size != NULL)
407 *size = (size_t)-1;
Victor Stinner4e314432010-10-07 21:45:39 +0000408 return NULL;
Xavier de Gaye76febd02016-12-15 20:59:58 +0100409#endif /* __APPLE__ or __ANDROID__ */
Victor Stinner4e314432010-10-07 21:45:39 +0000410}
411
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200412/* Encode a wide character string to the locale encoding with the
413 surrogateescape error handler: surrogate characters in the range
414 U+DC80..U+DCFF are converted to bytes 0x80..0xFF.
Victor Stinner4e314432010-10-07 21:45:39 +0000415
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200416 Return a pointer to a newly allocated byte string, use PyMem_Free() to free
417 the memory. Return NULL on encoding or memory allocation error.
Victor Stinner4e314432010-10-07 21:45:39 +0000418
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200419 If error_pos is not NULL, *error_pos is set to the index of the invalid
420 character on encoding error, or set to (size_t)-1 otherwise.
Victor Stinner2f02a512010-11-08 22:43:46 +0000421
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200422 Use the Py_DecodeLocale() function to decode the bytes string back to a wide
423 character string. */
Victor Stinner4e314432010-10-07 21:45:39 +0000424char*
Victor Stinnerf6a271a2014-08-01 12:28:48 +0200425Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
Victor Stinner4e314432010-10-07 21:45:39 +0000426{
Xavier de Gaye76febd02016-12-15 20:59:58 +0100427#if defined(__APPLE__) || defined(__ANDROID__)
Victor Stinnere2623772012-11-12 23:04:02 +0100428 Py_ssize_t len;
429 PyObject *unicode, *bytes = NULL;
430 char *cpath;
431
432 unicode = PyUnicode_FromWideChar(text, wcslen(text));
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100433 if (unicode == NULL)
Victor Stinnere2623772012-11-12 23:04:02 +0100434 return NULL;
Victor Stinnere2623772012-11-12 23:04:02 +0100435
436 bytes = _PyUnicode_AsUTF8String(unicode, "surrogateescape");
437 Py_DECREF(unicode);
438 if (bytes == NULL) {
439 PyErr_Clear();
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100440 if (error_pos != NULL)
441 *error_pos = (size_t)-1;
Victor Stinnere2623772012-11-12 23:04:02 +0100442 return NULL;
443 }
444
445 len = PyBytes_GET_SIZE(bytes);
446 cpath = PyMem_Malloc(len+1);
447 if (cpath == NULL) {
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100448 PyErr_Clear();
Victor Stinnere2623772012-11-12 23:04:02 +0100449 Py_DECREF(bytes);
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100450 if (error_pos != NULL)
451 *error_pos = (size_t)-1;
Victor Stinnere2623772012-11-12 23:04:02 +0100452 return NULL;
453 }
454 memcpy(cpath, PyBytes_AsString(bytes), len + 1);
455 Py_DECREF(bytes);
456 return cpath;
457#else /* __APPLE__ */
Victor Stinner4e314432010-10-07 21:45:39 +0000458 const size_t len = wcslen(text);
459 char *result = NULL, *bytes = NULL;
460 size_t i, size, converted;
461 wchar_t c, buf[2];
462
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100463#ifndef MS_WINDOWS
464 if (force_ascii == -1)
465 force_ascii = check_force_ascii();
466
467 if (force_ascii)
468 return encode_ascii_surrogateescape(text, error_pos);
469#endif
470
Victor Stinner4e314432010-10-07 21:45:39 +0000471 /* The function works in two steps:
472 1. compute the length of the output buffer in bytes (size)
473 2. outputs the bytes */
474 size = 0;
475 buf[1] = 0;
476 while (1) {
477 for (i=0; i < len; i++) {
478 c = text[i];
479 if (c >= 0xdc80 && c <= 0xdcff) {
480 /* UTF-8b surrogate */
481 if (bytes != NULL) {
482 *bytes++ = c - 0xdc00;
483 size--;
484 }
485 else
486 size++;
487 continue;
488 }
489 else {
490 buf[0] = c;
491 if (bytes != NULL)
492 converted = wcstombs(bytes, buf, size);
493 else
494 converted = wcstombs(NULL, buf, 0);
495 if (converted == (size_t)-1) {
496 if (result != NULL)
497 PyMem_Free(result);
Victor Stinner2f02a512010-11-08 22:43:46 +0000498 if (error_pos != NULL)
499 *error_pos = i;
Victor Stinner4e314432010-10-07 21:45:39 +0000500 return NULL;
501 }
502 if (bytes != NULL) {
503 bytes += converted;
504 size -= converted;
505 }
506 else
507 size += converted;
508 }
509 }
510 if (result != NULL) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100511 *bytes = '\0';
Victor Stinner4e314432010-10-07 21:45:39 +0000512 break;
513 }
514
515 size += 1; /* nul byte at the end */
516 result = PyMem_Malloc(size);
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100517 if (result == NULL) {
518 if (error_pos != NULL)
519 *error_pos = (size_t)-1;
Victor Stinner4e314432010-10-07 21:45:39 +0000520 return NULL;
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100521 }
Victor Stinner4e314432010-10-07 21:45:39 +0000522 bytes = result;
523 }
524 return result;
Xavier de Gaye76febd02016-12-15 20:59:58 +0100525#endif /* __APPLE__ or __ANDROID__ */
Victor Stinner4e314432010-10-07 21:45:39 +0000526}
527
Victor Stinner6672d0c2010-10-07 22:53:43 +0000528
Steve Dowerf2f373f2015-02-21 08:44:05 -0800529#ifdef MS_WINDOWS
530static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
531
532static void
533FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
534{
535 /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
536 /* Cannot simply cast and dereference in_ptr,
537 since it might not be aligned properly */
538 __int64 in;
539 memcpy(&in, in_ptr, sizeof(in));
540 *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
541 *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
542}
543
544void
Steve Dowerbf1f3762015-02-21 15:26:02 -0800545_Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
Steve Dowerf2f373f2015-02-21 08:44:05 -0800546{
547 /* XXX endianness */
548 __int64 out;
549 out = time_in + secs_between_epochs;
550 out = out * 10000000 + nsec_in / 100;
551 memcpy(out_ptr, &out, sizeof(out));
552}
553
554/* Below, we *know* that ugo+r is 0444 */
555#if _S_IREAD != 0400
556#error Unsupported C library
557#endif
558static int
559attributes_to_mode(DWORD attr)
560{
561 int m = 0;
562 if (attr & FILE_ATTRIBUTE_DIRECTORY)
563 m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
564 else
565 m |= _S_IFREG;
566 if (attr & FILE_ATTRIBUTE_READONLY)
567 m |= 0444;
568 else
569 m |= 0666;
570 return m;
571}
572
Steve Dowerbf1f3762015-02-21 15:26:02 -0800573void
Victor Stinnere134a7f2015-03-30 10:09:31 +0200574_Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
575 struct _Py_stat_struct *result)
Steve Dowerf2f373f2015-02-21 08:44:05 -0800576{
577 memset(result, 0, sizeof(*result));
578 result->st_mode = attributes_to_mode(info->dwFileAttributes);
579 result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
580 result->st_dev = info->dwVolumeSerialNumber;
581 result->st_rdev = result->st_dev;
582 FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
583 FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
584 FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
585 result->st_nlink = info->nNumberOfLinks;
Victor Stinner0f6d7332017-03-09 17:34:28 +0100586 result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800587 if (reparse_tag == IO_REPARSE_TAG_SYMLINK) {
588 /* first clear the S_IFMT bits */
589 result->st_mode ^= (result->st_mode & S_IFMT);
590 /* now set the bits that make this a symlink */
591 result->st_mode |= S_IFLNK;
592 }
593 result->st_file_attributes = info->dwFileAttributes;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800594}
595#endif
596
597/* Return information about a file.
598
599 On POSIX, use fstat().
600
601 On Windows, use GetFileType() and GetFileInformationByHandle() which support
Victor Stinner8c663fd2017-11-08 14:44:44 -0800602 files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
603 than 2 GiB because the file size type is a signed 32-bit integer: see issue
Steve Dowerf2f373f2015-02-21 08:44:05 -0800604 #23152.
Victor Stinnere134a7f2015-03-30 10:09:31 +0200605
606 On Windows, set the last Windows error and return nonzero on error. On
607 POSIX, set errno and return nonzero on error. Fill status and return 0 on
608 success. */
Steve Dowerf2f373f2015-02-21 08:44:05 -0800609int
Victor Stinnere134a7f2015-03-30 10:09:31 +0200610_Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
Steve Dowerf2f373f2015-02-21 08:44:05 -0800611{
612#ifdef MS_WINDOWS
613 BY_HANDLE_FILE_INFORMATION info;
614 HANDLE h;
615 int type;
616
Steve Dower940f33a2016-09-08 11:21:54 -0700617 _Py_BEGIN_SUPPRESS_IPH
618 h = (HANDLE)_get_osfhandle(fd);
619 _Py_END_SUPPRESS_IPH
Steve Dowerf2f373f2015-02-21 08:44:05 -0800620
621 if (h == INVALID_HANDLE_VALUE) {
Steve Dower8fc89802015-04-12 00:26:27 -0400622 /* errno is already set by _get_osfhandle, but we also set
623 the Win32 error for callers who expect that */
Steve Dower8acde7d2015-03-07 18:14:07 -0800624 SetLastError(ERROR_INVALID_HANDLE);
Steve Dowerf2f373f2015-02-21 08:44:05 -0800625 return -1;
626 }
Victor Stinnere134a7f2015-03-30 10:09:31 +0200627 memset(status, 0, sizeof(*status));
Steve Dowerf2f373f2015-02-21 08:44:05 -0800628
629 type = GetFileType(h);
630 if (type == FILE_TYPE_UNKNOWN) {
631 DWORD error = GetLastError();
Steve Dower8fc89802015-04-12 00:26:27 -0400632 if (error != 0) {
633 errno = winerror_to_errno(error);
Steve Dowerf2f373f2015-02-21 08:44:05 -0800634 return -1;
Steve Dower8fc89802015-04-12 00:26:27 -0400635 }
Steve Dowerf2f373f2015-02-21 08:44:05 -0800636 /* else: valid but unknown file */
637 }
638
639 if (type != FILE_TYPE_DISK) {
640 if (type == FILE_TYPE_CHAR)
Victor Stinnere134a7f2015-03-30 10:09:31 +0200641 status->st_mode = _S_IFCHR;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800642 else if (type == FILE_TYPE_PIPE)
Victor Stinnere134a7f2015-03-30 10:09:31 +0200643 status->st_mode = _S_IFIFO;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800644 return 0;
645 }
646
647 if (!GetFileInformationByHandle(h, &info)) {
Steve Dower8fc89802015-04-12 00:26:27 -0400648 /* The Win32 error is already set, but we also set errno for
649 callers who expect it */
650 errno = winerror_to_errno(GetLastError());
Steve Dowerf2f373f2015-02-21 08:44:05 -0800651 return -1;
652 }
653
Victor Stinnere134a7f2015-03-30 10:09:31 +0200654 _Py_attribute_data_to_stat(&info, 0, status);
Steve Dowerf2f373f2015-02-21 08:44:05 -0800655 /* specific to fstat() */
Victor Stinner0f6d7332017-03-09 17:34:28 +0100656 status->st_ino = (((uint64_t)info.nFileIndexHigh) << 32) + info.nFileIndexLow;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800657 return 0;
658#else
Victor Stinnere134a7f2015-03-30 10:09:31 +0200659 return fstat(fd, status);
Steve Dowerf2f373f2015-02-21 08:44:05 -0800660#endif
661}
Steve Dowerf2f373f2015-02-21 08:44:05 -0800662
Victor Stinnere134a7f2015-03-30 10:09:31 +0200663/* Return information about a file.
664
665 On POSIX, use fstat().
666
667 On Windows, use GetFileType() and GetFileInformationByHandle() which support
Victor Stinner8c663fd2017-11-08 14:44:44 -0800668 files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
669 than 2 GiB because the file size type is a signed 32-bit integer: see issue
Victor Stinnere134a7f2015-03-30 10:09:31 +0200670 #23152.
671
672 Raise an exception and return -1 on error. On Windows, set the last Windows
673 error on error. On POSIX, set errno on error. Fill status and return 0 on
674 success.
675
Victor Stinner6f4fae82015-04-01 18:34:32 +0200676 Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
677 to call fstat(). The caller must hold the GIL. */
Victor Stinnere134a7f2015-03-30 10:09:31 +0200678int
679_Py_fstat(int fd, struct _Py_stat_struct *status)
680{
681 int res;
682
Victor Stinner8a1be612016-03-14 22:07:55 +0100683 assert(PyGILState_Check());
Victor Stinner8a1be612016-03-14 22:07:55 +0100684
Victor Stinnere134a7f2015-03-30 10:09:31 +0200685 Py_BEGIN_ALLOW_THREADS
686 res = _Py_fstat_noraise(fd, status);
687 Py_END_ALLOW_THREADS
688
689 if (res != 0) {
690#ifdef MS_WINDOWS
691 PyErr_SetFromWindowsErr(0);
692#else
693 PyErr_SetFromErrno(PyExc_OSError);
694#endif
695 return -1;
696 }
697 return 0;
698}
Steve Dowerf2f373f2015-02-21 08:44:05 -0800699
Victor Stinner6672d0c2010-10-07 22:53:43 +0000700/* Call _wstat() on Windows, or encode the path to the filesystem encoding and
701 call stat() otherwise. Only fill st_mode attribute on Windows.
702
Victor Stinnerbd0850b2011-12-18 20:47:30 +0100703 Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
704 raised. */
Victor Stinner4e314432010-10-07 21:45:39 +0000705
706int
Victor Stinnera4a75952010-10-07 22:23:10 +0000707_Py_stat(PyObject *path, struct stat *statbuf)
Victor Stinner4e314432010-10-07 21:45:39 +0000708{
709#ifdef MS_WINDOWS
Victor Stinner4e314432010-10-07 21:45:39 +0000710 int err;
711 struct _stat wstatbuf;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300712 const wchar_t *wpath;
Victor Stinner4e314432010-10-07 21:45:39 +0000713
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300714 wpath = _PyUnicode_AsUnicode(path);
Victor Stinneree587ea2011-11-17 00:51:38 +0100715 if (wpath == NULL)
Victor Stinnerbd0850b2011-12-18 20:47:30 +0100716 return -2;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300717
Victor Stinneree587ea2011-11-17 00:51:38 +0100718 err = _wstat(wpath, &wstatbuf);
Victor Stinner4e314432010-10-07 21:45:39 +0000719 if (!err)
720 statbuf->st_mode = wstatbuf.st_mode;
721 return err;
722#else
723 int ret;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300724 PyObject *bytes;
725 char *cpath;
726
727 bytes = PyUnicode_EncodeFSDefault(path);
Victor Stinner4e314432010-10-07 21:45:39 +0000728 if (bytes == NULL)
Victor Stinnerbd0850b2011-12-18 20:47:30 +0100729 return -2;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300730
731 /* check for embedded null bytes */
732 if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
733 Py_DECREF(bytes);
734 return -2;
735 }
736
737 ret = stat(cpath, statbuf);
Victor Stinner4e314432010-10-07 21:45:39 +0000738 Py_DECREF(bytes);
739 return ret;
740#endif
741}
742
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100743
Antoine Pitrou409b5382013-10-12 22:41:17 +0200744static int
Victor Stinnerdaf45552013-08-28 00:53:59 +0200745get_inheritable(int fd, int raise)
746{
747#ifdef MS_WINDOWS
748 HANDLE handle;
749 DWORD flags;
Victor Stinner6672d0c2010-10-07 22:53:43 +0000750
Steve Dower8fc89802015-04-12 00:26:27 -0400751 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +0200752 handle = (HANDLE)_get_osfhandle(fd);
Steve Dower8fc89802015-04-12 00:26:27 -0400753 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +0200754 if (handle == INVALID_HANDLE_VALUE) {
755 if (raise)
Steve Dower41e72442015-03-14 11:38:27 -0700756 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200757 return -1;
758 }
759
760 if (!GetHandleInformation(handle, &flags)) {
761 if (raise)
762 PyErr_SetFromWindowsErr(0);
763 return -1;
764 }
765
766 return (flags & HANDLE_FLAG_INHERIT);
767#else
768 int flags;
769
770 flags = fcntl(fd, F_GETFD, 0);
771 if (flags == -1) {
772 if (raise)
773 PyErr_SetFromErrno(PyExc_OSError);
774 return -1;
775 }
776 return !(flags & FD_CLOEXEC);
777#endif
778}
779
780/* Get the inheritable flag of the specified file descriptor.
Victor Stinnerb034eee2013-09-07 10:36:04 +0200781 Return 1 if the file descriptor can be inherited, 0 if it cannot,
Victor Stinnerdaf45552013-08-28 00:53:59 +0200782 raise an exception and return -1 on error. */
783int
784_Py_get_inheritable(int fd)
785{
786 return get_inheritable(fd, 1);
787}
788
789static int
790set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
791{
792#ifdef MS_WINDOWS
793 HANDLE handle;
794 DWORD flags;
Victor Stinner282124b2014-09-02 11:41:04 +0200795#else
796#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
797 static int ioctl_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200798 int request;
799 int err;
Victor Stinner282124b2014-09-02 11:41:04 +0200800#endif
Victor Stinnera858bbd2016-04-17 16:51:52 +0200801 int flags, new_flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200802 int res;
803#endif
804
805 /* atomic_flag_works can only be used to make the file descriptor
806 non-inheritable */
807 assert(!(atomic_flag_works != NULL && inheritable));
808
809 if (atomic_flag_works != NULL && !inheritable) {
810 if (*atomic_flag_works == -1) {
Steve Dower41e72442015-03-14 11:38:27 -0700811 int isInheritable = get_inheritable(fd, raise);
812 if (isInheritable == -1)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200813 return -1;
Steve Dower41e72442015-03-14 11:38:27 -0700814 *atomic_flag_works = !isInheritable;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200815 }
816
817 if (*atomic_flag_works)
818 return 0;
819 }
820
821#ifdef MS_WINDOWS
Steve Dower8fc89802015-04-12 00:26:27 -0400822 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +0200823 handle = (HANDLE)_get_osfhandle(fd);
Steve Dower8fc89802015-04-12 00:26:27 -0400824 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +0200825 if (handle == INVALID_HANDLE_VALUE) {
826 if (raise)
Steve Dower41e72442015-03-14 11:38:27 -0700827 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200828 return -1;
829 }
830
831 if (inheritable)
832 flags = HANDLE_FLAG_INHERIT;
833 else
834 flags = 0;
835 if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
836 if (raise)
837 PyErr_SetFromWindowsErr(0);
838 return -1;
839 }
840 return 0;
841
Victor Stinnerdaf45552013-08-28 00:53:59 +0200842#else
Victor Stinner282124b2014-09-02 11:41:04 +0200843
844#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
845 if (ioctl_works != 0) {
846 /* fast-path: ioctl() only requires one syscall */
847 if (inheritable)
848 request = FIONCLEX;
849 else
850 request = FIOCLEX;
851 err = ioctl(fd, request, NULL);
852 if (!err) {
853 ioctl_works = 1;
854 return 0;
855 }
856
Victor Stinner3116cc42016-05-19 16:46:18 +0200857 if (errno != ENOTTY && errno != EACCES) {
Victor Stinner282124b2014-09-02 11:41:04 +0200858 if (raise)
859 PyErr_SetFromErrno(PyExc_OSError);
860 return -1;
861 }
862 else {
863 /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
864 device". The ioctl is declared but not supported by the kernel.
865 Remember that ioctl() doesn't work. It is the case on
Victor Stinner3116cc42016-05-19 16:46:18 +0200866 Illumos-based OS for example.
867
868 Issue #27057: When SELinux policy disallows ioctl it will fail
869 with EACCES. While FIOCLEX is safe operation it may be
870 unavailable because ioctl was denied altogether.
871 This can be the case on Android. */
Victor Stinner282124b2014-09-02 11:41:04 +0200872 ioctl_works = 0;
873 }
874 /* fallback to fcntl() if ioctl() does not work */
875 }
876#endif
877
878 /* slow-path: fcntl() requires two syscalls */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200879 flags = fcntl(fd, F_GETFD);
880 if (flags < 0) {
881 if (raise)
882 PyErr_SetFromErrno(PyExc_OSError);
883 return -1;
884 }
885
Victor Stinnera858bbd2016-04-17 16:51:52 +0200886 if (inheritable) {
887 new_flags = flags & ~FD_CLOEXEC;
888 }
889 else {
890 new_flags = flags | FD_CLOEXEC;
891 }
892
893 if (new_flags == flags) {
894 /* FD_CLOEXEC flag already set/cleared: nothing to do */
895 return 0;
896 }
897
Xavier de Gayeec5d3cd2016-11-19 16:19:29 +0100898 res = fcntl(fd, F_SETFD, new_flags);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200899 if (res < 0) {
900 if (raise)
901 PyErr_SetFromErrno(PyExc_OSError);
902 return -1;
903 }
904 return 0;
905#endif
906}
907
908/* Make the file descriptor non-inheritable.
Victor Stinnerb034eee2013-09-07 10:36:04 +0200909 Return 0 on success, set errno and return -1 on error. */
Victor Stinnerdaf45552013-08-28 00:53:59 +0200910static int
911make_non_inheritable(int fd)
912{
913 return set_inheritable(fd, 0, 0, NULL);
914}
915
916/* Set the inheritable flag of the specified file descriptor.
917 On success: return 0, on error: raise an exception if raise is nonzero
918 and return -1.
919
920 If atomic_flag_works is not NULL:
921
922 * if *atomic_flag_works==-1, check if the inheritable is set on the file
923 descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
924 set the inheritable flag
925 * if *atomic_flag_works==1: do nothing
926 * if *atomic_flag_works==0: set inheritable flag to False
927
928 Set atomic_flag_works to NULL if no atomic flag was used to create the
929 file descriptor.
930
931 atomic_flag_works can only be used to make a file descriptor
932 non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
933int
934_Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
935{
936 return set_inheritable(fd, inheritable, 1, atomic_flag_works);
937}
938
Victor Stinnera555cfc2015-03-18 00:22:14 +0100939static int
940_Py_open_impl(const char *pathname, int flags, int gil_held)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200941{
942 int fd;
Victor Stinnera47fc5c2015-03-18 09:52:54 +0100943 int async_err = 0;
Victor Stinnera555cfc2015-03-18 00:22:14 +0100944#ifndef MS_WINDOWS
Victor Stinnerdaf45552013-08-28 00:53:59 +0200945 int *atomic_flag_works;
Victor Stinnera555cfc2015-03-18 00:22:14 +0100946#endif
947
948#ifdef MS_WINDOWS
949 flags |= O_NOINHERIT;
950#elif defined(O_CLOEXEC)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200951 atomic_flag_works = &_Py_open_cloexec_works;
952 flags |= O_CLOEXEC;
953#else
954 atomic_flag_works = NULL;
955#endif
Victor Stinnerdaf45552013-08-28 00:53:59 +0200956
Victor Stinnera555cfc2015-03-18 00:22:14 +0100957 if (gil_held) {
Victor Stinnera47fc5c2015-03-18 09:52:54 +0100958 do {
959 Py_BEGIN_ALLOW_THREADS
960 fd = open(pathname, flags);
961 Py_END_ALLOW_THREADS
962 } while (fd < 0
963 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
964 if (async_err)
965 return -1;
Victor Stinnera555cfc2015-03-18 00:22:14 +0100966 if (fd < 0) {
967 PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname);
968 return -1;
969 }
970 }
971 else {
972 fd = open(pathname, flags);
973 if (fd < 0)
974 return -1;
975 }
976
977#ifndef MS_WINDOWS
978 if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
Victor Stinnerdaf45552013-08-28 00:53:59 +0200979 close(fd);
980 return -1;
981 }
Victor Stinnera555cfc2015-03-18 00:22:14 +0100982#endif
983
Victor Stinnerdaf45552013-08-28 00:53:59 +0200984 return fd;
985}
986
Victor Stinnera555cfc2015-03-18 00:22:14 +0100987/* Open a file with the specified flags (wrapper to open() function).
988 Return a file descriptor on success. Raise an exception and return -1 on
989 error.
990
991 The file descriptor is created non-inheritable.
992
Victor Stinnera47fc5c2015-03-18 09:52:54 +0100993 When interrupted by a signal (open() fails with EINTR), retry the syscall,
994 except if the Python signal handler raises an exception.
995
Victor Stinner6f4fae82015-04-01 18:34:32 +0200996 Release the GIL to call open(). The caller must hold the GIL. */
Victor Stinnera555cfc2015-03-18 00:22:14 +0100997int
998_Py_open(const char *pathname, int flags)
999{
1000 /* _Py_open() must be called with the GIL held. */
1001 assert(PyGILState_Check());
1002 return _Py_open_impl(pathname, flags, 1);
1003}
1004
1005/* Open a file with the specified flags (wrapper to open() function).
1006 Return a file descriptor on success. Set errno and return -1 on error.
1007
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001008 The file descriptor is created non-inheritable.
1009
1010 If interrupted by a signal, fail with EINTR. */
Victor Stinnera555cfc2015-03-18 00:22:14 +01001011int
1012_Py_open_noraise(const char *pathname, int flags)
1013{
1014 return _Py_open_impl(pathname, flags, 0);
1015}
1016
Victor Stinnerdaf45552013-08-28 00:53:59 +02001017/* Open a file. Use _wfopen() on Windows, encode the path to the locale
Victor Stinnere42ccd22015-03-18 01:39:23 +01001018 encoding and use fopen() otherwise.
1019
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001020 The file descriptor is created non-inheritable.
1021
1022 If interrupted by a signal, fail with EINTR. */
Victor Stinner4e314432010-10-07 21:45:39 +00001023FILE *
1024_Py_wfopen(const wchar_t *path, const wchar_t *mode)
1025{
Victor Stinner4e314432010-10-07 21:45:39 +00001026 FILE *f;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001027#ifndef MS_WINDOWS
Victor Stinner4e314432010-10-07 21:45:39 +00001028 char *cpath;
1029 char cmode[10];
1030 size_t r;
1031 r = wcstombs(cmode, mode, 10);
1032 if (r == (size_t)-1 || r >= 10) {
1033 errno = EINVAL;
1034 return NULL;
1035 }
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001036 cpath = Py_EncodeLocale(path, NULL);
Victor Stinner4e314432010-10-07 21:45:39 +00001037 if (cpath == NULL)
1038 return NULL;
1039 f = fopen(cpath, cmode);
1040 PyMem_Free(cpath);
Victor Stinner4e314432010-10-07 21:45:39 +00001041#else
Victor Stinnerdaf45552013-08-28 00:53:59 +02001042 f = _wfopen(path, mode);
Victor Stinner4e314432010-10-07 21:45:39 +00001043#endif
Victor Stinnerdaf45552013-08-28 00:53:59 +02001044 if (f == NULL)
1045 return NULL;
1046 if (make_non_inheritable(fileno(f)) < 0) {
1047 fclose(f);
1048 return NULL;
1049 }
1050 return f;
Victor Stinner4e314432010-10-07 21:45:39 +00001051}
1052
Victor Stinnere42ccd22015-03-18 01:39:23 +01001053/* Wrapper to fopen().
1054
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001055 The file descriptor is created non-inheritable.
1056
1057 If interrupted by a signal, fail with EINTR. */
Victor Stinnerdaf45552013-08-28 00:53:59 +02001058FILE*
1059_Py_fopen(const char *pathname, const char *mode)
1060{
1061 FILE *f = fopen(pathname, mode);
1062 if (f == NULL)
1063 return NULL;
1064 if (make_non_inheritable(fileno(f)) < 0) {
1065 fclose(f);
1066 return NULL;
1067 }
1068 return f;
1069}
1070
1071/* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
Victor Stinnere42ccd22015-03-18 01:39:23 +01001072 encoding and call fopen() otherwise.
Victor Stinner6672d0c2010-10-07 22:53:43 +00001073
Victor Stinnere42ccd22015-03-18 01:39:23 +01001074 Return the new file object on success. Raise an exception and return NULL
1075 on error.
1076
1077 The file descriptor is created non-inheritable.
1078
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001079 When interrupted by a signal (open() fails with EINTR), retry the syscall,
1080 except if the Python signal handler raises an exception.
1081
Victor Stinner6f4fae82015-04-01 18:34:32 +02001082 Release the GIL to call _wfopen() or fopen(). The caller must hold
1083 the GIL. */
Victor Stinner4e314432010-10-07 21:45:39 +00001084FILE*
Victor Stinnerdaf45552013-08-28 00:53:59 +02001085_Py_fopen_obj(PyObject *path, const char *mode)
Victor Stinner4e314432010-10-07 21:45:39 +00001086{
Victor Stinnerdaf45552013-08-28 00:53:59 +02001087 FILE *f;
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001088 int async_err = 0;
Victor Stinner4e314432010-10-07 21:45:39 +00001089#ifdef MS_WINDOWS
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03001090 const wchar_t *wpath;
Victor Stinner4e314432010-10-07 21:45:39 +00001091 wchar_t wmode[10];
1092 int usize;
Victor Stinner4e314432010-10-07 21:45:39 +00001093
Victor Stinnere42ccd22015-03-18 01:39:23 +01001094 assert(PyGILState_Check());
1095
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001096 if (!PyUnicode_Check(path)) {
1097 PyErr_Format(PyExc_TypeError,
1098 "str file path expected under Windows, got %R",
1099 Py_TYPE(path));
1100 return NULL;
1101 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03001102 wpath = _PyUnicode_AsUnicode(path);
Victor Stinneree587ea2011-11-17 00:51:38 +01001103 if (wpath == NULL)
1104 return NULL;
1105
Victor Stinner4e314432010-10-07 21:45:39 +00001106 usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
Victor Stinnere42ccd22015-03-18 01:39:23 +01001107 if (usize == 0) {
1108 PyErr_SetFromWindowsErr(0);
Victor Stinner4e314432010-10-07 21:45:39 +00001109 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01001110 }
Victor Stinner4e314432010-10-07 21:45:39 +00001111
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001112 do {
1113 Py_BEGIN_ALLOW_THREADS
1114 f = _wfopen(wpath, wmode);
1115 Py_END_ALLOW_THREADS
1116 } while (f == NULL
1117 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner4e314432010-10-07 21:45:39 +00001118#else
Antoine Pitrou2b1cc892011-12-19 18:19:06 +01001119 PyObject *bytes;
Victor Stinnere42ccd22015-03-18 01:39:23 +01001120 char *path_bytes;
1121
1122 assert(PyGILState_Check());
1123
Antoine Pitrou2b1cc892011-12-19 18:19:06 +01001124 if (!PyUnicode_FSConverter(path, &bytes))
Victor Stinner4e314432010-10-07 21:45:39 +00001125 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01001126 path_bytes = PyBytes_AS_STRING(bytes);
1127
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001128 do {
1129 Py_BEGIN_ALLOW_THREADS
1130 f = fopen(path_bytes, mode);
1131 Py_END_ALLOW_THREADS
1132 } while (f == NULL
1133 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnere42ccd22015-03-18 01:39:23 +01001134
Victor Stinner4e314432010-10-07 21:45:39 +00001135 Py_DECREF(bytes);
Victor Stinner4e314432010-10-07 21:45:39 +00001136#endif
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001137 if (async_err)
1138 return NULL;
1139
Victor Stinnere42ccd22015-03-18 01:39:23 +01001140 if (f == NULL) {
1141 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001142 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01001143 }
1144
1145 if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
Victor Stinnerdaf45552013-08-28 00:53:59 +02001146 fclose(f);
1147 return NULL;
1148 }
1149 return f;
Victor Stinner4e314432010-10-07 21:45:39 +00001150}
1151
Victor Stinner66aab0c2015-03-19 22:53:20 +01001152/* Read count bytes from fd into buf.
Victor Stinner82c3e452015-04-01 18:34:45 +02001153
1154 On success, return the number of read bytes, it can be lower than count.
1155 If the current file offset is at or past the end of file, no bytes are read,
1156 and read() returns zero.
1157
1158 On error, raise an exception, set errno and return -1.
1159
1160 When interrupted by a signal (read() 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
1164 Release the GIL to call read(). The caller must hold the GIL. */
Victor Stinner66aab0c2015-03-19 22:53:20 +01001165Py_ssize_t
1166_Py_read(int fd, void *buf, size_t count)
1167{
1168 Py_ssize_t n;
Victor Stinnera3c02022015-03-20 11:58:18 +01001169 int err;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001170 int async_err = 0;
1171
Victor Stinner8a1be612016-03-14 22:07:55 +01001172 assert(PyGILState_Check());
Victor Stinner8a1be612016-03-14 22:07:55 +01001173
Victor Stinner66aab0c2015-03-19 22:53:20 +01001174 /* _Py_read() must not be called with an exception set, otherwise the
1175 * caller may think that read() was interrupted by a signal and the signal
1176 * handler raised an exception. */
1177 assert(!PyErr_Occurred());
1178
Victor Stinner66aab0c2015-03-19 22:53:20 +01001179#ifdef MS_WINDOWS
1180 if (count > INT_MAX) {
1181 /* On Windows, the count parameter of read() is an int */
1182 count = INT_MAX;
1183 }
1184#else
1185 if (count > PY_SSIZE_T_MAX) {
1186 /* if count is greater than PY_SSIZE_T_MAX,
1187 * read() result is undefined */
1188 count = PY_SSIZE_T_MAX;
1189 }
1190#endif
1191
Steve Dower8fc89802015-04-12 00:26:27 -04001192 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner66aab0c2015-03-19 22:53:20 +01001193 do {
1194 Py_BEGIN_ALLOW_THREADS
1195 errno = 0;
1196#ifdef MS_WINDOWS
1197 n = read(fd, buf, (int)count);
1198#else
1199 n = read(fd, buf, count);
1200#endif
Victor Stinnera3c02022015-03-20 11:58:18 +01001201 /* save/restore errno because PyErr_CheckSignals()
1202 * and PyErr_SetFromErrno() can modify it */
1203 err = errno;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001204 Py_END_ALLOW_THREADS
Victor Stinnera3c02022015-03-20 11:58:18 +01001205 } while (n < 0 && err == EINTR &&
Victor Stinner66aab0c2015-03-19 22:53:20 +01001206 !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04001207 _Py_END_SUPPRESS_IPH
Victor Stinner66aab0c2015-03-19 22:53:20 +01001208
1209 if (async_err) {
1210 /* read() was interrupted by a signal (failed with EINTR)
1211 * and the Python signal handler raised an exception */
Victor Stinnera3c02022015-03-20 11:58:18 +01001212 errno = err;
1213 assert(errno == EINTR && PyErr_Occurred());
Victor Stinner66aab0c2015-03-19 22:53:20 +01001214 return -1;
1215 }
1216 if (n < 0) {
Victor Stinner66aab0c2015-03-19 22:53:20 +01001217 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnera3c02022015-03-20 11:58:18 +01001218 errno = err;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001219 return -1;
1220 }
1221
1222 return n;
1223}
1224
Victor Stinner82c3e452015-04-01 18:34:45 +02001225static Py_ssize_t
1226_Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
Victor Stinner66aab0c2015-03-19 22:53:20 +01001227{
1228 Py_ssize_t n;
Victor Stinnera3c02022015-03-20 11:58:18 +01001229 int err;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001230 int async_err = 0;
1231
Steve Dower8fc89802015-04-12 00:26:27 -04001232 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner66aab0c2015-03-19 22:53:20 +01001233#ifdef MS_WINDOWS
1234 if (count > 32767 && isatty(fd)) {
1235 /* Issue #11395: the Windows console returns an error (12: not
1236 enough space error) on writing into stdout if stdout mode is
1237 binary and the length is greater than 66,000 bytes (or less,
1238 depending on heap usage). */
1239 count = 32767;
1240 }
1241 else if (count > INT_MAX)
1242 count = INT_MAX;
1243#else
1244 if (count > PY_SSIZE_T_MAX) {
1245 /* write() should truncate count to PY_SSIZE_T_MAX, but it's safer
1246 * to do it ourself to have a portable behaviour. */
1247 count = PY_SSIZE_T_MAX;
1248 }
1249#endif
1250
Victor Stinner82c3e452015-04-01 18:34:45 +02001251 if (gil_held) {
1252 do {
1253 Py_BEGIN_ALLOW_THREADS
1254 errno = 0;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001255#ifdef MS_WINDOWS
Victor Stinner82c3e452015-04-01 18:34:45 +02001256 n = write(fd, buf, (int)count);
Victor Stinner66aab0c2015-03-19 22:53:20 +01001257#else
Victor Stinner82c3e452015-04-01 18:34:45 +02001258 n = write(fd, buf, count);
Victor Stinner66aab0c2015-03-19 22:53:20 +01001259#endif
Victor Stinner82c3e452015-04-01 18:34:45 +02001260 /* save/restore errno because PyErr_CheckSignals()
1261 * and PyErr_SetFromErrno() can modify it */
1262 err = errno;
1263 Py_END_ALLOW_THREADS
1264 } while (n < 0 && err == EINTR &&
1265 !(async_err = PyErr_CheckSignals()));
1266 }
1267 else {
1268 do {
1269 errno = 0;
1270#ifdef MS_WINDOWS
1271 n = write(fd, buf, (int)count);
1272#else
1273 n = write(fd, buf, count);
1274#endif
1275 err = errno;
1276 } while (n < 0 && err == EINTR);
1277 }
Steve Dower8fc89802015-04-12 00:26:27 -04001278 _Py_END_SUPPRESS_IPH
Victor Stinner66aab0c2015-03-19 22:53:20 +01001279
1280 if (async_err) {
1281 /* write() was interrupted by a signal (failed with EINTR)
Victor Stinner82c3e452015-04-01 18:34:45 +02001282 and the Python signal handler raised an exception (if gil_held is
1283 nonzero). */
Victor Stinnera3c02022015-03-20 11:58:18 +01001284 errno = err;
Victor Stinner82c3e452015-04-01 18:34:45 +02001285 assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
Victor Stinner66aab0c2015-03-19 22:53:20 +01001286 return -1;
1287 }
1288 if (n < 0) {
Victor Stinner82c3e452015-04-01 18:34:45 +02001289 if (gil_held)
1290 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnera3c02022015-03-20 11:58:18 +01001291 errno = err;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001292 return -1;
1293 }
1294
1295 return n;
1296}
1297
Victor Stinner82c3e452015-04-01 18:34:45 +02001298/* Write count bytes of buf into fd.
1299
1300 On success, return the number of written bytes, it can be lower than count
1301 including 0. On error, raise an exception, set errno and return -1.
1302
1303 When interrupted by a signal (write() fails with EINTR), retry the syscall.
1304 If the Python signal handler raises an exception, the function returns -1
1305 (the syscall is not retried).
1306
1307 Release the GIL to call write(). The caller must hold the GIL. */
1308Py_ssize_t
1309_Py_write(int fd, const void *buf, size_t count)
1310{
Victor Stinner8a1be612016-03-14 22:07:55 +01001311 assert(PyGILState_Check());
Victor Stinner8a1be612016-03-14 22:07:55 +01001312
Victor Stinner82c3e452015-04-01 18:34:45 +02001313 /* _Py_write() must not be called with an exception set, otherwise the
1314 * caller may think that write() was interrupted by a signal and the signal
1315 * handler raised an exception. */
1316 assert(!PyErr_Occurred());
1317
1318 return _Py_write_impl(fd, buf, count, 1);
1319}
1320
1321/* Write count bytes of buf into fd.
1322 *
1323 * On success, return the number of written bytes, it can be lower than count
1324 * including 0. On error, set errno and return -1.
1325 *
1326 * When interrupted by a signal (write() fails with EINTR), retry the syscall
1327 * without calling the Python signal handler. */
1328Py_ssize_t
1329_Py_write_noraise(int fd, const void *buf, size_t count)
1330{
1331 return _Py_write_impl(fd, buf, count, 0);
1332}
1333
Victor Stinner4e314432010-10-07 21:45:39 +00001334#ifdef HAVE_READLINK
Victor Stinner6672d0c2010-10-07 22:53:43 +00001335
1336/* Read value of symbolic link. Encode the path to the locale encoding, decode
Victor Stinneraf02e1c2011-12-16 23:56:01 +01001337 the result from the locale encoding. Return -1 on error. */
Victor Stinner6672d0c2010-10-07 22:53:43 +00001338
Victor Stinner4e314432010-10-07 21:45:39 +00001339int
1340_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
1341{
1342 char *cpath;
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001343 char cbuf[MAXPATHLEN];
Victor Stinner3f711f42010-10-16 22:47:37 +00001344 wchar_t *wbuf;
Victor Stinner4e314432010-10-07 21:45:39 +00001345 int res;
1346 size_t r1;
1347
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001348 cpath = Py_EncodeLocale(path, NULL);
Victor Stinner4e314432010-10-07 21:45:39 +00001349 if (cpath == NULL) {
1350 errno = EINVAL;
1351 return -1;
1352 }
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001353 res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf));
Victor Stinner4e314432010-10-07 21:45:39 +00001354 PyMem_Free(cpath);
1355 if (res == -1)
1356 return -1;
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001357 if (res == Py_ARRAY_LENGTH(cbuf)) {
Victor Stinner4e314432010-10-07 21:45:39 +00001358 errno = EINVAL;
1359 return -1;
1360 }
1361 cbuf[res] = '\0'; /* buf will be null terminated */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001362 wbuf = Py_DecodeLocale(cbuf, &r1);
Victor Stinner350147b2010-10-16 22:52:09 +00001363 if (wbuf == NULL) {
1364 errno = EINVAL;
1365 return -1;
1366 }
Victor Stinner3f711f42010-10-16 22:47:37 +00001367 if (bufsiz <= r1) {
Victor Stinner1a7425f2013-07-07 16:25:15 +02001368 PyMem_RawFree(wbuf);
Victor Stinner4e314432010-10-07 21:45:39 +00001369 errno = EINVAL;
1370 return -1;
1371 }
Victor Stinner3f711f42010-10-16 22:47:37 +00001372 wcsncpy(buf, wbuf, bufsiz);
Victor Stinner1a7425f2013-07-07 16:25:15 +02001373 PyMem_RawFree(wbuf);
Victor Stinner4e314432010-10-07 21:45:39 +00001374 return (int)r1;
1375}
1376#endif
1377
1378#ifdef HAVE_REALPATH
Victor Stinner6672d0c2010-10-07 22:53:43 +00001379
1380/* Return the canonicalized absolute pathname. Encode path to the locale
Victor Stinneraf02e1c2011-12-16 23:56:01 +01001381 encoding, decode the result from the locale encoding.
1382 Return NULL on error. */
Victor Stinner6672d0c2010-10-07 22:53:43 +00001383
Victor Stinner4e314432010-10-07 21:45:39 +00001384wchar_t*
Victor Stinner015f4d82010-10-07 22:29:53 +00001385_Py_wrealpath(const wchar_t *path,
1386 wchar_t *resolved_path, size_t resolved_path_size)
Victor Stinner4e314432010-10-07 21:45:39 +00001387{
1388 char *cpath;
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001389 char cresolved_path[MAXPATHLEN];
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001390 wchar_t *wresolved_path;
Victor Stinner4e314432010-10-07 21:45:39 +00001391 char *res;
1392 size_t r;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001393 cpath = Py_EncodeLocale(path, NULL);
Victor Stinner4e314432010-10-07 21:45:39 +00001394 if (cpath == NULL) {
1395 errno = EINVAL;
1396 return NULL;
1397 }
1398 res = realpath(cpath, cresolved_path);
1399 PyMem_Free(cpath);
1400 if (res == NULL)
1401 return NULL;
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001402
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001403 wresolved_path = Py_DecodeLocale(cresolved_path, &r);
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001404 if (wresolved_path == NULL) {
Victor Stinner4e314432010-10-07 21:45:39 +00001405 errno = EINVAL;
1406 return NULL;
1407 }
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001408 if (resolved_path_size <= r) {
Victor Stinner1a7425f2013-07-07 16:25:15 +02001409 PyMem_RawFree(wresolved_path);
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001410 errno = EINVAL;
1411 return NULL;
1412 }
1413 wcsncpy(resolved_path, wresolved_path, resolved_path_size);
Victor Stinner1a7425f2013-07-07 16:25:15 +02001414 PyMem_RawFree(wresolved_path);
Victor Stinner4e314432010-10-07 21:45:39 +00001415 return resolved_path;
1416}
1417#endif
1418
Victor Stinnerf4061da2010-10-14 12:37:19 +00001419/* Get the current directory. size is the buffer size in wide characters
Victor Stinneraf02e1c2011-12-16 23:56:01 +01001420 including the null character. Decode the path from the locale encoding.
1421 Return NULL on error. */
Victor Stinner6672d0c2010-10-07 22:53:43 +00001422
Victor Stinner4e314432010-10-07 21:45:39 +00001423wchar_t*
1424_Py_wgetcwd(wchar_t *buf, size_t size)
1425{
1426#ifdef MS_WINDOWS
Victor Stinner56785ea2013-06-05 00:46:29 +02001427 int isize = (int)Py_MIN(size, INT_MAX);
1428 return _wgetcwd(buf, isize);
Victor Stinner4e314432010-10-07 21:45:39 +00001429#else
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001430 char fname[MAXPATHLEN];
Victor Stinnerf4061da2010-10-14 12:37:19 +00001431 wchar_t *wname;
Victor Stinner168e1172010-10-16 23:16:16 +00001432 size_t len;
Victor Stinnerf4061da2010-10-14 12:37:19 +00001433
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001434 if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
Victor Stinner4e314432010-10-07 21:45:39 +00001435 return NULL;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001436 wname = Py_DecodeLocale(fname, &len);
Victor Stinnerf4061da2010-10-14 12:37:19 +00001437 if (wname == NULL)
1438 return NULL;
Victor Stinner168e1172010-10-16 23:16:16 +00001439 if (size <= len) {
Victor Stinner1a7425f2013-07-07 16:25:15 +02001440 PyMem_RawFree(wname);
Victor Stinner4e314432010-10-07 21:45:39 +00001441 return NULL;
1442 }
Victor Stinnerf4061da2010-10-14 12:37:19 +00001443 wcsncpy(buf, wname, size);
Victor Stinner1a7425f2013-07-07 16:25:15 +02001444 PyMem_RawFree(wname);
Victor Stinner4e314432010-10-07 21:45:39 +00001445 return buf;
1446#endif
1447}
1448
Victor Stinnerdaf45552013-08-28 00:53:59 +02001449/* Duplicate a file descriptor. The new file descriptor is created as
1450 non-inheritable. Return a new file descriptor on success, raise an OSError
1451 exception and return -1 on error.
1452
1453 The GIL is released to call dup(). The caller must hold the GIL. */
1454int
1455_Py_dup(int fd)
1456{
1457#ifdef MS_WINDOWS
1458 HANDLE handle;
1459 DWORD ftype;
1460#endif
1461
Victor Stinner8a1be612016-03-14 22:07:55 +01001462 assert(PyGILState_Check());
Victor Stinner8a1be612016-03-14 22:07:55 +01001463
Victor Stinnerdaf45552013-08-28 00:53:59 +02001464#ifdef MS_WINDOWS
Steve Dower8fc89802015-04-12 00:26:27 -04001465 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001466 handle = (HANDLE)_get_osfhandle(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001467 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001468 if (handle == INVALID_HANDLE_VALUE) {
Steve Dower41e72442015-03-14 11:38:27 -07001469 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001470 return -1;
1471 }
1472
1473 /* get the file type, ignore the error if it failed */
1474 ftype = GetFileType(handle);
1475
1476 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001477 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001478 fd = dup(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001479 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001480 Py_END_ALLOW_THREADS
1481 if (fd < 0) {
1482 PyErr_SetFromErrno(PyExc_OSError);
1483 return -1;
1484 }
1485
1486 /* Character files like console cannot be make non-inheritable */
1487 if (ftype != FILE_TYPE_CHAR) {
1488 if (_Py_set_inheritable(fd, 0, NULL) < 0) {
Steve Dower8fc89802015-04-12 00:26:27 -04001489 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001490 close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001491 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001492 return -1;
1493 }
1494 }
1495#elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
1496 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001497 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001498 fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
Steve Dower8fc89802015-04-12 00:26:27 -04001499 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001500 Py_END_ALLOW_THREADS
1501 if (fd < 0) {
1502 PyErr_SetFromErrno(PyExc_OSError);
1503 return -1;
1504 }
1505
1506#else
1507 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001508 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001509 fd = dup(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001510 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001511 Py_END_ALLOW_THREADS
1512 if (fd < 0) {
1513 PyErr_SetFromErrno(PyExc_OSError);
1514 return -1;
1515 }
1516
1517 if (_Py_set_inheritable(fd, 0, NULL) < 0) {
Steve Dower8fc89802015-04-12 00:26:27 -04001518 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001519 close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001520 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001521 return -1;
1522 }
1523#endif
1524 return fd;
1525}
1526
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001527#ifndef MS_WINDOWS
1528/* Get the blocking mode of the file descriptor.
1529 Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
1530 raise an exception and return -1 on error. */
1531int
1532_Py_get_blocking(int fd)
1533{
Steve Dower8fc89802015-04-12 00:26:27 -04001534 int flags;
1535 _Py_BEGIN_SUPPRESS_IPH
1536 flags = fcntl(fd, F_GETFL, 0);
1537 _Py_END_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001538 if (flags < 0) {
1539 PyErr_SetFromErrno(PyExc_OSError);
1540 return -1;
1541 }
1542
1543 return !(flags & O_NONBLOCK);
1544}
1545
1546/* Set the blocking mode of the specified file descriptor.
1547
1548 Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
1549 otherwise.
1550
1551 Return 0 on success, raise an exception and return -1 on error. */
1552int
1553_Py_set_blocking(int fd, int blocking)
1554{
1555#if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)
1556 int arg = !blocking;
1557 if (ioctl(fd, FIONBIO, &arg) < 0)
1558 goto error;
1559#else
1560 int flags, res;
1561
Steve Dower8fc89802015-04-12 00:26:27 -04001562 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001563 flags = fcntl(fd, F_GETFL, 0);
Steve Dower8fc89802015-04-12 00:26:27 -04001564 if (flags >= 0) {
1565 if (blocking)
1566 flags = flags & (~O_NONBLOCK);
1567 else
1568 flags = flags | O_NONBLOCK;
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001569
Steve Dower8fc89802015-04-12 00:26:27 -04001570 res = fcntl(fd, F_SETFL, flags);
1571 } else {
1572 res = -1;
1573 }
1574 _Py_END_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001575
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001576 if (res < 0)
1577 goto error;
1578#endif
1579 return 0;
1580
1581error:
1582 PyErr_SetFromErrno(PyExc_OSError);
1583 return -1;
1584}
1585#endif