fileutils.c 44.4 KB
Newer Older
Victor Stinner's avatar
Victor Stinner committed
1
#include "Python.h"
2
#include "osdefs.h"
3 4
#include <locale.h>

5
#ifdef MS_WINDOWS
6
#  include <malloc.h>
7 8
#  include <windows.h>
#endif
Victor Stinner's avatar
Victor Stinner committed
9

10 11 12 13
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif

14 15 16 17 18 19 20 21
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif /* HAVE_FCNTL_H */

22 23 24 25
#ifdef __APPLE__
extern wchar_t* _Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size);
#endif

26
#ifdef O_CLOEXEC
27
/* Does open() support the O_CLOEXEC flag? Possible values:
28 29 30 31 32

   -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

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

38 39 40
PyObject *
_Py_device_encoding(int fd)
{
41
#if defined(MS_WINDOWS)
42 43 44 45 46
    UINT cp;
#endif
    if (!_PyVerify_fd(fd) || !isatty(fd)) {
        Py_RETURN_NONE;
    }
47
#if defined(MS_WINDOWS)
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    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)
        return PyUnicode_FromFormat("cp%u", (unsigned int)cp);
#elif defined(CODESET)
    {
        char *codeset = nl_langinfo(CODESET);
        if (codeset != NULL && codeset[0] != 0)
            return PyUnicode_FromString(codeset);
    }
#endif
    Py_RETURN_NONE;
}

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#if !defined(__APPLE__) && !defined(MS_WINDOWS)
extern int _Py_normalize_encoding(const char *, char *, size_t);

/* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale.
   On these operating systems, 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.

Philip Jenvey's avatar
Philip Jenvey committed
85
   Values of force_ascii:
86

87 88
       1: the workaround is used: Py_EncodeLocale() uses
          encode_ascii_surrogateescape() and Py_DecodeLocale() uses
89
          decode_ascii_surrogateescape()
90 91
       0: the workaround is not used: Py_EncodeLocale() uses wcstombs() and
          Py_DecodeLocale() uses mbstowcs()
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
      -1: unknown, need to call check_force_ascii() to get the value
*/
static int force_ascii = -1;

static int
check_force_ascii(void)
{
    char *loc;
#if defined(HAVE_LANGINFO_H) && defined(CODESET)
    char *codeset, **alias;
    char encoding[100];
    int is_ascii;
    unsigned int i;
    char* ascii_aliases[] = {
        "ascii",
        "646",
        "ansi-x3.4-1968",
        "ansi-x3-4-1968",
        "ansi-x3.4-1986",
        "cp367",
        "csascii",
        "ibm367",
        "iso646-us",
        "iso-646.irv-1991",
        "iso-ir-6",
        "us",
        "us-ascii",
        NULL
    };
#endif

    loc = setlocale(LC_CTYPE, NULL);
    if (loc == NULL)
        goto error;
    if (strcmp(loc, "C") != 0) {
        /* the LC_CTYPE locale is different than C */
        return 0;
    }

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

    is_ascii = 0;
    for (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 (i=0x80; i<0xff; i++) {
        unsigned char ch;
        wchar_t wch;
        size_t res;

        ch = (unsigned char)i;
        res = mbstowcs(&wch, (char*)&ch, 1);
        if (res != (size_t)-1) {
            /* 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 */
    return 0;
#else
    /* nl_langinfo(CODESET) is not available: always force ASCII */
    return 1;
#endif

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

static char*
encode_ascii_surrogateescape(const wchar_t *text, size_t *error_pos)
{
    char *result = NULL, *out;
    size_t len, i;
    wchar_t ch;

    if (error_pos != NULL)
        *error_pos = (size_t)-1;

    len = wcslen(text);

    result = PyMem_Malloc(len + 1);  /* +1 for NUL byte */
    if (result == NULL)
        return NULL;

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

        if (ch <= 0x7f) {
            /* ASCII character */
            *out++ = (char)ch;
        }
        else if (0xdc80 <= ch && ch <= 0xdcff) {
            /* UTF-8b surrogate */
            *out++ = (char)(ch - 0xdc00);
        }
        else {
            if (error_pos != NULL)
                *error_pos = i;
            PyMem_Free(result);
            return NULL;
        }
    }
    *out = '\0';
    return result;
}
#endif   /* !defined(__APPLE__) && !defined(MS_WINDOWS) */

#if !defined(__APPLE__) && (!defined(MS_WINDOWS) || !defined(HAVE_MBRTOWC))
static wchar_t*
decode_ascii_surrogateescape(const char *arg, size_t *size)
{
    wchar_t *res;
    unsigned char *in;
    wchar_t *out;
225
    size_t argsize = strlen(arg) + 1;
226

227 228
    if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
        return NULL;
229
    res = PyMem_RawMalloc(argsize*sizeof(wchar_t));
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    if (!res)
        return NULL;

    in = (unsigned char*)arg;
    out = res;
    while(*in)
        if(*in < 128)
            *out++ = *in++;
        else
            *out++ = 0xdc00 + *in++;
    *out = 0;
    if (size != NULL)
        *size = out - res;
    return res;
}
#endif

Victor Stinner's avatar
Victor Stinner committed
247 248

/* Decode a byte string from the locale encoding with the
249 250
   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
Victor Stinner's avatar
Victor Stinner committed
251 252 253
   character, escape the bytes using the surrogateescape error handler instead
   of decoding them.

254 255 256
   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
Victor Stinner's avatar
Victor Stinner committed
257

258 259 260
   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.
261

262 263 264 265 266
   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. */
Victor Stinner's avatar
Victor Stinner committed
267
wchar_t*
268
Py_DecodeLocale(const char* arg, size_t *size)
Victor Stinner's avatar
Victor Stinner committed
269
{
270 271 272
#ifdef __APPLE__
    wchar_t *wstr;
    wstr = _Py_DecodeUTF8_surrogateescape(arg, strlen(arg));
273 274 275 276 277 278
    if (size != NULL) {
        if (wstr != NULL)
            *size = wcslen(wstr);
        else
            *size = (size_t)-1;
    }
279 280
    return wstr;
#else
Victor Stinner's avatar
Victor Stinner committed
281
    wchar_t *res;
282 283
    size_t argsize;
    size_t count;
284
#ifdef HAVE_MBRTOWC
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    unsigned char *in;
    wchar_t *out;
    mbstate_t mbs;
#endif

#ifndef MS_WINDOWS
    if (force_ascii == -1)
        force_ascii = check_force_ascii();

    if (force_ascii) {
        /* force ASCII encoding to workaround mbstowcs() issue */
        res = decode_ascii_surrogateescape(arg, size);
        if (res == NULL)
            goto oom;
        return res;
    }
#endif

Victor Stinner's avatar
Victor Stinner committed
303 304 305 306 307
#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.
     */
308
    argsize = strlen(arg);
Victor Stinner's avatar
Victor Stinner committed
309
#else
310
    argsize = mbstowcs(NULL, arg, 0);
Victor Stinner's avatar
Victor Stinner committed
311 312
#endif
    if (argsize != (size_t)-1) {
313 314 315 316 317
        if (argsize == PY_SSIZE_T_MAX)
            goto oom;
        argsize += 1;
        if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
            goto oom;
318
        res = (wchar_t *)PyMem_RawMalloc(argsize*sizeof(wchar_t));
Victor Stinner's avatar
Victor Stinner committed
319 320
        if (!res)
            goto oom;
321
        count = mbstowcs(res, arg, argsize);
Victor Stinner's avatar
Victor Stinner committed
322 323 324 325 326
        if (count != (size_t)-1) {
            wchar_t *tmp;
            /* Only use the result if it contains no
               surrogate characters. */
            for (tmp = res; *tmp != 0 &&
327
                         !Py_UNICODE_IS_SURROGATE(*tmp); tmp++)
Victor Stinner's avatar
Victor Stinner committed
328
                ;
329 330 331
            if (*tmp == 0) {
                if (size != NULL)
                    *size = count;
Victor Stinner's avatar
Victor Stinner committed
332
                return res;
333
            }
Victor Stinner's avatar
Victor Stinner committed
334
        }
335
        PyMem_RawFree(res);
Victor Stinner's avatar
Victor Stinner committed
336 337 338 339 340 341 342 343
    }
    /* 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;
344 345
    if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
        goto oom;
346
    res = (wchar_t*)PyMem_RawMalloc(argsize*sizeof(wchar_t));
347 348
    if (!res)
        goto oom;
Victor Stinner's avatar
Victor Stinner committed
349 350 351 352 353 354 355 356 357 358 359 360 361
    in = (unsigned char*)arg;
    out = res;
    memset(&mbs, 0, sizeof mbs);
    while (argsize) {
        size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
        if (converted == 0)
            /* Reached end of string; null char stored. */
            break;
        if (converted == (size_t)-2) {
            /* 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. */
362
            PyMem_RawFree(res);
363 364
            if (size != NULL)
                *size = (size_t)-2;
Victor Stinner's avatar
Victor Stinner committed
365 366 367 368 369 370 371 372 373 374
            return NULL;
        }
        if (converted == (size_t)-1) {
            /* Conversion error. Escape as UTF-8b, and start over
               in the initial shift state. */
            *out++ = 0xdc00 + *in++;
            argsize--;
            memset(&mbs, 0, sizeof mbs);
            continue;
        }
375
        if (Py_UNICODE_IS_SURROGATE(*out)) {
Victor Stinner's avatar
Victor Stinner committed
376 377 378 379 380 381 382 383 384 385 386 387
            /* Surrogate character.  Escape the original
               byte sequence with surrogateescape. */
            argsize -= converted;
            while (converted--)
                *out++ = 0xdc00 + *in++;
            continue;
        }
        /* successfully converted some bytes */
        in += converted;
        argsize -= converted;
        out++;
    }
388 389
    if (size != NULL)
        *size = out - res;
390
#else   /* HAVE_MBRTOWC */
Victor Stinner's avatar
Victor Stinner committed
391 392 393
    /* 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. */
394 395
    res = decode_ascii_surrogateescape(arg, size);
    if (res == NULL)
396
        goto oom;
397
#endif   /* HAVE_MBRTOWC */
Victor Stinner's avatar
Victor Stinner committed
398 399
    return res;
oom:
400 401
    if (size != NULL)
        *size = (size_t)-1;
Victor Stinner's avatar
Victor Stinner committed
402
    return NULL;
403
#endif   /* __APPLE__ */
Victor Stinner's avatar
Victor Stinner committed
404 405
}

406 407 408
/* 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.
Victor Stinner's avatar
Victor Stinner committed
409

410 411
   Return a pointer to a newly allocated byte string, use PyMem_Free() to free
   the memory. Return NULL on encoding or memory allocation error.
Victor Stinner's avatar
Victor Stinner committed
412

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

416 417
   Use the Py_DecodeLocale() function to decode the bytes string back to a wide
   character string. */
Victor Stinner's avatar
Victor Stinner committed
418
char*
419
Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
Victor Stinner's avatar
Victor Stinner committed
420
{
421 422 423 424 425 426
#ifdef __APPLE__
    Py_ssize_t len;
    PyObject *unicode, *bytes = NULL;
    char *cpath;

    unicode = PyUnicode_FromWideChar(text, wcslen(text));
427
    if (unicode == NULL)
428 429 430 431 432 433
        return NULL;

    bytes = _PyUnicode_AsUTF8String(unicode, "surrogateescape");
    Py_DECREF(unicode);
    if (bytes == NULL) {
        PyErr_Clear();
434 435
        if (error_pos != NULL)
            *error_pos = (size_t)-1;
436 437 438 439 440 441
        return NULL;
    }

    len = PyBytes_GET_SIZE(bytes);
    cpath = PyMem_Malloc(len+1);
    if (cpath == NULL) {
442
        PyErr_Clear();
443
        Py_DECREF(bytes);
444 445
        if (error_pos != NULL)
            *error_pos = (size_t)-1;
446 447 448 449 450 451
        return NULL;
    }
    memcpy(cpath, PyBytes_AsString(bytes), len + 1);
    Py_DECREF(bytes);
    return cpath;
#else   /* __APPLE__ */
Victor Stinner's avatar
Victor Stinner committed
452 453 454 455 456
    const size_t len = wcslen(text);
    char *result = NULL, *bytes = NULL;
    size_t i, size, converted;
    wchar_t c, buf[2];

457 458 459 460 461 462 463 464
#ifndef MS_WINDOWS
    if (force_ascii == -1)
        force_ascii = check_force_ascii();

    if (force_ascii)
        return encode_ascii_surrogateescape(text, error_pos);
#endif

Victor Stinner's avatar
Victor Stinner committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
    /* 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) {
                /* 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 == (size_t)-1) {
                    if (result != NULL)
                        PyMem_Free(result);
492 493
                    if (error_pos != NULL)
                        *error_pos = i;
Victor Stinner's avatar
Victor Stinner committed
494 495 496 497 498 499 500 501 502 503 504
                    return NULL;
                }
                if (bytes != NULL) {
                    bytes += converted;
                    size -= converted;
                }
                else
                    size += converted;
            }
        }
        if (result != NULL) {
505
            *bytes = '\0';
Victor Stinner's avatar
Victor Stinner committed
506 507 508 509 510
            break;
        }

        size += 1; /* nul byte at the end */
        result = PyMem_Malloc(size);
511 512 513
        if (result == NULL) {
            if (error_pos != NULL)
                *error_pos = (size_t)-1;
Victor Stinner's avatar
Victor Stinner committed
514
            return NULL;
515
        }
Victor Stinner's avatar
Victor Stinner committed
516 517 518
        bytes = result;
    }
    return result;
519
#endif   /* __APPLE__ */
Victor Stinner's avatar
Victor Stinner committed
520 521
}

522

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
#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);
}

void
539
_Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
{
    /* 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;
}

567
void
568 569
_Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
                           struct _Py_stat_struct *result)
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
{
    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 = info->dwVolumeSerialNumber;
    result->st_rdev = result->st_dev;
    FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_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;
    result->st_ino = (((__int64)info->nFileIndexHigh)<<32) + info->nFileIndexLow;
    if (reparse_tag == IO_REPARSE_TAG_SYMLINK) {
        /* first clear the S_IFMT bits */
        result->st_mode ^= (result->st_mode & S_IFMT);
        /* now set the bits that make this a symlink */
        result->st_mode |= S_IFLNK;
    }
    result->st_file_attributes = info->dwFileAttributes;
}
#endif

/* Return information about a file.

   On POSIX, use fstat().

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

   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. */
603
int
604
_Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
605 606 607 608 609 610 611 612 613 614 615
{
#ifdef MS_WINDOWS
    BY_HANDLE_FILE_INFORMATION info;
    HANDLE h;
    int type;

    if (!_PyVerify_fd(fd))
        h = INVALID_HANDLE_VALUE;
    else
        h = (HANDLE)_get_osfhandle(fd);

616 617
    /* Protocol violation: we explicitly clear errno, instead of
       setting it to a POSIX error. Callers should use GetLastError. */
618 619 620
    errno = 0;

    if (h == INVALID_HANDLE_VALUE) {
621 622 623
        /* This is really a C library error (invalid file handle).
           We set the Win32 error to the closes one matching. */
        SetLastError(ERROR_INVALID_HANDLE);
624 625
        return -1;
    }
626
    memset(status, 0, sizeof(*status));
627 628 629 630

    type = GetFileType(h);
    if (type == FILE_TYPE_UNKNOWN) {
        DWORD error = GetLastError();
631
        if (error != 0)
632 633 634 635 636 637
            return -1;
        /* else: valid but unknown file */
    }

    if (type != FILE_TYPE_DISK) {
        if (type == FILE_TYPE_CHAR)
638
            status->st_mode = _S_IFCHR;
639
        else if (type == FILE_TYPE_PIPE)
640
            status->st_mode = _S_IFIFO;
641 642 643 644 645 646 647
        return 0;
    }

    if (!GetFileInformationByHandle(h, &info)) {
        return -1;
    }

648
    _Py_attribute_data_to_stat(&info, 0, status);
649
    /* specific to fstat() */
650
    status->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
651 652
    return 0;
#else
653
    return fstat(fd, status);
654 655 656
#endif
}

657 658 659 660 661 662 663 664 665 666 667 668 669
/* Return information about a file.

   On POSIX, use fstat().

   On Windows, use GetFileType() and GetFileInformationByHandle() which support
   files larger than 2 GB.  fstat() may fail with EOVERFLOW on files larger
   than 2 GB because the file size type is an 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.

670 671
   Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
   to call fstat(). The caller must hold the GIL. */
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
int
_Py_fstat(int fd, struct _Py_stat_struct *status)
{
    int res;

    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;
}
691

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

695 696
   Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
   raised. */
Victor Stinner's avatar
Victor Stinner committed
697 698

int
699
_Py_stat(PyObject *path, struct stat *statbuf)
Victor Stinner's avatar
Victor Stinner committed
700 701 702 703
{
#ifdef MS_WINDOWS
    int err;
    struct _stat wstatbuf;
704
    wchar_t *wpath;
Victor Stinner's avatar
Victor Stinner committed
705

706 707
    wpath = PyUnicode_AsUnicode(path);
    if (wpath == NULL)
708
        return -2;
709
    err = _wstat(wpath, &wstatbuf);
Victor Stinner's avatar
Victor Stinner committed
710 711 712 713 714
    if (!err)
        statbuf->st_mode = wstatbuf.st_mode;
    return err;
#else
    int ret;
715
    PyObject *bytes = PyUnicode_EncodeFSDefault(path);
Victor Stinner's avatar
Victor Stinner committed
716
    if (bytes == NULL)
717
        return -2;
Victor Stinner's avatar
Victor Stinner committed
718 719 720 721 722 723
    ret = stat(PyBytes_AS_STRING(bytes), statbuf);
    Py_DECREF(bytes);
    return ret;
#endif
}

724

725
static int
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
get_inheritable(int fd, int raise)
{
#ifdef MS_WINDOWS
    HANDLE handle;
    DWORD flags;

    if (!_PyVerify_fd(fd)) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    handle = (HANDLE)_get_osfhandle(fd);
    if (handle == INVALID_HANDLE_VALUE) {
        if (raise)
741
            PyErr_SetFromErrno(PyExc_OSError);
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
        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.
766
   Return 1 if the file descriptor can be inherited, 0 if it cannot,
767 768 769 770 771 772 773 774 775 776 777 778 779
   raise an exception and return -1 on error. */
int
_Py_get_inheritable(int fd)
{
    return get_inheritable(fd, 1);
}

static int
set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
{
#ifdef MS_WINDOWS
    HANDLE handle;
    DWORD flags;
780 781 782
#else
#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
    static int ioctl_works = -1;
783 784
    int request;
    int err;
785
#endif
786 787 788 789 790 791 792 793 794 795
    int 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) {
796 797
            int isInheritable = get_inheritable(fd, raise);
            if (isInheritable == -1)
798
                return -1;
799
            *atomic_flag_works = !isInheritable;
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
        }

        if (*atomic_flag_works)
            return 0;
    }

#ifdef MS_WINDOWS
    if (!_PyVerify_fd(fd)) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    handle = (HANDLE)_get_osfhandle(fd);
    if (handle == INVALID_HANDLE_VALUE) {
        if (raise)
816
            PyErr_SetFromErrno(PyExc_OSError);
817 818 819 820 821 822 823 824 825 826 827 828 829 830
        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;

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
#else

#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
    if (ioctl_works != 0) {
        /* fast-path: ioctl() only requires one syscall */
        if (inheritable)
            request = FIONCLEX;
        else
            request = FIOCLEX;
        err = ioctl(fd, request, NULL);
        if (!err) {
            ioctl_works = 1;
            return 0;
        }

        if (errno != ENOTTY) {
            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. */
            ioctl_works = 0;
        }
        /* fallback to fcntl() if ioctl() does not work */
859
    }
860
#endif
861

862
    /* slow-path: fcntl() requires two syscalls */
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    flags = fcntl(fd, F_GETFD);
    if (flags < 0) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

    if (inheritable)
        flags &= ~FD_CLOEXEC;
    else
        flags |= FD_CLOEXEC;
    res = fcntl(fd, F_SETFD, flags);
    if (res < 0) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }
    return 0;
#endif
}

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

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
/* Set the inheritable flag of the specified file descriptor.
   On success: return 0, on error: raise an exception if raise is nonzero
   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);
}

915 916
static int
_Py_open_impl(const char *pathname, int flags, int gil_held)
917 918
{
    int fd;
919
    int async_err = 0;
920
#ifndef MS_WINDOWS
921
    int *atomic_flag_works;
922 923 924 925 926
#endif

#ifdef MS_WINDOWS
    flags |= O_NOINHERIT;
#elif defined(O_CLOEXEC)
927 928 929 930 931 932
    atomic_flag_works = &_Py_open_cloexec_works;
    flags |= O_CLOEXEC;
#else
    atomic_flag_works = NULL;
#endif

933
    if (gil_held) {
934 935 936 937 938 939 940 941
        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)
            return -1;
942 943 944 945 946 947 948 949 950 951 952 953 954
        if (fd < 0) {
            PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname);
            return -1;
        }
    }
    else {
        fd = open(pathname, flags);
        if (fd < 0)
            return -1;
    }

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

960 961 962
    return fd;
}

963 964 965 966 967 968
/* 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.

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

972
   Release the GIL to call open(). The caller must hold the GIL. */
973 974 975 976 977 978 979 980 981 982 983
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.

984 985 986
   The file descriptor is created non-inheritable.

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

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

996 997 998
   The file descriptor is created non-inheritable.

   If interrupted by a signal, fail with EINTR. */
Victor Stinner's avatar
Victor Stinner committed
999 1000 1001 1002
FILE *
_Py_wfopen(const wchar_t *path, const wchar_t *mode)
{
    FILE *f;
1003
#ifndef MS_WINDOWS
Victor Stinner's avatar
Victor Stinner committed
1004 1005 1006 1007 1008 1009 1010 1011
    char *cpath;
    char cmode[10];
    size_t r;
    r = wcstombs(cmode, mode, 10);
    if (r == (size_t)-1 || r >= 10) {
        errno = EINVAL;
        return NULL;
    }
1012
    cpath = Py_EncodeLocale(path, NULL);
Victor Stinner's avatar
Victor Stinner committed
1013 1014 1015 1016 1017
    if (cpath == NULL)
        return NULL;
    f = fopen(cpath, cmode);
    PyMem_Free(cpath);
#else
1018
    f = _wfopen(path, mode);
Victor Stinner's avatar
Victor Stinner committed
1019
#endif
1020 1021 1022 1023 1024 1025 1026
    if (f == NULL)
        return NULL;
    if (make_non_inheritable(fileno(f)) < 0) {
        fclose(f);
        return NULL;
    }
    return f;
Victor Stinner's avatar
Victor Stinner committed
1027 1028
}

1029 1030
/* Wrapper to fopen().

1031 1032 1033
   The file descriptor is created non-inheritable.

   If interrupted by a signal, fail with EINTR. */
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
FILE*
_Py_fopen(const char *pathname, const char *mode)
{
    FILE *f = fopen(pathname, mode);
    if (f == NULL)
        return NULL;
    if (make_non_inheritable(fileno(f)) < 0) {
        fclose(f);
        return NULL;
    }
    return f;
}
1046

1047
/* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
1048 1049 1050 1051 1052 1053
   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.
Victor Stinner's avatar
Victor Stinner committed
1054

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

1058 1059
   Release the GIL to call _wfopen() or fopen(). The caller must hold
   the GIL. */
Victor Stinner's avatar
Victor Stinner committed
1060
FILE*
1061
_Py_fopen_obj(PyObject *path, const char *mode)
Victor Stinner's avatar
Victor Stinner committed
1062
{
1063
    FILE *f;
1064
    int async_err = 0;
Victor Stinner's avatar
Victor Stinner committed
1065
#ifdef MS_WINDOWS
1066
    wchar_t *wpath;
Victor Stinner's avatar
Victor Stinner committed
1067 1068 1069
    wchar_t wmode[10];
    int usize;

1070 1071
    assert(PyGILState_Check());

1072 1073 1074 1075 1076 1077
    if (!PyUnicode_Check(path)) {
        PyErr_Format(PyExc_TypeError,
                     "str file path expected under Windows, got %R",
                     Py_TYPE(path));
        return NULL;
    }
1078 1079 1080 1081
    wpath = PyUnicode_AsUnicode(path);
    if (wpath == NULL)
        return NULL;

Victor Stinner's avatar
Victor Stinner committed
1082
    usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
1083 1084
    if (usize == 0) {
        PyErr_SetFromWindowsErr(0);
Victor Stinner's avatar
Victor Stinner committed
1085
        return NULL;
1086
    }
Victor Stinner's avatar
Victor Stinner committed
1087

1088 1089 1090 1091 1092 1093
    do {
        Py_BEGIN_ALLOW_THREADS
        f = _wfopen(wpath, wmode);
        Py_END_ALLOW_THREADS
    } while (f == NULL
             && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner's avatar
Victor Stinner committed
1094
#else
1095
    PyObject *bytes;
1096 1097 1098 1099
    char *path_bytes;

    assert(PyGILState_Check());

1100
    if (!PyUnicode_FSConverter(path, &bytes))
Victor Stinner's avatar
Victor Stinner committed
1101
        return NULL;
1102 1103
    path_bytes = PyBytes_AS_STRING(bytes);

1104 1105 1106 1107 1108 1109
    do {
        Py_BEGIN_ALLOW_THREADS
        f = fopen(path_bytes, mode);
        Py_END_ALLOW_THREADS
    } while (f == NULL
             && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1110

Victor Stinner's avatar
Victor Stinner committed
1111 1112
    Py_DECREF(bytes);
#endif
1113 1114 1115
    if (async_err)
        return NULL;

1116 1117
    if (f == NULL) {
        PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1118
        return NULL;
1119 1120 1121
    }

    if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
1122 1123 1124 1125
        fclose(f);
        return NULL;
    }
    return f;
Victor Stinner's avatar
Victor Stinner committed
1126 1127
}

1128
/* Read count bytes from fd into buf.
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

   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. */
1141 1142 1143 1144
Py_ssize_t
_Py_read(int fd, void *buf, size_t count)
{
    Py_ssize_t n;
1145
    int err;
1146 1147 1148 1149 1150 1151 1152
    int async_err = 0;

    /* _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());

1153
    if (!_PyVerify_fd(fd)) {
1154 1155
        /* save/restore errno because PyErr_SetFromErrno() can modify it */
        err = errno;
1156
        PyErr_SetFromErrno(PyExc_OSError);
1157
        errno = err;
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
        return -1;
    }

#ifdef MS_WINDOWS
    if (count > INT_MAX) {
        /* On Windows, the count parameter of read() is an int */
        count = INT_MAX;
    }
#else
    if (count > PY_SSIZE_T_MAX) {
        /* if count is greater than PY_SSIZE_T_MAX,
         * read() result is undefined */
        count = PY_SSIZE_T_MAX;
    }
#endif

    do {
        Py_BEGIN_ALLOW_THREADS
        errno = 0;
#ifdef MS_WINDOWS
        n = read(fd, buf, (int)count);
#else
        n = read(fd, buf, count);
#endif
1182 1183 1184
        /* save/restore errno because PyErr_CheckSignals()
         * and PyErr_SetFromErrno() can modify it */
        err = errno;
1185
        Py_END_ALLOW_THREADS
1186
    } while (n < 0 && err == EINTR &&
1187 1188 1189 1190 1191
            !(async_err = PyErr_CheckSignals()));

    if (async_err) {
        /* read() was interrupted by a signal (failed with EINTR)
         * and the Python signal handler raised an exception */
1192 1193
        errno = err;
        assert(errno == EINTR && PyErr_Occurred());
1194 1195 1196 1197
        return -1;
    }
    if (n < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
1198
        errno = err;
1199 1200 1201 1202 1203 1204
        return -1;
    }

    return n;
}

1205 1206
static Py_ssize_t
_Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
1207 1208
{
    Py_ssize_t n;
1209
    int err;
1210 1211 1212
    int async_err = 0;

    if (!_PyVerify_fd(fd)) {
1213 1214 1215 1216 1217 1218
        if (gil_held) {
            /* save/restore errno because PyErr_SetFromErrno() can modify it */
            err = errno;
            PyErr_SetFromErrno(PyExc_OSError);
            errno = err;
        }
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        return -1;
    }

#ifdef MS_WINDOWS
    if (count > 32767 && isatty(fd)) {
        /* 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). */
        count = 32767;
    }
    else if (count > INT_MAX)
        count = INT_MAX;
#else
    if (count > PY_SSIZE_T_MAX) {
        /* write() should truncate count to PY_SSIZE_T_MAX, but it's safer
         * to do it ourself to have a portable behaviour. */
        count = PY_SSIZE_T_MAX;
    }
#endif

1240 1241 1242 1243
    if (gil_held) {
        do {
            Py_BEGIN_ALLOW_THREADS
            errno = 0;
1244
#ifdef MS_WINDOWS
1245
            n = write(fd, buf, (int)count);
1246
#else
1247
            n = write(fd, buf, count);
1248
#endif
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
            /* 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
            n = write(fd, buf, (int)count);
#else
            n = write(fd, buf, count);
#endif
            err = errno;
        } while (n < 0 && err == EINTR);
    }
1267 1268 1269

    if (async_err) {
        /* write() was interrupted by a signal (failed with EINTR)
1270 1271
           and the Python signal handler raised an exception (if gil_held is
           nonzero). */
1272
        errno = err;
1273
        assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
1274 1275 1276
        return -1;
    }
    if (n < 0) {
1277 1278
        if (gil_held)
            PyErr_SetFromErrno(PyExc_OSError);
1279
        errno = err;
1280 1281 1282 1283 1284 1285
        return -1;
    }

    return n;
}

1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
/* 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)
{
    /* _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);
}

Victor Stinner's avatar
Victor Stinner committed
1320
#ifdef HAVE_READLINK
1321 1322

/* Read value of symbolic link. Encode the path to the locale encoding, decode
1323
   the result from the locale encoding. Return -1 on error. */
1324

Victor Stinner's avatar
Victor Stinner committed
1325 1326 1327 1328
int
_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
{
    char *cpath;
1329
    char cbuf[MAXPATHLEN];
1330
    wchar_t *wbuf;
Victor Stinner's avatar
Victor Stinner committed
1331 1332 1333
    int res;
    size_t r1;

1334
    cpath = Py_EncodeLocale(path, NULL);
Victor Stinner's avatar
Victor Stinner committed
1335 1336 1337 1338
    if (cpath == NULL) {
        errno = EINVAL;
        return -1;
    }
1339
    res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf));
Victor Stinner's avatar
Victor Stinner committed
1340 1341 1342
    PyMem_Free(cpath);
    if (res == -1)
        return -1;
1343
    if (res == Py_ARRAY_LENGTH(cbuf)) {
Victor Stinner's avatar
Victor Stinner committed
1344 1345 1346 1347
        errno = EINVAL;
        return -1;
    }
    cbuf[res] = '\0'; /* buf will be null terminated */
1348
    wbuf = Py_DecodeLocale(cbuf, &r1);
1349 1350 1351 1352
    if (wbuf == NULL) {
        errno = EINVAL;
        return -1;
    }
1353
    if (bufsiz <= r1) {
1354
        PyMem_RawFree(wbuf);
Victor Stinner's avatar
Victor Stinner committed
1355 1356 1357
        errno = EINVAL;
        return -1;
    }
1358
    wcsncpy(buf, wbuf, bufsiz);
1359
    PyMem_RawFree(wbuf);
Victor Stinner's avatar
Victor Stinner committed
1360 1361 1362 1363 1364
    return (int)r1;
}
#endif

#ifdef HAVE_REALPATH
1365 1366

/* Return the canonicalized absolute pathname. Encode path to the locale
1367 1368
   encoding, decode the result from the locale encoding.
   Return NULL on error. */
1369

Victor Stinner's avatar
Victor Stinner committed
1370
wchar_t*
1371 1372
_Py_wrealpath(const wchar_t *path,
              wchar_t *resolved_path, size_t resolved_path_size)
Victor Stinner's avatar
Victor Stinner committed
1373 1374
{
    char *cpath;
1375
    char cresolved_path[MAXPATHLEN];
1376
    wchar_t *wresolved_path;
Victor Stinner's avatar
Victor Stinner committed
1377 1378
    char *res;
    size_t r;
1379
    cpath = Py_EncodeLocale(path, NULL);
Victor Stinner's avatar
Victor Stinner committed
1380 1381 1382 1383 1384 1385 1386 1387
    if (cpath == NULL) {
        errno = EINVAL;
        return NULL;
    }
    res = realpath(cpath, cresolved_path);
    PyMem_Free(cpath);
    if (res == NULL)
        return NULL;
1388

1389
    wresolved_path = Py_DecodeLocale(cresolved_path, &r);
1390 1391 1392 1393 1394
    if (wresolved_path == NULL) {
        errno = EINVAL;
        return NULL;
    }
    if (resolved_path_size <= r) {
1395
        PyMem_RawFree(wresolved_path);
Victor Stinner's avatar
Victor Stinner committed
1396 1397 1398
        errno = EINVAL;
        return NULL;
    }
1399
    wcsncpy(resolved_path, wresolved_path, resolved_path_size);
1400
    PyMem_RawFree(wresolved_path);
Victor Stinner's avatar
Victor Stinner committed
1401 1402 1403 1404
    return resolved_path;
}
#endif

1405
/* Get the current directory. size is the buffer size in wide characters
1406 1407
   including the null character. Decode the path from the locale encoding.
   Return NULL on error. */
1408

Victor Stinner's avatar
Victor Stinner committed
1409 1410 1411 1412
wchar_t*
_Py_wgetcwd(wchar_t *buf, size_t size)
{
#ifdef MS_WINDOWS
1413 1414
    int isize = (int)Py_MIN(size, INT_MAX);
    return _wgetcwd(buf, isize);
Victor Stinner's avatar
Victor Stinner committed
1415
#else
1416
    char fname[MAXPATHLEN];
1417
    wchar_t *wname;
1418
    size_t len;
1419

1420
    if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
Victor Stinner's avatar
Victor Stinner committed
1421
        return NULL;
1422
    wname = Py_DecodeLocale(fname, &len);
1423 1424
    if (wname == NULL)
        return NULL;
1425
    if (size <= len) {
1426
        PyMem_RawFree(wname);
Victor Stinner's avatar
Victor Stinner committed
1427 1428
        return NULL;
    }
1429
    wcsncpy(buf, wname, size);
1430
    PyMem_RawFree(wname);
Victor Stinner's avatar
Victor Stinner committed
1431 1432 1433 1434
    return buf;
#endif
}

1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
/* 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;
    DWORD ftype;
#endif

    if (!_PyVerify_fd(fd)) {
        PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

#ifdef MS_WINDOWS
    handle = (HANDLE)_get_osfhandle(fd);
    if (handle == INVALID_HANDLE_VALUE) {
1456
        PyErr_SetFromErrno(PyExc_OSError);
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
        return -1;
    }

    /* get the file type, ignore the error if it failed */
    ftype = GetFileType(handle);

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

    /* Character files like console cannot be make non-inheritable */
    if (ftype != FILE_TYPE_CHAR) {
        if (_Py_set_inheritable(fd, 0, NULL) < 0) {
            close(fd);
            return -1;
        }
    }
#elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
    Py_BEGIN_ALLOW_THREADS
    fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
    Py_END_ALLOW_THREADS
    if (fd < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }

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

    if (_Py_set_inheritable(fd, 0, NULL) < 0) {
        close(fd);
        return -1;
    }
#endif
    return fd;
}

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
#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 = fcntl(fd, F_GETFL, 0);
    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)
{
#if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)
    int arg = !blocking;
    if (ioctl(fd, FIONBIO, &arg) < 0)
        goto error;
#else
    int flags, res;

    flags = fcntl(fd, F_GETFL, 0);
    if (flags < 0)
        goto error;

    if (blocking)
        flags = flags & (~O_NONBLOCK);
    else
        flags = flags | O_NONBLOCK;

    res = fcntl(fd, F_SETFL, flags);
    if (res < 0)
        goto error;
#endif
    return 0;

error:
    PyErr_SetFromErrno(PyExc_OSError);
    return -1;
}
#endif

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
#ifdef _MSC_VER
#if _MSC_VER >= 1900

/* This function lets the Windows CRT validate the file handle without
   terminating the process if it's invalid. */
int
_PyVerify_fd(int fd)
{
    intptr_t osh;
    /* Fast check for the only condition we know */
    if (fd < 0) {
        _set_errno(EBADF);
        return 0;
    }
    osh = _get_osfhandle(fd);
    return osh != (intptr_t)-1;
}

#elif _MSC_VER >= 1400
/* Legacy implementation of _PyVerify_fd while transitioning to
 * MSVC 14.0. This should eventually be removed. (issue23524)
 */

/* Microsoft CRT in VS2005 and higher will verify that a filehandle is
 * valid and raise an assertion if it isn't.
 * Normally, an invalid fd is likely to be a C program error and therefore
 * an assertion can be useful, but it does contradict the POSIX standard
 * which for write(2) states:
 *    "Otherwise, -1 shall be returned and errno set to indicate the error."
 *    "[EBADF] The fildes argument is not a valid file descriptor open for
 *     writing."
 * Furthermore, python allows the user to enter any old integer
 * as a fd and should merely raise a python exception on error.
 * The Microsoft CRT doesn't provide an official way to check for the
 * validity of a file descriptor, but we can emulate its internal behaviour
 * by using the exported __pinfo data member and knowledge of the
 * internal structures involved.
 * The structures below must be updated for each version of visual studio
 * according to the file internal.h in the CRT source, until MS comes
 * up with a less hacky way to do this.
 * (all of this is to avoid globally modifying the CRT behaviour using
 * _set_invalid_parameter_handler() and _CrtSetReportMode())
 */
/* The actual size of the structure is determined at runtime.
 * Only the first items must be present.
 */
typedef struct {
    intptr_t osfhnd;
    char osfile;
} my_ioinfo;

extern __declspec(dllimport) char * __pioinfo[];
#define IOINFO_L2E 5
#define IOINFO_ARRAYS 64
#define IOINFO_ARRAY_ELTS   (1 << IOINFO_L2E)
#define _NHANDLE_           (IOINFO_ARRAYS * IOINFO_ARRAY_ELTS)
#define FOPEN 0x01
#define _NO_CONSOLE_FILENO (intptr_t)-2

/* This function emulates what the windows CRT does to validate file handles */
int
_PyVerify_fd(int fd)
{
    const int i1 = fd >> IOINFO_L2E;
    const int i2 = fd & ((1 << IOINFO_L2E) - 1);

    static size_t sizeof_ioinfo = 0;

    /* Determine the actual size of the ioinfo structure,
     * as used by the CRT loaded in memory
     */
    if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) {
        sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS;
    }
    if (sizeof_ioinfo == 0) {
        /* This should not happen... */
        goto fail;
    }

    /* See that it isn't a special CLEAR fileno */
    if (fd != _NO_CONSOLE_FILENO) {
        /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that.  Instead
         * we check pointer validity and other info
         */
        if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) {
            /* finally, check that the file is open */
            my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo);
            if (info->osfile & FOPEN) {
                return 1;
            }
        }
    }
  fail:
    errno = EBADF;
    return 0;
}

#endif /* _MSC_VER >= 1900 || _MSC_VER >= 1400 */
#endif /* defined _MSC_VER */