blob: d610639688ea7a81e80f725ccc904cf942460d3a [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
Victor Stinnerdaf45552013-08-28 00:53:59 +020023#ifdef O_CLOEXEC
Victor Stinnerb034eee2013-09-07 10:36:04 +020024/* Does open() support the O_CLOEXEC flag? Possible values:
Victor Stinnerdaf45552013-08-28 00:53:59 +020025
26 -1: unknown
27 0: open() ignores O_CLOEXEC flag, ex: Linux kernel older than 2.6.23
28 1: open() supports O_CLOEXEC flag, close-on-exec is set
29
Victor Stinnera555cfc2015-03-18 00:22:14 +010030 The flag is used by _Py_open(), _Py_open_noraise(), io.FileIO
31 and os.open(). */
Victor Stinnerdaf45552013-08-28 00:53:59 +020032int _Py_open_cloexec_works = -1;
33#endif
34
Brett Cannonefb00c02012-02-29 18:31:31 -050035PyObject *
36_Py_device_encoding(int fd)
37{
Victor Stinner14b9b112013-06-25 00:37:25 +020038#if defined(MS_WINDOWS)
Brett Cannonefb00c02012-02-29 18:31:31 -050039 UINT cp;
40#endif
Steve Dower8fc89802015-04-12 00:26:27 -040041 int valid;
42 _Py_BEGIN_SUPPRESS_IPH
Steve Dower940f33a2016-09-08 11:21:54 -070043 valid = isatty(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040044 _Py_END_SUPPRESS_IPH
45 if (!valid)
Brett Cannonefb00c02012-02-29 18:31:31 -050046 Py_RETURN_NONE;
Steve Dower8fc89802015-04-12 00:26:27 -040047
Victor Stinner14b9b112013-06-25 00:37:25 +020048#if defined(MS_WINDOWS)
Brett Cannonefb00c02012-02-29 18:31:31 -050049 if (fd == 0)
50 cp = GetConsoleCP();
51 else if (fd == 1 || fd == 2)
52 cp = GetConsoleOutputCP();
53 else
54 cp = 0;
55 /* GetConsoleCP() and GetConsoleOutputCP() return 0 if the application
56 has no console */
57 if (cp != 0)
58 return PyUnicode_FromFormat("cp%u", (unsigned int)cp);
59#elif defined(CODESET)
60 {
61 char *codeset = nl_langinfo(CODESET);
62 if (codeset != NULL && codeset[0] != 0)
63 return PyUnicode_FromString(codeset);
64 }
65#endif
66 Py_RETURN_NONE;
67}
68
Victor Stinner7ed7aea2018-01-15 10:45:49 +010069#if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(MS_WINDOWS)
70
71#define USE_FORCE_ASCII
72
Victor Stinnerd45c7f82012-12-04 01:34:47 +010073extern int _Py_normalize_encoding(const char *, char *, size_t);
74
75/* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale.
76 On these operating systems, nl_langinfo(CODESET) announces an alias of the
77 ASCII encoding, whereas mbstowcs() and wcstombs() functions use the
78 ISO-8859-1 encoding. The problem is that os.fsencode() and os.fsdecode() use
79 locale.getpreferredencoding() codec. For example, if command line arguments
80 are decoded by mbstowcs() and encoded back by os.fsencode(), we get a
81 UnicodeEncodeError instead of retrieving the original byte string.
82
83 The workaround is enabled if setlocale(LC_CTYPE, NULL) returns "C",
84 nl_langinfo(CODESET) announces "ascii" (or an alias to ASCII), and at least
85 one byte in range 0x80-0xff can be decoded from the locale encoding. The
86 workaround is also enabled on error, for example if getting the locale
87 failed.
88
Philip Jenvey215c49a2013-01-15 13:24:12 -080089 Values of force_ascii:
Victor Stinnerd45c7f82012-12-04 01:34:47 +010090
Victor Stinnerf6a271a2014-08-01 12:28:48 +020091 1: the workaround is used: Py_EncodeLocale() uses
92 encode_ascii_surrogateescape() and Py_DecodeLocale() uses
Victor Stinner7ed7aea2018-01-15 10:45:49 +010093 decode_ascii()
Victor Stinnerf6a271a2014-08-01 12:28:48 +020094 0: the workaround is not used: Py_EncodeLocale() uses wcstombs() and
95 Py_DecodeLocale() uses mbstowcs()
Victor Stinnerd45c7f82012-12-04 01:34:47 +010096 -1: unknown, need to call check_force_ascii() to get the value
97*/
98static int force_ascii = -1;
99
100static int
101check_force_ascii(void)
102{
103 char *loc;
104#if defined(HAVE_LANGINFO_H) && defined(CODESET)
105 char *codeset, **alias;
Victor Stinner54de2b12016-09-09 23:11:52 -0700106 char encoding[20]; /* longest name: "iso_646.irv_1991\0" */
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100107 int is_ascii;
108 unsigned int i;
109 char* ascii_aliases[] = {
110 "ascii",
Victor Stinner54de2b12016-09-09 23:11:52 -0700111 /* Aliases from Lib/encodings/aliases.py */
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100112 "646",
Victor Stinner54de2b12016-09-09 23:11:52 -0700113 "ansi_x3.4_1968",
114 "ansi_x3.4_1986",
115 "ansi_x3_4_1968",
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100116 "cp367",
117 "csascii",
118 "ibm367",
Victor Stinner54de2b12016-09-09 23:11:52 -0700119 "iso646_us",
120 "iso_646.irv_1991",
121 "iso_ir_6",
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100122 "us",
Victor Stinner54de2b12016-09-09 23:11:52 -0700123 "us_ascii",
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100124 NULL
125 };
126#endif
127
128 loc = setlocale(LC_CTYPE, NULL);
129 if (loc == NULL)
130 goto error;
131 if (strcmp(loc, "C") != 0) {
132 /* the LC_CTYPE locale is different than C */
133 return 0;
134 }
135
136#if defined(HAVE_LANGINFO_H) && defined(CODESET)
137 codeset = nl_langinfo(CODESET);
138 if (!codeset || codeset[0] == '\0') {
139 /* CODESET is not set or empty */
140 goto error;
141 }
142 if (!_Py_normalize_encoding(codeset, encoding, sizeof(encoding)))
143 goto error;
144
145 is_ascii = 0;
146 for (alias=ascii_aliases; *alias != NULL; alias++) {
147 if (strcmp(encoding, *alias) == 0) {
148 is_ascii = 1;
149 break;
150 }
151 }
152 if (!is_ascii) {
153 /* nl_langinfo(CODESET) is not "ascii" or an alias of ASCII */
154 return 0;
155 }
156
157 for (i=0x80; i<0xff; i++) {
158 unsigned char ch;
159 wchar_t wch;
160 size_t res;
161
162 ch = (unsigned char)i;
163 res = mbstowcs(&wch, (char*)&ch, 1);
164 if (res != (size_t)-1) {
165 /* decoding a non-ASCII character from the locale encoding succeed:
166 the locale encoding is not ASCII, force ASCII */
167 return 1;
168 }
169 }
170 /* None of the bytes in the range 0x80-0xff can be decoded from the locale
171 encoding: the locale encoding is really ASCII */
172 return 0;
173#else
174 /* nl_langinfo(CODESET) is not available: always force ASCII */
175 return 1;
176#endif
177
178error:
Martin Panter46f50722016-05-26 05:35:26 +0000179 /* if an error occurred, force the ASCII encoding */
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100180 return 1;
181}
182
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100183static int
184encode_ascii(const wchar_t *text, char **str,
185 size_t *error_pos, const char **reason,
186 int raw_malloc, int surrogateescape)
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100187{
188 char *result = NULL, *out;
189 size_t len, i;
190 wchar_t ch;
191
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100192 len = wcslen(text);
193
Victor Stinner9bee3292017-12-21 16:49:13 +0100194 /* +1 for NULL byte */
Victor Stinner9dd76202017-12-21 16:20:32 +0100195 if (raw_malloc) {
196 result = PyMem_RawMalloc(len + 1);
197 }
198 else {
199 result = PyMem_Malloc(len + 1);
200 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100201 if (result == NULL) {
202 return -1;
203 }
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100204
205 out = result;
206 for (i=0; i<len; i++) {
207 ch = text[i];
208
209 if (ch <= 0x7f) {
210 /* ASCII character */
211 *out++ = (char)ch;
212 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100213 else if (surrogateescape && 0xdc80 <= ch && ch <= 0xdcff) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100214 /* UTF-8b surrogate */
215 *out++ = (char)(ch - 0xdc00);
216 }
217 else {
Victor Stinner9dd76202017-12-21 16:20:32 +0100218 if (raw_malloc) {
219 PyMem_RawFree(result);
220 }
221 else {
222 PyMem_Free(result);
223 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100224 if (error_pos != NULL) {
225 *error_pos = i;
226 }
227 if (reason) {
228 *reason = "encoding error";
229 }
230 return -2;
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100231 }
232 }
233 *out = '\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100234 *str = result;
235 return 0;
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100236}
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100237#endif /* !defined(__APPLE__) && !defined(__ANDROID__) && !defined(MS_WINDOWS) */
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100238
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100239
240#if !defined(HAVE_MBRTOWC) || defined(USE_FORCE_ASCII)
241static int
242decode_ascii(const char *arg, wchar_t **wstr, size_t *wlen,
243 const char **reason, int surrogateescape)
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100244{
245 wchar_t *res;
246 unsigned char *in;
247 wchar_t *out;
Benjamin Petersonf18bf6f2015-01-04 16:03:17 -0600248 size_t argsize = strlen(arg) + 1;
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100249
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100250 if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t)) {
251 return -1;
252 }
253 res = PyMem_RawMalloc(argsize * sizeof(wchar_t));
254 if (!res) {
255 return -1;
256 }
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100257
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100258 out = res;
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100259 for (in = (unsigned char*)arg; *in; in++) {
260 unsigned char ch = *in;
261 if (ch < 128) {
262 *out++ = ch;
263 }
264 else {
265 if (!surrogateescape) {
266 PyMem_RawFree(res);
267 if (wlen) {
268 *wlen = in - (unsigned char*)arg;
269 }
270 if (reason) {
271 *reason = "decoding error";
272 }
273 return -2;
274 }
275 *out++ = 0xdc00 + ch;
276 }
277 }
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100278 *out = 0;
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100279
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100280 if (wlen != NULL) {
281 *wlen = out - res;
282 }
283 *wstr = res;
284 return 0;
285}
286#endif /* !HAVE_MBRTOWC */
287
288static int
289decode_current_locale(const char* arg, wchar_t **wstr, size_t *wlen,
290 const char **reason, int surrogateescape)
Victor Stinner4e314432010-10-07 21:45:39 +0000291{
292 wchar_t *res;
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100293 size_t argsize;
Victor Stinner4e314432010-10-07 21:45:39 +0000294 size_t count;
Victor Stinner313f10c2013-05-07 23:48:56 +0200295#ifdef HAVE_MBRTOWC
Victor Stinner4e314432010-10-07 21:45:39 +0000296 unsigned char *in;
297 wchar_t *out;
Victor Stinner4e314432010-10-07 21:45:39 +0000298 mbstate_t mbs;
299#endif
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100300
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100301#ifdef HAVE_BROKEN_MBSTOWCS
302 /* Some platforms have a broken implementation of
303 * mbstowcs which does not count the characters that
304 * would result from conversion. Use an upper bound.
305 */
306 argsize = strlen(arg);
307#else
308 argsize = mbstowcs(NULL, arg, 0);
309#endif
Victor Stinner4e314432010-10-07 21:45:39 +0000310 if (argsize != (size_t)-1) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100311 if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
312 return -1;
313 }
314 res = (wchar_t *)PyMem_RawMalloc((argsize + 1) * sizeof(wchar_t));
315 if (!res) {
316 return -1;
317 }
318
319 count = mbstowcs(res, arg, argsize + 1);
Victor Stinner4e314432010-10-07 21:45:39 +0000320 if (count != (size_t)-1) {
321 wchar_t *tmp;
322 /* Only use the result if it contains no
323 surrogate characters. */
324 for (tmp = res; *tmp != 0 &&
Victor Stinner76df43d2012-10-30 01:42:39 +0100325 !Py_UNICODE_IS_SURROGATE(*tmp); tmp++)
Victor Stinner4e314432010-10-07 21:45:39 +0000326 ;
Victor Stinner168e1172010-10-16 23:16:16 +0000327 if (*tmp == 0) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100328 if (wlen != NULL) {
329 *wlen = count;
330 }
331 *wstr = res;
332 return 0;
Victor Stinner168e1172010-10-16 23:16:16 +0000333 }
Victor Stinner4e314432010-10-07 21:45:39 +0000334 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200335 PyMem_RawFree(res);
Victor Stinner4e314432010-10-07 21:45:39 +0000336 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100337
Victor Stinner4e314432010-10-07 21:45:39 +0000338 /* Conversion failed. Fall back to escaping with surrogateescape. */
339#ifdef HAVE_MBRTOWC
340 /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
341
342 /* Overallocate; as multi-byte characters are in the argument, the
343 actual output could use less memory. */
344 argsize = strlen(arg) + 1;
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100345 if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t)) {
346 return -1;
347 }
348 res = (wchar_t*)PyMem_RawMalloc(argsize * sizeof(wchar_t));
349 if (!res) {
350 return -1;
351 }
352
Victor Stinner4e314432010-10-07 21:45:39 +0000353 in = (unsigned char*)arg;
354 out = res;
355 memset(&mbs, 0, sizeof mbs);
356 while (argsize) {
357 size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100358 if (converted == 0) {
Victor Stinner4e314432010-10-07 21:45:39 +0000359 /* Reached end of string; null char stored. */
360 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100361 }
362
Victor Stinner4e314432010-10-07 21:45:39 +0000363 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 Stinner7ed7aea2018-01-15 10:45:49 +0100368 goto decode_error;
Victor Stinner4e314432010-10-07 21:45:39 +0000369 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100370
Victor Stinner4e314432010-10-07 21:45:39 +0000371 if (converted == (size_t)-1) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100372 if (!surrogateescape) {
373 goto decode_error;
374 }
375
Victor Stinner4e314432010-10-07 21:45:39 +0000376 /* Conversion error. Escape as UTF-8b, and start over
377 in the initial shift state. */
378 *out++ = 0xdc00 + *in++;
379 argsize--;
380 memset(&mbs, 0, sizeof mbs);
381 continue;
382 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100383
Victor Stinner76df43d2012-10-30 01:42:39 +0100384 if (Py_UNICODE_IS_SURROGATE(*out)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100385 if (!surrogateescape) {
386 goto decode_error;
387 }
388
Victor Stinner4e314432010-10-07 21:45:39 +0000389 /* Surrogate character. Escape the original
390 byte sequence with surrogateescape. */
391 argsize -= converted;
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100392 while (converted--) {
Victor Stinner4e314432010-10-07 21:45:39 +0000393 *out++ = 0xdc00 + *in++;
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100394 }
Victor Stinner4e314432010-10-07 21:45:39 +0000395 continue;
396 }
397 /* successfully converted some bytes */
398 in += converted;
399 argsize -= converted;
400 out++;
401 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100402 if (wlen != NULL) {
403 *wlen = out - res;
404 }
405 *wstr = res;
406 return 0;
407
408decode_error:
409 PyMem_RawFree(res);
410 if (wlen) {
411 *wlen = in - (unsigned char*)arg;
412 }
413 if (reason) {
414 *reason = "decoding error";
415 }
416 return -2;
Victor Stinnere2623772012-11-12 23:04:02 +0100417#else /* HAVE_MBRTOWC */
Victor Stinner4e314432010-10-07 21:45:39 +0000418 /* Cannot use C locale for escaping; manually escape as if charset
419 is ASCII (i.e. escape all bytes > 128. This will still roundtrip
420 correctly in the locale's charset, which must be an ASCII superset. */
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100421 return decode_ascii(arg, wstr, wlen, reason, surrogateescape);
Victor Stinnere2623772012-11-12 23:04:02 +0100422#endif /* HAVE_MBRTOWC */
Victor Stinner91106cd2017-12-13 12:29:09 +0100423}
424
425
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100426/* Decode a byte string from the locale encoding.
427
428 Use the strict error handler if 'surrogateescape' is zero. Use the
429 surrogateescape error handler if 'surrogateescape' is non-zero: undecodable
430 bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence
431 can be decoded as a surrogate character, escape the bytes using the
432 surrogateescape error handler instead of decoding them.
433
434 On sucess, return 0 and write the newly allocated wide character string into
435 *wstr (use PyMem_RawFree() to free the memory). If wlen is not NULL, write
436 the number of wide characters excluding the null character into *wlen.
437
438 On memory allocation failure, return -1.
439
440 On decoding error, return -2. If wlen is not NULL, write the start of
441 invalid byte sequence in the input string into *wlen. If reason is not NULL,
442 write the decoding error message into *reason.
443
444 Use the Py_EncodeLocaleEx() function to encode the character string back to
445 a byte string. */
446int
447_Py_DecodeLocaleEx(const char* arg, wchar_t **wstr, size_t *wlen,
448 const char **reason,
449 int current_locale, int surrogateescape)
Victor Stinner2cba6b82018-01-10 22:46:15 +0100450{
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100451 if (current_locale) {
Victor Stinner9089a262018-01-22 19:07:32 +0100452#ifdef __ANDROID__
453 return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
454 surrogateescape);
455#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100456 return decode_current_locale(arg, wstr, wlen, reason, surrogateescape);
Victor Stinner9089a262018-01-22 19:07:32 +0100457#endif
Victor Stinner2cba6b82018-01-10 22:46:15 +0100458 }
459
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100460#if defined(__APPLE__) || defined(__ANDROID__)
461 return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
462 surrogateescape);
463#else
464 if (Py_UTF8Mode == 1) {
465 return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
466 surrogateescape);
467 }
468
469#ifdef USE_FORCE_ASCII
470 if (force_ascii == -1) {
Victor Stinner2cba6b82018-01-10 22:46:15 +0100471 force_ascii = check_force_ascii();
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100472 }
Victor Stinner2cba6b82018-01-10 22:46:15 +0100473
474 if (force_ascii) {
475 /* force ASCII encoding to workaround mbstowcs() issue */
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100476 return decode_ascii(arg, wstr, wlen, reason, surrogateescape);
Victor Stinner2cba6b82018-01-10 22:46:15 +0100477 }
478#endif
479
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100480 return decode_current_locale(arg, wstr, wlen, reason, surrogateescape);
Victor Stinner2cba6b82018-01-10 22:46:15 +0100481#endif /* __APPLE__ or __ANDROID__ */
482}
483
484
Victor Stinner91106cd2017-12-13 12:29:09 +0100485/* Decode a byte string from the locale encoding with the
486 surrogateescape error handler: undecodable bytes are decoded as characters
487 in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate
488 character, escape the bytes using the surrogateescape error handler instead
489 of decoding them.
490
491 Return a pointer to a newly allocated wide character string, use
492 PyMem_RawFree() to free the memory. If size is not NULL, write the number of
493 wide characters excluding the null character into *size
494
495 Return NULL on decoding error or memory allocation error. If *size* is not
496 NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on
497 decoding error.
498
499 Decoding errors should never happen, unless there is a bug in the C
500 library.
501
502 Use the Py_EncodeLocale() function to encode the character string back to a
503 byte string. */
504wchar_t*
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100505Py_DecodeLocale(const char* arg, size_t *wlen)
Victor Stinner91106cd2017-12-13 12:29:09 +0100506{
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100507 wchar_t *wstr;
508 int res = _Py_DecodeLocaleEx(arg, &wstr, wlen, NULL, 0, 1);
509 if (res != 0) {
510 if (wlen != NULL) {
511 *wlen = (size_t)res;
512 }
513 return NULL;
514 }
515 return wstr;
Victor Stinner2cba6b82018-01-10 22:46:15 +0100516}
Victor Stinner91106cd2017-12-13 12:29:09 +0100517
Victor Stinner91106cd2017-12-13 12:29:09 +0100518
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100519static int
520encode_current_locale(const wchar_t *text, char **str,
521 size_t *error_pos, const char **reason,
522 int raw_malloc, int surrogateescape)
Victor Stinner91106cd2017-12-13 12:29:09 +0100523{
Victor Stinner4e314432010-10-07 21:45:39 +0000524 const size_t len = wcslen(text);
525 char *result = NULL, *bytes = NULL;
526 size_t i, size, converted;
527 wchar_t c, buf[2];
528
529 /* The function works in two steps:
530 1. compute the length of the output buffer in bytes (size)
531 2. outputs the bytes */
532 size = 0;
533 buf[1] = 0;
534 while (1) {
535 for (i=0; i < len; i++) {
536 c = text[i];
537 if (c >= 0xdc80 && c <= 0xdcff) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100538 if (!surrogateescape) {
539 goto encode_error;
540 }
Victor Stinner4e314432010-10-07 21:45:39 +0000541 /* UTF-8b surrogate */
542 if (bytes != NULL) {
543 *bytes++ = c - 0xdc00;
544 size--;
545 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100546 else {
Victor Stinner4e314432010-10-07 21:45:39 +0000547 size++;
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100548 }
Victor Stinner4e314432010-10-07 21:45:39 +0000549 continue;
550 }
551 else {
552 buf[0] = c;
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100553 if (bytes != NULL) {
Victor Stinner4e314432010-10-07 21:45:39 +0000554 converted = wcstombs(bytes, buf, size);
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100555 }
556 else {
Victor Stinner4e314432010-10-07 21:45:39 +0000557 converted = wcstombs(NULL, buf, 0);
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100558 }
Victor Stinner4e314432010-10-07 21:45:39 +0000559 if (converted == (size_t)-1) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100560 goto encode_error;
Victor Stinner4e314432010-10-07 21:45:39 +0000561 }
562 if (bytes != NULL) {
563 bytes += converted;
564 size -= converted;
565 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100566 else {
Victor Stinner4e314432010-10-07 21:45:39 +0000567 size += converted;
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100568 }
Victor Stinner4e314432010-10-07 21:45:39 +0000569 }
570 }
571 if (result != NULL) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100572 *bytes = '\0';
Victor Stinner4e314432010-10-07 21:45:39 +0000573 break;
574 }
575
576 size += 1; /* nul byte at the end */
Victor Stinner9dd76202017-12-21 16:20:32 +0100577 if (raw_malloc) {
578 result = PyMem_RawMalloc(size);
579 }
580 else {
581 result = PyMem_Malloc(size);
582 }
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100583 if (result == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100584 return -1;
Victor Stinner0d92c4f2012-11-12 23:32:21 +0100585 }
Victor Stinner4e314432010-10-07 21:45:39 +0000586 bytes = result;
587 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100588 *str = result;
589 return 0;
590
591encode_error:
592 if (raw_malloc) {
593 PyMem_RawFree(result);
594 }
595 else {
596 PyMem_Free(result);
597 }
598 if (error_pos != NULL) {
599 *error_pos = i;
600 }
601 if (reason) {
602 *reason = "encoding error";
603 }
604 return -2;
Victor Stinner91106cd2017-12-13 12:29:09 +0100605}
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100606
607static int
608encode_locale_ex(const wchar_t *text, char **str, size_t *error_pos,
609 const char **reason,
610 int raw_malloc, int current_locale, int surrogateescape)
611{
612 if (current_locale) {
Victor Stinner9089a262018-01-22 19:07:32 +0100613#ifdef __ANDROID__
614 return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
615 raw_malloc, surrogateescape);
616#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100617 return encode_current_locale(text, str, error_pos, reason,
618 raw_malloc, surrogateescape);
Victor Stinner9089a262018-01-22 19:07:32 +0100619#endif
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100620 }
621
622#if defined(__APPLE__) || defined(__ANDROID__)
623 return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
624 raw_malloc, surrogateescape);
625#else /* __APPLE__ */
626 if (Py_UTF8Mode == 1) {
627 return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
628 raw_malloc, surrogateescape);
629 }
630
631#ifdef USE_FORCE_ASCII
632 if (force_ascii == -1) {
633 force_ascii = check_force_ascii();
634 }
635
636 if (force_ascii) {
637 return encode_ascii(text, str, error_pos, reason,
638 raw_malloc, surrogateescape);
639 }
Victor Stinnerd2b02312017-12-15 23:06:17 +0100640#endif
Victor Stinner91106cd2017-12-13 12:29:09 +0100641
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100642 return encode_current_locale(text, str, error_pos, reason,
643 raw_malloc, surrogateescape);
644#endif /* __APPLE__ or __ANDROID__ */
645}
646
Victor Stinner9dd76202017-12-21 16:20:32 +0100647static char*
Victor Stinner2cba6b82018-01-10 22:46:15 +0100648encode_locale(const wchar_t *text, size_t *error_pos,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100649 int raw_malloc, int current_locale)
Victor Stinner9dd76202017-12-21 16:20:32 +0100650{
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100651 char *str;
652 int res = encode_locale_ex(text, &str, error_pos, NULL,
653 raw_malloc, current_locale, 1);
654 if (res != -2 && error_pos) {
655 *error_pos = (size_t)-1;
Victor Stinner9dd76202017-12-21 16:20:32 +0100656 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100657 if (res != 0) {
658 return NULL;
659 }
660 return str;
Victor Stinner9dd76202017-12-21 16:20:32 +0100661}
662
Victor Stinner91106cd2017-12-13 12:29:09 +0100663/* Encode a wide character string to the locale encoding with the
664 surrogateescape error handler: surrogate characters in the range
665 U+DC80..U+DCFF are converted to bytes 0x80..0xFF.
666
667 Return a pointer to a newly allocated byte string, use PyMem_Free() to free
668 the memory. Return NULL on encoding or memory allocation error.
669
670 If error_pos is not NULL, *error_pos is set to (size_t)-1 on success, or set
671 to the index of the invalid character on encoding error.
672
673 Use the Py_DecodeLocale() function to decode the bytes string back to a wide
674 character string. */
675char*
676Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
677{
Victor Stinner2cba6b82018-01-10 22:46:15 +0100678 return encode_locale(text, error_pos, 0, 0);
Victor Stinner9dd76202017-12-21 16:20:32 +0100679}
Victor Stinner91106cd2017-12-13 12:29:09 +0100680
Victor Stinner91106cd2017-12-13 12:29:09 +0100681
Victor Stinner9dd76202017-12-21 16:20:32 +0100682/* Similar to Py_EncodeLocale(), but result must be freed by PyMem_RawFree()
683 instead of PyMem_Free(). */
684char*
685_Py_EncodeLocaleRaw(const wchar_t *text, size_t *error_pos)
686{
Victor Stinner2cba6b82018-01-10 22:46:15 +0100687 return encode_locale(text, error_pos, 1, 0);
688}
689
690
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100691int
692_Py_EncodeLocaleEx(const wchar_t *text, char **str,
693 size_t *error_pos, const char **reason,
694 int current_locale, int surrogateescape)
Victor Stinner2cba6b82018-01-10 22:46:15 +0100695{
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100696 return encode_locale_ex(text, str, error_pos, reason, 1,
697 current_locale, surrogateescape);
Victor Stinner4e314432010-10-07 21:45:39 +0000698}
699
Victor Stinner6672d0c2010-10-07 22:53:43 +0000700
Steve Dowerf2f373f2015-02-21 08:44:05 -0800701#ifdef MS_WINDOWS
702static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
703
704static void
705FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
706{
707 /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
708 /* Cannot simply cast and dereference in_ptr,
709 since it might not be aligned properly */
710 __int64 in;
711 memcpy(&in, in_ptr, sizeof(in));
712 *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
713 *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
714}
715
716void
Steve Dowerbf1f3762015-02-21 15:26:02 -0800717_Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
Steve Dowerf2f373f2015-02-21 08:44:05 -0800718{
719 /* XXX endianness */
720 __int64 out;
721 out = time_in + secs_between_epochs;
722 out = out * 10000000 + nsec_in / 100;
723 memcpy(out_ptr, &out, sizeof(out));
724}
725
726/* Below, we *know* that ugo+r is 0444 */
727#if _S_IREAD != 0400
728#error Unsupported C library
729#endif
730static int
731attributes_to_mode(DWORD attr)
732{
733 int m = 0;
734 if (attr & FILE_ATTRIBUTE_DIRECTORY)
735 m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
736 else
737 m |= _S_IFREG;
738 if (attr & FILE_ATTRIBUTE_READONLY)
739 m |= 0444;
740 else
741 m |= 0666;
742 return m;
743}
744
Steve Dowerbf1f3762015-02-21 15:26:02 -0800745void
Victor Stinnere134a7f2015-03-30 10:09:31 +0200746_Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
747 struct _Py_stat_struct *result)
Steve Dowerf2f373f2015-02-21 08:44:05 -0800748{
749 memset(result, 0, sizeof(*result));
750 result->st_mode = attributes_to_mode(info->dwFileAttributes);
751 result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
752 result->st_dev = info->dwVolumeSerialNumber;
753 result->st_rdev = result->st_dev;
754 FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
755 FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
756 FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
757 result->st_nlink = info->nNumberOfLinks;
Victor Stinner0f6d7332017-03-09 17:34:28 +0100758 result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800759 if (reparse_tag == IO_REPARSE_TAG_SYMLINK) {
760 /* first clear the S_IFMT bits */
761 result->st_mode ^= (result->st_mode & S_IFMT);
762 /* now set the bits that make this a symlink */
763 result->st_mode |= S_IFLNK;
764 }
765 result->st_file_attributes = info->dwFileAttributes;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800766}
767#endif
768
769/* Return information about a file.
770
771 On POSIX, use fstat().
772
773 On Windows, use GetFileType() and GetFileInformationByHandle() which support
Victor Stinner8c663fd2017-11-08 14:44:44 -0800774 files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
775 than 2 GiB because the file size type is a signed 32-bit integer: see issue
Steve Dowerf2f373f2015-02-21 08:44:05 -0800776 #23152.
Victor Stinnere134a7f2015-03-30 10:09:31 +0200777
778 On Windows, set the last Windows error and return nonzero on error. On
779 POSIX, set errno and return nonzero on error. Fill status and return 0 on
780 success. */
Steve Dowerf2f373f2015-02-21 08:44:05 -0800781int
Victor Stinnere134a7f2015-03-30 10:09:31 +0200782_Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
Steve Dowerf2f373f2015-02-21 08:44:05 -0800783{
784#ifdef MS_WINDOWS
785 BY_HANDLE_FILE_INFORMATION info;
786 HANDLE h;
787 int type;
788
Steve Dower940f33a2016-09-08 11:21:54 -0700789 _Py_BEGIN_SUPPRESS_IPH
790 h = (HANDLE)_get_osfhandle(fd);
791 _Py_END_SUPPRESS_IPH
Steve Dowerf2f373f2015-02-21 08:44:05 -0800792
793 if (h == INVALID_HANDLE_VALUE) {
Steve Dower8fc89802015-04-12 00:26:27 -0400794 /* errno is already set by _get_osfhandle, but we also set
795 the Win32 error for callers who expect that */
Steve Dower8acde7d2015-03-07 18:14:07 -0800796 SetLastError(ERROR_INVALID_HANDLE);
Steve Dowerf2f373f2015-02-21 08:44:05 -0800797 return -1;
798 }
Victor Stinnere134a7f2015-03-30 10:09:31 +0200799 memset(status, 0, sizeof(*status));
Steve Dowerf2f373f2015-02-21 08:44:05 -0800800
801 type = GetFileType(h);
802 if (type == FILE_TYPE_UNKNOWN) {
803 DWORD error = GetLastError();
Steve Dower8fc89802015-04-12 00:26:27 -0400804 if (error != 0) {
805 errno = winerror_to_errno(error);
Steve Dowerf2f373f2015-02-21 08:44:05 -0800806 return -1;
Steve Dower8fc89802015-04-12 00:26:27 -0400807 }
Steve Dowerf2f373f2015-02-21 08:44:05 -0800808 /* else: valid but unknown file */
809 }
810
811 if (type != FILE_TYPE_DISK) {
812 if (type == FILE_TYPE_CHAR)
Victor Stinnere134a7f2015-03-30 10:09:31 +0200813 status->st_mode = _S_IFCHR;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800814 else if (type == FILE_TYPE_PIPE)
Victor Stinnere134a7f2015-03-30 10:09:31 +0200815 status->st_mode = _S_IFIFO;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800816 return 0;
817 }
818
819 if (!GetFileInformationByHandle(h, &info)) {
Steve Dower8fc89802015-04-12 00:26:27 -0400820 /* The Win32 error is already set, but we also set errno for
821 callers who expect it */
822 errno = winerror_to_errno(GetLastError());
Steve Dowerf2f373f2015-02-21 08:44:05 -0800823 return -1;
824 }
825
Victor Stinnere134a7f2015-03-30 10:09:31 +0200826 _Py_attribute_data_to_stat(&info, 0, status);
Steve Dowerf2f373f2015-02-21 08:44:05 -0800827 /* specific to fstat() */
Victor Stinner0f6d7332017-03-09 17:34:28 +0100828 status->st_ino = (((uint64_t)info.nFileIndexHigh) << 32) + info.nFileIndexLow;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800829 return 0;
830#else
Victor Stinnere134a7f2015-03-30 10:09:31 +0200831 return fstat(fd, status);
Steve Dowerf2f373f2015-02-21 08:44:05 -0800832#endif
833}
Steve Dowerf2f373f2015-02-21 08:44:05 -0800834
Victor Stinnere134a7f2015-03-30 10:09:31 +0200835/* Return information about a file.
836
837 On POSIX, use fstat().
838
839 On Windows, use GetFileType() and GetFileInformationByHandle() which support
Victor Stinner8c663fd2017-11-08 14:44:44 -0800840 files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
841 than 2 GiB because the file size type is a signed 32-bit integer: see issue
Victor Stinnere134a7f2015-03-30 10:09:31 +0200842 #23152.
843
844 Raise an exception and return -1 on error. On Windows, set the last Windows
845 error on error. On POSIX, set errno on error. Fill status and return 0 on
846 success.
847
Victor Stinner6f4fae82015-04-01 18:34:32 +0200848 Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
849 to call fstat(). The caller must hold the GIL. */
Victor Stinnere134a7f2015-03-30 10:09:31 +0200850int
851_Py_fstat(int fd, struct _Py_stat_struct *status)
852{
853 int res;
854
Victor Stinner8a1be612016-03-14 22:07:55 +0100855 assert(PyGILState_Check());
Victor Stinner8a1be612016-03-14 22:07:55 +0100856
Victor Stinnere134a7f2015-03-30 10:09:31 +0200857 Py_BEGIN_ALLOW_THREADS
858 res = _Py_fstat_noraise(fd, status);
859 Py_END_ALLOW_THREADS
860
861 if (res != 0) {
862#ifdef MS_WINDOWS
863 PyErr_SetFromWindowsErr(0);
864#else
865 PyErr_SetFromErrno(PyExc_OSError);
866#endif
867 return -1;
868 }
869 return 0;
870}
Steve Dowerf2f373f2015-02-21 08:44:05 -0800871
Victor Stinner6672d0c2010-10-07 22:53:43 +0000872/* Call _wstat() on Windows, or encode the path to the filesystem encoding and
873 call stat() otherwise. Only fill st_mode attribute on Windows.
874
Victor Stinnerbd0850b2011-12-18 20:47:30 +0100875 Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
876 raised. */
Victor Stinner4e314432010-10-07 21:45:39 +0000877
878int
Victor Stinnera4a75952010-10-07 22:23:10 +0000879_Py_stat(PyObject *path, struct stat *statbuf)
Victor Stinner4e314432010-10-07 21:45:39 +0000880{
881#ifdef MS_WINDOWS
Victor Stinner4e314432010-10-07 21:45:39 +0000882 int err;
883 struct _stat wstatbuf;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300884 const wchar_t *wpath;
Victor Stinner4e314432010-10-07 21:45:39 +0000885
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300886 wpath = _PyUnicode_AsUnicode(path);
Victor Stinneree587ea2011-11-17 00:51:38 +0100887 if (wpath == NULL)
Victor Stinnerbd0850b2011-12-18 20:47:30 +0100888 return -2;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300889
Victor Stinneree587ea2011-11-17 00:51:38 +0100890 err = _wstat(wpath, &wstatbuf);
Victor Stinner4e314432010-10-07 21:45:39 +0000891 if (!err)
892 statbuf->st_mode = wstatbuf.st_mode;
893 return err;
894#else
895 int ret;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300896 PyObject *bytes;
897 char *cpath;
898
899 bytes = PyUnicode_EncodeFSDefault(path);
Victor Stinner4e314432010-10-07 21:45:39 +0000900 if (bytes == NULL)
Victor Stinnerbd0850b2011-12-18 20:47:30 +0100901 return -2;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300902
903 /* check for embedded null bytes */
904 if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
905 Py_DECREF(bytes);
906 return -2;
907 }
908
909 ret = stat(cpath, statbuf);
Victor Stinner4e314432010-10-07 21:45:39 +0000910 Py_DECREF(bytes);
911 return ret;
912#endif
913}
914
Victor Stinnerd45c7f82012-12-04 01:34:47 +0100915
Antoine Pitrou409b5382013-10-12 22:41:17 +0200916static int
Victor Stinnerdaf45552013-08-28 00:53:59 +0200917get_inheritable(int fd, int raise)
918{
919#ifdef MS_WINDOWS
920 HANDLE handle;
921 DWORD flags;
Victor Stinner6672d0c2010-10-07 22:53:43 +0000922
Steve Dower8fc89802015-04-12 00:26:27 -0400923 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +0200924 handle = (HANDLE)_get_osfhandle(fd);
Steve Dower8fc89802015-04-12 00:26:27 -0400925 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +0200926 if (handle == INVALID_HANDLE_VALUE) {
927 if (raise)
Steve Dower41e72442015-03-14 11:38:27 -0700928 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200929 return -1;
930 }
931
932 if (!GetHandleInformation(handle, &flags)) {
933 if (raise)
934 PyErr_SetFromWindowsErr(0);
935 return -1;
936 }
937
938 return (flags & HANDLE_FLAG_INHERIT);
939#else
940 int flags;
941
942 flags = fcntl(fd, F_GETFD, 0);
943 if (flags == -1) {
944 if (raise)
945 PyErr_SetFromErrno(PyExc_OSError);
946 return -1;
947 }
948 return !(flags & FD_CLOEXEC);
949#endif
950}
951
952/* Get the inheritable flag of the specified file descriptor.
Victor Stinnerb034eee2013-09-07 10:36:04 +0200953 Return 1 if the file descriptor can be inherited, 0 if it cannot,
Victor Stinnerdaf45552013-08-28 00:53:59 +0200954 raise an exception and return -1 on error. */
955int
956_Py_get_inheritable(int fd)
957{
958 return get_inheritable(fd, 1);
959}
960
961static int
962set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
963{
964#ifdef MS_WINDOWS
965 HANDLE handle;
966 DWORD flags;
Victor Stinner282124b2014-09-02 11:41:04 +0200967#else
968#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
969 static int ioctl_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200970 int request;
971 int err;
Victor Stinner282124b2014-09-02 11:41:04 +0200972#endif
Victor Stinnera858bbd2016-04-17 16:51:52 +0200973 int flags, new_flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200974 int res;
975#endif
976
977 /* atomic_flag_works can only be used to make the file descriptor
978 non-inheritable */
979 assert(!(atomic_flag_works != NULL && inheritable));
980
981 if (atomic_flag_works != NULL && !inheritable) {
982 if (*atomic_flag_works == -1) {
Steve Dower41e72442015-03-14 11:38:27 -0700983 int isInheritable = get_inheritable(fd, raise);
984 if (isInheritable == -1)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200985 return -1;
Steve Dower41e72442015-03-14 11:38:27 -0700986 *atomic_flag_works = !isInheritable;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200987 }
988
989 if (*atomic_flag_works)
990 return 0;
991 }
992
993#ifdef MS_WINDOWS
Steve Dower8fc89802015-04-12 00:26:27 -0400994 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +0200995 handle = (HANDLE)_get_osfhandle(fd);
Steve Dower8fc89802015-04-12 00:26:27 -0400996 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +0200997 if (handle == INVALID_HANDLE_VALUE) {
998 if (raise)
Steve Dower41e72442015-03-14 11:38:27 -0700999 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001000 return -1;
1001 }
1002
1003 if (inheritable)
1004 flags = HANDLE_FLAG_INHERIT;
1005 else
1006 flags = 0;
1007 if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
1008 if (raise)
1009 PyErr_SetFromWindowsErr(0);
1010 return -1;
1011 }
1012 return 0;
1013
Victor Stinnerdaf45552013-08-28 00:53:59 +02001014#else
Victor Stinner282124b2014-09-02 11:41:04 +02001015
1016#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
1017 if (ioctl_works != 0) {
1018 /* fast-path: ioctl() only requires one syscall */
1019 if (inheritable)
1020 request = FIONCLEX;
1021 else
1022 request = FIOCLEX;
1023 err = ioctl(fd, request, NULL);
1024 if (!err) {
1025 ioctl_works = 1;
1026 return 0;
1027 }
1028
Victor Stinner3116cc42016-05-19 16:46:18 +02001029 if (errno != ENOTTY && errno != EACCES) {
Victor Stinner282124b2014-09-02 11:41:04 +02001030 if (raise)
1031 PyErr_SetFromErrno(PyExc_OSError);
1032 return -1;
1033 }
1034 else {
1035 /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
1036 device". The ioctl is declared but not supported by the kernel.
1037 Remember that ioctl() doesn't work. It is the case on
Victor Stinner3116cc42016-05-19 16:46:18 +02001038 Illumos-based OS for example.
1039
1040 Issue #27057: When SELinux policy disallows ioctl it will fail
1041 with EACCES. While FIOCLEX is safe operation it may be
1042 unavailable because ioctl was denied altogether.
1043 This can be the case on Android. */
Victor Stinner282124b2014-09-02 11:41:04 +02001044 ioctl_works = 0;
1045 }
1046 /* fallback to fcntl() if ioctl() does not work */
1047 }
1048#endif
1049
1050 /* slow-path: fcntl() requires two syscalls */
Victor Stinnerdaf45552013-08-28 00:53:59 +02001051 flags = fcntl(fd, F_GETFD);
1052 if (flags < 0) {
1053 if (raise)
1054 PyErr_SetFromErrno(PyExc_OSError);
1055 return -1;
1056 }
1057
Victor Stinnera858bbd2016-04-17 16:51:52 +02001058 if (inheritable) {
1059 new_flags = flags & ~FD_CLOEXEC;
1060 }
1061 else {
1062 new_flags = flags | FD_CLOEXEC;
1063 }
1064
1065 if (new_flags == flags) {
1066 /* FD_CLOEXEC flag already set/cleared: nothing to do */
1067 return 0;
1068 }
1069
Xavier de Gayeec5d3cd2016-11-19 16:19:29 +01001070 res = fcntl(fd, F_SETFD, new_flags);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001071 if (res < 0) {
1072 if (raise)
1073 PyErr_SetFromErrno(PyExc_OSError);
1074 return -1;
1075 }
1076 return 0;
1077#endif
1078}
1079
1080/* Make the file descriptor non-inheritable.
Victor Stinnerb034eee2013-09-07 10:36:04 +02001081 Return 0 on success, set errno and return -1 on error. */
Victor Stinnerdaf45552013-08-28 00:53:59 +02001082static int
1083make_non_inheritable(int fd)
1084{
1085 return set_inheritable(fd, 0, 0, NULL);
1086}
1087
1088/* Set the inheritable flag of the specified file descriptor.
1089 On success: return 0, on error: raise an exception if raise is nonzero
1090 and return -1.
1091
1092 If atomic_flag_works is not NULL:
1093
1094 * if *atomic_flag_works==-1, check if the inheritable is set on the file
1095 descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
1096 set the inheritable flag
1097 * if *atomic_flag_works==1: do nothing
1098 * if *atomic_flag_works==0: set inheritable flag to False
1099
1100 Set atomic_flag_works to NULL if no atomic flag was used to create the
1101 file descriptor.
1102
1103 atomic_flag_works can only be used to make a file descriptor
1104 non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
1105int
1106_Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
1107{
1108 return set_inheritable(fd, inheritable, 1, atomic_flag_works);
1109}
1110
Victor Stinnera555cfc2015-03-18 00:22:14 +01001111static int
1112_Py_open_impl(const char *pathname, int flags, int gil_held)
Victor Stinnerdaf45552013-08-28 00:53:59 +02001113{
1114 int fd;
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001115 int async_err = 0;
Victor Stinnera555cfc2015-03-18 00:22:14 +01001116#ifndef MS_WINDOWS
Victor Stinnerdaf45552013-08-28 00:53:59 +02001117 int *atomic_flag_works;
Victor Stinnera555cfc2015-03-18 00:22:14 +01001118#endif
1119
1120#ifdef MS_WINDOWS
1121 flags |= O_NOINHERIT;
1122#elif defined(O_CLOEXEC)
Victor Stinnerdaf45552013-08-28 00:53:59 +02001123 atomic_flag_works = &_Py_open_cloexec_works;
1124 flags |= O_CLOEXEC;
1125#else
1126 atomic_flag_works = NULL;
1127#endif
Victor Stinnerdaf45552013-08-28 00:53:59 +02001128
Victor Stinnera555cfc2015-03-18 00:22:14 +01001129 if (gil_held) {
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001130 do {
1131 Py_BEGIN_ALLOW_THREADS
1132 fd = open(pathname, flags);
1133 Py_END_ALLOW_THREADS
1134 } while (fd < 0
1135 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1136 if (async_err)
1137 return -1;
Victor Stinnera555cfc2015-03-18 00:22:14 +01001138 if (fd < 0) {
1139 PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname);
1140 return -1;
1141 }
1142 }
1143 else {
1144 fd = open(pathname, flags);
1145 if (fd < 0)
1146 return -1;
1147 }
1148
1149#ifndef MS_WINDOWS
1150 if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
Victor Stinnerdaf45552013-08-28 00:53:59 +02001151 close(fd);
1152 return -1;
1153 }
Victor Stinnera555cfc2015-03-18 00:22:14 +01001154#endif
1155
Victor Stinnerdaf45552013-08-28 00:53:59 +02001156 return fd;
1157}
1158
Victor Stinnera555cfc2015-03-18 00:22:14 +01001159/* Open a file with the specified flags (wrapper to open() function).
1160 Return a file descriptor on success. Raise an exception and return -1 on
1161 error.
1162
1163 The file descriptor is created non-inheritable.
1164
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001165 When interrupted by a signal (open() fails with EINTR), retry the syscall,
1166 except if the Python signal handler raises an exception.
1167
Victor Stinner6f4fae82015-04-01 18:34:32 +02001168 Release the GIL to call open(). The caller must hold the GIL. */
Victor Stinnera555cfc2015-03-18 00:22:14 +01001169int
1170_Py_open(const char *pathname, int flags)
1171{
1172 /* _Py_open() must be called with the GIL held. */
1173 assert(PyGILState_Check());
1174 return _Py_open_impl(pathname, flags, 1);
1175}
1176
1177/* Open a file with the specified flags (wrapper to open() function).
1178 Return a file descriptor on success. Set errno and return -1 on error.
1179
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001180 The file descriptor is created non-inheritable.
1181
1182 If interrupted by a signal, fail with EINTR. */
Victor Stinnera555cfc2015-03-18 00:22:14 +01001183int
1184_Py_open_noraise(const char *pathname, int flags)
1185{
1186 return _Py_open_impl(pathname, flags, 0);
1187}
1188
Victor Stinnerdaf45552013-08-28 00:53:59 +02001189/* Open a file. Use _wfopen() on Windows, encode the path to the locale
Victor Stinnere42ccd22015-03-18 01:39:23 +01001190 encoding and use fopen() otherwise.
1191
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001192 The file descriptor is created non-inheritable.
1193
1194 If interrupted by a signal, fail with EINTR. */
Victor Stinner4e314432010-10-07 21:45:39 +00001195FILE *
1196_Py_wfopen(const wchar_t *path, const wchar_t *mode)
1197{
Victor Stinner4e314432010-10-07 21:45:39 +00001198 FILE *f;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001199#ifndef MS_WINDOWS
Victor Stinner4e314432010-10-07 21:45:39 +00001200 char *cpath;
1201 char cmode[10];
1202 size_t r;
1203 r = wcstombs(cmode, mode, 10);
1204 if (r == (size_t)-1 || r >= 10) {
1205 errno = EINVAL;
1206 return NULL;
1207 }
Victor Stinner9dd76202017-12-21 16:20:32 +01001208 cpath = _Py_EncodeLocaleRaw(path, NULL);
1209 if (cpath == NULL) {
Victor Stinner4e314432010-10-07 21:45:39 +00001210 return NULL;
Victor Stinner9dd76202017-12-21 16:20:32 +01001211 }
Victor Stinner4e314432010-10-07 21:45:39 +00001212 f = fopen(cpath, cmode);
Victor Stinner9dd76202017-12-21 16:20:32 +01001213 PyMem_RawFree(cpath);
Victor Stinner4e314432010-10-07 21:45:39 +00001214#else
Victor Stinnerdaf45552013-08-28 00:53:59 +02001215 f = _wfopen(path, mode);
Victor Stinner4e314432010-10-07 21:45:39 +00001216#endif
Victor Stinnerdaf45552013-08-28 00:53:59 +02001217 if (f == NULL)
1218 return NULL;
1219 if (make_non_inheritable(fileno(f)) < 0) {
1220 fclose(f);
1221 return NULL;
1222 }
1223 return f;
Victor Stinner4e314432010-10-07 21:45:39 +00001224}
1225
Victor Stinnere42ccd22015-03-18 01:39:23 +01001226/* Wrapper to fopen().
1227
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001228 The file descriptor is created non-inheritable.
1229
1230 If interrupted by a signal, fail with EINTR. */
Victor Stinnerdaf45552013-08-28 00:53:59 +02001231FILE*
1232_Py_fopen(const char *pathname, const char *mode)
1233{
1234 FILE *f = fopen(pathname, mode);
1235 if (f == NULL)
1236 return NULL;
1237 if (make_non_inheritable(fileno(f)) < 0) {
1238 fclose(f);
1239 return NULL;
1240 }
1241 return f;
1242}
1243
1244/* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
Victor Stinnere42ccd22015-03-18 01:39:23 +01001245 encoding and call fopen() otherwise.
Victor Stinner6672d0c2010-10-07 22:53:43 +00001246
Victor Stinnere42ccd22015-03-18 01:39:23 +01001247 Return the new file object on success. Raise an exception and return NULL
1248 on error.
1249
1250 The file descriptor is created non-inheritable.
1251
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001252 When interrupted by a signal (open() fails with EINTR), retry the syscall,
1253 except if the Python signal handler raises an exception.
1254
Victor Stinner6f4fae82015-04-01 18:34:32 +02001255 Release the GIL to call _wfopen() or fopen(). The caller must hold
1256 the GIL. */
Victor Stinner4e314432010-10-07 21:45:39 +00001257FILE*
Victor Stinnerdaf45552013-08-28 00:53:59 +02001258_Py_fopen_obj(PyObject *path, const char *mode)
Victor Stinner4e314432010-10-07 21:45:39 +00001259{
Victor Stinnerdaf45552013-08-28 00:53:59 +02001260 FILE *f;
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001261 int async_err = 0;
Victor Stinner4e314432010-10-07 21:45:39 +00001262#ifdef MS_WINDOWS
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03001263 const wchar_t *wpath;
Victor Stinner4e314432010-10-07 21:45:39 +00001264 wchar_t wmode[10];
1265 int usize;
Victor Stinner4e314432010-10-07 21:45:39 +00001266
Victor Stinnere42ccd22015-03-18 01:39:23 +01001267 assert(PyGILState_Check());
1268
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001269 if (!PyUnicode_Check(path)) {
1270 PyErr_Format(PyExc_TypeError,
1271 "str file path expected under Windows, got %R",
1272 Py_TYPE(path));
1273 return NULL;
1274 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03001275 wpath = _PyUnicode_AsUnicode(path);
Victor Stinneree587ea2011-11-17 00:51:38 +01001276 if (wpath == NULL)
1277 return NULL;
1278
Victor Stinner4e314432010-10-07 21:45:39 +00001279 usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
Victor Stinnere42ccd22015-03-18 01:39:23 +01001280 if (usize == 0) {
1281 PyErr_SetFromWindowsErr(0);
Victor Stinner4e314432010-10-07 21:45:39 +00001282 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01001283 }
Victor Stinner4e314432010-10-07 21:45:39 +00001284
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001285 do {
1286 Py_BEGIN_ALLOW_THREADS
1287 f = _wfopen(wpath, wmode);
1288 Py_END_ALLOW_THREADS
1289 } while (f == NULL
1290 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner4e314432010-10-07 21:45:39 +00001291#else
Antoine Pitrou2b1cc892011-12-19 18:19:06 +01001292 PyObject *bytes;
Victor Stinnere42ccd22015-03-18 01:39:23 +01001293 char *path_bytes;
1294
1295 assert(PyGILState_Check());
1296
Antoine Pitrou2b1cc892011-12-19 18:19:06 +01001297 if (!PyUnicode_FSConverter(path, &bytes))
Victor Stinner4e314432010-10-07 21:45:39 +00001298 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01001299 path_bytes = PyBytes_AS_STRING(bytes);
1300
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001301 do {
1302 Py_BEGIN_ALLOW_THREADS
1303 f = fopen(path_bytes, mode);
1304 Py_END_ALLOW_THREADS
1305 } while (f == NULL
1306 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnere42ccd22015-03-18 01:39:23 +01001307
Victor Stinner4e314432010-10-07 21:45:39 +00001308 Py_DECREF(bytes);
Victor Stinner4e314432010-10-07 21:45:39 +00001309#endif
Victor Stinnera47fc5c2015-03-18 09:52:54 +01001310 if (async_err)
1311 return NULL;
1312
Victor Stinnere42ccd22015-03-18 01:39:23 +01001313 if (f == NULL) {
1314 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001315 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01001316 }
1317
1318 if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
Victor Stinnerdaf45552013-08-28 00:53:59 +02001319 fclose(f);
1320 return NULL;
1321 }
1322 return f;
Victor Stinner4e314432010-10-07 21:45:39 +00001323}
1324
Victor Stinner66aab0c2015-03-19 22:53:20 +01001325/* Read count bytes from fd into buf.
Victor Stinner82c3e452015-04-01 18:34:45 +02001326
1327 On success, return the number of read bytes, it can be lower than count.
1328 If the current file offset is at or past the end of file, no bytes are read,
1329 and read() returns zero.
1330
1331 On error, raise an exception, set errno and return -1.
1332
1333 When interrupted by a signal (read() fails with EINTR), retry the syscall.
1334 If the Python signal handler raises an exception, the function returns -1
1335 (the syscall is not retried).
1336
1337 Release the GIL to call read(). The caller must hold the GIL. */
Victor Stinner66aab0c2015-03-19 22:53:20 +01001338Py_ssize_t
1339_Py_read(int fd, void *buf, size_t count)
1340{
1341 Py_ssize_t n;
Victor Stinnera3c02022015-03-20 11:58:18 +01001342 int err;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001343 int async_err = 0;
1344
Victor Stinner8a1be612016-03-14 22:07:55 +01001345 assert(PyGILState_Check());
Victor Stinner8a1be612016-03-14 22:07:55 +01001346
Victor Stinner66aab0c2015-03-19 22:53:20 +01001347 /* _Py_read() must not be called with an exception set, otherwise the
1348 * caller may think that read() was interrupted by a signal and the signal
1349 * handler raised an exception. */
1350 assert(!PyErr_Occurred());
1351
Victor Stinner66aab0c2015-03-19 22:53:20 +01001352#ifdef MS_WINDOWS
1353 if (count > INT_MAX) {
1354 /* On Windows, the count parameter of read() is an int */
1355 count = INT_MAX;
1356 }
1357#else
1358 if (count > PY_SSIZE_T_MAX) {
1359 /* if count is greater than PY_SSIZE_T_MAX,
1360 * read() result is undefined */
1361 count = PY_SSIZE_T_MAX;
1362 }
1363#endif
1364
Steve Dower8fc89802015-04-12 00:26:27 -04001365 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner66aab0c2015-03-19 22:53:20 +01001366 do {
1367 Py_BEGIN_ALLOW_THREADS
1368 errno = 0;
1369#ifdef MS_WINDOWS
1370 n = read(fd, buf, (int)count);
1371#else
1372 n = read(fd, buf, count);
1373#endif
Victor Stinnera3c02022015-03-20 11:58:18 +01001374 /* save/restore errno because PyErr_CheckSignals()
1375 * and PyErr_SetFromErrno() can modify it */
1376 err = errno;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001377 Py_END_ALLOW_THREADS
Victor Stinnera3c02022015-03-20 11:58:18 +01001378 } while (n < 0 && err == EINTR &&
Victor Stinner66aab0c2015-03-19 22:53:20 +01001379 !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04001380 _Py_END_SUPPRESS_IPH
Victor Stinner66aab0c2015-03-19 22:53:20 +01001381
1382 if (async_err) {
1383 /* read() was interrupted by a signal (failed with EINTR)
1384 * and the Python signal handler raised an exception */
Victor Stinnera3c02022015-03-20 11:58:18 +01001385 errno = err;
1386 assert(errno == EINTR && PyErr_Occurred());
Victor Stinner66aab0c2015-03-19 22:53:20 +01001387 return -1;
1388 }
1389 if (n < 0) {
Victor Stinner66aab0c2015-03-19 22:53:20 +01001390 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnera3c02022015-03-20 11:58:18 +01001391 errno = err;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001392 return -1;
1393 }
1394
1395 return n;
1396}
1397
Victor Stinner82c3e452015-04-01 18:34:45 +02001398static Py_ssize_t
1399_Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
Victor Stinner66aab0c2015-03-19 22:53:20 +01001400{
1401 Py_ssize_t n;
Victor Stinnera3c02022015-03-20 11:58:18 +01001402 int err;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001403 int async_err = 0;
1404
Steve Dower8fc89802015-04-12 00:26:27 -04001405 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner66aab0c2015-03-19 22:53:20 +01001406#ifdef MS_WINDOWS
1407 if (count > 32767 && isatty(fd)) {
1408 /* Issue #11395: the Windows console returns an error (12: not
1409 enough space error) on writing into stdout if stdout mode is
1410 binary and the length is greater than 66,000 bytes (or less,
1411 depending on heap usage). */
1412 count = 32767;
1413 }
1414 else if (count > INT_MAX)
1415 count = INT_MAX;
1416#else
1417 if (count > PY_SSIZE_T_MAX) {
1418 /* write() should truncate count to PY_SSIZE_T_MAX, but it's safer
1419 * to do it ourself to have a portable behaviour. */
1420 count = PY_SSIZE_T_MAX;
1421 }
1422#endif
1423
Victor Stinner82c3e452015-04-01 18:34:45 +02001424 if (gil_held) {
1425 do {
1426 Py_BEGIN_ALLOW_THREADS
1427 errno = 0;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001428#ifdef MS_WINDOWS
Victor Stinner82c3e452015-04-01 18:34:45 +02001429 n = write(fd, buf, (int)count);
Victor Stinner66aab0c2015-03-19 22:53:20 +01001430#else
Victor Stinner82c3e452015-04-01 18:34:45 +02001431 n = write(fd, buf, count);
Victor Stinner66aab0c2015-03-19 22:53:20 +01001432#endif
Victor Stinner82c3e452015-04-01 18:34:45 +02001433 /* save/restore errno because PyErr_CheckSignals()
1434 * and PyErr_SetFromErrno() can modify it */
1435 err = errno;
1436 Py_END_ALLOW_THREADS
1437 } while (n < 0 && err == EINTR &&
1438 !(async_err = PyErr_CheckSignals()));
1439 }
1440 else {
1441 do {
1442 errno = 0;
1443#ifdef MS_WINDOWS
1444 n = write(fd, buf, (int)count);
1445#else
1446 n = write(fd, buf, count);
1447#endif
1448 err = errno;
1449 } while (n < 0 && err == EINTR);
1450 }
Steve Dower8fc89802015-04-12 00:26:27 -04001451 _Py_END_SUPPRESS_IPH
Victor Stinner66aab0c2015-03-19 22:53:20 +01001452
1453 if (async_err) {
1454 /* write() was interrupted by a signal (failed with EINTR)
Victor Stinner82c3e452015-04-01 18:34:45 +02001455 and the Python signal handler raised an exception (if gil_held is
1456 nonzero). */
Victor Stinnera3c02022015-03-20 11:58:18 +01001457 errno = err;
Victor Stinner82c3e452015-04-01 18:34:45 +02001458 assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
Victor Stinner66aab0c2015-03-19 22:53:20 +01001459 return -1;
1460 }
1461 if (n < 0) {
Victor Stinner82c3e452015-04-01 18:34:45 +02001462 if (gil_held)
1463 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnera3c02022015-03-20 11:58:18 +01001464 errno = err;
Victor Stinner66aab0c2015-03-19 22:53:20 +01001465 return -1;
1466 }
1467
1468 return n;
1469}
1470
Victor Stinner82c3e452015-04-01 18:34:45 +02001471/* Write count bytes of buf into fd.
1472
1473 On success, return the number of written bytes, it can be lower than count
1474 including 0. On error, raise an exception, set errno and return -1.
1475
1476 When interrupted by a signal (write() fails with EINTR), retry the syscall.
1477 If the Python signal handler raises an exception, the function returns -1
1478 (the syscall is not retried).
1479
1480 Release the GIL to call write(). The caller must hold the GIL. */
1481Py_ssize_t
1482_Py_write(int fd, const void *buf, size_t count)
1483{
Victor Stinner8a1be612016-03-14 22:07:55 +01001484 assert(PyGILState_Check());
Victor Stinner8a1be612016-03-14 22:07:55 +01001485
Victor Stinner82c3e452015-04-01 18:34:45 +02001486 /* _Py_write() must not be called with an exception set, otherwise the
1487 * caller may think that write() was interrupted by a signal and the signal
1488 * handler raised an exception. */
1489 assert(!PyErr_Occurred());
1490
1491 return _Py_write_impl(fd, buf, count, 1);
1492}
1493
1494/* Write count bytes of buf into fd.
1495 *
1496 * On success, return the number of written bytes, it can be lower than count
1497 * including 0. On error, set errno and return -1.
1498 *
1499 * When interrupted by a signal (write() fails with EINTR), retry the syscall
1500 * without calling the Python signal handler. */
1501Py_ssize_t
1502_Py_write_noraise(int fd, const void *buf, size_t count)
1503{
1504 return _Py_write_impl(fd, buf, count, 0);
1505}
1506
Victor Stinner4e314432010-10-07 21:45:39 +00001507#ifdef HAVE_READLINK
Victor Stinner6672d0c2010-10-07 22:53:43 +00001508
1509/* Read value of symbolic link. Encode the path to the locale encoding, decode
Victor Stinneraf02e1c2011-12-16 23:56:01 +01001510 the result from the locale encoding. Return -1 on error. */
Victor Stinner6672d0c2010-10-07 22:53:43 +00001511
Victor Stinner4e314432010-10-07 21:45:39 +00001512int
1513_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
1514{
1515 char *cpath;
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001516 char cbuf[MAXPATHLEN];
Victor Stinner3f711f42010-10-16 22:47:37 +00001517 wchar_t *wbuf;
Victor Stinner4e314432010-10-07 21:45:39 +00001518 int res;
1519 size_t r1;
1520
Victor Stinner9dd76202017-12-21 16:20:32 +01001521 cpath = _Py_EncodeLocaleRaw(path, NULL);
Victor Stinner4e314432010-10-07 21:45:39 +00001522 if (cpath == NULL) {
1523 errno = EINVAL;
1524 return -1;
1525 }
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001526 res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf));
Victor Stinner9dd76202017-12-21 16:20:32 +01001527 PyMem_RawFree(cpath);
Victor Stinner4e314432010-10-07 21:45:39 +00001528 if (res == -1)
1529 return -1;
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001530 if (res == Py_ARRAY_LENGTH(cbuf)) {
Victor Stinner4e314432010-10-07 21:45:39 +00001531 errno = EINVAL;
1532 return -1;
1533 }
1534 cbuf[res] = '\0'; /* buf will be null terminated */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001535 wbuf = Py_DecodeLocale(cbuf, &r1);
Victor Stinner350147b2010-10-16 22:52:09 +00001536 if (wbuf == NULL) {
1537 errno = EINVAL;
1538 return -1;
1539 }
Victor Stinner3f711f42010-10-16 22:47:37 +00001540 if (bufsiz <= r1) {
Victor Stinner1a7425f2013-07-07 16:25:15 +02001541 PyMem_RawFree(wbuf);
Victor Stinner4e314432010-10-07 21:45:39 +00001542 errno = EINVAL;
1543 return -1;
1544 }
Victor Stinner3f711f42010-10-16 22:47:37 +00001545 wcsncpy(buf, wbuf, bufsiz);
Victor Stinner1a7425f2013-07-07 16:25:15 +02001546 PyMem_RawFree(wbuf);
Victor Stinner4e314432010-10-07 21:45:39 +00001547 return (int)r1;
1548}
1549#endif
1550
1551#ifdef HAVE_REALPATH
Victor Stinner6672d0c2010-10-07 22:53:43 +00001552
1553/* Return the canonicalized absolute pathname. Encode path to the locale
Victor Stinneraf02e1c2011-12-16 23:56:01 +01001554 encoding, decode the result from the locale encoding.
1555 Return NULL on error. */
Victor Stinner6672d0c2010-10-07 22:53:43 +00001556
Victor Stinner4e314432010-10-07 21:45:39 +00001557wchar_t*
Victor Stinner015f4d82010-10-07 22:29:53 +00001558_Py_wrealpath(const wchar_t *path,
1559 wchar_t *resolved_path, size_t resolved_path_size)
Victor Stinner4e314432010-10-07 21:45:39 +00001560{
1561 char *cpath;
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001562 char cresolved_path[MAXPATHLEN];
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001563 wchar_t *wresolved_path;
Victor Stinner4e314432010-10-07 21:45:39 +00001564 char *res;
1565 size_t r;
Victor Stinner9dd76202017-12-21 16:20:32 +01001566 cpath = _Py_EncodeLocaleRaw(path, NULL);
Victor Stinner4e314432010-10-07 21:45:39 +00001567 if (cpath == NULL) {
1568 errno = EINVAL;
1569 return NULL;
1570 }
1571 res = realpath(cpath, cresolved_path);
Victor Stinner9dd76202017-12-21 16:20:32 +01001572 PyMem_RawFree(cpath);
Victor Stinner4e314432010-10-07 21:45:39 +00001573 if (res == NULL)
1574 return NULL;
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001575
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001576 wresolved_path = Py_DecodeLocale(cresolved_path, &r);
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001577 if (wresolved_path == NULL) {
Victor Stinner4e314432010-10-07 21:45:39 +00001578 errno = EINVAL;
1579 return NULL;
1580 }
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001581 if (resolved_path_size <= r) {
Victor Stinner1a7425f2013-07-07 16:25:15 +02001582 PyMem_RawFree(wresolved_path);
Victor Stinner0a1b8cb2010-10-16 22:55:47 +00001583 errno = EINVAL;
1584 return NULL;
1585 }
1586 wcsncpy(resolved_path, wresolved_path, resolved_path_size);
Victor Stinner1a7425f2013-07-07 16:25:15 +02001587 PyMem_RawFree(wresolved_path);
Victor Stinner4e314432010-10-07 21:45:39 +00001588 return resolved_path;
1589}
1590#endif
1591
Victor Stinnerf4061da2010-10-14 12:37:19 +00001592/* Get the current directory. size is the buffer size in wide characters
Victor Stinneraf02e1c2011-12-16 23:56:01 +01001593 including the null character. Decode the path from the locale encoding.
1594 Return NULL on error. */
Victor Stinner6672d0c2010-10-07 22:53:43 +00001595
Victor Stinner4e314432010-10-07 21:45:39 +00001596wchar_t*
1597_Py_wgetcwd(wchar_t *buf, size_t size)
1598{
1599#ifdef MS_WINDOWS
Victor Stinner56785ea2013-06-05 00:46:29 +02001600 int isize = (int)Py_MIN(size, INT_MAX);
1601 return _wgetcwd(buf, isize);
Victor Stinner4e314432010-10-07 21:45:39 +00001602#else
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001603 char fname[MAXPATHLEN];
Victor Stinnerf4061da2010-10-14 12:37:19 +00001604 wchar_t *wname;
Victor Stinner168e1172010-10-16 23:16:16 +00001605 size_t len;
Victor Stinnerf4061da2010-10-14 12:37:19 +00001606
Victor Stinnerb11d6cb2013-11-15 18:14:11 +01001607 if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
Victor Stinner4e314432010-10-07 21:45:39 +00001608 return NULL;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02001609 wname = Py_DecodeLocale(fname, &len);
Victor Stinnerf4061da2010-10-14 12:37:19 +00001610 if (wname == NULL)
1611 return NULL;
Victor Stinner168e1172010-10-16 23:16:16 +00001612 if (size <= len) {
Victor Stinner1a7425f2013-07-07 16:25:15 +02001613 PyMem_RawFree(wname);
Victor Stinner4e314432010-10-07 21:45:39 +00001614 return NULL;
1615 }
Victor Stinnerf4061da2010-10-14 12:37:19 +00001616 wcsncpy(buf, wname, size);
Victor Stinner1a7425f2013-07-07 16:25:15 +02001617 PyMem_RawFree(wname);
Victor Stinner4e314432010-10-07 21:45:39 +00001618 return buf;
1619#endif
1620}
1621
Victor Stinnerdaf45552013-08-28 00:53:59 +02001622/* Duplicate a file descriptor. The new file descriptor is created as
1623 non-inheritable. Return a new file descriptor on success, raise an OSError
1624 exception and return -1 on error.
1625
1626 The GIL is released to call dup(). The caller must hold the GIL. */
1627int
1628_Py_dup(int fd)
1629{
1630#ifdef MS_WINDOWS
1631 HANDLE handle;
1632 DWORD ftype;
1633#endif
1634
Victor Stinner8a1be612016-03-14 22:07:55 +01001635 assert(PyGILState_Check());
Victor Stinner8a1be612016-03-14 22:07:55 +01001636
Victor Stinnerdaf45552013-08-28 00:53:59 +02001637#ifdef MS_WINDOWS
Steve Dower8fc89802015-04-12 00:26:27 -04001638 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001639 handle = (HANDLE)_get_osfhandle(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001640 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001641 if (handle == INVALID_HANDLE_VALUE) {
Steve Dower41e72442015-03-14 11:38:27 -07001642 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001643 return -1;
1644 }
1645
1646 /* get the file type, ignore the error if it failed */
1647 ftype = GetFileType(handle);
1648
1649 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001650 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001651 fd = dup(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001652 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001653 Py_END_ALLOW_THREADS
1654 if (fd < 0) {
1655 PyErr_SetFromErrno(PyExc_OSError);
1656 return -1;
1657 }
1658
1659 /* Character files like console cannot be make non-inheritable */
1660 if (ftype != FILE_TYPE_CHAR) {
1661 if (_Py_set_inheritable(fd, 0, NULL) < 0) {
Steve Dower8fc89802015-04-12 00:26:27 -04001662 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001663 close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001664 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001665 return -1;
1666 }
1667 }
1668#elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
1669 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001670 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001671 fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
Steve Dower8fc89802015-04-12 00:26:27 -04001672 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001673 Py_END_ALLOW_THREADS
1674 if (fd < 0) {
1675 PyErr_SetFromErrno(PyExc_OSError);
1676 return -1;
1677 }
1678
1679#else
1680 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001681 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001682 fd = dup(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001683 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001684 Py_END_ALLOW_THREADS
1685 if (fd < 0) {
1686 PyErr_SetFromErrno(PyExc_OSError);
1687 return -1;
1688 }
1689
1690 if (_Py_set_inheritable(fd, 0, NULL) < 0) {
Steve Dower8fc89802015-04-12 00:26:27 -04001691 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001692 close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001693 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02001694 return -1;
1695 }
1696#endif
1697 return fd;
1698}
1699
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001700#ifndef MS_WINDOWS
1701/* Get the blocking mode of the file descriptor.
1702 Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
1703 raise an exception and return -1 on error. */
1704int
1705_Py_get_blocking(int fd)
1706{
Steve Dower8fc89802015-04-12 00:26:27 -04001707 int flags;
1708 _Py_BEGIN_SUPPRESS_IPH
1709 flags = fcntl(fd, F_GETFL, 0);
1710 _Py_END_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001711 if (flags < 0) {
1712 PyErr_SetFromErrno(PyExc_OSError);
1713 return -1;
1714 }
1715
1716 return !(flags & O_NONBLOCK);
1717}
1718
1719/* Set the blocking mode of the specified file descriptor.
1720
1721 Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
1722 otherwise.
1723
1724 Return 0 on success, raise an exception and return -1 on error. */
1725int
1726_Py_set_blocking(int fd, int blocking)
1727{
1728#if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)
1729 int arg = !blocking;
1730 if (ioctl(fd, FIONBIO, &arg) < 0)
1731 goto error;
1732#else
1733 int flags, res;
1734
Steve Dower8fc89802015-04-12 00:26:27 -04001735 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001736 flags = fcntl(fd, F_GETFL, 0);
Steve Dower8fc89802015-04-12 00:26:27 -04001737 if (flags >= 0) {
1738 if (blocking)
1739 flags = flags & (~O_NONBLOCK);
1740 else
1741 flags = flags | O_NONBLOCK;
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001742
Steve Dower8fc89802015-04-12 00:26:27 -04001743 res = fcntl(fd, F_SETFL, flags);
1744 } else {
1745 res = -1;
1746 }
1747 _Py_END_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001748
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001749 if (res < 0)
1750 goto error;
1751#endif
1752 return 0;
1753
1754error:
1755 PyErr_SetFromErrno(PyExc_OSError);
1756 return -1;
1757}
1758#endif
Victor Stinnercb064fc2018-01-15 15:58:02 +01001759
1760
1761int
1762_Py_GetLocaleconvNumeric(PyObject **decimal_point, PyObject **thousands_sep,
1763 const char **grouping)
1764{
1765 int res = -1;
1766
1767 struct lconv *lc = localeconv();
1768
1769 int change_locale = 0;
1770 if (decimal_point != NULL &&
1771 (strlen(lc->decimal_point) > 1 || ((unsigned char)lc->decimal_point[0]) > 127))
1772 {
1773 change_locale = 1;
1774 }
1775 if (thousands_sep != NULL &&
1776 (strlen(lc->thousands_sep) > 1 || ((unsigned char)lc->thousands_sep[0]) > 127))
1777 {
1778 change_locale = 1;
1779 }
1780
1781 /* Keep a copy of the LC_CTYPE locale */
1782 char *oldloc = NULL, *loc = NULL;
1783 if (change_locale) {
1784 oldloc = setlocale(LC_CTYPE, NULL);
1785 if (!oldloc) {
1786 PyErr_SetString(PyExc_RuntimeWarning, "faild to get LC_CTYPE locale");
1787 return -1;
1788 }
1789
1790 oldloc = _PyMem_Strdup(oldloc);
1791 if (!oldloc) {
1792 PyErr_NoMemory();
1793 return -1;
1794 }
1795
1796 loc = setlocale(LC_NUMERIC, NULL);
1797 if (loc != NULL && strcmp(loc, oldloc) == 0) {
1798 loc = NULL;
1799 }
1800
1801 if (loc != NULL) {
1802 /* Only set the locale temporarilty the LC_CTYPE locale
1803 if LC_NUMERIC locale is different than LC_CTYPE locale and
1804 decimal_point and/or thousands_sep are non-ASCII or longer than
1805 1 byte */
1806 setlocale(LC_CTYPE, loc);
1807 }
1808 }
1809
1810 if (decimal_point != NULL) {
1811 *decimal_point = PyUnicode_DecodeLocale(lc->decimal_point, NULL);
1812 if (*decimal_point == NULL) {
1813 goto error;
1814 }
1815 }
1816 if (thousands_sep != NULL) {
1817 *thousands_sep = PyUnicode_DecodeLocale(lc->thousands_sep, NULL);
1818 if (*thousands_sep == NULL) {
1819 goto error;
1820 }
1821 }
1822
1823 if (grouping != NULL) {
1824 *grouping = lc->grouping;
1825 }
1826
1827 res = 0;
1828
1829error:
1830 if (loc != NULL) {
1831 setlocale(LC_CTYPE, oldloc);
1832 }
1833 PyMem_Free(oldloc);
1834 return res;
1835}