summaryrefslogtreecommitdiffstats
path: root/Python/thread.c
blob: dd333e8f944a7229b0298ea8d0cfb2e8c68aef67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421

/* Thread package.
   This is intended to be usable independently from Python.
   The implementation for system foobar is in a file thread_foobar.h
   which is included by this file dependent on config settings.
   Stuff shared by all thread_*.h files is collected here. */

#include "Python.h"


#ifndef _POSIX_THREADS
/* This means pthreads are not implemented in libc headers, hence the macro
   not present in unistd.h. But they still can be implemented as an external
   library (e.g. gnu pth in pthread emulation) */
# ifdef HAVE_PTHREAD_H
#  include <pthread.h> /* _POSIX_THREADS */
# endif
#endif

#ifndef DONT_HAVE_STDIO_H
#include <stdio.h>
#endif

#include <stdlib.h>

#ifdef __sgi
#ifndef HAVE_PTHREAD_H /* XXX Need to check in configure.ac */
#undef _POSIX_THREADS
#endif
#endif

#include "pythread.h"

#ifndef _POSIX_THREADS

#ifdef __sgi
#define SGI_THREADS
#endif

#ifdef HAVE_THREAD_H
#define SOLARIS_THREADS
#endif

#if defined(sun) && !defined(SOLARIS_THREADS)
#define SUN_LWP
#endif

/* Check if we're running on HP-UX and _SC_THREADS is defined. If so, then
   enough of the Posix threads package is implemented to support python
   threads.

   This is valid for HP-UX 11.23 running on an ia64 system. If needed, add
   a check of __ia64 to verify that we're running on a ia64 system instead
   of a pa-risc system.
*/
#ifdef __hpux
#ifdef _SC_THREADS
#define _POSIX_THREADS
#endif
#endif

#endif /* _POSIX_THREADS */


#ifdef Py_DEBUG
static int thread_debug = 0;
#define dprintf(args)   (void)((thread_debug & 1) && printf args)
#define d2printf(args)  ((thread_debug & 8) && printf args)
#else
#define dprintf(args)
#define d2printf(args)
#endif

static int initialized;

static void PyThread__init_thread(void); /* Forward */

void
PyThread_init_thread(void)
{
#ifdef Py_DEBUG
    char *p = Py_GETENV("PYTHONTHREADDEBUG");

    if (p) {
        if (*p)
            thread_debug = atoi(p);
        else
            thread_debug = 1;
    }
#endif /* Py_DEBUG */
    if (initialized)
        return;
    initialized = 1;
    dprintf(("PyThread_init_thread called\n"));
    PyThread__init_thread();
}

/* Support for runtime thread stack size tuning.
   A value of 0 means using the platform's default stack size
   or the size specified by the THREAD_STACK_SIZE macro. */
static size_t _pythread_stacksize = 0;

#ifdef SGI_THREADS
#include "thread_sgi.h"
#endif

#ifdef SOLARIS_THREADS
#include "thread_solaris.h"
#endif

#ifdef SUN_LWP
#include "thread_lwp.h"
#endif

#ifdef HAVE_PTH
#include "thread_pth.h"
#undef _POSIX_THREADS
#endif

#ifdef _POSIX_THREADS
#include "thread_pthread.h"
#endif

#ifdef C_THREADS
#include "thread_cthread.h"
#endif

#ifdef NT_THREADS
#include "thread_nt.h"
#endif

#ifdef OS2_THREADS
#include "thread_os2.h"
#endif

#ifdef BEOS_THREADS
#include "thread_beos.h"
#endif

#ifdef PLAN9_THREADS
#include "thread_plan9.h"
#endif

#ifdef ATHEOS_THREADS
#include "thread_atheos.h"
#endif

/*
#ifdef FOOBAR_THREADS
#include "thread_foobar.h"
#endif
*/

/* return the current thread stack size */
size_t
PyThread_get_stacksize(void)
{
    return _pythread_stacksize;
}

/* Only platforms defining a THREAD_SET_STACKSIZE() macro
   in thread_<platform>.h support changing the stack size.
   Return 0 if stack size is valid,
      -1 if stack size value is invalid,
      -2 if setting stack size is not supported. */
int
PyThread_set_stacksize(size_t size)
{
#if defined(THREAD_SET_STACKSIZE)
    return THREAD_SET_STACKSIZE(size);
#else
    return -2;
#endif
}

#ifndef Py_HAVE_NATIVE_TLS
/* If the platform has not supplied a platform specific
   TLS implementation, provide our own.

   This code stolen from "thread_sgi.h", where it was the only
   implementation of an existing Python TLS API.
*/
/* ------------------------------------------------------------------------
Per-thread data ("key") support.

Use PyThread_create_key() to create a new key.  This is typically shared
across threads.

Use PyThread_set_key_value(thekey, value) to associate void* value with
thekey in the current thread.  Each thread has a distinct mapping of thekey
to a void* value.  Caution:  if the current thread already has a mapping
for thekey, value is ignored.

Use PyThread_get_key_value(thekey) to retrieve the void* value associated
with thekey in the current thread.  This returns NULL if no value is
associated with thekey in the current thread.

Use PyThread_delete_key_value(thekey) to forget the current thread's associated
value for thekey.  PyThread_delete_key(thekey) forgets the values associated
with thekey across *all* threads.

While some of these functions have error-return values, none set any
Python exception.

None of the functions does memory management on behalf of the void* values.
You need to allocate and deallocate them yourself.  If the void* values
happen to be PyObject*, these functions don't do refcount operations on
them either.

The GIL does not need to be held when calling these functions; they supply
their own locking.  This isn't true of PyThread_create_key(), though (see
next paragraph).

There's a hidden assumption that PyThread_create_key() will be called before
any of the other functions are called.  There's also a hidden assumption
that calls to PyThread_create_key() are serialized externally.
------------------------------------------------------------------------ */

/* A singly-linked list of struct key objects remembers all the key->value
 * associations.  File static keyhead heads the list.  keymutex is used
 * to enforce exclusion internally.
 */
struct key {
    /* Next record in the list, or NULL if this is the last record. */
    struct key *next;

    /* The thread id, according to PyThread_get_thread_ident(). */
    long id;

    /* The key and its associated value. */
    int key;
    void *value;
};

static struct key *keyhead = NULL;
static PyThread_type_lock keymutex = NULL;
static int nkeys = 0;  /* PyThread_create_key() hands out nkeys+1 next */

/* Internal helper.
 * If the current thread has a mapping for key, the appropriate struct key*
 * is returned.  NB:  value is ignored in this case!
 * If there is no mapping for key in the current thread, then:
 *     If value is NULL, NULL is returned.
 *     Else a mapping of key to value is created for the current thread,
 *     and a pointer to a new struct key* is returned; except that if
 *     malloc() can't find room for a new struct key*, NULL is returned.
 * So when value==NULL, this acts like a pure lookup routine, and when
 * value!=NULL, this acts like dict.setdefault(), returning an existing
 * mapping if one exists, else creating a new mapping.
 *
 * Caution:  this used to be too clever, trying to hold keymutex only
 * around the "p->next = keyhead; keyhead = p" pair.  That allowed
 * another thread to mutate the list, via key deletion, concurrent with
 * find_key() crawling over the list.  Hilarity ensued.  For example, when
 * the for-loop here does "p = p->next", p could end up pointing at a
 * record that PyThread_delete_key_value() was concurrently free()'ing.
 * That could lead to anything, from failing to find a key that exists, to
 * segfaults.  Now we lock the whole routine.
 */
static struct key *
find_key(int key, void *value)
{
    struct key *p, *prev_p;
    long id = PyThread_get_thread_ident();

    if (!keymutex)
        return NULL;
    PyThread_acquire_lock(keymutex, 1);
    prev_p = NULL;
    for (p = keyhead; p != NULL; p = p->next) {
        if (p->id == id && p->key == key)
            goto Done;
        /* Sanity check.  These states should never happen but if
         * they do we must abort.  Otherwise we'll end up spinning in
         * in a tight loop with the lock held.  A similar check is done
         * in pystate.c tstate_delete_common().  */
        if (p == prev_p)
            Py_FatalError("tls find_key: small circular list(!)");
        prev_p = p;
        if (p->next == keyhead)
            Py_FatalError("tls find_key: circular list(!)");
    }
    if (value == NULL) {
        assert(p == NULL);
        goto Done;
    }
    p = (struct key *)malloc(sizeof(struct key));
    if (p != NULL) {
        p->id = id;
        p->key = key;
        p->value = value;
        p->next = keyhead;
        keyhead = p;
    }
 Done:
    PyThread_release_lock(keymutex);
    return p;
}

/* Return a new key.  This must be called before any other functions in
 * this family, and callers must arrange to serialize calls to this
 * function.  No violations are detected.
 */
int
PyThread_create_key(void)
{
    /* All parts of this function are wrong if it's called by multiple
     * threads simultaneously.
     */
    if (keymutex == NULL)
        keymutex = PyThread_allocate_lock();
    return ++nkeys;
}

/* Forget the associations for key across *all* threads. */
void
PyThread_delete_key(int key)
{
    struct key *p, **q;

    PyThread_acquire_lock(keymutex, 1);
    q = &keyhead;
    while ((p = *q) != NULL) {
        if (p->key == key) {
            *q = p->next;
            free((void *)p);
            /* NB This does *not* free p->value! */
        }
        else
            q = &p->next;
    }
    PyThread_release_lock(keymutex);
}

/* Confusing:  If the current thread has an association for key,
 * value is ignored, and 0 is returned.  Else an attempt is made to create
 * an association of key to value for the current thread.  0 is returned
 * if that succeeds, but -1 is returned if there's not enough memory
 * to create the association.  value must not be NULL.
 */
int
PyThread_set_key_value(int key, void *value)
{
    struct key *p;

    assert(value != NULL);
    p = find_key(key, value);
    if (p == NULL)
        return -1;
    else
        return 0;
}

/* Retrieve the value associated with key in the current thread, or NULL
 * if the current thread doesn't have an association for key.
 */
void *
PyThread_get_key_value(int key)
{
    struct key *p = find_key(key, NULL);

    if (p == NULL)
        return NULL;
    else
        return p->value;
}

/* Forget the current thread's association for key, if any. */
void
PyThread_delete_key_value(int key)
{
    long id = PyThread_get_thread_ident();
    struct key *p, **q;

    PyThread_acquire_lock(keymutex, 1);
    q = &keyhead;
    while ((p = *q) != NULL) {
        if (p->key == key && p->id == id) {
            *q = p->next;
            free((void *)p);
            /* NB This does *not* free p->value! */
            break;
        }
        else
            q = &p->next;
    }
    PyThread_release_lock(keymutex);
}

/* Forget everything not associated with the current thread id.
 * This function is called from PyOS_AfterFork().  It is necessary
 * because other thread ids which were in use at the time of the fork
 * may be reused for new threads created in the forked process.
 */
void
PyThread_ReInitTLS(void)
{
    long id = PyThread_get_thread_ident();
    struct key *p, **q;

    if (!keymutex)
        return;

    /* As with interpreter_lock in PyEval_ReInitThreads()
       we just create a new lock without freeing the old one */
    keymutex = PyThread_allocate_lock();

    /* Delete all keys which do not match the current thread id */
    q = &keyhead;
    while ((p = *q) != NULL) {
        if (p->id != id) {
            *q = p->next;
            free((void *)p);
            /* NB This does *not* free p->value! */
        }
        else
            q = &p->next;
    }
}

#endif /* Py_HAVE_NATIVE_TLS */
ref='#n1325'>1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103
#include "Python.h"
#include "pycore_fileutils.h"     // fileutils definitions
#include "pycore_runtime.h"       // _PyRuntime
#include "osdefs.h"               // SEP

#include <stdlib.h>               // mbstowcs()
#ifdef HAVE_UNISTD_H
#  include <unistd.h>             // getcwd()
#endif

#ifdef MS_WINDOWS
#  include <malloc.h>
#  include <windows.h>
#  include <winioctl.h>             // FILE_DEVICE_* constants
#  include "pycore_fileutils_windows.h" // FILE_STAT_BASIC_INFORMATION
#  if defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP)
#    define PATHCCH_ALLOW_LONG_PATHS 0x01
#  else
#    include <pathcch.h>            // PathCchCombineEx
#  endif
extern int winerror_to_errno(int);
#endif

#ifdef HAVE_LANGINFO_H
#  include <langinfo.h>           // nl_langinfo(CODESET)
#endif

#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif

#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
#  include <iconv.h>              // iconv_open()
#endif

#ifdef HAVE_FCNTL_H
#  include <fcntl.h>              // fcntl(F_GETFD)
#endif

#ifdef O_CLOEXEC
/* Does open() support the O_CLOEXEC flag? Possible values:

   -1: unknown
    0: open() ignores O_CLOEXEC flag, ex: Linux kernel older than 2.6.23
    1: open() supports O_CLOEXEC flag, close-on-exec is set

   The flag is used by _Py_open(), _Py_open_noraise(), io.FileIO
   and os.open(). */
int _Py_open_cloexec_works = -1;
#endif

// The value must be the same in unicodeobject.c.
#define MAX_UNICODE 0x10ffff

// mbstowcs() and mbrtowc() errors
static const size_t DECODE_ERROR = ((size_t)-1);
static const size_t INCOMPLETE_CHARACTER = (size_t)-2;


static int
get_surrogateescape(_Py_error_handler errors, int *surrogateescape)
{
    switch (errors)
    {
    case _Py_ERROR_STRICT:
        *surrogateescape = 0;
        return 0;
    case _Py_ERROR_SURROGATEESCAPE:
        *surrogateescape = 1;
        return 0;
    default:
        return -1;
    }
}


PyObject *
_Py_device_encoding(int fd)
{
    int valid;
    Py_BEGIN_ALLOW_THREADS
    _Py_BEGIN_SUPPRESS_IPH
    valid = isatty(fd);
    _Py_END_SUPPRESS_IPH
    Py_END_ALLOW_THREADS
    if (!valid)
        Py_RETURN_NONE;

#ifdef MS_WINDOWS
#ifdef HAVE_WINDOWS_CONSOLE_IO
    UINT cp;
    if (fd == 0)
        cp = GetConsoleCP();
    else if (fd == 1 || fd == 2)
        cp = GetConsoleOutputCP();
    else
        cp = 0;
    /* GetConsoleCP() and GetConsoleOutputCP() return 0 if the application
       has no console */
    if (cp == 0) {
        Py_RETURN_NONE;
    }

    return PyUnicode_FromFormat("cp%u", (unsigned int)cp);
#else
    Py_RETURN_NONE;
#endif /* HAVE_WINDOWS_CONSOLE_IO */
#else
    if (_PyRuntime.preconfig.utf8_mode) {
        _Py_DECLARE_STR(utf_8, "utf-8");
        return &_Py_STR(utf_8);
    }
    return _Py_GetLocaleEncodingObject();
#endif
}


static int
is_valid_wide_char(wchar_t ch)
{
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
    /* Oracle Solaris doesn't use Unicode code points as wchar_t encoding
       for non-Unicode locales, which makes values higher than MAX_UNICODE
       possibly valid. */
    return 1;
#endif
    if (Py_UNICODE_IS_SURROGATE(ch)) {
        // Reject lone surrogate characters
        return 0;
    }
    if (ch > MAX_UNICODE) {
        // bpo-35883: Reject characters outside [U+0000; U+10ffff] range.
        // The glibc mbstowcs() UTF-8 decoder does not respect the RFC 3629,
        // it creates characters outside the [U+0000; U+10ffff] range:
        // https://sourceware.org/bugzilla/show_bug.cgi?id=2373
        return 0;
    }
    return 1;
}


static size_t
_Py_mbstowcs(wchar_t *dest, const char *src, size_t n)
{
    size_t count = mbstowcs(dest, src, n);
    if (dest != NULL && count != DECODE_ERROR) {
        for (size_t i=0; i < count; i++) {
            wchar_t ch = dest[i];
            if (!is_valid_wide_char(ch)) {
                return DECODE_ERROR;
            }
        }
    }
    return count;
}


#ifdef HAVE_MBRTOWC
static size_t
_Py_mbrtowc(wchar_t *pwc, const char *str, size_t len, mbstate_t *pmbs)
{
    assert(pwc != NULL);
    size_t count = mbrtowc(pwc, str, len, pmbs);
    if (count != 0 && count != DECODE_ERROR && count != INCOMPLETE_CHARACTER) {
        if (!is_valid_wide_char(*pwc)) {
            return DECODE_ERROR;
        }
    }
    return count;
}
#endif


#if !defined(_Py_FORCE_UTF8_FS_ENCODING) && !defined(MS_WINDOWS)

#define USE_FORCE_ASCII

extern int _Py_normalize_encoding(const char *, char *, size_t);

/* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale
   and POSIX locale. nl_langinfo(CODESET) announces an alias of the
   ASCII encoding, whereas mbstowcs() and wcstombs() functions use the
   ISO-8859-1 encoding. The problem is that os.fsencode() and os.fsdecode() use
   locale.getpreferredencoding() codec. For example, if command line arguments
   are decoded by mbstowcs() and encoded back by os.fsencode(), we get a
   UnicodeEncodeError instead of retrieving the original byte string.

   The workaround is enabled if setlocale(LC_CTYPE, NULL) returns "C",
   nl_langinfo(CODESET) announces "ascii" (or an alias to ASCII), and at least
   one byte in range 0x80-0xff can be decoded from the locale encoding. The
   workaround is also enabled on error, for example if getting the locale
   failed.

   On HP-UX with the C locale or the POSIX locale, nl_langinfo(CODESET)
   announces "roman8" but mbstowcs() uses Latin1 in practice. Force also the
   ASCII encoding in this case.

   Values of force_ascii:

       1: the workaround is used: Py_EncodeLocale() uses
          encode_ascii_surrogateescape() and Py_DecodeLocale() uses
          decode_ascii()
       0: the workaround is not used: Py_EncodeLocale() uses wcstombs() and
          Py_DecodeLocale() uses mbstowcs()
      -1: unknown, need to call check_force_ascii() to get the value
*/
#define force_ascii (_PyRuntime.fileutils.force_ascii)

static int
check_force_ascii(void)
{
    char *loc = setlocale(LC_CTYPE, NULL);
    if (loc == NULL) {
        goto error;
    }
    if (strcmp(loc, "C") != 0 && strcmp(loc, "POSIX") != 0) {
        /* the LC_CTYPE locale is different than C and POSIX */
        return 0;
    }

#if defined(HAVE_LANGINFO_H) && defined(CODESET)
    const char *codeset = nl_langinfo(CODESET);
    if (!codeset || codeset[0] == '\0') {
        /* CODESET is not set or empty */
        goto error;
    }

    char encoding[20];   /* longest name: "iso_646.irv_1991\0" */
    if (!_Py_normalize_encoding(codeset, encoding, sizeof(encoding))) {
        goto error;
    }

#ifdef __hpux
    if (strcmp(encoding, "roman8") == 0) {
        unsigned char ch;
        wchar_t wch;
        size_t res;

        ch = (unsigned char)0xA7;
        res = _Py_mbstowcs(&wch, (char*)&ch, 1);
        if (res != DECODE_ERROR && wch == L'\xA7') {
            /* On HP-UX with C locale or the POSIX locale,
               nl_langinfo(CODESET) announces "roman8", whereas mbstowcs() uses
               Latin1 encoding in practice. Force ASCII in this case.

               Roman8 decodes 0xA7 to U+00CF. Latin1 decodes 0xA7 to U+00A7. */
            return 1;
        }
    }
#else
    const char* ascii_aliases[] = {
        "ascii",
        /* Aliases from Lib/encodings/aliases.py */
        "646",
        "ansi_x3.4_1968",
        "ansi_x3.4_1986",
        "ansi_x3_4_1968",
        "cp367",
        "csascii",
        "ibm367",
        "iso646_us",
        "iso_646.irv_1991",
        "iso_ir_6",
        "us",
        "us_ascii",
        NULL
    };

    int is_ascii = 0;
    for (const char **alias=ascii_aliases; *alias != NULL; alias++) {
        if (strcmp(encoding, *alias) == 0) {
            is_ascii = 1;
            break;
        }
    }
    if (!is_ascii) {
        /* nl_langinfo(CODESET) is not "ascii" or an alias of ASCII */
        return 0;
    }

    for (unsigned int i=0x80; i<=0xff; i++) {
        char ch[1];
        wchar_t wch[1];
        size_t res;

        unsigned uch = (unsigned char)i;
        ch[0] = (char)uch;
        res = _Py_mbstowcs(wch, ch, 1);
        if (res != DECODE_ERROR) {
            /* decoding a non-ASCII character from the locale encoding succeed:
               the locale encoding is not ASCII, force ASCII */
            return 1;
        }
    }
    /* None of the bytes in the range 0x80-0xff can be decoded from the locale
       encoding: the locale encoding is really ASCII */
#endif   /* !defined(__hpux) */
    return 0;
#else
    /* nl_langinfo(CODESET) is not available: always force ASCII */
    return 1;
#endif   /* defined(HAVE_LANGINFO_H) && defined(CODESET) */

error:
    /* if an error occurred, force the ASCII encoding */
    return 1;
}


int
_Py_GetForceASCII(void)
{
    if (force_ascii == -1) {
        force_ascii = check_force_ascii();
    }
    return force_ascii;
}


void
_Py_ResetForceASCII(void)
{
    force_ascii = -1;
}


static int
encode_ascii(const wchar_t *text, char **str,
             size_t *error_pos, const char **reason,
             int raw_malloc, _Py_error_handler errors)
{
    char *result = NULL, *out;
    size_t len, i;
    wchar_t ch;

    int surrogateescape;
    if (get_surrogateescape(errors, &surrogateescape) < 0) {
        return -3;
    }

    len = wcslen(text);

    /* +1 for NULL byte */
    if (raw_malloc) {
        result = PyMem_RawMalloc(len + 1);
    }
    else {
        result = PyMem_Malloc(len + 1);
    }
    if (result == NULL) {
        return -1;
    }

    out = result;
    for (i=0; i<len; i++) {
        ch = text[i];

        if (ch <= 0x7f) {
            /* ASCII character */
            *out++ = (char)ch;
        }
        else if (surrogateescape && 0xdc80 <= ch && ch <= 0xdcff) {
            /* UTF-8b surrogate */
            *out++ = (char)(ch - 0xdc00);
        }
        else {
            if (raw_malloc) {
                PyMem_RawFree(result);
            }
            else {
                PyMem_Free(result);
            }
            if (error_pos != NULL) {
                *error_pos = i;
            }
            if (reason) {
                *reason = "encoding error";
            }
            return -2;
        }
    }
    *out = '\0';
    *str = result;
    return 0;
}
#else
int
_Py_GetForceASCII(void)
{
    return 0;
}

void
_Py_ResetForceASCII(void)
{
    /* nothing to do */
}
#endif   /* !defined(_Py_FORCE_UTF8_FS_ENCODING) && !defined(MS_WINDOWS) */


#if !defined(HAVE_MBRTOWC) || defined(USE_FORCE_ASCII)
static int
decode_ascii(const char *arg, wchar_t **wstr, size_t *wlen,
             const char **reason, _Py_error_handler errors)
{
    wchar_t *res;
    unsigned char *in;
    wchar_t *out;
    size_t argsize = strlen(arg) + 1;

    int surrogateescape;
    if (get_surrogateescape(errors, &surrogateescape) < 0) {
        return -3;
    }

    if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t)) {
        return -1;
    }
    res = PyMem_RawMalloc(argsize * sizeof(wchar_t));
    if (!res) {
        return -1;
    }

    out = res;
    for (in = (unsigned char*)arg; *in; in++) {
        unsigned char ch = *in;
        if (ch < 128) {
            *out++ = ch;
        }
        else {
            if (!surrogateescape) {
                PyMem_RawFree(res);
                if (wlen) {
                    *wlen = in - (unsigned char*)arg;
                }
                if (reason) {
                    *reason = "decoding error";
                }
                return -2;
            }
            *out++ = 0xdc00 + ch;
        }
    }
    *out = 0;

    if (wlen != NULL) {
        *wlen = out - res;
    }
    *wstr = res;
    return 0;
}
#endif   /* !HAVE_MBRTOWC */

static int
decode_current_locale(const char* arg, wchar_t **wstr, size_t *wlen,
                      const char **reason, _Py_error_handler errors)
{
    wchar_t *res;
    size_t argsize;
    size_t count;
#ifdef HAVE_MBRTOWC
    unsigned char *in;
    wchar_t *out;
    mbstate_t mbs;
#endif

    int surrogateescape;
    if (get_surrogateescape(errors, &surrogateescape) < 0) {
        return -3;
    }

#ifdef HAVE_BROKEN_MBSTOWCS
    /* Some platforms have a broken implementation of
     * mbstowcs which does not count the characters that
     * would result from conversion.  Use an upper bound.
     */
    argsize = strlen(arg);
#else
    argsize = _Py_mbstowcs(NULL, arg, 0);
#endif
    if (argsize != DECODE_ERROR) {
        if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
            return -1;
        }
        res = (wchar_t *)PyMem_RawMalloc((argsize + 1) * sizeof(wchar_t));
        if (!res) {
            return -1;
        }

        count = _Py_mbstowcs(res, arg, argsize + 1);
        if (count != DECODE_ERROR) {
            *wstr = res;
            if (wlen != NULL) {
                *wlen = count;
            }
            return 0;
        }
        PyMem_RawFree(res);
    }

    /* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC
    /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */

    /* Overallocate; as multi-byte characters are in the argument, the
       actual output could use less memory. */
    argsize = strlen(arg) + 1;
    if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t)) {
        return -1;
    }
    res = (wchar_t*)PyMem_RawMalloc(argsize * sizeof(wchar_t));
    if (!res) {
        return -1;
    }

    in = (unsigned char*)arg;
    out = res;
    memset(&mbs, 0, sizeof mbs);
    while (argsize) {
        size_t converted = _Py_mbrtowc(out, (char*)in, argsize, &mbs);
        if (converted == 0) {
            /* Reached end of string; null char stored. */
            break;
        }

        if (converted == INCOMPLETE_CHARACTER) {
            /* Incomplete character. This should never happen,
               since we provide everything that we have -
               unless there is a bug in the C library, or I
               misunderstood how mbrtowc works. */
            goto decode_error;
        }

        if (converted == DECODE_ERROR) {
            if (!surrogateescape) {
                goto decode_error;
            }

            /* Decoding error. Escape as UTF-8b, and start over in the initial
               shift state. */
            *out++ = 0xdc00 + *in++;
            argsize--;
            memset(&mbs, 0, sizeof mbs);
            continue;
        }

        // _Py_mbrtowc() reject lone surrogate characters
        assert(!Py_UNICODE_IS_SURROGATE(*out));

        /* successfully converted some bytes */
        in += converted;
        argsize -= converted;
        out++;
    }
    if (wlen != NULL) {
        *wlen = out - res;
    }
    *wstr = res;
    return 0;

decode_error:
    PyMem_RawFree(res);
    if (wlen) {
        *wlen = in - (unsigned char*)arg;
    }
    if (reason) {
        *reason = "decoding error";
    }
    return -2;
#else   /* HAVE_MBRTOWC */
    /* Cannot use C locale for escaping; manually escape as if charset
       is ASCII (i.e. escape all bytes > 128. This will still roundtrip
       correctly in the locale's charset, which must be an ASCII superset. */
    return decode_ascii(arg, wstr, wlen, reason, errors);
#endif   /* HAVE_MBRTOWC */
}


/* Decode a byte string from the locale encoding.

   Use the strict error handler if 'surrogateescape' is zero.  Use the
   surrogateescape error handler if 'surrogateescape' is non-zero: undecodable
   bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence
   can be decoded as a surrogate character, escape the bytes using the
   surrogateescape error handler instead of decoding them.

   On success, return 0 and write the newly allocated wide character string into
   *wstr (use PyMem_RawFree() to free the memory). If wlen is not NULL, write
   the number of wide characters excluding the null character into *wlen.

   On memory allocation failure, return -1.

   On decoding error, return -2. If wlen is not NULL, write the start of
   invalid byte sequence in the input string into *wlen. If reason is not NULL,
   write the decoding error message into *reason.

   Return -3 if the error handler 'errors' is not supported.

   Use the Py_EncodeLocaleEx() function to encode the character string back to
   a byte string. */
int
_Py_DecodeLocaleEx(const char* arg, wchar_t **wstr, size_t *wlen,
                   const char **reason,
                   int current_locale, _Py_error_handler errors)
{
    if (current_locale) {
#ifdef _Py_FORCE_UTF8_LOCALE
        return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
                                errors);
#else
        return decode_current_locale(arg, wstr, wlen, reason, errors);
#endif
    }

#ifdef _Py_FORCE_UTF8_FS_ENCODING
    return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
                            errors);
#else
    int use_utf8 = (_PyRuntime.preconfig.utf8_mode >= 1);
#ifdef MS_WINDOWS
    use_utf8 |= (_PyRuntime.preconfig.legacy_windows_fs_encoding == 0);
#endif
    if (use_utf8) {
        return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
                                errors);
    }

#ifdef USE_FORCE_ASCII
    if (force_ascii == -1) {
        force_ascii = check_force_ascii();
    }

    if (force_ascii) {
        /* force ASCII encoding to workaround mbstowcs() issue */
        return decode_ascii(arg, wstr, wlen, reason, errors);
    }
#endif

    return decode_current_locale(arg, wstr, wlen, reason, errors);
#endif   /* !_Py_FORCE_UTF8_FS_ENCODING */
}


/* Decode a byte string from the locale encoding with the
   surrogateescape error handler: undecodable bytes are decoded as characters
   in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate
   character, escape the bytes using the surrogateescape error handler instead
   of decoding them.

   Return a pointer to a newly allocated wide character string, use
   PyMem_RawFree() to free the memory. If size is not NULL, write the number of
   wide characters excluding the null character into *size

   Return NULL on decoding error or memory allocation error. If *size* is not
   NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on
   decoding error.

   Decoding errors should never happen, unless there is a bug in the C
   library.

   Use the Py_EncodeLocale() function to encode the character string back to a
   byte string. */
wchar_t*
Py_DecodeLocale(const char* arg, size_t *wlen)
{
    wchar_t *wstr;
    int res = _Py_DecodeLocaleEx(arg, &wstr, wlen,
                                 NULL, 0,
                                 _Py_ERROR_SURROGATEESCAPE);
    if (res != 0) {
        assert(res != -3);
        if (wlen != NULL) {
            *wlen = (size_t)res;
        }
        return NULL;
    }
    return wstr;
}


static int
encode_current_locale(const wchar_t *text, char **str,
                      size_t *error_pos, const char **reason,
                      int raw_malloc, _Py_error_handler errors)
{
    const size_t len = wcslen(text);
    char *result = NULL, *bytes = NULL;
    size_t i, size, converted;
    wchar_t c, buf[2];

    int surrogateescape;
    if (get_surrogateescape(errors, &surrogateescape) < 0) {
        return -3;
    }

    /* The function works in two steps:
       1. compute the length of the output buffer in bytes (size)
       2. outputs the bytes */
    size = 0;
    buf[1] = 0;
    while (1) {
        for (i=0; i < len; i++) {
            c = text[i];
            if (c >= 0xdc80 && c <= 0xdcff) {
                if (!surrogateescape) {
                    goto encode_error;
                }
                /* UTF-8b surrogate */
                if (bytes != NULL) {
                    *bytes++ = c - 0xdc00;
                    size--;
                }
                else {
                    size++;
                }
                continue;
            }
            else {
                buf[0] = c;
                if (bytes != NULL) {
                    converted = wcstombs(bytes, buf, size);
                }
                else {
                    converted = wcstombs(NULL, buf, 0);
                }
                if (converted == DECODE_ERROR) {
                    goto encode_error;
                }
                if (bytes != NULL) {
                    bytes += converted;
                    size -= converted;
                }
                else {
                    size += converted;
                }
            }
        }
        if (result != NULL) {
            *bytes = '\0';
            break;
        }

        size += 1; /* nul byte at the end */
        if (raw_malloc) {
            result = PyMem_RawMalloc(size);
        }
        else {
            result = PyMem_Malloc(size);
        }
        if (result == NULL) {
            return -1;
        }
        bytes = result;
    }
    *str = result;
    return 0;

encode_error:
    if (raw_malloc) {
        PyMem_RawFree(result);
    }
    else {
        PyMem_Free(result);
    }
    if (error_pos != NULL) {
        *error_pos = i;
    }
    if (reason) {
        *reason = "encoding error";
    }
    return -2;
}


/* Encode a string to the locale encoding.

   Parameters:

   * raw_malloc: if non-zero, allocate memory using PyMem_RawMalloc() instead
     of PyMem_Malloc().
   * current_locale: if non-zero, use the current LC_CTYPE, otherwise use
     Python filesystem encoding.
   * errors: error handler like "strict" or "surrogateescape".

   Return value:

    0: success, *str is set to a newly allocated decoded string.
   -1: memory allocation failure
   -2: encoding error, set *error_pos and *reason (if set).
   -3: the error handler 'errors' is not supported.
 */
static int
encode_locale_ex(const wchar_t *text, char **str, size_t *error_pos,
                 const char **reason,
                 int raw_malloc, int current_locale, _Py_error_handler errors)
{
    if (current_locale) {
#ifdef _Py_FORCE_UTF8_LOCALE
        return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
                                raw_malloc, errors);
#else
        return encode_current_locale(text, str, error_pos, reason,
                                     raw_malloc, errors);
#endif
    }

#ifdef _Py_FORCE_UTF8_FS_ENCODING
    return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
                            raw_malloc, errors);
#else
    int use_utf8 = (_PyRuntime.preconfig.utf8_mode >= 1);
#ifdef MS_WINDOWS
    use_utf8 |= (_PyRuntime.preconfig.legacy_windows_fs_encoding == 0);
#endif
    if (use_utf8) {
        return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
                                raw_malloc, errors);
    }

#ifdef USE_FORCE_ASCII
    if (force_ascii == -1) {
        force_ascii = check_force_ascii();
    }

    if (force_ascii) {
        return encode_ascii(text, str, error_pos, reason,
                            raw_malloc, errors);
    }
#endif

    return encode_current_locale(text, str, error_pos, reason,
                                 raw_malloc, errors);
#endif   /* _Py_FORCE_UTF8_FS_ENCODING */
}

static char*
encode_locale(const wchar_t *text, size_t *error_pos,
              int raw_malloc, int current_locale)
{
    char *str;
    int res = encode_locale_ex(text, &str, error_pos, NULL,
                               raw_malloc, current_locale,
                               _Py_ERROR_SURROGATEESCAPE);
    if (res != -2 && error_pos) {
        *error_pos = (size_t)-1;
    }
    if (res != 0) {
        return NULL;
    }
    return str;
}

/* Encode a wide character string to the locale encoding with the
   surrogateescape error handler: surrogate characters in the range
   U+DC80..U+DCFF are converted to bytes 0x80..0xFF.

   Return a pointer to a newly allocated byte string, use PyMem_Free() to free
   the memory. Return NULL on encoding or memory allocation error.

   If error_pos is not NULL, *error_pos is set to (size_t)-1 on success, or set
   to the index of the invalid character on encoding error.

   Use the Py_DecodeLocale() function to decode the bytes string back to a wide
   character string. */
char*
Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
{
    return encode_locale(text, error_pos, 0, 0);
}


/* Similar to Py_EncodeLocale(), but result must be freed by PyMem_RawFree()
   instead of PyMem_Free(). */
char*
_Py_EncodeLocaleRaw(const wchar_t *text, size_t *error_pos)
{
    return encode_locale(text, error_pos, 1, 0);
}


int
_Py_EncodeLocaleEx(const wchar_t *text, char **str,
                   size_t *error_pos, const char **reason,
                   int current_locale, _Py_error_handler errors)
{
    return encode_locale_ex(text, str, error_pos, reason, 1,
                            current_locale, errors);
}


// Get the current locale encoding name:
//
// - Return "utf-8" if _Py_FORCE_UTF8_LOCALE macro is defined (ex: on Android)
// - Return "utf-8" if the UTF-8 Mode is enabled
// - On Windows, return the ANSI code page (ex: "cp1250")
// - Return "utf-8" if nl_langinfo(CODESET) returns an empty string.
// - Otherwise, return nl_langinfo(CODESET).
//
// Return NULL on memory allocation failure.
//
// See also config_get_locale_encoding()
wchar_t*
_Py_GetLocaleEncoding(void)
{
#ifdef _Py_FORCE_UTF8_LOCALE
    // On Android langinfo.h and CODESET are missing,
    // and UTF-8 is always used in mbstowcs() and wcstombs().
    return _PyMem_RawWcsdup(L"utf-8");
#else

#ifdef MS_WINDOWS
    wchar_t encoding[23];
    unsigned int ansi_codepage = GetACP();
    swprintf(encoding, Py_ARRAY_LENGTH(encoding), L"cp%u", ansi_codepage);
    encoding[Py_ARRAY_LENGTH(encoding) - 1] = 0;
    return _PyMem_RawWcsdup(encoding);
#else
    const char *encoding = nl_langinfo(CODESET);
    if (!encoding || encoding[0] == '\0') {
        // Use UTF-8 if nl_langinfo() returns an empty string. It can happen on
        // macOS if the LC_CTYPE locale is not supported.
        return _PyMem_RawWcsdup(L"utf-8");
    }

    wchar_t *wstr;
    int res = decode_current_locale(encoding, &wstr, NULL,
                                    NULL, _Py_ERROR_SURROGATEESCAPE);
    if (res < 0) {
        return NULL;
    }
    return wstr;
#endif  // !MS_WINDOWS

#endif  // !_Py_FORCE_UTF8_LOCALE
}


PyObject *
_Py_GetLocaleEncodingObject(void)
{
    wchar_t *encoding = _Py_GetLocaleEncoding();
    if (encoding == NULL) {
        PyErr_NoMemory();
        return NULL;
    }

    PyObject *str = PyUnicode_FromWideChar(encoding, -1);
    PyMem_RawFree(encoding);
    return str;
}

#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION

/* Check whether current locale uses Unicode as internal wchar_t form. */
int
_Py_LocaleUsesNonUnicodeWchar(void)
{
    /* Oracle Solaris uses non-Unicode internal wchar_t form for
       non-Unicode locales and hence needs conversion to UTF first. */
    char* codeset = nl_langinfo(CODESET);
    if (!codeset) {
        return 0;
    }
    /* 646 refers to ISO/IEC 646 standard that corresponds to ASCII encoding */
    return (strcmp(codeset, "UTF-8") != 0 && strcmp(codeset, "646") != 0);
}

static wchar_t *
_Py_ConvertWCharForm(const wchar_t *source, Py_ssize_t size,
                     const char *tocode, const char *fromcode)
{
    static_assert(sizeof(wchar_t) == 4, "wchar_t must be 32-bit");

    /* Ensure we won't overflow the size. */
    if (size > (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t))) {
        PyErr_NoMemory();
        return NULL;
    }

    /* the string doesn't have to be NULL terminated */
    wchar_t* target = PyMem_Malloc(size * sizeof(wchar_t));
    if (target == NULL) {
        PyErr_NoMemory();
        return NULL;
    }

    iconv_t cd = iconv_open(tocode, fromcode);
    if (cd == (iconv_t)-1) {
        PyErr_Format(PyExc_ValueError, "iconv_open() failed");
        PyMem_Free(target);
        return NULL;
    }

    char *inbuf = (char *) source;
    char *outbuf = (char *) target;
    size_t inbytesleft = sizeof(wchar_t) * size;
    size_t outbytesleft = inbytesleft;

    size_t ret = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
    if (ret == DECODE_ERROR) {
        PyErr_Format(PyExc_ValueError, "iconv() failed");
        PyMem_Free(target);
        iconv_close(cd);
        return NULL;
    }

    iconv_close(cd);
    return target;
}

/* Convert a wide character string to the UCS-4 encoded string. This
   is necessary on systems where internal form of wchar_t are not Unicode
   code points (e.g. Oracle Solaris).

   Return a pointer to a newly allocated string, use PyMem_Free() to free
   the memory. Return NULL and raise exception on conversion or memory
   allocation error. */
wchar_t *
_Py_DecodeNonUnicodeWchar(const wchar_t *native, Py_ssize_t size)
{
    return _Py_ConvertWCharForm(native, size, "UCS-4-INTERNAL", "wchar_t");
}

/* Convert a UCS-4 encoded string to native wide character string. This
   is necessary on systems where internal form of wchar_t are not Unicode
   code points (e.g. Oracle Solaris).

   The conversion is done in place. This can be done because both wchar_t
   and UCS-4 use 4-byte encoding, and one wchar_t symbol always correspond
   to a single UCS-4 symbol and vice versa. (This is true for Oracle Solaris,
   which is currently the only system using these functions; it doesn't have
   to be for other systems).

   Return 0 on success. Return -1 and raise exception on conversion
   or memory allocation error. */
int
_Py_EncodeNonUnicodeWchar_InPlace(wchar_t *unicode, Py_ssize_t size)
{
    wchar_t* result = _Py_ConvertWCharForm(unicode, size, "wchar_t", "UCS-4-INTERNAL");
    if (!result) {
        return -1;
    }
    memcpy(unicode, result, size * sizeof(wchar_t));
    PyMem_Free(result);
    return 0;
}
#endif /* HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION */

#ifdef MS_WINDOWS
static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */

static void
FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
{
    /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
    /* Cannot simply cast and dereference in_ptr,
       since it might not be aligned properly */
    __int64 in;
    memcpy(&in, in_ptr, sizeof(in));
    *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
    *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
}

static void
LARGE_INTEGER_to_time_t_nsec(LARGE_INTEGER *in_ptr, time_t *time_out, int* nsec_out)
{
    *nsec_out = (int)(in_ptr->QuadPart % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
    *time_out = Py_SAFE_DOWNCAST((in_ptr->QuadPart / 10000000) - secs_between_epochs, __int64, time_t);
}

void
_Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
{
    /* XXX endianness */
    __int64 out;
    out = time_in + secs_between_epochs;
    out = out * 10000000 + nsec_in / 100;
    memcpy(out_ptr, &out, sizeof(out));
}

/* Below, we *know* that ugo+r is 0444 */
#if _S_IREAD != 0400
#error Unsupported C library
#endif
static int
attributes_to_mode(DWORD attr)
{
    int m = 0;
    if (attr & FILE_ATTRIBUTE_DIRECTORY)
        m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
    else
        m |= _S_IFREG;
    if (attr & FILE_ATTRIBUTE_READONLY)
        m |= 0444;
    else
        m |= 0666;
    return m;
}


typedef union {
    FILE_ID_128 id;
    struct {
        uint64_t st_ino;
        uint64_t st_ino_high;
    };
} id_128_to_ino;


void
_Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
                           FILE_BASIC_INFO *basic_info, FILE_ID_INFO *id_info,
                           struct _Py_stat_struct *result)
{
    memset(result, 0, sizeof(*result));
    result->st_mode = attributes_to_mode(info->dwFileAttributes);
    result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
    result->st_dev = id_info ? id_info->VolumeSerialNumber : info->dwVolumeSerialNumber;
    result->st_rdev = 0;
    /* st_ctime is deprecated, but we preserve the legacy value in our caller, not here */
    if (basic_info) {
        LARGE_INTEGER_to_time_t_nsec(&basic_info->CreationTime, &result->st_birthtime, &result->st_birthtime_nsec);
        LARGE_INTEGER_to_time_t_nsec(&basic_info->ChangeTime, &result->st_ctime, &result->st_ctime_nsec);
        LARGE_INTEGER_to_time_t_nsec(&basic_info->LastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
        LARGE_INTEGER_to_time_t_nsec(&basic_info->LastAccessTime, &result->st_atime, &result->st_atime_nsec);
    } else {
        FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_birthtime, &result->st_birthtime_nsec);
        FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
        FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
    }
    result->st_nlink = info->nNumberOfLinks;

    if (id_info) {
        id_128_to_ino file_id;
        file_id.id = id_info->FileId;
        result->st_ino = file_id.st_ino;
        result->st_ino_high = file_id.st_ino_high;
    }
    if (!result->st_ino && !result->st_ino_high) {
        /* should only occur for DirEntry_from_find_data, in which case the
           index is likely to be zero anyway. */
        result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow;
    }

    /* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will
       open other name surrogate reparse points without traversing them. To
       detect/handle these, check st_file_attributes and st_reparse_tag. */
    result->st_reparse_tag = reparse_tag;
    if (info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
        reparse_tag == IO_REPARSE_TAG_SYMLINK) {
        /* set the bits that make this a symlink */
        result->st_mode = (result->st_mode & ~S_IFMT) | S_IFLNK;
    }
    result->st_file_attributes = info->dwFileAttributes;
}

void
_Py_stat_basic_info_to_stat(FILE_STAT_BASIC_INFORMATION *info,
                            struct _Py_stat_struct *result)
{
    memset(result, 0, sizeof(*result));
    result->st_mode = attributes_to_mode(info->FileAttributes);
    result->st_size = info->EndOfFile.QuadPart;
    LARGE_INTEGER_to_time_t_nsec(&info->CreationTime, &result->st_birthtime, &result->st_birthtime_nsec);
    LARGE_INTEGER_to_time_t_nsec(&info->ChangeTime, &result->st_ctime, &result->st_ctime_nsec);
    LARGE_INTEGER_to_time_t_nsec(&info->LastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
    LARGE_INTEGER_to_time_t_nsec(&info->LastAccessTime, &result->st_atime, &result->st_atime_nsec);
    result->st_nlink = info->NumberOfLinks;
    result->st_dev = info->VolumeSerialNumber.QuadPart;
    /* File systems with less than 128-bits zero pad into this field */
    id_128_to_ino file_id;
    file_id.id = info->FileId128;
    result->st_ino = file_id.st_ino;
    result->st_ino_high = file_id.st_ino_high;
    /* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will
       open other name surrogate reparse points without traversing them. To
       detect/handle these, check st_file_attributes and st_reparse_tag. */
    result->st_reparse_tag = info->ReparseTag;
    if (info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
        info->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
        /* set the bits that make this a symlink */
        result->st_mode = (result->st_mode & ~S_IFMT) | S_IFLNK;
    }
    result->st_file_attributes = info->FileAttributes;
    switch (info->DeviceType) {
    case FILE_DEVICE_DISK:
    case FILE_DEVICE_VIRTUAL_DISK:
    case FILE_DEVICE_DFS:
    case FILE_DEVICE_CD_ROM:
    case FILE_DEVICE_CONTROLLER:
    case FILE_DEVICE_DATALINK:
        break;
    case FILE_DEVICE_DISK_FILE_SYSTEM:
    case FILE_DEVICE_CD_ROM_FILE_SYSTEM:
    case FILE_DEVICE_NETWORK_FILE_SYSTEM:
        result->st_mode = (result->st_mode & ~S_IFMT) | 0x6000; /* _S_IFBLK */
        break;
    case FILE_DEVICE_CONSOLE:
    case FILE_DEVICE_NULL:
    case FILE_DEVICE_KEYBOARD:
    case FILE_DEVICE_MODEM:
    case FILE_DEVICE_MOUSE:
    case FILE_DEVICE_PARALLEL_PORT:
    case FILE_DEVICE_PRINTER:
    case FILE_DEVICE_SCREEN:
    case FILE_DEVICE_SERIAL_PORT:
    case FILE_DEVICE_SOUND:
        result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFCHR;
        break;
    case FILE_DEVICE_NAMED_PIPE:
        result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFIFO;
        break;
    default:
        if (info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFDIR;
        }
        break;
    }
}

#endif

/* Return information about a file.

   On POSIX, use fstat().

   On Windows, use GetFileType() and GetFileInformationByHandle() which support
   files larger than 2 GiB.  fstat() may fail with EOVERFLOW on files larger
   than 2 GiB because the file size type is a signed 32-bit integer: see issue
   #23152.

   On Windows, set the last Windows error and return nonzero on error. On
   POSIX, set errno and return nonzero on error. Fill status and return 0 on
   success. */
int
_Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
{
#ifdef MS_WINDOWS
    BY_HANDLE_FILE_INFORMATION info;
    FILE_BASIC_INFO basicInfo;
    FILE_ID_INFO idInfo;
    FILE_ID_INFO *pIdInfo = &idInfo;
    HANDLE h;
    int type;

    h = _Py_get_osfhandle_noraise(fd);

    if (h == INVALID_HANDLE_VALUE) {
        /* errno is already set by _get_osfhandle, but we also set
           the Win32 error for callers who expect that */
        SetLastError(ERROR_INVALID_HANDLE);
        return -1;
    }
    memset(status, 0, sizeof(*status));

    type = GetFileType(h);
    if (type == FILE_TYPE_UNKNOWN) {
        DWORD error = GetLastError();
        if (error != 0) {
            errno = winerror_to_errno(error);
            return -1;
        }
        /* else: valid but unknown file */
    }

    if (type != FILE_TYPE_DISK) {
        if (type == FILE_TYPE_CHAR)
            status->st_mode = _S_IFCHR;
        else if (type == FILE_TYPE_PIPE)
            status->st_mode = _S_IFIFO;
        return 0;
    }

    if (!GetFileInformationByHandle(h, &info) ||
        !GetFileInformationByHandleEx(h, FileBasicInfo, &basicInfo, sizeof(basicInfo))) {
        /* The Win32 error is already set, but we also set errno for
           callers who expect it */
        errno = winerror_to_errno(GetLastError());
        return -1;
    }

    if (!GetFileInformationByHandleEx(h, FileIdInfo, &idInfo, sizeof(idInfo))) {
        /* Failed to get FileIdInfo, so do not pass it along */
        pIdInfo = NULL;
    }

    _Py_attribute_data_to_stat(&info, 0, &basicInfo, pIdInfo, status);
    return 0;
#else
    return fstat(fd, status);
#endif
}

/* Return information about a file.

   On POSIX, use fstat().

   On Windows, use GetFileType() and GetFileInformationByHandle() which support
   files larger than 2 GiB.  fstat() may fail with EOVERFLOW on files larger
   than 2 GiB because the file size type is a signed 32-bit integer: see issue
   #23152.

   Raise an exception and return -1 on error. On Windows, set the last Windows
   error on error. On POSIX, set errno on error. Fill status and return 0 on
   success.

   Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
   to call fstat(). The caller must hold the GIL. */
int
_Py_fstat(int fd, struct _Py_stat_struct *status)
{
    int res;

    assert(PyGILState_Check());

    Py_BEGIN_ALLOW_THREADS
    res = _Py_fstat_noraise(fd, status);
    Py_END_ALLOW_THREADS

    if (res != 0) {
#ifdef MS_WINDOWS
        PyErr_SetFromWindowsErr(0);
#else
        PyErr_SetFromErrno(PyExc_OSError);
#endif
        return -1;
    }
    return 0;
}

/* Like _Py_stat() but with a raw filename. */
int
_Py_wstat(const wchar_t* path, struct stat *buf)
{
    int err;
#ifdef MS_WINDOWS
    struct _stat wstatbuf;
    err = _wstat(path, &wstatbuf);
    if (!err) {
        buf->st_mode = wstatbuf.st_mode;
    }
#else
    char *fname;
    fname = _Py_EncodeLocaleRaw(path, NULL);
    if (fname == NULL) {
        errno = EINVAL;
        return -1;
    }
    err = stat(fname, buf);
    PyMem_RawFree(fname);
#endif
    return err;
}


/* Call _wstat() on Windows, or encode the path to the filesystem encoding and
   call stat() otherwise. Only fill st_mode attribute on Windows.

   Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
   raised. */

int
_Py_stat(PyObject *path, struct stat *statbuf)
{
#ifdef MS_WINDOWS
    int err;

    wchar_t *wpath = PyUnicode_AsWideCharString(path, NULL);
    if (wpath == NULL)
        return -2;

    err = _Py_wstat(wpath, statbuf);
    PyMem_Free(wpath);
    return err;
#else
    int ret;
    PyObject *bytes;
    char *cpath;

    bytes = PyUnicode_EncodeFSDefault(path);
    if (bytes == NULL)
        return -2;

    /* check for embedded null bytes */
    if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
        Py_DECREF(bytes);
        return -2;
    }

    ret = stat(cpath, statbuf);
    Py_DECREF(bytes);
    return ret;
#endif
}

#ifdef MS_WINDOWS
// For some Windows API partitions, SetHandleInformation() is declared
// but none of the handle flags are defined.
#ifndef HANDLE_FLAG_INHERIT
#define HANDLE_FLAG_INHERIT 0x00000001
#endif
#endif

/* This function MUST be kept async-signal-safe on POSIX when raise=0. */
static int
get_inheritable(int fd, int raise)
{
#ifdef MS_WINDOWS
    HANDLE handle;
    DWORD flags;

    handle = _Py_get_osfhandle_noraise(fd);
    if (handle == INVALID_HANDLE_VALUE) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    if (!GetHandleInformation(handle, &flags)) {
        if (raise)
            PyErr_SetFromWindowsErr(0);
        return -1;
    }

    return (flags & HANDLE_FLAG_INHERIT);
#else
    int flags;

    flags = fcntl(fd, F_GETFD, 0);
    if (flags == -1) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }
    return !(flags & FD_CLOEXEC);
#endif
}

/* Get the inheritable flag of the specified file descriptor.
   Return 1 if the file descriptor can be inherited, 0 if it cannot,
   raise an exception and return -1 on error. */
int
_Py_get_inheritable(int fd)
{
    return get_inheritable(fd, 1);
}


/* This function MUST be kept async-signal-safe on POSIX when raise=0. */
static int
set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
{
#ifdef MS_WINDOWS
    HANDLE handle;
    DWORD flags;
#else
#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
    static int ioctl_works = -1;
    int request;
    int err;
#endif
    int flags, new_flags;
    int res;
#endif

    /* atomic_flag_works can only be used to make the file descriptor
       non-inheritable */
    assert(!(atomic_flag_works != NULL && inheritable));

    if (atomic_flag_works != NULL && !inheritable) {
        if (*atomic_flag_works == -1) {
            int isInheritable = get_inheritable(fd, raise);
            if (isInheritable == -1)
                return -1;
            *atomic_flag_works = !isInheritable;
        }

        if (*atomic_flag_works)
            return 0;
    }

#ifdef MS_WINDOWS
    handle = _Py_get_osfhandle_noraise(fd);
    if (handle == INVALID_HANDLE_VALUE) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    if (inheritable)
        flags = HANDLE_FLAG_INHERIT;
    else
        flags = 0;

    if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
        if (raise)
            PyErr_SetFromWindowsErr(0);
        return -1;
    }
    return 0;

#else

#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
    if (raise != 0 && _Py_atomic_load_int_relaxed(&ioctl_works) != 0) {
        /* fast-path: ioctl() only requires one syscall */
        /* caveat: raise=0 is an indicator that we must be async-signal-safe
         * thus avoid using ioctl() so we skip the fast-path. */
        if (inheritable)
            request = FIONCLEX;
        else
            request = FIOCLEX;
        err = ioctl(fd, request, NULL);
        if (!err) {
            if (_Py_atomic_load_int_relaxed(&ioctl_works) == -1) {
                _Py_atomic_store_int_relaxed(&ioctl_works, 1);
            }
            return 0;
        }

#ifdef O_PATH
        if (errno == EBADF) {
            // bpo-44849: On Linux and FreeBSD, ioctl(FIOCLEX) fails with EBADF
            // on O_PATH file descriptors. Fall through to the fcntl()
            // implementation.
        }
        else
#endif
        if (errno != ENOTTY && errno != EACCES) {
            if (raise)
                PyErr_SetFromErrno(PyExc_OSError);
            return -1;
        }
        else {
            /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
               device". The ioctl is declared but not supported by the kernel.
               Remember that ioctl() doesn't work. It is the case on
               Illumos-based OS for example.

               Issue #27057: When SELinux policy disallows ioctl it will fail
               with EACCES. While FIOCLEX is safe operation it may be
               unavailable because ioctl was denied altogether.
               This can be the case on Android. */
            _Py_atomic_store_int_relaxed(&ioctl_works, 0);
        }
        /* fallback to fcntl() if ioctl() does not work */
    }
#endif

    /* slow-path: fcntl() requires two syscalls */
    flags = fcntl(fd, F_GETFD);
    if (flags < 0) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    if (inheritable) {
        new_flags = flags & ~FD_CLOEXEC;
    }
    else {
        new_flags = flags | FD_CLOEXEC;
    }

    if (new_flags == flags) {
        /* FD_CLOEXEC flag already set/cleared: nothing to do */
        return 0;
    }

    res = fcntl(fd, F_SETFD, new_flags);
    if (res < 0) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }
    return 0;
#endif
}

/* Make the file descriptor non-inheritable.
   Return 0 on success, set errno and return -1 on error. */
static int
make_non_inheritable(int fd)
{
    return set_inheritable(fd, 0, 0, NULL);
}

/* Set the inheritable flag of the specified file descriptor.
   On success: return 0, on error: raise an exception and return -1.

   If atomic_flag_works is not NULL:

    * if *atomic_flag_works==-1, check if the inheritable is set on the file
      descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
      set the inheritable flag
    * if *atomic_flag_works==1: do nothing
    * if *atomic_flag_works==0: set inheritable flag to False

   Set atomic_flag_works to NULL if no atomic flag was used to create the
   file descriptor.

   atomic_flag_works can only be used to make a file descriptor
   non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
int
_Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
{
    return set_inheritable(fd, inheritable, 1, atomic_flag_works);
}

/* Same as _Py_set_inheritable() but on error, set errno and
   don't raise an exception.
   This function is async-signal-safe. */
int
_Py_set_inheritable_async_safe(int fd, int inheritable, int *atomic_flag_works)
{
    return set_inheritable(fd, inheritable, 0, atomic_flag_works);
}

static int
_Py_open_impl(const char *pathname, int flags, int gil_held)
{
    int fd;
    int async_err = 0;
#ifndef MS_WINDOWS
    int *atomic_flag_works;
#endif

#ifdef MS_WINDOWS
    flags |= O_NOINHERIT;
#elif defined(O_CLOEXEC)
    atomic_flag_works = &_Py_open_cloexec_works;
    flags |= O_CLOEXEC;
#else
    atomic_flag_works = NULL;
#endif

    if (gil_held) {
        PyObject *pathname_obj = PyUnicode_DecodeFSDefault(pathname);
        if (pathname_obj == NULL) {
            return -1;
        }
        if (PySys_Audit("open", "OOi", pathname_obj, Py_None, flags) < 0) {
            Py_DECREF(pathname_obj);
            return -1;
        }

        do {
            Py_BEGIN_ALLOW_THREADS
            fd = open(pathname, flags);
            Py_END_ALLOW_THREADS
        } while (fd < 0
                 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
        if (async_err) {
            Py_DECREF(pathname_obj);
            return -1;
        }
        if (fd < 0) {
            PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, pathname_obj, NULL);
            Py_DECREF(pathname_obj);
            return -1;
        }
        Py_DECREF(pathname_obj);
    }
    else {
        fd = open(pathname, flags);
        if (fd < 0)
            return -1;
    }

#ifndef MS_WINDOWS
    if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
        close(fd);
        return -1;
    }
#endif

    return fd;
}

/* Open a file with the specified flags (wrapper to open() function).
   Return a file descriptor on success. Raise an exception and return -1 on
   error.

   The file descriptor is created non-inheritable.

   When interrupted by a signal (open() fails with EINTR), retry the syscall,
   except if the Python signal handler raises an exception.

   Release the GIL to call open(). The caller must hold the GIL. */
int
_Py_open(const char *pathname, int flags)
{
    /* _Py_open() must be called with the GIL held. */
    assert(PyGILState_Check());
    return _Py_open_impl(pathname, flags, 1);
}

/* Open a file with the specified flags (wrapper to open() function).
   Return a file descriptor on success. Set errno and return -1 on error.

   The file descriptor is created non-inheritable.

   If interrupted by a signal, fail with EINTR. */
int
_Py_open_noraise(const char *pathname, int flags)
{
    return _Py_open_impl(pathname, flags, 0);
}

/* Open a file. Use _wfopen() on Windows, encode the path to the locale
   encoding and use fopen() otherwise.

   The file descriptor is created non-inheritable.

   If interrupted by a signal, fail with EINTR. */
FILE *
_Py_wfopen(const wchar_t *path, const wchar_t *mode)
{
    FILE *f;
    if (PySys_Audit("open", "uui", path, mode, 0) < 0) {
        return NULL;
    }
#ifndef MS_WINDOWS
    char *cpath;
    char cmode[10];
    size_t r;
    r = wcstombs(cmode, mode, 10);
    if (r == DECODE_ERROR || r >= 10) {
        errno = EINVAL;
        return NULL;
    }
    cpath = _Py_EncodeLocaleRaw(path, NULL);
    if (cpath == NULL) {
        return NULL;
    }
    f = fopen(cpath, cmode);
    PyMem_RawFree(cpath);
#else
    f = _wfopen(path, mode);
#endif
    if (f == NULL)
        return NULL;
    if (make_non_inheritable(fileno(f)) < 0) {
        fclose(f);
        return NULL;
    }
    return f;
}


/* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
   encoding and call fopen() otherwise.

   Return the new file object on success. Raise an exception and return NULL
   on error.

   The file descriptor is created non-inheritable.

   When interrupted by a signal (open() fails with EINTR), retry the syscall,
   except if the Python signal handler raises an exception.

   Release the GIL to call _wfopen() or fopen(). The caller must hold
   the GIL. */
FILE*
_Py_fopen_obj(PyObject *path, const char *mode)
{
    FILE *f;
    int async_err = 0;
#ifdef MS_WINDOWS
    wchar_t wmode[10];
    int usize;

    assert(PyGILState_Check());

    if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
        return NULL;
    }
    if (!PyUnicode_Check(path)) {
        PyErr_Format(PyExc_TypeError,
                     "str file path expected under Windows, got %R",
                     Py_TYPE(path));
        return NULL;
    }

    wchar_t *wpath = PyUnicode_AsWideCharString(path, NULL);
    if (wpath == NULL)
        return NULL;

    usize = MultiByteToWideChar(CP_ACP, 0, mode, -1,
                                wmode, Py_ARRAY_LENGTH(wmode));
    if (usize == 0) {
        PyErr_SetFromWindowsErr(0);
        PyMem_Free(wpath);
        return NULL;
    }

    do {
        Py_BEGIN_ALLOW_THREADS
        f = _wfopen(wpath, wmode);
        Py_END_ALLOW_THREADS
    } while (f == NULL
             && errno == EINTR && !(async_err = PyErr_CheckSignals()));
    int saved_errno = errno;
    PyMem_Free(wpath);
#else
    PyObject *bytes;
    const char *path_bytes;

    assert(PyGILState_Check());

    if (!PyUnicode_FSConverter(path, &bytes))
        return NULL;
    path_bytes = PyBytes_AS_STRING(bytes);

    if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
        Py_DECREF(bytes);
        return NULL;
    }

    do {
        Py_BEGIN_ALLOW_THREADS
        f = fopen(path_bytes, mode);
        Py_END_ALLOW_THREADS
    } while (f == NULL
             && errno == EINTR && !(async_err = PyErr_CheckSignals()));
    int saved_errno = errno;
    Py_DECREF(bytes);
#endif
    if (async_err)
        return NULL;

    if (f == NULL) {
        errno = saved_errno;
        PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
        return NULL;
    }

    if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
        fclose(f);
        return NULL;
    }
    return f;
}

/* Read count bytes from fd into buf.

   On success, return the number of read bytes, it can be lower than count.
   If the current file offset is at or past the end of file, no bytes are read,
   and read() returns zero.

   On error, raise an exception, set errno and return -1.

   When interrupted by a signal (read() fails with EINTR), retry the syscall.
   If the Python signal handler raises an exception, the function returns -1
   (the syscall is not retried).

   Release the GIL to call read(). The caller must hold the GIL. */
Py_ssize_t
_Py_read(int fd, void *buf, size_t count)
{
    Py_ssize_t n;
    int err;
    int async_err = 0;

    assert(PyGILState_Check());

    /* _Py_read() must not be called with an exception set, otherwise the
     * caller may think that read() was interrupted by a signal and the signal
     * handler raised an exception. */
    assert(!PyErr_Occurred());

    if (count > _PY_READ_MAX) {
        count = _PY_READ_MAX;
    }

    _Py_BEGIN_SUPPRESS_IPH
    do {
        Py_BEGIN_ALLOW_THREADS
        errno = 0;
#ifdef MS_WINDOWS
        _doserrno = 0;
        n = read(fd, buf, (int)count);
        // read() on a non-blocking empty pipe fails with EINVAL, which is
        // mapped from the Windows error code ERROR_NO_DATA.
        if (n < 0 && errno == EINVAL) {
            if (_doserrno == ERROR_NO_DATA) {
                errno = EAGAIN;
            }
        }
#else
        n = read(fd, buf, count);
#endif
        /* save/restore errno because PyErr_CheckSignals()
         * and PyErr_SetFromErrno() can modify it */
        err = errno;
        Py_END_ALLOW_THREADS
    } while (n < 0 && err == EINTR &&
            !(async_err = PyErr_CheckSignals()));
    _Py_END_SUPPRESS_IPH

    if (async_err) {
        /* read() was interrupted by a signal (failed with EINTR)
         * and the Python signal handler raised an exception */
        errno = err;
        assert(errno == EINTR && PyErr_Occurred());
        return -1;
    }
    if (n < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        errno = err;
        return -1;
    }

    return n;
}

static Py_ssize_t
_Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
{
    Py_ssize_t n;
    int err;
    int async_err = 0;

    _Py_BEGIN_SUPPRESS_IPH
#ifdef MS_WINDOWS
    if (count > 32767) {
        /* Issue #11395: the Windows console returns an error (12: not
           enough space error) on writing into stdout if stdout mode is
           binary and the length is greater than 66,000 bytes (or less,
           depending on heap usage). */
        if (gil_held) {
            Py_BEGIN_ALLOW_THREADS
            if (isatty(fd)) {
                count = 32767;
            }
            Py_END_ALLOW_THREADS
        } else {
            if (isatty(fd)) {
                count = 32767;
            }
        }
    }

#endif
    if (count > _PY_WRITE_MAX) {
        count = _PY_WRITE_MAX;
    }

    if (gil_held) {
        do {
            Py_BEGIN_ALLOW_THREADS
            errno = 0;
#ifdef MS_WINDOWS
            // write() on a non-blocking pipe fails with ENOSPC on Windows if
            // the pipe lacks available space for the entire buffer.
            int c = (int)count;
            do {
                _doserrno = 0;
                n = write(fd, buf, c);
                if (n >= 0 || errno != ENOSPC || _doserrno != 0) {
                    break;
                }
                errno = EAGAIN;
                c /= 2;
            } while (c > 0);
#else
            n = write(fd, buf, count);
#endif
            /* save/restore errno because PyErr_CheckSignals()
             * and PyErr_SetFromErrno() can modify it */
            err = errno;
            Py_END_ALLOW_THREADS
        } while (n < 0 && err == EINTR &&
                !(async_err = PyErr_CheckSignals()));
    }
    else {
        do {
            errno = 0;
#ifdef MS_WINDOWS
            // write() on a non-blocking pipe fails with ENOSPC on Windows if
            // the pipe lacks available space for the entire buffer.
            int c = (int)count;
            do {
                _doserrno = 0;
                n = write(fd, buf, c);
                if (n >= 0 || errno != ENOSPC || _doserrno != 0) {
                    break;
                }
                errno = EAGAIN;
                c /= 2;
            } while (c > 0);
#else
            n = write(fd, buf, count);
#endif
            err = errno;
        } while (n < 0 && err == EINTR);
    }
    _Py_END_SUPPRESS_IPH

    if (async_err) {
        /* write() was interrupted by a signal (failed with EINTR)
           and the Python signal handler raised an exception (if gil_held is
           nonzero). */
        errno = err;
        assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
        return -1;
    }
    if (n < 0) {
        if (gil_held)
            PyErr_SetFromErrno(PyExc_OSError);
        errno = err;
        return -1;
    }

    return n;
}

/* Write count bytes of buf into fd.

   On success, return the number of written bytes, it can be lower than count
   including 0. On error, raise an exception, set errno and return -1.

   When interrupted by a signal (write() fails with EINTR), retry the syscall.
   If the Python signal handler raises an exception, the function returns -1
   (the syscall is not retried).

   Release the GIL to call write(). The caller must hold the GIL. */
Py_ssize_t
_Py_write(int fd, const void *buf, size_t count)
{
    assert(PyGILState_Check());

    /* _Py_write() must not be called with an exception set, otherwise the
     * caller may think that write() was interrupted by a signal and the signal
     * handler raised an exception. */
    assert(!PyErr_Occurred());

    return _Py_write_impl(fd, buf, count, 1);
}

/* Write count bytes of buf into fd.
 *
 * On success, return the number of written bytes, it can be lower than count
 * including 0. On error, set errno and return -1.
 *
 * When interrupted by a signal (write() fails with EINTR), retry the syscall
 * without calling the Python signal handler. */
Py_ssize_t
_Py_write_noraise(int fd, const void *buf, size_t count)
{
    return _Py_write_impl(fd, buf, count, 0);
}

#ifdef HAVE_READLINK

/* Read value of symbolic link. Encode the path to the locale encoding, decode
   the result from the locale encoding.

   Return -1 on encoding error, on readlink() error, if the internal buffer is
   too short, on decoding error, or if 'buf' is too short. */
int
_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t buflen)
{
    char *cpath;
    char cbuf[MAXPATHLEN];
    size_t cbuf_len = Py_ARRAY_LENGTH(cbuf);
    wchar_t *wbuf;
    Py_ssize_t res;
    size_t r1;

    cpath = _Py_EncodeLocaleRaw(path, NULL);
    if (cpath == NULL) {
        errno = EINVAL;
        return -1;
    }
    res = readlink(cpath, cbuf, cbuf_len);
    PyMem_RawFree(cpath);
    if (res == -1) {
        return -1;
    }
    if ((size_t)res == cbuf_len) {
        errno = EINVAL;
        return -1;
    }
    cbuf[res] = '\0'; /* buf will be null terminated */
    wbuf = Py_DecodeLocale(cbuf, &r1);
    if (wbuf == NULL) {
        errno = EINVAL;
        return -1;
    }
    /* wbuf must have space to store the trailing NUL character */
    if (buflen <= r1) {
        PyMem_RawFree(wbuf);
        errno = EINVAL;
        return -1;
    }
    wcsncpy(buf, wbuf, buflen);
    PyMem_RawFree(wbuf);
    return (int)r1;
}
#endif

#ifdef HAVE_REALPATH

/* Return the canonicalized absolute pathname. Encode path to the locale
   encoding, decode the result from the locale encoding.

   Return NULL on encoding error, realpath() error, decoding error
   or if 'resolved_path' is too short. */
wchar_t*
_Py_wrealpath(const wchar_t *path,
              wchar_t *resolved_path, size_t resolved_path_len)
{
    char *cpath;
    char cresolved_path[MAXPATHLEN];
    wchar_t *wresolved_path;
    char *res;
    size_t r;
    cpath = _Py_EncodeLocaleRaw(path, NULL);
    if (cpath == NULL) {
        errno = EINVAL;
        return NULL;
    }
    res = realpath(cpath, cresolved_path);
    PyMem_RawFree(cpath);
    if (res == NULL)
        return NULL;

    wresolved_path = Py_DecodeLocale(cresolved_path, &r);
    if (wresolved_path == NULL) {
        errno = EINVAL;
        return NULL;
    }
    /* wresolved_path must have space to store the trailing NUL character */
    if (resolved_path_len <= r) {
        PyMem_RawFree(wresolved_path);
        errno = EINVAL;
        return NULL;
    }
    wcsncpy(resolved_path, wresolved_path, resolved_path_len);
    PyMem_RawFree(wresolved_path);
    return resolved_path;
}
#endif


int
_Py_isabs(const wchar_t *path)
{
#ifdef MS_WINDOWS
    const wchar_t *tail;
    HRESULT hr = PathCchSkipRoot(path, &tail);
    if (FAILED(hr) || path == tail) {
        return 0;
    }
    if (tail == &path[1] && (path[0] == SEP || path[0] == ALTSEP)) {
        // Exclude paths with leading SEP
        return 0;
    }
    if (tail == &path[2] && path[1] == L':') {
        // Exclude drive-relative paths (e.g. C:filename.ext)
        return 0;
    }
    return 1;
#else
    return (path[0] == SEP);
#endif
}


/* Get an absolute path.
   On error (ex: fail to get the current directory), return -1.
   On memory allocation failure, set *abspath_p to NULL and return 0.
   On success, return a newly allocated to *abspath_p to and return 0.
   The string must be freed by PyMem_RawFree(). */
int
_Py_abspath(const wchar_t *path, wchar_t **abspath_p)
{
    if (path[0] == '\0' || !wcscmp(path, L".")) {
        wchar_t cwd[MAXPATHLEN + 1];
        cwd[Py_ARRAY_LENGTH(cwd) - 1] = 0;
        if (!_Py_wgetcwd(cwd, Py_ARRAY_LENGTH(cwd) - 1)) {
            /* unable to get the current directory */
            return -1;
        }
        *abspath_p = _PyMem_RawWcsdup(cwd);
        return 0;
    }

    if (_Py_isabs(path)) {
        *abspath_p = _PyMem_RawWcsdup(path);
        return 0;
    }

#ifdef MS_WINDOWS
    return _PyOS_getfullpathname(path, abspath_p);
#else
    wchar_t cwd[MAXPATHLEN + 1];
    cwd[Py_ARRAY_LENGTH(cwd) - 1] = 0;
    if (!_Py_wgetcwd(cwd, Py_ARRAY_LENGTH(cwd) - 1)) {
        /* unable to get the current directory */
        return -1;
    }

    size_t cwd_len = wcslen(cwd);
    size_t path_len = wcslen(path);
    size_t len = cwd_len + 1 + path_len + 1;
    if (len <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
        *abspath_p = PyMem_RawMalloc(len * sizeof(wchar_t));
    }
    else {
        *abspath_p = NULL;
    }
    if (*abspath_p == NULL) {
        return 0;
    }

    wchar_t *abspath = *abspath_p;
    memcpy(abspath, cwd, cwd_len * sizeof(wchar_t));
    abspath += cwd_len;

    *abspath = (wchar_t)SEP;
    abspath++;

    memcpy(abspath, path, path_len * sizeof(wchar_t));
    abspath += path_len;

    *abspath = 0;
    return 0;
#endif
}

// The Windows Games API family implements the PathCch* APIs in the Xbox OS,
// but does not expose them yet. Load them dynamically until
// 1) they are officially exposed
// 2) we stop supporting older versions of the GDK which do not expose them
#if defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP)
HRESULT
PathCchSkipRoot(const wchar_t *path, const wchar_t **rootEnd)
{
    static int initialized = 0;
    typedef HRESULT(__stdcall *PPathCchSkipRoot) (PCWSTR pszPath,
                                                  PCWSTR *ppszRootEnd);
    static PPathCchSkipRoot _PathCchSkipRoot;

    if (initialized == 0) {
        HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL,
                                         LOAD_LIBRARY_SEARCH_SYSTEM32);
        if (pathapi) {
            _PathCchSkipRoot = (PPathCchSkipRoot)GetProcAddress(
                pathapi, "PathCchSkipRoot");
        }
        else {
            _PathCchSkipRoot = NULL;
        }
        initialized = 1;
    }

    if (!_PathCchSkipRoot) {
        return E_NOINTERFACE;
    }

    return _PathCchSkipRoot(path, rootEnd);
}

static HRESULT
PathCchCombineEx(wchar_t *buffer, size_t bufsize, const wchar_t *dirname,
                 const wchar_t *relfile, unsigned long flags)
{
    static int initialized = 0;
    typedef HRESULT(__stdcall *PPathCchCombineEx) (PWSTR pszPathOut,
                                                   size_t cchPathOut,
                                                   PCWSTR pszPathIn,
                                                   PCWSTR pszMore,
                                                   unsigned long dwFlags);
    static PPathCchCombineEx _PathCchCombineEx;

    if (initialized == 0) {
        HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL,
                                         LOAD_LIBRARY_SEARCH_SYSTEM32);
        if (pathapi) {
            _PathCchCombineEx = (PPathCchCombineEx)GetProcAddress(
                pathapi, "PathCchCombineEx");
        }
        else {
            _PathCchCombineEx = NULL;
        }
        initialized = 1;
    }

    if (!_PathCchCombineEx) {
        return E_NOINTERFACE;
    }

    return _PathCchCombineEx(buffer, bufsize, dirname, relfile, flags);
}

#endif /* defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP) */

void
_Py_skiproot(const wchar_t *path, Py_ssize_t size, Py_ssize_t *drvsize,
             Py_ssize_t *rootsize)
{
    assert(drvsize);
    assert(rootsize);
#ifndef MS_WINDOWS
#define IS_SEP(x) (*(x) == SEP)
    *drvsize = 0;
    if (!IS_SEP(&path[0])) {
        // Relative path, e.g.: 'foo'
        *rootsize = 0;
    }
    else if (!IS_SEP(&path[1]) || IS_SEP(&path[2])) {
        // Absolute path, e.g.: '/foo', '///foo', '////foo', etc.
        *rootsize = 1;
    }
    else {
        // Precisely two leading slashes, e.g.: '//foo'. Implementation defined per POSIX, see
        // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
        *rootsize = 2;
    }
#undef IS_SEP
#else
    const wchar_t *pEnd = size >= 0 ? &path[size] : NULL;
#define IS_END(x) (pEnd ? (x) == pEnd : !*(x))
#define IS_SEP(x) (*(x) == SEP || *(x) == ALTSEP)
#define SEP_OR_END(x) (IS_SEP(x) || IS_END(x))
    if (IS_SEP(&path[0])) {
        if (IS_SEP(&path[1])) {
            // Device drives, e.g. \\.\device or \\?\device
            // UNC drives, e.g. \\server\share or \\?\UNC\server\share
            Py_ssize_t idx;
            if (path[2] == L'?' && IS_SEP(&path[3]) &&
                (path[4] == L'U' || path[4] == L'u') &&
                (path[5] == L'N' || path[5] == L'n') &&
                (path[6] == L'C' || path[6] == L'c') &&
                IS_SEP(&path[7]))
            {
                idx = 8;
            }
            else {
                idx = 2;
            }
            while (!SEP_OR_END(&path[idx])) {
                idx++;
            }
            if (IS_END(&path[idx])) {
                *drvsize = idx;
                *rootsize = 0;
            }
            else {
                idx++;
                while (!SEP_OR_END(&path[idx])) {
                    idx++;
                }
                *drvsize = idx;
                if (IS_END(&path[idx])) {
                    *rootsize = 0;
                }
                else {
                    *rootsize = 1;
                }
            }
        }
        else {
            // Relative path with root, e.g. \Windows
            *drvsize = 0;
            *rootsize = 1;
        }
    }
    else if (!IS_END(&path[0]) && path[1] == L':') {
        *drvsize = 2;
        if (IS_SEP(&path[2])) {
            // Absolute drive-letter path, e.g. X:\Windows
            *rootsize = 1;
        }
        else {
            // Relative path with drive, e.g. X:Windows
            *rootsize = 0;
        }
    }
    else {
        // Relative path, e.g. Windows
        *drvsize = 0;
        *rootsize = 0;
    }
#undef SEP_OR_END
#undef IS_SEP
#undef IS_END
#endif
}

// The caller must ensure "buffer" is big enough.
static int
join_relfile(wchar_t *buffer, size_t bufsize,
             const wchar_t *dirname, const wchar_t *relfile)
{
#ifdef MS_WINDOWS
    if (FAILED(PathCchCombineEx(buffer, bufsize, dirname, relfile,
        PATHCCH_ALLOW_LONG_PATHS))) {
        return -1;
    }
#else
    assert(!_Py_isabs(relfile));
    size_t dirlen = wcslen(dirname);
    size_t rellen = wcslen(relfile);
    size_t maxlen = bufsize - 1;
    if (maxlen > MAXPATHLEN || dirlen >= maxlen || rellen >= maxlen - dirlen) {
        return -1;
    }
    if (dirlen == 0) {
        // We do not add a leading separator.
        wcscpy(buffer, relfile);
    }
    else {
        if (dirname != buffer) {
            wcscpy(buffer, dirname);
        }
        size_t relstart = dirlen;
        if (dirlen > 1 && dirname[dirlen - 1] != SEP) {
            buffer[dirlen] = SEP;
            relstart += 1;
        }
        wcscpy(&buffer[relstart], relfile);
    }
#endif
    return 0;
}

/* Join the two paths together, like os.path.join().  Return NULL
   if memory could not be allocated.  The caller is responsible
   for calling PyMem_RawFree() on the result. */
wchar_t *
_Py_join_relfile(const wchar_t *dirname, const wchar_t *relfile)
{
    assert(dirname != NULL && relfile != NULL);
#ifndef MS_WINDOWS
    assert(!_Py_isabs(relfile));
#endif
    size_t maxlen = wcslen(dirname) + 1 + wcslen(relfile);
    size_t bufsize = maxlen + 1;
    wchar_t *filename = PyMem_RawMalloc(bufsize * sizeof(wchar_t));
    if (filename == NULL) {
        return NULL;
    }
    assert(wcslen(dirname) < MAXPATHLEN);
    assert(wcslen(relfile) < MAXPATHLEN - wcslen(dirname));
    if (join_relfile(filename, bufsize, dirname, relfile) < 0) {
        PyMem_RawFree(filename);
        return NULL;
    }
    return filename;
}

/* Join the two paths together, like os.path.join().
     dirname: the target buffer with the dirname already in place,
              including trailing NUL
     relfile: this must be a relative path
     bufsize: total allocated size of the buffer
   Return -1 if anything is wrong with the path lengths. */
int
_Py_add_relfile(wchar_t *dirname, const wchar_t *relfile, size_t bufsize)
{
    assert(dirname != NULL && relfile != NULL);
    assert(bufsize > 0);
    return join_relfile(dirname, bufsize, dirname, relfile);
}


size_t
_Py_find_basename(const wchar_t *filename)
{
    for (size_t i = wcslen(filename); i > 0; --i) {
        if (filename[i] == SEP) {
            return i + 1;
        }
    }
    return 0;
}

/* In-place path normalisation. Returns the start of the normalized
   path, which will be within the original buffer. Guaranteed to not
   make the path longer, and will not fail. 'size' is the length of
   the path, if known. If -1, the first null character will be assumed
   to be the end of the path. 'normsize' will be set to contain the
   length of the resulting normalized path. */
wchar_t *
_Py_normpath_and_size(wchar_t *path, Py_ssize_t size, Py_ssize_t *normsize)
{
    assert(path != NULL);
    if ((size < 0 && !path[0]) || size == 0) {
        *normsize = 0;
        return path;
    }
    wchar_t *pEnd = size >= 0 ? &path[size] : NULL;
    wchar_t *p1 = path;     // sequentially scanned address in the path
    wchar_t *p2 = path;     // destination of a scanned character to be ljusted
    wchar_t *minP2 = path;  // the beginning of the destination range
    wchar_t lastC = L'\0';  // the last ljusted character, p2[-1] in most cases

#define IS_END(x) (pEnd ? (x) == pEnd : !*(x))
#ifdef ALTSEP
#define IS_SEP(x) (*(x) == SEP || *(x) == ALTSEP)
#else
#define IS_SEP(x) (*(x) == SEP)
#endif
#define SEP_OR_END(x) (IS_SEP(x) || IS_END(x))

    if (p1[0] == L'.' && IS_SEP(&p1[1])) {
        // Skip leading '.\'
        path = &path[2];
        while (IS_SEP(path)) {
            path++;
        }
        p1 = p2 = minP2 = path;
        lastC = SEP;
    }
    else {
        Py_ssize_t drvsize, rootsize;
        _Py_skiproot(path, size, &drvsize, &rootsize);
        if (drvsize || rootsize) {
            // Skip past root and update minP2
            p1 = &path[drvsize + rootsize];
#ifndef ALTSEP
            p2 = p1;
#else
            for (; p2 < p1; ++p2) {
                if (*p2 == ALTSEP) {
                    *p2 = SEP;
                }
            }
#endif
            minP2 = p2 - 1;
            lastC = *minP2;
#ifdef MS_WINDOWS
            if (lastC != SEP) {
                minP2++;
            }
#endif
        }
    }

    /* if pEnd is specified, check that. Else, check for null terminator */
    for (; !IS_END(p1); ++p1) {
        wchar_t c = *p1;
#ifdef ALTSEP
        if (c == ALTSEP) {
            c = SEP;
        }
#endif
        if (lastC == SEP) {
            if (c == L'.') {
                int sep_at_1 = SEP_OR_END(&p1[1]);
                int sep_at_2 = !sep_at_1 && SEP_OR_END(&p1[2]);
                if (sep_at_2 && p1[1] == L'.') {
                    wchar_t *p3 = p2;
                    while (p3 != minP2 && *--p3 == SEP) { }
                    while (p3 != minP2 && *(p3 - 1) != SEP) { --p3; }
                    if (p2 == minP2
                        || (p3[0] == L'.' && p3[1] == L'.' && IS_SEP(&p3[2])))
                    {
                        // Previous segment is also ../, so append instead.
                        // Relative path does not absorb ../ at minP2 as well.
                        *p2++ = L'.';
                        *p2++ = L'.';
                        lastC = L'.';
                    } else if (p3[0] == SEP) {
                        // Absolute path, so absorb segment
                        p2 = p3 + 1;
                    } else {
                        p2 = p3;
                    }
                    p1 += 1;
                } else if (sep_at_1) {
                } else {
                    *p2++ = lastC = c;
                }
            } else if (c == SEP) {
            } else {
                *p2++ = lastC = c;
            }
        } else {
            *p2++ = lastC = c;
        }
    }
    *p2 = L'\0';
    if (p2 != minP2) {
        while (--p2 != minP2 && *p2 == SEP) {
            *p2 = L'\0';
        }
    } else {
        --p2;
    }
    *normsize = p2 - path + 1;
#undef SEP_OR_END
#undef IS_SEP
#undef IS_END
    return path;
}

/* In-place path normalisation. Returns the start of the normalized
   path, which will be within the original buffer. Guaranteed to not
   make the path longer, and will not fail. 'size' is the length of
   the path, if known. If -1, the first null character will be assumed
   to be the end of the path. */
wchar_t *
_Py_normpath(wchar_t *path, Py_ssize_t size)
{
    Py_ssize_t norm_length;
    return _Py_normpath_and_size(path, size, &norm_length);
}


/* Get the current directory. buflen is the buffer size in wide characters
   including the null character. Decode the path from the locale encoding.

   Return NULL on getcwd() error, on decoding error, or if 'buf' is
   too short. */
wchar_t*
_Py_wgetcwd(wchar_t *buf, size_t buflen)
{
#ifdef MS_WINDOWS
    int ibuflen = (int)Py_MIN(buflen, INT_MAX);
    return _wgetcwd(buf, ibuflen);
#else
    char fname[MAXPATHLEN];
    wchar_t *wname;
    size_t len;

    if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
        return NULL;
    wname = Py_DecodeLocale(fname, &len);
    if (wname == NULL)
        return NULL;
    /* wname must have space to store the trailing NUL character */
    if (buflen <= len) {
        PyMem_RawFree(wname);
        return NULL;
    }
    wcsncpy(buf, wname, buflen);
    PyMem_RawFree(wname);
    return buf;
#endif
}

/* Duplicate a file descriptor. The new file descriptor is created as
   non-inheritable. Return a new file descriptor on success, raise an OSError
   exception and return -1 on error.

   The GIL is released to call dup(). The caller must hold the GIL. */
int
_Py_dup(int fd)
{
#ifdef MS_WINDOWS
    HANDLE handle;
#endif

    assert(PyGILState_Check());

#ifdef MS_WINDOWS
    handle = _Py_get_osfhandle(fd);
    if (handle == INVALID_HANDLE_VALUE)
        return -1;

    Py_BEGIN_ALLOW_THREADS
    _Py_BEGIN_SUPPRESS_IPH
    fd = dup(fd);
    _Py_END_SUPPRESS_IPH
    Py_END_ALLOW_THREADS
    if (fd < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    if (_Py_set_inheritable(fd, 0, NULL) < 0) {
        _Py_BEGIN_SUPPRESS_IPH
        close(fd);
        _Py_END_SUPPRESS_IPH
        return -1;
    }
#elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
    Py_BEGIN_ALLOW_THREADS
    _Py_BEGIN_SUPPRESS_IPH
    fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
    _Py_END_SUPPRESS_IPH
    Py_END_ALLOW_THREADS
    if (fd < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

#elif HAVE_DUP
    Py_BEGIN_ALLOW_THREADS
    _Py_BEGIN_SUPPRESS_IPH
    fd = dup(fd);
    _Py_END_SUPPRESS_IPH
    Py_END_ALLOW_THREADS
    if (fd < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    if (_Py_set_inheritable(fd, 0, NULL) < 0) {
        _Py_BEGIN_SUPPRESS_IPH
        close(fd);
        _Py_END_SUPPRESS_IPH
        return -1;
    }
#else
    errno = ENOTSUP;
    PyErr_SetFromErrno(PyExc_OSError);
    return -1;
#endif
    return fd;
}

#ifndef MS_WINDOWS
/* Get the blocking mode of the file descriptor.
   Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
   raise an exception and return -1 on error. */
int
_Py_get_blocking(int fd)
{
    int flags;
    _Py_BEGIN_SUPPRESS_IPH
    flags = fcntl(fd, F_GETFL, 0);
    _Py_END_SUPPRESS_IPH
    if (flags < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    return !(flags & O_NONBLOCK);
}

/* Set the blocking mode of the specified file descriptor.

   Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
   otherwise.

   Return 0 on success, raise an exception and return -1 on error. */
int
_Py_set_blocking(int fd, int blocking)
{
/* bpo-41462: On VxWorks, ioctl(FIONBIO) only works on sockets.
   Use fcntl() instead. */
#if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO) && !defined(__VXWORKS__)
    int arg = !blocking;
    if (ioctl(fd, FIONBIO, &arg) < 0)
        goto error;
#else
    int flags, res;

    _Py_BEGIN_SUPPRESS_IPH
    flags = fcntl(fd, F_GETFL, 0);
    if (flags >= 0) {
        if (blocking)
            flags = flags & (~O_NONBLOCK);
        else
            flags = flags | O_NONBLOCK;

        res = fcntl(fd, F_SETFL, flags);
    } else {
        res = -1;
    }
    _Py_END_SUPPRESS_IPH

    if (res < 0)
        goto error;
#endif
    return 0;

error:
    PyErr_SetFromErrno(PyExc_OSError);
    return -1;
}
#else   /* MS_WINDOWS */
int
_Py_get_blocking(int fd)
{
    HANDLE handle;
    DWORD mode;
    BOOL success;

    handle = _Py_get_osfhandle(fd);
    if (handle == INVALID_HANDLE_VALUE) {
        return -1;
    }

    Py_BEGIN_ALLOW_THREADS
    success = GetNamedPipeHandleStateW(handle, &mode,
                                       NULL, NULL, NULL, NULL, 0);
    Py_END_ALLOW_THREADS

    if (!success) {
        PyErr_SetFromWindowsErr(0);
        return -1;
    }

    return !(mode & PIPE_NOWAIT);
}

int
_Py_set_blocking(int fd, int blocking)
{
    HANDLE handle;
    DWORD mode;
    BOOL success;

    handle = _Py_get_osfhandle(fd);
    if (handle == INVALID_HANDLE_VALUE) {
        return -1;
    }

    Py_BEGIN_ALLOW_THREADS
    success = GetNamedPipeHandleStateW(handle, &mode,
                                       NULL, NULL, NULL, NULL, 0);
    if (success) {
        if (blocking) {
            mode &= ~PIPE_NOWAIT;
        }
        else {
            mode |= PIPE_NOWAIT;
        }
        success = SetNamedPipeHandleState(handle, &mode, NULL, NULL);
    }
    Py_END_ALLOW_THREADS

    if (!success) {
        PyErr_SetFromWindowsErr(0);
        return -1;
    }
    return 0;
}

void*
_Py_get_osfhandle_noraise(int fd)
{
    void *handle;
    _Py_BEGIN_SUPPRESS_IPH
    handle = (void*)_get_osfhandle(fd);
    _Py_END_SUPPRESS_IPH
    return handle;
}

void*
_Py_get_osfhandle(int fd)
{
    void *handle = _Py_get_osfhandle_noraise(fd);
    if (handle == INVALID_HANDLE_VALUE)
        PyErr_SetFromErrno(PyExc_OSError);

    return handle;
}

int
_Py_open_osfhandle_noraise(void *handle, int flags)
{
    int fd;
    _Py_BEGIN_SUPPRESS_IPH
    fd = _open_osfhandle((intptr_t)handle, flags);
    _Py_END_SUPPRESS_IPH
    return fd;
}

int
_Py_open_osfhandle(void *handle, int flags)
{
    int fd = _Py_open_osfhandle_noraise(handle, flags);
    if (fd == -1)
        PyErr_SetFromErrno(PyExc_OSError);

    return fd;
}
#endif  /* MS_WINDOWS */

int
_Py_GetLocaleconvNumeric(struct lconv *lc,
                         PyObject **decimal_point, PyObject **thousands_sep)
{
    assert(decimal_point != NULL);
    assert(thousands_sep != NULL);

#ifndef MS_WINDOWS
    int change_locale = 0;
    if ((strlen(lc->decimal_point) > 1 || ((unsigned char)lc->decimal_point[0]) > 127)) {
        change_locale = 1;
    }
    if ((strlen(lc->thousands_sep) > 1 || ((unsigned char)lc->thousands_sep[0]) > 127)) {
        change_locale = 1;
    }

    /* Keep a copy of the LC_CTYPE locale */
    char *oldloc = NULL, *loc = NULL;
    if (change_locale) {
        oldloc = setlocale(LC_CTYPE, NULL);
        if (!oldloc) {
            PyErr_SetString(PyExc_RuntimeWarning,
                            "failed to get LC_CTYPE locale");
            return -1;
        }

        oldloc = _PyMem_Strdup(oldloc);
        if (!oldloc) {
            PyErr_NoMemory();
            return -1;
        }

        loc = setlocale(LC_NUMERIC, NULL);
        if (loc != NULL && strcmp(loc, oldloc) == 0) {
            loc = NULL;
        }

        if (loc != NULL) {
            /* Only set the locale temporarily the LC_CTYPE locale
               if LC_NUMERIC locale is different than LC_CTYPE locale and
               decimal_point and/or thousands_sep are non-ASCII or longer than
               1 byte */
            setlocale(LC_CTYPE, loc);
        }
    }

#define GET_LOCALE_STRING(ATTR) PyUnicode_DecodeLocale(lc->ATTR, NULL)
#else /* MS_WINDOWS */
/* Use _W_* fields of Windows strcut lconv */
#define GET_LOCALE_STRING(ATTR) PyUnicode_FromWideChar(lc->_W_ ## ATTR, -1)
#endif /* MS_WINDOWS */

    int res = -1;

    *decimal_point = GET_LOCALE_STRING(decimal_point);
    if (*decimal_point == NULL) {
        goto done;
    }

    *thousands_sep = GET_LOCALE_STRING(thousands_sep);
    if (*thousands_sep == NULL) {
        goto done;
    }

    res = 0;

done:
#ifndef MS_WINDOWS
    if (loc != NULL) {
        setlocale(LC_CTYPE, oldloc);
    }
    PyMem_Free(oldloc);
#endif
    return res;

#undef GET_LOCALE_STRING
}

/* Our selection logic for which function to use is as follows:
 * 1. If close_range(2) is available, always prefer that; it's better for
 *    contiguous ranges like this than fdwalk(3) which entails iterating over
 *    the entire fd space and simply doing nothing for those outside the range.
 * 2. If closefrom(2) is available, we'll attempt to use that next if we're
 *    closing up to sysconf(_SC_OPEN_MAX).
 * 2a. Fallback to fdwalk(3) if we're not closing up to sysconf(_SC_OPEN_MAX),
 *    as that will be more performant if the range happens to have any chunk of
 *    non-opened fd in the middle.
 * 2b. If fdwalk(3) isn't available, just do a plain close(2) loop.
 */
#ifdef HAVE_CLOSEFROM
#  define USE_CLOSEFROM
#endif /* HAVE_CLOSEFROM */

#ifdef HAVE_FDWALK
#  define USE_FDWALK
#endif /* HAVE_FDWALK */

#ifdef USE_FDWALK
static int
_fdwalk_close_func(void *lohi, int fd)
{
    int lo = ((int *)lohi)[0];
    int hi = ((int *)lohi)[1];

    if (fd >= hi) {
        return 1;
    }
    else if (fd >= lo) {
        /* Ignore errors */
        (void)close(fd);
    }
    return 0;
}
#endif /* USE_FDWALK */

/* Closes all file descriptors in [first, last], ignoring errors. */
void
_Py_closerange(int first, int last)
{
    first = Py_MAX(first, 0);
    _Py_BEGIN_SUPPRESS_IPH
#ifdef HAVE_CLOSE_RANGE
    if (close_range(first, last, 0) == 0) {
        /* close_range() ignores errors when it closes file descriptors.
         * Possible reasons of an error return are lack of kernel support
         * or denial of the underlying syscall by a seccomp sandbox on Linux.
         * Fallback to other methods in case of any error. */
    }
    else
#endif /* HAVE_CLOSE_RANGE */
#ifdef USE_CLOSEFROM
    if (last >= sysconf(_SC_OPEN_MAX)) {
        /* Any errors encountered while closing file descriptors are ignored */
        (void)closefrom(first);
    }
    else
#endif /* USE_CLOSEFROM */
#ifdef USE_FDWALK
    {
        int lohi[2];
        lohi[0] = first;
        lohi[1] = last + 1;
        fdwalk(_fdwalk_close_func, lohi);
    }
#else
    {
        for (int i = first; i <= last; i++) {
            /* Ignore errors */
            (void)close(i);
        }
    }
#endif /* USE_FDWALK */
    _Py_END_SUPPRESS_IPH
}


#ifndef MS_WINDOWS
// Ticks per second used by clock() and times() functions.
// See os.times() and time.process_time() implementations.
int
_Py_GetTicksPerSecond(long *ticks_per_second)
{
#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
    long value = sysconf(_SC_CLK_TCK);
    if (value < 1) {
        return -1;
    }
    *ticks_per_second = value;
#elif defined(HZ)
    assert(HZ >= 1);
    *ticks_per_second = HZ;
#else
    // Magic fallback value; may be bogus
    *ticks_per_second = 60;
#endif
    return 0;
}
#endif


/* Check if a file descriptor is valid or not.
   Return 0 if the file descriptor is invalid, return non-zero otherwise. */
int
_Py_IsValidFD(int fd)
{
/* dup() is faster than fstat(): fstat() can require input/output operations,
   whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
   startup. Problem: dup() doesn't check if the file descriptor is valid on
   some platforms.

   fcntl(fd, F_GETFD) is even faster, because it only checks the process table.
   It is preferred over dup() when available, since it cannot fail with the
   "too many open files" error (EMFILE).

   bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
   side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
   EBADF. FreeBSD has similar issue (bpo-32849).

   Only use dup() on Linux where dup() is enough to detect invalid FD
   (bpo-32849).
*/
    if (fd < 0) {
        return 0;
    }
#if defined(F_GETFD) && ( \
        defined(__linux__) || \
        defined(__APPLE__) || \
        (defined(__wasm__) && !defined(__wasi__)))
    return fcntl(fd, F_GETFD) >= 0;
#elif defined(__linux__)
    int fd2 = dup(fd);
    if (fd2 >= 0) {
        close(fd2);
    }
    return (fd2 >= 0);
#elif defined(MS_WINDOWS)
    HANDLE hfile;
    _Py_BEGIN_SUPPRESS_IPH
    hfile = (HANDLE)_get_osfhandle(fd);
    _Py_END_SUPPRESS_IPH
    return (hfile != INVALID_HANDLE_VALUE
            && GetFileType(hfile) != FILE_TYPE_UNKNOWN);
#else
    struct stat st;
    return (fstat(fd, &st) == 0);
#endif
}