Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Modules/posixmodule.c

    r2 r388  
    1212   as the compiler specific macro for the EMX port of gcc to OS/2. */
    1313
    14 /* See also ../Dos/dosmodule.c */
    15 
    1614#ifdef __APPLE__
    1715   /*
    18     * Step 1 of support for weak-linking a number of symbols existing on 
     16    * Step 1 of support for weak-linking a number of symbols existing on
    1917    * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
    2018    * at the end of this file for more information.
     
    3028#include "Python.h"
    3129#include "structseq.h"
     30#ifndef MS_WINDOWS
     31#include "posixmodule.h"
     32#endif
    3233
    3334#if defined(__VMS)
     
    7475
    7576#ifdef HAVE_SYS_WAIT_H
    76 #include <sys/wait.h>           /* For WNOHANG */
     77#include <sys/wait.h>           /* For WNOHANG */
    7778#endif
    7879
     
    102103#include <process.h>
    103104#else
    104 #if defined(__WATCOMC__) && !defined(__QNX__)           /* Watcom compiler */
     105#if defined(__WATCOMC__) && !defined(__QNX__)           /* Watcom compiler */
    105106#define HAVE_GETCWD     1
    106107#define HAVE_OPENDIR    1
    107 #define HAVE_SYSTEM     1
     108#define HAVE_SYSTEM     1
    108109#if defined(__OS2__)
    109110#define HAVE_EXECV      1
     
    112113#include <process.h>
    113114#else
    114 #ifdef __BORLANDC__             /* Borland compiler */
     115#ifdef __BORLANDC__             /* Borland compiler */
    115116#define HAVE_EXECV      1
    116117#define HAVE_GETCWD     1
     
    118119#define HAVE_PIPE       1
    119120#define HAVE_POPEN      1
    120 #define HAVE_SYSTEM     1
     121#define HAVE_SYSTEM     1
    121122#define HAVE_WAIT       1
    122123#else
    123 #ifdef _MSC_VER         /* Microsoft compiler */
     124#ifdef _MSC_VER         /* Microsoft compiler */
    124125#define HAVE_GETCWD     1
    125 #define HAVE_SPAWNV     1
     126#define HAVE_SPAWNV     1
    126127#define HAVE_EXECV      1
    127128#define HAVE_PIPE       1
    128129#define HAVE_POPEN      1
    129 #define HAVE_SYSTEM     1
    130 #define HAVE_CWAIT      1
    131 #define HAVE_FSYNC      1
     130#define HAVE_SYSTEM     1
     131#define HAVE_CWAIT      1
     132#define HAVE_FSYNC      1
    132133#define fsync _commit
    133134#else
    134135#if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS)
    135136/* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */
    136 #else                   /* all other compilers */
     137#else                   /* all other compilers */
    137138/* Unix functions that the configure script doesn't check for */
    138139#define HAVE_EXECV      1
    139140#define HAVE_FORK       1
    140 #if defined(__USLC__) && defined(__SCO_VERSION__)       /* SCO UDK Compiler */
     141#if defined(__USLC__) && defined(__SCO_VERSION__)       /* SCO UDK Compiler */
    141142#define HAVE_FORK1      1
    142143#endif
     
    153154#define HAVE_POPEN      1
    154155#endif
    155 #define HAVE_SYSTEM     1
     156#define HAVE_SYSTEM     1
    156157#define HAVE_WAIT       1
    157 #define HAVE_TTYNAME    1
     158#define HAVE_TTYNAME    1
    158159#endif  /* PYOS_OS2 && PYCC_GCC && __VMS */
    159160#endif  /* _MSC_VER */
     
    270271#endif
    271272#include "osdefs.h"
     273#include <malloc.h>
    272274#include <windows.h>
    273 #include <shellapi.h>   /* for ShellExecute() */
    274 #define popen   _popen
    275 #define pclose  _pclose
     275#include <shellapi.h>   /* for ShellExecute() */
     276#define popen   _popen
     277#define pclose  _pclose
    276278#endif /* _MSC_VER */
    277279
     
    338340#endif
    339341
    340 /* choose the appropriate stat and fstat functions and return structs */
    341 #undef STAT
    342 #if defined(MS_WIN64) || defined(MS_WINDOWS)
    343 #       define STAT win32_stat
    344 #       define FSTAT win32_fstat
    345 #       define STRUCT_STAT struct win32_stat
    346 #else
    347 #       define STAT stat
    348 #       define FSTAT fstat
    349 #       define STRUCT_STAT struct stat
    350 #endif
    351 
    352342#if defined(MAJOR_IN_MKDEV)
    353343#include <sys/mkdev.h>
     
    361351#endif
    362352
     353
     354#ifndef MS_WINDOWS
     355PyObject *
     356_PyInt_FromUid(uid_t uid)
     357{
     358    if (uid <= LONG_MAX)
     359        return PyInt_FromLong(uid);
     360    return PyLong_FromUnsignedLong(uid);
     361}
     362
     363PyObject *
     364_PyInt_FromGid(gid_t gid)
     365{
     366    if (gid <= LONG_MAX)
     367        return PyInt_FromLong(gid);
     368    return PyLong_FromUnsignedLong(gid);
     369}
     370
     371int
     372_Py_Uid_Converter(PyObject *obj, void *p)
     373{
     374    int overflow;
     375    long result;
     376    if (PyFloat_Check(obj)) {
     377        PyErr_SetString(PyExc_TypeError,
     378                        "integer argument expected, got float");
     379        return 0;
     380    }
     381    result = PyLong_AsLongAndOverflow(obj, &overflow);
     382    if (overflow < 0)
     383        goto OverflowDown;
     384    if (!overflow && result == -1) {
     385        /* error or -1 */
     386        if (PyErr_Occurred())
     387            return 0;
     388        *(uid_t *)p = (uid_t)-1;
     389    }
     390    else {
     391        /* unsigned uid_t */
     392        unsigned long uresult;
     393        if (overflow > 0) {
     394            uresult = PyLong_AsUnsignedLong(obj);
     395            if (PyErr_Occurred()) {
     396                if (PyErr_ExceptionMatches(PyExc_OverflowError))
     397                    goto OverflowUp;
     398                return 0;
     399            }
     400        } else {
     401            if (result < 0)
     402                goto OverflowDown;
     403            uresult = result;
     404        }
     405        if (sizeof(uid_t) < sizeof(long) &&
     406            (unsigned long)(uid_t)uresult != uresult)
     407            goto OverflowUp;
     408        *(uid_t *)p = (uid_t)uresult;
     409    }
     410    return 1;
     411
     412OverflowDown:
     413    PyErr_SetString(PyExc_OverflowError,
     414                    "user id is less than minimum");
     415    return 0;
     416
     417OverflowUp:
     418    PyErr_SetString(PyExc_OverflowError,
     419                    "user id is greater than maximum");
     420    return 0;
     421}
     422
     423int
     424_Py_Gid_Converter(PyObject *obj, void *p)
     425{
     426    int overflow;
     427    long result;
     428    if (PyFloat_Check(obj)) {
     429        PyErr_SetString(PyExc_TypeError,
     430                        "integer argument expected, got float");
     431        return 0;
     432    }
     433    result = PyLong_AsLongAndOverflow(obj, &overflow);
     434    if (overflow < 0)
     435        goto OverflowDown;
     436    if (!overflow && result == -1) {
     437        /* error or -1 */
     438        if (PyErr_Occurred())
     439            return 0;
     440        *(gid_t *)p = (gid_t)-1;
     441    }
     442    else {
     443        /* unsigned gid_t */
     444        unsigned long uresult;
     445        if (overflow > 0) {
     446            uresult = PyLong_AsUnsignedLong(obj);
     447            if (PyErr_Occurred()) {
     448                if (PyErr_ExceptionMatches(PyExc_OverflowError))
     449                    goto OverflowUp;
     450                return 0;
     451            }
     452        } else {
     453            if (result < 0)
     454                goto OverflowDown;
     455            uresult = result;
     456        }
     457        if (sizeof(gid_t) < sizeof(long) &&
     458            (unsigned long)(gid_t)uresult != uresult)
     459            goto OverflowUp;
     460        *(gid_t *)p = (gid_t)uresult;
     461    }
     462    return 1;
     463
     464OverflowDown:
     465    PyErr_SetString(PyExc_OverflowError,
     466                    "group id is less than minimum");
     467    return 0;
     468
     469OverflowUp:
     470    PyErr_SetString(PyExc_OverflowError,
     471                    "group id is greater than maximum");
     472    return 0;
     473}
     474#endif /* MS_WINDOWS */
     475
     476
     477#if defined _MSC_VER && _MSC_VER >= 1400
     478/* Microsoft CRT in VS2005 and higher will verify that a filehandle is
     479 * valid and raise an assertion if it isn't.
     480 * Normally, an invalid fd is likely to be a C program error and therefore
     481 * an assertion can be useful, but it does contradict the POSIX standard
     482 * which for write(2) states:
     483 *    "Otherwise, -1 shall be returned and errno set to indicate the error."
     484 *    "[EBADF] The fildes argument is not a valid file descriptor open for
     485 *     writing."
     486 * Furthermore, python allows the user to enter any old integer
     487 * as a fd and should merely raise a python exception on error.
     488 * The Microsoft CRT doesn't provide an official way to check for the
     489 * validity of a file descriptor, but we can emulate its internal behaviour
     490 * by using the exported __pinfo data member and knowledge of the
     491 * internal structures involved.
     492 * The structures below must be updated for each version of visual studio
     493 * according to the file internal.h in the CRT source, until MS comes
     494 * up with a less hacky way to do this.
     495 * (all of this is to avoid globally modifying the CRT behaviour using
     496 * _set_invalid_parameter_handler() and _CrtSetReportMode())
     497 */
     498/* The actual size of the structure is determined at runtime.
     499 * Only the first items must be present.
     500 */
     501typedef struct {
     502    intptr_t osfhnd;
     503    char osfile;
     504} my_ioinfo;
     505
     506extern __declspec(dllimport) char * __pioinfo[];
     507#define IOINFO_L2E 5
     508#define IOINFO_ARRAY_ELTS   (1 << IOINFO_L2E)
     509#define IOINFO_ARRAYS 64
     510#define _NHANDLE_           (IOINFO_ARRAYS * IOINFO_ARRAY_ELTS)
     511#define FOPEN 0x01
     512#define _NO_CONSOLE_FILENO (intptr_t)-2
     513
     514/* This function emulates what the windows CRT does to validate file handles */
     515int
     516_PyVerify_fd(int fd)
     517{
     518    const int i1 = fd >> IOINFO_L2E;
     519    const int i2 = fd & ((1 << IOINFO_L2E) - 1);
     520
     521    static int sizeof_ioinfo = 0;
     522
     523    /* Determine the actual size of the ioinfo structure,
     524     * as used by the CRT loaded in memory
     525     */
     526    if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) {
     527        sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS;
     528    }
     529    if (sizeof_ioinfo == 0) {
     530        /* This should not happen... */
     531        goto fail;
     532    }
     533
     534    /* See that it isn't a special CLEAR fileno */
     535    if (fd != _NO_CONSOLE_FILENO) {
     536        /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that.  Instead
     537         * we check pointer validity and other info
     538         */
     539        if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) {
     540            /* finally, check that the file is open */
     541            my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo);
     542            if (info->osfile & FOPEN) {
     543                return 1;
     544            }
     545        }
     546    }
     547  fail:
     548    errno = EBADF;
     549    return 0;
     550}
     551
     552/* the special case of checking dup2.  The target fd must be in a sensible range */
     553static int
     554_PyVerify_fd_dup2(int fd1, int fd2)
     555{
     556    if (!_PyVerify_fd(fd1))
     557        return 0;
     558    if (fd2 == _NO_CONSOLE_FILENO)
     559        return 0;
     560    if ((unsigned)fd2 < _NHANDLE_)
     561        return 1;
     562    else
     563        return 0;
     564}
     565#else
     566/* dummy version. _PyVerify_fd() is already defined in fileobject.h */
     567#define _PyVerify_fd_dup2(A, B) (1)
     568#endif
     569
    363570/* Return a dictionary corresponding to the POSIX environment table */
    364 #ifdef WITH_NEXT_FRAMEWORK
     571#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
    365572/* On Darwin/MacOSX a shared library or framework has no access to
    366 ** environ directly, we must obtain it with _NSGetEnviron().
     573** environ directly, we must obtain it with _NSGetEnviron(). See also
     574** man environ(7).
    367575*/
    368576#include <crt_externs.h>
     
    375583convertenviron(void)
    376584{
    377         PyObject *d;
    378         char **e;
    379         d = PyDict_New();
    380         if (d == NULL)
    381                 return NULL;
    382 #ifdef WITH_NEXT_FRAMEWORK
    383         if (environ == NULL)
    384                 environ = *_NSGetEnviron();
    385 #endif
    386         if (environ == NULL)
    387                 return d;
    388         /* This part ignores errors */
    389         for (e = environ; *e != NULL; e++) {
    390                 PyObject *k;
    391                 PyObject *v;
    392                 char *p = strchr(*e, '=');
    393                 if (p == NULL)
    394                         continue;
    395                 k = PyString_FromStringAndSize(*e, (int)(p-*e));
    396                 if (k == NULL) {
    397                         PyErr_Clear();
    398                         continue;
    399                 }
    400                 v = PyString_FromString(p+1);
    401                 if (v == NULL) {
    402                         PyErr_Clear();
    403                         Py_DECREF(k);
    404                         continue;
    405                 }
    406                 if (PyDict_GetItem(d, k) == NULL) {
    407                         if (PyDict_SetItem(d, k, v) != 0)
    408                                 PyErr_Clear();
    409                 }
    410                 Py_DECREF(k);
    411                 Py_DECREF(v);
    412         }
     585    PyObject *d;
     586    char **e;
    413587#if defined(PYOS_OS2)
    414     {
    415         APIRET rc;
    416         char   buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */
    417 
    418         rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH);
    419         if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
    420             PyObject *v = PyString_FromString(buffer);
    421                     PyDict_SetItemString(d, "BEGINLIBPATH", v);
    422             Py_DECREF(v);
     588    APIRET rc;
     589    char   buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */
     590#endif
     591    d = PyDict_New();
     592    if (d == NULL)
     593        return NULL;
     594#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
     595    if (environ == NULL)
     596        environ = *_NSGetEnviron();
     597#endif
     598    if (environ == NULL)
     599        return d;
     600    /* This part ignores errors */
     601    for (e = environ; *e != NULL; e++) {
     602        PyObject *k;
     603        PyObject *v;
     604        char *p = strchr(*e, '=');
     605        if (p == NULL)
     606            continue;
     607        k = PyString_FromStringAndSize(*e, (int)(p-*e));
     608        if (k == NULL) {
     609            PyErr_Clear();
     610            continue;
    423611        }
    424         rc = DosQueryExtLIBPATH(buffer, END_LIBPATH);
    425         if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */
    426             PyObject *v = PyString_FromString(buffer);
    427                     PyDict_SetItemString(d, "ENDLIBPATH", v);
    428             Py_DECREF(v);
     612        v = PyString_FromString(p+1);
     613        if (v == NULL) {
     614            PyErr_Clear();
     615            Py_DECREF(k);
     616            continue;
    429617        }
    430     }
    431 #endif
    432         return d;
     618        if (PyDict_GetItem(d, k) == NULL) {
     619            if (PyDict_SetItem(d, k, v) != 0)
     620                PyErr_Clear();
     621        }
     622        Py_DECREF(k);
     623        Py_DECREF(v);
     624    }
     625#if defined(PYOS_OS2)
     626    rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH);
     627    if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
     628        PyObject *v = PyString_FromString(buffer);
     629            PyDict_SetItemString(d, "BEGINLIBPATH", v);
     630        Py_DECREF(v);
     631    }
     632    rc = DosQueryExtLIBPATH(buffer, END_LIBPATH);
     633    if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */
     634        PyObject *v = PyString_FromString(buffer);
     635            PyDict_SetItemString(d, "ENDLIBPATH", v);
     636        Py_DECREF(v);
     637    }
     638#endif
     639    return d;
    433640}
    434641
     
    439646posix_error(void)
    440647{
    441         return PyErr_SetFromErrno(PyExc_OSError);
     648    return PyErr_SetFromErrno(PyExc_OSError);
    442649}
    443650static PyObject *
    444651posix_error_with_filename(char* name)
    445652{
    446         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
    447 }
    448 
    449 #ifdef Py_WIN_WIDE_FILENAMES
     653    return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
     654}
     655
     656#ifdef MS_WINDOWS
    450657static PyObject *
    451658posix_error_with_unicode_filename(Py_UNICODE* name)
    452659{
    453         return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name);
    454 }
    455 #endif /* Py_WIN_WIDE_FILENAMES */
     660    return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name);
     661}
     662#endif /* MS_WINDOWS */
    456663
    457664
     
    459666posix_error_with_allocated_filename(char* name)
    460667{
    461         PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
    462         PyMem_Free(name);
    463         return rc;
     668    PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
     669    PyMem_Free(name);
     670    return rc;
    464671}
    465672
     
    468675win32_error(char* function, char* filename)
    469676{
    470         /* XXX We should pass the function name along in the future.
    471            (_winreg.c also wants to pass the function name.)
    472            This would however require an additional param to the
    473            Windows error object, which is non-trivial.
    474         */
    475         errno = GetLastError();
    476         if (filename)
    477                 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
    478         else
    479                 return PyErr_SetFromWindowsErr(errno);
    480 }
    481 
    482 #ifdef Py_WIN_WIDE_FILENAMES
     677    /* XXX We should pass the function name along in the future.
     678       (_winreg.c also wants to pass the function name.)
     679       This would however require an additional param to the
     680       Windows error object, which is non-trivial.
     681    */
     682    errno = GetLastError();
     683    if (filename)
     684        return PyErr_SetFromWindowsErrWithFilename(errno, filename);
     685    else
     686        return PyErr_SetFromWindowsErr(errno);
     687}
     688
    483689static PyObject *
    484690win32_error_unicode(char* function, Py_UNICODE* filename)
    485691{
    486         /* XXX - see win32_error for comments on 'function' */
    487         errno = GetLastError();
    488         if (filename)
    489                 return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename);
    490         else
    491                 return PyErr_SetFromWindowsErr(errno);
    492 }
    493 
    494 static PyObject *_PyUnicode_FromFileSystemEncodedObject(register PyObject *obj)
    495 {
     692    /* XXX - see win32_error for comments on 'function' */
     693    errno = GetLastError();
     694    if (filename)
     695        return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename);
     696    else
     697        return PyErr_SetFromWindowsErr(errno);
    496698}
    497699
     
    499701convert_to_unicode(PyObject **param)
    500702{
    501         if (PyUnicode_CheckExact(*param))
    502                 Py_INCREF(*param);
    503         else if (PyUnicode_Check(*param))
    504                 /* For a Unicode subtype that's not a Unicode object,
    505                    return a true Unicode object with the same data. */
    506                 *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param),
    507                                                PyUnicode_GET_SIZE(*param));
    508         else
    509                 *param = PyUnicode_FromEncodedObject(*param,
    510                                                      Py_FileSystemDefaultEncoding,
    511                                                      "strict");
    512         return (*param) != NULL;
    513 }
    514 
    515 #endif /* Py_WIN_WIDE_FILENAMES */
    516 
    517 #endif
     703    if (PyUnicode_CheckExact(*param))
     704        Py_INCREF(*param);
     705    else if (PyUnicode_Check(*param))
     706        /* For a Unicode subtype that's not a Unicode object,
     707           return a true Unicode object with the same data. */
     708        *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param),
     709                                       PyUnicode_GET_SIZE(*param));
     710    else
     711        *param = PyUnicode_FromEncodedObject(*param,
     712                                             Py_FileSystemDefaultEncoding,
     713                                             "strict");
     714    return (*param) != NULL;
     715}
     716
     717#endif /* MS_WINDOWS */
    518718
    519719#if defined(PYOS_OS2)
     
    521721 *         Helper Function to Trim and Format OS/2 Messages
    522722 **********************************************************************/
    523     static void
     723static void
    524724os2_formatmsg(char *msgbuf, int msglen, char *reason)
    525725{
     
    551751 *
    552752 **********************************************************************/
    553     static char *
     753static char *
    554754os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason)
    555755{
     
    567767    else
    568768        PyOS_snprintf(msgbuf, msgbuflen,
    569                       "unknown OS error #%d", errorcode);
     769                      "unknown OS error #%d", errorcode);
    570770
    571771    return msgbuf;
     
    576776   they congruent with posix error numbers. */
    577777
    578 static PyObject * os2_error(int code)
     778static PyObject *
     779os2_error(int code)
    579780{
    580781    char text[1024];
     
    598799posix_fildes(PyObject *fdobj, int (*func)(int))
    599800{
    600         int fd;
    601         int res;
    602         fd = PyObject_AsFileDescriptor(fdobj);
    603         if (fd < 0)
    604                 return NULL;
    605         Py_BEGIN_ALLOW_THREADS
    606         res = (*func)(fd);
    607         Py_END_ALLOW_THREADS
    608         if (res < 0)
    609                 return posix_error();
    610         Py_INCREF(Py_None);
    611         return Py_None;
    612 }
    613 
    614 #ifdef Py_WIN_WIDE_FILENAMES
    615 static int
    616 unicode_file_names(void)
    617 {
    618         static int canusewide = -1;
    619         if (canusewide == -1) {
    620                 /* As per doc for ::GetVersion(), this is the correct test for
    621                    the Windows NT family. */
    622                 canusewide = (GetVersion() < 0x80000000) ? 1 : 0;
    623         }
    624         return canusewide;
    625 }
    626 #endif
     801    int fd;
     802    int res;
     803    fd = PyObject_AsFileDescriptor(fdobj);
     804    if (fd < 0)
     805        return NULL;
     806    if (!_PyVerify_fd(fd))
     807        return posix_error();
     808    Py_BEGIN_ALLOW_THREADS
     809    res = (*func)(fd);
     810    Py_END_ALLOW_THREADS
     811    if (res < 0)
     812        return posix_error();
     813    Py_INCREF(Py_None);
     814    return Py_None;
     815}
    627816
    628817static PyObject *
    629818posix_1str(PyObject *args, char *format, int (*func)(const char*))
    630819{
    631         char *path1 = NULL;
    632         int res;
    633         if (!PyArg_ParseTuple(args, format,
    634                               Py_FileSystemDefaultEncoding, &path1))
    635                 return NULL;
    636         Py_BEGIN_ALLOW_THREADS
    637         res = (*func)(path1);
    638         Py_END_ALLOW_THREADS
    639         if (res < 0)
    640                 return posix_error_with_allocated_filename(path1);
    641         PyMem_Free(path1);
    642         Py_INCREF(Py_None);
    643         return Py_None;
     820    char *path1 = NULL;
     821    int res;
     822    if (!PyArg_ParseTuple(args, format,
     823                          Py_FileSystemDefaultEncoding, &path1))
     824        return NULL;
     825    Py_BEGIN_ALLOW_THREADS
     826    res = (*func)(path1);
     827    Py_END_ALLOW_THREADS
     828    if (res < 0)
     829        return posix_error_with_allocated_filename(path1);
     830    PyMem_Free(path1);
     831    Py_INCREF(Py_None);
     832    return Py_None;
    644833}
    645834
    646835static PyObject *
    647836posix_2str(PyObject *args,
    648            char *format,
    649            int (*func)(const char *, const char *))
    650 {
    651         char *path1 = NULL, *path2 = NULL;
    652         int res;
    653         if (!PyArg_ParseTuple(args, format,
    654                               Py_FileSystemDefaultEncoding, &path1,
    655                               Py_FileSystemDefaultEncoding, &path2))
    656                 return NULL;
    657         Py_BEGIN_ALLOW_THREADS
    658         res = (*func)(path1, path2);
    659         Py_END_ALLOW_THREADS
    660         PyMem_Free(path1);
    661         PyMem_Free(path2);
    662         if (res != 0)
    663                 /* XXX how to report both path1 and path2??? */
    664                 return posix_error();
    665         Py_INCREF(Py_None);
    666         return Py_None;
    667 }
    668 
    669 #ifdef Py_WIN_WIDE_FILENAMES
     837           char *format,
     838           int (*func)(const char *, const char *))
     839{
     840    char *path1 = NULL, *path2 = NULL;
     841    int res;
     842    if (!PyArg_ParseTuple(args, format,
     843                          Py_FileSystemDefaultEncoding, &path1,
     844                          Py_FileSystemDefaultEncoding, &path2))
     845        return NULL;
     846    Py_BEGIN_ALLOW_THREADS
     847    res = (*func)(path1, path2);
     848    Py_END_ALLOW_THREADS
     849    PyMem_Free(path1);
     850    PyMem_Free(path2);
     851    if (res != 0)
     852        /* XXX how to report both path1 and path2??? */
     853        return posix_error();
     854    Py_INCREF(Py_None);
     855    return Py_None;
     856}
     857
     858#ifdef MS_WINDOWS
    670859static PyObject*
    671 win32_1str(PyObject* args, char* func,
    672            char* format, BOOL (__stdcall *funcA)(LPCSTR),
    673            char* wformat, BOOL (__stdcall *funcW)(LPWSTR))
    674 {
    675         PyObject *uni;
    676         char *ansi;
    677         BOOL result;
    678         if (unicode_file_names()) {
    679                 if (!PyArg_ParseTuple(args, wformat, &uni))
    680                         PyErr_Clear();
    681                 else {
    682                         Py_BEGIN_ALLOW_THREADS
    683                         result = funcW(PyUnicode_AsUnicode(uni));
    684                         Py_END_ALLOW_THREADS
    685                         if (!result)
    686                                 return win32_error_unicode(func, PyUnicode_AsUnicode(uni));
    687                         Py_INCREF(Py_None);
    688                         return Py_None;
    689                 }
    690         }
    691         if (!PyArg_ParseTuple(args, format, &ansi))
    692                 return NULL;
    693         Py_BEGIN_ALLOW_THREADS
    694         result = funcA(ansi);
    695         Py_END_ALLOW_THREADS
    696         if (!result)
    697                 return win32_error(func, ansi);
    698         Py_INCREF(Py_None);
    699         return Py_None;
     860win32_1str(PyObject* args, char* func,
     861           char* format, BOOL (__stdcall *funcA)(LPCSTR),
     862           char* wformat, BOOL (__stdcall *funcW)(LPWSTR))
     863{
     864    PyObject *uni;
     865    char *ansi;
     866    BOOL result;
     867
     868    if (!PyArg_ParseTuple(args, wformat, &uni))
     869        PyErr_Clear();
     870    else {
     871        Py_BEGIN_ALLOW_THREADS
     872        result = funcW(PyUnicode_AsUnicode(uni));
     873        Py_END_ALLOW_THREADS
     874        if (!result)
     875            return win32_error_unicode(func, PyUnicode_AsUnicode(uni));
     876        Py_INCREF(Py_None);
     877        return Py_None;
     878    }
     879    if (!PyArg_ParseTuple(args, format, &ansi))
     880        return NULL;
     881    Py_BEGIN_ALLOW_THREADS
     882    result = funcA(ansi);
     883    Py_END_ALLOW_THREADS
     884    if (!result)
     885        return win32_error(func, ansi);
     886    Py_INCREF(Py_None);
     887    return Py_None;
    700888
    701889}
     
    706894   it also needs to set "magic" environment variables indicating
    707895   the per-drive current directory, which are of the form =<drive>: */
    708 BOOL __stdcall
     896static BOOL __stdcall
    709897win32_chdir(LPCSTR path)
    710898{
    711         char new_path[MAX_PATH+1];
    712         int result;
    713         char env[4] = "=x:";
    714 
    715         if(!SetCurrentDirectoryA(path))
    716                 return FALSE;
    717         result = GetCurrentDirectoryA(MAX_PATH+1, new_path);
    718         if (!result)
    719                 return FALSE;
    720         /* In the ANSI API, there should not be any paths longer
    721            than MAX_PATH. */
    722         assert(result <= MAX_PATH+1);
    723         if (strncmp(new_path, "\\\\", 2) == 0 ||
    724             strncmp(new_path, "//", 2) == 0)
    725             /* UNC path, nothing to do. */
    726             return TRUE;
    727         env[1] = new_path[0];
    728         return SetEnvironmentVariableA(env, new_path);
     899    char new_path[MAX_PATH+1];
     900    int result;
     901    char env[4] = "=x:";
     902
     903    if(!SetCurrentDirectoryA(path))
     904        return FALSE;
     905    result = GetCurrentDirectoryA(MAX_PATH+1, new_path);
     906    if (!result)
     907        return FALSE;
     908    /* In the ANSI API, there should not be any paths longer
     909       than MAX_PATH. */
     910    assert(result <= MAX_PATH+1);
     911    if (strncmp(new_path, "\\\\", 2) == 0 ||
     912        strncmp(new_path, "//", 2) == 0)
     913        /* UNC path, nothing to do. */
     914        return TRUE;
     915    env[1] = new_path[0];
     916    return SetEnvironmentVariableA(env, new_path);
    729917}
    730918
    731919/* The Unicode version differs from the ANSI version
    732920   since the current directory might exceed MAX_PATH characters */
    733 BOOL __stdcall
     921static BOOL __stdcall
    734922win32_wchdir(LPCWSTR path)
    735923{
    736         wchar_t _new_path[MAX_PATH+1], *new_path = _new_path;
    737         int result;
    738         wchar_t env[4] = L"=x:";
    739 
    740         if(!SetCurrentDirectoryW(path))
    741                 return FALSE;
    742         result = GetCurrentDirectoryW(MAX_PATH+1, new_path);
    743         if (!result)
    744                 return FALSE;
    745         if (result > MAX_PATH+1) {
    746                 new_path = malloc(result * sizeof(wchar_t));
    747                 if (!new_path) {
    748                         SetLastError(ERROR_OUTOFMEMORY);
    749                         return FALSE;
    750                 }
    751                 result = GetCurrentDirectoryW(result, new_path);
    752                 if (!result) {
    753                         free(new_path);
    754                         return FALSE;
    755                 }
    756         }
    757         if (wcsncmp(new_path, L"\\\\", 2) == 0 ||
    758             wcsncmp(new_path, L"//", 2) == 0)
    759             /* UNC path, nothing to do. */
    760             return TRUE;
    761         env[1] = new_path[0];
    762         result = SetEnvironmentVariableW(env, new_path);
    763         if (new_path != _new_path)
    764                 free(new_path);
    765         return result;
    766 }
     924    wchar_t _new_path[MAX_PATH+1], *new_path = _new_path;
     925    int result;
     926    wchar_t env[4] = L"=x:";
     927
     928    if(!SetCurrentDirectoryW(path))
     929        return FALSE;
     930    result = GetCurrentDirectoryW(MAX_PATH+1, new_path);
     931    if (!result)
     932        return FALSE;
     933    if (result > MAX_PATH+1) {
     934        new_path = malloc(result * sizeof(wchar_t));
     935        if (!new_path) {
     936            SetLastError(ERROR_OUTOFMEMORY);
     937            return FALSE;
     938        }
     939        result = GetCurrentDirectoryW(result, new_path);
     940        if (!result) {
     941            free(new_path);
     942            return FALSE;
     943        }
     944    }
     945    if (wcsncmp(new_path, L"\\\\", 2) == 0 ||
     946        wcsncmp(new_path, L"//", 2) == 0)
     947        /* UNC path, nothing to do. */
     948        return TRUE;
     949    env[1] = new_path[0];
     950    result = SetEnvironmentVariableW(env, new_path);
     951    if (new_path != _new_path)
     952        free(new_path);
     953    return result;
     954}
     955#endif
     956
     957/* choose the appropriate stat and fstat functions and return structs */
     958#undef STAT
     959#undef FSTAT
     960#undef STRUCT_STAT
     961#if defined(MS_WIN64) || defined(MS_WINDOWS)
     962#       define STAT win32_stat
     963#       define FSTAT win32_fstat
     964#       define STRUCT_STAT struct win32_stat
     965#else
     966#       define STAT stat
     967#       define FSTAT fstat
     968#       define STRUCT_STAT struct stat
    767969#endif
    768970
     
    774976   Therefore, we implement our own stat, based on the Win32 API directly.
    775977*/
    776 #define HAVE_STAT_NSEC 1 
     978#define HAVE_STAT_NSEC 1
    777979
    778980struct win32_stat{
     
    785987    int st_rdev;
    786988    __int64 st_size;
    787     int st_atime;
     989    time_t st_atime;
    788990    int st_atime_nsec;
    789     int st_mtime;
     991    time_t st_mtime;
    790992    int st_mtime_nsec;
    791     int st_ctime;
     993    time_t st_ctime;
    792994    int st_ctime_nsec;
    793995};
     
    796998
    797999static void
    798 FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out)
    799 {
    800         /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
    801         /* Cannot simply cast and dereference in_ptr,
    802            since it might not be aligned properly */
    803         __int64 in;
    804         memcpy(&in, in_ptr, sizeof(in));
    805         *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
    806         /* XXX Win32 supports time stamps past 2038; we currently don't */
    807         *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int);
     1000FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
     1001{
     1002    /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
     1003    /* Cannot simply cast and dereference in_ptr,
     1004       since it might not be aligned properly */
     1005    __int64 in;
     1006    memcpy(&in, in_ptr, sizeof(in));
     1007    *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
     1008    *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
    8081009}
    8091010
    8101011static void
    811 time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr)
    812 {
    813         /* XXX endianness */
    814         __int64 out;
    815         out = time_in + secs_between_epochs;
    816         out = out * 10000000 + nsec_in / 100;
    817         memcpy(out_ptr, &out, sizeof(out));
     1012time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
     1013{
     1014    /* XXX endianness */
     1015    __int64 out;
     1016    out = time_in + secs_between_epochs;
     1017    out = out * 10000000 + nsec_in / 100;
     1018    memcpy(out_ptr, &out, sizeof(out));
    8181019}
    8191020
     
    8251026attributes_to_mode(DWORD attr)
    8261027{
    827         int m = 0;
    828         if (attr & FILE_ATTRIBUTE_DIRECTORY)
    829                 m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
    830         else
    831                 m |= _S_IFREG;
    832         if (attr & FILE_ATTRIBUTE_READONLY)
    833                 m |= 0444;
    834         else
    835                 m |= 0666;
    836         return m;
     1028    int m = 0;
     1029    if (attr & FILE_ATTRIBUTE_DIRECTORY)
     1030        m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
     1031    else
     1032        m |= _S_IFREG;
     1033    if (attr & FILE_ATTRIBUTE_READONLY)
     1034        m |= 0444;
     1035    else
     1036        m |= 0666;
     1037    return m;
    8371038}
    8381039
     
    8401041attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result)
    8411042{
    842         memset(result, 0, sizeof(*result));
    843         result->st_mode = attributes_to_mode(info->dwFileAttributes);
    844         result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
    845         FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
    846         FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
    847         FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
    848 
    849         return 0;
    850 }
    851 
    852 /* Emulate GetFileAttributesEx[AW] on Windows 95 */
    853 static int checked = 0;
    854 static BOOL (CALLBACK *gfaxa)(LPCSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
    855 static BOOL (CALLBACK *gfaxw)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
    856 static void
    857 check_gfax()
    858 {
    859         HINSTANCE hKernel32;
    860         if (checked)
    861             return;
    862         checked = 1;
    863         hKernel32 = GetModuleHandle("KERNEL32");
    864         *(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA");
    865         *(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW");
     1043    memset(result, 0, sizeof(*result));
     1044    result->st_mode = attributes_to_mode(info->dwFileAttributes);
     1045    result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
     1046    FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
     1047    FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
     1048    FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
     1049
     1050    return 0;
    8661051}
    8671052
     
    8691054attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
    8701055{
    871         HANDLE hFindFile;
    872         WIN32_FIND_DATAA FileData;
    873         hFindFile = FindFirstFileA(pszFile, &FileData);
    874         if (hFindFile == INVALID_HANDLE_VALUE)
    875                 return FALSE;
    876         FindClose(hFindFile);
    877         pfad->dwFileAttributes = FileData.dwFileAttributes;
    878         pfad->ftCreationTime   = FileData.ftCreationTime;
    879         pfad->ftLastAccessTime = FileData.ftLastAccessTime;
    880         pfad->ftLastWriteTime  = FileData.ftLastWriteTime;
    881         pfad->nFileSizeHigh    = FileData.nFileSizeHigh;
    882         pfad->nFileSizeLow     = FileData.nFileSizeLow;
    883         return TRUE;
     1056    HANDLE hFindFile;
     1057    WIN32_FIND_DATAA FileData;
     1058    hFindFile = FindFirstFileA(pszFile, &FileData);
     1059    if (hFindFile == INVALID_HANDLE_VALUE)
     1060        return FALSE;
     1061    FindClose(hFindFile);
     1062    pfad->dwFileAttributes = FileData.dwFileAttributes;
     1063    pfad->ftCreationTime   = FileData.ftCreationTime;
     1064    pfad->ftLastAccessTime = FileData.ftLastAccessTime;
     1065    pfad->ftLastWriteTime  = FileData.ftLastWriteTime;
     1066    pfad->nFileSizeHigh    = FileData.nFileSizeHigh;
     1067    pfad->nFileSizeLow     = FileData.nFileSizeLow;
     1068    return TRUE;
    8841069}
    8851070
     
    8871072attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
    8881073{
    889         HANDLE hFindFile;
    890         WIN32_FIND_DATAW FileData;
    891         hFindFile = FindFirstFileW(pszFile, &FileData);
    892         if (hFindFile == INVALID_HANDLE_VALUE)
    893                 return FALSE;
    894         FindClose(hFindFile);
    895         pfad->dwFileAttributes = FileData.dwFileAttributes;
    896         pfad->ftCreationTime   = FileData.ftCreationTime;
    897         pfad->ftLastAccessTime = FileData.ftLastAccessTime;
    898         pfad->ftLastWriteTime  = FileData.ftLastWriteTime;
    899         pfad->nFileSizeHigh    = FileData.nFileSizeHigh;
    900         pfad->nFileSizeLow     = FileData.nFileSizeLow;
    901         return TRUE;
    902 }
    903 
    904 static BOOL WINAPI
    905 Py_GetFileAttributesExA(LPCSTR pszFile,
    906                        GET_FILEEX_INFO_LEVELS level,
    907                        LPVOID pv)
    908 {
    909         BOOL result;
    910         LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;
    911         /* First try to use the system's implementation, if that is
    912            available and either succeeds to gives an error other than
    913            that it isn't implemented. */
    914         check_gfax();
    915         if (gfaxa) {
    916                 result = gfaxa(pszFile, level, pv);
    917                 if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
    918                         return result;
    919         }
    920         /* It's either not present, or not implemented.
    921            Emulate using FindFirstFile. */
    922         if (level != GetFileExInfoStandard) {
    923                 SetLastError(ERROR_INVALID_PARAMETER);
    924                 return FALSE;
    925         }
    926         /* Use GetFileAttributes to validate that the file name
    927            does not contain wildcards (which FindFirstFile would
    928            accept). */
    929         if (GetFileAttributesA(pszFile) == 0xFFFFFFFF)
    930                 return FALSE;
    931         return attributes_from_dir(pszFile, pfad);
    932 }
    933 
    934 static BOOL WINAPI
    935 Py_GetFileAttributesExW(LPCWSTR pszFile,
    936                        GET_FILEEX_INFO_LEVELS level,
    937                        LPVOID pv)
    938 {
    939         BOOL result;
    940         LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;
    941         /* First try to use the system's implementation, if that is
    942            available and either succeeds to gives an error other than
    943            that it isn't implemented. */
    944         check_gfax();
    945         if (gfaxa) {
    946                 result = gfaxw(pszFile, level, pv);
    947                 if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
    948                         return result;
    949         }
    950         /* It's either not present, or not implemented.
    951            Emulate using FindFirstFile. */
    952         if (level != GetFileExInfoStandard) {
    953                 SetLastError(ERROR_INVALID_PARAMETER);
    954                 return FALSE;
    955         }
    956         /* Use GetFileAttributes to validate that the file name
    957            does not contain wildcards (which FindFirstFile would
    958            accept). */
    959         if (GetFileAttributesW(pszFile) == 0xFFFFFFFF)
    960                 return FALSE;
    961         return attributes_from_dir_w(pszFile, pfad);
    962 }
    963 
    964 static int
     1074    HANDLE hFindFile;
     1075    WIN32_FIND_DATAW FileData;
     1076    hFindFile = FindFirstFileW(pszFile, &FileData);
     1077    if (hFindFile == INVALID_HANDLE_VALUE)
     1078        return FALSE;
     1079    FindClose(hFindFile);
     1080    pfad->dwFileAttributes = FileData.dwFileAttributes;
     1081    pfad->ftCreationTime   = FileData.ftCreationTime;
     1082    pfad->ftLastAccessTime = FileData.ftLastAccessTime;
     1083    pfad->ftLastWriteTime  = FileData.ftLastWriteTime;
     1084    pfad->nFileSizeHigh    = FileData.nFileSizeHigh;
     1085    pfad->nFileSizeLow     = FileData.nFileSizeLow;
     1086    return TRUE;
     1087}
     1088
     1089static int
    9651090win32_stat(const char* path, struct win32_stat *result)
    9661091{
    967         WIN32_FILE_ATTRIBUTE_DATA info;
    968         int code;
    969         char *dot;
    970         /* XXX not supported on Win95 and NT 3.x */
    971         if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
    972                 if (GetLastError() != ERROR_SHARING_VIOLATION) {
    973                         /* Protocol violation: we explicitly clear errno, instead of
    974                            setting it to a POSIX error. Callers should use GetLastError. */
    975                         errno = 0;
    976                         return -1;
    977                 } else {
    978                         /* Could not get attributes on open file. Fall back to
    979                            reading the directory. */
    980                         if (!attributes_from_dir(path, &info)) {
    981                                 /* Very strange. This should not fail now */
    982                                 errno = 0;
    983                                 return -1;
    984                         }
    985                 }
    986         }
    987         code = attribute_data_to_stat(&info, result);
    988         if (code != 0)
    989                 return code;
    990         /* Set S_IFEXEC if it is an .exe, .bat, ... */
    991         dot = strrchr(path, '.');
    992         if (dot) {
    993                 if (stricmp(dot, ".bat") == 0 ||
    994                 stricmp(dot, ".cmd") == 0 ||
    995                 stricmp(dot, ".exe") == 0 ||
    996                 stricmp(dot, ".com") == 0)
    997                 result->st_mode |= 0111;
    998         }
    999         return code;
    1000 }
    1001 
    1002 static int
     1092    WIN32_FILE_ATTRIBUTE_DATA info;
     1093    int code;
     1094    char *dot;
     1095    if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
     1096        if (GetLastError() != ERROR_SHARING_VIOLATION) {
     1097            /* Protocol violation: we explicitly clear errno, instead of
     1098               setting it to a POSIX error. Callers should use GetLastError. */
     1099            errno = 0;
     1100            return -1;
     1101        } else {
     1102            /* Could not get attributes on open file. Fall back to
     1103               reading the directory. */
     1104            if (!attributes_from_dir(path, &info)) {
     1105                /* Very strange. This should not fail now */
     1106                errno = 0;
     1107                return -1;
     1108            }
     1109        }
     1110    }
     1111    code = attribute_data_to_stat(&info, result);
     1112    if (code != 0)
     1113        return code;
     1114    /* Set S_IFEXEC if it is an .exe, .bat, ... */
     1115    dot = strrchr(path, '.');
     1116    if (dot) {
     1117        if (stricmp(dot, ".bat") == 0 ||
     1118        stricmp(dot, ".cmd") == 0 ||
     1119        stricmp(dot, ".exe") == 0 ||
     1120        stricmp(dot, ".com") == 0)
     1121            result->st_mode |= 0111;
     1122    }
     1123    return code;
     1124}
     1125
     1126static int
    10031127win32_wstat(const wchar_t* path, struct win32_stat *result)
    10041128{
    1005         int code;
    1006         const wchar_t *dot;
    1007         WIN32_FILE_ATTRIBUTE_DATA info;
    1008         /* XXX not supported on Win95 and NT 3.x */
    1009         if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
    1010                 if (GetLastError() != ERROR_SHARING_VIOLATION) {
    1011                         /* Protocol violation: we explicitly clear errno, instead of
    1012                            setting it to a POSIX error. Callers should use GetLastError. */
    1013                         errno = 0;
    1014                         return -1;
    1015                 } else {
    1016                         /* Could not get attributes on open file. Fall back to
    1017                            reading the directory. */
    1018                         if (!attributes_from_dir_w(path, &info)) {
    1019                                 /* Very strange. This should not fail now */
    1020                                 errno = 0;
    1021                                 return -1;
    1022                         }
    1023                 }
    1024         }
    1025         code = attribute_data_to_stat(&info, result);
    1026         if (code < 0)
    1027                 return code;
    1028         /* Set IFEXEC if it is an .exe, .bat, ... */
    1029         dot = wcsrchr(path, '.');
    1030         if (dot) {
    1031                 if (_wcsicmp(dot, L".bat") == 0 ||
    1032                     _wcsicmp(dot, L".cmd") == 0 ||
    1033                     _wcsicmp(dot, L".exe") == 0 ||
    1034                     _wcsicmp(dot, L".com") == 0)
    1035                         result->st_mode |= 0111;
    1036         }
    1037         return code;
     1129    int code;
     1130    const wchar_t *dot;
     1131    WIN32_FILE_ATTRIBUTE_DATA info;
     1132    if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
     1133        if (GetLastError() != ERROR_SHARING_VIOLATION) {
     1134            /* Protocol violation: we explicitly clear errno, instead of
     1135               setting it to a POSIX error. Callers should use GetLastError. */
     1136            errno = 0;
     1137            return -1;
     1138        } else {
     1139            /* Could not get attributes on open file. Fall back to
     1140               reading the directory. */
     1141            if (!attributes_from_dir_w(path, &info)) {
     1142                /* Very strange. This should not fail now */
     1143                errno = 0;
     1144                return -1;
     1145            }
     1146        }
     1147    }
     1148    code = attribute_data_to_stat(&info, result);
     1149    if (code < 0)
     1150        return code;
     1151    /* Set IFEXEC if it is an .exe, .bat, ... */
     1152    dot = wcsrchr(path, '.');
     1153    if (dot) {
     1154        if (_wcsicmp(dot, L".bat") == 0 ||
     1155            _wcsicmp(dot, L".cmd") == 0 ||
     1156            _wcsicmp(dot, L".exe") == 0 ||
     1157            _wcsicmp(dot, L".com") == 0)
     1158            result->st_mode |= 0111;
     1159    }
     1160    return code;
    10381161}
    10391162
     
    10411164win32_fstat(int file_number, struct win32_stat *result)
    10421165{
    1043         BY_HANDLE_FILE_INFORMATION info;
    1044         HANDLE h;
    1045         int type;
    1046    
    1047         h = (HANDLE)_get_osfhandle(file_number);
    1048    
    1049         /* Protocol violation: we explicitly clear errno, instead of
    1050            setting it to a POSIX error. Callers should use GetLastError. */
    1051         errno = 0;
    1052 
    1053         if (h == INVALID_HANDLE_VALUE) {
    1054                 /* This is really a C library error (invalid file handle).
    1055                    We set the Win32 error to the closes one matching. */
    1056                 SetLastError(ERROR_INVALID_HANDLE);
    1057                 return -1;
    1058         }
    1059         memset(result, 0, sizeof(*result));
    1060 
    1061         type = GetFileType(h);
    1062         if (type == FILE_TYPE_UNKNOWN) {
    1063             DWORD error = GetLastError();
    1064             if (error != 0) {
    1065                 return -1;
    1066             }
    1067             /* else: valid but unknown file */
    1068         }
    1069 
    1070         if (type != FILE_TYPE_DISK) {
    1071                 if (type == FILE_TYPE_CHAR)
    1072                         result->st_mode = _S_IFCHR;
    1073                 else if (type == FILE_TYPE_PIPE)
    1074                         result->st_mode = _S_IFIFO;
    1075                 return 0;
    1076         }
    1077 
    1078         if (!GetFileInformationByHandle(h, &info)) {
    1079                 return -1;
    1080         }
    1081 
    1082         /* similar to stat() */
    1083         result->st_mode = attributes_to_mode(info.dwFileAttributes);
    1084         result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow;
    1085         FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
    1086         FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
    1087         FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
    1088         /* specific to fstat() */
    1089         result->st_nlink = info.nNumberOfLinks;
    1090         result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
    1091         return 0;
     1166    BY_HANDLE_FILE_INFORMATION info;
     1167    HANDLE h;
     1168    int type;
     1169
     1170    h = (HANDLE)_get_osfhandle(file_number);
     1171
     1172    /* Protocol violation: we explicitly clear errno, instead of
     1173       setting it to a POSIX error. Callers should use GetLastError. */
     1174    errno = 0;
     1175
     1176    if (h == INVALID_HANDLE_VALUE) {
     1177        /* This is really a C library error (invalid file handle).
     1178           We set the Win32 error to the closes one matching. */
     1179        SetLastError(ERROR_INVALID_HANDLE);
     1180        return -1;
     1181    }
     1182    memset(result, 0, sizeof(*result));
     1183
     1184    type = GetFileType(h);
     1185    if (type == FILE_TYPE_UNKNOWN) {
     1186        DWORD error = GetLastError();
     1187        if (error != 0) {
     1188        return -1;
     1189        }
     1190        /* else: valid but unknown file */
     1191    }
     1192
     1193    if (type != FILE_TYPE_DISK) {
     1194        if (type == FILE_TYPE_CHAR)
     1195            result->st_mode = _S_IFCHR;
     1196        else if (type == FILE_TYPE_PIPE)
     1197            result->st_mode = _S_IFIFO;
     1198        return 0;
     1199    }
     1200
     1201    if (!GetFileInformationByHandle(h, &info)) {
     1202        return -1;
     1203    }
     1204
     1205    /* similar to stat() */
     1206    result->st_mode = attributes_to_mode(info.dwFileAttributes);
     1207    result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow;
     1208    FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
     1209    FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
     1210    FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
     1211    /* specific to fstat() */
     1212    result->st_nlink = info.nNumberOfLinks;
     1213    result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
     1214    return 0;
    10921215}
    10931216
     
    11061229
    11071230static PyStructSequence_Field stat_result_fields[] = {
    1108         {"st_mode",    "protection bits"},
    1109         {"st_ino",     "inode"},
    1110         {"st_dev",     "device"},
    1111         {"st_nlink",   "number of hard links"},
    1112         {"st_uid",     "user ID of owner"},
    1113         {"st_gid",     "group ID of owner"},
    1114         {"st_size",    "total size, in bytes"},
    1115         /* The NULL is replaced with PyStructSequence_UnnamedField later. */
    1116         {NULL,   "integer time of last access"},
    1117         {NULL,   "integer time of last modification"},
    1118         {NULL,   "integer time of last change"},
    1119         {"st_atime",   "time of last access"},
    1120         {"st_mtime",   "time of last modification"},
    1121         {"st_ctime",   "time of last change"},
     1231    {"st_mode",    "protection bits"},
     1232    {"st_ino",     "inode"},
     1233    {"st_dev",     "device"},
     1234    {"st_nlink",   "number of hard links"},
     1235    {"st_uid",     "user ID of owner"},
     1236    {"st_gid",     "group ID of owner"},
     1237    {"st_size",    "total size, in bytes"},
     1238    /* The NULL is replaced with PyStructSequence_UnnamedField later. */
     1239    {NULL,   "integer time of last access"},
     1240    {NULL,   "integer time of last modification"},
     1241    {NULL,   "integer time of last change"},
     1242    {"st_atime",   "time of last access"},
     1243    {"st_mtime",   "time of last modification"},
     1244    {"st_ctime",   "time of last change"},
    11221245#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
    1123         {"st_blksize", "blocksize for filesystem I/O"},
     1246    {"st_blksize", "blocksize for filesystem I/O"},
    11241247#endif
    11251248#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
    1126         {"st_blocks",  "number of blocks allocated"},
     1249    {"st_blocks",  "number of blocks allocated"},
    11271250#endif
    11281251#ifdef HAVE_STRUCT_STAT_ST_RDEV
    1129         {"st_rdev",    "device type (if inode device)"},
     1252    {"st_rdev",    "device type (if inode device)"},
    11301253#endif
    11311254#ifdef HAVE_STRUCT_STAT_ST_FLAGS
    1132         {"st_flags",   "user defined flags for file"},
     1255    {"st_flags",   "user defined flags for file"},
    11331256#endif
    11341257#ifdef HAVE_STRUCT_STAT_ST_GEN
    1135         {"st_gen",    "generation number"},
     1258    {"st_gen",    "generation number"},
    11361259#endif
    11371260#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
    1138         {"st_birthtime",   "time of creation"},
    1139 #endif
    1140         {0}
     1261    {"st_birthtime",   "time of creation"},
     1262#endif
     1263    {0}
    11411264};
    11421265
     
    11781301
    11791302static PyStructSequence_Desc stat_result_desc = {
    1180         "stat_result", /* name */
    1181         stat_result__doc__, /* doc */
    1182         stat_result_fields,
    1183         10
     1303    "stat_result", /* name */
     1304    stat_result__doc__, /* doc */
     1305    stat_result_fields,
     1306    10
    11841307};
    11851308
     
    11931316
    11941317static PyStructSequence_Field statvfs_result_fields[] = {
    1195         {"f_bsize",  },
    1196         {"f_frsize", },
    1197         {"f_blocks", },
    1198         {"f_bfree",  },
    1199         {"f_bavail", },
    1200         {"f_files",  },
    1201         {"f_ffree",  },
    1202         {"f_favail", },
    1203         {"f_flag",   },
    1204         {"f_namemax",},
    1205         {0}
     1318    {"f_bsize",  },
     1319    {"f_frsize", },
     1320    {"f_blocks", },
     1321    {"f_bfree",  },
     1322    {"f_bavail", },
     1323    {"f_files",  },
     1324    {"f_ffree",  },
     1325    {"f_favail", },
     1326    {"f_flag",   },
     1327    {"f_namemax",},
     1328    {0}
    12061329};
    12071330
    12081331static PyStructSequence_Desc statvfs_result_desc = {
    1209         "statvfs_result", /* name */
    1210         statvfs_result__doc__, /* doc */
    1211         statvfs_result_fields,
    1212         10
     1332    "statvfs_result", /* name */
     1333    statvfs_result__doc__, /* doc */
     1334    statvfs_result_fields,
     1335    10
    12131336};
    12141337
     
    12211344statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    12221345{
    1223         PyStructSequence *result;
    1224         int i;
    1225 
    1226         result = (PyStructSequence*)structseq_new(type, args, kwds);
    1227         if (!result)
    1228                 return NULL;
    1229         /* If we have been initialized from a tuple,
    1230            st_?time might be set to None. Initialize it
    1231            from the int slots.  */
    1232         for (i = 7; i <= 9; i++) {
    1233                 if (result->ob_item[i+3] == Py_None) {
    1234                         Py_DECREF(Py_None);
    1235                         Py_INCREF(result->ob_item[i]);
    1236                         result->ob_item[i+3] = result->ob_item[i];
    1237                 }
    1238         }
    1239         return (PyObject*)result;
     1346    PyStructSequence *result;
     1347    int i;
     1348
     1349    result = (PyStructSequence*)structseq_new(type, args, kwds);
     1350    if (!result)
     1351        return NULL;
     1352    /* If we have been initialized from a tuple,
     1353       st_?time might be set to None. Initialize it
     1354       from the int slots.  */
     1355    for (i = 7; i <= 9; i++) {
     1356        if (result->ob_item[i+3] == Py_None) {
     1357            Py_DECREF(Py_None);
     1358            Py_INCREF(result->ob_item[i]);
     1359            result->ob_item[i+3] = result->ob_item[i];
     1360        }
     1361    }
     1362    return (PyObject*)result;
    12401363}
    12411364
     
    12551378stat_float_times(PyObject* self, PyObject *args)
    12561379{
    1257         int newval = -1;
    1258         if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval))
    1259                 return NULL;
    1260         if (newval == -1)
    1261                 /* Return old value */
    1262                 return PyBool_FromLong(_stat_float_times);
    1263         _stat_float_times = newval;
    1264         Py_INCREF(Py_None);
    1265         return Py_None;
     1380    int newval = -1;
     1381    if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval))
     1382        return NULL;
     1383    if (newval == -1)
     1384        /* Return old value */
     1385        return PyBool_FromLong(_stat_float_times);
     1386    _stat_float_times = newval;
     1387    Py_INCREF(Py_None);
     1388    return Py_None;
    12661389}
    12671390
     
    12691392fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
    12701393{
    1271         PyObject *fval,*ival;
     1394    PyObject *fval,*ival;
    12721395#if SIZEOF_TIME_T > SIZEOF_LONG
    1273         ival = PyLong_FromLongLong((PY_LONG_LONG)sec);
     1396    ival = PyLong_FromLongLong((PY_LONG_LONG)sec);
    12741397#else
    1275         ival = PyInt_FromLong((long)sec);
    1276 #endif
    1277         if (!ival)
    1278                 return;
    1279         if (_stat_float_times) {
    1280                 fval = PyFloat_FromDouble(sec + 1e-9*nsec);
    1281         } else {
    1282                 fval = ival;
    1283                 Py_INCREF(fval);
    1284         }
    1285         PyStructSequence_SET_ITEM(v, index, ival);
    1286         PyStructSequence_SET_ITEM(v, index+3, fval);
     1398    ival = PyInt_FromLong((long)sec);
     1399#endif
     1400    if (!ival)
     1401        return;
     1402    if (_stat_float_times) {
     1403        fval = PyFloat_FromDouble(sec + 1e-9*nsec);
     1404    } else {
     1405        fval = ival;
     1406        Py_INCREF(fval);
     1407    }
     1408    PyStructSequence_SET_ITEM(v, index, ival);
     1409    PyStructSequence_SET_ITEM(v, index+3, fval);
    12871410}
    12881411
     
    12921415_pystat_fromstructstat(STRUCT_STAT *st)
    12931416{
    1294         unsigned long ansec, mnsec, cnsec;
    1295         PyObject *v = PyStructSequence_New(&StatResultType);
    1296         if (v == NULL)
    1297                 return NULL;
    1298 
    1299         PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode));
     1417    unsigned long ansec, mnsec, cnsec;
     1418    PyObject *v = PyStructSequence_New(&StatResultType);
     1419    if (v == NULL)
     1420        return NULL;
     1421
     1422    PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode));
    13001423#ifdef HAVE_LARGEFILE_SUPPORT
    1301         PyStructSequence_SET_ITEM(v, 1,
    1302                                   PyLong_FromLongLong((PY_LONG_LONG)st->st_ino));
     1424    PyStructSequence_SET_ITEM(v, 1,
     1425                              PyLong_FromLongLong((PY_LONG_LONG)st->st_ino));
    13031426#else
    1304         PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino));
     1427    PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino));
    13051428#endif
    13061429#if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS)
    1307         PyStructSequence_SET_ITEM(v, 2,
    1308                                   PyLong_FromLongLong((PY_LONG_LONG)st->st_dev));
     1430    PyStructSequence_SET_ITEM(v, 2,
     1431                              PyLong_FromLongLong((PY_LONG_LONG)st->st_dev));
    13091432#else
    1310         PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev));
    1311 #endif
    1312         PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink));
    1313         PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long)st->st_uid));
    1314         PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long)st->st_gid));
     1433    PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev));
     1434#endif
     1435    PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink));
     1436#if defined(MS_WINDOWS)
     1437    PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong(0));
     1438    PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong(0));
     1439#else
     1440    PyStructSequence_SET_ITEM(v, 4, _PyInt_FromUid(st->st_uid));
     1441    PyStructSequence_SET_ITEM(v, 5, _PyInt_FromGid(st->st_gid));
     1442#endif
    13151443#ifdef HAVE_LARGEFILE_SUPPORT
    1316         PyStructSequence_SET_ITEM(v, 6,
    1317                                   PyLong_FromLongLong((PY_LONG_LONG)st->st_size));
     1444    PyStructSequence_SET_ITEM(v, 6,
     1445                              PyLong_FromLongLong((PY_LONG_LONG)st->st_size));
    13181446#else
    1319         PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size));
     1447    PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size));
    13201448#endif
    13211449
    13221450#if defined(HAVE_STAT_TV_NSEC)
    1323         ansec = st->st_atim.tv_nsec;
    1324         mnsec = st->st_mtim.tv_nsec;
    1325         cnsec = st->st_ctim.tv_nsec;
     1451    ansec = st->st_atim.tv_nsec;
     1452    mnsec = st->st_mtim.tv_nsec;
     1453    cnsec = st->st_ctim.tv_nsec;
    13261454#elif defined(HAVE_STAT_TV_NSEC2)
    1327         ansec = st->st_atimespec.tv_nsec;
    1328         mnsec = st->st_mtimespec.tv_nsec;
    1329         cnsec = st->st_ctimespec.tv_nsec;
     1455    ansec = st->st_atimespec.tv_nsec;
     1456    mnsec = st->st_mtimespec.tv_nsec;
     1457    cnsec = st->st_ctimespec.tv_nsec;
    13301458#elif defined(HAVE_STAT_NSEC)
    1331         ansec = st->st_atime_nsec;
    1332         mnsec = st->st_mtime_nsec;
    1333         cnsec = st->st_ctime_nsec;
     1459    ansec = st->st_atime_nsec;
     1460    mnsec = st->st_mtime_nsec;
     1461    cnsec = st->st_ctime_nsec;
    13341462#else
    1335         ansec = mnsec = cnsec = 0;
    1336 #endif
    1337         fill_time(v, 7, st->st_atime, ansec);
    1338         fill_time(v, 8, st->st_mtime, mnsec);
    1339         fill_time(v, 9, st->st_ctime, cnsec);
     1463    ansec = mnsec = cnsec = 0;
     1464#endif
     1465    fill_time(v, 7, st->st_atime, ansec);
     1466    fill_time(v, 8, st->st_mtime, mnsec);
     1467    fill_time(v, 9, st->st_ctime, cnsec);
    13401468
    13411469#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
    1342         PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
    1343                         PyInt_FromLong((long)st->st_blksize));
     1470    PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
     1471                              PyInt_FromLong((long)st->st_blksize));
    13441472#endif
    13451473#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
    1346         PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
    1347                         PyInt_FromLong((long)st->st_blocks));
     1474    PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
     1475                              PyInt_FromLong((long)st->st_blocks));
    13481476#endif
    13491477#ifdef HAVE_STRUCT_STAT_ST_RDEV
    1350         PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
    1351                         PyInt_FromLong((long)st->st_rdev));
     1478    PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
     1479                              PyInt_FromLong((long)st->st_rdev));
    13521480#endif
    13531481#ifdef HAVE_STRUCT_STAT_ST_GEN
    1354         PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
    1355                         PyInt_FromLong((long)st->st_gen));
     1482    PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
     1483                              PyInt_FromLong((long)st->st_gen));
    13561484#endif
    13571485#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
    1358         {
    1359           PyObject *val;
    1360           unsigned long bsec,bnsec;
    1361           bsec = (long)st->st_birthtime;
     1486    {
     1487      PyObject *val;
     1488      unsigned long bsec,bnsec;
     1489      bsec = (long)st->st_birthtime;
    13621490#ifdef HAVE_STAT_TV_NSEC2
    1363           bnsec = st->st_birthtimespec.tv_nsec;
     1491      bnsec = st->st_birthtimespec.tv_nsec;
    13641492#else
    1365           bnsec = 0;
    1366 #endif
    1367           if (_stat_float_times) {
    1368             val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
    1369           } else {
    1370             val = PyInt_FromLong((long)bsec);
    1371           }
    1372           PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
    1373                                     val);
    1374         }
     1493      bnsec = 0;
     1494#endif
     1495      if (_stat_float_times) {
     1496        val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
     1497      } else {
     1498        val = PyInt_FromLong((long)bsec);
     1499      }
     1500      PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
     1501                                val);
     1502    }
    13751503#endif
    13761504#ifdef HAVE_STRUCT_STAT_ST_FLAGS
    1377         PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
    1378                         PyInt_FromLong((long)st->st_flags));
    1379 #endif
    1380 
    1381         if (PyErr_Occurred()) {
    1382                 Py_DECREF(v);
    1383                 return NULL;
    1384         }
    1385 
    1386         return v;
     1505    PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
     1506                              PyInt_FromLong((long)st->st_flags));
     1507#endif
     1508
     1509    if (PyErr_Occurred()) {
     1510        Py_DECREF(v);
     1511        return NULL;
     1512    }
     1513
     1514    return v;
    13871515}
    13881516
     
    14031531IsUNCRootA(char *path, int pathlen)
    14041532{
    1405         #define ISSLASH ISSLASHA
    1406 
    1407         int i, share;
    1408 
    1409         if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
    1410                 /* minimum UNCRoot is \\x\y */
    1411                 return FALSE;
    1412         for (i = 2; i < pathlen ; i++)
    1413                 if (ISSLASH(path[i])) break;
    1414         if (i == 2 || i == pathlen)
    1415                 /* do not allow \\\SHARE or \\SERVER */
    1416                 return FALSE;
    1417         share = i+1;
    1418         for (i = share; i < pathlen; i++)
    1419                 if (ISSLASH(path[i])) break;
    1420         return (i != share && (i == pathlen || i == pathlen-1));
    1421 
    1422         #undef ISSLASH
    1423 }
    1424 
    1425 #ifdef Py_WIN_WIDE_FILENAMES
     1533    #define ISSLASH ISSLASHA
     1534
     1535    int i, share;
     1536
     1537    if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
     1538        /* minimum UNCRoot is \\x\y */
     1539        return FALSE;
     1540    for (i = 2; i < pathlen ; i++)
     1541        if (ISSLASH(path[i])) break;
     1542    if (i == 2 || i == pathlen)
     1543        /* do not allow \\\SHARE or \\SERVER */
     1544        return FALSE;
     1545    share = i+1;
     1546    for (i = share; i < pathlen; i++)
     1547        if (ISSLASH(path[i])) break;
     1548    return (i != share && (i == pathlen || i == pathlen-1));
     1549
     1550    #undef ISSLASH
     1551}
     1552
    14261553static BOOL
    14271554IsUNCRootW(Py_UNICODE *path, int pathlen)
    14281555{
    1429         #define ISSLASH ISSLASHW
    1430 
    1431         int i, share;
    1432 
    1433         if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
    1434                 /* minimum UNCRoot is \\x\y */
    1435                 return FALSE;
    1436         for (i = 2; i < pathlen ; i++)
    1437                 if (ISSLASH(path[i])) break;
    1438         if (i == 2 || i == pathlen)
    1439                 /* do not allow \\\SHARE or \\SERVER */
    1440                 return FALSE;
    1441         share = i+1;
    1442         for (i = share; i < pathlen; i++)
    1443                 if (ISSLASH(path[i])) break;
    1444         return (i != share && (i == pathlen || i == pathlen-1));
    1445 
    1446         #undef ISSLASH
    1447 }
    1448 #endif /* Py_WIN_WIDE_FILENAMES */
     1556    #define ISSLASH ISSLASHW
     1557
     1558    int i, share;
     1559
     1560    if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
     1561        /* minimum UNCRoot is \\x\y */
     1562        return FALSE;
     1563    for (i = 2; i < pathlen ; i++)
     1564        if (ISSLASH(path[i])) break;
     1565    if (i == 2 || i == pathlen)
     1566        /* do not allow \\\SHARE or \\SERVER */
     1567        return FALSE;
     1568    share = i+1;
     1569    for (i = share; i < pathlen; i++)
     1570        if (ISSLASH(path[i])) break;
     1571    return (i != share && (i == pathlen || i == pathlen-1));
     1572
     1573    #undef ISSLASH
     1574}
    14491575#endif /* MS_WINDOWS */
    14501576
    14511577static PyObject *
    14521578posix_do_stat(PyObject *self, PyObject *args,
    1453               char *format,
     1579              char *format,
    14541580#ifdef __VMS
    1455               int (*statfunc)(const char *, STRUCT_STAT *, ...),
     1581              int (*statfunc)(const char *, STRUCT_STAT *, ...),
    14561582#else
    1457               int (*statfunc)(const char *, STRUCT_STAT *),
    1458 #endif
    1459               char *wformat,
    1460               int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *))
    1461 {
    1462         STRUCT_STAT st;
    1463         char *path = NULL;      /* pass this to stat; do not free() it */
    1464         char *pathfree = NULL;  /* this memory must be free'd */
    1465         int res;
    1466         PyObject *result;
    1467 
    1468 #ifdef Py_WIN_WIDE_FILENAMES
    1469         /* If on wide-character-capable OS see if argument
    1470            is Unicode and if so use wide API.  */
    1471         if (unicode_file_names()) {
    1472                 PyUnicodeObject *po;
    1473                 if (PyArg_ParseTuple(args, wformat, &po)) {
    1474                         Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
    1475 
    1476                         Py_BEGIN_ALLOW_THREADS
    1477                                 /* PyUnicode_AS_UNICODE result OK without
    1478                                    thread lock as it is a simple dereference. */
    1479                         res = wstatfunc(wpath, &st);
    1480                         Py_END_ALLOW_THREADS
    1481 
    1482                         if (res != 0)
    1483                                 return win32_error_unicode("stat", wpath);
    1484                         return _pystat_fromstructstat(&st);
    1485                 }
    1486                 /* Drop the argument parsing error as narrow strings
    1487                    are also valid. */
    1488                 PyErr_Clear();
    1489         }
    1490 #endif
    1491 
    1492         if (!PyArg_ParseTuple(args, format,
    1493                               Py_FileSystemDefaultEncoding, &path))
    1494                 return NULL;
    1495         pathfree = path;
    1496 
    1497         Py_BEGIN_ALLOW_THREADS
    1498         res = (*statfunc)(path, &st);
    1499         Py_END_ALLOW_THREADS
    1500 
    1501         if (res != 0) {
     1583              int (*statfunc)(const char *, STRUCT_STAT *),
     1584#endif
     1585              char *wformat,
     1586              int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *))
     1587{
     1588    STRUCT_STAT st;
     1589    char *path = NULL;          /* pass this to stat; do not free() it */
     1590    char *pathfree = NULL;  /* this memory must be free'd */
     1591    int res;
     1592    PyObject *result;
     1593
    15021594#ifdef MS_WINDOWS
    1503                 result = win32_error("stat", pathfree);
     1595    PyUnicodeObject *po;
     1596    if (PyArg_ParseTuple(args, wformat, &po)) {
     1597        Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
     1598
     1599        Py_BEGIN_ALLOW_THREADS
     1600            /* PyUnicode_AS_UNICODE result OK without
     1601               thread lock as it is a simple dereference. */
     1602        res = wstatfunc(wpath, &st);
     1603        Py_END_ALLOW_THREADS
     1604
     1605        if (res != 0)
     1606            return win32_error_unicode("stat", wpath);
     1607        return _pystat_fromstructstat(&st);
     1608    }
     1609    /* Drop the argument parsing error as narrow strings
     1610       are also valid. */
     1611    PyErr_Clear();
     1612#endif
     1613
     1614    if (!PyArg_ParseTuple(args, format,
     1615                          Py_FileSystemDefaultEncoding, &path))
     1616        return NULL;
     1617    pathfree = path;
     1618
     1619    Py_BEGIN_ALLOW_THREADS
     1620    res = (*statfunc)(path, &st);
     1621    Py_END_ALLOW_THREADS
     1622
     1623    if (res != 0) {
     1624#ifdef MS_WINDOWS
     1625        result = win32_error("stat", pathfree);
    15041626#else
    1505                 result = posix_error_with_filename(pathfree);
    1506 #endif
    1507         }
    1508         else
    1509                 result = _pystat_fromstructstat(&st);
    1510 
    1511         PyMem_Free(pathfree);
    1512         return result;
     1627        result = posix_error_with_filename(pathfree);
     1628#endif
     1629    }
     1630    else
     1631        result = _pystat_fromstructstat(&st);
     1632
     1633    PyMem_Free(pathfree);
     1634    return result;
    15131635}
    15141636
     
    15261648posix_access(PyObject *self, PyObject *args)
    15271649{
    1528         char *path;
    1529         int mode;
    1530        
    1531 #ifdef Py_WIN_WIDE_FILENAMES
    1532         DWORD attr;
    1533         if (unicode_file_names()) {
    1534                 PyUnicodeObject *po;
    1535                 if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) {
    1536                         Py_BEGIN_ALLOW_THREADS
    1537                         /* PyUnicode_AS_UNICODE OK without thread lock as
    1538                            it is a simple dereference. */
    1539                         attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
    1540                         Py_END_ALLOW_THREADS
    1541                         goto finish;
    1542                 }
    1543                 /* Drop the argument parsing error as narrow strings
    1544                    are also valid. */
    1545                 PyErr_Clear();
    1546         }
    1547         if (!PyArg_ParseTuple(args, "eti:access",
    1548                               Py_FileSystemDefaultEncoding, &path, &mode))
    1549                 return 0;
    1550         Py_BEGIN_ALLOW_THREADS
    1551         attr = GetFileAttributesA(path);
    1552         Py_END_ALLOW_THREADS
    1553         PyMem_Free(path);
     1650    char *path;
     1651    int mode;
     1652
     1653#ifdef MS_WINDOWS
     1654    DWORD attr;
     1655    PyUnicodeObject *po;
     1656    if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) {
     1657        Py_BEGIN_ALLOW_THREADS
     1658        /* PyUnicode_AS_UNICODE OK without thread lock as
     1659           it is a simple dereference. */
     1660        attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
     1661        Py_END_ALLOW_THREADS
     1662        goto finish;
     1663    }
     1664    /* Drop the argument parsing error as narrow strings
     1665       are also valid. */
     1666    PyErr_Clear();
     1667    if (!PyArg_ParseTuple(args, "eti:access",
     1668                          Py_FileSystemDefaultEncoding, &path, &mode))
     1669        return NULL;
     1670    Py_BEGIN_ALLOW_THREADS
     1671    attr = GetFileAttributesA(path);
     1672    Py_END_ALLOW_THREADS
     1673    PyMem_Free(path);
    15541674finish:
    1555         if (attr == 0xFFFFFFFF)
    1556                 /* File does not exist, or cannot read attributes */
    1557                 return PyBool_FromLong(0);
    1558         /* Access is possible if either write access wasn't requested, or
    1559            the file isn't read-only, or if it's a directory, as there are
    1560            no read-only directories on Windows. */
    1561         return PyBool_FromLong(!(mode & 2)
    1562                                || !(attr & FILE_ATTRIBUTE_READONLY)
    1563                                || (attr & FILE_ATTRIBUTE_DIRECTORY));
    1564 #else
    1565         int res;
    1566         if (!PyArg_ParseTuple(args, "eti:access",
    1567                               Py_FileSystemDefaultEncoding, &path, &mode))
    1568                 return NULL;
    1569         Py_BEGIN_ALLOW_THREADS
    1570         res = access(path, mode);
    1571         Py_END_ALLOW_THREADS
    1572         PyMem_Free(path);
    1573         return PyBool_FromLong(res == 0);
    1574 #endif
     1675    if (attr == 0xFFFFFFFF)
     1676        /* File does not exist, or cannot read attributes */
     1677        return PyBool_FromLong(0);
     1678    /* Access is possible if either write access wasn't requested, or
     1679       the file isn't read-only, or if it's a directory, as there are
     1680       no read-only directories on Windows. */
     1681    return PyBool_FromLong(!(mode & 2)
     1682                           || !(attr & FILE_ATTRIBUTE_READONLY)
     1683                           || (attr & FILE_ATTRIBUTE_DIRECTORY));
     1684#else /* MS_WINDOWS */
     1685    int res;
     1686    if (!PyArg_ParseTuple(args, "eti:access",
     1687                          Py_FileSystemDefaultEncoding, &path, &mode))
     1688        return NULL;
     1689    Py_BEGIN_ALLOW_THREADS
     1690    res = access(path, mode);
     1691    Py_END_ALLOW_THREADS
     1692    PyMem_Free(path);
     1693    return PyBool_FromLong(res == 0);
     1694#endif /* MS_WINDOWS */
    15751695}
    15761696
     
    15961716posix_ttyname(PyObject *self, PyObject *args)
    15971717{
    1598         int id;
    1599         char *ret;
    1600 
    1601         if (!PyArg_ParseTuple(args, "i:ttyname", &id))
    1602                 return NULL;
     1718    int id;
     1719    char *ret;
     1720
     1721    if (!PyArg_ParseTuple(args, "i:ttyname", &id))
     1722        return NULL;
    16031723
    16041724#if defined(__VMS)
    1605         /* file descriptor 0 only, the default input device (stdin) */
    1606         if (id == 0) {
    1607                 ret = ttyname();
    1608         }
    1609         else {
    1610                 ret = NULL;
    1611         }
     1725    /* file descriptor 0 only, the default input device (stdin) */
     1726    if (id == 0) {
     1727        ret = ttyname();
     1728    }
     1729    else {
     1730        ret = NULL;
     1731    }
    16121732#else
    1613         ret = ttyname(id);
    1614 #endif
    1615         if (ret == NULL)
    1616                 return posix_error();
    1617         return PyString_FromString(ret);
     1733    ret = ttyname(id);
     1734#endif
     1735    if (ret == NULL)
     1736        return posix_error();
     1737    return PyString_FromString(ret);
    16181738}
    16191739#endif
     
    16271747posix_ctermid(PyObject *self, PyObject *noargs)
    16281748{
    1629         char *ret;
    1630         char buffer[L_ctermid];
     1749    char *ret;
     1750    char buffer[L_ctermid];
    16311751
    16321752#ifdef USE_CTERMID_R
    1633         ret = ctermid_r(buffer);
     1753    ret = ctermid_r(buffer);
    16341754#else
    1635         ret = ctermid(buffer);
    1636 #endif
    1637         if (ret == NULL)
    1638                 return posix_error();
    1639         return PyString_FromString(buffer);
     1755    ret = ctermid(buffer);
     1756#endif
     1757    if (ret == NULL)
     1758        return posix_error();
     1759    return PyString_FromString(buffer);
    16401760}
    16411761#endif
     
    16491769{
    16501770#ifdef MS_WINDOWS
    1651         return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir);
     1771    return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir);
    16521772#elif defined(PYOS_OS2) && defined(PYCC_GCC)
    1653         return posix_1str(args, "et:chdir", _chdir2);
     1773    return posix_1str(args, "et:chdir", _chdir2);
    16541774#elif defined(__VMS)
    1655         return posix_1str(args, "et:chdir", (int (*)(const char *))chdir);
     1775    return posix_1str(args, "et:chdir", (int (*)(const char *))chdir);
    16561776#else
    1657         return posix_1str(args, "et:chdir", chdir);
     1777    return posix_1str(args, "et:chdir", chdir);
    16581778#endif
    16591779}
     
    16681788posix_fchdir(PyObject *self, PyObject *fdobj)
    16691789{
    1670         return posix_fildes(fdobj, fchdir);
     1790    return posix_fildes(fdobj, fchdir);
    16711791}
    16721792#endif /* HAVE_FCHDIR */
     
    16801800posix_chmod(PyObject *self, PyObject *args)
    16811801{
    1682         char *path = NULL;
    1683         int i;
    1684         int res;
    1685 #ifdef Py_WIN_WIDE_FILENAMES
    1686         DWORD attr;
    1687         if (unicode_file_names()) {
    1688                 PyUnicodeObject *po;
    1689                 if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) {
    1690                         Py_BEGIN_ALLOW_THREADS
    1691                         attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
    1692                         if (attr != 0xFFFFFFFF) {
    1693                                 if (i & _S_IWRITE)
    1694                                         attr &= ~FILE_ATTRIBUTE_READONLY;
    1695                                 else
    1696                                         attr |= FILE_ATTRIBUTE_READONLY;
    1697                                 res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr);
    1698                         }
    1699                         else
    1700                                 res = 0;
    1701                         Py_END_ALLOW_THREADS
    1702                         if (!res)
    1703                                 return win32_error_unicode("chmod",
    1704                                                 PyUnicode_AS_UNICODE(po));
    1705                         Py_INCREF(Py_None);
    1706                         return Py_None;
    1707                 }
    1708                 /* Drop the argument parsing error as narrow strings
    1709                    are also valid. */
    1710                 PyErr_Clear();
    1711         }
    1712         if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
    1713                               &path, &i))
    1714                 return NULL;
    1715         Py_BEGIN_ALLOW_THREADS
    1716         attr = GetFileAttributesA(path);
    1717         if (attr != 0xFFFFFFFF) {
    1718                 if (i & _S_IWRITE)
    1719                         attr &= ~FILE_ATTRIBUTE_READONLY;
    1720                 else
    1721                         attr |= FILE_ATTRIBUTE_READONLY;
    1722                 res = SetFileAttributesA(path, attr);
    1723         }
    1724         else
    1725                 res = 0;
    1726         Py_END_ALLOW_THREADS
    1727         if (!res) {
    1728                 win32_error("chmod", path);
    1729                 PyMem_Free(path);
    1730                 return NULL;
    1731         }
    1732         PyMem_Free(path);
    1733         Py_INCREF(Py_None);
    1734         return Py_None;
    1735 #else /* Py_WIN_WIDE_FILENAMES */
    1736         if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
    1737                               &path, &i))
    1738                 return NULL;
    1739         Py_BEGIN_ALLOW_THREADS
    1740         res = chmod(path, i);
    1741         Py_END_ALLOW_THREADS
    1742         if (res < 0)
    1743                 return posix_error_with_allocated_filename(path);
    1744         PyMem_Free(path);
    1745         Py_INCREF(Py_None);
    1746         return Py_None;
     1802    char *path = NULL;
     1803    int i;
     1804    int res;
     1805#ifdef MS_WINDOWS
     1806    DWORD attr;
     1807    PyUnicodeObject *po;
     1808    if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) {
     1809        Py_BEGIN_ALLOW_THREADS
     1810        attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
     1811        if (attr != 0xFFFFFFFF) {
     1812            if (i & _S_IWRITE)
     1813                attr &= ~FILE_ATTRIBUTE_READONLY;
     1814            else
     1815                attr |= FILE_ATTRIBUTE_READONLY;
     1816            res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr);
     1817        }
     1818        else
     1819            res = 0;
     1820        Py_END_ALLOW_THREADS
     1821        if (!res)
     1822            return win32_error_unicode("chmod",
     1823                                       PyUnicode_AS_UNICODE(po));
     1824        Py_INCREF(Py_None);
     1825        return Py_None;
     1826    }
     1827    /* Drop the argument parsing error as narrow strings
     1828       are also valid. */
     1829    PyErr_Clear();
     1830
     1831    if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
     1832                          &path, &i))
     1833        return NULL;
     1834    Py_BEGIN_ALLOW_THREADS
     1835    attr = GetFileAttributesA(path);
     1836    if (attr != 0xFFFFFFFF) {
     1837        if (i & _S_IWRITE)
     1838            attr &= ~FILE_ATTRIBUTE_READONLY;
     1839        else
     1840            attr |= FILE_ATTRIBUTE_READONLY;
     1841        res = SetFileAttributesA(path, attr);
     1842    }
     1843    else
     1844        res = 0;
     1845    Py_END_ALLOW_THREADS
     1846    if (!res) {
     1847        win32_error("chmod", path);
     1848        PyMem_Free(path);
     1849        return NULL;
     1850    }
     1851    PyMem_Free(path);
     1852    Py_INCREF(Py_None);
     1853    return Py_None;
     1854#else /* MS_WINDOWS */
     1855    if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
     1856                          &path, &i))
     1857        return NULL;
     1858    Py_BEGIN_ALLOW_THREADS
     1859    res = chmod(path, i);
     1860    Py_END_ALLOW_THREADS
     1861    if (res < 0)
     1862        return posix_error_with_allocated_filename(path);
     1863    PyMem_Free(path);
     1864    Py_INCREF(Py_None);
     1865    return Py_None;
    17471866#endif
    17481867}
     
    17571876posix_fchmod(PyObject *self, PyObject *args)
    17581877{
    1759         int fd, mode, res;
    1760         if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode))
    1761                 return NULL;
    1762         Py_BEGIN_ALLOW_THREADS
    1763         res = fchmod(fd, mode);
    1764         Py_END_ALLOW_THREADS
    1765         if (res < 0)
    1766                 return posix_error();
    1767         Py_RETURN_NONE;
     1878    int fd, mode, res;
     1879    if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode))
     1880        return NULL;
     1881    Py_BEGIN_ALLOW_THREADS
     1882    res = fchmod(fd, mode);
     1883    Py_END_ALLOW_THREADS
     1884    if (res < 0)
     1885        return posix_error();
     1886    Py_RETURN_NONE;
    17681887}
    17691888#endif /* HAVE_FCHMOD */
     
    17781897posix_lchmod(PyObject *self, PyObject *args)
    17791898{
    1780         char *path = NULL;
    1781         int i;
    1782         int res;
    1783         if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding,
    1784                               &path, &i))
    1785                 return NULL;
    1786         Py_BEGIN_ALLOW_THREADS
    1787         res = lchmod(path, i);
    1788         Py_END_ALLOW_THREADS
    1789         if (res < 0)
    1790                 return posix_error_with_allocated_filename(path);
    1791         PyMem_Free(path);
    1792         Py_RETURN_NONE;
     1899    char *path = NULL;
     1900    int i;
     1901    int res;
     1902    if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding,
     1903                          &path, &i))
     1904        return NULL;
     1905    Py_BEGIN_ALLOW_THREADS
     1906    res = lchmod(path, i);
     1907    Py_END_ALLOW_THREADS
     1908    if (res < 0)
     1909        return posix_error_with_allocated_filename(path);
     1910    PyMem_Free(path);
     1911    Py_RETURN_NONE;
    17931912}
    17941913#endif /* HAVE_LCHMOD */
     
    18031922posix_chflags(PyObject *self, PyObject *args)
    18041923{
    1805         char *path;
    1806         unsigned long flags;
    1807         int res;
    1808         if (!PyArg_ParseTuple(args, "etk:chflags",
    1809                               Py_FileSystemDefaultEncoding, &path, &flags))
    1810                 return NULL;
    1811         Py_BEGIN_ALLOW_THREADS
    1812         res = chflags(path, flags);
    1813         Py_END_ALLOW_THREADS
    1814         if (res < 0)
    1815                 return posix_error_with_allocated_filename(path);
    1816         PyMem_Free(path);
    1817         Py_INCREF(Py_None);
    1818         return Py_None;
     1924    char *path;
     1925    unsigned long flags;
     1926    int res;
     1927    if (!PyArg_ParseTuple(args, "etk:chflags",
     1928                          Py_FileSystemDefaultEncoding, &path, &flags))
     1929        return NULL;
     1930    Py_BEGIN_ALLOW_THREADS
     1931    res = chflags(path, flags);
     1932    Py_END_ALLOW_THREADS
     1933    if (res < 0)
     1934        return posix_error_with_allocated_filename(path);
     1935    PyMem_Free(path);
     1936    Py_INCREF(Py_None);
     1937    return Py_None;
    18191938}
    18201939#endif /* HAVE_CHFLAGS */
     
    18291948posix_lchflags(PyObject *self, PyObject *args)
    18301949{
    1831         char *path;
    1832         unsigned long flags;
    1833         int res;
    1834         if (!PyArg_ParseTuple(args, "etk:lchflags",
    1835                               Py_FileSystemDefaultEncoding, &path, &flags))
    1836                 return NULL;
    1837         Py_BEGIN_ALLOW_THREADS
    1838         res = lchflags(path, flags);
    1839         Py_END_ALLOW_THREADS
    1840         if (res < 0)
    1841                 return posix_error_with_allocated_filename(path);
    1842         PyMem_Free(path);
    1843         Py_INCREF(Py_None);
    1844         return Py_None;
     1950    char *path;
     1951    unsigned long flags;
     1952    int res;
     1953    if (!PyArg_ParseTuple(args, "etk:lchflags",
     1954                          Py_FileSystemDefaultEncoding, &path, &flags))
     1955        return NULL;
     1956    Py_BEGIN_ALLOW_THREADS
     1957    res = lchflags(path, flags);
     1958    Py_END_ALLOW_THREADS
     1959    if (res < 0)
     1960        return posix_error_with_allocated_filename(path);
     1961    PyMem_Free(path);
     1962    Py_INCREF(Py_None);
     1963    return Py_None;
    18451964}
    18461965#endif /* HAVE_LCHFLAGS */
     
    18541973posix_chroot(PyObject *self, PyObject *args)
    18551974{
    1856         return posix_1str(args, "et:chroot", chroot);
     1975    return posix_1str(args, "et:chroot", chroot);
    18571976}
    18581977#endif
     
    18661985posix_fsync(PyObject *self, PyObject *fdobj)
    18671986{
    1868        return posix_fildes(fdobj, fsync);
     1987    return posix_fildes(fdobj, fsync);
    18691988}
    18701989#endif /* HAVE_FSYNC */
     
    18842003posix_fdatasync(PyObject *self, PyObject *fdobj)
    18852004{
    1886        return posix_fildes(fdobj, fdatasync);
     2005    return posix_fildes(fdobj, fdatasync);
    18872006}
    18882007#endif /* HAVE_FDATASYNC */
     
    18972016posix_chown(PyObject *self, PyObject *args)
    18982017{
    1899         char *path = NULL;
    1900         long uid, gid;
    1901         int res;
    1902         if (!PyArg_ParseTuple(args, "etll:chown",
    1903                               Py_FileSystemDefaultEncoding, &path,
    1904                               &uid, &gid))
    1905                 return NULL;
    1906         Py_BEGIN_ALLOW_THREADS
    1907         res = chown(path, (uid_t) uid, (gid_t) gid);
    1908         Py_END_ALLOW_THREADS
    1909         if (res < 0)
    1910                 return posix_error_with_allocated_filename(path);
    1911         PyMem_Free(path);
    1912         Py_INCREF(Py_None);
    1913         return Py_None;
     2018    char *path = NULL;
     2019    uid_t uid;
     2020    gid_t gid;
     2021    int res;
     2022    if (!PyArg_ParseTuple(args, "etO&O&:chown",
     2023                          Py_FileSystemDefaultEncoding, &path,
     2024                          _Py_Uid_Converter, &uid,
     2025                          _Py_Gid_Converter, &gid))
     2026        return NULL;
     2027    Py_BEGIN_ALLOW_THREADS
     2028    res = chown(path, uid, gid);
     2029    Py_END_ALLOW_THREADS
     2030    if (res < 0)
     2031        return posix_error_with_allocated_filename(path);
     2032    PyMem_Free(path);
     2033    Py_INCREF(Py_None);
     2034    return Py_None;
    19142035}
    19152036#endif /* HAVE_CHOWN */
     
    19242045posix_fchown(PyObject *self, PyObject *args)
    19252046{
    1926         int fd;
    1927         long uid, gid;
    1928         int res;
    1929         if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid))
    1930                 return NULL;
    1931         Py_BEGIN_ALLOW_THREADS
    1932         res = fchown(fd, (uid_t) uid, (gid_t) gid);
    1933         Py_END_ALLOW_THREADS
    1934         if (res < 0)
    1935                 return posix_error();
    1936         Py_RETURN_NONE;
     2047    int fd;
     2048    uid_t uid;
     2049    gid_t gid;
     2050    int res;
     2051    if (!PyArg_ParseTuple(args, "iO&O&:fchown", &fd,
     2052                          _Py_Uid_Converter, &uid,
     2053                          _Py_Gid_Converter, &gid))
     2054        return NULL;
     2055    Py_BEGIN_ALLOW_THREADS
     2056    res = fchown(fd, uid, gid);
     2057    Py_END_ALLOW_THREADS
     2058    if (res < 0)
     2059        return posix_error();
     2060    Py_RETURN_NONE;
    19372061}
    19382062#endif /* HAVE_FCHOWN */
     
    19472071posix_lchown(PyObject *self, PyObject *args)
    19482072{
    1949         char *path = NULL;
    1950         long uid, gid;
    1951         int res;
    1952         if (!PyArg_ParseTuple(args, "etll:lchown",
    1953                               Py_FileSystemDefaultEncoding, &path,
    1954                               &uid, &gid))
    1955                 return NULL;
    1956         Py_BEGIN_ALLOW_THREADS
    1957         res = lchown(path, (uid_t) uid, (gid_t) gid);
    1958         Py_END_ALLOW_THREADS
    1959         if (res < 0)
    1960                 return posix_error_with_allocated_filename(path);
    1961         PyMem_Free(path);
    1962         Py_INCREF(Py_None);
    1963         return Py_None;
     2073    char *path = NULL;
     2074    uid_t uid;
     2075    gid_t gid;
     2076    int res;
     2077    if (!PyArg_ParseTuple(args, "etO&O&:lchown",
     2078                          Py_FileSystemDefaultEncoding, &path,
     2079                          _Py_Uid_Converter, &uid,
     2080                          _Py_Gid_Converter, &gid))
     2081        return NULL;
     2082    Py_BEGIN_ALLOW_THREADS
     2083    res = lchown(path, uid, gid);
     2084    Py_END_ALLOW_THREADS
     2085    if (res < 0)
     2086        return posix_error_with_allocated_filename(path);
     2087    PyMem_Free(path);
     2088    Py_INCREF(Py_None);
     2089    return Py_None;
    19642090}
    19652091#endif /* HAVE_LCHOWN */
     
    19712097Return a string representing the current working directory.");
    19722098
     2099#if (defined(__sun) && defined(__SVR4)) || \
     2100     defined(__OpenBSD__)               || \
     2101     defined(__NetBSD__)
     2102/* Issue 9185: getcwd() returns NULL/ERANGE indefinitely. */
    19732103static PyObject *
    19742104posix_getcwd(PyObject *self, PyObject *noargs)
    19752105{
    1976         int bufsize_incr = 1024;
    1977         int bufsize = 0;
    1978         char *tmpbuf = NULL;
    1979         char *res = NULL;
    1980         PyObject *dynamic_return;
    1981 
    1982         Py_BEGIN_ALLOW_THREADS
    1983         do {
    1984                 bufsize = bufsize + bufsize_incr;
    1985                 tmpbuf = malloc(bufsize);
    1986                 if (tmpbuf == NULL) {
    1987                         break;
    1988                 }
     2106    char buf[PATH_MAX+2];
     2107    char *res;
     2108
     2109    Py_BEGIN_ALLOW_THREADS
     2110    res = getcwd(buf, sizeof buf);
     2111    Py_END_ALLOW_THREADS
     2112
     2113    if (res == NULL)
     2114        return posix_error();
     2115
     2116    return PyString_FromString(buf);
     2117}
     2118#else
     2119static PyObject *
     2120posix_getcwd(PyObject *self, PyObject *noargs)
     2121{
     2122    int bufsize_incr = 1024;
     2123    int bufsize = 0;
     2124    char *tmpbuf = NULL;
     2125    char *res = NULL;
     2126    PyObject *dynamic_return;
     2127
     2128    Py_BEGIN_ALLOW_THREADS
     2129    do {
     2130        bufsize = bufsize + bufsize_incr;
     2131        tmpbuf = malloc(bufsize);
     2132        if (tmpbuf == NULL) {
     2133            break;
     2134        }
    19892135#if defined(PYOS_OS2) && defined(PYCC_GCC)
    1990                 res = _getcwd2(tmpbuf, bufsize);
     2136        res = _getcwd2(tmpbuf, bufsize);
    19912137#else
    1992                 res = getcwd(tmpbuf, bufsize);
    1993 #endif
    1994 
    1995                 if (res == NULL) {
    1996                         free(tmpbuf);
    1997                 }
    1998         } while ((res == NULL) && (errno == ERANGE));
    1999         Py_END_ALLOW_THREADS
    2000 
    2001         if (res == NULL)
    2002                 return posix_error();
    2003 
    2004         dynamic_return = PyString_FromString(tmpbuf);
    2005         free(tmpbuf);
    2006 
    2007         return dynamic_return;
    2008 }
     2138        res = getcwd(tmpbuf, bufsize);
     2139#endif
     2140
     2141        if (res == NULL) {
     2142            free(tmpbuf);
     2143        }
     2144    } while ((res == NULL) && (errno == ERANGE));
     2145    Py_END_ALLOW_THREADS
     2146
     2147    if (res == NULL)
     2148        return posix_error();
     2149
     2150    dynamic_return = PyString_FromString(tmpbuf);
     2151    free(tmpbuf);
     2152
     2153    return dynamic_return;
     2154}
     2155#endif /* getcwd() NULL/ERANGE workaround. */
    20092156
    20102157#ifdef Py_USING_UNICODE
     
    20162163posix_getcwdu(PyObject *self, PyObject *noargs)
    20172164{
    2018         char buf[1026];
    2019         char *res;
    2020 
    2021 #ifdef Py_WIN_WIDE_FILENAMES
    2022         DWORD len;
    2023         if (unicode_file_names()) {
    2024                 wchar_t wbuf[1026];
    2025                 wchar_t *wbuf2 = wbuf;
    2026                 PyObject *resobj;
    2027                 Py_BEGIN_ALLOW_THREADS
    2028                 len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf);
    2029                 /* If the buffer is large enough, len does not include the
    2030                    terminating \0. If the buffer is too small, len includes
    2031                    the space needed for the terminator. */
    2032                 if (len >= sizeof wbuf/ sizeof wbuf[0]) {
    2033                         wbuf2 = malloc(len * sizeof(wchar_t));
    2034                         if (wbuf2)
    2035                                 len = GetCurrentDirectoryW(len, wbuf2);
    2036                 }
    2037                 Py_END_ALLOW_THREADS
    2038                 if (!wbuf2) {
    2039                         PyErr_NoMemory();
    2040                         return NULL;
    2041                 }
    2042                 if (!len) {
    2043                         if (wbuf2 != wbuf) free(wbuf2);
    2044                         return win32_error("getcwdu", NULL);
    2045                 }
    2046                 resobj = PyUnicode_FromWideChar(wbuf2, len);
    2047                 if (wbuf2 != wbuf) free(wbuf2);
    2048                 return resobj;
    2049         }
    2050 #endif
    2051 
    2052         Py_BEGIN_ALLOW_THREADS
     2165    char buf[1026];
     2166    char *res;
     2167
     2168#ifdef MS_WINDOWS
     2169    DWORD len;
     2170    wchar_t wbuf[1026];
     2171    wchar_t *wbuf2 = wbuf;
     2172    PyObject *resobj;
     2173    Py_BEGIN_ALLOW_THREADS
     2174    len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf);
     2175    /* If the buffer is large enough, len does not include the
     2176       terminating \0. If the buffer is too small, len includes
     2177       the space needed for the terminator. */
     2178    if (len >= sizeof wbuf/ sizeof wbuf[0]) {
     2179        wbuf2 = malloc(len * sizeof(wchar_t));
     2180        if (wbuf2)
     2181            len = GetCurrentDirectoryW(len, wbuf2);
     2182    }
     2183    Py_END_ALLOW_THREADS
     2184    if (!wbuf2) {
     2185        PyErr_NoMemory();
     2186        return NULL;
     2187    }
     2188    if (!len) {
     2189        if (wbuf2 != wbuf) free(wbuf2);
     2190        return win32_error("getcwdu", NULL);
     2191    }
     2192    resobj = PyUnicode_FromWideChar(wbuf2, len);
     2193    if (wbuf2 != wbuf) free(wbuf2);
     2194    return resobj;
     2195#endif /* MS_WINDOWS */
     2196
     2197    Py_BEGIN_ALLOW_THREADS
    20532198#if defined(PYOS_OS2) && defined(PYCC_GCC)
    2054         res = _getcwd2(buf, sizeof buf);
     2199    res = _getcwd2(buf, sizeof buf);
    20552200#else
    2056         res = getcwd(buf, sizeof buf);
    2057 #endif
    2058         Py_END_ALLOW_THREADS
    2059         if (res == NULL)
    2060                 return posix_error();
    2061         return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict");
    2062 }
    2063 #endif
    2064 #endif
     2201    res = getcwd(buf, sizeof buf);
     2202#endif
     2203    Py_END_ALLOW_THREADS
     2204    if (res == NULL)
     2205        return posix_error();
     2206    return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict");
     2207}
     2208#endif /* Py_USING_UNICODE */
     2209#endif /* HAVE_GETCWD */
    20652210
    20662211
     
    20732218posix_link(PyObject *self, PyObject *args)
    20742219{
    2075         return posix_2str(args, "etet:link", link);
     2220    return posix_2str(args, "etet:link", link);
    20762221}
    20772222#endif /* HAVE_LINK */
     
    20822227Return a list containing the names of the entries in the directory.\n\
    20832228\n\
    2084         path: path of directory to list\n\
     2229    path: path of directory to list\n\
    20852230\n\
    20862231The list is in arbitrary order.  It does not include the special\n\
     
    20902235posix_listdir(PyObject *self, PyObject *args)
    20912236{
    2092         /* XXX Should redo this putting the (now four) versions of opendir
    2093            in separate files instead of having them all here... */
     2237    /* XXX Should redo this putting the (now four) versions of opendir
     2238       in separate files instead of having them all here... */
    20942239#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
    20952240
    2096         PyObject *d, *v;
    2097         HANDLE hFindFile;
    2098         BOOL result;
    2099         WIN32_FIND_DATA FileData;
    2100         char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */
    2101         char *bufptr = namebuf;
    2102         Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */
    2103 
    2104 #ifdef Py_WIN_WIDE_FILENAMES
    2105         /* If on wide-character-capable OS see if argument
    2106            is Unicode and if so use wide API.  */
    2107         if (unicode_file_names()) {
    2108                 PyObject *po;
    2109                 if (PyArg_ParseTuple(args, "U:listdir", &po)) {
    2110                         WIN32_FIND_DATAW wFileData;
    2111                         Py_UNICODE *wnamebuf;
    2112                         Py_UNICODE wch;
    2113                         /* Overallocate for \\*.*\0 */
    2114                         len = PyUnicode_GET_SIZE(po);
    2115                         wnamebuf = malloc((len + 5) * sizeof(wchar_t));
    2116                         if (!wnamebuf) {
    2117                                 PyErr_NoMemory();
    2118                                 return NULL;
    2119                         }
    2120                         wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po));
    2121                         wch = len > 0 ? wnamebuf[len-1] : '\0';
    2122                         if (wch != L'/' && wch != L'\\' && wch != L':')
    2123                                 wnamebuf[len++] = L'\\';
    2124                         wcscpy(wnamebuf + len, L"*.*");
    2125                         if ((d = PyList_New(0)) == NULL) {
    2126                                 free(wnamebuf);
    2127                                 return NULL;
    2128                         }
    2129                         hFindFile = FindFirstFileW(wnamebuf, &wFileData);
    2130                         if (hFindFile == INVALID_HANDLE_VALUE) {
    2131                                 int error = GetLastError();
    2132                                 if (error == ERROR_FILE_NOT_FOUND) {
    2133                                         free(wnamebuf);
    2134                                         return d;
    2135                                 }
    2136                                 Py_DECREF(d);
    2137                                 win32_error_unicode("FindFirstFileW", wnamebuf);
    2138                                 free(wnamebuf);
    2139                                 return NULL;
    2140                         }
    2141                         do {
    2142                                 /* Skip over . and .. */
    2143                                 if (wcscmp(wFileData.cFileName, L".") != 0 &&
    2144                                     wcscmp(wFileData.cFileName, L"..") != 0) {
    2145                                         v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName));
    2146                                         if (v == NULL) {
    2147                                                 Py_DECREF(d);
    2148                                                 d = NULL;
    2149                                                 break;
    2150                                         }
    2151                                         if (PyList_Append(d, v) != 0) {
    2152                                                 Py_DECREF(v);
    2153                                                 Py_DECREF(d);
    2154                                                 d = NULL;
    2155                                                 break;
    2156                                         }
    2157                                         Py_DECREF(v);
    2158                                 }
    2159                                 Py_BEGIN_ALLOW_THREADS
    2160                                 result = FindNextFileW(hFindFile, &wFileData);
    2161                                 Py_END_ALLOW_THREADS
    2162                                 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
    2163                                    it got to the end of the directory. */
    2164                                 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
    2165                                     Py_DECREF(d);
    2166                                     win32_error_unicode("FindNextFileW", wnamebuf);
    2167                                     FindClose(hFindFile);
    2168                                     free(wnamebuf);
    2169                                     return NULL;
    2170                                 }
    2171                         } while (result == TRUE);
    2172 
    2173                         if (FindClose(hFindFile) == FALSE) {
    2174                                 Py_DECREF(d);
    2175                                 win32_error_unicode("FindClose", wnamebuf);
    2176                                 free(wnamebuf);
    2177                                 return NULL;
    2178                         }
    2179                         free(wnamebuf);
    2180                         return d;
    2181                 }
    2182                 /* Drop the argument parsing error as narrow strings
    2183                    are also valid. */
    2184                 PyErr_Clear();
    2185         }
    2186 #endif
    2187 
    2188         if (!PyArg_ParseTuple(args, "et#:listdir",
    2189                               Py_FileSystemDefaultEncoding, &bufptr, &len))
    2190                 return NULL;
    2191         if (len > 0) {
    2192                 char ch = namebuf[len-1];
    2193                 if (ch != SEP && ch != ALTSEP && ch != ':')
    2194                         namebuf[len++] = '/';
    2195         }
    2196         strcpy(namebuf + len, "*.*");
    2197 
    2198         if ((d = PyList_New(0)) == NULL)
    2199                 return NULL;
    2200 
    2201         hFindFile = FindFirstFile(namebuf, &FileData);
    2202         if (hFindFile == INVALID_HANDLE_VALUE) {
    2203                 int error = GetLastError();
    2204                 if (error == ERROR_FILE_NOT_FOUND)
    2205                         return d;
    2206                 Py_DECREF(d);
    2207                 return win32_error("FindFirstFile", namebuf);
    2208         }
    2209         do {
    2210                 /* Skip over . and .. */
    2211                 if (strcmp(FileData.cFileName, ".") != 0 &&
    2212                     strcmp(FileData.cFileName, "..") != 0) {
    2213                         v = PyString_FromString(FileData.cFileName);
    2214                         if (v == NULL) {
    2215                                 Py_DECREF(d);
    2216                                 d = NULL;
    2217                                 break;
    2218                         }
    2219                         if (PyList_Append(d, v) != 0) {
    2220                                 Py_DECREF(v);
    2221                                 Py_DECREF(d);
    2222                                 d = NULL;
    2223                                 break;
    2224                         }
    2225                         Py_DECREF(v);
    2226                 }
    2227                 Py_BEGIN_ALLOW_THREADS
    2228                 result = FindNextFile(hFindFile, &FileData);
    2229                 Py_END_ALLOW_THREADS
    2230                 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
    2231                    it got to the end of the directory. */
    2232                 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
    2233                     Py_DECREF(d);
    2234                     win32_error("FindNextFile", namebuf);
    2235                     FindClose(hFindFile);
    2236                     return NULL;
    2237                 }
    2238         } while (result == TRUE);
    2239 
    2240         if (FindClose(hFindFile) == FALSE) {
    2241                 Py_DECREF(d);
    2242                 return win32_error("FindClose", namebuf);
    2243         }
    2244 
    2245         return d;
     2241    PyObject *d, *v;
     2242    HANDLE hFindFile;
     2243    BOOL result;
     2244    WIN32_FIND_DATA FileData;
     2245    char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */
     2246    char *bufptr = namebuf;
     2247    Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */
     2248
     2249    PyObject *po;
     2250    if (PyArg_ParseTuple(args, "U:listdir", &po)) {
     2251        WIN32_FIND_DATAW wFileData;
     2252        Py_UNICODE *wnamebuf;
     2253        /* Overallocate for \\*.*\0 */
     2254        len = PyUnicode_GET_SIZE(po);
     2255        wnamebuf = malloc((len + 5) * sizeof(wchar_t));
     2256        if (!wnamebuf) {
     2257            PyErr_NoMemory();
     2258            return NULL;
     2259        }
     2260        wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po));
     2261        if (len > 0) {
     2262            Py_UNICODE wch = wnamebuf[len-1];
     2263            if (wch != L'/' && wch != L'\\' && wch != L':')
     2264                wnamebuf[len++] = L'\\';
     2265            wcscpy(wnamebuf + len, L"*.*");
     2266        }
     2267        if ((d = PyList_New(0)) == NULL) {
     2268            free(wnamebuf);
     2269            return NULL;
     2270        }
     2271        Py_BEGIN_ALLOW_THREADS
     2272        hFindFile = FindFirstFileW(wnamebuf, &wFileData);
     2273        Py_END_ALLOW_THREADS
     2274        if (hFindFile == INVALID_HANDLE_VALUE) {
     2275            int error = GetLastError();
     2276            if (error == ERROR_FILE_NOT_FOUND) {
     2277                free(wnamebuf);
     2278                return d;
     2279            }
     2280            Py_DECREF(d);
     2281            win32_error_unicode("FindFirstFileW", wnamebuf);
     2282            free(wnamebuf);
     2283            return NULL;
     2284        }
     2285        do {
     2286            /* Skip over . and .. */
     2287            if (wcscmp(wFileData.cFileName, L".") != 0 &&
     2288                wcscmp(wFileData.cFileName, L"..") != 0) {
     2289                v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName));
     2290                if (v == NULL) {
     2291                    Py_DECREF(d);
     2292                    d = NULL;
     2293                    break;
     2294                }
     2295                if (PyList_Append(d, v) != 0) {
     2296                    Py_DECREF(v);
     2297                    Py_DECREF(d);
     2298                    d = NULL;
     2299                    break;
     2300                }
     2301                Py_DECREF(v);
     2302            }
     2303            Py_BEGIN_ALLOW_THREADS
     2304            result = FindNextFileW(hFindFile, &wFileData);
     2305            Py_END_ALLOW_THREADS
     2306            /* FindNextFile sets error to ERROR_NO_MORE_FILES if
     2307               it got to the end of the directory. */
     2308            if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
     2309                Py_DECREF(d);
     2310                win32_error_unicode("FindNextFileW", wnamebuf);
     2311                FindClose(hFindFile);
     2312                free(wnamebuf);
     2313                return NULL;
     2314            }
     2315        } while (result == TRUE);
     2316
     2317        if (FindClose(hFindFile) == FALSE) {
     2318            Py_DECREF(d);
     2319            win32_error_unicode("FindClose", wnamebuf);
     2320            free(wnamebuf);
     2321            return NULL;
     2322        }
     2323        free(wnamebuf);
     2324        return d;
     2325    }
     2326    /* Drop the argument parsing error as narrow strings
     2327       are also valid. */
     2328    PyErr_Clear();
     2329
     2330    if (!PyArg_ParseTuple(args, "et#:listdir",
     2331                          Py_FileSystemDefaultEncoding, &bufptr, &len))
     2332        return NULL;
     2333    if (len > 0) {
     2334        char ch = namebuf[len-1];
     2335        if (ch != SEP && ch != ALTSEP && ch != ':')
     2336            namebuf[len++] = '/';
     2337        strcpy(namebuf + len, "*.*");
     2338    }
     2339
     2340    if ((d = PyList_New(0)) == NULL)
     2341        return NULL;
     2342
     2343    Py_BEGIN_ALLOW_THREADS
     2344    hFindFile = FindFirstFile(namebuf, &FileData);
     2345    Py_END_ALLOW_THREADS
     2346    if (hFindFile == INVALID_HANDLE_VALUE) {
     2347        int error = GetLastError();
     2348        if (error == ERROR_FILE_NOT_FOUND)
     2349            return d;
     2350        Py_DECREF(d);
     2351        return win32_error("FindFirstFile", namebuf);
     2352    }
     2353    do {
     2354        /* Skip over . and .. */
     2355        if (strcmp(FileData.cFileName, ".") != 0 &&
     2356            strcmp(FileData.cFileName, "..") != 0) {
     2357            v = PyString_FromString(FileData.cFileName);
     2358            if (v == NULL) {
     2359                Py_DECREF(d);
     2360                d = NULL;
     2361                break;
     2362            }
     2363            if (PyList_Append(d, v) != 0) {
     2364                Py_DECREF(v);
     2365                Py_DECREF(d);
     2366                d = NULL;
     2367                break;
     2368            }
     2369            Py_DECREF(v);
     2370        }
     2371        Py_BEGIN_ALLOW_THREADS
     2372        result = FindNextFile(hFindFile, &FileData);
     2373        Py_END_ALLOW_THREADS
     2374        /* FindNextFile sets error to ERROR_NO_MORE_FILES if
     2375           it got to the end of the directory. */
     2376        if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
     2377            Py_DECREF(d);
     2378            win32_error("FindNextFile", namebuf);
     2379            FindClose(hFindFile);
     2380            return NULL;
     2381        }
     2382    } while (result == TRUE);
     2383
     2384    if (FindClose(hFindFile) == FALSE) {
     2385        Py_DECREF(d);
     2386        return win32_error("FindClose", namebuf);
     2387    }
     2388
     2389    return d;
    22462390
    22472391#elif defined(PYOS_OS2)
     
    22622406        return NULL;
    22632407    if (len >= MAX_PATH) {
    2264                 PyErr_SetString(PyExc_ValueError, "path too long");
     2408        PyErr_SetString(PyExc_ValueError, "path too long");
    22652409        return NULL;
    22662410    }
     
    22732417    strcpy(namebuf + len, "*.*");
    22742418
    2275         if ((d = PyList_New(0)) == NULL)
     2419    if ((d = PyList_New(0)) == NULL)
    22762420        return NULL;
    22772421
     
    23182462#else
    23192463
    2320         char *name = NULL;
    2321         PyObject *d, *v;
    2322         DIR *dirp;
    2323         struct dirent *ep;
    2324         int arg_is_unicode = 1;
    2325 
    2326         errno = 0;
    2327         if (!PyArg_ParseTuple(args, "U:listdir", &v)) {
    2328                 arg_is_unicode = 0;
    2329                 PyErr_Clear();
    2330         }
    2331         if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name))
    2332                 return NULL;
    2333         if ((dirp = opendir(name)) == NULL) {
    2334                 return posix_error_with_allocated_filename(name);
    2335         }
    2336         if ((d = PyList_New(0)) == NULL) {
    2337                 closedir(dirp);
    2338                 PyMem_Free(name);
    2339                 return NULL;
    2340         }
    2341         for (;;) {
    2342                 errno = 0;
    2343                 Py_BEGIN_ALLOW_THREADS
    2344                 ep = readdir(dirp);
    2345                 Py_END_ALLOW_THREADS
    2346                 if (ep == NULL) {
    2347                         if (errno == 0) {
    2348                                 break;
    2349                         } else {
    2350                                 closedir(dirp);
    2351                                 Py_DECREF(d);
    2352                                 return posix_error_with_allocated_filename(name);
    2353                         }
    2354                 }
    2355                 if (ep->d_name[0] == '.' &&
    2356                     (NAMLEN(ep) == 1 ||
    2357                      (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
    2358                         continue;
    2359                 v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep));
    2360                 if (v == NULL) {
    2361                         Py_DECREF(d);
    2362                         d = NULL;
    2363                         break;
    2364                 }
     2464    char *name = NULL;
     2465    PyObject *d, *v;
     2466    DIR *dirp;
     2467    struct dirent *ep;
     2468    int arg_is_unicode = 1;
     2469
     2470    errno = 0;
     2471    if (!PyArg_ParseTuple(args, "U:listdir", &v)) {
     2472        arg_is_unicode = 0;
     2473        PyErr_Clear();
     2474    }
     2475    if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name))
     2476        return NULL;
     2477    Py_BEGIN_ALLOW_THREADS
     2478    dirp = opendir(name);
     2479    Py_END_ALLOW_THREADS
     2480    if (dirp == NULL) {
     2481        return posix_error_with_allocated_filename(name);
     2482    }
     2483    if ((d = PyList_New(0)) == NULL) {
     2484        Py_BEGIN_ALLOW_THREADS
     2485        closedir(dirp);
     2486        Py_END_ALLOW_THREADS
     2487        PyMem_Free(name);
     2488        return NULL;
     2489    }
     2490    for (;;) {
     2491        errno = 0;
     2492        Py_BEGIN_ALLOW_THREADS
     2493        ep = readdir(dirp);
     2494        Py_END_ALLOW_THREADS
     2495        if (ep == NULL) {
     2496            if (errno == 0) {
     2497                break;
     2498            } else {
     2499                Py_BEGIN_ALLOW_THREADS
     2500                closedir(dirp);
     2501                Py_END_ALLOW_THREADS
     2502                Py_DECREF(d);
     2503                return posix_error_with_allocated_filename(name);
     2504            }
     2505        }
     2506        if (ep->d_name[0] == '.' &&
     2507            (NAMLEN(ep) == 1 ||
     2508             (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
     2509            continue;
     2510        v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep));
     2511        if (v == NULL) {
     2512            Py_DECREF(d);
     2513            d = NULL;
     2514            break;
     2515        }
    23652516#ifdef Py_USING_UNICODE
    2366                 if (arg_is_unicode) {
    2367                         PyObject *w;
    2368 
    2369                         w = PyUnicode_FromEncodedObject(v,
    2370                                         Py_FileSystemDefaultEncoding,
    2371                                         "strict");
    2372                         if (w != NULL) {
    2373                                 Py_DECREF(v);
    2374                                 v = w;
    2375                         }
    2376                         else {
    2377                                 /* fall back to the original byte string, as
    2378                                    discussed in patch #683592 */
    2379                                 PyErr_Clear();
    2380                         }
    2381                 }
    2382 #endif
    2383                 if (PyList_Append(d, v) != 0) {
    2384                         Py_DECREF(v);
    2385                         Py_DECREF(d);
    2386                         d = NULL;
    2387                         break;
    2388                 }
    2389                 Py_DECREF(v);
    2390         }
    2391         closedir(dirp);
    2392         PyMem_Free(name);
    2393 
    2394         return d;
     2517        if (arg_is_unicode) {
     2518            PyObject *w;
     2519
     2520            w = PyUnicode_FromEncodedObject(v,
     2521                                            Py_FileSystemDefaultEncoding,
     2522                                            "strict");
     2523            if (w != NULL) {
     2524                Py_DECREF(v);
     2525                v = w;
     2526            }
     2527            else {
     2528                /* fall back to the original byte string, as
     2529                   discussed in patch #683592 */
     2530                PyErr_Clear();
     2531            }
     2532        }
     2533#endif
     2534        if (PyList_Append(d, v) != 0) {
     2535            Py_DECREF(v);
     2536            Py_DECREF(d);
     2537            d = NULL;
     2538            break;
     2539        }
     2540        Py_DECREF(v);
     2541    }
     2542    Py_BEGIN_ALLOW_THREADS
     2543    closedir(dirp);
     2544    Py_END_ALLOW_THREADS
     2545    PyMem_Free(name);
     2546
     2547    return d;
    23952548
    23962549#endif /* which OS */
     
    24022555posix__getfullpathname(PyObject *self, PyObject *args)
    24032556{
    2404         /* assume encoded strings won't more than double no of chars */
    2405         char inbuf[MAX_PATH*2];
    2406         char *inbufp = inbuf;
    2407         Py_ssize_t insize = sizeof(inbuf);
    2408         char outbuf[MAX_PATH*2];
    2409         char *temp;
    2410 #ifdef Py_WIN_WIDE_FILENAMES
    2411         if (unicode_file_names()) {
    2412                 PyUnicodeObject *po;
    2413                 if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) {
    2414                         Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
    2415                         Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf;
    2416                         Py_UNICODE *wtemp;
    2417                         DWORD result;
    2418                         PyObject *v;
    2419                         result = GetFullPathNameW(wpath,
    2420                                                    sizeof(woutbuf)/sizeof(woutbuf[0]),
    2421                                                     woutbuf, &wtemp);
    2422                         if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) {
    2423                                 woutbufp = malloc(result * sizeof(Py_UNICODE));
    2424                                 if (!woutbufp)
    2425                                         return PyErr_NoMemory();
    2426                                 result = GetFullPathNameW(wpath, result, woutbufp, &wtemp);
    2427                         }
    2428                         if (result)
    2429                                 v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp));
    2430                         else
    2431                                 v = win32_error_unicode("GetFullPathNameW", wpath);
    2432                         if (woutbufp != woutbuf)
    2433                                 free(woutbufp);
    2434                         return v;
    2435                 }
    2436                 /* Drop the argument parsing error as narrow strings
    2437                    are also valid. */
    2438                 PyErr_Clear();
    2439         }
    2440 #endif
    2441         if (!PyArg_ParseTuple (args, "et#:_getfullpathname",
    2442                                Py_FileSystemDefaultEncoding, &inbufp,
    2443                                &insize))
    2444                 return NULL;
    2445         if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]),
    2446                              outbuf, &temp))
    2447                 return win32_error("GetFullPathName", inbuf);
    2448         if (PyUnicode_Check(PyTuple_GetItem(args, 0))) {
    2449                 return PyUnicode_Decode(outbuf, strlen(outbuf),
    2450                         Py_FileSystemDefaultEncoding, NULL);
    2451         }
    2452         return PyString_FromString(outbuf);
     2557    /* assume encoded strings won't more than double no of chars */
     2558    char inbuf[MAX_PATH*2];
     2559    char *inbufp = inbuf;
     2560    Py_ssize_t insize = sizeof(inbuf);
     2561    char outbuf[MAX_PATH*2];
     2562    char *temp;
     2563
     2564    PyUnicodeObject *po;
     2565    if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) {
     2566        Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
     2567        Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf;
     2568        Py_UNICODE *wtemp;
     2569        DWORD result;
     2570        PyObject *v;
     2571        result = GetFullPathNameW(wpath,
     2572                                  sizeof(woutbuf)/sizeof(woutbuf[0]),
     2573                                  woutbuf, &wtemp);
     2574        if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) {
     2575            woutbufp = malloc(result * sizeof(Py_UNICODE));
     2576            if (!woutbufp)
     2577                return PyErr_NoMemory();
     2578            result = GetFullPathNameW(wpath, result, woutbufp, &wtemp);
     2579        }
     2580        if (result)
     2581            v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp));
     2582        else
     2583            v = win32_error_unicode("GetFullPathNameW", wpath);
     2584        if (woutbufp != woutbuf)
     2585            free(woutbufp);
     2586        return v;
     2587    }
     2588    /* Drop the argument parsing error as narrow strings
     2589       are also valid. */
     2590    PyErr_Clear();
     2591
     2592    if (!PyArg_ParseTuple (args, "et#:_getfullpathname",
     2593                           Py_FileSystemDefaultEncoding, &inbufp,
     2594                           &insize))
     2595        return NULL;
     2596    if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]),
     2597                         outbuf, &temp))
     2598        return win32_error("GetFullPathName", inbuf);
     2599    if (PyUnicode_Check(PyTuple_GetItem(args, 0))) {
     2600        return PyUnicode_Decode(outbuf, strlen(outbuf),
     2601                                Py_FileSystemDefaultEncoding, NULL);
     2602    }
     2603    return PyString_FromString(outbuf);
    24532604} /* end of posix__getfullpathname */
    24542605#endif /* MS_WINDOWS */
     
    24612612posix_mkdir(PyObject *self, PyObject *args)
    24622613{
    2463         int res;
    2464         char *path = NULL;
    2465         int mode = 0777;
    2466 
    2467 #ifdef Py_WIN_WIDE_FILENAMES
    2468         if (unicode_file_names()) {
    2469                 PyUnicodeObject *po;
    2470                 if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) {
    2471                         Py_BEGIN_ALLOW_THREADS
    2472                         /* PyUnicode_AS_UNICODE OK without thread lock as
    2473                            it is a simple dereference. */
    2474                         res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL);
    2475                         Py_END_ALLOW_THREADS
    2476                         if (!res)
    2477                                 return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po));
    2478                         Py_INCREF(Py_None);
    2479                         return Py_None;
    2480                 }
    2481                 /* Drop the argument parsing error as narrow strings
    2482                    are also valid. */
    2483                 PyErr_Clear();
    2484         }
    2485         if (!PyArg_ParseTuple(args, "et|i:mkdir",
    2486                               Py_FileSystemDefaultEncoding, &path, &mode))
    2487                 return NULL;
    2488         Py_BEGIN_ALLOW_THREADS
    2489         /* PyUnicode_AS_UNICODE OK without thread lock as
    2490            it is a simple dereference. */
    2491         res = CreateDirectoryA(path, NULL);
    2492         Py_END_ALLOW_THREADS
    2493         if (!res) {
    2494                 win32_error("mkdir", path);
    2495                 PyMem_Free(path);
    2496                 return NULL;
    2497         }
    2498         PyMem_Free(path);
    2499         Py_INCREF(Py_None);
    2500         return Py_None;
     2614    int res;
     2615    char *path = NULL;
     2616    int mode = 0777;
     2617
     2618#ifdef MS_WINDOWS
     2619    PyUnicodeObject *po;
     2620    if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) {
     2621        Py_BEGIN_ALLOW_THREADS
     2622        /* PyUnicode_AS_UNICODE OK without thread lock as
     2623           it is a simple dereference. */
     2624        res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL);
     2625        Py_END_ALLOW_THREADS
     2626        if (!res)
     2627            return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po));
     2628        Py_INCREF(Py_None);
     2629        return Py_None;
     2630    }
     2631    /* Drop the argument parsing error as narrow strings
     2632       are also valid. */
     2633    PyErr_Clear();
     2634    if (!PyArg_ParseTuple(args, "et|i:mkdir",
     2635                          Py_FileSystemDefaultEncoding, &path, &mode))
     2636        return NULL;
     2637    Py_BEGIN_ALLOW_THREADS
     2638    /* PyUnicode_AS_UNICODE OK without thread lock as
     2639       it is a simple dereference. */
     2640    res = CreateDirectoryA(path, NULL);
     2641    Py_END_ALLOW_THREADS
     2642    if (!res) {
     2643        win32_error("mkdir", path);
     2644        PyMem_Free(path);
     2645        return NULL;
     2646    }
     2647    PyMem_Free(path);
     2648    Py_INCREF(Py_None);
     2649    return Py_None;
     2650#else /* MS_WINDOWS */
     2651
     2652    if (!PyArg_ParseTuple(args, "et|i:mkdir",
     2653                          Py_FileSystemDefaultEncoding, &path, &mode))
     2654        return NULL;
     2655    Py_BEGIN_ALLOW_THREADS
     2656#if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
     2657    res = mkdir(path);
    25012658#else
    2502 
    2503         if (!PyArg_ParseTuple(args, "et|i:mkdir",
    2504                               Py_FileSystemDefaultEncoding, &path, &mode))
    2505                 return NULL;
    2506         Py_BEGIN_ALLOW_THREADS
    2507 #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
    2508         res = mkdir(path);
    2509 #else
    2510         res = mkdir(path, mode);
    2511 #endif
    2512         Py_END_ALLOW_THREADS
    2513         if (res < 0)
    2514                 return posix_error_with_allocated_filename(path);
    2515         PyMem_Free(path);
    2516         Py_INCREF(Py_None);
    2517         return Py_None;
    2518 #endif
     2659    res = mkdir(path, mode);
     2660#endif
     2661    Py_END_ALLOW_THREADS
     2662    if (res < 0)
     2663        return posix_error_with_allocated_filename(path);
     2664    PyMem_Free(path);
     2665    Py_INCREF(Py_None);
     2666    return Py_None;
     2667#endif /* MS_WINDOWS */
    25192668}
    25202669
     
    25342683posix_nice(PyObject *self, PyObject *args)
    25352684{
    2536         int increment, value;
    2537 
    2538         if (!PyArg_ParseTuple(args, "i:nice", &increment))
    2539                 return NULL;
    2540 
    2541         /* There are two flavours of 'nice': one that returns the new
    2542            priority (as required by almost all standards out there) and the
    2543            Linux/FreeBSD/BSDI one, which returns '0' on success and advices
    2544            the use of getpriority() to get the new priority.
    2545 
    2546            If we are of the nice family that returns the new priority, we
    2547            need to clear errno before the call, and check if errno is filled
    2548            before calling posix_error() on a returnvalue of -1, because the
    2549            -1 may be the actual new priority! */
    2550 
    2551         errno = 0;
    2552         value = nice(increment);
     2685    int increment, value;
     2686
     2687    if (!PyArg_ParseTuple(args, "i:nice", &increment))
     2688        return NULL;
     2689
     2690    /* There are two flavours of 'nice': one that returns the new
     2691       priority (as required by almost all standards out there) and the
     2692       Linux/FreeBSD/BSDI one, which returns '0' on success and advices
     2693       the use of getpriority() to get the new priority.
     2694
     2695       If we are of the nice family that returns the new priority, we
     2696       need to clear errno before the call, and check if errno is filled
     2697       before calling posix_error() on a returnvalue of -1, because the
     2698       -1 may be the actual new priority! */
     2699
     2700    errno = 0;
     2701    value = nice(increment);
    25532702#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
    2554         if (value == 0)
    2555                 value = getpriority(PRIO_PROCESS, 0);
    2556 #endif
    2557         if (value == -1 && errno != 0)
    2558                 /* either nice() or getpriority() returned an error */
    2559                 return posix_error();
    2560         return PyInt_FromLong((long) value);
     2703    if (value == 0)
     2704        value = getpriority(PRIO_PROCESS, 0);
     2705#endif
     2706    if (value == -1 && errno != 0)
     2707        /* either nice() or getpriority() returned an error */
     2708        return posix_error();
     2709    return PyInt_FromLong((long) value);
    25612710}
    25622711#endif /* HAVE_NICE */
     
    25702719{
    25712720#ifdef MS_WINDOWS
    2572         PyObject *o1, *o2;
    2573         char *p1, *p2;
    2574         BOOL result;
    2575         if (unicode_file_names()) {
    2576             if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2))
    2577                 goto error;
    2578             if (!convert_to_unicode(&o1))
    2579                 goto error;
    2580             if (!convert_to_unicode(&o2)) {
    2581                 Py_DECREF(o1);
    2582                 goto error;
    2583             }
    2584             Py_BEGIN_ALLOW_THREADS
    2585             result = MoveFileW(PyUnicode_AsUnicode(o1),
    2586                                PyUnicode_AsUnicode(o2));
    2587             Py_END_ALLOW_THREADS
    2588             Py_DECREF(o1);
    2589             Py_DECREF(o2);
    2590             if (!result)
    2591                     return win32_error("rename", NULL);
    2592             Py_INCREF(Py_None);
    2593             return Py_None;
     2721    PyObject *o1, *o2;
     2722    char *p1, *p2;
     2723    BOOL result;
     2724    if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2))
     2725        goto error;
     2726    if (!convert_to_unicode(&o1))
     2727        goto error;
     2728    if (!convert_to_unicode(&o2)) {
     2729        Py_DECREF(o1);
     2730        goto error;
     2731    }
     2732    Py_BEGIN_ALLOW_THREADS
     2733    result = MoveFileW(PyUnicode_AsUnicode(o1),
     2734                       PyUnicode_AsUnicode(o2));
     2735    Py_END_ALLOW_THREADS
     2736    Py_DECREF(o1);
     2737    Py_DECREF(o2);
     2738    if (!result)
     2739        return win32_error("rename", NULL);
     2740    Py_INCREF(Py_None);
     2741    return Py_None;
    25942742error:
    2595             PyErr_Clear();
    2596         }
    2597         if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2))
    2598                 return NULL;
    2599         Py_BEGIN_ALLOW_THREADS
    2600         result = MoveFileA(p1, p2);
    2601         Py_END_ALLOW_THREADS
    2602         if (!result)
    2603                 return win32_error("rename", NULL);
    2604         Py_INCREF(Py_None);
    2605         return Py_None;
     2743    PyErr_Clear();
     2744    if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2))
     2745        return NULL;
     2746    Py_BEGIN_ALLOW_THREADS
     2747    result = MoveFileA(p1, p2);
     2748    Py_END_ALLOW_THREADS
     2749    if (!result)
     2750        return win32_error("rename", NULL);
     2751    Py_INCREF(Py_None);
     2752    return Py_None;
    26062753#else
    2607         return posix_2str(args, "etet:rename", rename);
     2754    return posix_2str(args, "etet:rename", rename);
    26082755#endif
    26092756}
     
    26182765{
    26192766#ifdef MS_WINDOWS
    2620         return win32_1str(args, "rmdir", "s:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW);
     2767    return win32_1str(args, "rmdir", "s:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW);
    26212768#else
    2622         return posix_1str(args, "et:rmdir", rmdir);
     2769    return posix_1str(args, "et:rmdir", rmdir);
    26232770#endif
    26242771}
     
    26332780{
    26342781#ifdef MS_WINDOWS
    2635         return posix_do_stat(self, args, "et:stat", STAT, "U:stat", win32_wstat);
     2782    return posix_do_stat(self, args, "et:stat", STAT, "U:stat", win32_wstat);
    26362783#else
    2637         return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL);
     2784    return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL);
    26382785#endif
    26392786}
     
    26482795posix_system(PyObject *self, PyObject *args)
    26492796{
    2650         char *command;
    2651         long sts;
    2652         if (!PyArg_ParseTuple(args, "s:system", &command))
    2653                 return NULL;
    2654         Py_BEGIN_ALLOW_THREADS
    2655         sts = system(command);
    2656         Py_END_ALLOW_THREADS
    2657         return PyInt_FromLong(sts);
     2797    char *command;
     2798    long sts;
     2799    if (!PyArg_ParseTuple(args, "s:system", &command))
     2800        return NULL;
     2801    Py_BEGIN_ALLOW_THREADS
     2802    sts = system(command);
     2803    Py_END_ALLOW_THREADS
     2804    return PyInt_FromLong(sts);
    26582805}
    26592806#endif
     
    26672814posix_umask(PyObject *self, PyObject *args)
    26682815{
    2669         int i;
    2670         if (!PyArg_ParseTuple(args, "i:umask", &i))
    2671                 return NULL;
    2672         i = (int)umask(i);
    2673         if (i < 0)
    2674                 return posix_error();
    2675         return PyInt_FromLong((long)i);
     2816    int i;
     2817    if (!PyArg_ParseTuple(args, "i:umask", &i))
     2818        return NULL;
     2819    i = (int)umask(i);
     2820    if (i < 0)
     2821        return posix_error();
     2822    return PyInt_FromLong((long)i);
    26762823}
    26772824
     
    26892836{
    26902837#ifdef MS_WINDOWS
    2691         return win32_1str(args, "remove", "s:remove", DeleteFileA, "U:remove", DeleteFileW);
     2838    return win32_1str(args, "remove", "s:remove", DeleteFileA, "U:remove", DeleteFileW);
    26922839#else
    2693         return posix_1str(args, "et:remove", unlink);
     2840    return posix_1str(args, "et:remove", unlink);
    26942841#endif
    26952842}
     
    27042851posix_uname(PyObject *self, PyObject *noargs)
    27052852{
    2706         struct utsname u;
    2707         int res;
    2708 
    2709         Py_BEGIN_ALLOW_THREADS
    2710         res = uname(&u);
    2711         Py_END_ALLOW_THREADS
    2712         if (res < 0)
    2713                 return posix_error();
    2714         return Py_BuildValue("(sssss)",
    2715                              u.sysname,
    2716                              u.nodename,
    2717                              u.release,
    2718                              u.version,
    2719                              u.machine);
     2853    struct utsname u;
     2854    int res;
     2855
     2856    Py_BEGIN_ALLOW_THREADS
     2857    res = uname(&u);
     2858    Py_END_ALLOW_THREADS
     2859    if (res < 0)
     2860        return posix_error();
     2861    return Py_BuildValue("(sssss)",
     2862                         u.sysname,
     2863                         u.nodename,
     2864                         u.release,
     2865                         u.version,
     2866                         u.machine);
    27202867}
    27212868#endif /* HAVE_UNAME */
    27222869
    27232870static int
    2724 extract_time(PyObject *t, long* sec, long* usec)
    2725 {
    2726         long intval;
    2727         if (PyFloat_Check(t)) {
    2728                 double tval = PyFloat_AsDouble(t);
    2729                 PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t);
    2730                 if (!intobj)
    2731                         return -1;
    2732                 intval = PyInt_AsLong(intobj);
    2733                 Py_DECREF(intobj);
    2734                 if (intval == -1 && PyErr_Occurred())
    2735                         return -1;
    2736                 *sec = intval;
    2737                 *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */
    2738                 if (*usec < 0)
    2739                         /* If rounding gave us a negative number,
    2740                            truncate.  */
    2741                         *usec = 0;
    2742                 return 0;
    2743         }
    2744         intval = PyInt_AsLong(t);
    2745         if (intval == -1 && PyErr_Occurred())
    2746                 return -1;
    2747         *sec = intval;
    2748         *usec = 0;
     2871extract_time(PyObject *t, time_t* sec, long* usec)
     2872{
     2873    time_t intval;
     2874    if (PyFloat_Check(t)) {
     2875        double tval = PyFloat_AsDouble(t);
     2876        PyObject *intobj = PyNumber_Long(t);
     2877        if (!intobj)
     2878            return -1;
     2879#if SIZEOF_TIME_T > SIZEOF_LONG
     2880        intval = PyInt_AsUnsignedLongLongMask(intobj);
     2881#else
     2882        intval = PyInt_AsLong(intobj);
     2883#endif
     2884        Py_DECREF(intobj);
     2885        if (intval == -1 && PyErr_Occurred())
     2886            return -1;
     2887        *sec = intval;
     2888        *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */
     2889        if (*usec < 0)
     2890            /* If rounding gave us a negative number,
     2891               truncate.  */
     2892            *usec = 0;
    27492893        return 0;
     2894    }
     2895#if SIZEOF_TIME_T > SIZEOF_LONG
     2896    intval = PyInt_AsUnsignedLongLongMask(t);
     2897#else
     2898    intval = PyInt_AsLong(t);
     2899#endif
     2900    if (intval == -1 && PyErr_Occurred())
     2901        return -1;
     2902    *sec = intval;
     2903    *usec = 0;
     2904    return 0;
    27502905}
    27512906
     
    27592914posix_utime(PyObject *self, PyObject *args)
    27602915{
    2761 #ifdef Py_WIN_WIDE_FILENAMES
    2762         PyObject *arg;
    2763         PyUnicodeObject *obwpath;
    2764         wchar_t *wpath = NULL;
    2765         char *apath = NULL;
    2766         HANDLE hFile;
    2767         long atimesec, mtimesec, ausec, musec;
    2768         FILETIME atime, mtime;
    2769         PyObject *result = NULL;
    2770 
    2771         if (unicode_file_names()) {
    2772                 if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) {
    2773                         wpath = PyUnicode_AS_UNICODE(obwpath);
    2774                         Py_BEGIN_ALLOW_THREADS
    2775                         hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0,
    2776                                             NULL, OPEN_EXISTING,
    2777                                             FILE_FLAG_BACKUP_SEMANTICS, NULL);
    2778                         Py_END_ALLOW_THREADS
    2779                         if (hFile == INVALID_HANDLE_VALUE)
    2780                                 return win32_error_unicode("utime", wpath);
    2781                 } else
    2782                         /* Drop the argument parsing error as narrow strings
    2783                            are also valid. */
    2784                         PyErr_Clear();
    2785         }
    2786         if (!wpath) {
    2787                 if (!PyArg_ParseTuple(args, "etO:utime",
    2788                                 Py_FileSystemDefaultEncoding, &apath, &arg))
    2789                         return NULL;
    2790                 Py_BEGIN_ALLOW_THREADS
    2791                 hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0,
    2792                                     NULL, OPEN_EXISTING,
    2793                                     FILE_FLAG_BACKUP_SEMANTICS, NULL);
    2794                 Py_END_ALLOW_THREADS
    2795                 if (hFile == INVALID_HANDLE_VALUE) {
    2796                         win32_error("utime", apath);
    2797                         PyMem_Free(apath);
    2798                         return NULL;
    2799                 }
    2800                 PyMem_Free(apath);
    2801         }
    2802        
    2803         if (arg == Py_None) {
    2804                 SYSTEMTIME now;
    2805                 GetSystemTime(&now);
    2806                 if (!SystemTimeToFileTime(&now, &mtime) ||
    2807                     !SystemTimeToFileTime(&now, &atime)) {
    2808                         win32_error("utime", NULL);
    2809                         goto done;
    2810                     }
    2811         }
    2812         else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
    2813                 PyErr_SetString(PyExc_TypeError,
    2814                                 "utime() arg 2 must be a tuple (atime, mtime)");
    2815                 goto done;
    2816         }
    2817         else {
    2818                 if (extract_time(PyTuple_GET_ITEM(arg, 0),
    2819                                  &atimesec, &ausec) == -1)
    2820                         goto done;
    2821                 time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime);
    2822                 if (extract_time(PyTuple_GET_ITEM(arg, 1),
    2823                                  &mtimesec, &musec) == -1)
    2824                         goto done;
    2825                 time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime);
    2826         }
    2827         if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
    2828                 /* Avoid putting the file name into the error here,
    2829                    as that may confuse the user into believing that
    2830                    something is wrong with the file, when it also
    2831                    could be the time stamp that gives a problem. */
    2832                 win32_error("utime", NULL);
    2833         }
    2834         Py_INCREF(Py_None);
    2835         result = Py_None;
     2916#ifdef MS_WINDOWS
     2917    PyObject *arg;
     2918    PyUnicodeObject *obwpath;
     2919    wchar_t *wpath = NULL;
     2920    char *apath = NULL;
     2921    HANDLE hFile;
     2922    time_t atimesec, mtimesec;
     2923    long ausec, musec;
     2924    FILETIME atime, mtime;
     2925    PyObject *result = NULL;
     2926
     2927    if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) {
     2928        wpath = PyUnicode_AS_UNICODE(obwpath);
     2929        Py_BEGIN_ALLOW_THREADS
     2930        hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0,
     2931                            NULL, OPEN_EXISTING,
     2932                            FILE_FLAG_BACKUP_SEMANTICS, NULL);
     2933        Py_END_ALLOW_THREADS
     2934        if (hFile == INVALID_HANDLE_VALUE)
     2935            return win32_error_unicode("utime", wpath);
     2936    } else
     2937        /* Drop the argument parsing error as narrow strings
     2938           are also valid. */
     2939        PyErr_Clear();
     2940
     2941    if (!wpath) {
     2942        if (!PyArg_ParseTuple(args, "etO:utime",
     2943                              Py_FileSystemDefaultEncoding, &apath, &arg))
     2944            return NULL;
     2945        Py_BEGIN_ALLOW_THREADS
     2946        hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0,
     2947                            NULL, OPEN_EXISTING,
     2948                            FILE_FLAG_BACKUP_SEMANTICS, NULL);
     2949        Py_END_ALLOW_THREADS
     2950        if (hFile == INVALID_HANDLE_VALUE) {
     2951            win32_error("utime", apath);
     2952            PyMem_Free(apath);
     2953            return NULL;
     2954        }
     2955        PyMem_Free(apath);
     2956    }
     2957
     2958    if (arg == Py_None) {
     2959        SYSTEMTIME now;
     2960        GetSystemTime(&now);
     2961        if (!SystemTimeToFileTime(&now, &mtime) ||
     2962            !SystemTimeToFileTime(&now, &atime)) {
     2963            win32_error("utime", NULL);
     2964            goto done;
     2965        }
     2966    }
     2967    else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
     2968        PyErr_SetString(PyExc_TypeError,
     2969                        "utime() arg 2 must be a tuple (atime, mtime)");
     2970        goto done;
     2971    }
     2972    else {
     2973        if (extract_time(PyTuple_GET_ITEM(arg, 0),
     2974                         &atimesec, &ausec) == -1)
     2975            goto done;
     2976        time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime);
     2977        if (extract_time(PyTuple_GET_ITEM(arg, 1),
     2978                         &mtimesec, &musec) == -1)
     2979            goto done;
     2980        time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime);
     2981    }
     2982    if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
     2983        /* Avoid putting the file name into the error here,
     2984           as that may confuse the user into believing that
     2985           something is wrong with the file, when it also
     2986           could be the time stamp that gives a problem. */
     2987        win32_error("utime", NULL);
     2988        goto done;
     2989    }
     2990    Py_INCREF(Py_None);
     2991    result = Py_None;
    28362992done:
    2837         CloseHandle(hFile);
    2838         return result;
    2839 #else /* Py_WIN_WIDE_FILENAMES */
    2840 
    2841         char *path = NULL;
    2842         long atime, mtime, ausec, musec;
    2843         int res;
    2844         PyObject* arg;
     2993    CloseHandle(hFile);
     2994    return result;
     2995#else /* MS_WINDOWS */
     2996
     2997    char *path = NULL;
     2998    time_t atime, mtime;
     2999    long ausec, musec;
     3000    int res;
     3001    PyObject* arg;
    28453002
    28463003#if defined(HAVE_UTIMES)
    2847         struct timeval buf[2];
     3004    struct timeval buf[2];
    28483005#define ATIME buf[0].tv_sec
    28493006#define MTIME buf[1].tv_sec
    28503007#elif defined(HAVE_UTIME_H)
    28513008/* XXX should define struct utimbuf instead, above */
    2852         struct utimbuf buf;
     3009    struct utimbuf buf;
    28533010#define ATIME buf.actime
    28543011#define MTIME buf.modtime
    28553012#define UTIME_ARG &buf
    28563013#else /* HAVE_UTIMES */
    2857         time_t buf[2];
     3014    time_t buf[2];
    28583015#define ATIME buf[0]
    28593016#define MTIME buf[1]
     
    28623019
    28633020
    2864         if (!PyArg_ParseTuple(args, "etO:utime",
    2865                                   Py_FileSystemDefaultEncoding, &path, &arg))
    2866                 return NULL;
    2867         if (arg == Py_None) {
    2868                 /* optional time values not given */
    2869                 Py_BEGIN_ALLOW_THREADS
    2870                 res = utime(path, NULL);
    2871                 Py_END_ALLOW_THREADS
    2872         }
    2873         else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
    2874                 PyErr_SetString(PyExc_TypeError,
    2875                                 "utime() arg 2 must be a tuple (atime, mtime)");
    2876                 PyMem_Free(path);
    2877                 return NULL;
    2878         }
    2879         else {
    2880                 if (extract_time(PyTuple_GET_ITEM(arg, 0),
    2881                                 &atime, &ausec) == -1) {
    2882                         PyMem_Free(path);
    2883                         return NULL;
    2884                 }
    2885                 if (extract_time(PyTuple_GET_ITEM(arg, 1),
    2886                                 &mtime, &musec) == -1) {
    2887                         PyMem_Free(path);
    2888                         return NULL;
    2889                 }
    2890                 ATIME = atime;
    2891                 MTIME = mtime;
     3021    if (!PyArg_ParseTuple(args, "etO:utime",
     3022                          Py_FileSystemDefaultEncoding, &path, &arg))
     3023        return NULL;
     3024    if (arg == Py_None) {
     3025        /* optional time values not given */
     3026        Py_BEGIN_ALLOW_THREADS
     3027        res = utime(path, NULL);
     3028        Py_END_ALLOW_THREADS
     3029    }
     3030    else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
     3031        PyErr_SetString(PyExc_TypeError,
     3032                        "utime() arg 2 must be a tuple (atime, mtime)");
     3033        PyMem_Free(path);
     3034        return NULL;
     3035    }
     3036    else {
     3037        if (extract_time(PyTuple_GET_ITEM(arg, 0),
     3038                        &atime, &ausec) == -1) {
     3039            PyMem_Free(path);
     3040            return NULL;
     3041        }
     3042        if (extract_time(PyTuple_GET_ITEM(arg, 1),
     3043                        &mtime, &musec) == -1) {
     3044            PyMem_Free(path);
     3045            return NULL;
     3046        }
     3047        ATIME = atime;
     3048        MTIME = mtime;
    28923049#ifdef HAVE_UTIMES
    2893                 buf[0].tv_usec = ausec;
    2894                 buf[1].tv_usec = musec;
    2895                 Py_BEGIN_ALLOW_THREADS
    2896                 res = utimes(path, buf);
    2897                 Py_END_ALLOW_THREADS
     3050        buf[0].tv_usec = ausec;
     3051        buf[1].tv_usec = musec;
     3052        Py_BEGIN_ALLOW_THREADS
     3053        res = utimes(path, buf);
     3054        Py_END_ALLOW_THREADS
    28983055#else
    2899                 Py_BEGIN_ALLOW_THREADS
    2900                 res = utime(path, UTIME_ARG);
    2901                 Py_END_ALLOW_THREADS
     3056        Py_BEGIN_ALLOW_THREADS
     3057        res = utime(path, UTIME_ARG);
     3058        Py_END_ALLOW_THREADS
    29023059#endif /* HAVE_UTIMES */
    2903         }
    2904         if (res < 0) {
    2905                 return posix_error_with_allocated_filename(path);
    2906         }
    2907         PyMem_Free(path);
    2908         Py_INCREF(Py_None);
    2909         return Py_None;
     3060    }
     3061    if (res < 0) {
     3062        return posix_error_with_allocated_filename(path);
     3063    }
     3064    PyMem_Free(path);
     3065    Py_INCREF(Py_None);
     3066    return Py_None;
    29103067#undef UTIME_ARG
    29113068#undef ATIME
    29123069#undef MTIME
    2913 #endif /* Py_WIN_WIDE_FILENAMES */
     3070#endif /* MS_WINDOWS */
    29143071}
    29153072
     
    29243081posix__exit(PyObject *self, PyObject *args)
    29253082{
    2926         int sts;
    2927         if (!PyArg_ParseTuple(args, "i:_exit", &sts))
    2928                 return NULL;
    2929         _exit(sts);
    2930         return NULL; /* Make gcc -Wall happy */
     3083    int sts;
     3084    if (!PyArg_ParseTuple(args, "i:_exit", &sts))
     3085        return NULL;
     3086    _exit(sts);
     3087    return NULL; /* Make gcc -Wall happy */
    29313088}
    29323089
     
    29353092free_string_array(char **array, Py_ssize_t count)
    29363093{
    2937         Py_ssize_t i;
    2938         for (i = 0; i < count; i++)
    2939                 PyMem_Free(array[i]);
    2940         PyMem_DEL(array);
     3094    Py_ssize_t i;
     3095    for (i = 0; i < count; i++)
     3096        PyMem_Free(array[i]);
     3097    PyMem_DEL(array);
    29413098}
    29423099#endif
     
    29483105Execute an executable path with arguments, replacing current process.\n\
    29493106\n\
    2950         path: path of executable file\n\
    2951         args: tuple or list of strings");
     3107    path: path of executable file\n\
     3108    args: tuple or list of strings");
    29523109
    29533110static PyObject *
    29543111posix_execv(PyObject *self, PyObject *args)
    29553112{
    2956         char *path;
    2957         PyObject *argv;
    2958         char **argvlist;
    2959         Py_ssize_t i, argc;
    2960         PyObject *(*getitem)(PyObject *, Py_ssize_t);
    2961 
    2962         /* execv has two arguments: (path, argv), where
    2963            argv is a list or tuple of strings. */
    2964 
    2965         if (!PyArg_ParseTuple(args, "etO:execv",
    2966                               Py_FileSystemDefaultEncoding,
    2967                               &path, &argv))
    2968                 return NULL;
    2969         if (PyList_Check(argv)) {
    2970                 argc = PyList_Size(argv);
    2971                 getitem = PyList_GetItem;
    2972         }
    2973         else if (PyTuple_Check(argv)) {
    2974                 argc = PyTuple_Size(argv);
    2975                 getitem = PyTuple_GetItem;
    2976         }
    2977         else {
    2978                 PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list");
    2979                 PyMem_Free(path);
    2980                 return NULL;
    2981         }
    2982 
    2983         argvlist = PyMem_NEW(char *, argc+1);
    2984         if (argvlist == NULL) {
    2985                 PyMem_Free(path);
    2986                 return PyErr_NoMemory();
    2987         }
    2988         for (i = 0; i < argc; i++) {
    2989                 if (!PyArg_Parse((*getitem)(argv, i), "et",
    2990                                  Py_FileSystemDefaultEncoding,
    2991                                  &argvlist[i])) {
    2992                         free_string_array(argvlist, i);
    2993                         PyErr_SetString(PyExc_TypeError,
    2994                                         "execv() arg 2 must contain only strings");
    2995                         PyMem_Free(path);
    2996                         return NULL;
    2997 
    2998                 }
    2999         }
    3000         argvlist[argc] = NULL;
    3001 
    3002         execv(path, argvlist);
    3003 
    3004         /* If we get here it's definitely an error */
    3005 
    3006         free_string_array(argvlist, argc);
    3007         PyMem_Free(path);
    3008         return posix_error();
     3113    char *path;
     3114    PyObject *argv;
     3115    char **argvlist;
     3116    Py_ssize_t i, argc;
     3117    PyObject *(*getitem)(PyObject *, Py_ssize_t);
     3118
     3119    /* execv has two arguments: (path, argv), where
     3120       argv is a list or tuple of strings. */
     3121
     3122    if (!PyArg_ParseTuple(args, "etO:execv",
     3123                          Py_FileSystemDefaultEncoding,
     3124                          &path, &argv))
     3125        return NULL;
     3126    if (PyList_Check(argv)) {
     3127        argc = PyList_Size(argv);
     3128        getitem = PyList_GetItem;
     3129    }
     3130    else if (PyTuple_Check(argv)) {
     3131        argc = PyTuple_Size(argv);
     3132        getitem = PyTuple_GetItem;
     3133    }
     3134    else {
     3135        PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list");
     3136        PyMem_Free(path);
     3137        return NULL;
     3138    }
     3139    if (argc < 1) {
     3140        PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
     3141        PyMem_Free(path);
     3142        return NULL;
     3143    }
     3144
     3145    argvlist = PyMem_NEW(char *, argc+1);
     3146    if (argvlist == NULL) {
     3147        PyMem_Free(path);
     3148        return PyErr_NoMemory();
     3149    }
     3150    for (i = 0; i < argc; i++) {
     3151        if (!PyArg_Parse((*getitem)(argv, i), "et",
     3152                         Py_FileSystemDefaultEncoding,
     3153                         &argvlist[i])) {
     3154            free_string_array(argvlist, i);
     3155            PyErr_SetString(PyExc_TypeError,
     3156                            "execv() arg 2 must contain only strings");
     3157            PyMem_Free(path);
     3158            return NULL;
     3159
     3160        }
     3161    }
     3162    argvlist[argc] = NULL;
     3163
     3164    execv(path, argvlist);
     3165
     3166    /* If we get here it's definitely an error */
     3167
     3168    free_string_array(argvlist, argc);
     3169    PyMem_Free(path);
     3170    return posix_error();
    30093171}
    30103172
     
    30143176Execute a path with arguments and environment, replacing current process.\n\
    30153177\n\
    3016         path: path of executable file\n\
    3017         args: tuple or list of arguments\n\
    3018         env: dictionary of strings mapping to strings");
     3178    path: path of executable file\n\
     3179    args: tuple or list of arguments\n\
     3180    env: dictionary of strings mapping to strings");
    30193181
    30203182static PyObject *
    30213183posix_execve(PyObject *self, PyObject *args)
    30223184{
    3023         char *path;
    3024         PyObject *argv, *env;
    3025         char **argvlist;
    3026         char **envlist;
    3027         PyObject *key, *val, *keys=NULL, *vals=NULL;
    3028         Py_ssize_t i, pos, argc, envc;
    3029         PyObject *(*getitem)(PyObject *, Py_ssize_t);
    3030         Py_ssize_t lastarg = 0;
    3031 
    3032         /* execve has three arguments: (path, argv, env), where
    3033            argv is a list or tuple of strings and env is a dictionary
    3034            like posix.environ. */
    3035 
    3036         if (!PyArg_ParseTuple(args, "etOO:execve",
    3037                               Py_FileSystemDefaultEncoding,
    3038                               &path, &argv, &env))
    3039                 return NULL;
    3040         if (PyList_Check(argv)) {
    3041                 argc = PyList_Size(argv);
    3042                 getitem = PyList_GetItem;
    3043         }
    3044         else if (PyTuple_Check(argv)) {
    3045                 argc = PyTuple_Size(argv);
    3046                 getitem = PyTuple_GetItem;
    3047         }
    3048         else {
    3049                 PyErr_SetString(PyExc_TypeError,
    3050                                 "execve() arg 2 must be a tuple or list");
    3051                 goto fail_0;
    3052         }
    3053         if (!PyMapping_Check(env)) {
    3054                 PyErr_SetString(PyExc_TypeError,
    3055                                 "execve() arg 3 must be a mapping object");
    3056                 goto fail_0;
    3057         }
    3058 
    3059         argvlist = PyMem_NEW(char *, argc+1);
    3060         if (argvlist == NULL) {
    3061                 PyErr_NoMemory();
    3062                 goto fail_0;
    3063         }
    3064         for (i = 0; i < argc; i++) {
    3065                 if (!PyArg_Parse((*getitem)(argv, i),
    3066                                 "et;execve() arg 2 must contain only strings",
    3067                                 Py_FileSystemDefaultEncoding,
    3068                                 &argvlist[i]))
    3069                 {
    3070                         lastarg = i;
    3071                         goto fail_1;
    3072                 }
    3073         }
    3074         lastarg = argc;
    3075         argvlist[argc] = NULL;
    3076 
    3077         i = PyMapping_Size(env);
    3078         if (i < 0)
    3079                 goto fail_1;
    3080         envlist = PyMem_NEW(char *, i + 1);
    3081         if (envlist == NULL) {
    3082                 PyErr_NoMemory();
    3083                 goto fail_1;
    3084         }
    3085         envc = 0;
    3086         keys = PyMapping_Keys(env);
    3087         vals = PyMapping_Values(env);
    3088         if (!keys || !vals)
    3089                 goto fail_2;
    3090         if (!PyList_Check(keys) || !PyList_Check(vals)) {
    3091                 PyErr_SetString(PyExc_TypeError,
    3092                         "execve(): env.keys() or env.values() is not a list");
    3093                 goto fail_2;
    3094         }
    3095 
    3096         for (pos = 0; pos < i; pos++) {
    3097                 char *p, *k, *v;
    3098                 size_t len;
    3099 
    3100                 key = PyList_GetItem(keys, pos);
    3101                 val = PyList_GetItem(vals, pos);
    3102                 if (!key || !val)
    3103                         goto fail_2;
    3104 
    3105                 if (!PyArg_Parse(
    3106                             key,
    3107                             "s;execve() arg 3 contains a non-string key",
    3108                             &k) ||
    3109                     !PyArg_Parse(
    3110                             val,
    3111                             "s;execve() arg 3 contains a non-string value",
    3112                             &v))
    3113                 {
    3114                         goto fail_2;
    3115                 }
     3185    char *path;
     3186    PyObject *argv, *env;
     3187    char **argvlist;
     3188    char **envlist;
     3189    PyObject *key, *val, *keys=NULL, *vals=NULL;
     3190    Py_ssize_t i, pos, argc, envc;
     3191    PyObject *(*getitem)(PyObject *, Py_ssize_t);
     3192    Py_ssize_t lastarg = 0;
     3193
     3194    /* execve has three arguments: (path, argv, env), where
     3195       argv is a list or tuple of strings and env is a dictionary
     3196       like posix.environ. */
     3197
     3198    if (!PyArg_ParseTuple(args, "etOO:execve",
     3199                          Py_FileSystemDefaultEncoding,
     3200                          &path, &argv, &env))
     3201        return NULL;
     3202    if (PyList_Check(argv)) {
     3203        argc = PyList_Size(argv);
     3204        getitem = PyList_GetItem;
     3205    }
     3206    else if (PyTuple_Check(argv)) {
     3207        argc = PyTuple_Size(argv);
     3208        getitem = PyTuple_GetItem;
     3209    }
     3210    else {
     3211        PyErr_SetString(PyExc_TypeError,
     3212                        "execve() arg 2 must be a tuple or list");
     3213        goto fail_0;
     3214    }
     3215    if (!PyMapping_Check(env)) {
     3216        PyErr_SetString(PyExc_TypeError,
     3217                        "execve() arg 3 must be a mapping object");
     3218        goto fail_0;
     3219    }
     3220
     3221    argvlist = PyMem_NEW(char *, argc+1);
     3222    if (argvlist == NULL) {
     3223        PyErr_NoMemory();
     3224        goto fail_0;
     3225    }
     3226    for (i = 0; i < argc; i++) {
     3227        if (!PyArg_Parse((*getitem)(argv, i),
     3228                        "et;execve() arg 2 must contain only strings",
     3229                        Py_FileSystemDefaultEncoding,
     3230                        &argvlist[i]))
     3231        {
     3232            lastarg = i;
     3233            goto fail_1;
     3234        }
     3235    }
     3236    lastarg = argc;
     3237    argvlist[argc] = NULL;
     3238
     3239    i = PyMapping_Size(env);
     3240    if (i < 0)
     3241        goto fail_1;
     3242    envlist = PyMem_NEW(char *, i + 1);
     3243    if (envlist == NULL) {
     3244        PyErr_NoMemory();
     3245        goto fail_1;
     3246    }
     3247    envc = 0;
     3248    keys = PyMapping_Keys(env);
     3249    vals = PyMapping_Values(env);
     3250    if (!keys || !vals)
     3251        goto fail_2;
     3252    if (!PyList_Check(keys) || !PyList_Check(vals)) {
     3253        PyErr_SetString(PyExc_TypeError,
     3254                        "execve(): env.keys() or env.values() is not a list");
     3255        goto fail_2;
     3256    }
     3257
     3258    for (pos = 0; pos < i; pos++) {
     3259        char *p, *k, *v;
     3260        size_t len;
     3261
     3262        key = PyList_GetItem(keys, pos);
     3263        val = PyList_GetItem(vals, pos);
     3264        if (!key || !val)
     3265            goto fail_2;
     3266
     3267        if (!PyArg_Parse(
     3268                    key,
     3269                    "s;execve() arg 3 contains a non-string key",
     3270                    &k) ||
     3271            !PyArg_Parse(
     3272                val,
     3273                "s;execve() arg 3 contains a non-string value",
     3274                &v))
     3275        {
     3276            goto fail_2;
     3277        }
    31163278
    31173279#if defined(PYOS_OS2)
     
    31193281        if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) {
    31203282#endif
    3121                 len = PyString_Size(key) + PyString_Size(val) + 2;
    3122                 p = PyMem_NEW(char, len);
    3123                 if (p == NULL) {
    3124                         PyErr_NoMemory();
    3125                         goto fail_2;
    3126                 }
    3127                 PyOS_snprintf(p, len, "%s=%s", k, v);
    3128                 envlist[envc++] = p;
     3283        len = PyString_Size(key) + PyString_Size(val) + 2;
     3284        p = PyMem_NEW(char, len);
     3285        if (p == NULL) {
     3286            PyErr_NoMemory();
     3287            goto fail_2;
     3288        }
     3289        PyOS_snprintf(p, len, "%s=%s", k, v);
     3290        envlist[envc++] = p;
    31293291#if defined(PYOS_OS2)
    3130     }
    3131 #endif
    3132         }
    3133         envlist[envc] = 0;
    3134 
    3135         execve(path, argvlist, envlist);
    3136 
    3137         /* If we get here it's definitely an error */
    3138 
    3139         (void) posix_error();
     3292        }
     3293#endif
     3294    }
     3295    envlist[envc] = 0;
     3296
     3297    execve(path, argvlist, envlist);
     3298
     3299    /* If we get here it's definitely an error */
     3300
     3301    (void) posix_error();
    31403302
    31413303  fail_2:
    3142         while (--envc >= 0)
    3143                 PyMem_DEL(envlist[envc]);
    3144         PyMem_DEL(envlist);
     3304    while (--envc >= 0)
     3305        PyMem_DEL(envlist[envc]);
     3306    PyMem_DEL(envlist);
    31453307  fail_1:
    3146         free_string_array(argvlist, lastarg);
    3147         Py_XDECREF(vals);
    3148         Py_XDECREF(keys);
     3308    free_string_array(argvlist, lastarg);
     3309    Py_XDECREF(vals);
     3310    Py_XDECREF(keys);
    31493311  fail_0:
    3150         PyMem_Free(path);
    3151         return NULL;
     3312    PyMem_Free(path);
     3313    return NULL;
    31523314}
    31533315#endif /* HAVE_EXECV */
     
    31593321Execute the program 'path' in a new process.\n\
    31603322\n\
    3161         mode: mode of process creation\n\
    3162         path: path of executable file\n\
    3163         args: tuple or list of strings");
     3323    mode: mode of process creation\n\
     3324    path: path of executable file\n\
     3325    args: tuple or list of strings");
    31643326
    31653327static PyObject *
    31663328posix_spawnv(PyObject *self, PyObject *args)
    31673329{
    3168         char *path;
    3169         PyObject *argv;
    3170         char **argvlist;
    3171         int mode, i;
    3172         Py_ssize_t argc;
    3173         Py_intptr_t spawnval;
    3174         PyObject *(*getitem)(PyObject *, Py_ssize_t);
    3175 
    3176         /* spawnv has three arguments: (mode, path, argv), where
    3177            argv is a list or tuple of strings. */
    3178 
    3179         if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode,
    3180                               Py_FileSystemDefaultEncoding,
    3181                               &path, &argv))
    3182                 return NULL;
    3183         if (PyList_Check(argv)) {
    3184                 argc = PyList_Size(argv);
    3185                 getitem = PyList_GetItem;
    3186         }
    3187         else if (PyTuple_Check(argv)) {
    3188                 argc = PyTuple_Size(argv);
    3189                 getitem = PyTuple_GetItem;
    3190         }
    3191         else {
    3192                 PyErr_SetString(PyExc_TypeError,
    3193                                 "spawnv() arg 2 must be a tuple or list");
    3194                 PyMem_Free(path);
    3195                 return NULL;
    3196         }
    3197 
    3198         argvlist = PyMem_NEW(char *, argc+1);
    3199         if (argvlist == NULL) {
    3200                 PyMem_Free(path);
    3201                 return PyErr_NoMemory();
    3202         }
    3203         for (i = 0; i < argc; i++) {
    3204                 if (!PyArg_Parse((*getitem)(argv, i), "et",
    3205                                 Py_FileSystemDefaultEncoding,
    3206                                 &argvlist[i])) {
    3207                         free_string_array(argvlist, i);
    3208                         PyErr_SetString(
    3209                                 PyExc_TypeError,
    3210                                 "spawnv() arg 2 must contain only strings");
    3211                         PyMem_Free(path);
    3212                         return NULL;
    3213                 }
    3214         }
    3215         argvlist[argc] = NULL;
     3330    char *path;
     3331    PyObject *argv;
     3332    char **argvlist;
     3333    int mode, i;
     3334    Py_ssize_t argc;
     3335    Py_intptr_t spawnval;
     3336    PyObject *(*getitem)(PyObject *, Py_ssize_t);
     3337
     3338    /* spawnv has three arguments: (mode, path, argv), where
     3339       argv is a list or tuple of strings. */
     3340
     3341    if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode,
     3342                          Py_FileSystemDefaultEncoding,
     3343                          &path, &argv))
     3344        return NULL;
     3345    if (PyList_Check(argv)) {
     3346        argc = PyList_Size(argv);
     3347        getitem = PyList_GetItem;
     3348    }
     3349    else if (PyTuple_Check(argv)) {
     3350        argc = PyTuple_Size(argv);
     3351        getitem = PyTuple_GetItem;
     3352    }
     3353    else {
     3354        PyErr_SetString(PyExc_TypeError,
     3355                        "spawnv() arg 2 must be a tuple or list");
     3356        PyMem_Free(path);
     3357        return NULL;
     3358    }
     3359
     3360    argvlist = PyMem_NEW(char *, argc+1);
     3361    if (argvlist == NULL) {
     3362        PyMem_Free(path);
     3363        return PyErr_NoMemory();
     3364    }
     3365    for (i = 0; i < argc; i++) {
     3366        if (!PyArg_Parse((*getitem)(argv, i), "et",
     3367                        Py_FileSystemDefaultEncoding,
     3368                        &argvlist[i])) {
     3369            free_string_array(argvlist, i);
     3370            PyErr_SetString(
     3371                PyExc_TypeError,
     3372                "spawnv() arg 2 must contain only strings");
     3373            PyMem_Free(path);
     3374            return NULL;
     3375        }
     3376    }
     3377    argvlist[argc] = NULL;
    32163378
    32173379#if defined(PYOS_OS2) && defined(PYCC_GCC)
    3218         Py_BEGIN_ALLOW_THREADS
    3219         spawnval = spawnv(mode, path, argvlist);
    3220         Py_END_ALLOW_THREADS
     3380    Py_BEGIN_ALLOW_THREADS
     3381    spawnval = spawnv(mode, path, argvlist);
     3382    Py_END_ALLOW_THREADS
    32213383#else
    3222         if (mode == _OLD_P_OVERLAY)
    3223                 mode = _P_OVERLAY;
    3224 
    3225         Py_BEGIN_ALLOW_THREADS
    3226         spawnval = _spawnv(mode, path, argvlist);
    3227         Py_END_ALLOW_THREADS
    3228 #endif
    3229 
    3230         free_string_array(argvlist, argc);
    3231         PyMem_Free(path);
    3232 
    3233         if (spawnval == -1)
    3234                 return posix_error();
    3235         else
     3384    if (mode == _OLD_P_OVERLAY)
     3385        mode = _P_OVERLAY;
     3386
     3387    Py_BEGIN_ALLOW_THREADS
     3388    spawnval = _spawnv(mode, path, argvlist);
     3389    Py_END_ALLOW_THREADS
     3390#endif
     3391
     3392    free_string_array(argvlist, argc);
     3393    PyMem_Free(path);
     3394
     3395    if (spawnval == -1)
     3396        return posix_error();
     3397    else
    32363398#if SIZEOF_LONG == SIZEOF_VOID_P
    3237                 return Py_BuildValue("l", (long) spawnval);
     3399        return Py_BuildValue("l", (long) spawnval);
    32383400#else
    3239                 return Py_BuildValue("L", (PY_LONG_LONG) spawnval);
     3401        return Py_BuildValue("L", (PY_LONG_LONG) spawnval);
    32403402#endif
    32413403}
     
    32463408Execute the program 'path' in a new process.\n\
    32473409\n\
    3248         mode: mode of process creation\n\
    3249         path: path of executable file\n\
    3250         args: tuple or list of arguments\n\
    3251         env: dictionary of strings mapping to strings");
     3410    mode: mode of process creation\n\
     3411    path: path of executable file\n\
     3412    args: tuple or list of arguments\n\
     3413    env: dictionary of strings mapping to strings");
    32523414
    32533415static PyObject *
    32543416posix_spawnve(PyObject *self, PyObject *args)
    32553417{
    3256         char *path;
    3257         PyObject *argv, *env;
    3258         char **argvlist;
    3259         char **envlist;
    3260         PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;
    3261         int mode, pos, envc;
    3262         Py_ssize_t argc, i;
    3263         Py_intptr_t spawnval;
    3264         PyObject *(*getitem)(PyObject *, Py_ssize_t);
    3265         Py_ssize_t lastarg = 0;
    3266 
    3267         /* spawnve has four arguments: (mode, path, argv, env), where
    3268            argv is a list or tuple of strings and env is a dictionary
    3269            like posix.environ. */
    3270 
    3271         if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode,
    3272                               Py_FileSystemDefaultEncoding,
    3273                               &path, &argv, &env))
    3274                 return NULL;
    3275         if (PyList_Check(argv)) {
    3276                 argc = PyList_Size(argv);
    3277                 getitem = PyList_GetItem;
    3278         }
    3279         else if (PyTuple_Check(argv)) {
    3280                 argc = PyTuple_Size(argv);
    3281                 getitem = PyTuple_GetItem;
    3282         }
    3283         else {
    3284                 PyErr_SetString(PyExc_TypeError,
    3285                                 "spawnve() arg 2 must be a tuple or list");
    3286                 goto fail_0;
    3287         }
    3288         if (!PyMapping_Check(env)) {
    3289                 PyErr_SetString(PyExc_TypeError,
    3290                                 "spawnve() arg 3 must be a mapping object");
    3291                 goto fail_0;
    3292         }
    3293 
    3294         argvlist = PyMem_NEW(char *, argc+1);
    3295         if (argvlist == NULL) {
    3296                 PyErr_NoMemory();
    3297                 goto fail_0;
    3298         }
    3299         for (i = 0; i < argc; i++) {
    3300                 if (!PyArg_Parse((*getitem)(argv, i),
    3301                              "et;spawnve() arg 2 must contain only strings",
    3302                                 Py_FileSystemDefaultEncoding,
    3303                                 &argvlist[i]))
    3304                 {
    3305                         lastarg = i;
    3306                         goto fail_1;
    3307                 }
    3308         }
    3309         lastarg = argc;
    3310         argvlist[argc] = NULL;
    3311 
    3312         i = PyMapping_Size(env);
    3313         if (i < 0)
    3314                 goto fail_1;
    3315         envlist = PyMem_NEW(char *, i + 1);
    3316         if (envlist == NULL) {
    3317                 PyErr_NoMemory();
    3318                 goto fail_1;
    3319         }
    3320         envc = 0;
    3321         keys = PyMapping_Keys(env);
    3322         vals = PyMapping_Values(env);
    3323         if (!keys || !vals)
    3324                 goto fail_2;
    3325         if (!PyList_Check(keys) || !PyList_Check(vals)) {
    3326                 PyErr_SetString(PyExc_TypeError,
    3327                         "spawnve(): env.keys() or env.values() is not a list");
    3328                 goto fail_2;
    3329         }
    3330 
    3331         for (pos = 0; pos < i; pos++) {
    3332                 char *p, *k, *v;
    3333                 size_t len;
    3334 
    3335                 key = PyList_GetItem(keys, pos);
    3336                 val = PyList_GetItem(vals, pos);
    3337                 if (!key || !val)
    3338                         goto fail_2;
    3339 
    3340                 if (!PyArg_Parse(
    3341                             key,
    3342                             "s;spawnve() arg 3 contains a non-string key",
    3343                             &k) ||
    3344                     !PyArg_Parse(
    3345                             val,
    3346                             "s;spawnve() arg 3 contains a non-string value",
    3347                             &v))
    3348                 {
    3349                         goto fail_2;
    3350                 }
    3351                 len = PyString_Size(key) + PyString_Size(val) + 2;
    3352                 p = PyMem_NEW(char, len);
    3353                 if (p == NULL) {
    3354                         PyErr_NoMemory();
    3355                         goto fail_2;
    3356                 }
    3357                 PyOS_snprintf(p, len, "%s=%s", k, v);
    3358                 envlist[envc++] = p;
    3359         }
    3360         envlist[envc] = 0;
     3418    char *path;
     3419    PyObject *argv, *env;
     3420    char **argvlist;
     3421    char **envlist;
     3422    PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;
     3423    int mode, pos, envc;
     3424    Py_ssize_t argc, i;
     3425    Py_intptr_t spawnval;
     3426    PyObject *(*getitem)(PyObject *, Py_ssize_t);
     3427    Py_ssize_t lastarg = 0;
     3428
     3429    /* spawnve has four arguments: (mode, path, argv, env), where
     3430       argv is a list or tuple of strings and env is a dictionary
     3431       like posix.environ. */
     3432
     3433    if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode,
     3434                          Py_FileSystemDefaultEncoding,
     3435                          &path, &argv, &env))
     3436        return NULL;
     3437    if (PyList_Check(argv)) {
     3438        argc = PyList_Size(argv);
     3439        getitem = PyList_GetItem;
     3440    }
     3441    else if (PyTuple_Check(argv)) {
     3442        argc = PyTuple_Size(argv);
     3443        getitem = PyTuple_GetItem;
     3444    }
     3445    else {
     3446        PyErr_SetString(PyExc_TypeError,
     3447                        "spawnve() arg 2 must be a tuple or list");
     3448        goto fail_0;
     3449    }
     3450    if (!PyMapping_Check(env)) {
     3451        PyErr_SetString(PyExc_TypeError,
     3452                        "spawnve() arg 3 must be a mapping object");
     3453        goto fail_0;
     3454    }
     3455
     3456    argvlist = PyMem_NEW(char *, argc+1);
     3457    if (argvlist == NULL) {
     3458        PyErr_NoMemory();
     3459        goto fail_0;
     3460    }
     3461    for (i = 0; i < argc; i++) {
     3462        if (!PyArg_Parse((*getitem)(argv, i),
     3463                     "et;spawnve() arg 2 must contain only strings",
     3464                        Py_FileSystemDefaultEncoding,
     3465                        &argvlist[i]))
     3466        {
     3467            lastarg = i;
     3468            goto fail_1;
     3469        }
     3470    }
     3471    lastarg = argc;
     3472    argvlist[argc] = NULL;
     3473
     3474    i = PyMapping_Size(env);
     3475    if (i < 0)
     3476        goto fail_1;
     3477    envlist = PyMem_NEW(char *, i + 1);
     3478    if (envlist == NULL) {
     3479        PyErr_NoMemory();
     3480        goto fail_1;
     3481    }
     3482    envc = 0;
     3483    keys = PyMapping_Keys(env);
     3484    vals = PyMapping_Values(env);
     3485    if (!keys || !vals)
     3486        goto fail_2;
     3487    if (!PyList_Check(keys) || !PyList_Check(vals)) {
     3488        PyErr_SetString(PyExc_TypeError,
     3489                        "spawnve(): env.keys() or env.values() is not a list");
     3490        goto fail_2;
     3491    }
     3492
     3493    for (pos = 0; pos < i; pos++) {
     3494        char *p, *k, *v;
     3495        size_t len;
     3496
     3497        key = PyList_GetItem(keys, pos);
     3498        val = PyList_GetItem(vals, pos);
     3499        if (!key || !val)
     3500            goto fail_2;
     3501
     3502        if (!PyArg_Parse(
     3503                    key,
     3504                    "s;spawnve() arg 3 contains a non-string key",
     3505                    &k) ||
     3506            !PyArg_Parse(
     3507                val,
     3508                "s;spawnve() arg 3 contains a non-string value",
     3509                &v))
     3510        {
     3511            goto fail_2;
     3512        }
     3513        len = PyString_Size(key) + PyString_Size(val) + 2;
     3514        p = PyMem_NEW(char, len);
     3515        if (p == NULL) {
     3516            PyErr_NoMemory();
     3517            goto fail_2;
     3518        }
     3519        PyOS_snprintf(p, len, "%s=%s", k, v);
     3520        envlist[envc++] = p;
     3521    }
     3522    envlist[envc] = 0;
    33613523
    33623524#if defined(PYOS_OS2) && defined(PYCC_GCC)
    3363         Py_BEGIN_ALLOW_THREADS
    3364         spawnval = spawnve(mode, path, argvlist, envlist);
    3365         Py_END_ALLOW_THREADS
     3525    Py_BEGIN_ALLOW_THREADS
     3526    spawnval = spawnve(mode, path, argvlist, envlist);
     3527    Py_END_ALLOW_THREADS
    33663528#else
    3367         if (mode == _OLD_P_OVERLAY)
    3368                 mode = _P_OVERLAY;
    3369 
    3370         Py_BEGIN_ALLOW_THREADS
    3371         spawnval = _spawnve(mode, path, argvlist, envlist);
    3372         Py_END_ALLOW_THREADS
    3373 #endif
    3374 
    3375         if (spawnval == -1)
    3376                 (void) posix_error();
    3377         else
     3529    if (mode == _OLD_P_OVERLAY)
     3530        mode = _P_OVERLAY;
     3531
     3532    Py_BEGIN_ALLOW_THREADS
     3533    spawnval = _spawnve(mode, path, argvlist, envlist);
     3534    Py_END_ALLOW_THREADS
     3535#endif
     3536
     3537    if (spawnval == -1)
     3538        (void) posix_error();
     3539    else
    33783540#if SIZEOF_LONG == SIZEOF_VOID_P
    3379                 res = Py_BuildValue("l", (long) spawnval);
     3541        res = Py_BuildValue("l", (long) spawnval);
    33803542#else
    3381                 res = Py_BuildValue("L", (PY_LONG_LONG) spawnval);
     3543        res = Py_BuildValue("L", (PY_LONG_LONG) spawnval);
    33823544#endif
    33833545
    33843546  fail_2:
    3385         while (--envc >= 0)
    3386                 PyMem_DEL(envlist[envc]);
    3387         PyMem_DEL(envlist);
     3547    while (--envc >= 0)
     3548        PyMem_DEL(envlist[envc]);
     3549    PyMem_DEL(envlist);
    33883550  fail_1:
    3389         free_string_array(argvlist, lastarg);
    3390         Py_XDECREF(vals);
    3391         Py_XDECREF(keys);
     3551    free_string_array(argvlist, lastarg);
     3552    Py_XDECREF(vals);
     3553    Py_XDECREF(keys);
    33923554  fail_0:
    3393         PyMem_Free(path);
    3394         return res;
     3555    PyMem_Free(path);
     3556    return res;
    33953557}
    33963558
     
    34023564search path to find the file.\n\
    34033565\n\
    3404         mode: mode of process creation\n\
    3405         file: executable file name\n\
    3406         args: tuple or list of strings");
     3566    mode: mode of process creation\n\
     3567    file: executable file name\n\
     3568    args: tuple or list of strings");
    34073569
    34083570static PyObject *
    34093571posix_spawnvp(PyObject *self, PyObject *args)
    34103572{
    3411         char *path;
    3412         PyObject *argv;
    3413         char **argvlist;
    3414         int mode, i, argc;
    3415         Py_intptr_t spawnval;
    3416         PyObject *(*getitem)(PyObject *, Py_ssize_t);
    3417 
    3418         /* spawnvp has three arguments: (mode, path, argv), where
    3419            argv is a list or tuple of strings. */
    3420 
    3421         if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode,
    3422                               Py_FileSystemDefaultEncoding,
    3423                               &path, &argv))
    3424                 return NULL;
    3425         if (PyList_Check(argv)) {
    3426                 argc = PyList_Size(argv);
    3427                 getitem = PyList_GetItem;
    3428         }
    3429         else if (PyTuple_Check(argv)) {
    3430                 argc = PyTuple_Size(argv);
    3431                 getitem = PyTuple_GetItem;
    3432         }
    3433         else {
    3434                 PyErr_SetString(PyExc_TypeError,
    3435                                 "spawnvp() arg 2 must be a tuple or list");
    3436                 PyMem_Free(path);
    3437                 return NULL;
    3438         }
    3439 
    3440         argvlist = PyMem_NEW(char *, argc+1);
    3441         if (argvlist == NULL) {
    3442                 PyMem_Free(path);
    3443                 return PyErr_NoMemory();
    3444         }
    3445         for (i = 0; i < argc; i++) {
    3446                 if (!PyArg_Parse((*getitem)(argv, i), "et",
    3447                                 Py_FileSystemDefaultEncoding,
    3448                                 &argvlist[i])) {
    3449                         free_string_array(argvlist, i);
    3450                         PyErr_SetString(
    3451                                 PyExc_TypeError,
    3452                                 "spawnvp() arg 2 must contain only strings");
    3453                         PyMem_Free(path);
    3454                         return NULL;
    3455                 }
    3456         }
    3457         argvlist[argc] = NULL;
    3458 
    3459         Py_BEGIN_ALLOW_THREADS
     3573    char *path;
     3574    PyObject *argv;
     3575    char **argvlist;
     3576    int mode, i, argc;
     3577    Py_intptr_t spawnval;
     3578    PyObject *(*getitem)(PyObject *, Py_ssize_t);
     3579
     3580    /* spawnvp has three arguments: (mode, path, argv), where
     3581       argv is a list or tuple of strings. */
     3582
     3583    if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode,
     3584                          Py_FileSystemDefaultEncoding,
     3585                          &path, &argv))
     3586        return NULL;
     3587    if (PyList_Check(argv)) {
     3588        argc = PyList_Size(argv);
     3589        getitem = PyList_GetItem;
     3590    }
     3591    else if (PyTuple_Check(argv)) {
     3592        argc = PyTuple_Size(argv);
     3593        getitem = PyTuple_GetItem;
     3594    }
     3595    else {
     3596        PyErr_SetString(PyExc_TypeError,
     3597                        "spawnvp() arg 2 must be a tuple or list");
     3598        PyMem_Free(path);
     3599        return NULL;
     3600    }
     3601
     3602    argvlist = PyMem_NEW(char *, argc+1);
     3603    if (argvlist == NULL) {
     3604        PyMem_Free(path);
     3605        return PyErr_NoMemory();
     3606    }
     3607    for (i = 0; i < argc; i++) {
     3608        if (!PyArg_Parse((*getitem)(argv, i), "et",
     3609                        Py_FileSystemDefaultEncoding,
     3610                        &argvlist[i])) {
     3611            free_string_array(argvlist, i);
     3612            PyErr_SetString(
     3613                PyExc_TypeError,
     3614                "spawnvp() arg 2 must contain only strings");
     3615            PyMem_Free(path);
     3616            return NULL;
     3617        }
     3618    }
     3619    argvlist[argc] = NULL;
     3620
     3621    Py_BEGIN_ALLOW_THREADS
    34603622#if defined(PYCC_GCC)
    3461         spawnval = spawnvp(mode, path, argvlist);
     3623    spawnval = spawnvp(mode, path, argvlist);
    34623624#else
    3463         spawnval = _spawnvp(mode, path, argvlist);
    3464 #endif
    3465         Py_END_ALLOW_THREADS
    3466 
    3467         free_string_array(argvlist, argc);
    3468         PyMem_Free(path);
    3469 
    3470         if (spawnval == -1)
    3471                 return posix_error();
    3472         else
    3473                 return Py_BuildValue("l", (long) spawnval);
     3625    spawnval = _spawnvp(mode, path, argvlist);
     3626#endif
     3627    Py_END_ALLOW_THREADS
     3628
     3629    free_string_array(argvlist, argc);
     3630    PyMem_Free(path);
     3631
     3632    if (spawnval == -1)
     3633        return posix_error();
     3634    else
     3635        return Py_BuildValue("l", (long) spawnval);
    34743636}
    34753637
     
    34803642search path to find the file.\n\
    34813643\n\
    3482         mode: mode of process creation\n\
    3483         file: executable file name\n\
    3484         args: tuple or list of arguments\n\
    3485         env: dictionary of strings mapping to strings");
     3644    mode: mode of process creation\n\
     3645    file: executable file name\n\
     3646    args: tuple or list of arguments\n\
     3647    env: dictionary of strings mapping to strings");
    34863648
    34873649static PyObject *
    34883650posix_spawnvpe(PyObject *self, PyObject *args)
    34893651{
    3490         char *path;
    3491         PyObject *argv, *env;
    3492         char **argvlist;
    3493         char **envlist;
    3494         PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;
    3495         int mode, i, pos, argc, envc;
    3496         Py_intptr_t spawnval;
    3497         PyObject *(*getitem)(PyObject *, Py_ssize_t);
    3498         int lastarg = 0;
    3499 
    3500         /* spawnvpe has four arguments: (mode, path, argv, env), where
    3501            argv is a list or tuple of strings and env is a dictionary
    3502            like posix.environ. */
    3503 
    3504         if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode,
    3505                               Py_FileSystemDefaultEncoding,
    3506                               &path, &argv, &env))
    3507                 return NULL;
    3508         if (PyList_Check(argv)) {
    3509                 argc = PyList_Size(argv);
    3510                 getitem = PyList_GetItem;
    3511         }
    3512         else if (PyTuple_Check(argv)) {
    3513                 argc = PyTuple_Size(argv);
    3514                 getitem = PyTuple_GetItem;
    3515         }
    3516         else {
    3517                 PyErr_SetString(PyExc_TypeError,
    3518                                 "spawnvpe() arg 2 must be a tuple or list");
    3519                 goto fail_0;
    3520         }
    3521         if (!PyMapping_Check(env)) {
    3522                 PyErr_SetString(PyExc_TypeError,
    3523                                 "spawnvpe() arg 3 must be a mapping object");
    3524                 goto fail_0;
    3525         }
    3526 
    3527         argvlist = PyMem_NEW(char *, argc+1);
    3528         if (argvlist == NULL) {
    3529                 PyErr_NoMemory();
    3530                 goto fail_0;
    3531         }
    3532         for (i = 0; i < argc; i++) {
    3533                 if (!PyArg_Parse((*getitem)(argv, i),
    3534                              "et;spawnvpe() arg 2 must contain only strings",
    3535                                 Py_FileSystemDefaultEncoding,
    3536                                 &argvlist[i]))
    3537                 {
    3538                         lastarg = i;
    3539                         goto fail_1;
    3540                 }
    3541         }
    3542         lastarg = argc;
    3543         argvlist[argc] = NULL;
    3544 
    3545         i = PyMapping_Size(env);
    3546         if (i < 0)
    3547                 goto fail_1;
    3548         envlist = PyMem_NEW(char *, i + 1);
    3549         if (envlist == NULL) {
    3550                 PyErr_NoMemory();
    3551                 goto fail_1;
    3552         }
    3553         envc = 0;
    3554         keys = PyMapping_Keys(env);
    3555         vals = PyMapping_Values(env);
    3556         if (!keys || !vals)
    3557                 goto fail_2;
    3558         if (!PyList_Check(keys) || !PyList_Check(vals)) {
    3559                 PyErr_SetString(PyExc_TypeError,
    3560                         "spawnvpe(): env.keys() or env.values() is not a list");
    3561                 goto fail_2;
    3562         }
    3563 
    3564         for (pos = 0; pos < i; pos++) {
    3565                 char *p, *k, *v;
    3566                 size_t len;
    3567 
    3568                 key = PyList_GetItem(keys, pos);
    3569                 val = PyList_GetItem(vals, pos);
    3570                 if (!key || !val)
    3571                         goto fail_2;
    3572 
    3573                 if (!PyArg_Parse(
    3574                             key,
    3575                             "s;spawnvpe() arg 3 contains a non-string key",
    3576                             &k) ||
    3577                     !PyArg_Parse(
    3578                             val,
    3579                             "s;spawnvpe() arg 3 contains a non-string value",
    3580                             &v))
    3581                 {
    3582                         goto fail_2;
    3583                 }
    3584                 len = PyString_Size(key) + PyString_Size(val) + 2;
    3585                 p = PyMem_NEW(char, len);
    3586                 if (p == NULL) {
    3587                         PyErr_NoMemory();
    3588                         goto fail_2;
    3589                 }
    3590                 PyOS_snprintf(p, len, "%s=%s", k, v);
    3591                 envlist[envc++] = p;
    3592         }
    3593         envlist[envc] = 0;
    3594 
    3595         Py_BEGIN_ALLOW_THREADS
     3652    char *path;
     3653    PyObject *argv, *env;
     3654    char **argvlist;
     3655    char **envlist;
     3656    PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;
     3657    int mode, i, pos, argc, envc;
     3658    Py_intptr_t spawnval;
     3659    PyObject *(*getitem)(PyObject *, Py_ssize_t);
     3660    int lastarg = 0;
     3661
     3662    /* spawnvpe has four arguments: (mode, path, argv, env), where
     3663       argv is a list or tuple of strings and env is a dictionary
     3664       like posix.environ. */
     3665
     3666    if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode,
     3667                          Py_FileSystemDefaultEncoding,
     3668                          &path, &argv, &env))
     3669        return NULL;
     3670    if (PyList_Check(argv)) {
     3671        argc = PyList_Size(argv);
     3672        getitem = PyList_GetItem;
     3673    }
     3674    else if (PyTuple_Check(argv)) {
     3675        argc = PyTuple_Size(argv);
     3676        getitem = PyTuple_GetItem;
     3677    }
     3678    else {
     3679        PyErr_SetString(PyExc_TypeError,
     3680                        "spawnvpe() arg 2 must be a tuple or list");
     3681        goto fail_0;
     3682    }
     3683    if (!PyMapping_Check(env)) {
     3684        PyErr_SetString(PyExc_TypeError,
     3685                        "spawnvpe() arg 3 must be a mapping object");
     3686        goto fail_0;
     3687    }
     3688
     3689    argvlist = PyMem_NEW(char *, argc+1);
     3690    if (argvlist == NULL) {
     3691        PyErr_NoMemory();
     3692        goto fail_0;
     3693    }
     3694    for (i = 0; i < argc; i++) {
     3695        if (!PyArg_Parse((*getitem)(argv, i),
     3696                     "et;spawnvpe() arg 2 must contain only strings",
     3697                        Py_FileSystemDefaultEncoding,
     3698                        &argvlist[i]))
     3699        {
     3700            lastarg = i;
     3701            goto fail_1;
     3702        }
     3703    }
     3704    lastarg = argc;
     3705    argvlist[argc] = NULL;
     3706
     3707    i = PyMapping_Size(env);
     3708    if (i < 0)
     3709        goto fail_1;
     3710    envlist = PyMem_NEW(char *, i + 1);
     3711    if (envlist == NULL) {
     3712        PyErr_NoMemory();
     3713        goto fail_1;
     3714    }
     3715    envc = 0;
     3716    keys = PyMapping_Keys(env);
     3717    vals = PyMapping_Values(env);
     3718    if (!keys || !vals)
     3719        goto fail_2;
     3720    if (!PyList_Check(keys) || !PyList_Check(vals)) {
     3721        PyErr_SetString(PyExc_TypeError,
     3722                        "spawnvpe(): env.keys() or env.values() is not a list");
     3723        goto fail_2;
     3724    }
     3725
     3726    for (pos = 0; pos < i; pos++) {
     3727        char *p, *k, *v;
     3728        size_t len;
     3729
     3730        key = PyList_GetItem(keys, pos);
     3731        val = PyList_GetItem(vals, pos);
     3732        if (!key || !val)
     3733            goto fail_2;
     3734
     3735        if (!PyArg_Parse(
     3736                    key,
     3737                    "s;spawnvpe() arg 3 contains a non-string key",
     3738                    &k) ||
     3739            !PyArg_Parse(
     3740                val,
     3741                "s;spawnvpe() arg 3 contains a non-string value",
     3742                &v))
     3743        {
     3744            goto fail_2;
     3745        }
     3746        len = PyString_Size(key) + PyString_Size(val) + 2;
     3747        p = PyMem_NEW(char, len);
     3748        if (p == NULL) {
     3749            PyErr_NoMemory();
     3750            goto fail_2;
     3751        }
     3752        PyOS_snprintf(p, len, "%s=%s", k, v);
     3753        envlist[envc++] = p;
     3754    }
     3755    envlist[envc] = 0;
     3756
     3757    Py_BEGIN_ALLOW_THREADS
    35963758#if defined(PYCC_GCC)
    3597         spawnval = spawnvpe(mode, path, argvlist, envlist);
     3759    spawnval = spawnvpe(mode, path, argvlist, envlist);
    35983760#else
    3599         spawnval = _spawnvpe(mode, path, argvlist, envlist);
    3600 #endif
    3601         Py_END_ALLOW_THREADS
    3602 
    3603         if (spawnval == -1)
    3604                 (void) posix_error();
    3605         else
    3606                 res = Py_BuildValue("l", (long) spawnval);
     3761    spawnval = _spawnvpe(mode, path, argvlist, envlist);
     3762#endif
     3763    Py_END_ALLOW_THREADS
     3764
     3765    if (spawnval == -1)
     3766        (void) posix_error();
     3767    else
     3768        res = Py_BuildValue("l", (long) spawnval);
    36073769
    36083770  fail_2:
    3609         while (--envc >= 0)
    3610                 PyMem_DEL(envlist[envc]);
    3611         PyMem_DEL(envlist);
     3771    while (--envc >= 0)
     3772        PyMem_DEL(envlist[envc]);
     3773    PyMem_DEL(envlist);
    36123774  fail_1:
    3613         free_string_array(argvlist, lastarg);
    3614         Py_XDECREF(vals);
    3615         Py_XDECREF(keys);
     3775    free_string_array(argvlist, lastarg);
     3776    Py_XDECREF(vals);
     3777    Py_XDECREF(keys);
    36163778  fail_0:
    3617         PyMem_Free(path);
    3618         return res;
     3779    PyMem_Free(path);
     3780    return res;
    36193781}
    36203782#endif /* PYOS_OS2 */
     
    36323794posix_fork1(PyObject *self, PyObject *noargs)
    36333795{
    3634         pid_t pid;
    3635         int result = 0;
    3636         _PyImport_AcquireLock();
    3637         pid = fork1();
    3638         if (pid == 0) {
    3639                 /* child: this clobbers and resets the import lock. */
    3640                 PyOS_AfterFork();
    3641         } else {
    3642                 /* parent: release the import lock. */
    3643                 result = _PyImport_ReleaseLock();
    3644         }
    3645         if (pid == -1)
    3646                 return posix_error();
    3647         if (result < 0) {
    3648                 /* Don't clobber the OSError if the fork failed. */
    3649                 PyErr_SetString(PyExc_RuntimeError,
    3650                                 "not holding the import lock");
    3651                 return NULL;
    3652         }
    3653         return PyLong_FromPid(pid);
     3796    pid_t pid;
     3797    int result = 0;
     3798    _PyImport_AcquireLock();
     3799    pid = fork1();
     3800    if (pid == 0) {
     3801        /* child: this clobbers and resets the import lock. */
     3802        PyOS_AfterFork();
     3803    } else {
     3804        /* parent: release the import lock. */
     3805        result = _PyImport_ReleaseLock();
     3806    }
     3807    if (pid == -1)
     3808        return posix_error();
     3809    if (result < 0) {
     3810        /* Don't clobber the OSError if the fork failed. */
     3811        PyErr_SetString(PyExc_RuntimeError,
     3812                        "not holding the import lock");
     3813        return NULL;
     3814    }
     3815    return PyLong_FromPid(pid);
    36543816}
    36553817#endif
     
    36653827posix_fork(PyObject *self, PyObject *noargs)
    36663828{
    3667         pid_t pid;
    3668         int result = 0;
    3669         _PyImport_AcquireLock();
    3670         pid = fork();
    3671         if (pid == 0) {
    3672                 /* child: this clobbers and resets the import lock. */
    3673                 PyOS_AfterFork();
    3674         } else {
    3675                 /* parent: release the import lock. */
    3676                 result = _PyImport_ReleaseLock();
    3677         }
    3678         if (pid == -1)
    3679                 return posix_error();
    3680         if (result < 0) {
    3681                 /* Don't clobber the OSError if the fork failed. */
    3682                 PyErr_SetString(PyExc_RuntimeError,
    3683                                 "not holding the import lock");
    3684                 return NULL;
    3685         }
    3686         return PyLong_FromPid(pid);
     3829    pid_t pid;
     3830    int result = 0;
     3831    _PyImport_AcquireLock();
     3832    pid = fork();
     3833    if (pid == 0) {
     3834        /* child: this clobbers and resets the import lock. */
     3835        PyOS_AfterFork();
     3836    } else {
     3837        /* parent: release the import lock. */
     3838        result = _PyImport_ReleaseLock();
     3839    }
     3840    if (pid == -1)
     3841        return posix_error();
     3842    if (result < 0) {
     3843        /* Don't clobber the OSError if the fork failed. */
     3844        PyErr_SetString(PyExc_RuntimeError,
     3845                        "not holding the import lock");
     3846        return NULL;
     3847    }
     3848    return PyLong_FromPid(pid);
    36873849}
    36883850#endif
     
    37033865#ifdef HAVE_LIBUTIL_H
    37043866#include <libutil.h>
     3867#else
     3868#ifdef HAVE_UTIL_H
     3869#include <util.h>
     3870#endif /* HAVE_UTIL_H */
    37053871#endif /* HAVE_LIBUTIL_H */
    37063872#endif /* HAVE_PTY_H */
     
    37183884posix_openpty(PyObject *self, PyObject *noargs)
    37193885{
    3720         int master_fd, slave_fd;
     3886    int master_fd, slave_fd;
    37213887#ifndef HAVE_OPENPTY
    3722         char * slave_name;
     3888    char * slave_name;
    37233889#endif
    37243890#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
    3725         PyOS_sighandler_t sig_saved;
     3891    PyOS_sighandler_t sig_saved;
    37263892#ifdef sun
    3727         extern char *ptsname(int fildes);
     3893    extern char *ptsname(int fildes);
    37283894#endif
    37293895#endif
    37303896
    37313897#ifdef HAVE_OPENPTY
    3732         if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
    3733                 return posix_error();
     3898    if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
     3899        return posix_error();
    37343900#elif defined(HAVE__GETPTY)
    3735         slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
    3736         if (slave_name == NULL)
    3737                 return posix_error();
    3738 
    3739         slave_fd = open(slave_name, O_RDWR);
    3740         if (slave_fd < 0)
    3741                 return posix_error();
     3901    slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
     3902    if (slave_name == NULL)
     3903        return posix_error();
     3904
     3905    slave_fd = open(slave_name, O_RDWR);
     3906    if (slave_fd < 0)
     3907        return posix_error();
    37423908#else
    3743         master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
    3744         if (master_fd < 0)
    3745                 return posix_error();
    3746         sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
    3747         /* change permission of slave */
    3748         if (grantpt(master_fd) < 0) {
    3749                 PyOS_setsig(SIGCHLD, sig_saved);
    3750                 return posix_error();
    3751         }
    3752         /* unlock slave */
    3753         if (unlockpt(master_fd) < 0) {
    3754                 PyOS_setsig(SIGCHLD, sig_saved);
    3755                 return posix_error();
    3756         }
    3757         PyOS_setsig(SIGCHLD, sig_saved);
    3758         slave_name = ptsname(master_fd); /* get name of slave */
    3759         if (slave_name == NULL)
    3760                 return posix_error();
    3761         slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
    3762         if (slave_fd < 0)
    3763                 return posix_error();
     3909    master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
     3910    if (master_fd < 0)
     3911        return posix_error();
     3912    sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
     3913    /* change permission of slave */
     3914    if (grantpt(master_fd) < 0) {
     3915        PyOS_setsig(SIGCHLD, sig_saved);
     3916        return posix_error();
     3917    }
     3918    /* unlock slave */
     3919    if (unlockpt(master_fd) < 0) {
     3920        PyOS_setsig(SIGCHLD, sig_saved);
     3921        return posix_error();
     3922    }
     3923    PyOS_setsig(SIGCHLD, sig_saved);
     3924    slave_name = ptsname(master_fd); /* get name of slave */
     3925    if (slave_name == NULL)
     3926        return posix_error();
     3927    slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
     3928    if (slave_fd < 0)
     3929        return posix_error();
    37643930#if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC)
    3765         ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
    3766         ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
     3931    ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
     3932    ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
    37673933#ifndef __hpux
    3768         ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
     3934    ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
    37693935#endif /* __hpux */
    37703936#endif /* HAVE_CYGWIN */
    37713937#endif /* HAVE_OPENPTY */
    37723938
    3773         return Py_BuildValue("(ii)", master_fd, slave_fd);
     3939    return Py_BuildValue("(ii)", master_fd, slave_fd);
    37743940
    37753941}
     
    37863952posix_forkpty(PyObject *self, PyObject *noargs)
    37873953{
    3788         int master_fd = -1, result = 0;
    3789         pid_t pid;
    3790 
    3791         _PyImport_AcquireLock();
    3792         pid = forkpty(&master_fd, NULL, NULL, NULL);
    3793         if (pid == 0) {
    3794                 /* child: this clobbers and resets the import lock. */
    3795                 PyOS_AfterFork();
    3796         } else {
    3797                 /* parent: release the import lock. */
    3798                 result = _PyImport_ReleaseLock();
    3799         }
    3800         if (pid == -1)
    3801                 return posix_error();
    3802         if (result < 0) {
    3803                 /* Don't clobber the OSError if the fork failed. */
    3804                 PyErr_SetString(PyExc_RuntimeError,
    3805                                 "not holding the import lock");
    3806                 return NULL;
    3807         }
    3808         return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
     3954    int master_fd = -1, result = 0;
     3955    pid_t pid;
     3956
     3957    _PyImport_AcquireLock();
     3958    pid = forkpty(&master_fd, NULL, NULL, NULL);
     3959    if (pid == 0) {
     3960        /* child: this clobbers and resets the import lock. */
     3961        PyOS_AfterFork();
     3962    } else {
     3963        /* parent: release the import lock. */
     3964        result = _PyImport_ReleaseLock();
     3965    }
     3966    if (pid == -1)
     3967        return posix_error();
     3968    if (result < 0) {
     3969        /* Don't clobber the OSError if the fork failed. */
     3970        PyErr_SetString(PyExc_RuntimeError,
     3971                        "not holding the import lock");
     3972        return NULL;
     3973    }
     3974    return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
    38093975}
    38103976#endif
     
    38183984posix_getegid(PyObject *self, PyObject *noargs)
    38193985{
    3820         return PyInt_FromLong((long)getegid());
     3986    return _PyInt_FromGid(getegid());
    38213987}
    38223988#endif
     
    38313997posix_geteuid(PyObject *self, PyObject *noargs)
    38323998{
    3833         return PyInt_FromLong((long)geteuid());
     3999    return _PyInt_FromUid(geteuid());
    38344000}
    38354001#endif
     
    38444010posix_getgid(PyObject *self, PyObject *noargs)
    38454011{
    3846         return PyInt_FromLong((long)getgid());
     4012    return _PyInt_FromGid(getgid());
    38474013}
    38484014#endif
     
    38564022posix_getpid(PyObject *self, PyObject *noargs)
    38574023{
    3858         return PyLong_FromPid(getpid());
     4024    return PyLong_FromPid(getpid());
    38594025}
    38604026
     
    38734039#define MAX_GROUPS NGROUPS_MAX
    38744040#else
    3875         /* defined to be 16 on Solaris7, so this should be a small number */
     4041    /* defined to be 16 on Solaris7, so this should be a small number */
    38764042#define MAX_GROUPS 64
    38774043#endif
    3878         gid_t grouplist[MAX_GROUPS];
    3879         int n;
    3880 
    3881         n = getgroups(MAX_GROUPS, grouplist);
    3882         if (n < 0)
    3883             posix_error();
    3884         else {
    3885             result = PyList_New(n);
    3886             if (result != NULL) {
    3887                 int i;
    3888                 for (i = 0; i < n; ++i) {
    3889                     PyObject *o = PyInt_FromLong((long)grouplist[i]);
    3890                     if (o == NULL) {
    3891                         Py_DECREF(result);
    3892                         result = NULL;
    3893                         break;
    3894                     }
    3895                     PyList_SET_ITEM(result, i, o);
     4044    gid_t grouplist[MAX_GROUPS];
     4045
     4046    /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
     4047     * This is a helper variable to store the intermediate result when
     4048     * that happens.
     4049     *
     4050     * To keep the code readable the OSX behaviour is unconditional,
     4051     * according to the POSIX spec this should be safe on all unix-y
     4052     * systems.
     4053     */
     4054    gid_t* alt_grouplist = grouplist;
     4055    int n;
     4056
     4057#ifdef __APPLE__
     4058    /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
     4059     * there are more groups than can fit in grouplist.  Therefore, on OS X
     4060     * always first call getgroups with length 0 to get the actual number
     4061     * of groups.
     4062     */
     4063    n = getgroups(0, NULL);
     4064    if (n < 0) {
     4065        return posix_error();
     4066    } else if (n <= MAX_GROUPS) {
     4067        /* groups will fit in existing array */
     4068        alt_grouplist = grouplist;
     4069    } else {
     4070        alt_grouplist = PyMem_Malloc(n * sizeof(gid_t));
     4071        if (alt_grouplist == NULL) {
     4072            errno = EINVAL;
     4073            return posix_error();
     4074        }
     4075    }
     4076
     4077    n = getgroups(n, alt_grouplist);
     4078    if (n == -1) {
     4079        if (alt_grouplist != grouplist) {
     4080            PyMem_Free(alt_grouplist);
     4081        }
     4082        return posix_error();
     4083    }
     4084#else
     4085    n = getgroups(MAX_GROUPS, grouplist);
     4086    if (n < 0) {
     4087        if (errno == EINVAL) {
     4088            n = getgroups(0, NULL);
     4089            if (n == -1) {
     4090                return posix_error();
     4091            }
     4092            if (n == 0) {
     4093                /* Avoid malloc(0) */
     4094                alt_grouplist = grouplist;
     4095            } else {
     4096                alt_grouplist = PyMem_Malloc(n * sizeof(gid_t));
     4097                if (alt_grouplist == NULL) {
     4098                    errno = EINVAL;
     4099                    return posix_error();
     4100                }
     4101                n = getgroups(n, alt_grouplist);
     4102                if (n == -1) {
     4103                    PyMem_Free(alt_grouplist);
     4104                    return posix_error();
    38964105                }
    38974106            }
     4107        } else {
     4108            return posix_error();
    38984109        }
     4110    }
     4111#endif
     4112
     4113    result = PyList_New(n);
     4114    if (result != NULL) {
     4115        int i;
     4116        for (i = 0; i < n; ++i) {
     4117            PyObject *o = _PyInt_FromGid(alt_grouplist[i]);
     4118            if (o == NULL) {
     4119                Py_DECREF(result);
     4120                result = NULL;
     4121                break;
     4122            }
     4123            PyList_SET_ITEM(result, i, o);
     4124        }
     4125    }
     4126
     4127    if (alt_grouplist != grouplist) {
     4128        PyMem_Free(alt_grouplist);
     4129    }
    38994130
    39004131    return result;
     4132}
     4133#endif
     4134
     4135#ifdef HAVE_INITGROUPS
     4136PyDoc_STRVAR(posix_initgroups__doc__,
     4137"initgroups(username, gid) -> None\n\n\
     4138Call the system initgroups() to initialize the group access list with all of\n\
     4139the groups of which the specified username is a member, plus the specified\n\
     4140group id.");
     4141
     4142static PyObject *
     4143posix_initgroups(PyObject *self, PyObject *args)
     4144{
     4145    char *username;
     4146#ifdef __APPLE__
     4147    int gid;
     4148#else
     4149    gid_t gid;
     4150#endif
     4151
     4152#ifdef __APPLE__
     4153    if (!PyArg_ParseTuple(args, "si:initgroups", &username,
     4154                          &gid))
     4155#else
     4156    if (!PyArg_ParseTuple(args, "sO&:initgroups", &username,
     4157                          _Py_Gid_Converter, &gid))
     4158#endif
     4159        return NULL;
     4160
     4161    if (initgroups(username, gid) == -1)
     4162        return PyErr_SetFromErrno(PyExc_OSError);
     4163
     4164    Py_INCREF(Py_None);
     4165    return Py_None;
    39014166}
    39024167#endif
     
    39104175posix_getpgid(PyObject *self, PyObject *args)
    39114176{
    3912         pid_t pid, pgid;
    3913         if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid))
    3914                 return NULL;
    3915         pgid = getpgid(pid);
    3916         if (pgid < 0)
    3917                 return posix_error();
    3918         return PyLong_FromPid(pgid);
     4177    pid_t pid, pgid;
     4178    if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid))
     4179        return NULL;
     4180    pgid = getpgid(pid);
     4181    if (pgid < 0)
     4182        return posix_error();
     4183    return PyLong_FromPid(pgid);
    39194184}
    39204185#endif /* HAVE_GETPGID */
     
    39304195{
    39314196#ifdef GETPGRP_HAVE_ARG
    3932         return PyLong_FromPid(getpgrp(0));
     4197    return PyLong_FromPid(getpgrp(0));
    39334198#else /* GETPGRP_HAVE_ARG */
    3934         return PyLong_FromPid(getpgrp());
     4199    return PyLong_FromPid(getpgrp());
    39354200#endif /* GETPGRP_HAVE_ARG */
    39364201}
     
    39414206PyDoc_STRVAR(posix_setpgrp__doc__,
    39424207"setpgrp()\n\n\
    3943 Make this process a session leader.");
     4208Make this process the process group leader.");
    39444209
    39454210static PyObject *
     
    39474212{
    39484213#ifdef SETPGRP_HAVE_ARG
    3949         if (setpgrp(0, 0) < 0)
     4214    if (setpgrp(0, 0) < 0)
    39504215#else /* SETPGRP_HAVE_ARG */
    3951         if (setpgrp() < 0)
     4216    if (setpgrp() < 0)
    39524217#endif /* SETPGRP_HAVE_ARG */
    3953                 return posix_error();
    3954         Py_INCREF(Py_None);
    3955         return Py_None;
     4218        return posix_error();
     4219    Py_INCREF(Py_None);
     4220    return Py_None;
    39564221}
    39574222
     
    39664231posix_getppid(PyObject *self, PyObject *noargs)
    39674232{
    3968         return PyLong_FromPid(getppid());
     4233    return PyLong_FromPid(getppid());
    39694234}
    39704235#endif
     
    39794244posix_getlogin(PyObject *self, PyObject *noargs)
    39804245{
    3981         PyObject *result = NULL;
    3982         char *name;
    3983         int old_errno = errno;
    3984 
    3985         errno = 0;
    3986         name = getlogin();
    3987         if (name == NULL) {
    3988             if (errno)
    3989                 posix_error();
    3990             else
    3991                 PyErr_SetString(PyExc_OSError,
    3992                                 "unable to determine login name");
    3993         }
     4246    PyObject *result = NULL;
     4247    char *name;
     4248    int old_errno = errno;
     4249
     4250    errno = 0;
     4251    name = getlogin();
     4252    if (name == NULL) {
     4253        if (errno)
     4254        posix_error();
    39944255        else
    3995             result = PyString_FromString(name);
    3996         errno = old_errno;
     4256        PyErr_SetString(PyExc_OSError,
     4257                        "unable to determine login name");
     4258    }
     4259    else
     4260        result = PyString_FromString(name);
     4261    errno = old_errno;
    39974262
    39984263    return result;
     
    40084273posix_getuid(PyObject *self, PyObject *noargs)
    40094274{
    4010         return PyInt_FromLong((long)getuid());
     4275    return _PyInt_FromUid(getuid());
    40114276}
    40124277#endif
     
    40214286posix_kill(PyObject *self, PyObject *args)
    40224287{
    4023         pid_t pid;
    4024         int sig;
    4025         if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig))
    4026                 return NULL;
     4288    pid_t pid;
     4289    int sig;
     4290    if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig))
     4291        return NULL;
    40274292#if defined(PYOS_OS2) && !defined(PYCC_GCC)
    40284293    if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) {
     
    40394304        return NULL; /* Unrecognized Signal Requested */
    40404305#else
    4041         if (kill(pid, sig) == -1)
    4042                 return posix_error();
    4043 #endif
    4044         Py_INCREF(Py_None);
    4045         return Py_None;
     4306    if (kill(pid, sig) == -1)
     4307        return posix_error();
     4308#endif
     4309    Py_INCREF(Py_None);
     4310    return Py_None;
    40464311}
    40474312#endif
     
    40554320posix_killpg(PyObject *self, PyObject *args)
    40564321{
    4057         int sig;
    4058         pid_t pgid;
    4059         /* XXX some man pages make the `pgid` parameter an int, others
    4060            a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
    4061            take the same type. Moreover, pid_t is always at least as wide as
    4062            int (else compilation of this module fails), which is safe. */
    4063         if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig))
    4064                 return NULL;
    4065         if (killpg(pgid, sig) == -1)
    4066                 return posix_error();
    4067         Py_INCREF(Py_None);
    4068         return Py_None;
    4069 }
    4070 #endif
     4322    int sig;
     4323    pid_t pgid;
     4324    /* XXX some man pages make the `pgid` parameter an int, others
     4325       a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
     4326       take the same type. Moreover, pid_t is always at least as wide as
     4327       int (else compilation of this module fails), which is safe. */
     4328    if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig))
     4329        return NULL;
     4330    if (killpg(pgid, sig) == -1)
     4331        return posix_error();
     4332    Py_INCREF(Py_None);
     4333    return Py_None;
     4334}
     4335#endif
     4336
     4337#ifdef MS_WINDOWS
     4338PyDoc_STRVAR(win32_kill__doc__,
     4339"kill(pid, sig)\n\n\
     4340Kill a process with a signal.");
     4341
     4342static PyObject *
     4343win32_kill(PyObject *self, PyObject *args)
     4344{
     4345    PyObject *result;
     4346    DWORD pid, sig, err;
     4347    HANDLE handle;
     4348
     4349    if (!PyArg_ParseTuple(args, "kk:kill", &pid, &sig))
     4350        return NULL;
     4351
     4352    /* Console processes which share a common console can be sent CTRL+C or
     4353       CTRL+BREAK events, provided they handle said events. */
     4354    if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
     4355        if (GenerateConsoleCtrlEvent(sig, pid) == 0) {
     4356            err = GetLastError();
     4357            return PyErr_SetFromWindowsErr(err);
     4358        }
     4359        else
     4360            Py_RETURN_NONE;
     4361    }
     4362
     4363    /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
     4364       attempt to open and terminate the process. */
     4365    handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
     4366    if (handle == NULL) {
     4367        err = GetLastError();
     4368        return PyErr_SetFromWindowsErr(err);
     4369    }
     4370
     4371    if (TerminateProcess(handle, sig) == 0) {
     4372        err = GetLastError();
     4373        result = PyErr_SetFromWindowsErr(err);
     4374    } else {
     4375        Py_INCREF(Py_None);
     4376        result = Py_None;
     4377    }
     4378
     4379    CloseHandle(handle);
     4380    return result;
     4381}
     4382
     4383PyDoc_STRVAR(posix__isdir__doc__,
     4384"Return true if the pathname refers to an existing directory.");
     4385
     4386static PyObject *
     4387posix__isdir(PyObject *self, PyObject *args)
     4388{
     4389    PyObject *opath;
     4390    char *path;
     4391    PyUnicodeObject *po;
     4392    DWORD attributes;
     4393
     4394    if (PyArg_ParseTuple(args, "U|:_isdir", &po)) {
     4395        Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
     4396
     4397        attributes = GetFileAttributesW(wpath);
     4398        if (attributes == INVALID_FILE_ATTRIBUTES)
     4399            Py_RETURN_FALSE;
     4400        goto check;
     4401    }
     4402    /* Drop the argument parsing error as narrow strings
     4403       are also valid. */
     4404    PyErr_Clear();
     4405
     4406    if (!PyArg_ParseTuple(args, "et:_isdir",
     4407                          Py_FileSystemDefaultEncoding, &path))
     4408        return NULL;
     4409
     4410    attributes = GetFileAttributesA(path);
     4411    PyMem_Free(path);
     4412    if (attributes == INVALID_FILE_ATTRIBUTES)
     4413        Py_RETURN_FALSE;
     4414
     4415check:
     4416    if (attributes & FILE_ATTRIBUTE_DIRECTORY)
     4417        Py_RETURN_TRUE;
     4418    else
     4419        Py_RETURN_FALSE;
     4420}
     4421#endif /* MS_WINDOWS */
    40714422
    40724423#ifdef HAVE_PLOCK
     
    40834434posix_plock(PyObject *self, PyObject *args)
    40844435{
    4085         int op;
    4086         if (!PyArg_ParseTuple(args, "i:plock", &op))
    4087                 return NULL;
    4088         if (plock(op) == -1)
    4089                 return posix_error();
    4090         Py_INCREF(Py_None);
    4091         return Py_None;
     4436    int op;
     4437    if (!PyArg_ParseTuple(args, "i:plock", &op))
     4438        return NULL;
     4439    if (plock(op) == -1)
     4440        return posix_error();
     4441    Py_INCREF(Py_None);
     4442    return Py_None;
    40924443}
    40934444#endif
     
    41044455async_system(const char *command)
    41054456{
    4106         char errormsg[256], args[1024];
    4107         RESULTCODES rcodes;
    4108         APIRET rc;
    4109 
    4110         char *shell = getenv("COMSPEC");
    4111         if (!shell)
    4112                 shell = "cmd";
    4113 
    4114         /* avoid overflowing the argument buffer */
    4115         if (strlen(shell) + 3 + strlen(command) >= 1024)
    4116                 return ERROR_NOT_ENOUGH_MEMORY
    4117 
    4118         args[0] = '\0';
    4119         strcat(args, shell);
    4120         strcat(args, "/c ");
    4121         strcat(args, command);
    4122 
    4123         /* execute asynchronously, inheriting the environment */
    4124         rc = DosExecPgm(errormsg,
    4125                         sizeof(errormsg),
    4126                         EXEC_ASYNC,
    4127                         args,
    4128                         NULL,
    4129                         &rcodes,
    4130                         shell);
    4131         return rc;
     4457    char errormsg[256], args[1024];
     4458    RESULTCODES rcodes;
     4459    APIRET rc;
     4460
     4461    char *shell = getenv("COMSPEC");
     4462    if (!shell)
     4463        shell = "cmd";
     4464
     4465    /* avoid overflowing the argument buffer */
     4466    if (strlen(shell) + 3 + strlen(command) >= 1024)
     4467        return ERROR_NOT_ENOUGH_MEMORY
     4468
     4469    args[0] = '\0';
     4470    strcat(args, shell);
     4471    strcat(args, "/c ");
     4472    strcat(args, command);
     4473
     4474    /* execute asynchronously, inheriting the environment */
     4475    rc = DosExecPgm(errormsg,
     4476                    sizeof(errormsg),
     4477                    EXEC_ASYNC,
     4478                    args,
     4479                    NULL,
     4480                    &rcodes,
     4481                    shell);
     4482    return rc;
    41324483}
    41334484
     
    41354486popen(const char *command, const char *mode, int pipesize, int *err)
    41364487{
    4137         int oldfd, tgtfd;
    4138         HFILE pipeh[2];
    4139         APIRET rc;
    4140 
    4141         /* mode determines which of stdin or stdout is reconnected to
    4142         * the pipe to the child
    4143         */
    4144         if (strchr(mode, 'r') != NULL) {
    4145                 tgt_fd = 1;     /* stdout */
    4146         } else if (strchr(mode, 'w')) {
    4147                 tgt_fd = 0;     /* stdin */
    4148         } else {
    4149                 *err = ERROR_INVALID_ACCESS;
    4150                 return NULL;
    4151         }
    4152 
    4153         /* setup the pipe */
    4154         if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) {
    4155                 *err = rc;
    4156                 return NULL;
    4157         }
    4158 
    4159         /* prevent other threads accessing stdio */
    4160         DosEnterCritSec();
    4161 
    4162         /* reconnect stdio and execute child */
    4163         oldfd = dup(tgtfd);
    4164         close(tgtfd);
    4165         if (dup2(pipeh[tgtfd], tgtfd) == 0) {
    4166                 DosClose(pipeh[tgtfd]);
    4167                 rc = async_system(command);
    4168         }
    4169 
    4170         /* restore stdio */
    4171         dup2(oldfd, tgtfd);
    4172         close(oldfd);
    4173 
    4174         /* allow other threads access to stdio */
    4175         DosExitCritSec();
    4176 
    4177         /* if execution of child was successful return file stream */
    4178         if (rc == NO_ERROR)
    4179                 return fdopen(pipeh[1 - tgtfd], mode);
    4180         else {
    4181                 DosClose(pipeh[1 - tgtfd]);
    4182                 *err = rc;
    4183                 return NULL;
    4184         }
     4488    int oldfd, tgtfd;
     4489    HFILE pipeh[2];
     4490    APIRET rc;
     4491
     4492    /* mode determines which of stdin or stdout is reconnected to
     4493    * the pipe to the child
     4494    */
     4495    if (strchr(mode, 'r') != NULL) {
     4496        tgt_fd = 1;             /* stdout */
     4497    } else if (strchr(mode, 'w')) {
     4498        tgt_fd = 0;             /* stdin */
     4499    } else {
     4500        *err = ERROR_INVALID_ACCESS;
     4501        return NULL;
     4502    }
     4503
     4504    /* setup the pipe */
     4505    if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) {
     4506        *err = rc;
     4507        return NULL;
     4508    }
     4509
     4510    /* prevent other threads accessing stdio */
     4511    DosEnterCritSec();
     4512
     4513    /* reconnect stdio and execute child */
     4514    oldfd = dup(tgtfd);
     4515    close(tgtfd);
     4516    if (dup2(pipeh[tgtfd], tgtfd) == 0) {
     4517        DosClose(pipeh[tgtfd]);
     4518        rc = async_system(command);
     4519    }
     4520
     4521    /* restore stdio */
     4522    dup2(oldfd, tgtfd);
     4523    close(oldfd);
     4524
     4525    /* allow other threads access to stdio */
     4526    DosExitCritSec();
     4527
     4528    /* if execution of child was successful return file stream */
     4529    if (rc == NO_ERROR)
     4530        return fdopen(pipeh[1 - tgtfd], mode);
     4531    else {
     4532        DosClose(pipeh[1 - tgtfd]);
     4533        *err = rc;
     4534        return NULL;
     4535    }
    41854536}
    41864537
     
    41884539posix_popen(PyObject *self, PyObject *args)
    41894540{
    4190         char *name;
    4191         char *mode = "r";
    4192         int   err, bufsize = -1;
    4193         FILE *fp;
    4194         PyObject *f;
    4195         if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
    4196                 return NULL;
    4197         Py_BEGIN_ALLOW_THREADS
    4198         fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err);
    4199         Py_END_ALLOW_THREADS
    4200         if (fp == NULL)
    4201                 return os2_error(err);
    4202 
    4203         f = PyFile_FromFile(fp, name, mode, fclose);
    4204         if (f != NULL)
    4205                 PyFile_SetBufSize(f, bufsize);
    4206         return f;
     4541    char *name;
     4542    char *mode = "r";
     4543    int   err, bufsize = -1;
     4544    FILE *fp;
     4545    PyObject *f;
     4546    if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
     4547        return NULL;
     4548    Py_BEGIN_ALLOW_THREADS
     4549    fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err);
     4550    Py_END_ALLOW_THREADS
     4551    if (fp == NULL)
     4552        return os2_error(err);
     4553
     4554    f = PyFile_FromFile(fp, name, mode, fclose);
     4555    if (f != NULL)
     4556        PyFile_SetBufSize(f, bufsize);
     4557    return f;
    42074558}
    42084559
     
    42134564posix_popen(PyObject *self, PyObject *args)
    42144565{
    4215         char *name;
    4216         char *mode = "r";
    4217         int bufsize = -1;
    4218         FILE *fp;
    4219         PyObject *f;
    4220         if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
    4221                 return NULL;
    4222         Py_BEGIN_ALLOW_THREADS
    4223         fp = popen(name, mode);
    4224         Py_END_ALLOW_THREADS
    4225         if (fp == NULL)
    4226                 return posix_error();
    4227         f = PyFile_FromFile(fp, name, mode, pclose);
    4228         if (f != NULL)
    4229                 PyFile_SetBufSize(f, bufsize);
    4230         return f;
     4566    char *name;
     4567    char *mode = "r";
     4568    int bufsize = -1;
     4569    FILE *fp;
     4570    PyObject *f;
     4571    if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
     4572        return NULL;
     4573    Py_BEGIN_ALLOW_THREADS
     4574    fp = popen(name, mode);
     4575    Py_END_ALLOW_THREADS
     4576    if (fp == NULL)
     4577        return posix_error();
     4578    f = PyFile_FromFile(fp, name, mode, pclose);
     4579    if (f != NULL)
     4580        PyFile_SetBufSize(f, bufsize);
     4581    return f;
    42314582}
    42324583
     
    42624613os2emx_popen2(PyObject *self, PyObject  *args)
    42634614{
    4264         PyObject *f;
    4265         int tm=0;
    4266 
    4267         char *cmdstring;
    4268         char *mode = "t";
    4269         int bufsize = -1;
    4270         if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))
    4271                 return NULL;
    4272 
    4273         if (*mode == 't')
    4274                 tm = O_TEXT;
    4275         else if (*mode != 'b') {
    4276                 PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
    4277                 return NULL;
    4278         } else
    4279                 tm = O_BINARY;
    4280 
    4281         f = _PyPopen(cmdstring, tm, POPEN_2, bufsize);
    4282 
    4283         return f;
     4615    PyObject *f;
     4616    int tm=0;
     4617
     4618    char *cmdstring;
     4619    char *mode = "t";
     4620    int bufsize = -1;
     4621    if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))
     4622        return NULL;
     4623
     4624    if (*mode == 't')
     4625        tm = O_TEXT;
     4626    else if (*mode != 'b') {
     4627        PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
     4628        return NULL;
     4629    } else
     4630        tm = O_BINARY;
     4631
     4632    f = _PyPopen(cmdstring, tm, POPEN_2, bufsize);
     4633
     4634    return f;
    42844635}
    42854636
     
    42944645os2emx_popen3(PyObject *self, PyObject *args)
    42954646{
    4296         PyObject *f;
    4297         int tm = 0;
    4298 
    4299         char *cmdstring;
    4300         char *mode = "t";
    4301         int bufsize = -1;
    4302         if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))
    4303                 return NULL;
    4304 
    4305         if (*mode == 't')
    4306                 tm = O_TEXT;
    4307         else if (*mode != 'b') {
    4308                 PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
    4309                 return NULL;
    4310         } else
    4311                 tm = O_BINARY;
    4312 
    4313         f = _PyPopen(cmdstring, tm, POPEN_3, bufsize);
    4314 
    4315         return f;
     4647    PyObject *f;
     4648    int tm = 0;
     4649
     4650    char *cmdstring;
     4651    char *mode = "t";
     4652    int bufsize = -1;
     4653    if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))
     4654        return NULL;
     4655
     4656    if (*mode == 't')
     4657        tm = O_TEXT;
     4658    else if (*mode != 'b') {
     4659        PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
     4660        return NULL;
     4661    } else
     4662        tm = O_BINARY;
     4663
     4664    f = _PyPopen(cmdstring, tm, POPEN_3, bufsize);
     4665
     4666    return f;
    43164667}
    43174668
     
    43264677os2emx_popen4(PyObject *self, PyObject  *args)
    43274678{
    4328         PyObject *f;
    4329         int tm = 0;
    4330 
    4331         char *cmdstring;
    4332         char *mode = "t";
    4333         int bufsize = -1;
    4334         if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))
    4335                 return NULL;
    4336 
    4337         if (*mode == 't')
    4338                 tm = O_TEXT;
    4339         else if (*mode != 'b') {
    4340                 PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
    4341                 return NULL;
    4342         } else
    4343                 tm = O_BINARY;
    4344 
    4345         f = _PyPopen(cmdstring, tm, POPEN_4, bufsize);
    4346 
    4347         return f;
     4679    PyObject *f;
     4680    int tm = 0;
     4681
     4682    char *cmdstring;
     4683    char *mode = "t";
     4684    int bufsize = -1;
     4685    if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))
     4686        return NULL;
     4687
     4688    if (*mode == 't')
     4689        tm = O_TEXT;
     4690    else if (*mode != 'b') {
     4691        PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
     4692        return NULL;
     4693    } else
     4694        tm = O_BINARY;
     4695
     4696    f = _PyPopen(cmdstring, tm, POPEN_4, bufsize);
     4697
     4698    return f;
    43484699}
    43494700
     
    43534704struct file_ref
    43544705{
    4355         int handle;
    4356         int flags;
     4706    int handle;
     4707    int flags;
    43574708};
    43584709
    43594710struct pipe_ref
    43604711{
    4361         int rd;
    4362         int wr;
     4712    int rd;
     4713    int wr;
    43634714};
    43644715
     
    43684719_PyPopen(char *cmdstring, int mode, int n, int bufsize)
    43694720{
    4370         struct file_ref stdio[3];
    4371         struct pipe_ref p_fd[3];
    4372         FILE *p_s[3];
    4373         int file_count, i, pipe_err;
    4374         pid_t pipe_pid;
    4375         char *shell, *sh_name, *opt, *rd_mode, *wr_mode;
    4376         PyObject *f, *p_f[3];
    4377 
    4378         /* file modes for subsequent fdopen's on pipe handles */
    4379         if (mode == O_TEXT)
    4380         {
    4381                 rd_mode = "rt";
    4382                 wr_mode = "wt";
    4383         }
    4384         else
    4385         {
    4386                 rd_mode = "rb";
    4387                 wr_mode = "wb";
    4388         }
    4389 
    4390         /* prepare shell references */
    4391         if ((shell = getenv("EMXSHELL")) == NULL)
    4392                 if ((shell = getenv("COMSPEC")) == NULL)
    4393                 {
    4394                         errno = ENOENT;
    4395                         return posix_error();
    4396                 }
    4397 
    4398         sh_name = _getname(shell);
    4399         if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0)
    4400                 opt = "/c";
    4401         else
    4402                 opt = "-c";
    4403 
    4404         /* save current stdio fds + their flags, and set not inheritable */
    4405         i = pipe_err = 0;
    4406         while (pipe_err >= 0 && i < 3)
    4407         {
    4408                 pipe_err = stdio[i].handle = dup(i);
    4409                 stdio[i].flags = fcntl(i, F_GETFD, 0);
    4410                 fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC);
    4411                 i++;
    4412         }
    4413         if (pipe_err < 0)
    4414         {
    4415                 /* didn't get them all saved - clean up and bail out */
    4416                 int saved_err = errno;
    4417                 while (i-- > 0)
    4418                 {
    4419                         close(stdio[i].handle);
    4420                 }
    4421                 errno = saved_err;
    4422                 return posix_error();
    4423         }
    4424 
    4425         /* create pipe ends */
    4426         file_count = 2;
    4427         if (n == POPEN_3)
    4428                 file_count = 3;
    4429         i = pipe_err = 0;
    4430         while ((pipe_err == 0) && (i < file_count))
    4431                 pipe_err = pipe((int *)&p_fd[i++]);
    4432         if (pipe_err < 0)
    4433         {
    4434                 /* didn't get them all made - clean up and bail out */
    4435                 while (i-- > 0)
    4436                 {
    4437                         close(p_fd[i].wr);
    4438                         close(p_fd[i].rd);
    4439                 }
    4440                 errno = EPIPE;
    4441                 return posix_error();
    4442         }
    4443 
    4444         /* change the actual standard IO streams over temporarily,
    4445         * making the retained pipe ends non-inheritable
    4446         */
    4447         pipe_err = 0;
    4448 
    4449         /* - stdin */
    4450         if (dup2(p_fd[0].rd, 0) == 0)
    4451         {
    4452                 close(p_fd[0].rd);
    4453                 i = fcntl(p_fd[0].wr, F_GETFD, 0);
    4454                 fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC);
    4455                 if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL)
    4456                 {
    4457                         close(p_fd[0].wr);
    4458                         pipe_err = -1;
    4459                 }
    4460         }
    4461         else
    4462         {
    4463                 pipe_err = -1;
    4464         }
    4465 
    4466         /* - stdout */
    4467         if (pipe_err == 0)
    4468         {
    4469                 if (dup2(p_fd[1].wr, 1) == 1)
    4470                 {
    4471                         close(p_fd[1].wr);
    4472                         i = fcntl(p_fd[1].rd, F_GETFD, 0);
    4473                         fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC);
    4474                         if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL)
    4475                         {
    4476                                 close(p_fd[1].rd);
    4477                                 pipe_err = -1;
    4478                         }
    4479                 }
    4480                 else
    4481                 {
    4482                         pipe_err = -1;
    4483                 }
    4484         }
    4485 
    4486         /* - stderr, as required */
    4487         if (pipe_err == 0)
    4488                 switch (n)
    4489                 {
    4490                         case POPEN_3:
    4491                         {
    4492                                 if (dup2(p_fd[2].wr, 2) == 2)
    4493                                 {
    4494                                         close(p_fd[2].wr);
    4495                                         i = fcntl(p_fd[2].rd, F_GETFD, 0);
    4496                                         fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC);
    4497                                         if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL)
    4498                                         {
    4499                                                 close(p_fd[2].rd);
    4500                                                 pipe_err = -1;
    4501                                         }
    4502                                 }
    4503                                 else
    4504                                 {
    4505                                         pipe_err = -1;
    4506                                 }
    4507                                 break;
    4508                         }
    4509 
    4510                         case POPEN_4:
    4511                         {
    4512                                 if (dup2(1, 2) != 2)
    4513                                 {
    4514                                         pipe_err = -1;
    4515                                 }
    4516                                 break;
    4517                         }
    4518                 }
    4519 
    4520         /* spawn the child process */
    4521         if (pipe_err == 0)
    4522         {
    4523                 pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0);
    4524                 if (pipe_pid == -1)
    4525                 {
    4526                         pipe_err = -1;
    4527                 }
    4528                 else
    4529                 {
    4530                         /* save the PID into the FILE structure
    4531                         * NOTE: this implementation doesn't actually
    4532                         * take advantage of this, but do it for
    4533                         * completeness - AIM Apr01
    4534                         */
    4535                         for (i = 0; i < file_count; i++)
    4536                                 p_s[i]->_pid = pipe_pid;
    4537                 }
    4538         }
    4539 
    4540         /* reset standard IO to normal */
    4541         for (i = 0; i < 3; i++)
    4542         {
    4543                 dup2(stdio[i].handle, i);
    4544                 fcntl(i, F_SETFD, stdio[i].flags);
    4545                 close(stdio[i].handle);
    4546         }
    4547 
    4548         /* if any remnant problems, clean up and bail out */
    4549         if (pipe_err < 0)
    4550         {
    4551                 for (i = 0; i < 3; i++)
    4552                 {
    4553                         close(p_fd[i].rd);
    4554                         close(p_fd[i].wr);
    4555                 }
    4556                 errno = EPIPE;
    4557                 return posix_error_with_filename(cmdstring);
    4558         }
    4559 
    4560         /* build tuple of file objects to return */
    4561         if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL)
    4562                 PyFile_SetBufSize(p_f[0], bufsize);
    4563         if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL)
    4564                 PyFile_SetBufSize(p_f[1], bufsize);
    4565         if (n == POPEN_3)
    4566         {
    4567                 if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL)
    4568                         PyFile_SetBufSize(p_f[0], bufsize);
    4569                 f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]);
    4570         }
    4571         else
    4572                 f = PyTuple_Pack(2, p_f[0], p_f[1]);
    4573 
    4574         /*
    4575         * Insert the files we've created into the process dictionary
    4576         * all referencing the list with the process handle and the
    4577         * initial number of files (see description below in _PyPclose).
    4578         * Since if _PyPclose later tried to wait on a process when all
    4579         * handles weren't closed, it could create a deadlock with the
    4580         * child, we spend some energy here to try to ensure that we
    4581         * either insert all file handles into the dictionary or none
    4582         * at all.  It's a little clumsy with the various popen modes
    4583         * and variable number of files involved.
    4584         */
    4585         if (!_PyPopenProcs)
    4586         {
    4587                 _PyPopenProcs = PyDict_New();
    4588         }
    4589 
    4590         if (_PyPopenProcs)
    4591         {
    4592                 PyObject *procObj, *pidObj, *intObj, *fileObj[3];
    4593                 int ins_rc[3];
    4594 
    4595                 fileObj[0] = fileObj[1] = fileObj[2] = NULL;
    4596                 ins_rc[0]  = ins_rc[1]  = ins_rc[2]  = 0;
    4597 
    4598                 procObj = PyList_New(2);
    4599                 pidObj = PyLong_FromPid(pipe_pid);
    4600                 intObj = PyInt_FromLong((long) file_count);
    4601 
    4602                 if (procObj && pidObj && intObj)
    4603                 {
    4604                         PyList_SetItem(procObj, 0, pidObj);
    4605                         PyList_SetItem(procObj, 1, intObj);
    4606 
    4607                         fileObj[0] = PyLong_FromVoidPtr(p_s[0]);
    4608                         if (fileObj[0])
    4609                         {
    4610                             ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
    4611                                                        fileObj[0],
    4612                                                        procObj);
    4613                         }
    4614                         fileObj[1] = PyLong_FromVoidPtr(p_s[1]);
    4615                         if (fileObj[1])
    4616                         {
    4617                             ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
    4618                                                        fileObj[1],
    4619                                                        procObj);
    4620                         }
    4621                         if (file_count >= 3)
    4622                         {
    4623                                 fileObj[2] = PyLong_FromVoidPtr(p_s[2]);
    4624                                 if (fileObj[2])
    4625                                 {
    4626                                     ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
    4627                                                                fileObj[2],
    4628                                                                procObj);
    4629                                 }
    4630                         }
    4631 
    4632                         if (ins_rc[0] < 0 || !fileObj[0] ||
    4633                             ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
    4634                             ins_rc[2] < 0 || (file_count > 2 && !fileObj[2]))
    4635                         {
    4636                                 /* Something failed - remove any dictionary
    4637                                 * entries that did make it.
    4638                                 */
    4639                                 if (!ins_rc[0] && fileObj[0])
    4640                                 {
    4641                                         PyDict_DelItem(_PyPopenProcs,
    4642                                                         fileObj[0]);
    4643                                 }
    4644                                 if (!ins_rc[1] && fileObj[1])
    4645                                 {
    4646                                         PyDict_DelItem(_PyPopenProcs,
    4647                                                         fileObj[1]);
    4648                                 }
    4649                                 if (!ins_rc[2] && fileObj[2])
    4650                                 {
    4651                                         PyDict_DelItem(_PyPopenProcs,
    4652                                                         fileObj[2]);
    4653                                 }
    4654                         }
    4655                 }
    4656 
    4657                 /*
    4658                 * Clean up our localized references for the dictionary keys
    4659                 * and value since PyDict_SetItem will Py_INCREF any copies
    4660                 * that got placed in the dictionary.
    4661                 */
    4662                 Py_XDECREF(procObj);
    4663                 Py_XDECREF(fileObj[0]);
    4664                 Py_XDECREF(fileObj[1]);
    4665                 Py_XDECREF(fileObj[2]);
    4666         }
    4667 
    4668         /* Child is launched. */
    4669         return f;
     4721    struct file_ref stdio[3];
     4722    struct pipe_ref p_fd[3];
     4723    FILE *p_s[3];
     4724    int file_count, i, pipe_err;
     4725    pid_t pipe_pid;
     4726    char *shell, *sh_name, *opt, *rd_mode, *wr_mode;
     4727    PyObject *f, *p_f[3];
     4728
     4729    /* file modes for subsequent fdopen's on pipe handles */
     4730    if (mode == O_TEXT)
     4731    {
     4732        rd_mode = "rt";
     4733        wr_mode = "wt";
     4734    }
     4735    else
     4736    {
     4737        rd_mode = "rb";
     4738        wr_mode = "wb";
     4739    }
     4740
     4741    /* prepare shell references */
     4742    if ((shell = getenv("EMXSHELL")) == NULL)
     4743        if ((shell = getenv("COMSPEC")) == NULL)
     4744        {
     4745            errno = ENOENT;
     4746            return posix_error();
     4747        }
     4748
     4749    sh_name = _getname(shell);
     4750    if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0)
     4751        opt = "/c";
     4752    else
     4753        opt = "-c";
     4754
     4755    /* save current stdio fds + their flags, and set not inheritable */
     4756    i = pipe_err = 0;
     4757    while (pipe_err >= 0 && i < 3)
     4758    {
     4759        pipe_err = stdio[i].handle = dup(i);
     4760        stdio[i].flags = fcntl(i, F_GETFD, 0);
     4761        fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC);
     4762        i++;
     4763    }
     4764    if (pipe_err < 0)
     4765    {
     4766        /* didn't get them all saved - clean up and bail out */
     4767        int saved_err = errno;
     4768        while (i-- > 0)
     4769        {
     4770            close(stdio[i].handle);
     4771        }
     4772        errno = saved_err;
     4773        return posix_error();
     4774    }
     4775
     4776    /* create pipe ends */
     4777    file_count = 2;
     4778    if (n == POPEN_3)
     4779        file_count = 3;
     4780    i = pipe_err = 0;
     4781    while ((pipe_err == 0) && (i < file_count))
     4782        pipe_err = pipe((int *)&p_fd[i++]);
     4783    if (pipe_err < 0)
     4784    {
     4785        /* didn't get them all made - clean up and bail out */
     4786        while (i-- > 0)
     4787        {
     4788            close(p_fd[i].wr);
     4789            close(p_fd[i].rd);
     4790        }
     4791        errno = EPIPE;
     4792        return posix_error();
     4793    }
     4794
     4795    /* change the actual standard IO streams over temporarily,
     4796    * making the retained pipe ends non-inheritable
     4797    */
     4798    pipe_err = 0;
     4799
     4800    /* - stdin */
     4801    if (dup2(p_fd[0].rd, 0) == 0)
     4802    {
     4803        close(p_fd[0].rd);
     4804        i = fcntl(p_fd[0].wr, F_GETFD, 0);
     4805        fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC);
     4806        if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL)
     4807        {
     4808            close(p_fd[0].wr);
     4809            pipe_err = -1;
     4810        }
     4811    }
     4812    else
     4813    {
     4814        pipe_err = -1;
     4815    }
     4816
     4817    /* - stdout */
     4818    if (pipe_err == 0)
     4819    {
     4820        if (dup2(p_fd[1].wr, 1) == 1)
     4821        {
     4822            close(p_fd[1].wr);
     4823            i = fcntl(p_fd[1].rd, F_GETFD, 0);
     4824            fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC);
     4825            if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL)
     4826            {
     4827                close(p_fd[1].rd);
     4828                pipe_err = -1;
     4829            }
     4830        }
     4831        else
     4832        {
     4833            pipe_err = -1;
     4834        }
     4835    }
     4836
     4837    /* - stderr, as required */
     4838    if (pipe_err == 0)
     4839        switch (n)
     4840        {
     4841            case POPEN_3:
     4842            {
     4843                if (dup2(p_fd[2].wr, 2) == 2)
     4844                {
     4845                    close(p_fd[2].wr);
     4846                    i = fcntl(p_fd[2].rd, F_GETFD, 0);
     4847                    fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC);
     4848                    if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL)
     4849                    {
     4850                        close(p_fd[2].rd);
     4851                        pipe_err = -1;
     4852                    }
     4853                }
     4854                else
     4855                {
     4856                    pipe_err = -1;
     4857                }
     4858                break;
     4859            }
     4860
     4861            case POPEN_4:
     4862            {
     4863                if (dup2(1, 2) != 2)
     4864                {
     4865                    pipe_err = -1;
     4866                }
     4867                break;
     4868            }
     4869        }
     4870
     4871    /* spawn the child process */
     4872    if (pipe_err == 0)
     4873    {
     4874        pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0);
     4875        if (pipe_pid == -1)
     4876        {
     4877            pipe_err = -1;
     4878        }
     4879        else
     4880        {
     4881            /* save the PID into the FILE structure
     4882            * NOTE: this implementation doesn't actually
     4883            * take advantage of this, but do it for
     4884            * completeness - AIM Apr01
     4885            */
     4886            for (i = 0; i < file_count; i++)
     4887                p_s[i]->_pid = pipe_pid;
     4888        }
     4889    }
     4890
     4891    /* reset standard IO to normal */
     4892    for (i = 0; i < 3; i++)
     4893    {
     4894        dup2(stdio[i].handle, i);
     4895        fcntl(i, F_SETFD, stdio[i].flags);
     4896        close(stdio[i].handle);
     4897    }
     4898
     4899    /* if any remnant problems, clean up and bail out */
     4900    if (pipe_err < 0)
     4901    {
     4902        for (i = 0; i < 3; i++)
     4903        {
     4904            close(p_fd[i].rd);
     4905            close(p_fd[i].wr);
     4906        }
     4907        errno = EPIPE;
     4908        return posix_error_with_filename(cmdstring);
     4909    }
     4910
     4911    /* build tuple of file objects to return */
     4912    if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL)
     4913        PyFile_SetBufSize(p_f[0], bufsize);
     4914    if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL)
     4915        PyFile_SetBufSize(p_f[1], bufsize);
     4916    if (n == POPEN_3)
     4917    {
     4918        if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL)
     4919            PyFile_SetBufSize(p_f[0], bufsize);
     4920        f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]);
     4921    }
     4922    else
     4923        f = PyTuple_Pack(2, p_f[0], p_f[1]);
     4924
     4925    /*
     4926    * Insert the files we've created into the process dictionary
     4927    * all referencing the list with the process handle and the
     4928    * initial number of files (see description below in _PyPclose).
     4929    * Since if _PyPclose later tried to wait on a process when all
     4930    * handles weren't closed, it could create a deadlock with the
     4931    * child, we spend some energy here to try to ensure that we
     4932    * either insert all file handles into the dictionary or none
     4933    * at all.  It's a little clumsy with the various popen modes
     4934    * and variable number of files involved.
     4935    */
     4936    if (!_PyPopenProcs)
     4937    {
     4938        _PyPopenProcs = PyDict_New();
     4939    }
     4940
     4941    if (_PyPopenProcs)
     4942    {
     4943        PyObject *procObj, *pidObj, *intObj, *fileObj[3];
     4944        int ins_rc[3];
     4945
     4946        fileObj[0] = fileObj[1] = fileObj[2] = NULL;
     4947        ins_rc[0]  = ins_rc[1]  = ins_rc[2]  = 0;
     4948
     4949        procObj = PyList_New(2);
     4950        pidObj = PyLong_FromPid(pipe_pid);
     4951        intObj = PyInt_FromLong((long) file_count);
     4952
     4953        if (procObj && pidObj && intObj)
     4954        {
     4955            PyList_SetItem(procObj, 0, pidObj);
     4956            PyList_SetItem(procObj, 1, intObj);
     4957
     4958            fileObj[0] = PyLong_FromVoidPtr(p_s[0]);
     4959            if (fileObj[0])
     4960            {
     4961                ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
     4962                                           fileObj[0],
     4963                                           procObj);
     4964            }
     4965            fileObj[1] = PyLong_FromVoidPtr(p_s[1]);
     4966            if (fileObj[1])
     4967            {
     4968                ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
     4969                                           fileObj[1],
     4970                                           procObj);
     4971            }
     4972            if (file_count >= 3)
     4973            {
     4974                fileObj[2] = PyLong_FromVoidPtr(p_s[2]);
     4975                if (fileObj[2])
     4976                {
     4977                    ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
     4978                                               fileObj[2],
     4979                                               procObj);
     4980                }
     4981            }
     4982
     4983            if (ins_rc[0] < 0 || !fileObj[0] ||
     4984                ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
     4985                ins_rc[2] < 0 || (file_count > 2 && !fileObj[2]))
     4986            {
     4987                /* Something failed - remove any dictionary
     4988                * entries that did make it.
     4989                */
     4990                if (!ins_rc[0] && fileObj[0])
     4991                {
     4992                    PyDict_DelItem(_PyPopenProcs,
     4993                                   fileObj[0]);
     4994                }
     4995                if (!ins_rc[1] && fileObj[1])
     4996                {
     4997                    PyDict_DelItem(_PyPopenProcs,
     4998                                   fileObj[1]);
     4999                }
     5000                if (!ins_rc[2] && fileObj[2])
     5001                {
     5002                    PyDict_DelItem(_PyPopenProcs,
     5003                                   fileObj[2]);
     5004                }
     5005            }
     5006        }
     5007
     5008        /*
     5009        * Clean up our localized references for the dictionary keys
     5010        * and value since PyDict_SetItem will Py_INCREF any copies
     5011        * that got placed in the dictionary.
     5012        */
     5013        Py_XDECREF(procObj);
     5014        Py_XDECREF(fileObj[0]);
     5015        Py_XDECREF(fileObj[1]);
     5016        Py_XDECREF(fileObj[2]);
     5017    }
     5018
     5019    /* Child is launched. */
     5020    return f;
    46705021}
    46715022
     
    46985049static int _PyPclose(FILE *file)
    46995050{
    4700         int result;
    4701         int exit_code;
    4702         pid_t pipe_pid;
    4703         PyObject *procObj, *pidObj, *intObj, *fileObj;
    4704         int file_count;
     5051    int result;
     5052    int exit_code;
     5053    pid_t pipe_pid;
     5054    PyObject *procObj, *pidObj, *intObj, *fileObj;
     5055    int file_count;
    47055056#ifdef WITH_THREAD
    4706         PyGILState_STATE state;
    4707 #endif
    4708 
    4709         /* Close the file handle first, to ensure it can't block the
    4710         * child from exiting if it's the last handle.
    4711         */
    4712         result = fclose(file);
     5057    PyGILState_STATE state;
     5058#endif
     5059
     5060    /* Close the file handle first, to ensure it can't block the
     5061    * child from exiting if it's the last handle.
     5062    */
     5063    result = fclose(file);
    47135064
    47145065#ifdef WITH_THREAD
    4715         state = PyGILState_Ensure();
    4716 #endif
    4717         if (_PyPopenProcs)
    4718         {
    4719                 if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&
    4720                     (procObj = PyDict_GetItem(_PyPopenProcs,
    4721                                               fileObj)) != NULL &&
    4722                     (pidObj = PyList_GetItem(procObj,0)) != NULL &&
    4723                     (intObj = PyList_GetItem(procObj,1)) != NULL)
    4724                 {
    4725                         pipe_pid = (pid_t) PyLong_AsPid(pidObj);
    4726                         file_count = (int) PyInt_AsLong(intObj);
    4727 
    4728                         if (file_count > 1)
    4729                         {
    4730                                 /* Still other files referencing process */
    4731                                 file_count--;
    4732                                 PyList_SetItem(procObj,1,
    4733                                                PyInt_FromLong((long) file_count));
    4734                         }
    4735                         else
    4736                         {
    4737                                 /* Last file for this process */
    4738                                 if (result != EOF &&
    4739                                     waitpid(pipe_pid, &exit_code, 0) == pipe_pid)
    4740                                 {
    4741                                         /* extract exit status */
    4742                                         if (WIFEXITED(exit_code))
    4743                                         {
    4744                                                 result = WEXITSTATUS(exit_code);
    4745                                         }
    4746                                         else
    4747                                         {
    4748                                                 errno = EPIPE;
    4749                                                 result = -1;
    4750                                         }
    4751                                 }
    4752                                 else
    4753                                 {
    4754                                         /* Indicate failure - this will cause the file object
    4755                                         * to raise an I/O error and translate the last
    4756                                         * error code from errno.  We do have a problem with
    4757                                         * last errors that overlap the normal errno table,
    4758                                         * but that's a consistent problem with the file object.
    4759                                         */
    4760                                         result = -1;
    4761                                 }
    4762                         }
    4763 
    4764                         /* Remove this file pointer from dictionary */
    4765                         PyDict_DelItem(_PyPopenProcs, fileObj);
    4766 
    4767                         if (PyDict_Size(_PyPopenProcs) == 0)
    4768                         {
    4769                                 Py_DECREF(_PyPopenProcs);
    4770                                 _PyPopenProcs = NULL;
    4771                         }
    4772 
    4773                 } /* if object retrieval ok */
    4774 
    4775                 Py_XDECREF(fileObj);
    4776         } /* if _PyPopenProcs */
     5066    state = PyGILState_Ensure();
     5067#endif
     5068    if (_PyPopenProcs)
     5069    {
     5070        if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&
     5071            (procObj = PyDict_GetItem(_PyPopenProcs,
     5072                                      fileObj)) != NULL &&
     5073            (pidObj = PyList_GetItem(procObj,0)) != NULL &&
     5074            (intObj = PyList_GetItem(procObj,1)) != NULL)
     5075        {
     5076            pipe_pid = (pid_t) PyLong_AsPid(pidObj);
     5077            file_count = (int) PyInt_AsLong(intObj);
     5078
     5079            if (file_count > 1)
     5080            {
     5081                /* Still other files referencing process */
     5082                file_count--;
     5083                PyList_SetItem(procObj,1,
     5084                               PyInt_FromLong((long) file_count));
     5085            }
     5086            else
     5087            {
     5088                /* Last file for this process */
     5089                if (result != EOF &&
     5090                    waitpid(pipe_pid, &exit_code, 0) == pipe_pid)
     5091                {
     5092                    /* extract exit status */
     5093                    if (WIFEXITED(exit_code))
     5094                    {
     5095                        result = WEXITSTATUS(exit_code);
     5096                    }
     5097                    else
     5098                    {
     5099                        errno = EPIPE;
     5100                        result = -1;
     5101                    }
     5102                }
     5103                else
     5104                {
     5105                    /* Indicate failure - this will cause the file object
     5106                    * to raise an I/O error and translate the last
     5107                    * error code from errno.  We do have a problem with
     5108                    * last errors that overlap the normal errno table,
     5109                    * but that's a consistent problem with the file object.
     5110                    */
     5111                    result = -1;
     5112                }
     5113            }
     5114
     5115            /* Remove this file pointer from dictionary */
     5116            PyDict_DelItem(_PyPopenProcs, fileObj);
     5117
     5118            if (PyDict_Size(_PyPopenProcs) == 0)
     5119            {
     5120                Py_DECREF(_PyPopenProcs);
     5121                _PyPopenProcs = NULL;
     5122            }
     5123
     5124        } /* if object retrieval ok */
     5125
     5126        Py_XDECREF(fileObj);
     5127    } /* if _PyPopenProcs */
    47775128
    47785129#ifdef WITH_THREAD
    4779         PyGILState_Release(state);
    4780 #endif
    4781         return result;
     5130    PyGILState_Release(state);
     5131#endif
     5132    return result;
    47825133}
    47835134
     
    48245175posix_popen(PyObject *self, PyObject *args)
    48255176{
    4826         PyObject *f;
    4827         int tm = 0;
    4828 
    4829         char *cmdstring;
    4830         char *mode = "r";
    4831         int bufsize = -1;
    4832         if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize))
    4833                 return NULL;
    4834 
    4835         if (*mode == 'r')
    4836                 tm = _O_RDONLY;
    4837         else if (*mode != 'w') {
    4838                 PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'");
    4839                 return NULL;
    4840         } else
    4841                 tm = _O_WRONLY;
    4842 
    4843         if (bufsize != -1) {
    4844                 PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1");
    4845                 return NULL;
    4846         }
    4847 
    4848         if (*(mode+1) == 't')
    4849                 f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);
    4850         else if (*(mode+1) == 'b')
    4851                 f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1);
    4852         else
    4853                 f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);
    4854 
    4855         return f;
     5177    PyObject *f;
     5178    int tm = 0;
     5179
     5180    char *cmdstring;
     5181    char *mode = "r";
     5182    int bufsize = -1;
     5183    if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize))
     5184        return NULL;
     5185
     5186    if (*mode == 'r')
     5187        tm = _O_RDONLY;
     5188    else if (*mode != 'w') {
     5189        PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'");
     5190        return NULL;
     5191    } else
     5192        tm = _O_WRONLY;
     5193
     5194    if (bufsize != -1) {
     5195        PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1");
     5196        return NULL;
     5197    }
     5198
     5199    if (*(mode+1) == 't')
     5200        f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);
     5201    else if (*(mode+1) == 'b')
     5202        f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1);
     5203    else
     5204        f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);
     5205
     5206    return f;
    48565207}
    48575208
     
    48655216win32_popen2(PyObject *self, PyObject  *args)
    48665217{
    4867         PyObject *f;
    4868         int tm=0;
    4869 
    4870         char *cmdstring;
    4871         char *mode = "t";
    4872         int bufsize = -1;
    4873         if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))
    4874                 return NULL;
    4875 
    4876         if (*mode == 't')
    4877                 tm = _O_TEXT;
    4878         else if (*mode != 'b') {
    4879                 PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'");
    4880                 return NULL;
    4881         } else
    4882                 tm = _O_BINARY;
    4883 
    4884         if (bufsize != -1) {
    4885                 PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1");
    4886                 return NULL;
    4887         }
    4888 
    4889         f = _PyPopen(cmdstring, tm, POPEN_2);
    4890 
    4891         return f;
     5218    PyObject *f;
     5219    int tm=0;
     5220
     5221    char *cmdstring;
     5222    char *mode = "t";
     5223    int bufsize = -1;
     5224    if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))
     5225        return NULL;
     5226
     5227    if (*mode == 't')
     5228        tm = _O_TEXT;
     5229    else if (*mode != 'b') {
     5230        PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'");
     5231        return NULL;
     5232    } else
     5233        tm = _O_BINARY;
     5234
     5235    if (bufsize != -1) {
     5236        PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1");
     5237        return NULL;
     5238    }
     5239
     5240    f = _PyPopen(cmdstring, tm, POPEN_2);
     5241
     5242    return f;
    48925243}
    48935244
     
    49025253win32_popen3(PyObject *self, PyObject *args)
    49035254{
    4904         PyObject *f;
    4905         int tm = 0;
    4906 
    4907         char *cmdstring;
    4908         char *mode = "t";
    4909         int bufsize = -1;
    4910         if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))
    4911                 return NULL;
    4912 
    4913         if (*mode == 't')
    4914                 tm = _O_TEXT;
    4915         else if (*mode != 'b') {
    4916                 PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'");
    4917                 return NULL;
    4918         } else
    4919                 tm = _O_BINARY;
    4920 
    4921         if (bufsize != -1) {
    4922                 PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1");
    4923                 return NULL;
    4924         }
    4925 
    4926         f = _PyPopen(cmdstring, tm, POPEN_3);
    4927 
    4928         return f;
     5255    PyObject *f;
     5256    int tm = 0;
     5257
     5258    char *cmdstring;
     5259    char *mode = "t";
     5260    int bufsize = -1;
     5261    if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))
     5262        return NULL;
     5263
     5264    if (*mode == 't')
     5265        tm = _O_TEXT;
     5266    else if (*mode != 'b') {
     5267        PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'");
     5268        return NULL;
     5269    } else
     5270        tm = _O_BINARY;
     5271
     5272    if (bufsize != -1) {
     5273        PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1");
     5274        return NULL;
     5275    }
     5276
     5277    f = _PyPopen(cmdstring, tm, POPEN_3);
     5278
     5279    return f;
    49295280}
    49305281
     
    49395290win32_popen4(PyObject *self, PyObject  *args)
    49405291{
    4941         PyObject *f;
    4942         int tm = 0;
    4943 
    4944         char *cmdstring;
    4945         char *mode = "t";
    4946         int bufsize = -1;
    4947         if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))
    4948                 return NULL;
    4949 
    4950         if (*mode == 't')
    4951                 tm = _O_TEXT;
    4952         else if (*mode != 'b') {
    4953                 PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'");
    4954                 return NULL;
    4955         } else
    4956                 tm = _O_BINARY;
    4957 
    4958         if (bufsize != -1) {
    4959                 PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1");
    4960                 return NULL;
    4961         }
    4962 
    4963         f = _PyPopen(cmdstring, tm, POPEN_4);
    4964 
    4965         return f;
     5292    PyObject *f;
     5293    int tm = 0;
     5294
     5295    char *cmdstring;
     5296    char *mode = "t";
     5297    int bufsize = -1;
     5298    if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))
     5299        return NULL;
     5300
     5301    if (*mode == 't')
     5302        tm = _O_TEXT;
     5303    else if (*mode != 'b') {
     5304        PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'");
     5305        return NULL;
     5306    } else
     5307        tm = _O_BINARY;
     5308
     5309    if (bufsize != -1) {
     5310        PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1");
     5311        return NULL;
     5312    }
     5313
     5314    f = _PyPopen(cmdstring, tm, POPEN_4);
     5315
     5316    return f;
    49665317}
    49675318
    49685319static BOOL
    49695320_PyPopenCreateProcess(char *cmdstring,
    4970                       HANDLE hStdin,
    4971                       HANDLE hStdout,
    4972                       HANDLE hStderr,
    4973                       HANDLE *hProcess)
    4974 {
    4975         PROCESS_INFORMATION piProcInfo;
    4976         STARTUPINFO siStartInfo;
    4977         DWORD dwProcessFlags = 0;  /* no NEW_CONSOLE by default for Ctrl+C handling */
    4978         char *s1,*s2, *s3 = " /c ";
    4979         const char *szConsoleSpawn = "w9xpopen.exe";
    4980         int i;
    4981         Py_ssize_t x;
    4982 
    4983         if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) {
    4984                 char *comshell;
    4985 
    4986                 s1 = (char *)alloca(i);
    4987                 if (!(x = GetEnvironmentVariable("COMSPEC", s1, i)))
    4988                         /* x < i, so x fits into an integer */
    4989                         return (int)x;
    4990 
    4991                 /* Explicitly check if we are using COMMAND.COM.  If we are
    4992                 * then use the w9xpopen hack.
    4993                 */
    4994                 comshell = s1 + x;
    4995                 while (comshell >= s1 && *comshell != '\\')
    4996                         --comshell;
    4997                 ++comshell;
    4998 
    4999                 if (GetVersion() < 0x80000000 &&
    5000                     _stricmp(comshell, "command.com") != 0) {
    5001                         /* NT/2000 and not using command.com. */
    5002                         x = i + strlen(s3) + strlen(cmdstring) + 1;
    5003                         s2 = (char *)alloca(x);
    5004                         ZeroMemory(s2, x);
    5005                         PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring);
    5006                 }
    5007                 else {
    5008                         /*
    5009                         * Oh gag, we're on Win9x or using COMMAND.COM. Use
    5010                         * the workaround listed in KB: Q150956
    5011                         */
    5012                         char modulepath[_MAX_PATH];
    5013                         struct stat statinfo;
    5014                         GetModuleFileName(NULL, modulepath, sizeof(modulepath));
    5015                         for (x = i = 0; modulepath[i]; i++)
    5016                                 if (modulepath[i] == SEP)
    5017                                         x = i+1;
    5018                         modulepath[x] = '\0';
    5019                         /* Create the full-name to w9xpopen, so we can test it exists */
    5020                         strncat(modulepath,
    5021                                 szConsoleSpawn,
    5022                                 (sizeof(modulepath)/sizeof(modulepath[0]))
    5023                                        -strlen(modulepath));
    5024                         if (stat(modulepath, &statinfo) != 0) {
    5025                                 size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]);
    5026                                 /* Eeek - file-not-found - possibly an embedding
    5027                                    situation - see if we can locate it in sys.prefix
    5028                                 */
    5029                                 strncpy(modulepath,
    5030                                         Py_GetExecPrefix(),
    5031                                         mplen);
    5032                                 modulepath[mplen-1] = '\0';
    5033                                 if (modulepath[strlen(modulepath)-1] != '\\')
    5034                                         strcat(modulepath, "\\");
    5035                                 strncat(modulepath,
    5036                                         szConsoleSpawn,
    5037                                         mplen-strlen(modulepath));
    5038                                 /* No where else to look - raise an easily identifiable
    5039                                    error, rather than leaving Windows to report
    5040                                    "file not found" - as the user is probably blissfully
    5041                                    unaware this shim EXE is used, and it will confuse them.
    5042                                    (well, it confused me for a while ;-)
    5043                                 */
    5044                                 if (stat(modulepath, &statinfo) != 0) {
    5045                                         PyErr_Format(PyExc_RuntimeError,
    5046                                             "Can not locate '%s' which is needed "
    5047                                             "for popen to work with your shell "
    5048                                             "or platform.",
    5049                                             szConsoleSpawn);
    5050                                         return FALSE;
    5051                                 }
    5052                         }
    5053                         x = i + strlen(s3) + strlen(cmdstring) + 1 +
    5054                                 strlen(modulepath) +
    5055                                 strlen(szConsoleSpawn) + 1;
    5056 
    5057                         s2 = (char *)alloca(x);
    5058                         ZeroMemory(s2, x);
    5059                         /* To maintain correct argument passing semantics,
    5060                            we pass the command-line as it stands, and allow
    5061                            quoting to be applied.  w9xpopen.exe will then
    5062                            use its argv vector, and re-quote the necessary
    5063                            args for the ultimate child process.
    5064                         */
    5065                         PyOS_snprintf(
    5066                                 s2, x,
    5067                                 "\"%s\" %s%s%s",
    5068                                 modulepath,
    5069                                 s1,
    5070                                 s3,
    5071                                 cmdstring);
    5072                         /* Not passing CREATE_NEW_CONSOLE has been known to
    5073                            cause random failures on win9x.  Specifically a
    5074                            dialog:
    5075                            "Your program accessed mem currently in use at xxx"
    5076                            and a hopeful warning about the stability of your
    5077                            system.
    5078                            Cost is Ctrl+C won't kill children, but anyone
    5079                            who cares can have a go!
    5080                         */
    5081                         dwProcessFlags |= CREATE_NEW_CONSOLE;
    5082                 }
    5083         }
    5084 
    5085         /* Could be an else here to try cmd.exe / command.com in the path
    5086            Now we'll just error out.. */
    5087         else {
    5088                 PyErr_SetString(PyExc_RuntimeError,
    5089                         "Cannot locate a COMSPEC environment variable to "
    5090                         "use as the shell");
    5091                 return FALSE;
    5092         }
    5093 
    5094         ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
    5095         siStartInfo.cb = sizeof(STARTUPINFO);
    5096         siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    5097         siStartInfo.hStdInput = hStdin;
    5098         siStartInfo.hStdOutput = hStdout;
    5099         siStartInfo.hStdError = hStderr;
    5100         siStartInfo.wShowWindow = SW_HIDE;
    5101 
    5102         if (CreateProcess(NULL,
    5103                           s2,
    5104                           NULL,
    5105                           NULL,
    5106                           TRUE,
    5107                           dwProcessFlags,
    5108                           NULL,
    5109                           NULL,
    5110                           &siStartInfo,
    5111                           &piProcInfo) ) {
    5112                 /* Close the handles now so anyone waiting is woken. */
    5113                 CloseHandle(piProcInfo.hThread);
    5114 
    5115                 /* Return process handle */
    5116                 *hProcess = piProcInfo.hProcess;
    5117                 return TRUE;
    5118         }
    5119         win32_error("CreateProcess", s2);
    5120         return FALSE;
     5321                      HANDLE hStdin,
     5322                      HANDLE hStdout,
     5323                      HANDLE hStderr,
     5324                      HANDLE *hProcess)
     5325{
     5326    PROCESS_INFORMATION piProcInfo;
     5327    STARTUPINFO siStartInfo;
     5328    DWORD dwProcessFlags = 0;  /* no NEW_CONSOLE by default for Ctrl+C handling */
     5329    char *s1,*s2, *s3 = " /c ";
     5330    const char *szConsoleSpawn = "w9xpopen.exe";
     5331    int i;
     5332    Py_ssize_t x;
     5333
     5334    if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) {
     5335        char *comshell;
     5336
     5337        s1 = (char *)alloca(i);
     5338        if (!(x = GetEnvironmentVariable("COMSPEC", s1, i)))
     5339            /* x < i, so x fits into an integer */
     5340            return (int)x;
     5341
     5342        /* Explicitly check if we are using COMMAND.COM.  If we are
     5343        * then use the w9xpopen hack.
     5344        */
     5345        comshell = s1 + x;
     5346        while (comshell >= s1 && *comshell != '\\')
     5347            --comshell;
     5348        ++comshell;
     5349
     5350        if (GetVersion() < 0x80000000 &&
     5351            _stricmp(comshell, "command.com") != 0) {
     5352            /* NT/2000 and not using command.com. */
     5353            x = i + strlen(s3) + strlen(cmdstring) + 1;
     5354            s2 = (char *)alloca(x);
     5355            ZeroMemory(s2, x);
     5356            PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring);
     5357        }
     5358        else {
     5359            /*
     5360            * Oh gag, we're on Win9x or using COMMAND.COM. Use
     5361            * the workaround listed in KB: Q150956
     5362            */
     5363            char modulepath[_MAX_PATH];
     5364            struct stat statinfo;
     5365            GetModuleFileName(NULL, modulepath, sizeof(modulepath));
     5366            for (x = i = 0; modulepath[i]; i++)
     5367                if (modulepath[i] == SEP)
     5368                    x = i+1;
     5369            modulepath[x] = '\0';
     5370            /* Create the full-name to w9xpopen, so we can test it exists */
     5371            strncat(modulepath,
     5372                    szConsoleSpawn,
     5373                    (sizeof(modulepath)/sizeof(modulepath[0]))
     5374                        -strlen(modulepath));
     5375            if (stat(modulepath, &statinfo) != 0) {
     5376                size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]);
     5377                /* Eeek - file-not-found - possibly an embedding
     5378                   situation - see if we can locate it in sys.prefix
     5379                */
     5380                strncpy(modulepath,
     5381                        Py_GetExecPrefix(),
     5382                        mplen);
     5383                modulepath[mplen-1] = '\0';
     5384                if (modulepath[strlen(modulepath)-1] != '\\')
     5385                    strcat(modulepath, "\\");
     5386                strncat(modulepath,
     5387                        szConsoleSpawn,
     5388                        mplen-strlen(modulepath));
     5389                /* No where else to look - raise an easily identifiable
     5390                   error, rather than leaving Windows to report
     5391                   "file not found" - as the user is probably blissfully
     5392                   unaware this shim EXE is used, and it will confuse them.
     5393                   (well, it confused me for a while ;-)
     5394                */
     5395                if (stat(modulepath, &statinfo) != 0) {
     5396                    PyErr_Format(PyExc_RuntimeError,
     5397                                 "Can not locate '%s' which is needed "
     5398                                 "for popen to work with your shell "
     5399                                 "or platform.",
     5400                                 szConsoleSpawn);
     5401                    return FALSE;
     5402                }
     5403            }
     5404            x = i + strlen(s3) + strlen(cmdstring) + 1 +
     5405                strlen(modulepath) +
     5406                strlen(szConsoleSpawn) + 1;
     5407
     5408            s2 = (char *)alloca(x);
     5409            ZeroMemory(s2, x);
     5410            /* To maintain correct argument passing semantics,
     5411               we pass the command-line as it stands, and allow
     5412               quoting to be applied.  w9xpopen.exe will then
     5413               use its argv vector, and re-quote the necessary
     5414               args for the ultimate child process.
     5415            */
     5416            PyOS_snprintf(
     5417                s2, x,
     5418                "\"%s\" %s%s%s",
     5419                modulepath,
     5420                s1,
     5421                s3,
     5422                cmdstring);
     5423            /* Not passing CREATE_NEW_CONSOLE has been known to
     5424               cause random failures on win9x.  Specifically a
     5425               dialog:
     5426               "Your program accessed mem currently in use at xxx"
     5427               and a hopeful warning about the stability of your
     5428               system.
     5429               Cost is Ctrl+C won't kill children, but anyone
     5430               who cares can have a go!
     5431            */
     5432            dwProcessFlags |= CREATE_NEW_CONSOLE;
     5433        }
     5434    }
     5435
     5436    /* Could be an else here to try cmd.exe / command.com in the path
     5437       Now we'll just error out.. */
     5438    else {
     5439        PyErr_SetString(PyExc_RuntimeError,
     5440                        "Cannot locate a COMSPEC environment variable to "
     5441                        "use as the shell");
     5442        return FALSE;
     5443    }
     5444
     5445    ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
     5446    siStartInfo.cb = sizeof(STARTUPINFO);
     5447    siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
     5448    siStartInfo.hStdInput = hStdin;
     5449    siStartInfo.hStdOutput = hStdout;
     5450    siStartInfo.hStdError = hStderr;
     5451    siStartInfo.wShowWindow = SW_HIDE;
     5452
     5453    if (CreateProcess(NULL,
     5454                      s2,
     5455                      NULL,
     5456                      NULL,
     5457                      TRUE,
     5458                      dwProcessFlags,
     5459                      NULL,
     5460                      NULL,
     5461                      &siStartInfo,
     5462                      &piProcInfo) ) {
     5463        /* Close the handles now so anyone waiting is woken. */
     5464        CloseHandle(piProcInfo.hThread);
     5465
     5466        /* Return process handle */
     5467        *hProcess = piProcInfo.hProcess;
     5468        return TRUE;
     5469    }
     5470    win32_error("CreateProcess", s2);
     5471    return FALSE;
    51215472}
    51225473
     
    51265477_PyPopen(char *cmdstring, int mode, int n)
    51275478{
    5128         HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr,
    5129                 hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup,
    5130                 hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */
    5131 
    5132         SECURITY_ATTRIBUTES saAttr;
    5133         BOOL fSuccess;
    5134         int fd1, fd2, fd3;
    5135         FILE *f1, *f2, *f3;
    5136         long file_count;
    5137         PyObject *f;
    5138 
    5139         saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    5140         saAttr.bInheritHandle = TRUE;
    5141         saAttr.lpSecurityDescriptor = NULL;
    5142 
    5143         if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
    5144                 return win32_error("CreatePipe", NULL);
    5145 
    5146         /* Create new output read handle and the input write handle. Set
    5147         * the inheritance properties to FALSE. Otherwise, the child inherits
    5148         * these handles; resulting in non-closeable handles to the pipes
    5149         * being created. */
    5150         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
    5151                                     GetCurrentProcess(), &hChildStdinWrDup, 0,
    5152                                     FALSE,
    5153                                     DUPLICATE_SAME_ACCESS);
    5154         if (!fSuccess)
    5155                 return win32_error("DuplicateHandle", NULL);
    5156 
    5157         /* Close the inheritable version of ChildStdin
    5158         that we're using. */
    5159         CloseHandle(hChildStdinWr);
    5160 
    5161         if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
    5162                 return win32_error("CreatePipe", NULL);
    5163 
    5164         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
    5165                                     GetCurrentProcess(), &hChildStdoutRdDup, 0,
    5166                                     FALSE, DUPLICATE_SAME_ACCESS);
    5167         if (!fSuccess)
    5168                 return win32_error("DuplicateHandle", NULL);
    5169 
    5170         /* Close the inheritable version of ChildStdout
    5171                 that we're using. */
    5172         CloseHandle(hChildStdoutRd);
    5173 
    5174         if (n != POPEN_4) {
    5175                 if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0))
    5176                         return win32_error("CreatePipe", NULL);
    5177                 fSuccess = DuplicateHandle(GetCurrentProcess(),
    5178                                             hChildStderrRd,
    5179                                             GetCurrentProcess(),
    5180                                             &hChildStderrRdDup, 0,
    5181                                             FALSE, DUPLICATE_SAME_ACCESS);
    5182                 if (!fSuccess)
    5183                         return win32_error("DuplicateHandle", NULL);
    5184                 /* Close the inheritable version of ChildStdErr that we're using. */
    5185                 CloseHandle(hChildStderrRd);
    5186         }
    5187 
    5188         switch (n) {
    5189         case POPEN_1:
    5190                 switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) {
    5191                 case _O_WRONLY | _O_TEXT:
    5192                         /* Case for writing to child Stdin in text mode. */
    5193                         fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
    5194                         f1 = _fdopen(fd1, "w");
    5195                         f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose);
    5196                         PyFile_SetBufSize(f, 0);
    5197                         /* We don't care about these pipes anymore, so close them. */
    5198                         CloseHandle(hChildStdoutRdDup);
    5199                         CloseHandle(hChildStderrRdDup);
    5200                         break;
    5201 
    5202                 case _O_RDONLY | _O_TEXT:
    5203                         /* Case for reading from child Stdout in text mode. */
    5204                         fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
    5205                         f1 = _fdopen(fd1, "r");
    5206                         f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose);
    5207                         PyFile_SetBufSize(f, 0);
    5208                         /* We don't care about these pipes anymore, so close them. */
    5209                         CloseHandle(hChildStdinWrDup);
    5210                         CloseHandle(hChildStderrRdDup);
    5211                         break;
    5212 
    5213                 case _O_RDONLY | _O_BINARY:
    5214                         /* Case for readinig from child Stdout in binary mode. */
    5215                         fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
    5216                         f1 = _fdopen(fd1, "rb");
    5217                         f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose);
    5218                         PyFile_SetBufSize(f, 0);
    5219                         /* We don't care about these pipes anymore, so close them. */
    5220                         CloseHandle(hChildStdinWrDup);
    5221                         CloseHandle(hChildStderrRdDup);
    5222                         break;
    5223 
    5224                 case _O_WRONLY | _O_BINARY:
    5225                         /* Case for writing to child Stdin in binary mode. */
    5226                         fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
    5227                         f1 = _fdopen(fd1, "wb");
    5228                         f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose);
    5229                         PyFile_SetBufSize(f, 0);
    5230                         /* We don't care about these pipes anymore, so close them. */
    5231                         CloseHandle(hChildStdoutRdDup);
    5232                         CloseHandle(hChildStderrRdDup);
    5233                         break;
    5234                 }
    5235                 file_count = 1;
    5236                 break;
    5237 
    5238         case POPEN_2:
    5239         case POPEN_4:
    5240         {
    5241                 char *m1, *m2;
    5242                 PyObject *p1, *p2;
    5243 
    5244                 if (mode & _O_TEXT) {
    5245                         m1 = "r";
    5246                         m2 = "w";
    5247                 } else {
    5248                         m1 = "rb";
    5249                         m2 = "wb";
    5250                 }
    5251 
    5252                 fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
    5253                 f1 = _fdopen(fd1, m2);
    5254                 fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
    5255                 f2 = _fdopen(fd2, m1);
    5256                 p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
    5257                 PyFile_SetBufSize(p1, 0);
    5258                 p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
    5259                 PyFile_SetBufSize(p2, 0);
    5260 
    5261                 if (n != 4)
    5262                         CloseHandle(hChildStderrRdDup);
    5263 
    5264                 f = PyTuple_Pack(2,p1,p2);
    5265                 Py_XDECREF(p1);
    5266                 Py_XDECREF(p2);
    5267                 file_count = 2;
    5268                 break;
    5269         }
    5270 
    5271         case POPEN_3:
    5272         {
    5273                 char *m1, *m2;
    5274                 PyObject *p1, *p2, *p3;
    5275 
    5276                 if (mode & _O_TEXT) {
    5277                         m1 = "r";
    5278                         m2 = "w";
    5279                 } else {
    5280                         m1 = "rb";
    5281                         m2 = "wb";
    5282                 }
    5283 
    5284                 fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
    5285                 f1 = _fdopen(fd1, m2);
    5286                 fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
    5287                 f2 = _fdopen(fd2, m1);
    5288                 fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode);
    5289                 f3 = _fdopen(fd3, m1);
    5290                 p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
    5291                 p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
    5292                 p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose);
    5293                 PyFile_SetBufSize(p1, 0);
    5294                 PyFile_SetBufSize(p2, 0);
    5295                 PyFile_SetBufSize(p3, 0);
    5296                 f = PyTuple_Pack(3,p1,p2,p3);
    5297                 Py_XDECREF(p1);
    5298                 Py_XDECREF(p2);
    5299                 Py_XDECREF(p3);
    5300                 file_count = 3;
    5301                 break;
    5302         }
    5303         }
    5304 
    5305         if (n == POPEN_4) {
    5306                 if (!_PyPopenCreateProcess(cmdstring,
    5307                                             hChildStdinRd,
    5308                                             hChildStdoutWr,
    5309                                             hChildStdoutWr,
    5310                                             &hProcess))
    5311                         return NULL;
    5312         }
    5313         else {
    5314                 if (!_PyPopenCreateProcess(cmdstring,
    5315                                             hChildStdinRd,
    5316                                             hChildStdoutWr,
    5317                                             hChildStderrWr,
    5318                                             &hProcess))
    5319                         return NULL;
    5320         }
    5321 
    5322         /*
    5323           * Insert the files we've created into the process dictionary
    5324           * all referencing the list with the process handle and the
    5325           * initial number of files (see description below in _PyPclose).
    5326           * Since if _PyPclose later tried to wait on a process when all
    5327           * handles weren't closed, it could create a deadlock with the
    5328           * child, we spend some energy here to try to ensure that we
    5329           * either insert all file handles into the dictionary or none
    5330           * at all.  It's a little clumsy with the various popen modes
    5331           * and variable number of files involved.
    5332           */
    5333         if (!_PyPopenProcs) {
    5334                 _PyPopenProcs = PyDict_New();
    5335         }
    5336 
    5337         if (_PyPopenProcs) {
    5338                 PyObject *procObj, *hProcessObj, *intObj, *fileObj[3];
    5339                 int ins_rc[3];
    5340 
    5341                 fileObj[0] = fileObj[1] = fileObj[2] = NULL;
    5342                 ins_rc[0]  = ins_rc[1]  = ins_rc[2]  = 0;
    5343 
    5344                 procObj = PyList_New(2);
    5345                 hProcessObj = PyLong_FromVoidPtr(hProcess);
    5346                 intObj = PyInt_FromLong(file_count);
    5347 
    5348                 if (procObj && hProcessObj && intObj) {
    5349                         PyList_SetItem(procObj,0,hProcessObj);
    5350                         PyList_SetItem(procObj,1,intObj);
    5351 
    5352                         fileObj[0] = PyLong_FromVoidPtr(f1);
    5353                         if (fileObj[0]) {
    5354                             ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
    5355                                                        fileObj[0],
    5356                                                        procObj);
    5357                         }
    5358                         if (file_count >= 2) {
    5359                                 fileObj[1] = PyLong_FromVoidPtr(f2);
    5360                                 if (fileObj[1]) {
    5361                                     ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
    5362                                                                fileObj[1],
    5363                                                                procObj);
    5364                                 }
    5365                         }
    5366                         if (file_count >= 3) {
    5367                                 fileObj[2] = PyLong_FromVoidPtr(f3);
    5368                                 if (fileObj[2]) {
    5369                                     ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
    5370                                                                fileObj[2],
    5371                                                                procObj);
    5372                                 }
    5373                         }
    5374 
    5375                         if (ins_rc[0] < 0 || !fileObj[0] ||
    5376                              ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
    5377                              ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) {
    5378                                 /* Something failed - remove any dictionary
    5379                                   * entries that did make it.
    5380                                   */
    5381                                 if (!ins_rc[0] && fileObj[0]) {
    5382                                         PyDict_DelItem(_PyPopenProcs,
    5383                                                         fileObj[0]);
    5384                                 }
    5385                                 if (!ins_rc[1] && fileObj[1]) {
    5386                                         PyDict_DelItem(_PyPopenProcs,
    5387                                                         fileObj[1]);
    5388                                 }
    5389                                 if (!ins_rc[2] && fileObj[2]) {
    5390                                         PyDict_DelItem(_PyPopenProcs,
    5391                                                         fileObj[2]);
    5392                                 }
    5393                         }
    5394                 }
    5395 
    5396                 /*
    5397                   * Clean up our localized references for the dictionary keys
    5398                   * and value since PyDict_SetItem will Py_INCREF any copies
    5399                   * that got placed in the dictionary.
    5400                   */
    5401                 Py_XDECREF(procObj);
    5402                 Py_XDECREF(fileObj[0]);
    5403                 Py_XDECREF(fileObj[1]);
    5404                 Py_XDECREF(fileObj[2]);
    5405         }
    5406 
    5407         /* Child is launched. Close the parents copy of those pipe
    5408           * handles that only the child should have open.  You need to
    5409           * make sure that no handles to the write end of the output pipe
    5410           * are maintained in this process or else the pipe will not close
    5411           * when the child process exits and the ReadFile will hang. */
    5412 
    5413         if (!CloseHandle(hChildStdinRd))
    5414                 return win32_error("CloseHandle", NULL);
    5415 
    5416         if (!CloseHandle(hChildStdoutWr))
    5417                 return win32_error("CloseHandle", NULL);
    5418 
    5419         if ((n != 4) && (!CloseHandle(hChildStderrWr)))
    5420                 return win32_error("CloseHandle", NULL);
    5421 
    5422         return f;
     5479    HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr,
     5480        hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup,
     5481        hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */
     5482
     5483    SECURITY_ATTRIBUTES saAttr;
     5484    BOOL fSuccess;
     5485    int fd1, fd2, fd3;
     5486    FILE *f1, *f2, *f3;
     5487    long file_count;
     5488    PyObject *f;
     5489
     5490    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
     5491    saAttr.bInheritHandle = TRUE;
     5492    saAttr.lpSecurityDescriptor = NULL;
     5493
     5494    if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
     5495        return win32_error("CreatePipe", NULL);
     5496
     5497    /* Create new output read handle and the input write handle. Set
     5498    * the inheritance properties to FALSE. Otherwise, the child inherits
     5499    * these handles; resulting in non-closeable handles to the pipes
     5500    * being created. */
     5501    fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
     5502                                GetCurrentProcess(), &hChildStdinWrDup, 0,
     5503                                FALSE,
     5504                                DUPLICATE_SAME_ACCESS);
     5505    if (!fSuccess)
     5506        return win32_error("DuplicateHandle", NULL);
     5507
     5508    /* Close the inheritable version of ChildStdin
     5509    that we're using. */
     5510    CloseHandle(hChildStdinWr);
     5511
     5512    if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
     5513        return win32_error("CreatePipe", NULL);
     5514
     5515    fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
     5516                                GetCurrentProcess(), &hChildStdoutRdDup, 0,
     5517                                FALSE, DUPLICATE_SAME_ACCESS);
     5518    if (!fSuccess)
     5519        return win32_error("DuplicateHandle", NULL);
     5520
     5521    /* Close the inheritable version of ChildStdout
     5522        that we're using. */
     5523    CloseHandle(hChildStdoutRd);
     5524
     5525    if (n != POPEN_4) {
     5526        if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0))
     5527            return win32_error("CreatePipe", NULL);
     5528        fSuccess = DuplicateHandle(GetCurrentProcess(),
     5529                                    hChildStderrRd,
     5530                                    GetCurrentProcess(),
     5531                                    &hChildStderrRdDup, 0,
     5532                                    FALSE, DUPLICATE_SAME_ACCESS);
     5533        if (!fSuccess)
     5534            return win32_error("DuplicateHandle", NULL);
     5535        /* Close the inheritable version of ChildStdErr that we're using. */
     5536        CloseHandle(hChildStderrRd);
     5537    }
     5538
     5539    switch (n) {
     5540    case POPEN_1:
     5541        switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) {
     5542        case _O_WRONLY | _O_TEXT:
     5543            /* Case for writing to child Stdin in text mode. */
     5544            fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
     5545            f1 = _fdopen(fd1, "w");
     5546            f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose);
     5547            PyFile_SetBufSize(f, 0);
     5548            /* We don't care about these pipes anymore, so close them. */
     5549            CloseHandle(hChildStdoutRdDup);
     5550            CloseHandle(hChildStderrRdDup);
     5551            break;
     5552
     5553        case _O_RDONLY | _O_TEXT:
     5554            /* Case for reading from child Stdout in text mode. */
     5555            fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
     5556            f1 = _fdopen(fd1, "r");
     5557            f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose);
     5558            PyFile_SetBufSize(f, 0);
     5559            /* We don't care about these pipes anymore, so close them. */
     5560            CloseHandle(hChildStdinWrDup);
     5561            CloseHandle(hChildStderrRdDup);
     5562            break;
     5563
     5564        case _O_RDONLY | _O_BINARY:
     5565            /* Case for readinig from child Stdout in binary mode. */
     5566            fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
     5567            f1 = _fdopen(fd1, "rb");
     5568            f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose);
     5569            PyFile_SetBufSize(f, 0);
     5570            /* We don't care about these pipes anymore, so close them. */
     5571            CloseHandle(hChildStdinWrDup);
     5572            CloseHandle(hChildStderrRdDup);
     5573            break;
     5574
     5575        case _O_WRONLY | _O_BINARY:
     5576            /* Case for writing to child Stdin in binary mode. */
     5577            fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
     5578            f1 = _fdopen(fd1, "wb");
     5579            f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose);
     5580            PyFile_SetBufSize(f, 0);
     5581            /* We don't care about these pipes anymore, so close them. */
     5582            CloseHandle(hChildStdoutRdDup);
     5583            CloseHandle(hChildStderrRdDup);
     5584            break;
     5585        }
     5586        file_count = 1;
     5587        break;
     5588
     5589    case POPEN_2:
     5590    case POPEN_4:
     5591    {
     5592        char *m1, *m2;
     5593        PyObject *p1, *p2;
     5594
     5595        if (mode & _O_TEXT) {
     5596            m1 = "r";
     5597            m2 = "w";
     5598        } else {
     5599            m1 = "rb";
     5600            m2 = "wb";
     5601        }
     5602
     5603        fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
     5604        f1 = _fdopen(fd1, m2);
     5605        fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
     5606        f2 = _fdopen(fd2, m1);
     5607        p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
     5608        PyFile_SetBufSize(p1, 0);
     5609        p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
     5610        PyFile_SetBufSize(p2, 0);
     5611
     5612        if (n != 4)
     5613            CloseHandle(hChildStderrRdDup);
     5614
     5615        f = PyTuple_Pack(2,p1,p2);
     5616        Py_XDECREF(p1);
     5617        Py_XDECREF(p2);
     5618        file_count = 2;
     5619        break;
     5620    }
     5621
     5622    case POPEN_3:
     5623    {
     5624        char *m1, *m2;
     5625        PyObject *p1, *p2, *p3;
     5626
     5627        if (mode & _O_TEXT) {
     5628            m1 = "r";
     5629            m2 = "w";
     5630        } else {
     5631            m1 = "rb";
     5632            m2 = "wb";
     5633        }
     5634
     5635        fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
     5636        f1 = _fdopen(fd1, m2);
     5637        fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
     5638        f2 = _fdopen(fd2, m1);
     5639        fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode);
     5640        f3 = _fdopen(fd3, m1);
     5641        p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
     5642        p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
     5643        p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose);
     5644        PyFile_SetBufSize(p1, 0);
     5645        PyFile_SetBufSize(p2, 0);
     5646        PyFile_SetBufSize(p3, 0);
     5647        f = PyTuple_Pack(3,p1,p2,p3);
     5648        Py_XDECREF(p1);
     5649        Py_XDECREF(p2);
     5650        Py_XDECREF(p3);
     5651        file_count = 3;
     5652        break;
     5653    }
     5654    }
     5655
     5656    if (n == POPEN_4) {
     5657        if (!_PyPopenCreateProcess(cmdstring,
     5658                                    hChildStdinRd,
     5659                                    hChildStdoutWr,
     5660                                    hChildStdoutWr,
     5661                                    &hProcess))
     5662            return NULL;
     5663    }
     5664    else {
     5665        if (!_PyPopenCreateProcess(cmdstring,
     5666                                    hChildStdinRd,
     5667                                    hChildStdoutWr,
     5668                                    hChildStderrWr,
     5669                                    &hProcess))
     5670            return NULL;
     5671    }
     5672
     5673    /*
     5674      * Insert the files we've created into the process dictionary
     5675      * all referencing the list with the process handle and the
     5676      * initial number of files (see description below in _PyPclose).
     5677      * Since if _PyPclose later tried to wait on a process when all
     5678      * handles weren't closed, it could create a deadlock with the
     5679      * child, we spend some energy here to try to ensure that we
     5680      * either insert all file handles into the dictionary or none
     5681      * at all.  It's a little clumsy with the various popen modes
     5682      * and variable number of files involved.
     5683      */
     5684    if (!_PyPopenProcs) {
     5685        _PyPopenProcs = PyDict_New();
     5686    }
     5687
     5688    if (_PyPopenProcs) {
     5689        PyObject *procObj, *hProcessObj, *intObj, *fileObj[3];
     5690        int ins_rc[3];
     5691
     5692        fileObj[0] = fileObj[1] = fileObj[2] = NULL;
     5693        ins_rc[0]  = ins_rc[1]  = ins_rc[2]  = 0;
     5694
     5695        procObj = PyList_New(2);
     5696        hProcessObj = PyLong_FromVoidPtr(hProcess);
     5697        intObj = PyInt_FromLong(file_count);
     5698
     5699        if (procObj && hProcessObj && intObj) {
     5700            PyList_SetItem(procObj,0,hProcessObj);
     5701            PyList_SetItem(procObj,1,intObj);
     5702
     5703            fileObj[0] = PyLong_FromVoidPtr(f1);
     5704            if (fileObj[0]) {
     5705                ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
     5706                                           fileObj[0],
     5707                                           procObj);
     5708            }
     5709            if (file_count >= 2) {
     5710                fileObj[1] = PyLong_FromVoidPtr(f2);
     5711                if (fileObj[1]) {
     5712                    ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
     5713                                               fileObj[1],
     5714                                               procObj);
     5715                }
     5716            }
     5717            if (file_count >= 3) {
     5718                fileObj[2] = PyLong_FromVoidPtr(f3);
     5719                if (fileObj[2]) {
     5720                    ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
     5721                                               fileObj[2],
     5722                                               procObj);
     5723                }
     5724            }
     5725
     5726            if (ins_rc[0] < 0 || !fileObj[0] ||
     5727                 ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
     5728                 ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) {
     5729                /* Something failed - remove any dictionary
     5730                  * entries that did make it.
     5731                  */
     5732                if (!ins_rc[0] && fileObj[0]) {
     5733                    PyDict_DelItem(_PyPopenProcs,
     5734                                    fileObj[0]);
     5735                }
     5736                if (!ins_rc[1] && fileObj[1]) {
     5737                    PyDict_DelItem(_PyPopenProcs,
     5738                                    fileObj[1]);
     5739                }
     5740                if (!ins_rc[2] && fileObj[2]) {
     5741                    PyDict_DelItem(_PyPopenProcs,
     5742                                    fileObj[2]);
     5743                }
     5744            }
     5745        }
     5746
     5747        /*
     5748          * Clean up our localized references for the dictionary keys
     5749          * and value since PyDict_SetItem will Py_INCREF any copies
     5750          * that got placed in the dictionary.
     5751          */
     5752        Py_XDECREF(procObj);
     5753        Py_XDECREF(fileObj[0]);
     5754        Py_XDECREF(fileObj[1]);
     5755        Py_XDECREF(fileObj[2]);
     5756    }
     5757
     5758    /* Child is launched. Close the parents copy of those pipe
     5759      * handles that only the child should have open.  You need to
     5760      * make sure that no handles to the write end of the output pipe
     5761      * are maintained in this process or else the pipe will not close
     5762      * when the child process exits and the ReadFile will hang. */
     5763
     5764    if (!CloseHandle(hChildStdinRd))
     5765        return win32_error("CloseHandle", NULL);
     5766
     5767    if (!CloseHandle(hChildStdoutWr))
     5768        return win32_error("CloseHandle", NULL);
     5769
     5770    if ((n != 4) && (!CloseHandle(hChildStderrWr)))
     5771        return win32_error("CloseHandle", NULL);
     5772
     5773    return f;
    54235774}
    54245775
     
    54515802static int _PyPclose(FILE *file)
    54525803{
    5453         int result;
    5454         DWORD exit_code;
    5455         HANDLE hProcess;
    5456         PyObject *procObj, *hProcessObj, *intObj, *fileObj;
    5457         long file_count;
     5804    int result;
     5805    DWORD exit_code;
     5806    HANDLE hProcess;
     5807    PyObject *procObj, *hProcessObj, *intObj, *fileObj;
     5808    long file_count;
    54585809#ifdef WITH_THREAD
    5459         PyGILState_STATE state;
    5460 #endif
    5461 
    5462         /* Close the file handle first, to ensure it can't block the
    5463         * child from exiting if it's the last handle.
    5464         */
    5465         result = fclose(file);
     5810    PyGILState_STATE state;
     5811#endif
     5812
     5813    /* Close the file handle first, to ensure it can't block the
     5814    * child from exiting if it's the last handle.
     5815    */
     5816    result = fclose(file);
    54665817#ifdef WITH_THREAD
    5467         state = PyGILState_Ensure();
    5468 #endif
    5469         if (_PyPopenProcs) {
    5470                 if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&
    5471                     (procObj = PyDict_GetItem(_PyPopenProcs,
    5472                                               fileObj)) != NULL &&
    5473                     (hProcessObj = PyList_GetItem(procObj,0)) != NULL &&
    5474                     (intObj = PyList_GetItem(procObj,1)) != NULL) {
    5475 
    5476                         hProcess = PyLong_AsVoidPtr(hProcessObj);
    5477                         file_count = PyInt_AsLong(intObj);
    5478 
    5479                         if (file_count > 1) {
    5480                                 /* Still other files referencing process */
    5481                                 file_count--;
    5482                                 PyList_SetItem(procObj,1,
    5483                                                PyInt_FromLong(file_count));
    5484                         } else {
    5485                                 /* Last file for this process */
    5486                                 if (result != EOF &&
    5487                                     WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED &&
    5488                                     GetExitCodeProcess(hProcess, &exit_code)) {
    5489                                         /* Possible truncation here in 16-bit environments, but
    5490                                         * real exit codes are just the lower byte in any event.
    5491                                         */
    5492                                         result = exit_code;
    5493                                 } else {
    5494                                         /* Indicate failure - this will cause the file object
    5495                                         * to raise an I/O error and translate the last Win32
    5496                                         * error code from errno.  We do have a problem with
    5497                                         * last errors that overlap the normal errno table,
    5498                                         * but that's a consistent problem with the file object.
    5499                                         */
    5500                                         if (result != EOF) {
    5501                                                 /* If the error wasn't from the fclose(), then
    5502                                                 * set errno for the file object error handling.
    5503                                                 */
    5504                                                 errno = GetLastError();
    5505                                         }
    5506                                         result = -1;
    5507                                 }
    5508 
    5509                                 /* Free up the native handle at this point */
    5510                                 CloseHandle(hProcess);
    5511                         }
    5512 
    5513                         /* Remove this file pointer from dictionary */
    5514                         PyDict_DelItem(_PyPopenProcs, fileObj);
    5515 
    5516                         if (PyDict_Size(_PyPopenProcs) == 0) {
    5517                                 Py_DECREF(_PyPopenProcs);
    5518                                 _PyPopenProcs = NULL;
    5519                         }
    5520 
    5521                 } /* if object retrieval ok */
    5522 
    5523                 Py_XDECREF(fileObj);
    5524         } /* if _PyPopenProcs */
     5818    state = PyGILState_Ensure();
     5819#endif
     5820    if (_PyPopenProcs) {
     5821        if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&
     5822            (procObj = PyDict_GetItem(_PyPopenProcs,
     5823                                      fileObj)) != NULL &&
     5824            (hProcessObj = PyList_GetItem(procObj,0)) != NULL &&
     5825            (intObj = PyList_GetItem(procObj,1)) != NULL) {
     5826
     5827            hProcess = PyLong_AsVoidPtr(hProcessObj);
     5828            file_count = PyInt_AsLong(intObj);
     5829
     5830            if (file_count > 1) {
     5831                /* Still other files referencing process */
     5832                file_count--;
     5833                PyList_SetItem(procObj,1,
     5834                               PyInt_FromLong(file_count));
     5835            } else {
     5836                /* Last file for this process */
     5837                if (result != EOF &&
     5838                    WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED &&
     5839                    GetExitCodeProcess(hProcess, &exit_code)) {
     5840                    /* Possible truncation here in 16-bit environments, but
     5841                    * real exit codes are just the lower byte in any event.
     5842                    */
     5843                    result = exit_code;
     5844                } else {
     5845                    /* Indicate failure - this will cause the file object
     5846                    * to raise an I/O error and translate the last Win32
     5847                    * error code from errno.  We do have a problem with
     5848                    * last errors that overlap the normal errno table,
     5849                    * but that's a consistent problem with the file object.
     5850                    */
     5851                    if (result != EOF) {
     5852                        /* If the error wasn't from the fclose(), then
     5853                        * set errno for the file object error handling.
     5854                        */
     5855                        errno = GetLastError();
     5856                    }
     5857                    result = -1;
     5858                }
     5859
     5860                /* Free up the native handle at this point */
     5861                CloseHandle(hProcess);
     5862            }
     5863
     5864            /* Remove this file pointer from dictionary */
     5865            PyDict_DelItem(_PyPopenProcs, fileObj);
     5866
     5867            if (PyDict_Size(_PyPopenProcs) == 0) {
     5868                Py_DECREF(_PyPopenProcs);
     5869                _PyPopenProcs = NULL;
     5870            }
     5871
     5872        } /* if object retrieval ok */
     5873
     5874        Py_XDECREF(fileObj);
     5875    } /* if _PyPopenProcs */
    55255876
    55265877#ifdef WITH_THREAD
    5527         PyGILState_Release(state);
    5528 #endif
    5529         return result;
     5878    PyGILState_Release(state);
     5879#endif
     5880    return result;
    55305881}
    55315882
     
    55345885posix_popen(PyObject *self, PyObject *args)
    55355886{
    5536         char *name;
    5537         char *mode = "r";
    5538         int bufsize = -1;
    5539         FILE *fp;
    5540         PyObject *f;
    5541         if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
    5542                 return NULL;
    5543         /* Strip mode of binary or text modifiers */
    5544         if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0)
    5545                 mode = "r";
    5546         else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0)
    5547                 mode = "w";
    5548         Py_BEGIN_ALLOW_THREADS
    5549         fp = popen(name, mode);
    5550         Py_END_ALLOW_THREADS
    5551         if (fp == NULL)
    5552                 return posix_error();
    5553         f = PyFile_FromFile(fp, name, mode, pclose);
    5554         if (f != NULL)
    5555                 PyFile_SetBufSize(f, bufsize);
    5556         return f;
     5887    char *name;
     5888    char *mode = "r";
     5889    int bufsize = -1;
     5890    FILE *fp;
     5891    PyObject *f;
     5892    if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
     5893        return NULL;
     5894    /* Strip mode of binary or text modifiers */
     5895    if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0)
     5896        mode = "r";
     5897    else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0)
     5898        mode = "w";
     5899    Py_BEGIN_ALLOW_THREADS
     5900    fp = popen(name, mode);
     5901    Py_END_ALLOW_THREADS
     5902    if (fp == NULL)
     5903        return posix_error();
     5904    f = PyFile_FromFile(fp, name, mode, pclose);
     5905    if (f != NULL)
     5906        PyFile_SetBufSize(f, bufsize);
     5907    return f;
    55575908}
    55585909
     
    55695920posix_setuid(PyObject *self, PyObject *args)
    55705921{
    5571         long uid_arg;
    5572         uid_t uid;
    5573         if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg))
    5574                 return NULL;
    5575         uid = uid_arg;
    5576         if (uid != uid_arg) {
    5577                 PyErr_SetString(PyExc_OverflowError, "user id too big");
    5578                 return NULL;
    5579         }
    5580         if (setuid(uid) < 0)
    5581                 return posix_error();
    5582         Py_INCREF(Py_None);
    5583         return Py_None;
     5922    uid_t uid;
     5923    if (!PyArg_ParseTuple(args, "O&:setuid", _Py_Uid_Converter, &uid))
     5924        return NULL;
     5925    if (setuid(uid) < 0)
     5926        return posix_error();
     5927    Py_INCREF(Py_None);
     5928    return Py_None;
    55845929}
    55855930#endif /* HAVE_SETUID */
     
    55945939posix_seteuid (PyObject *self, PyObject *args)
    55955940{
    5596         long euid_arg;
    5597         uid_t euid;
    5598         if (!PyArg_ParseTuple(args, "l", &euid_arg))
    5599                 return NULL;
    5600         euid = euid_arg;
    5601         if (euid != euid_arg) {
    5602                 PyErr_SetString(PyExc_OverflowError, "user id too big");
    5603                 return NULL;
    5604         }
    5605         if (seteuid(euid) < 0) {
    5606                 return posix_error();
    5607         } else {
    5608                 Py_INCREF(Py_None);
    5609                 return Py_None;
    5610         }
     5941    uid_t euid;
     5942    if (!PyArg_ParseTuple(args, "O&:seteuid", _Py_Uid_Converter, &euid))
     5943        return NULL;
     5944    if (seteuid(euid) < 0) {
     5945        return posix_error();
     5946    } else {
     5947        Py_INCREF(Py_None);
     5948        return Py_None;
     5949    }
    56115950}
    56125951#endif /* HAVE_SETEUID */
     
    56205959posix_setegid (PyObject *self, PyObject *args)
    56215960{
    5622         long egid_arg;
    5623         gid_t egid;
    5624         if (!PyArg_ParseTuple(args, "l", &egid_arg))
    5625                 return NULL;
    5626         egid = egid_arg;
    5627         if (egid != egid_arg) {
    5628                 PyErr_SetString(PyExc_OverflowError, "group id too big");
    5629                 return NULL;
    5630         }
    5631         if (setegid(egid) < 0) {
    5632                 return posix_error();
    5633         } else {
    5634                 Py_INCREF(Py_None);
    5635                 return Py_None;
    5636         }
     5961    gid_t egid;
     5962    if (!PyArg_ParseTuple(args, "O&:setegid", _Py_Gid_Converter, &egid))
     5963        return NULL;
     5964    if (setegid(egid) < 0) {
     5965        return posix_error();
     5966    } else {
     5967        Py_INCREF(Py_None);
     5968        return Py_None;
     5969    }
    56375970}
    56385971#endif /* HAVE_SETEGID */
     
    56465979posix_setreuid (PyObject *self, PyObject *args)
    56475980{
    5648         long ruid_arg, euid_arg;
    5649         uid_t ruid, euid;
    5650         if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg))
    5651                 return NULL;
    5652         if (ruid_arg == -1)
    5653                 ruid = (uid_t)-1;  /* let the compiler choose how -1 fits */
    5654         else
    5655                 ruid = ruid_arg;  /* otherwise, assign from our long */
    5656         if (euid_arg == -1)
    5657                 euid = (uid_t)-1;
    5658         else
    5659                 euid = euid_arg;
    5660         if ((euid_arg != -1 && euid != euid_arg) ||
    5661             (ruid_arg != -1 && ruid != ruid_arg)) {
    5662                 PyErr_SetString(PyExc_OverflowError, "user id too big");
    5663                 return NULL;
    5664         }
    5665         if (setreuid(ruid, euid) < 0) {
    5666                 return posix_error();
    5667         } else {
    5668                 Py_INCREF(Py_None);
    5669                 return Py_None;
    5670         }
     5981    uid_t ruid, euid;
     5982    if (!PyArg_ParseTuple(args, "O&O&:setreuid",
     5983                          _Py_Uid_Converter, &ruid,
     5984                          _Py_Uid_Converter, &euid))
     5985        return NULL;
     5986    if (setreuid(ruid, euid) < 0) {
     5987        return posix_error();
     5988    } else {
     5989        Py_INCREF(Py_None);
     5990        return Py_None;
     5991    }
    56715992}
    56725993#endif /* HAVE_SETREUID */
     
    56806001posix_setregid (PyObject *self, PyObject *args)
    56816002{
    5682         long rgid_arg, egid_arg;
    5683         gid_t rgid, egid;
    5684         if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg))
    5685                 return NULL;
    5686         if (rgid_arg == -1)
    5687                 rgid = (gid_t)-1;  /* let the compiler choose how -1 fits */
    5688         else
    5689                 rgid = rgid_arg;  /* otherwise, assign from our long */
    5690         if (egid_arg == -1)
    5691                 egid = (gid_t)-1;
    5692         else
    5693                 egid = egid_arg;
    5694         if ((egid_arg != -1 && egid != egid_arg) ||
    5695             (rgid_arg != -1 && rgid != rgid_arg)) {
    5696                 PyErr_SetString(PyExc_OverflowError, "group id too big");
    5697                 return NULL;
    5698         }
    5699         if (setregid(rgid, egid) < 0) {
    5700                 return posix_error();
    5701         } else {
    5702                 Py_INCREF(Py_None);
    5703                 return Py_None;
    5704         }
     6003    gid_t rgid, egid;
     6004    if (!PyArg_ParseTuple(args, "O&O&:setregid",
     6005                          _Py_Gid_Converter, &rgid,
     6006                          _Py_Gid_Converter, &egid))
     6007        return NULL;
     6008    if (setregid(rgid, egid) < 0) {
     6009        return posix_error();
     6010    } else {
     6011        Py_INCREF(Py_None);
     6012        return Py_None;
     6013    }
    57056014}
    57066015#endif /* HAVE_SETREGID */
     
    57146023posix_setgid(PyObject *self, PyObject *args)
    57156024{
    5716         long gid_arg;
    5717         gid_t gid;
    5718         if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg))
    5719                 return NULL;
    5720         gid = gid_arg;
    5721         if (gid != gid_arg) {
    5722                 PyErr_SetString(PyExc_OverflowError, "group id too big");
    5723                 return NULL;
    5724         }
    5725         if (setgid(gid) < 0)
    5726                 return posix_error();
    5727         Py_INCREF(Py_None);
    5728         return Py_None;
     6025    gid_t gid;
     6026    if (!PyArg_ParseTuple(args, "O&:setgid", _Py_Gid_Converter, &gid))
     6027        return NULL;
     6028    if (setgid(gid) < 0)
     6029        return posix_error();
     6030    Py_INCREF(Py_None);
     6031    return Py_None;
    57296032}
    57306033#endif /* HAVE_SETGID */
     
    57386041posix_setgroups(PyObject *self, PyObject *groups)
    57396042{
    5740         int i, len;
    5741         gid_t grouplist[MAX_GROUPS];
    5742 
    5743         if (!PySequence_Check(groups)) {
    5744                 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
    5745                 return NULL;
    5746         }
    5747         len = PySequence_Size(groups);
    5748         if (len > MAX_GROUPS) {
    5749                 PyErr_SetString(PyExc_ValueError, "too many groups");
    5750                 return NULL;
    5751         }
    5752         for(i = 0; i < len; i++) {
    5753                 PyObject *elem;
    5754                 elem = PySequence_GetItem(groups, i);
    5755                 if (!elem)
    5756                         return NULL;
    5757                 if (!PyInt_Check(elem)) {
    5758                         if (!PyLong_Check(elem)) {
    5759                                 PyErr_SetString(PyExc_TypeError,
    5760                                                 "groups must be integers");
    5761                                 Py_DECREF(elem);
    5762                                 return NULL;
    5763                         } else {
    5764                                 unsigned long x = PyLong_AsUnsignedLong(elem);
    5765                                 if (PyErr_Occurred()) {
    5766                                         PyErr_SetString(PyExc_TypeError,
    5767                                                         "group id too big");
    5768                                         Py_DECREF(elem);
    5769                                         return NULL;
    5770                                 }
    5771                                 grouplist[i] = x;
    5772                                 /* read back to see if it fits in gid_t */
    5773                                 if (grouplist[i] != x) {
    5774                                         PyErr_SetString(PyExc_TypeError,
    5775                                                         "group id too big");
    5776                                         Py_DECREF(elem);
    5777                                         return NULL;
    5778                                 }
    5779                         }
    5780                 } else {
    5781                         long x  = PyInt_AsLong(elem);
    5782                         grouplist[i] = x;
    5783                         if (grouplist[i] != x) {
    5784                                 PyErr_SetString(PyExc_TypeError,
    5785                                                 "group id too big");
    5786                                 Py_DECREF(elem);
    5787                                 return NULL;
    5788                         }
    5789                 }
    5790                 Py_DECREF(elem);
    5791         }
    5792 
    5793         if (setgroups(len, grouplist) < 0)
    5794                 return posix_error();
    5795         Py_INCREF(Py_None);
    5796         return Py_None;
     6043    int i, len;
     6044    gid_t grouplist[MAX_GROUPS];
     6045
     6046    if (!PySequence_Check(groups)) {
     6047        PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
     6048        return NULL;
     6049    }
     6050    len = PySequence_Size(groups);
     6051    if (len > MAX_GROUPS) {
     6052        PyErr_SetString(PyExc_ValueError, "too many groups");
     6053        return NULL;
     6054    }
     6055    for(i = 0; i < len; i++) {
     6056        PyObject *elem;
     6057        elem = PySequence_GetItem(groups, i);
     6058        if (!elem)
     6059            return NULL;
     6060        if (!PyInt_Check(elem) && !PyLong_Check(elem)) {
     6061            PyErr_SetString(PyExc_TypeError,
     6062                            "groups must be integers");
     6063            Py_DECREF(elem);
     6064            return NULL;
     6065        } else {
     6066            if (!_Py_Gid_Converter(elem, &grouplist[i])) {
     6067                Py_DECREF(elem);
     6068                return NULL;
     6069            }
     6070        }
     6071        Py_DECREF(elem);
     6072    }
     6073
     6074    if (setgroups(len, grouplist) < 0)
     6075        return posix_error();
     6076    Py_INCREF(Py_None);
     6077    return Py_None;
    57976078}
    57986079#endif /* HAVE_SETGROUPS */
     
    58026083wait_helper(pid_t pid, int status, struct rusage *ru)
    58036084{
    5804         PyObject *result;
    5805         static PyObject *struct_rusage;
    5806 
    5807         if (pid == -1)
    5808                 return posix_error();
    5809 
    5810         if (struct_rusage == NULL) {
    5811                 PyObject *m = PyImport_ImportModuleNoBlock("resource");
    5812                 if (m == NULL)
    5813                         return NULL;
    5814                 struct_rusage = PyObject_GetAttrString(m, "struct_rusage");
    5815                 Py_DECREF(m);
    5816                 if (struct_rusage == NULL)
    5817                         return NULL;
    5818         }
    5819 
    5820         /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
    5821         result = PyStructSequence_New((PyTypeObject*) struct_rusage);
    5822         if (!result)
    5823                 return NULL;
     6085    PyObject *result;
     6086    static PyObject *struct_rusage;
     6087
     6088    if (pid == -1)
     6089        return posix_error();
     6090
     6091    if (struct_rusage == NULL) {
     6092        PyObject *m = PyImport_ImportModuleNoBlock("resource");
     6093        if (m == NULL)
     6094            return NULL;
     6095        struct_rusage = PyObject_GetAttrString(m, "struct_rusage");
     6096        Py_DECREF(m);
     6097        if (struct_rusage == NULL)
     6098            return NULL;
     6099    }
     6100
     6101    /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
     6102    result = PyStructSequence_New((PyTypeObject*) struct_rusage);
     6103    if (!result)
     6104        return NULL;
    58246105
    58256106#ifndef doubletime
     
    58276108#endif
    58286109
    5829         PyStructSequence_SET_ITEM(result, 0,
    5830                         PyFloat_FromDouble(doubletime(ru->ru_utime)));
    5831         PyStructSequence_SET_ITEM(result, 1,
    5832                         PyFloat_FromDouble(doubletime(ru->ru_stime)));
     6110    PyStructSequence_SET_ITEM(result, 0,
     6111                              PyFloat_FromDouble(doubletime(ru->ru_utime)));
     6112    PyStructSequence_SET_ITEM(result, 1,
     6113                              PyFloat_FromDouble(doubletime(ru->ru_stime)));
    58336114#define SET_INT(result, index, value)\
    5834                 PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value))
    5835         SET_INT(result, 2, ru->ru_maxrss);
    5836         SET_INT(result, 3, ru->ru_ixrss);
    5837         SET_INT(result, 4, ru->ru_idrss);
    5838         SET_INT(result, 5, ru->ru_isrss);
    5839         SET_INT(result, 6, ru->ru_minflt);
    5840         SET_INT(result, 7, ru->ru_majflt);
    5841         SET_INT(result, 8, ru->ru_nswap);
    5842         SET_INT(result, 9, ru->ru_inblock);
    5843         SET_INT(result, 10, ru->ru_oublock);
    5844         SET_INT(result, 11, ru->ru_msgsnd);
    5845         SET_INT(result, 12, ru->ru_msgrcv);
    5846         SET_INT(result, 13, ru->ru_nsignals);
    5847         SET_INT(result, 14, ru->ru_nvcsw);
    5848         SET_INT(result, 15, ru->ru_nivcsw);
     6115        PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value))
     6116    SET_INT(result, 2, ru->ru_maxrss);
     6117    SET_INT(result, 3, ru->ru_ixrss);
     6118    SET_INT(result, 4, ru->ru_idrss);
     6119    SET_INT(result, 5, ru->ru_isrss);
     6120    SET_INT(result, 6, ru->ru_minflt);
     6121    SET_INT(result, 7, ru->ru_majflt);
     6122    SET_INT(result, 8, ru->ru_nswap);
     6123    SET_INT(result, 9, ru->ru_inblock);
     6124    SET_INT(result, 10, ru->ru_oublock);
     6125    SET_INT(result, 11, ru->ru_msgsnd);
     6126    SET_INT(result, 12, ru->ru_msgrcv);
     6127    SET_INT(result, 13, ru->ru_nsignals);
     6128    SET_INT(result, 14, ru->ru_nvcsw);
     6129    SET_INT(result, 15, ru->ru_nivcsw);
    58496130#undef SET_INT
    58506131
    5851         if (PyErr_Occurred()) {
    5852                 Py_DECREF(result);
    5853                 return NULL;
    5854         }
    5855 
    5856         return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
     6132    if (PyErr_Occurred()) {
     6133        Py_DECREF(result);
     6134        return NULL;
     6135    }
     6136
     6137    return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
    58576138}
    58586139#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
     
    58666147posix_wait3(PyObject *self, PyObject *args)
    58676148{
    5868         pid_t pid;
    5869         int options;
    5870         struct rusage ru;
    5871         WAIT_TYPE status;
    5872         WAIT_STATUS_INT(status) = 0;
    5873 
    5874         if (!PyArg_ParseTuple(args, "i:wait3", &options))
    5875                 return NULL;
    5876 
    5877         Py_BEGIN_ALLOW_THREADS
    5878         pid = wait3(&status, options, &ru);
    5879         Py_END_ALLOW_THREADS
    5880 
    5881         return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
     6149    pid_t pid;
     6150    int options;
     6151    struct rusage ru;
     6152    WAIT_TYPE status;
     6153    WAIT_STATUS_INT(status) = 0;
     6154
     6155    if (!PyArg_ParseTuple(args, "i:wait3", &options))
     6156        return NULL;
     6157
     6158    Py_BEGIN_ALLOW_THREADS
     6159    pid = wait3(&status, options, &ru);
     6160    Py_END_ALLOW_THREADS
     6161
     6162    return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
    58826163}
    58836164#endif /* HAVE_WAIT3 */
     
    58916172posix_wait4(PyObject *self, PyObject *args)
    58926173{
    5893         pid_t pid;
    5894         int options;
    5895         struct rusage ru;
    5896         WAIT_TYPE status;
    5897         WAIT_STATUS_INT(status) = 0;
    5898 
    5899         if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options))
    5900                 return NULL;
    5901 
    5902         Py_BEGIN_ALLOW_THREADS
    5903         pid = wait4(pid, &status, options, &ru);
    5904         Py_END_ALLOW_THREADS
    5905 
    5906         return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
     6174    pid_t pid;
     6175    int options;
     6176    struct rusage ru;
     6177    WAIT_TYPE status;
     6178    WAIT_STATUS_INT(status) = 0;
     6179
     6180    if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options))
     6181        return NULL;
     6182
     6183    Py_BEGIN_ALLOW_THREADS
     6184    pid = wait4(pid, &status, options, &ru);
     6185    Py_END_ALLOW_THREADS
     6186
     6187    return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
    59076188}
    59086189#endif /* HAVE_WAIT4 */
     
    59166197posix_waitpid(PyObject *self, PyObject *args)
    59176198{
    5918         pid_t pid;
    5919         int options;
    5920         WAIT_TYPE status;
    5921         WAIT_STATUS_INT(status) = 0;
    5922 
    5923         if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))
    5924                 return NULL;
    5925         Py_BEGIN_ALLOW_THREADS
    5926         pid = waitpid(pid, &status, options);
    5927         Py_END_ALLOW_THREADS
    5928         if (pid == -1)
    5929                 return posix_error();
    5930 
    5931         return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
     6199    pid_t pid;
     6200    int options;
     6201    WAIT_TYPE status;
     6202    WAIT_STATUS_INT(status) = 0;
     6203
     6204    if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))
     6205        return NULL;
     6206    Py_BEGIN_ALLOW_THREADS
     6207    pid = waitpid(pid, &status, options);
     6208    Py_END_ALLOW_THREADS
     6209    if (pid == -1)
     6210        return posix_error();
     6211
     6212    return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
    59326213}
    59336214
     
    59426223posix_waitpid(PyObject *self, PyObject *args)
    59436224{
    5944         Py_intptr_t pid;
    5945         int status, options;
    5946 
    5947         if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))
    5948                 return NULL;
    5949         Py_BEGIN_ALLOW_THREADS
    5950         pid = _cwait(&status, pid, options);
    5951         Py_END_ALLOW_THREADS
    5952         if (pid == -1)
    5953                 return posix_error();
    5954 
    5955         /* shift the status left a byte so this is more like the POSIX waitpid */
    5956         return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8);
     6225    Py_intptr_t pid;
     6226    int status, options;
     6227
     6228    if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))
     6229        return NULL;
     6230    Py_BEGIN_ALLOW_THREADS
     6231    pid = _cwait(&status, pid, options);
     6232    Py_END_ALLOW_THREADS
     6233    if (pid == -1)
     6234        return posix_error();
     6235
     6236    /* shift the status left a byte so this is more like the POSIX waitpid */
     6237    return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8);
    59576238}
    59586239#endif /* HAVE_WAITPID || HAVE_CWAIT */
     
    59666247posix_wait(PyObject *self, PyObject *noargs)
    59676248{
    5968         pid_t pid;
    5969         WAIT_TYPE status;
    5970         WAIT_STATUS_INT(status) = 0;
    5971 
    5972         Py_BEGIN_ALLOW_THREADS
    5973         pid = wait(&status);
    5974         Py_END_ALLOW_THREADS
    5975         if (pid == -1)
    5976                 return posix_error();
    5977 
    5978         return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
     6249    pid_t pid;
     6250    WAIT_TYPE status;
     6251    WAIT_STATUS_INT(status) = 0;
     6252
     6253    Py_BEGIN_ALLOW_THREADS
     6254    pid = wait(&status);
     6255    Py_END_ALLOW_THREADS
     6256    if (pid == -1)
     6257        return posix_error();
     6258
     6259    return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
    59796260}
    59806261#endif
     
    59896270{
    59906271#ifdef HAVE_LSTAT
    5991         return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL);
     6272    return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL);
    59926273#else /* !HAVE_LSTAT */
    59936274#ifdef MS_WINDOWS
    5994         return posix_do_stat(self, args, "et:lstat", STAT, "U:lstat", win32_wstat);
     6275    return posix_do_stat(self, args, "et:lstat", STAT, "U:lstat", win32_wstat);
    59956276#else
    5996         return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL);
     6277    return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL);
    59976278#endif
    59986279#endif /* !HAVE_LSTAT */
     
    60086289posix_readlink(PyObject *self, PyObject *args)
    60096290{
    6010         PyObject* v;
    6011         char buf[MAXPATHLEN];
    6012         char *path;
    6013         int n;
     6291    PyObject* v;
     6292    char buf[MAXPATHLEN];
     6293    char *path;
     6294    int n;
    60146295#ifdef Py_USING_UNICODE
    6015         int arg_is_unicode = 0;
    6016 #endif
    6017 
    6018         if (!PyArg_ParseTuple(args, "et:readlink",
    6019                                 Py_FileSystemDefaultEncoding, &path))
    6020                 return NULL;
     6296    int arg_is_unicode = 0;
     6297#endif
     6298
     6299    if (!PyArg_ParseTuple(args, "et:readlink",
     6300                          Py_FileSystemDefaultEncoding, &path))
     6301        return NULL;
    60216302#ifdef Py_USING_UNICODE
    6022         v = PySequence_GetItem(args, 0);
    6023         if (v == NULL) {
    6024                 PyMem_Free(path);
    6025                 return NULL;
    6026         }
    6027 
    6028         if (PyUnicode_Check(v)) {
    6029                 arg_is_unicode = 1;
    6030         }
    6031         Py_DECREF(v);
    6032 #endif
    6033 
    6034         Py_BEGIN_ALLOW_THREADS
    6035         n = readlink(path, buf, (int) sizeof buf);
    6036         Py_END_ALLOW_THREADS
    6037         if (n < 0)
    6038                 return posix_error_with_allocated_filename(path);
    6039 
    6040         PyMem_Free(path);
    6041         v = PyString_FromStringAndSize(buf, n);
     6303    v = PySequence_GetItem(args, 0);
     6304    if (v == NULL) {
     6305        PyMem_Free(path);
     6306        return NULL;
     6307    }
     6308
     6309    if (PyUnicode_Check(v)) {
     6310        arg_is_unicode = 1;
     6311    }
     6312    Py_DECREF(v);
     6313#endif
     6314
     6315    Py_BEGIN_ALLOW_THREADS
     6316    n = readlink(path, buf, (int) sizeof buf);
     6317    Py_END_ALLOW_THREADS
     6318    if (n < 0)
     6319        return posix_error_with_allocated_filename(path);
     6320
     6321    PyMem_Free(path);
     6322    v = PyString_FromStringAndSize(buf, n);
    60426323#ifdef Py_USING_UNICODE
    6043         if (arg_is_unicode) {
    6044                 PyObject *w;
    6045 
    6046                 w = PyUnicode_FromEncodedObject(v,
    6047                                 Py_FileSystemDefaultEncoding,
    6048                                 "strict");
    6049                 if (w != NULL) {
    6050                         Py_DECREF(v);
    6051                         v = w;
    6052                 }
    6053                 else {
    6054                         /* fall back to the original byte string, as
    6055                            discussed in patch #683592 */
    6056                         PyErr_Clear();
    6057                 }
    6058         }
    6059 #endif
    6060         return v;
     6324    if (arg_is_unicode) {
     6325        PyObject *w;
     6326
     6327        w = PyUnicode_FromEncodedObject(v,
     6328                                        Py_FileSystemDefaultEncoding,
     6329                                        "strict");
     6330        if (w != NULL) {
     6331            Py_DECREF(v);
     6332            v = w;
     6333        }
     6334        else {
     6335            /* fall back to the original byte string, as
     6336               discussed in patch #683592 */
     6337            PyErr_Clear();
     6338        }
     6339    }
     6340#endif
     6341    return v;
    60616342}
    60626343#endif /* HAVE_READLINK */
     
    60716352posix_symlink(PyObject *self, PyObject *args)
    60726353{
    6073         return posix_2str(args, "etet:symlink", symlink);
     6354    return posix_2str(args, "etet:symlink", symlink);
    60746355}
    60756356#endif /* HAVE_SYMLINK */
     
    60946375{
    60956376    /* Currently Only Uptime is Provided -- Others Later */
    6096         return Py_BuildValue("ddddd",
    6097                              (double)0 /* t.tms_utime / HZ */,
    6098                              (double)0 /* t.tms_stime / HZ */,
    6099                              (double)0 /* t.tms_cutime / HZ */,
    6100                              (double)0 /* t.tms_cstime / HZ */,
    6101                              (double)system_uptime() / 1000);
     6377    return Py_BuildValue("ddddd",
     6378                         (double)0 /* t.tms_utime / HZ */,
     6379                         (double)0 /* t.tms_stime / HZ */,
     6380                         (double)0 /* t.tms_cutime / HZ */,
     6381                         (double)0 /* t.tms_cstime / HZ */,
     6382                         (double)system_uptime() / 1000);
    61026383}
    61036384#else /* not OS2 */
     
    61076388posix_times(PyObject *self, PyObject *noargs)
    61086389{
    6109         struct tms t;
    6110         clock_t c;
    6111         errno = 0;
    6112         c = times(&t);
    6113         if (c == (clock_t) -1)
    6114                 return posix_error();
    6115         return Py_BuildValue("ddddd",
    6116                              (double)t.tms_utime / ticks_per_second,
    6117                              (double)t.tms_stime / ticks_per_second,
    6118                              (double)t.tms_cutime / ticks_per_second,
    6119                              (double)t.tms_cstime / ticks_per_second,
    6120                              (double)c / ticks_per_second);
     6390    struct tms t;
     6391    clock_t c;
     6392    errno = 0;
     6393    c = times(&t);
     6394    if (c == (clock_t) -1)
     6395        return posix_error();
     6396    return Py_BuildValue("ddddd",
     6397                         (double)t.tms_utime / ticks_per_second,
     6398                         (double)t.tms_stime / ticks_per_second,
     6399                         (double)t.tms_cutime / ticks_per_second,
     6400                         (double)t.tms_cstime / ticks_per_second,
     6401                         (double)c / ticks_per_second);
    61216402}
    61226403#endif /* not OS2 */
     
    61256406
    61266407#ifdef MS_WINDOWS
    6127 #define HAVE_TIMES      /* so the method table will pick it up */
     6408#define HAVE_TIMES      /* so the method table will pick it up */
    61286409static PyObject *
    61296410posix_times(PyObject *self, PyObject *noargs)
    61306411{
    6131         FILETIME create, exit, kernel, user;
    6132         HANDLE hProc;
    6133         hProc = GetCurrentProcess();
    6134         GetProcessTimes(hProc, &create, &exit, &kernel, &user);
    6135         /* The fields of a FILETIME structure are the hi and lo part
    6136            of a 64-bit value expressed in 100 nanosecond units.
    6137            1e7 is one second in such units; 1e-7 the inverse.
    6138            429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
    6139         */
    6140         return Py_BuildValue(
    6141                 "ddddd",
    6142                 (double)(user.dwHighDateTime*429.4967296 +
    6143                          user.dwLowDateTime*1e-7),
    6144                 (double)(kernel.dwHighDateTime*429.4967296 +
    6145                          kernel.dwLowDateTime*1e-7),
    6146                 (double)0,
    6147                 (double)0,
    6148                 (double)0);
     6412    FILETIME create, exit, kernel, user;
     6413    HANDLE hProc;
     6414    hProc = GetCurrentProcess();
     6415    GetProcessTimes(hProc, &create, &exit, &kernel, &user);
     6416    /* The fields of a FILETIME structure are the hi and lo part
     6417       of a 64-bit value expressed in 100 nanosecond units.
     6418       1e7 is one second in such units; 1e-7 the inverse.
     6419       429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
     6420    */
     6421    return Py_BuildValue(
     6422        "ddddd",
     6423        (double)(user.dwHighDateTime*429.4967296 +
     6424                 user.dwLowDateTime*1e-7),
     6425        (double)(kernel.dwHighDateTime*429.4967296 +
     6426                 kernel.dwLowDateTime*1e-7),
     6427        (double)0,
     6428        (double)0,
     6429        (double)0);
    61496430}
    61506431#endif /* MS_WINDOWS */
     
    61656446posix_getsid(PyObject *self, PyObject *args)
    61666447{
    6167         pid_t pid;
    6168         int sid;
    6169         if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid))
    6170                 return NULL;
    6171         sid = getsid(pid);
    6172         if (sid < 0)
    6173                 return posix_error();
    6174         return PyInt_FromLong((long)sid);
     6448    pid_t pid;
     6449    int sid;
     6450    if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid))
     6451        return NULL;
     6452    sid = getsid(pid);
     6453    if (sid < 0)
     6454        return posix_error();
     6455    return PyInt_FromLong((long)sid);
    61756456}
    61766457#endif /* HAVE_GETSID */
     
    61856466posix_setsid(PyObject *self, PyObject *noargs)
    61866467{
    6187         if (setsid() < 0)
    6188                 return posix_error();
    6189         Py_INCREF(Py_None);
    6190         return Py_None;
     6468    if (setsid() < 0)
     6469        return posix_error();
     6470    Py_INCREF(Py_None);
     6471    return Py_None;
    61916472}
    61926473#endif /* HAVE_SETSID */
     
    62006481posix_setpgid(PyObject *self, PyObject *args)
    62016482{
    6202         pid_t pid;
    6203         int pgrp;
    6204         if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp))
    6205                 return NULL;
    6206         if (setpgid(pid, pgrp) < 0)
    6207                 return posix_error();
    6208         Py_INCREF(Py_None);
    6209         return Py_None;
     6483    pid_t pid;
     6484    int pgrp;
     6485    if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp))
     6486        return NULL;
     6487    if (setpgid(pid, pgrp) < 0)
     6488        return posix_error();
     6489    Py_INCREF(Py_None);
     6490    return Py_None;
    62106491}
    62116492#endif /* HAVE_SETPGID */
     
    62206501posix_tcgetpgrp(PyObject *self, PyObject *args)
    62216502{
    6222         int fd;
    6223         pid_t pgid;
    6224         if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd))
    6225                 return NULL;
    6226         pgid = tcgetpgrp(fd);
    6227         if (pgid < 0)
    6228                 return posix_error();
    6229         return PyLong_FromPid(pgid);
     6503    int fd;
     6504    pid_t pgid;
     6505    if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd))
     6506        return NULL;
     6507    pgid = tcgetpgrp(fd);
     6508    if (pgid < 0)
     6509        return posix_error();
     6510    return PyLong_FromPid(pgid);
    62306511}
    62316512#endif /* HAVE_TCGETPGRP */
     
    62406521posix_tcsetpgrp(PyObject *self, PyObject *args)
    62416522{
    6242         int fd;
    6243         pid_t pgid;
    6244         if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid))
    6245                 return NULL;
    6246         if (tcsetpgrp(fd, pgid) < 0)
    6247                 return posix_error();
    6248         Py_INCREF(Py_None);
    6249         return Py_None;
     6523    int fd;
     6524    pid_t pgid;
     6525    if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid))
     6526        return NULL;
     6527    if (tcsetpgrp(fd, pgid) < 0)
     6528        return posix_error();
     6529    Py_INCREF(Py_None);
     6530    return Py_None;
    62506531}
    62516532#endif /* HAVE_TCSETPGRP */
     
    62606541posix_open(PyObject *self, PyObject *args)
    62616542{
    6262         char *file = NULL;
    6263         int flag;
    6264         int mode = 0777;
    6265         int fd;
     6543    char *file = NULL;
     6544    int flag;
     6545    int mode = 0777;
     6546    int fd;
    62666547
    62676548#ifdef MS_WINDOWS
    6268         if (unicode_file_names()) {
    6269                 PyUnicodeObject *po;
    6270                 if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) {
    6271                         Py_BEGIN_ALLOW_THREADS
    6272                         /* PyUnicode_AS_UNICODE OK without thread
    6273                            lock as it is a simple dereference. */
    6274                         fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode);
    6275                         Py_END_ALLOW_THREADS
    6276                         if (fd < 0)
    6277                                 return posix_error();
    6278                         return PyInt_FromLong((long)fd);
    6279                 }
    6280                 /* Drop the argument parsing error as narrow strings
    6281                    are also valid. */
    6282                 PyErr_Clear();
    6283         }
    6284 #endif
    6285 
    6286         if (!PyArg_ParseTuple(args, "eti|i",
    6287                               Py_FileSystemDefaultEncoding, &file,
    6288                               &flag, &mode))
    6289                 return NULL;
    6290 
    6291         Py_BEGIN_ALLOW_THREADS
    6292         fd = open(file, flag, mode);
    6293         Py_END_ALLOW_THREADS
    6294         if (fd < 0)
    6295                 return posix_error_with_allocated_filename(file);
    6296         PyMem_Free(file);
    6297         return PyInt_FromLong((long)fd);
     6549    PyUnicodeObject *po;
     6550    if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) {
     6551        Py_BEGIN_ALLOW_THREADS
     6552        /* PyUnicode_AS_UNICODE OK without thread
     6553           lock as it is a simple dereference. */
     6554        fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode);
     6555        Py_END_ALLOW_THREADS
     6556        if (fd < 0)
     6557            return posix_error();
     6558        return PyInt_FromLong((long)fd);
     6559    }
     6560    /* Drop the argument parsing error as narrow strings
     6561       are also valid. */
     6562    PyErr_Clear();
     6563#endif
     6564
     6565    if (!PyArg_ParseTuple(args, "eti|i",
     6566                          Py_FileSystemDefaultEncoding, &file,
     6567                          &flag, &mode))
     6568        return NULL;
     6569
     6570    Py_BEGIN_ALLOW_THREADS
     6571    fd = open(file, flag, mode);
     6572    Py_END_ALLOW_THREADS
     6573    if (fd < 0)
     6574        return posix_error_with_allocated_filename(file);
     6575    PyMem_Free(file);
     6576    return PyInt_FromLong((long)fd);
    62986577}
    62996578
     
    63066585posix_close(PyObject *self, PyObject *args)
    63076586{
    6308         int fd, res;
    6309         if (!PyArg_ParseTuple(args, "i:close", &fd))
    6310                 return NULL;
    6311         Py_BEGIN_ALLOW_THREADS
    6312         res = close(fd);
    6313         Py_END_ALLOW_THREADS
    6314         if (res < 0)
    6315                 return posix_error();
    6316         Py_INCREF(Py_None);
    6317         return Py_None;
    6318 }
    6319 
    6320 
    6321 PyDoc_STRVAR(posix_closerange__doc__,
     6587    int fd, res;
     6588    if (!PyArg_ParseTuple(args, "i:close", &fd))
     6589        return NULL;
     6590    if (!_PyVerify_fd(fd))
     6591        return posix_error();
     6592    Py_BEGIN_ALLOW_THREADS
     6593    res = close(fd);
     6594    Py_END_ALLOW_THREADS
     6595    if (res < 0)
     6596        return posix_error();
     6597    Py_INCREF(Py_None);
     6598    return Py_None;
     6599}
     6600
     6601
     6602PyDoc_STRVAR(posix_closerange__doc__,
    63226603"closerange(fd_low, fd_high)\n\n\
    63236604Closes all file descriptors in [fd_low, fd_high), ignoring errors.");
     
    63266607posix_closerange(PyObject *self, PyObject *args)
    63276608{
    6328         int fd_from, fd_to, i;
    6329         if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to))
    6330                 return NULL;
    6331         Py_BEGIN_ALLOW_THREADS
    6332         for (i = fd_from; i < fd_to; i++)
    6333                 close(i);
    6334         Py_END_ALLOW_THREADS
    6335         Py_RETURN_NONE;
     6609    int fd_from, fd_to, i;
     6610    if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to))
     6611        return NULL;
     6612    Py_BEGIN_ALLOW_THREADS
     6613    for (i = fd_from; i < fd_to; i++)
     6614        if (_PyVerify_fd(i))
     6615            close(i);
     6616    Py_END_ALLOW_THREADS
     6617    Py_RETURN_NONE;
    63366618}
    63376619
     
    63446626posix_dup(PyObject *self, PyObject *args)
    63456627{
    6346         int fd;
    6347         if (!PyArg_ParseTuple(args, "i:dup", &fd))
    6348                 return NULL;
    6349         Py_BEGIN_ALLOW_THREADS
    6350         fd = dup(fd);
    6351         Py_END_ALLOW_THREADS
    6352         if (fd < 0)
    6353                 return posix_error();
    6354         return PyInt_FromLong((long)fd);
     6628    int fd;
     6629    if (!PyArg_ParseTuple(args, "i:dup", &fd))
     6630        return NULL;
     6631    if (!_PyVerify_fd(fd))
     6632        return posix_error();
     6633    Py_BEGIN_ALLOW_THREADS
     6634    fd = dup(fd);
     6635    Py_END_ALLOW_THREADS
     6636    if (fd < 0)
     6637        return posix_error();
     6638    return PyInt_FromLong((long)fd);
    63556639}
    63566640
     
    63636647posix_dup2(PyObject *self, PyObject *args)
    63646648{
    6365         int fd, fd2, res;
    6366         if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2))
    6367                 return NULL;
    6368         Py_BEGIN_ALLOW_THREADS
    6369         res = dup2(fd, fd2);
    6370         Py_END_ALLOW_THREADS
    6371         if (res < 0)
    6372                 return posix_error();
    6373         Py_INCREF(Py_None);
    6374         return Py_None;
     6649    int fd, fd2, res;
     6650    if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2))
     6651        return NULL;
     6652    if (!_PyVerify_fd_dup2(fd, fd2))
     6653        return posix_error();
     6654    Py_BEGIN_ALLOW_THREADS
     6655    res = dup2(fd, fd2);
     6656    Py_END_ALLOW_THREADS
     6657    if (res < 0)
     6658        return posix_error();
     6659    Py_INCREF(Py_None);
     6660    return Py_None;
    63756661}
    63766662
     
    63836669posix_lseek(PyObject *self, PyObject *args)
    63846670{
    6385         int fd, how;
     6671    int fd, how;
    63866672#if defined(MS_WIN64) || defined(MS_WINDOWS)
    6387         PY_LONG_LONG pos, res;
     6673    PY_LONG_LONG pos, res;
    63886674#else
    6389         off_t pos, res;
    6390 #endif
    6391         PyObject *posobj;
    6392         if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how))
    6393                 return NULL;
     6675    off_t pos, res;
     6676#endif
     6677    PyObject *posobj;
     6678    if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how))
     6679        return NULL;
    63946680#ifdef SEEK_SET
    6395         /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
    6396         switch (how) {
    6397         case 0: how = SEEK_SET; break;
    6398         case 1: how = SEEK_CUR; break;
    6399         case 2: how = SEEK_END; break;
    6400         }
     6681    /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
     6682    switch (how) {
     6683    case 0: how = SEEK_SET; break;
     6684    case 1: how = SEEK_CUR; break;
     6685    case 2: how = SEEK_END; break;
     6686    }
    64016687#endif /* SEEK_END */
    64026688
    64036689#if !defined(HAVE_LARGEFILE_SUPPORT)
    6404         pos = PyInt_AsLong(posobj);
     6690    pos = PyInt_AsLong(posobj);
    64056691#else
    6406         pos = PyLong_Check(posobj) ?
    6407                 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
    6408 #endif
    6409         if (PyErr_Occurred())
    6410                 return NULL;
    6411 
    6412         Py_BEGIN_ALLOW_THREADS
     6692    pos = PyLong_Check(posobj) ?
     6693        PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
     6694#endif
     6695    if (PyErr_Occurred())
     6696        return NULL;
     6697
     6698    if (!_PyVerify_fd(fd))
     6699        return posix_error();
     6700    Py_BEGIN_ALLOW_THREADS
    64136701#if defined(MS_WIN64) || defined(MS_WINDOWS)
    6414         res = _lseeki64(fd, pos, how);
     6702    res = _lseeki64(fd, pos, how);
    64156703#else
    6416         res = lseek(fd, pos, how);
    6417 #endif
    6418         Py_END_ALLOW_THREADS
    6419         if (res < 0)
    6420                 return posix_error();
     6704    res = lseek(fd, pos, how);
     6705#endif
     6706    Py_END_ALLOW_THREADS
     6707    if (res < 0)
     6708        return posix_error();
    64216709
    64226710#if !defined(HAVE_LARGEFILE_SUPPORT)
    6423         return PyInt_FromLong(res);
     6711    return PyInt_FromLong(res);
    64246712#else
    6425         return PyLong_FromLongLong(res);
     6713    return PyLong_FromLongLong(res);
    64266714#endif
    64276715}
     
    64356723posix_read(PyObject *self, PyObject *args)
    64366724{
    6437         int fd, size, n;
    6438         PyObject *buffer;
    6439         if (!PyArg_ParseTuple(args, "ii:read", &fd, &size))
    6440                 return NULL;
    6441         if (size < 0) {
    6442                 errno = EINVAL;
    6443                 return posix_error();
    6444         }
    6445         buffer = PyString_FromStringAndSize((char *)NULL, size);
    6446         if (buffer == NULL)
    6447                 return NULL;
    6448         Py_BEGIN_ALLOW_THREADS
    6449         n = read(fd, PyString_AsString(buffer), size);
    6450         Py_END_ALLOW_THREADS
    6451         if (n < 0) {
    6452                 Py_DECREF(buffer);
    6453                 return posix_error();
    6454         }
    6455         if (n != size)
    6456                 _PyString_Resize(&buffer, n);
    6457         return buffer;
     6725    int fd, size, n;
     6726    PyObject *buffer;
     6727    if (!PyArg_ParseTuple(args, "ii:read", &fd, &size))
     6728        return NULL;
     6729    if (size < 0) {
     6730        errno = EINVAL;
     6731        return posix_error();
     6732    }
     6733    buffer = PyString_FromStringAndSize((char *)NULL, size);
     6734    if (buffer == NULL)
     6735        return NULL;
     6736    if (!_PyVerify_fd(fd)) {
     6737        Py_DECREF(buffer);
     6738        return posix_error();
     6739    }
     6740    Py_BEGIN_ALLOW_THREADS
     6741    n = read(fd, PyString_AsString(buffer), size);
     6742    Py_END_ALLOW_THREADS
     6743    if (n < 0) {
     6744        Py_DECREF(buffer);
     6745        return posix_error();
     6746    }
     6747    if (n != size)
     6748        _PyString_Resize(&buffer, n);
     6749    return buffer;
    64586750}
    64596751
     
    64666758posix_write(PyObject *self, PyObject *args)
    64676759{
    6468         Py_buffer pbuf;
    6469         int fd;
    6470         Py_ssize_t size;
    6471 
    6472         if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf))
    6473                 return NULL;
    6474         Py_BEGIN_ALLOW_THREADS
    6475         size = write(fd, pbuf.buf, (size_t)pbuf.len);
    6476         Py_END_ALLOW_THREADS
    6477                 PyBuffer_Release(&pbuf);
    6478         if (size < 0)
    6479                 return posix_error();
    6480         return PyInt_FromSsize_t(size);
     6760    Py_buffer pbuf;
     6761    int fd;
     6762    Py_ssize_t size, len;
     6763
     6764    if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf))
     6765        return NULL;
     6766    if (!_PyVerify_fd(fd)) {
     6767        PyBuffer_Release(&pbuf);
     6768        return posix_error();
     6769    }
     6770    len = pbuf.len;
     6771    Py_BEGIN_ALLOW_THREADS
     6772#if defined(MS_WIN64) || defined(MS_WINDOWS)
     6773    if (len > INT_MAX)
     6774        len = INT_MAX;
     6775    size = write(fd, pbuf.buf, (int)len);
     6776#else
     6777    size = write(fd, pbuf.buf, len);
     6778#endif
     6779    Py_END_ALLOW_THREADS
     6780    PyBuffer_Release(&pbuf);
     6781    if (size < 0)
     6782        return posix_error();
     6783    return PyInt_FromSsize_t(size);
    64816784}
    64826785
     
    64896792posix_fstat(PyObject *self, PyObject *args)
    64906793{
    6491         int fd;
    6492         STRUCT_STAT st;
    6493         int res;
    6494         if (!PyArg_ParseTuple(args, "i:fstat", &fd))
    6495                 return NULL;
     6794    int fd;
     6795    STRUCT_STAT st;
     6796    int res;
     6797    if (!PyArg_ParseTuple(args, "i:fstat", &fd))
     6798        return NULL;
    64966799#ifdef __VMS
    6497         /* on OpenVMS we must ensure that all bytes are written to the file */
    6498         fsync(fd);
    6499 #endif
    6500         Py_BEGIN_ALLOW_THREADS
    6501         res = FSTAT(fd, &st);
    6502         Py_END_ALLOW_THREADS
    6503         if (res != 0) {
     6800    /* on OpenVMS we must ensure that all bytes are written to the file */
     6801    fsync(fd);
     6802#endif
     6803    if (!_PyVerify_fd(fd))
     6804        return posix_error();
     6805    Py_BEGIN_ALLOW_THREADS
     6806    res = FSTAT(fd, &st);
     6807    Py_END_ALLOW_THREADS
     6808    if (res != 0) {
    65046809#ifdef MS_WINDOWS
    6505                 return win32_error("fstat", NULL);
     6810        return win32_error("fstat", NULL);
    65066811#else
    6507                 return posix_error();
    6508 #endif
    6509         }
    6510 
    6511         return _pystat_fromstructstat(&st);
     6812        return posix_error();
     6813#endif
     6814    }
     6815
     6816    return _pystat_fromstructstat(&st);
    65126817}
    65136818
     
    65206825posix_fdopen(PyObject *self, PyObject *args)
    65216826{
    6522         int fd;
    6523         char *orgmode = "r";
    6524         int bufsize = -1;
    6525         FILE *fp;
    6526         PyObject *f;
    6527         char *mode;
    6528         if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize))
    6529                 return NULL;
    6530 
    6531         /* Sanitize mode.  See fileobject.c */
    6532         mode = PyMem_MALLOC(strlen(orgmode)+3);
    6533         if (!mode) {
    6534                 PyErr_NoMemory();
    6535                 return NULL;
    6536         }
    6537         strcpy(mode, orgmode);
    6538         if (_PyFile_SanitizeMode(mode)) {
    6539                 PyMem_FREE(mode);
    6540                 return NULL;
    6541         }
    6542         Py_BEGIN_ALLOW_THREADS
     6827    int fd;
     6828    char *orgmode = "r";
     6829    int bufsize = -1;
     6830    FILE *fp;
     6831    PyObject *f;
     6832    char *mode;
     6833    if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize))
     6834        return NULL;
     6835
     6836    /* Sanitize mode.  See fileobject.c */
     6837    mode = PyMem_MALLOC(strlen(orgmode)+3);
     6838    if (!mode) {
     6839        PyErr_NoMemory();
     6840        return NULL;
     6841    }
     6842    strcpy(mode, orgmode);
     6843    if (_PyFile_SanitizeMode(mode)) {
     6844        PyMem_FREE(mode);
     6845        return NULL;
     6846    }
     6847    if (!_PyVerify_fd(fd))
     6848        return posix_error();
     6849    Py_BEGIN_ALLOW_THREADS
    65436850#if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H)
    6544         if (mode[0] == 'a') {
    6545                 /* try to make sure the O_APPEND flag is set */
    6546                 int flags;
    6547                 flags = fcntl(fd, F_GETFL);
    6548                 if (flags != -1)
    6549                         fcntl(fd, F_SETFL, flags | O_APPEND);
    6550                 fp = fdopen(fd, mode);
    6551                 if (fp == NULL && flags != -1)
    6552                         /* restore old mode if fdopen failed */
    6553                         fcntl(fd, F_SETFL, flags);
    6554         } else {
    6555                 fp = fdopen(fd, mode);
    6556         }
     6851    if (mode[0] == 'a') {
     6852        /* try to make sure the O_APPEND flag is set */
     6853        int flags;
     6854        flags = fcntl(fd, F_GETFL);
     6855        if (flags != -1)
     6856            fcntl(fd, F_SETFL, flags | O_APPEND);
     6857        fp = fdopen(fd, mode);
     6858        if (fp == NULL && flags != -1)
     6859            /* restore old mode if fdopen failed */
     6860            fcntl(fd, F_SETFL, flags);
     6861    } else {
     6862        fp = fdopen(fd, mode);
     6863    }
    65576864#else
    6558         fp = fdopen(fd, mode);
    6559 #endif
    6560         Py_END_ALLOW_THREADS
    6561         PyMem_FREE(mode);
    6562         if (fp == NULL)
    6563                 return posix_error();
    6564         f = PyFile_FromFile(fp, "<fdopen>", orgmode, fclose);
    6565         if (f != NULL)
    6566                 PyFile_SetBufSize(f, bufsize);
    6567         return f;
     6865    fp = fdopen(fd, mode);
     6866#endif
     6867    Py_END_ALLOW_THREADS
     6868    PyMem_FREE(mode);
     6869    if (fp == NULL)
     6870        return posix_error();
     6871    /* The dummy filename used here must be kept in sync with the value
     6872       tested against in gzip.GzipFile.__init__() - see issue #13781. */
     6873    f = PyFile_FromFile(fp, "<fdopen>", orgmode, fclose);
     6874    if (f != NULL)
     6875        PyFile_SetBufSize(f, bufsize);
     6876    return f;
    65686877}
    65696878
     
    65766885posix_isatty(PyObject *self, PyObject *args)
    65776886{
    6578         int fd;
    6579         if (!PyArg_ParseTuple(args, "i:isatty", &fd))
    6580                 return NULL;
    6581         return PyBool_FromLong(isatty(fd));
     6887    int fd;
     6888    if (!PyArg_ParseTuple(args, "i:isatty", &fd))
     6889        return NULL;
     6890    if (!_PyVerify_fd(fd))
     6891        return PyBool_FromLong(0);
     6892    return PyBool_FromLong(isatty(fd));
    65826893}
    65836894
     
    65946905    APIRET rc;
    65956906
    6596         Py_BEGIN_ALLOW_THREADS
     6907    Py_BEGIN_ALLOW_THREADS
    65976908    rc = DosCreatePipe( &read, &write, 4096);
    6598         Py_END_ALLOW_THREADS
     6909    Py_END_ALLOW_THREADS
    65996910    if (rc != NO_ERROR)
    66006911        return os2_error(rc);
     
    66036914#else
    66046915#if !defined(MS_WINDOWS)
    6605         int fds[2];
    6606         int res;
    6607         Py_BEGIN_ALLOW_THREADS
    6608         res = pipe(fds);
    6609         Py_END_ALLOW_THREADS
    6610         if (res != 0)
    6611                 return posix_error();
    6612         return Py_BuildValue("(ii)", fds[0], fds[1]);
     6916    int fds[2];
     6917    int res;
     6918    Py_BEGIN_ALLOW_THREADS
     6919    res = pipe(fds);
     6920    Py_END_ALLOW_THREADS
     6921    if (res != 0)
     6922        return posix_error();
     6923    return Py_BuildValue("(ii)", fds[0], fds[1]);
    66136924#else /* MS_WINDOWS */
    6614         HANDLE read, write;
    6615         int read_fd, write_fd;
    6616         BOOL ok;
    6617         Py_BEGIN_ALLOW_THREADS
    6618         ok = CreatePipe(&read, &write, NULL, 0);
    6619         Py_END_ALLOW_THREADS
    6620         if (!ok)
    6621                 return win32_error("CreatePipe", NULL);
    6622         read_fd = _open_osfhandle((Py_intptr_t)read, 0);
    6623         write_fd = _open_osfhandle((Py_intptr_t)write, 1);
    6624         return Py_BuildValue("(ii)", read_fd, write_fd);
     6925    HANDLE read, write;
     6926    int read_fd, write_fd;
     6927    BOOL ok;
     6928    Py_BEGIN_ALLOW_THREADS
     6929    ok = CreatePipe(&read, &write, NULL, 0);
     6930    Py_END_ALLOW_THREADS
     6931    if (!ok)
     6932        return win32_error("CreatePipe", NULL);
     6933    read_fd = _open_osfhandle((Py_intptr_t)read, 0);
     6934    write_fd = _open_osfhandle((Py_intptr_t)write, 1);
     6935    return Py_BuildValue("(ii)", read_fd, write_fd);
    66256936#endif /* MS_WINDOWS */
    66266937#endif
     
    66376948posix_mkfifo(PyObject *self, PyObject *args)
    66386949{
    6639         char *filename;
    6640         int mode = 0666;
    6641         int res;
    6642         if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode))
    6643                 return NULL;
    6644         Py_BEGIN_ALLOW_THREADS
    6645         res = mkfifo(filename, mode);
    6646         Py_END_ALLOW_THREADS
    6647         if (res < 0)
    6648                 return posix_error();
    6649         Py_INCREF(Py_None);
    6650         return Py_None;
     6950    char *filename;
     6951    int mode = 0666;
     6952    int res;
     6953    if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode))
     6954        return NULL;
     6955    Py_BEGIN_ALLOW_THREADS
     6956    res = mkfifo(filename, mode);
     6957    Py_END_ALLOW_THREADS
     6958    if (res < 0)
     6959        return posix_error();
     6960    Py_INCREF(Py_None);
     6961    return Py_None;
    66516962}
    66526963#endif
     
    66676978posix_mknod(PyObject *self, PyObject *args)
    66686979{
    6669         char *filename;
    6670         int mode = 0600;
    6671         int device = 0;
    6672         int res;
    6673         if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device))
    6674                 return NULL;
    6675         Py_BEGIN_ALLOW_THREADS
    6676         res = mknod(filename, mode, device);
    6677         Py_END_ALLOW_THREADS
    6678         if (res < 0)
    6679                 return posix_error();
    6680         Py_INCREF(Py_None);
    6681         return Py_None;
     6980    char *filename;
     6981    int mode = 0600;
     6982    int device = 0;
     6983    int res;
     6984    if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device))
     6985        return NULL;
     6986    Py_BEGIN_ALLOW_THREADS
     6987    res = mknod(filename, mode, device);
     6988    Py_END_ALLOW_THREADS
     6989    if (res < 0)
     6990        return posix_error();
     6991    Py_INCREF(Py_None);
     6992    return Py_None;
    66826993}
    66836994#endif
     
    66917002posix_major(PyObject *self, PyObject *args)
    66927003{
    6693         int device;
    6694         if (!PyArg_ParseTuple(args, "i:major", &device))
    6695                 return NULL;
    6696         return PyInt_FromLong((long)major(device));
     7004    int device;
     7005    if (!PyArg_ParseTuple(args, "i:major", &device))
     7006        return NULL;
     7007    return PyInt_FromLong((long)major(device));
    66977008}
    66987009
     
    67047015posix_minor(PyObject *self, PyObject *args)
    67057016{
    6706         int device;
    6707         if (!PyArg_ParseTuple(args, "i:minor", &device))
    6708                 return NULL;
    6709         return PyInt_FromLong((long)minor(device));
     7017    int device;
     7018    if (!PyArg_ParseTuple(args, "i:minor", &device))
     7019        return NULL;
     7020    return PyInt_FromLong((long)minor(device));
    67107021}
    67117022
     
    67177028posix_makedev(PyObject *self, PyObject *args)
    67187029{
    6719         int major, minor;
    6720         if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor))
    6721                 return NULL;
    6722         return PyInt_FromLong((long)makedev(major, minor));
     7030    int major, minor;
     7031    if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor))
     7032        return NULL;
     7033    return PyInt_FromLong((long)makedev(major, minor));
    67237034}
    67247035#endif /* device macros */
     
    67337044posix_ftruncate(PyObject *self, PyObject *args)
    67347045{
    6735         int fd;
    6736         off_t length;
    6737         int res;
    6738         PyObject *lenobj;
    6739 
    6740         if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj))
    6741                 return NULL;
     7046    int fd;
     7047    off_t length;
     7048    int res;
     7049    PyObject *lenobj;
     7050
     7051    if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj))
     7052        return NULL;
    67427053
    67437054#if !defined(HAVE_LARGEFILE_SUPPORT)
    6744         length = PyInt_AsLong(lenobj);
     7055    length = PyInt_AsLong(lenobj);
    67457056#else
    6746         length = PyLong_Check(lenobj) ?
    6747                 PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj);
    6748 #endif
    6749         if (PyErr_Occurred())
    6750                 return NULL;
    6751 
    6752         Py_BEGIN_ALLOW_THREADS
    6753         res = ftruncate(fd, length);
    6754         Py_END_ALLOW_THREADS
    6755         if (res < 0) {
    6756                 PyErr_SetFromErrno(PyExc_IOError);
    6757                 return NULL;
    6758         }
    6759         Py_INCREF(Py_None);
    6760         return Py_None;
     7057    length = PyLong_Check(lenobj) ?
     7058        PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj);
     7059#endif
     7060    if (PyErr_Occurred())
     7061        return NULL;
     7062
     7063    Py_BEGIN_ALLOW_THREADS
     7064    res = ftruncate(fd, length);
     7065    Py_END_ALLOW_THREADS
     7066    if (res < 0)
     7067        return posix_error();
     7068    Py_INCREF(Py_None);
     7069    return Py_None;
    67617070}
    67627071#endif
     
    67747083posix_putenv(PyObject *self, PyObject *args)
    67757084{
    6776         char *s1, *s2;
    6777         char *newenv;
    6778         PyObject *newstr;
    6779         size_t len;
    6780 
    6781         if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2))
    6782                 return NULL;
     7085    char *s1, *s2;
     7086    char *newenv;
     7087    PyObject *newstr;
     7088    size_t len;
     7089
     7090    if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2))
     7091        return NULL;
    67837092
    67847093#if defined(PYOS_OS2)
     
    67997108#endif
    68007109
    6801         /* XXX This can leak memory -- not easy to fix :-( */
    6802         len = strlen(s1) + strlen(s2) + 2;
    6803         /* len includes space for a trailing \0; the size arg to
    6804            PyString_FromStringAndSize does not count that */
    6805         newstr = PyString_FromStringAndSize(NULL, (int)len - 1);
    6806         if (newstr == NULL)
    6807                 return PyErr_NoMemory();
    6808         newenv = PyString_AS_STRING(newstr);
    6809         PyOS_snprintf(newenv, len, "%s=%s", s1, s2);
    6810         if (putenv(newenv)) {
    6811                 Py_DECREF(newstr);
    6812                 posix_error();
    6813                 return NULL;
    6814         }
    6815         /* Install the first arg and newstr in posix_putenv_garbage;
    6816          * this will cause previous value to be collected.  This has to
    6817          * happen after the real putenv() call because the old value
    6818          * was still accessible until then. */
    6819         if (PyDict_SetItem(posix_putenv_garbage,
    6820                            PyTuple_GET_ITEM(args, 0), newstr)) {
    6821                 /* really not much we can do; just leak */
    6822                 PyErr_Clear();
    6823         }
    6824         else {
    6825                 Py_DECREF(newstr);
    6826         }
     7110    /* XXX This can leak memory -- not easy to fix :-( */
     7111    len = strlen(s1) + strlen(s2) + 2;
     7112#ifdef MS_WINDOWS
     7113    if (_MAX_ENV < (len - 1)) {
     7114        PyErr_Format(PyExc_ValueError,
     7115                     "the environment variable is longer than %u bytes",
     7116                     _MAX_ENV);
     7117        return NULL;
     7118    }
     7119#endif
     7120    /* len includes space for a trailing \0; the size arg to
     7121       PyString_FromStringAndSize does not count that */
     7122    newstr = PyString_FromStringAndSize(NULL, (int)len - 1);
     7123    if (newstr == NULL)
     7124        return PyErr_NoMemory();
     7125    newenv = PyString_AS_STRING(newstr);
     7126    PyOS_snprintf(newenv, len, "%s=%s", s1, s2);
     7127    if (putenv(newenv)) {
     7128        Py_DECREF(newstr);
     7129        posix_error();
     7130        return NULL;
     7131    }
     7132    /* Install the first arg and newstr in posix_putenv_garbage;
     7133     * this will cause previous value to be collected.  This has to
     7134     * happen after the real putenv() call because the old value
     7135     * was still accessible until then. */
     7136    if (PyDict_SetItem(posix_putenv_garbage,
     7137                       PyTuple_GET_ITEM(args, 0), newstr)) {
     7138        /* really not much we can do; just leak */
     7139        PyErr_Clear();
     7140    }
     7141    else {
     7142        Py_DECREF(newstr);
     7143    }
    68277144
    68287145#if defined(PYOS_OS2)
    68297146    }
    68307147#endif
    6831         Py_INCREF(Py_None);
    6832         return Py_None;
     7148    Py_INCREF(Py_None);
     7149    return Py_None;
    68337150}
    68347151#endif /* putenv */
     
    68427159posix_unsetenv(PyObject *self, PyObject *args)
    68437160{
    6844         char *s1;
    6845 
    6846         if (!PyArg_ParseTuple(args, "s:unsetenv", &s1))
    6847                 return NULL;
    6848 
    6849         unsetenv(s1);
    6850 
    6851         /* Remove the key from posix_putenv_garbage;
    6852          * this will cause it to be collected.  This has to
    6853          * happen after the real unsetenv() call because the
    6854          * old value was still accessible until then.
    6855          */
    6856         if (PyDict_DelItem(posix_putenv_garbage,
    6857                 PyTuple_GET_ITEM(args, 0))) {
    6858                 /* really not much we can do; just leak */
    6859                 PyErr_Clear();
    6860         }
    6861 
    6862         Py_INCREF(Py_None);
    6863         return Py_None;
     7161    char *s1;
     7162#ifndef HAVE_BROKEN_UNSETENV
     7163    int err;
     7164#endif
     7165
     7166    if (!PyArg_ParseTuple(args, "s:unsetenv", &s1))
     7167        return NULL;
     7168
     7169#ifdef HAVE_BROKEN_UNSETENV
     7170    unsetenv(s1);
     7171#else
     7172    err = unsetenv(s1);
     7173    if (err)
     7174        return posix_error();
     7175#endif
     7176
     7177    /* Remove the key from posix_putenv_garbage;
     7178     * this will cause it to be collected.  This has to
     7179     * happen after the real unsetenv() call because the
     7180     * old value was still accessible until then.
     7181     */
     7182    if (PyDict_DelItem(posix_putenv_garbage,
     7183                       PyTuple_GET_ITEM(args, 0))) {
     7184        /* really not much we can do; just leak */
     7185        PyErr_Clear();
     7186    }
     7187
     7188    Py_INCREF(Py_None);
     7189    return Py_None;
    68647190}
    68657191#endif /* unsetenv */
     
    68727198posix_strerror(PyObject *self, PyObject *args)
    68737199{
    6874         int code;
    6875         char *message;
    6876         if (!PyArg_ParseTuple(args, "i:strerror", &code))
    6877                 return NULL;
    6878         message = strerror(code);
    6879         if (message == NULL) {
    6880                 PyErr_SetString(PyExc_ValueError,
    6881                                 "strerror() argument out of range");
    6882                 return NULL;
    6883         }
    6884         return PyString_FromString(message);
     7200    int code;
     7201    char *message;
     7202    if (!PyArg_ParseTuple(args, "i:strerror", &code))
     7203        return NULL;
     7204    message = strerror(code);
     7205    if (message == NULL) {
     7206        PyErr_SetString(PyExc_ValueError,
     7207                        "strerror() argument out of range");
     7208        return NULL;
     7209    }
     7210    return PyString_FromString(message);
    68857211}
    68867212
     
    68967222posix_WCOREDUMP(PyObject *self, PyObject *args)
    68977223{
    6898         WAIT_TYPE status;
    6899         WAIT_STATUS_INT(status) = 0;
    6900 
    6901         if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status)))
    6902                 return NULL;
    6903 
    6904         return PyBool_FromLong(WCOREDUMP(status));
     7224    WAIT_TYPE status;
     7225    WAIT_STATUS_INT(status) = 0;
     7226
     7227    if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status)))
     7228        return NULL;
     7229
     7230    return PyBool_FromLong(WCOREDUMP(status));
    69057231}
    69067232#endif /* WCOREDUMP */
     
    69157241posix_WIFCONTINUED(PyObject *self, PyObject *args)
    69167242{
    6917         WAIT_TYPE status;
    6918         WAIT_STATUS_INT(status) = 0;
    6919 
    6920         if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status)))
    6921                 return NULL;
    6922 
    6923         return PyBool_FromLong(WIFCONTINUED(status));
     7243    WAIT_TYPE status;
     7244    WAIT_STATUS_INT(status) = 0;
     7245
     7246    if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status)))
     7247        return NULL;
     7248
     7249    return PyBool_FromLong(WIFCONTINUED(status));
    69247250}
    69257251#endif /* WIFCONTINUED */
     
    69337259posix_WIFSTOPPED(PyObject *self, PyObject *args)
    69347260{
    6935         WAIT_TYPE status;
    6936         WAIT_STATUS_INT(status) = 0;
    6937 
    6938         if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status)))
    6939                 return NULL;
    6940 
    6941         return PyBool_FromLong(WIFSTOPPED(status));
     7261    WAIT_TYPE status;
     7262    WAIT_STATUS_INT(status) = 0;
     7263
     7264    if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status)))
     7265        return NULL;
     7266
     7267    return PyBool_FromLong(WIFSTOPPED(status));
    69427268}
    69437269#endif /* WIFSTOPPED */
     
    69517277posix_WIFSIGNALED(PyObject *self, PyObject *args)
    69527278{
    6953         WAIT_TYPE status;
    6954         WAIT_STATUS_INT(status) = 0;
    6955 
    6956         if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status)))
    6957                 return NULL;
    6958 
    6959         return PyBool_FromLong(WIFSIGNALED(status));
     7279    WAIT_TYPE status;
     7280    WAIT_STATUS_INT(status) = 0;
     7281
     7282    if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status)))
     7283        return NULL;
     7284
     7285    return PyBool_FromLong(WIFSIGNALED(status));
    69607286}
    69617287#endif /* WIFSIGNALED */
     
    69707296posix_WIFEXITED(PyObject *self, PyObject *args)
    69717297{
    6972         WAIT_TYPE status;
    6973         WAIT_STATUS_INT(status) = 0;
    6974 
    6975         if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status)))
    6976                 return NULL;
    6977 
    6978         return PyBool_FromLong(WIFEXITED(status));
     7298    WAIT_TYPE status;
     7299    WAIT_STATUS_INT(status) = 0;
     7300
     7301    if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status)))
     7302        return NULL;
     7303
     7304    return PyBool_FromLong(WIFEXITED(status));
    69797305}
    69807306#endif /* WIFEXITED */
     
    69887314posix_WEXITSTATUS(PyObject *self, PyObject *args)
    69897315{
    6990         WAIT_TYPE status;
    6991         WAIT_STATUS_INT(status) = 0;
    6992 
    6993         if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status)))
    6994                 return NULL;
    6995 
    6996         return Py_BuildValue("i", WEXITSTATUS(status));
     7316    WAIT_TYPE status;
     7317    WAIT_STATUS_INT(status) = 0;
     7318
     7319    if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status)))
     7320        return NULL;
     7321
     7322    return Py_BuildValue("i", WEXITSTATUS(status));
    69977323}
    69987324#endif /* WEXITSTATUS */
     
    70077333posix_WTERMSIG(PyObject *self, PyObject *args)
    70087334{
    7009         WAIT_TYPE status;
    7010         WAIT_STATUS_INT(status) = 0;
    7011 
    7012         if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status)))
    7013                 return NULL;
    7014 
    7015         return Py_BuildValue("i", WTERMSIG(status));
     7335    WAIT_TYPE status;
     7336    WAIT_STATUS_INT(status) = 0;
     7337
     7338    if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status)))
     7339        return NULL;
     7340
     7341    return Py_BuildValue("i", WTERMSIG(status));
    70167342}
    70177343#endif /* WTERMSIG */
     
    70267352posix_WSTOPSIG(PyObject *self, PyObject *args)
    70277353{
    7028         WAIT_TYPE status;
    7029         WAIT_STATUS_INT(status) = 0;
    7030 
    7031         if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status)))
    7032                 return NULL;
    7033 
    7034         return Py_BuildValue("i", WSTOPSIG(status));
     7354    WAIT_TYPE status;
     7355    WAIT_STATUS_INT(status) = 0;
     7356
     7357    if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status)))
     7358        return NULL;
     7359
     7360    return Py_BuildValue("i", WSTOPSIG(status));
    70357361}
    70367362#endif /* WSTOPSIG */
     
    70497375static PyObject*
    70507376_pystatvfs_fromstructstatvfs(struct statvfs st) {
    7051         PyObject *v = PyStructSequence_New(&StatVFSResultType);
    7052         if (v == NULL)
    7053                 return NULL;
     7377    PyObject *v = PyStructSequence_New(&StatVFSResultType);
     7378    if (v == NULL)
     7379        return NULL;
    70547380
    70557381#if !defined(HAVE_LARGEFILE_SUPPORT)
    7056         PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));
    7057         PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));
    7058         PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks));
    7059         PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree));
    7060         PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail));
    7061         PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files));
    7062         PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree));
    7063         PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail));
    7064         PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));
    7065         PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));
     7382    PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));
     7383    PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));
     7384    PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks));
     7385    PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree));
     7386    PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail));
     7387    PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files));
     7388    PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree));
     7389    PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail));
     7390    PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));
     7391    PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));
    70667392#else
    7067         PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));
    7068         PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));
    7069         PyStructSequence_SET_ITEM(v, 2,
    7070                                PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks));
    7071         PyStructSequence_SET_ITEM(v, 3,
    7072                                PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree));
    7073         PyStructSequence_SET_ITEM(v, 4,
    7074                                PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail));
    7075         PyStructSequence_SET_ITEM(v, 5,
    7076                                PyLong_FromLongLong((PY_LONG_LONG) st.f_files));
    7077         PyStructSequence_SET_ITEM(v, 6,
    7078                                PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree));
    7079         PyStructSequence_SET_ITEM(v, 7,
    7080                                PyLong_FromLongLong((PY_LONG_LONG) st.f_favail));
    7081         PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));
    7082         PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));
    7083 #endif
    7084 
    7085         return v;
     7393    PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));
     7394    PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));
     7395    PyStructSequence_SET_ITEM(v, 2,
     7396                              PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks));
     7397    PyStructSequence_SET_ITEM(v, 3,
     7398                              PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree));
     7399    PyStructSequence_SET_ITEM(v, 4,
     7400                              PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail));
     7401    PyStructSequence_SET_ITEM(v, 5,
     7402                              PyLong_FromLongLong((PY_LONG_LONG) st.f_files));
     7403    PyStructSequence_SET_ITEM(v, 6,
     7404                              PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree));
     7405    PyStructSequence_SET_ITEM(v, 7,
     7406                              PyLong_FromLongLong((PY_LONG_LONG) st.f_favail));
     7407    PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));
     7408    PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));
     7409#endif
     7410
     7411    return v;
    70867412}
    70877413
     
    70937419posix_fstatvfs(PyObject *self, PyObject *args)
    70947420{
    7095         int fd, res;
    7096         struct statvfs st;
    7097 
    7098         if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd))
    7099                 return NULL;
    7100         Py_BEGIN_ALLOW_THREADS
    7101         res = fstatvfs(fd, &st);
    7102         Py_END_ALLOW_THREADS
    7103         if (res != 0)
    7104                 return posix_error();
    7105 
    7106         return _pystatvfs_fromstructstatvfs(st);
     7421    int fd, res;
     7422    struct statvfs st;
     7423
     7424    if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd))
     7425        return NULL;
     7426    Py_BEGIN_ALLOW_THREADS
     7427    res = fstatvfs(fd, &st);
     7428    Py_END_ALLOW_THREADS
     7429    if (res != 0)
     7430        return posix_error();
     7431
     7432    return _pystatvfs_fromstructstatvfs(st);
    71077433}
    71087434#endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */
     
    71197445posix_statvfs(PyObject *self, PyObject *args)
    71207446{
    7121         char *path;
    7122         int res;
    7123         struct statvfs st;
    7124         if (!PyArg_ParseTuple(args, "s:statvfs", &path))
    7125                 return NULL;
    7126         Py_BEGIN_ALLOW_THREADS
    7127         res = statvfs(path, &st);
    7128         Py_END_ALLOW_THREADS
    7129         if (res != 0)
    7130                 return posix_error_with_filename(path);
    7131 
    7132         return _pystatvfs_fromstructstatvfs(st);
     7447    char *path;
     7448    int res;
     7449    struct statvfs st;
     7450    if (!PyArg_ParseTuple(args, "s:statvfs", &path))
     7451        return NULL;
     7452    Py_BEGIN_ALLOW_THREADS
     7453    res = statvfs(path, &st);
     7454    Py_END_ALLOW_THREADS
     7455    if (res != 0)
     7456        return posix_error_with_filename(path);
     7457
     7458    return _pystatvfs_fromstructstatvfs(st);
    71337459}
    71347460#endif /* HAVE_STATVFS */
     
    71517477
    71527478    if (!PyArg_ParseTuple(args, "|zz:tempnam", &dir, &pfx))
    7153         return NULL;
     7479    return NULL;
    71547480
    71557481    if (PyErr_Warn(PyExc_RuntimeWarning,
    7156                   "tempnam is a potential security risk to your program") < 0)
    7157             return NULL;
     7482                   "tempnam is a potential security risk to your program") < 0)
     7483        return NULL;
     7484
     7485    if (PyErr_WarnPy3k("tempnam has been removed in 3.x; "
     7486                       "use the tempfile module", 1) < 0)
     7487        return NULL;
    71587488
    71597489#ifdef MS_WINDOWS
     
    71817511    FILE *fp;
    71827512
     7513    if (PyErr_WarnPy3k("tmpfile has been removed in 3.x; "
     7514                       "use the tempfile module", 1) < 0)
     7515        return NULL;
     7516
    71837517    fp = tmpfile();
    71847518    if (fp == NULL)
     
    72017535
    72027536    if (PyErr_Warn(PyExc_RuntimeWarning,
    7203                   "tmpnam is a potential security risk to your program") < 0)
    7204             return NULL;
     7537                   "tmpnam is a potential security risk to your program") < 0)
     7538        return NULL;
     7539
     7540    if (PyErr_WarnPy3k("tmpnam has been removed in 3.x; "
     7541                       "use the tempfile module", 1) < 0)
     7542        return NULL;
    72057543
    72067544#ifdef USE_TMPNAM_R
     
    72107548#endif
    72117549    if (name == NULL) {
    7212         PyObject *err = Py_BuildValue("is", 0,
     7550        PyObject *err = Py_BuildValue("is", 0,
    72137551#ifdef USE_TMPNAM_R
    72147552                                      "unexpected NULL from tmpnam_r"
     
    72177555#endif
    72187556                                      );
    7219         PyErr_SetObject(PyExc_OSError, err);
    7220         Py_XDECREF(err);
    7221         return NULL;
     7557        PyErr_SetObject(PyExc_OSError, err);
     7558        Py_XDECREF(err);
     7559        return NULL;
    72227560    }
    72237561    return PyString_FromString(buffer);
     
    72447582static int
    72457583conv_confname(PyObject *arg, int *valuep, struct constdef *table,
    7246               size_t tablesize)
     7584              size_t tablesize)
    72477585{
    72487586    if (PyInt_Check(arg)) {
     
    72537591        /* look up the value in the table using a binary search */
    72547592        size_t lo = 0;
    7255                 size_t mid;
     7593        size_t mid;
    72567594        size_t hi = tablesize;
    72577595        int cmp;
     
    72817619static struct constdef  posix_constants_pathconf[] = {
    72827620#ifdef _PC_ABI_AIO_XFER_MAX
    7283     {"PC_ABI_AIO_XFER_MAX",     _PC_ABI_AIO_XFER_MAX},
     7621    {"PC_ABI_AIO_XFER_MAX",     _PC_ABI_AIO_XFER_MAX},
    72847622#endif
    72857623#ifdef _PC_ABI_ASYNC_IO
    7286     {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
     7624    {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
    72877625#endif
    72887626#ifdef _PC_ASYNC_IO
    7289     {"PC_ASYNC_IO",     _PC_ASYNC_IO},
     7627    {"PC_ASYNC_IO",     _PC_ASYNC_IO},
    72907628#endif
    72917629#ifdef _PC_CHOWN_RESTRICTED
    7292     {"PC_CHOWN_RESTRICTED",     _PC_CHOWN_RESTRICTED},
     7630    {"PC_CHOWN_RESTRICTED",     _PC_CHOWN_RESTRICTED},
    72937631#endif
    72947632#ifdef _PC_FILESIZEBITS
    7295     {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
     7633    {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
    72967634#endif
    72977635#ifdef _PC_LAST
    7298     {"PC_LAST", _PC_LAST},
     7636    {"PC_LAST", _PC_LAST},
    72997637#endif
    73007638#ifdef _PC_LINK_MAX
    7301     {"PC_LINK_MAX",     _PC_LINK_MAX},
     7639    {"PC_LINK_MAX",     _PC_LINK_MAX},
    73027640#endif
    73037641#ifdef _PC_MAX_CANON
    7304     {"PC_MAX_CANON",    _PC_MAX_CANON},
     7642    {"PC_MAX_CANON",    _PC_MAX_CANON},
    73057643#endif
    73067644#ifdef _PC_MAX_INPUT
    7307     {"PC_MAX_INPUT",    _PC_MAX_INPUT},
     7645    {"PC_MAX_INPUT",    _PC_MAX_INPUT},
    73087646#endif
    73097647#ifdef _PC_NAME_MAX
    7310     {"PC_NAME_MAX",     _PC_NAME_MAX},
     7648    {"PC_NAME_MAX",     _PC_NAME_MAX},
    73117649#endif
    73127650#ifdef _PC_NO_TRUNC
    7313     {"PC_NO_TRUNC",     _PC_NO_TRUNC},
     7651    {"PC_NO_TRUNC",     _PC_NO_TRUNC},
    73147652#endif
    73157653#ifdef _PC_PATH_MAX
    7316     {"PC_PATH_MAX",     _PC_PATH_MAX},
     7654    {"PC_PATH_MAX",     _PC_PATH_MAX},
    73177655#endif
    73187656#ifdef _PC_PIPE_BUF
    7319     {"PC_PIPE_BUF",     _PC_PIPE_BUF},
     7657    {"PC_PIPE_BUF",     _PC_PIPE_BUF},
    73207658#endif
    73217659#ifdef _PC_PRIO_IO
    7322     {"PC_PRIO_IO",      _PC_PRIO_IO},
     7660    {"PC_PRIO_IO",      _PC_PRIO_IO},
    73237661#endif
    73247662#ifdef _PC_SOCK_MAXBUF
    7325     {"PC_SOCK_MAXBUF",  _PC_SOCK_MAXBUF},
     7663    {"PC_SOCK_MAXBUF",  _PC_SOCK_MAXBUF},
    73267664#endif
    73277665#ifdef _PC_SYNC_IO
    7328     {"PC_SYNC_IO",      _PC_SYNC_IO},
     7666    {"PC_SYNC_IO",      _PC_SYNC_IO},
    73297667#endif
    73307668#ifdef _PC_VDISABLE
    7331     {"PC_VDISABLE",     _PC_VDISABLE},
     7669    {"PC_VDISABLE",     _PC_VDISABLE},
    73327670#endif
    73337671};
     
    73857723    if (PyArg_ParseTuple(args, "sO&:pathconf", &path,
    73867724                         conv_path_confname, &name)) {
    7387         long limit;
    7388 
    7389         errno = 0;
    7390         limit = pathconf(path, name);
    7391         if (limit == -1 && errno != 0) {
    7392             if (errno == EINVAL)
    7393                 /* could be a path or name problem */
    7394                 posix_error();
    7395             else
    7396                 posix_error_with_filename(path);
    7397         }
     7725    long limit;
     7726
     7727    errno = 0;
     7728    limit = pathconf(path, name);
     7729    if (limit == -1 && errno != 0) {
     7730        if (errno == EINVAL)
     7731            /* could be a path or name problem */
     7732            posix_error();
    73987733        else
    7399             result = PyInt_FromLong(limit);
     7734            posix_error_with_filename(path);
     7735    }
     7736    else
     7737        result = PyInt_FromLong(limit);
    74007738    }
    74017739    return result;
     
    74067744static struct constdef posix_constants_confstr[] = {
    74077745#ifdef _CS_ARCHITECTURE
    7408     {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
     7746    {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
    74097747#endif
    74107748#ifdef _CS_HOSTNAME
    7411     {"CS_HOSTNAME",     _CS_HOSTNAME},
     7749    {"CS_HOSTNAME",     _CS_HOSTNAME},
    74127750#endif
    74137751#ifdef _CS_HW_PROVIDER
    7414     {"CS_HW_PROVIDER",  _CS_HW_PROVIDER},
     7752    {"CS_HW_PROVIDER",  _CS_HW_PROVIDER},
    74157753#endif
    74167754#ifdef _CS_HW_SERIAL
    7417     {"CS_HW_SERIAL",    _CS_HW_SERIAL},
     7755    {"CS_HW_SERIAL",    _CS_HW_SERIAL},
    74187756#endif
    74197757#ifdef _CS_INITTAB_NAME
    7420     {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
     7758    {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
    74217759#endif
    74227760#ifdef _CS_LFS64_CFLAGS
    7423     {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
     7761    {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
    74247762#endif
    74257763#ifdef _CS_LFS64_LDFLAGS
    7426     {"CS_LFS64_LDFLAGS",        _CS_LFS64_LDFLAGS},
     7764    {"CS_LFS64_LDFLAGS",        _CS_LFS64_LDFLAGS},
    74277765#endif
    74287766#ifdef _CS_LFS64_LIBS
    7429     {"CS_LFS64_LIBS",   _CS_LFS64_LIBS},
     7767    {"CS_LFS64_LIBS",   _CS_LFS64_LIBS},
    74307768#endif
    74317769#ifdef _CS_LFS64_LINTFLAGS
    7432     {"CS_LFS64_LINTFLAGS",      _CS_LFS64_LINTFLAGS},
     7770    {"CS_LFS64_LINTFLAGS",      _CS_LFS64_LINTFLAGS},
    74337771#endif
    74347772#ifdef _CS_LFS_CFLAGS
    7435     {"CS_LFS_CFLAGS",   _CS_LFS_CFLAGS},
     7773    {"CS_LFS_CFLAGS",   _CS_LFS_CFLAGS},
    74367774#endif
    74377775#ifdef _CS_LFS_LDFLAGS
    7438     {"CS_LFS_LDFLAGS",  _CS_LFS_LDFLAGS},
     7776    {"CS_LFS_LDFLAGS",  _CS_LFS_LDFLAGS},
    74397777#endif
    74407778#ifdef _CS_LFS_LIBS
    7441     {"CS_LFS_LIBS",     _CS_LFS_LIBS},
     7779    {"CS_LFS_LIBS",     _CS_LFS_LIBS},
    74427780#endif
    74437781#ifdef _CS_LFS_LINTFLAGS
    7444     {"CS_LFS_LINTFLAGS",        _CS_LFS_LINTFLAGS},
     7782    {"CS_LFS_LINTFLAGS",        _CS_LFS_LINTFLAGS},
    74457783#endif
    74467784#ifdef _CS_MACHINE
    7447     {"CS_MACHINE",      _CS_MACHINE},
     7785    {"CS_MACHINE",      _CS_MACHINE},
    74487786#endif
    74497787#ifdef _CS_PATH
    7450     {"CS_PATH", _CS_PATH},
     7788    {"CS_PATH", _CS_PATH},
    74517789#endif
    74527790#ifdef _CS_RELEASE
    7453     {"CS_RELEASE",      _CS_RELEASE},
     7791    {"CS_RELEASE",      _CS_RELEASE},
    74547792#endif
    74557793#ifdef _CS_SRPC_DOMAIN
    7456     {"CS_SRPC_DOMAIN",  _CS_SRPC_DOMAIN},
     7794    {"CS_SRPC_DOMAIN",  _CS_SRPC_DOMAIN},
    74577795#endif
    74587796#ifdef _CS_SYSNAME
    7459     {"CS_SYSNAME",      _CS_SYSNAME},
     7797    {"CS_SYSNAME",      _CS_SYSNAME},
    74607798#endif
    74617799#ifdef _CS_VERSION
    7462     {"CS_VERSION",      _CS_VERSION},
     7800    {"CS_VERSION",      _CS_VERSION},
    74637801#endif
    74647802#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
    7465     {"CS_XBS5_ILP32_OFF32_CFLAGS",      _CS_XBS5_ILP32_OFF32_CFLAGS},
     7803    {"CS_XBS5_ILP32_OFF32_CFLAGS",      _CS_XBS5_ILP32_OFF32_CFLAGS},
    74667804#endif
    74677805#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
    7468     {"CS_XBS5_ILP32_OFF32_LDFLAGS",     _CS_XBS5_ILP32_OFF32_LDFLAGS},
     7806    {"CS_XBS5_ILP32_OFF32_LDFLAGS",     _CS_XBS5_ILP32_OFF32_LDFLAGS},
    74697807#endif
    74707808#ifdef _CS_XBS5_ILP32_OFF32_LIBS
    7471     {"CS_XBS5_ILP32_OFF32_LIBS",        _CS_XBS5_ILP32_OFF32_LIBS},
     7809    {"CS_XBS5_ILP32_OFF32_LIBS",        _CS_XBS5_ILP32_OFF32_LIBS},
    74727810#endif
    74737811#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
    7474     {"CS_XBS5_ILP32_OFF32_LINTFLAGS",   _CS_XBS5_ILP32_OFF32_LINTFLAGS},
     7812    {"CS_XBS5_ILP32_OFF32_LINTFLAGS",   _CS_XBS5_ILP32_OFF32_LINTFLAGS},
    74757813#endif
    74767814#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
    7477     {"CS_XBS5_ILP32_OFFBIG_CFLAGS",     _CS_XBS5_ILP32_OFFBIG_CFLAGS},
     7815    {"CS_XBS5_ILP32_OFFBIG_CFLAGS",     _CS_XBS5_ILP32_OFFBIG_CFLAGS},
    74787816#endif
    74797817#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
    7480     {"CS_XBS5_ILP32_OFFBIG_LDFLAGS",    _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
     7818    {"CS_XBS5_ILP32_OFFBIG_LDFLAGS",    _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
    74817819#endif
    74827820#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
    7483     {"CS_XBS5_ILP32_OFFBIG_LIBS",       _CS_XBS5_ILP32_OFFBIG_LIBS},
     7821    {"CS_XBS5_ILP32_OFFBIG_LIBS",       _CS_XBS5_ILP32_OFFBIG_LIBS},
    74847822#endif
    74857823#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
    7486     {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS",  _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
     7824    {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS",  _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
    74877825#endif
    74887826#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
    7489     {"CS_XBS5_LP64_OFF64_CFLAGS",       _CS_XBS5_LP64_OFF64_CFLAGS},
     7827    {"CS_XBS5_LP64_OFF64_CFLAGS",       _CS_XBS5_LP64_OFF64_CFLAGS},
    74907828#endif
    74917829#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
    7492     {"CS_XBS5_LP64_OFF64_LDFLAGS",      _CS_XBS5_LP64_OFF64_LDFLAGS},
     7830    {"CS_XBS5_LP64_OFF64_LDFLAGS",      _CS_XBS5_LP64_OFF64_LDFLAGS},
    74937831#endif
    74947832#ifdef _CS_XBS5_LP64_OFF64_LIBS
    7495     {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
     7833    {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
    74967834#endif
    74977835#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
    7498     {"CS_XBS5_LP64_OFF64_LINTFLAGS",    _CS_XBS5_LP64_OFF64_LINTFLAGS},
     7836    {"CS_XBS5_LP64_OFF64_LINTFLAGS",    _CS_XBS5_LP64_OFF64_LINTFLAGS},
    74997837#endif
    75007838#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
    7501     {"CS_XBS5_LPBIG_OFFBIG_CFLAGS",     _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
     7839    {"CS_XBS5_LPBIG_OFFBIG_CFLAGS",     _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
    75027840#endif
    75037841#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
    7504     {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS",    _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
     7842    {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS",    _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
    75057843#endif
    75067844#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
    7507     {"CS_XBS5_LPBIG_OFFBIG_LIBS",       _CS_XBS5_LPBIG_OFFBIG_LIBS},
     7845    {"CS_XBS5_LPBIG_OFFBIG_LIBS",       _CS_XBS5_LPBIG_OFFBIG_LIBS},
    75087846#endif
    75097847#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
    7510     {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS",  _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
     7848    {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS",  _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
    75117849#endif
    75127850#ifdef _MIPS_CS_AVAIL_PROCESSORS
    7513     {"MIPS_CS_AVAIL_PROCESSORS",        _MIPS_CS_AVAIL_PROCESSORS},
     7851    {"MIPS_CS_AVAIL_PROCESSORS",        _MIPS_CS_AVAIL_PROCESSORS},
    75147852#endif
    75157853#ifdef _MIPS_CS_BASE
    7516     {"MIPS_CS_BASE",    _MIPS_CS_BASE},
     7854    {"MIPS_CS_BASE",    _MIPS_CS_BASE},
    75177855#endif
    75187856#ifdef _MIPS_CS_HOSTID
    7519     {"MIPS_CS_HOSTID",  _MIPS_CS_HOSTID},
     7857    {"MIPS_CS_HOSTID",  _MIPS_CS_HOSTID},
    75207858#endif
    75217859#ifdef _MIPS_CS_HW_NAME
    7522     {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
     7860    {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
    75237861#endif
    75247862#ifdef _MIPS_CS_NUM_PROCESSORS
    7525     {"MIPS_CS_NUM_PROCESSORS",  _MIPS_CS_NUM_PROCESSORS},
     7863    {"MIPS_CS_NUM_PROCESSORS",  _MIPS_CS_NUM_PROCESSORS},
    75267864#endif
    75277865#ifdef _MIPS_CS_OSREL_MAJ
    7528     {"MIPS_CS_OSREL_MAJ",       _MIPS_CS_OSREL_MAJ},
     7866    {"MIPS_CS_OSREL_MAJ",       _MIPS_CS_OSREL_MAJ},
    75297867#endif
    75307868#ifdef _MIPS_CS_OSREL_MIN
    7531     {"MIPS_CS_OSREL_MIN",       _MIPS_CS_OSREL_MIN},
     7869    {"MIPS_CS_OSREL_MIN",       _MIPS_CS_OSREL_MIN},
    75327870#endif
    75337871#ifdef _MIPS_CS_OSREL_PATCH
    7534     {"MIPS_CS_OSREL_PATCH",     _MIPS_CS_OSREL_PATCH},
     7872    {"MIPS_CS_OSREL_PATCH",     _MIPS_CS_OSREL_PATCH},
    75357873#endif
    75367874#ifdef _MIPS_CS_OS_NAME
    7537     {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
     7875    {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
    75387876#endif
    75397877#ifdef _MIPS_CS_OS_PROVIDER
    7540     {"MIPS_CS_OS_PROVIDER",     _MIPS_CS_OS_PROVIDER},
     7878    {"MIPS_CS_OS_PROVIDER",     _MIPS_CS_OS_PROVIDER},
    75417879#endif
    75427880#ifdef _MIPS_CS_PROCESSORS
    7543     {"MIPS_CS_PROCESSORS",      _MIPS_CS_PROCESSORS},
     7881    {"MIPS_CS_PROCESSORS",      _MIPS_CS_PROCESSORS},
    75447882#endif
    75457883#ifdef _MIPS_CS_SERIAL
    7546     {"MIPS_CS_SERIAL",  _MIPS_CS_SERIAL},
     7884    {"MIPS_CS_SERIAL",  _MIPS_CS_SERIAL},
    75477885#endif
    75487886#ifdef _MIPS_CS_VENDOR
    7549     {"MIPS_CS_VENDOR",  _MIPS_CS_VENDOR},
     7887    {"MIPS_CS_VENDOR",  _MIPS_CS_VENDOR},
    75507888#endif
    75517889};
     
    75717909
    75727910    if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) {
    7573         int len;
    7574 
    7575         errno = 0;
    7576         len = confstr(name, buffer, sizeof(buffer));
    7577         if (len == 0) {
    7578             if (errno) {
    7579                 posix_error();
    7580             }
    7581             else {
    7582                 result = Py_None;
    7583                 Py_INCREF(Py_None);
    7584             }
     7911    int len;
     7912
     7913    errno = 0;
     7914    len = confstr(name, buffer, sizeof(buffer));
     7915    if (len == 0) {
     7916        if (errno) {
     7917        posix_error();
    75857918        }
    75867919        else {
    7587             if ((unsigned int)len >= sizeof(buffer)) {
    7588                 result = PyString_FromStringAndSize(NULL, len-1);
    7589                 if (result != NULL)
    7590                     confstr(name, PyString_AS_STRING(result), len);
    7591             }
    7592             else
    7593                 result = PyString_FromStringAndSize(buffer, len-1);
     7920        result = Py_None;
     7921        Py_INCREF(Py_None);
    75947922        }
     7923    }
     7924    else {
     7925        if ((unsigned int)len >= sizeof(buffer)) {
     7926        result = PyString_FromStringAndSize(NULL, len-1);
     7927        if (result != NULL)
     7928            confstr(name, PyString_AS_STRING(result), len);
     7929        }
     7930        else
     7931        result = PyString_FromStringAndSize(buffer, len-1);
     7932    }
    75957933    }
    75967934    return result;
     
    76027940static struct constdef posix_constants_sysconf[] = {
    76037941#ifdef _SC_2_CHAR_TERM
    7604     {"SC_2_CHAR_TERM",  _SC_2_CHAR_TERM},
     7942    {"SC_2_CHAR_TERM",  _SC_2_CHAR_TERM},
    76057943#endif
    76067944#ifdef _SC_2_C_BIND
    7607     {"SC_2_C_BIND",     _SC_2_C_BIND},
     7945    {"SC_2_C_BIND",     _SC_2_C_BIND},
    76087946#endif
    76097947#ifdef _SC_2_C_DEV
    7610     {"SC_2_C_DEV",      _SC_2_C_DEV},
     7948    {"SC_2_C_DEV",      _SC_2_C_DEV},
    76117949#endif
    76127950#ifdef _SC_2_C_VERSION
    7613     {"SC_2_C_VERSION",  _SC_2_C_VERSION},
     7951    {"SC_2_C_VERSION",  _SC_2_C_VERSION},
    76147952#endif
    76157953#ifdef _SC_2_FORT_DEV
    7616     {"SC_2_FORT_DEV",   _SC_2_FORT_DEV},
     7954    {"SC_2_FORT_DEV",   _SC_2_FORT_DEV},
    76177955#endif
    76187956#ifdef _SC_2_FORT_RUN
    7619     {"SC_2_FORT_RUN",   _SC_2_FORT_RUN},
     7957    {"SC_2_FORT_RUN",   _SC_2_FORT_RUN},
    76207958#endif
    76217959#ifdef _SC_2_LOCALEDEF
    7622     {"SC_2_LOCALEDEF",  _SC_2_LOCALEDEF},
     7960    {"SC_2_LOCALEDEF",  _SC_2_LOCALEDEF},
    76237961#endif
    76247962#ifdef _SC_2_SW_DEV
    7625     {"SC_2_SW_DEV",     _SC_2_SW_DEV},
     7963    {"SC_2_SW_DEV",     _SC_2_SW_DEV},
    76267964#endif
    76277965#ifdef _SC_2_UPE
    7628     {"SC_2_UPE",        _SC_2_UPE},
     7966    {"SC_2_UPE",        _SC_2_UPE},
    76297967#endif
    76307968#ifdef _SC_2_VERSION
    7631     {"SC_2_VERSION",    _SC_2_VERSION},
     7969    {"SC_2_VERSION",    _SC_2_VERSION},
    76327970#endif
    76337971#ifdef _SC_ABI_ASYNCHRONOUS_IO
    7634     {"SC_ABI_ASYNCHRONOUS_IO",  _SC_ABI_ASYNCHRONOUS_IO},
     7972    {"SC_ABI_ASYNCHRONOUS_IO",  _SC_ABI_ASYNCHRONOUS_IO},
    76357973#endif
    76367974#ifdef _SC_ACL
    7637     {"SC_ACL",  _SC_ACL},
     7975    {"SC_ACL",  _SC_ACL},
    76387976#endif
    76397977#ifdef _SC_AIO_LISTIO_MAX
    7640     {"SC_AIO_LISTIO_MAX",       _SC_AIO_LISTIO_MAX},
     7978    {"SC_AIO_LISTIO_MAX",       _SC_AIO_LISTIO_MAX},
    76417979#endif
    76427980#ifdef _SC_AIO_MAX
    7643     {"SC_AIO_MAX",      _SC_AIO_MAX},
     7981    {"SC_AIO_MAX",      _SC_AIO_MAX},
    76447982#endif
    76457983#ifdef _SC_AIO_PRIO_DELTA_MAX
    7646     {"SC_AIO_PRIO_DELTA_MAX",   _SC_AIO_PRIO_DELTA_MAX},
     7984    {"SC_AIO_PRIO_DELTA_MAX",   _SC_AIO_PRIO_DELTA_MAX},
    76477985#endif
    76487986#ifdef _SC_ARG_MAX
    7649     {"SC_ARG_MAX",      _SC_ARG_MAX},
     7987    {"SC_ARG_MAX",      _SC_ARG_MAX},
    76507988#endif
    76517989#ifdef _SC_ASYNCHRONOUS_IO
    7652     {"SC_ASYNCHRONOUS_IO",      _SC_ASYNCHRONOUS_IO},
     7990    {"SC_ASYNCHRONOUS_IO",      _SC_ASYNCHRONOUS_IO},
    76537991#endif
    76547992#ifdef _SC_ATEXIT_MAX
    7655     {"SC_ATEXIT_MAX",   _SC_ATEXIT_MAX},
     7993    {"SC_ATEXIT_MAX",   _SC_ATEXIT_MAX},
    76567994#endif
    76577995#ifdef _SC_AUDIT
    7658     {"SC_AUDIT",        _SC_AUDIT},
     7996    {"SC_AUDIT",        _SC_AUDIT},
    76597997#endif
    76607998#ifdef _SC_AVPHYS_PAGES
    7661     {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
     7999    {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
    76628000#endif
    76638001#ifdef _SC_BC_BASE_MAX
    7664     {"SC_BC_BASE_MAX",  _SC_BC_BASE_MAX},
     8002    {"SC_BC_BASE_MAX",  _SC_BC_BASE_MAX},
    76658003#endif
    76668004#ifdef _SC_BC_DIM_MAX
    7667     {"SC_BC_DIM_MAX",   _SC_BC_DIM_MAX},
     8005    {"SC_BC_DIM_MAX",   _SC_BC_DIM_MAX},
    76688006#endif
    76698007#ifdef _SC_BC_SCALE_MAX
    7670     {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
     8008    {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
    76718009#endif
    76728010#ifdef _SC_BC_STRING_MAX
    7673     {"SC_BC_STRING_MAX",        _SC_BC_STRING_MAX},
     8011    {"SC_BC_STRING_MAX",        _SC_BC_STRING_MAX},
    76748012#endif
    76758013#ifdef _SC_CAP
    7676     {"SC_CAP",  _SC_CAP},
     8014    {"SC_CAP",  _SC_CAP},
    76778015#endif
    76788016#ifdef _SC_CHARCLASS_NAME_MAX
    7679     {"SC_CHARCLASS_NAME_MAX",   _SC_CHARCLASS_NAME_MAX},
     8017    {"SC_CHARCLASS_NAME_MAX",   _SC_CHARCLASS_NAME_MAX},
    76808018#endif
    76818019#ifdef _SC_CHAR_BIT
    7682     {"SC_CHAR_BIT",     _SC_CHAR_BIT},
     8020    {"SC_CHAR_BIT",     _SC_CHAR_BIT},
    76838021#endif
    76848022#ifdef _SC_CHAR_MAX
    7685     {"SC_CHAR_MAX",     _SC_CHAR_MAX},
     8023    {"SC_CHAR_MAX",     _SC_CHAR_MAX},
    76868024#endif
    76878025#ifdef _SC_CHAR_MIN
    7688     {"SC_CHAR_MIN",     _SC_CHAR_MIN},
     8026    {"SC_CHAR_MIN",     _SC_CHAR_MIN},
    76898027#endif
    76908028#ifdef _SC_CHILD_MAX
    7691     {"SC_CHILD_MAX",    _SC_CHILD_MAX},
     8029    {"SC_CHILD_MAX",    _SC_CHILD_MAX},
    76928030#endif
    76938031#ifdef _SC_CLK_TCK
    7694     {"SC_CLK_TCK",      _SC_CLK_TCK},
     8032    {"SC_CLK_TCK",      _SC_CLK_TCK},
    76958033#endif
    76968034#ifdef _SC_COHER_BLKSZ
    7697     {"SC_COHER_BLKSZ",  _SC_COHER_BLKSZ},
     8035    {"SC_COHER_BLKSZ",  _SC_COHER_BLKSZ},
    76988036#endif
    76998037#ifdef _SC_COLL_WEIGHTS_MAX
    7700     {"SC_COLL_WEIGHTS_MAX",     _SC_COLL_WEIGHTS_MAX},
     8038    {"SC_COLL_WEIGHTS_MAX",     _SC_COLL_WEIGHTS_MAX},
    77018039#endif
    77028040#ifdef _SC_DCACHE_ASSOC
    7703     {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
     8041    {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
    77048042#endif
    77058043#ifdef _SC_DCACHE_BLKSZ
    7706     {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
     8044    {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
    77078045#endif
    77088046#ifdef _SC_DCACHE_LINESZ
    7709     {"SC_DCACHE_LINESZ",        _SC_DCACHE_LINESZ},
     8047    {"SC_DCACHE_LINESZ",        _SC_DCACHE_LINESZ},
    77108048#endif
    77118049#ifdef _SC_DCACHE_SZ
    7712     {"SC_DCACHE_SZ",    _SC_DCACHE_SZ},
     8050    {"SC_DCACHE_SZ",    _SC_DCACHE_SZ},
    77138051#endif
    77148052#ifdef _SC_DCACHE_TBLKSZ
    7715     {"SC_DCACHE_TBLKSZ",        _SC_DCACHE_TBLKSZ},
     8053    {"SC_DCACHE_TBLKSZ",        _SC_DCACHE_TBLKSZ},
    77168054#endif
    77178055#ifdef _SC_DELAYTIMER_MAX
    7718     {"SC_DELAYTIMER_MAX",       _SC_DELAYTIMER_MAX},
     8056    {"SC_DELAYTIMER_MAX",       _SC_DELAYTIMER_MAX},
    77198057#endif
    77208058#ifdef _SC_EQUIV_CLASS_MAX
    7721     {"SC_EQUIV_CLASS_MAX",      _SC_EQUIV_CLASS_MAX},
     8059    {"SC_EQUIV_CLASS_MAX",      _SC_EQUIV_CLASS_MAX},
    77228060#endif
    77238061#ifdef _SC_EXPR_NEST_MAX
    7724     {"SC_EXPR_NEST_MAX",        _SC_EXPR_NEST_MAX},
     8062    {"SC_EXPR_NEST_MAX",        _SC_EXPR_NEST_MAX},
    77258063#endif
    77268064#ifdef _SC_FSYNC
    7727     {"SC_FSYNC",        _SC_FSYNC},
     8065    {"SC_FSYNC",        _SC_FSYNC},
    77288066#endif
    77298067#ifdef _SC_GETGR_R_SIZE_MAX
    7730     {"SC_GETGR_R_SIZE_MAX",     _SC_GETGR_R_SIZE_MAX},
     8068    {"SC_GETGR_R_SIZE_MAX",     _SC_GETGR_R_SIZE_MAX},
    77318069#endif
    77328070#ifdef _SC_GETPW_R_SIZE_MAX
    7733     {"SC_GETPW_R_SIZE_MAX",     _SC_GETPW_R_SIZE_MAX},
     8071    {"SC_GETPW_R_SIZE_MAX",     _SC_GETPW_R_SIZE_MAX},
    77348072#endif
    77358073#ifdef _SC_ICACHE_ASSOC
    7736     {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
     8074    {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
    77378075#endif
    77388076#ifdef _SC_ICACHE_BLKSZ
    7739     {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
     8077    {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
    77408078#endif
    77418079#ifdef _SC_ICACHE_LINESZ
    7742     {"SC_ICACHE_LINESZ",        _SC_ICACHE_LINESZ},
     8080    {"SC_ICACHE_LINESZ",        _SC_ICACHE_LINESZ},
    77438081#endif
    77448082#ifdef _SC_ICACHE_SZ
    7745     {"SC_ICACHE_SZ",    _SC_ICACHE_SZ},
     8083    {"SC_ICACHE_SZ",    _SC_ICACHE_SZ},
    77468084#endif
    77478085#ifdef _SC_INF
    7748     {"SC_INF",  _SC_INF},
     8086    {"SC_INF",  _SC_INF},
    77498087#endif
    77508088#ifdef _SC_INT_MAX
    7751     {"SC_INT_MAX",      _SC_INT_MAX},
     8089    {"SC_INT_MAX",      _SC_INT_MAX},
    77528090#endif
    77538091#ifdef _SC_INT_MIN
    7754     {"SC_INT_MIN",      _SC_INT_MIN},
     8092    {"SC_INT_MIN",      _SC_INT_MIN},
    77558093#endif
    77568094#ifdef _SC_IOV_MAX
    7757     {"SC_IOV_MAX",      _SC_IOV_MAX},
     8095    {"SC_IOV_MAX",      _SC_IOV_MAX},
    77588096#endif
    77598097#ifdef _SC_IP_SECOPTS
    7760     {"SC_IP_SECOPTS",   _SC_IP_SECOPTS},
     8098    {"SC_IP_SECOPTS",   _SC_IP_SECOPTS},
    77618099#endif
    77628100#ifdef _SC_JOB_CONTROL
    7763     {"SC_JOB_CONTROL",  _SC_JOB_CONTROL},
     8101    {"SC_JOB_CONTROL",  _SC_JOB_CONTROL},
    77648102#endif
    77658103#ifdef _SC_KERN_POINTERS
    7766     {"SC_KERN_POINTERS",        _SC_KERN_POINTERS},
     8104    {"SC_KERN_POINTERS",        _SC_KERN_POINTERS},
    77678105#endif
    77688106#ifdef _SC_KERN_SIM
    7769     {"SC_KERN_SIM",     _SC_KERN_SIM},
     8107    {"SC_KERN_SIM",     _SC_KERN_SIM},
    77708108#endif
    77718109#ifdef _SC_LINE_MAX
    7772     {"SC_LINE_MAX",     _SC_LINE_MAX},
     8110    {"SC_LINE_MAX",     _SC_LINE_MAX},
    77738111#endif
    77748112#ifdef _SC_LOGIN_NAME_MAX
    7775     {"SC_LOGIN_NAME_MAX",       _SC_LOGIN_NAME_MAX},
     8113    {"SC_LOGIN_NAME_MAX",       _SC_LOGIN_NAME_MAX},
    77768114#endif
    77778115#ifdef _SC_LOGNAME_MAX
    7778     {"SC_LOGNAME_MAX",  _SC_LOGNAME_MAX},
     8116    {"SC_LOGNAME_MAX",  _SC_LOGNAME_MAX},
    77798117#endif
    77808118#ifdef _SC_LONG_BIT
    7781     {"SC_LONG_BIT",     _SC_LONG_BIT},
     8119    {"SC_LONG_BIT",     _SC_LONG_BIT},
    77828120#endif
    77838121#ifdef _SC_MAC
    7784     {"SC_MAC",  _SC_MAC},
     8122    {"SC_MAC",  _SC_MAC},
    77858123#endif
    77868124#ifdef _SC_MAPPED_FILES
    7787     {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
     8125    {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
    77888126#endif
    77898127#ifdef _SC_MAXPID
    7790     {"SC_MAXPID",       _SC_MAXPID},
     8128    {"SC_MAXPID",       _SC_MAXPID},
    77918129#endif
    77928130#ifdef _SC_MB_LEN_MAX
    7793     {"SC_MB_LEN_MAX",   _SC_MB_LEN_MAX},
     8131    {"SC_MB_LEN_MAX",   _SC_MB_LEN_MAX},
    77948132#endif
    77958133#ifdef _SC_MEMLOCK
    7796     {"SC_MEMLOCK",      _SC_MEMLOCK},
     8134    {"SC_MEMLOCK",      _SC_MEMLOCK},
    77978135#endif
    77988136#ifdef _SC_MEMLOCK_RANGE
    7799     {"SC_MEMLOCK_RANGE",        _SC_MEMLOCK_RANGE},
     8137    {"SC_MEMLOCK_RANGE",        _SC_MEMLOCK_RANGE},
    78008138#endif
    78018139#ifdef _SC_MEMORY_PROTECTION
    7802     {"SC_MEMORY_PROTECTION",    _SC_MEMORY_PROTECTION},
     8140    {"SC_MEMORY_PROTECTION",    _SC_MEMORY_PROTECTION},
    78038141#endif
    78048142#ifdef _SC_MESSAGE_PASSING
    7805     {"SC_MESSAGE_PASSING",      _SC_MESSAGE_PASSING},
     8143    {"SC_MESSAGE_PASSING",      _SC_MESSAGE_PASSING},
    78068144#endif
    78078145#ifdef _SC_MMAP_FIXED_ALIGNMENT
    7808     {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
     8146    {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
    78098147#endif
    78108148#ifdef _SC_MQ_OPEN_MAX
    7811     {"SC_MQ_OPEN_MAX",  _SC_MQ_OPEN_MAX},
     8149    {"SC_MQ_OPEN_MAX",  _SC_MQ_OPEN_MAX},
    78128150#endif
    78138151#ifdef _SC_MQ_PRIO_MAX
    7814     {"SC_MQ_PRIO_MAX",  _SC_MQ_PRIO_MAX},
     8152    {"SC_MQ_PRIO_MAX",  _SC_MQ_PRIO_MAX},
    78158153#endif
    78168154#ifdef _SC_NACLS_MAX
    7817     {"SC_NACLS_MAX",    _SC_NACLS_MAX},
     8155    {"SC_NACLS_MAX",    _SC_NACLS_MAX},
    78188156#endif
    78198157#ifdef _SC_NGROUPS_MAX
    7820     {"SC_NGROUPS_MAX",  _SC_NGROUPS_MAX},
     8158    {"SC_NGROUPS_MAX",  _SC_NGROUPS_MAX},
    78218159#endif
    78228160#ifdef _SC_NL_ARGMAX
    7823     {"SC_NL_ARGMAX",    _SC_NL_ARGMAX},
     8161    {"SC_NL_ARGMAX",    _SC_NL_ARGMAX},
    78248162#endif
    78258163#ifdef _SC_NL_LANGMAX
    7826     {"SC_NL_LANGMAX",   _SC_NL_LANGMAX},
     8164    {"SC_NL_LANGMAX",   _SC_NL_LANGMAX},
    78278165#endif
    78288166#ifdef _SC_NL_MSGMAX
    7829     {"SC_NL_MSGMAX",    _SC_NL_MSGMAX},
     8167    {"SC_NL_MSGMAX",    _SC_NL_MSGMAX},
    78308168#endif
    78318169#ifdef _SC_NL_NMAX
    7832     {"SC_NL_NMAX",      _SC_NL_NMAX},
     8170    {"SC_NL_NMAX",      _SC_NL_NMAX},
    78338171#endif
    78348172#ifdef _SC_NL_SETMAX
    7835     {"SC_NL_SETMAX",    _SC_NL_SETMAX},
     8173    {"SC_NL_SETMAX",    _SC_NL_SETMAX},
    78368174#endif
    78378175#ifdef _SC_NL_TEXTMAX
    7838     {"SC_NL_TEXTMAX",   _SC_NL_TEXTMAX},
     8176    {"SC_NL_TEXTMAX",   _SC_NL_TEXTMAX},
    78398177#endif
    78408178#ifdef _SC_NPROCESSORS_CONF
    7841     {"SC_NPROCESSORS_CONF",     _SC_NPROCESSORS_CONF},
     8179    {"SC_NPROCESSORS_CONF",     _SC_NPROCESSORS_CONF},
    78428180#endif
    78438181#ifdef _SC_NPROCESSORS_ONLN
    7844     {"SC_NPROCESSORS_ONLN",     _SC_NPROCESSORS_ONLN},
     8182    {"SC_NPROCESSORS_ONLN",     _SC_NPROCESSORS_ONLN},
    78458183#endif
    78468184#ifdef _SC_NPROC_CONF
    7847     {"SC_NPROC_CONF",   _SC_NPROC_CONF},
     8185    {"SC_NPROC_CONF",   _SC_NPROC_CONF},
    78488186#endif
    78498187#ifdef _SC_NPROC_ONLN
    7850     {"SC_NPROC_ONLN",   _SC_NPROC_ONLN},
     8188    {"SC_NPROC_ONLN",   _SC_NPROC_ONLN},
    78518189#endif
    78528190#ifdef _SC_NZERO
    7853     {"SC_NZERO",        _SC_NZERO},
     8191    {"SC_NZERO",        _SC_NZERO},
    78548192#endif
    78558193#ifdef _SC_OPEN_MAX
    7856     {"SC_OPEN_MAX",     _SC_OPEN_MAX},
     8194    {"SC_OPEN_MAX",     _SC_OPEN_MAX},
    78578195#endif
    78588196#ifdef _SC_PAGESIZE
    7859     {"SC_PAGESIZE",     _SC_PAGESIZE},
     8197    {"SC_PAGESIZE",     _SC_PAGESIZE},
    78608198#endif
    78618199#ifdef _SC_PAGE_SIZE
    7862     {"SC_PAGE_SIZE",    _SC_PAGE_SIZE},
     8200    {"SC_PAGE_SIZE",    _SC_PAGE_SIZE},
    78638201#endif
    78648202#ifdef _SC_PASS_MAX
    7865     {"SC_PASS_MAX",     _SC_PASS_MAX},
     8203    {"SC_PASS_MAX",     _SC_PASS_MAX},
    78668204#endif
    78678205#ifdef _SC_PHYS_PAGES
    7868     {"SC_PHYS_PAGES",   _SC_PHYS_PAGES},
     8206    {"SC_PHYS_PAGES",   _SC_PHYS_PAGES},
    78698207#endif
    78708208#ifdef _SC_PII
    7871     {"SC_PII",  _SC_PII},
     8209    {"SC_PII",  _SC_PII},
    78728210#endif
    78738211#ifdef _SC_PII_INTERNET
    7874     {"SC_PII_INTERNET", _SC_PII_INTERNET},
     8212    {"SC_PII_INTERNET", _SC_PII_INTERNET},
    78758213#endif
    78768214#ifdef _SC_PII_INTERNET_DGRAM
    7877     {"SC_PII_INTERNET_DGRAM",   _SC_PII_INTERNET_DGRAM},
     8215    {"SC_PII_INTERNET_DGRAM",   _SC_PII_INTERNET_DGRAM},
    78788216#endif
    78798217#ifdef _SC_PII_INTERNET_STREAM
    7880     {"SC_PII_INTERNET_STREAM",  _SC_PII_INTERNET_STREAM},
     8218    {"SC_PII_INTERNET_STREAM",  _SC_PII_INTERNET_STREAM},
    78818219#endif
    78828220#ifdef _SC_PII_OSI
    7883     {"SC_PII_OSI",      _SC_PII_OSI},
     8221    {"SC_PII_OSI",      _SC_PII_OSI},
    78848222#endif
    78858223#ifdef _SC_PII_OSI_CLTS
    7886     {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
     8224    {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
    78878225#endif
    78888226#ifdef _SC_PII_OSI_COTS
    7889     {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
     8227    {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
    78908228#endif
    78918229#ifdef _SC_PII_OSI_M
    7892     {"SC_PII_OSI_M",    _SC_PII_OSI_M},
     8230    {"SC_PII_OSI_M",    _SC_PII_OSI_M},
    78938231#endif
    78948232#ifdef _SC_PII_SOCKET
    7895     {"SC_PII_SOCKET",   _SC_PII_SOCKET},
     8233    {"SC_PII_SOCKET",   _SC_PII_SOCKET},
    78968234#endif
    78978235#ifdef _SC_PII_XTI
    7898     {"SC_PII_XTI",      _SC_PII_XTI},
     8236    {"SC_PII_XTI",      _SC_PII_XTI},
    78998237#endif
    79008238#ifdef _SC_POLL
    7901     {"SC_POLL", _SC_POLL},
     8239    {"SC_POLL", _SC_POLL},
    79028240#endif
    79038241#ifdef _SC_PRIORITIZED_IO
    7904     {"SC_PRIORITIZED_IO",       _SC_PRIORITIZED_IO},
     8242    {"SC_PRIORITIZED_IO",       _SC_PRIORITIZED_IO},
    79058243#endif
    79068244#ifdef _SC_PRIORITY_SCHEDULING
    7907     {"SC_PRIORITY_SCHEDULING",  _SC_PRIORITY_SCHEDULING},
     8245    {"SC_PRIORITY_SCHEDULING",  _SC_PRIORITY_SCHEDULING},
    79088246#endif
    79098247#ifdef _SC_REALTIME_SIGNALS
    7910     {"SC_REALTIME_SIGNALS",     _SC_REALTIME_SIGNALS},
     8248    {"SC_REALTIME_SIGNALS",     _SC_REALTIME_SIGNALS},
    79118249#endif
    79128250#ifdef _SC_RE_DUP_MAX
    7913     {"SC_RE_DUP_MAX",   _SC_RE_DUP_MAX},
     8251    {"SC_RE_DUP_MAX",   _SC_RE_DUP_MAX},
    79148252#endif
    79158253#ifdef _SC_RTSIG_MAX
    7916     {"SC_RTSIG_MAX",    _SC_RTSIG_MAX},
     8254    {"SC_RTSIG_MAX",    _SC_RTSIG_MAX},
    79178255#endif
    79188256#ifdef _SC_SAVED_IDS
    7919     {"SC_SAVED_IDS",    _SC_SAVED_IDS},
     8257    {"SC_SAVED_IDS",    _SC_SAVED_IDS},
    79208258#endif
    79218259#ifdef _SC_SCHAR_MAX
    7922     {"SC_SCHAR_MAX",    _SC_SCHAR_MAX},
     8260    {"SC_SCHAR_MAX",    _SC_SCHAR_MAX},
    79238261#endif
    79248262#ifdef _SC_SCHAR_MIN
    7925     {"SC_SCHAR_MIN",    _SC_SCHAR_MIN},
     8263    {"SC_SCHAR_MIN",    _SC_SCHAR_MIN},
    79268264#endif
    79278265#ifdef _SC_SELECT
    7928     {"SC_SELECT",       _SC_SELECT},
     8266    {"SC_SELECT",       _SC_SELECT},
    79298267#endif
    79308268#ifdef _SC_SEMAPHORES
    7931     {"SC_SEMAPHORES",   _SC_SEMAPHORES},
     8269    {"SC_SEMAPHORES",   _SC_SEMAPHORES},
    79328270#endif
    79338271#ifdef _SC_SEM_NSEMS_MAX
    7934     {"SC_SEM_NSEMS_MAX",        _SC_SEM_NSEMS_MAX},
     8272    {"SC_SEM_NSEMS_MAX",        _SC_SEM_NSEMS_MAX},
    79358273#endif
    79368274#ifdef _SC_SEM_VALUE_MAX
    7937     {"SC_SEM_VALUE_MAX",        _SC_SEM_VALUE_MAX},
     8275    {"SC_SEM_VALUE_MAX",        _SC_SEM_VALUE_MAX},
    79388276#endif
    79398277#ifdef _SC_SHARED_MEMORY_OBJECTS
    7940     {"SC_SHARED_MEMORY_OBJECTS",        _SC_SHARED_MEMORY_OBJECTS},
     8278    {"SC_SHARED_MEMORY_OBJECTS",        _SC_SHARED_MEMORY_OBJECTS},
    79418279#endif
    79428280#ifdef _SC_SHRT_MAX
    7943     {"SC_SHRT_MAX",     _SC_SHRT_MAX},
     8281    {"SC_SHRT_MAX",     _SC_SHRT_MAX},
    79448282#endif
    79458283#ifdef _SC_SHRT_MIN
    7946     {"SC_SHRT_MIN",     _SC_SHRT_MIN},
     8284    {"SC_SHRT_MIN",     _SC_SHRT_MIN},
    79478285#endif
    79488286#ifdef _SC_SIGQUEUE_MAX
    7949     {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
     8287    {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
    79508288#endif
    79518289#ifdef _SC_SIGRT_MAX
    7952     {"SC_SIGRT_MAX",    _SC_SIGRT_MAX},
     8290    {"SC_SIGRT_MAX",    _SC_SIGRT_MAX},
    79538291#endif
    79548292#ifdef _SC_SIGRT_MIN
    7955     {"SC_SIGRT_MIN",    _SC_SIGRT_MIN},
     8293    {"SC_SIGRT_MIN",    _SC_SIGRT_MIN},
    79568294#endif
    79578295#ifdef _SC_SOFTPOWER
    7958     {"SC_SOFTPOWER",    _SC_SOFTPOWER},
     8296    {"SC_SOFTPOWER",    _SC_SOFTPOWER},
    79598297#endif
    79608298#ifdef _SC_SPLIT_CACHE
    7961     {"SC_SPLIT_CACHE",  _SC_SPLIT_CACHE},
     8299    {"SC_SPLIT_CACHE",  _SC_SPLIT_CACHE},
    79628300#endif
    79638301#ifdef _SC_SSIZE_MAX
    7964     {"SC_SSIZE_MAX",    _SC_SSIZE_MAX},
     8302    {"SC_SSIZE_MAX",    _SC_SSIZE_MAX},
    79658303#endif
    79668304#ifdef _SC_STACK_PROT
    7967     {"SC_STACK_PROT",   _SC_STACK_PROT},
     8305    {"SC_STACK_PROT",   _SC_STACK_PROT},
    79688306#endif
    79698307#ifdef _SC_STREAM_MAX
    7970     {"SC_STREAM_MAX",   _SC_STREAM_MAX},
     8308    {"SC_STREAM_MAX",   _SC_STREAM_MAX},
    79718309#endif
    79728310#ifdef _SC_SYNCHRONIZED_IO
    7973     {"SC_SYNCHRONIZED_IO",      _SC_SYNCHRONIZED_IO},
     8311    {"SC_SYNCHRONIZED_IO",      _SC_SYNCHRONIZED_IO},
    79748312#endif
    79758313#ifdef _SC_THREADS
    7976     {"SC_THREADS",      _SC_THREADS},
     8314    {"SC_THREADS",      _SC_THREADS},
    79778315#endif
    79788316#ifdef _SC_THREAD_ATTR_STACKADDR
    7979     {"SC_THREAD_ATTR_STACKADDR",        _SC_THREAD_ATTR_STACKADDR},
     8317    {"SC_THREAD_ATTR_STACKADDR",        _SC_THREAD_ATTR_STACKADDR},
    79808318#endif
    79818319#ifdef _SC_THREAD_ATTR_STACKSIZE
    7982     {"SC_THREAD_ATTR_STACKSIZE",        _SC_THREAD_ATTR_STACKSIZE},
     8320    {"SC_THREAD_ATTR_STACKSIZE",        _SC_THREAD_ATTR_STACKSIZE},
    79838321#endif
    79848322#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
    7985     {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
     8323    {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
    79868324#endif
    79878325#ifdef _SC_THREAD_KEYS_MAX
    7988     {"SC_THREAD_KEYS_MAX",      _SC_THREAD_KEYS_MAX},
     8326    {"SC_THREAD_KEYS_MAX",      _SC_THREAD_KEYS_MAX},
    79898327#endif
    79908328#ifdef _SC_THREAD_PRIORITY_SCHEDULING
    7991     {"SC_THREAD_PRIORITY_SCHEDULING",   _SC_THREAD_PRIORITY_SCHEDULING},
     8329    {"SC_THREAD_PRIORITY_SCHEDULING",   _SC_THREAD_PRIORITY_SCHEDULING},
    79928330#endif
    79938331#ifdef _SC_THREAD_PRIO_INHERIT
    7994     {"SC_THREAD_PRIO_INHERIT",  _SC_THREAD_PRIO_INHERIT},
     8332    {"SC_THREAD_PRIO_INHERIT",  _SC_THREAD_PRIO_INHERIT},
    79958333#endif
    79968334#ifdef _SC_THREAD_PRIO_PROTECT
    7997     {"SC_THREAD_PRIO_PROTECT",  _SC_THREAD_PRIO_PROTECT},
     8335    {"SC_THREAD_PRIO_PROTECT",  _SC_THREAD_PRIO_PROTECT},
    79988336#endif
    79998337#ifdef _SC_THREAD_PROCESS_SHARED
    8000     {"SC_THREAD_PROCESS_SHARED",        _SC_THREAD_PROCESS_SHARED},
     8338    {"SC_THREAD_PROCESS_SHARED",        _SC_THREAD_PROCESS_SHARED},
    80018339#endif
    80028340#ifdef _SC_THREAD_SAFE_FUNCTIONS
    8003     {"SC_THREAD_SAFE_FUNCTIONS",        _SC_THREAD_SAFE_FUNCTIONS},
     8341    {"SC_THREAD_SAFE_FUNCTIONS",        _SC_THREAD_SAFE_FUNCTIONS},
    80048342#endif
    80058343#ifdef _SC_THREAD_STACK_MIN
    8006     {"SC_THREAD_STACK_MIN",     _SC_THREAD_STACK_MIN},
     8344    {"SC_THREAD_STACK_MIN",     _SC_THREAD_STACK_MIN},
    80078345#endif
    80088346#ifdef _SC_THREAD_THREADS_MAX
    8009     {"SC_THREAD_THREADS_MAX",   _SC_THREAD_THREADS_MAX},
     8347    {"SC_THREAD_THREADS_MAX",   _SC_THREAD_THREADS_MAX},
    80108348#endif
    80118349#ifdef _SC_TIMERS
    8012     {"SC_TIMERS",       _SC_TIMERS},
     8350    {"SC_TIMERS",       _SC_TIMERS},
    80138351#endif
    80148352#ifdef _SC_TIMER_MAX
    8015     {"SC_TIMER_MAX",    _SC_TIMER_MAX},
     8353    {"SC_TIMER_MAX",    _SC_TIMER_MAX},
    80168354#endif
    80178355#ifdef _SC_TTY_NAME_MAX
    8018     {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
     8356    {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
    80198357#endif
    80208358#ifdef _SC_TZNAME_MAX
    8021     {"SC_TZNAME_MAX",   _SC_TZNAME_MAX},
     8359    {"SC_TZNAME_MAX",   _SC_TZNAME_MAX},
    80228360#endif
    80238361#ifdef _SC_T_IOV_MAX
    8024     {"SC_T_IOV_MAX",    _SC_T_IOV_MAX},
     8362    {"SC_T_IOV_MAX",    _SC_T_IOV_MAX},
    80258363#endif
    80268364#ifdef _SC_UCHAR_MAX
    8027     {"SC_UCHAR_MAX",    _SC_UCHAR_MAX},
     8365    {"SC_UCHAR_MAX",    _SC_UCHAR_MAX},
    80288366#endif
    80298367#ifdef _SC_UINT_MAX
    8030     {"SC_UINT_MAX",     _SC_UINT_MAX},
     8368    {"SC_UINT_MAX",     _SC_UINT_MAX},
    80318369#endif
    80328370#ifdef _SC_UIO_MAXIOV
    8033     {"SC_UIO_MAXIOV",   _SC_UIO_MAXIOV},
     8371    {"SC_UIO_MAXIOV",   _SC_UIO_MAXIOV},
    80348372#endif
    80358373#ifdef _SC_ULONG_MAX
    8036     {"SC_ULONG_MAX",    _SC_ULONG_MAX},
     8374    {"SC_ULONG_MAX",    _SC_ULONG_MAX},
    80378375#endif
    80388376#ifdef _SC_USHRT_MAX
    8039     {"SC_USHRT_MAX",    _SC_USHRT_MAX},
     8377    {"SC_USHRT_MAX",    _SC_USHRT_MAX},
    80408378#endif
    80418379#ifdef _SC_VERSION
    8042     {"SC_VERSION",      _SC_VERSION},
     8380    {"SC_VERSION",      _SC_VERSION},
    80438381#endif
    80448382#ifdef _SC_WORD_BIT
    8045     {"SC_WORD_BIT",     _SC_WORD_BIT},
     8383    {"SC_WORD_BIT",     _SC_WORD_BIT},
    80468384#endif
    80478385#ifdef _SC_XBS5_ILP32_OFF32
    8048     {"SC_XBS5_ILP32_OFF32",     _SC_XBS5_ILP32_OFF32},
     8386    {"SC_XBS5_ILP32_OFF32",     _SC_XBS5_ILP32_OFF32},
    80498387#endif
    80508388#ifdef _SC_XBS5_ILP32_OFFBIG
    8051     {"SC_XBS5_ILP32_OFFBIG",    _SC_XBS5_ILP32_OFFBIG},
     8389    {"SC_XBS5_ILP32_OFFBIG",    _SC_XBS5_ILP32_OFFBIG},
    80528390#endif
    80538391#ifdef _SC_XBS5_LP64_OFF64
    8054     {"SC_XBS5_LP64_OFF64",      _SC_XBS5_LP64_OFF64},
     8392    {"SC_XBS5_LP64_OFF64",      _SC_XBS5_LP64_OFF64},
    80558393#endif
    80568394#ifdef _SC_XBS5_LPBIG_OFFBIG
    8057     {"SC_XBS5_LPBIG_OFFBIG",    _SC_XBS5_LPBIG_OFFBIG},
     8395    {"SC_XBS5_LPBIG_OFFBIG",    _SC_XBS5_LPBIG_OFFBIG},
    80588396#endif
    80598397#ifdef _SC_XOPEN_CRYPT
    8060     {"SC_XOPEN_CRYPT",  _SC_XOPEN_CRYPT},
     8398    {"SC_XOPEN_CRYPT",  _SC_XOPEN_CRYPT},
    80618399#endif
    80628400#ifdef _SC_XOPEN_ENH_I18N
    8063     {"SC_XOPEN_ENH_I18N",       _SC_XOPEN_ENH_I18N},
     8401    {"SC_XOPEN_ENH_I18N",       _SC_XOPEN_ENH_I18N},
    80648402#endif
    80658403#ifdef _SC_XOPEN_LEGACY
    8066     {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
     8404    {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
    80678405#endif
    80688406#ifdef _SC_XOPEN_REALTIME
    8069     {"SC_XOPEN_REALTIME",       _SC_XOPEN_REALTIME},
     8407    {"SC_XOPEN_REALTIME",       _SC_XOPEN_REALTIME},
    80708408#endif
    80718409#ifdef _SC_XOPEN_REALTIME_THREADS
    8072     {"SC_XOPEN_REALTIME_THREADS",       _SC_XOPEN_REALTIME_THREADS},
     8410    {"SC_XOPEN_REALTIME_THREADS",       _SC_XOPEN_REALTIME_THREADS},
    80738411#endif
    80748412#ifdef _SC_XOPEN_SHM
    8075     {"SC_XOPEN_SHM",    _SC_XOPEN_SHM},
     8413    {"SC_XOPEN_SHM",    _SC_XOPEN_SHM},
    80768414#endif
    80778415#ifdef _SC_XOPEN_UNIX
    8078     {"SC_XOPEN_UNIX",   _SC_XOPEN_UNIX},
     8416    {"SC_XOPEN_UNIX",   _SC_XOPEN_UNIX},
    80798417#endif
    80808418#ifdef _SC_XOPEN_VERSION
    8081     {"SC_XOPEN_VERSION",        _SC_XOPEN_VERSION},
     8419    {"SC_XOPEN_VERSION",        _SC_XOPEN_VERSION},
    80828420#endif
    80838421#ifdef _SC_XOPEN_XCU_VERSION
    8084     {"SC_XOPEN_XCU_VERSION",    _SC_XOPEN_XCU_VERSION},
     8422    {"SC_XOPEN_XCU_VERSION",    _SC_XOPEN_XCU_VERSION},
    80858423#endif
    80868424#ifdef _SC_XOPEN_XPG2
    8087     {"SC_XOPEN_XPG2",   _SC_XOPEN_XPG2},
     8425    {"SC_XOPEN_XPG2",   _SC_XOPEN_XPG2},
    80888426#endif
    80898427#ifdef _SC_XOPEN_XPG3
    8090     {"SC_XOPEN_XPG3",   _SC_XOPEN_XPG3},
     8428    {"SC_XOPEN_XPG3",   _SC_XOPEN_XPG3},
    80918429#endif
    80928430#ifdef _SC_XOPEN_XPG4
    8093     {"SC_XOPEN_XPG4",   _SC_XOPEN_XPG4},
     8431    {"SC_XOPEN_XPG4",   _SC_XOPEN_XPG4},
    80948432#endif
    80958433};
     
    81428480{
    81438481    const struct constdef *c1 =
    8144         (const struct constdef *) v1;
     8482    (const struct constdef *) v1;
    81458483    const struct constdef *c2 =
    8146         (const struct constdef *) v2;
     8484    (const struct constdef *) v2;
    81478485
    81488486    return strcmp(c1->name, c2->name);
     
    81518489static int
    81528490setup_confname_table(struct constdef *table, size_t tablesize,
    8153                      char *tablename, PyObject *module)
     8491                     char *tablename, PyObject *module)
    81548492{
    81558493    PyObject *d = NULL;
     
    81598497    d = PyDict_New();
    81608498    if (d == NULL)
    8161             return -1;
     8499        return -1;
    81628500
    81638501    for (i=0; i < tablesize; ++i) {
    8164             PyObject *o = PyInt_FromLong(table[i].value);
    8165             if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
    8166                     Py_XDECREF(o);
    8167                     Py_DECREF(d);
    8168                     return -1;
    8169             }
    8170             Py_DECREF(o);
     8502        PyObject *o = PyInt_FromLong(table[i].value);
     8503        if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
     8504            Py_XDECREF(o);
     8505            Py_DECREF(d);
     8506            return -1;
     8507        }
     8508        Py_DECREF(o);
    81718509    }
    81728510    return PyModule_AddObject(module, tablename, d);
     
    82398577win32_startfile(PyObject *self, PyObject *args)
    82408578{
    8241         char *filepath;
    8242         char *operation = NULL;
    8243         HINSTANCE rc;
    8244 #ifdef Py_WIN_WIDE_FILENAMES
    8245         if (unicode_file_names()) {
    8246                 PyObject *unipath, *woperation = NULL;
    8247                 if (!PyArg_ParseTuple(args, "U|s:startfile",
    8248                                       &unipath, &operation)) {
    8249                         PyErr_Clear();
    8250                         goto normal;
    8251                 }
    8252                
    8253 
    8254                 if (operation) {
    8255                     woperation = PyUnicode_DecodeASCII(operation,
    8256                                                        strlen(operation), NULL);
    8257                     if (!woperation) {
    8258                             PyErr_Clear();
    8259                             operation = NULL;
    8260                             goto normal;
    8261                     }
    8262                 }
    8263                        
    8264                 Py_BEGIN_ALLOW_THREADS
    8265                 rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0,
    8266                         PyUnicode_AS_UNICODE(unipath),
    8267                         NULL, NULL, SW_SHOWNORMAL);
    8268                 Py_END_ALLOW_THREADS
    8269 
    8270                 Py_XDECREF(woperation);
    8271                 if (rc <= (HINSTANCE)32) {
    8272                         PyObject *errval = win32_error_unicode("startfile",
    8273                                                 PyUnicode_AS_UNICODE(unipath));
    8274                         return errval;
    8275                 }
    8276                 Py_INCREF(Py_None);
    8277                 return Py_None;
    8278         }
    8279 #endif
     8579    char *filepath;
     8580    char *operation = NULL;
     8581    HINSTANCE rc;
     8582
     8583    PyObject *unipath, *woperation = NULL;
     8584    if (!PyArg_ParseTuple(args, "U|s:startfile",
     8585                          &unipath, &operation)) {
     8586        PyErr_Clear();
     8587        goto normal;
     8588    }
     8589
     8590    if (operation) {
     8591        woperation = PyUnicode_DecodeASCII(operation,
     8592                                           strlen(operation), NULL);
     8593        if (!woperation) {
     8594            PyErr_Clear();
     8595            operation = NULL;
     8596            goto normal;
     8597        }
     8598    }
     8599
     8600    Py_BEGIN_ALLOW_THREADS
     8601    rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0,
     8602        PyUnicode_AS_UNICODE(unipath),
     8603        NULL, NULL, SW_SHOWNORMAL);
     8604    Py_END_ALLOW_THREADS
     8605
     8606    Py_XDECREF(woperation);
     8607    if (rc <= (HINSTANCE)32) {
     8608        PyObject *errval = win32_error_unicode("startfile",
     8609                                               PyUnicode_AS_UNICODE(unipath));
     8610        return errval;
     8611    }
     8612    Py_INCREF(Py_None);
     8613    return Py_None;
    82808614
    82818615normal:
    8282         if (!PyArg_ParseTuple(args, "et|s:startfile",
    8283                               Py_FileSystemDefaultEncoding, &filepath,
    8284                               &operation))
    8285                 return NULL;
    8286         Py_BEGIN_ALLOW_THREADS
    8287         rc = ShellExecute((HWND)0, operation, filepath,
    8288                           NULL, NULL, SW_SHOWNORMAL);
    8289         Py_END_ALLOW_THREADS
    8290         if (rc <= (HINSTANCE)32) {
    8291                 PyObject *errval = win32_error("startfile", filepath);
    8292                 PyMem_Free(filepath);
    8293                 return errval;
    8294         }
    8295         PyMem_Free(filepath);
    8296         Py_INCREF(Py_None);
    8297         return Py_None;
    8298 }
    8299 #endif
     8616    if (!PyArg_ParseTuple(args, "et|s:startfile",
     8617                          Py_FileSystemDefaultEncoding, &filepath,
     8618                          &operation))
     8619        return NULL;
     8620    Py_BEGIN_ALLOW_THREADS
     8621    rc = ShellExecute((HWND)0, operation, filepath,
     8622                      NULL, NULL, SW_SHOWNORMAL);
     8623    Py_END_ALLOW_THREADS
     8624    if (rc <= (HINSTANCE)32) {
     8625        PyObject *errval = win32_error("startfile", filepath);
     8626        PyMem_Free(filepath);
     8627        return errval;
     8628    }
     8629    PyMem_Free(filepath);
     8630    Py_INCREF(Py_None);
     8631    return Py_None;
     8632}
     8633#endif /* MS_WINDOWS */
    83008634
    83018635#ifdef HAVE_GETLOADAVG
     
    83188652#endif
    83198653
    8320 #ifdef MS_WINDOWS
    8321 
    8322 PyDoc_STRVAR(win32_urandom__doc__,
     8654PyDoc_STRVAR(posix_urandom__doc__,
    83238655"urandom(n) -> str\n\n\
    8324 Return a string of n random bytes suitable for cryptographic use.");
    8325 
    8326 typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\
    8327               LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\
    8328               DWORD dwFlags );
    8329 typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\
    8330               BYTE *pbBuffer );
    8331 
    8332 static CRYPTGENRANDOM pCryptGenRandom = NULL;
    8333 /* This handle is never explicitly released. Instead, the operating
    8334    system will release it when the process terminates. */
    8335 static HCRYPTPROV hCryptProv = 0;
     8656Return n random bytes suitable for cryptographic use.");
     8657
     8658static PyObject *
     8659posix_urandom(PyObject *self, PyObject *args)
     8660{
     8661    Py_ssize_t size;
     8662    PyObject *result;
     8663    int ret;
     8664
     8665     /* Read arguments */
     8666    if (!PyArg_ParseTuple(args, "n:urandom", &size))
     8667        return NULL;
     8668    if (size < 0)
     8669        return PyErr_Format(PyExc_ValueError,
     8670                            "negative argument not allowed");
     8671    result = PyBytes_FromStringAndSize(NULL, size);
     8672    if (result == NULL)
     8673        return NULL;
     8674
     8675    ret = _PyOS_URandom(PyBytes_AS_STRING(result),
     8676                        PyBytes_GET_SIZE(result));
     8677    if (ret == -1) {
     8678        Py_DECREF(result);
     8679        return NULL;
     8680    }
     8681    return result;
     8682}
     8683
     8684#ifdef HAVE_SETRESUID
     8685PyDoc_STRVAR(posix_setresuid__doc__,
     8686"setresuid(ruid, euid, suid)\n\n\
     8687Set the current process's real, effective, and saved user ids.");
    83368688
    83378689static PyObject*
    8338 win32_urandom(PyObject *self, PyObject *args)
    8339 {
    8340         int howMany;
    8341         PyObject* result;
    8342 
    8343         /* Read arguments */
    8344         if (! PyArg_ParseTuple(args, "i:urandom", &howMany))
    8345                 return NULL;
    8346         if (howMany < 0)
    8347                 return PyErr_Format(PyExc_ValueError,
    8348                                     "negative argument not allowed");
    8349 
    8350         if (hCryptProv == 0) {
    8351                 HINSTANCE hAdvAPI32 = NULL;
    8352                 CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL;
    8353 
    8354                 /* Obtain handle to the DLL containing CryptoAPI
    8355                    This should not fail */
    8356                 hAdvAPI32 = GetModuleHandle("advapi32.dll");
    8357                 if(hAdvAPI32 == NULL)
    8358                         return win32_error("GetModuleHandle", NULL);
    8359 
    8360                 /* Obtain pointers to the CryptoAPI functions
    8361                    This will fail on some early versions of Win95 */
    8362                 pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress(
    8363                                                 hAdvAPI32,
    8364                                                 "CryptAcquireContextA");
    8365                 if (pCryptAcquireContext == NULL)
    8366                         return PyErr_Format(PyExc_NotImplementedError,
    8367                                             "CryptAcquireContextA not found");
    8368 
    8369                 pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress(
    8370                                                 hAdvAPI32, "CryptGenRandom");
    8371                 if (pCryptGenRandom == NULL)
    8372                         return PyErr_Format(PyExc_NotImplementedError,
    8373                                             "CryptGenRandom not found");
    8374 
    8375                 /* Acquire context */
    8376                 if (! pCryptAcquireContext(&hCryptProv, NULL, NULL,
    8377                                            PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
    8378                         return win32_error("CryptAcquireContext", NULL);
    8379         }
    8380 
    8381         /* Allocate bytes */
    8382         result = PyString_FromStringAndSize(NULL, howMany);
    8383         if (result != NULL) {
    8384                 /* Get random data */
    8385                 memset(PyString_AS_STRING(result), 0, howMany); /* zero seed */
    8386                 if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*)
    8387                                       PyString_AS_STRING(result))) {
    8388                         Py_DECREF(result);
    8389                         return win32_error("CryptGenRandom", NULL);
    8390                 }
    8391         }
    8392         return result;
    8393 }
    8394 #endif
    8395 
    8396 #ifdef __VMS
    8397 /* Use openssl random routine */
    8398 #include <openssl/rand.h>
    8399 PyDoc_STRVAR(vms_urandom__doc__,
    8400 "urandom(n) -> str\n\n\
    8401 Return a string of n random bytes suitable for cryptographic use.");
     8690posix_setresuid (PyObject *self, PyObject *args)
     8691{
     8692    uid_t ruid, euid, suid;
     8693    if (!PyArg_ParseTuple(args, "O&O&O&:setresuid",
     8694                          _Py_Uid_Converter, &ruid,
     8695                          _Py_Uid_Converter, &euid,
     8696                          _Py_Uid_Converter, &suid))
     8697        return NULL;
     8698    if (setresuid(ruid, euid, suid) < 0)
     8699        return posix_error();
     8700    Py_RETURN_NONE;
     8701}
     8702#endif
     8703
     8704#ifdef HAVE_SETRESGID
     8705PyDoc_STRVAR(posix_setresgid__doc__,
     8706"setresgid(rgid, egid, sgid)\n\n\
     8707Set the current process's real, effective, and saved group ids.");
    84028708
    84038709static PyObject*
    8404 vms_urandom(PyObject *self, PyObject *args)
    8405 {
    8406         int howMany;
    8407         PyObject* result;
    8408 
    8409         /* Read arguments */
    8410         if (! PyArg_ParseTuple(args, "i:urandom", &howMany))
    8411                 return NULL;
    8412         if (howMany < 0)
    8413                 return PyErr_Format(PyExc_ValueError,
    8414                                     "negative argument not allowed");
    8415 
    8416         /* Allocate bytes */
    8417         result = PyString_FromStringAndSize(NULL, howMany);
    8418         if (result != NULL) {
    8419                 /* Get random data */
    8420                 if (RAND_pseudo_bytes((unsigned char*)
    8421                                       PyString_AS_STRING(result),
    8422                                       howMany) < 0) {
    8423                         Py_DECREF(result);
    8424                         return PyErr_Format(PyExc_ValueError,
    8425                                             "RAND_pseudo_bytes");
    8426                 }
    8427         }
    8428         return result;
     8710posix_setresgid (PyObject *self, PyObject *args)
     8711{
     8712    gid_t rgid, egid, sgid;
     8713    if (!PyArg_ParseTuple(args, "O&O&O&:setresgid",
     8714                          _Py_Gid_Converter, &rgid,
     8715                          _Py_Gid_Converter, &egid,
     8716                          _Py_Gid_Converter, &sgid))
     8717        return NULL;
     8718    if (setresgid(rgid, egid, sgid) < 0)
     8719        return posix_error();
     8720    Py_RETURN_NONE;
     8721}
     8722#endif
     8723
     8724#ifdef HAVE_GETRESUID
     8725PyDoc_STRVAR(posix_getresuid__doc__,
     8726"getresuid() -> (ruid, euid, suid)\n\n\
     8727Get tuple of the current process's real, effective, and saved user ids.");
     8728
     8729static PyObject*
     8730posix_getresuid (PyObject *self, PyObject *noargs)
     8731{
     8732    uid_t ruid, euid, suid;
     8733    if (getresuid(&ruid, &euid, &suid) < 0)
     8734        return posix_error();
     8735    return Py_BuildValue("(NNN)", _PyInt_FromUid(ruid),
     8736                                  _PyInt_FromUid(euid),
     8737                                  _PyInt_FromUid(suid));
     8738}
     8739#endif
     8740
     8741#ifdef HAVE_GETRESGID
     8742PyDoc_STRVAR(posix_getresgid__doc__,
     8743"getresgid() -> (rgid, egid, sgid)\n\n\
     8744Get tuple of the current process's real, effective, and saved group ids.");
     8745
     8746static PyObject*
     8747posix_getresgid (PyObject *self, PyObject *noargs)
     8748{
     8749    uid_t rgid, egid, sgid;
     8750    if (getresgid(&rgid, &egid, &sgid) < 0)
     8751        return posix_error();
     8752    return Py_BuildValue("(NNN)", _PyInt_FromGid(rgid),
     8753                                  _PyInt_FromGid(egid),
     8754                                  _PyInt_FromGid(sgid));
    84298755}
    84308756#endif
    84318757
    84328758static PyMethodDef posix_methods[] = {
    8433         {"access",      posix_access, METH_VARARGS, posix_access__doc__},
     8759    {"access",          posix_access, METH_VARARGS, posix_access__doc__},
    84348760#ifdef HAVE_TTYNAME
    8435         {"ttyname",     posix_ttyname, METH_VARARGS, posix_ttyname__doc__},
    8436 #endif
    8437         {"chdir",       posix_chdir, METH_VARARGS, posix_chdir__doc__},
     8761    {"ttyname",         posix_ttyname, METH_VARARGS, posix_ttyname__doc__},
     8762#endif
     8763    {"chdir",           posix_chdir, METH_VARARGS, posix_chdir__doc__},
    84388764#ifdef HAVE_CHFLAGS
    8439         {"chflags",     posix_chflags, METH_VARARGS, posix_chflags__doc__},
     8765    {"chflags",         posix_chflags, METH_VARARGS, posix_chflags__doc__},
    84408766#endif /* HAVE_CHFLAGS */
    8441         {"chmod",       posix_chmod, METH_VARARGS, posix_chmod__doc__},
     8767    {"chmod",           posix_chmod, METH_VARARGS, posix_chmod__doc__},
    84428768#ifdef HAVE_FCHMOD
    8443         {"fchmod",      posix_fchmod, METH_VARARGS, posix_fchmod__doc__},
     8769    {"fchmod",          posix_fchmod, METH_VARARGS, posix_fchmod__doc__},
    84448770#endif /* HAVE_FCHMOD */
    84458771#ifdef HAVE_CHOWN
    8446         {"chown",       posix_chown, METH_VARARGS, posix_chown__doc__},
     8772    {"chown",           posix_chown, METH_VARARGS, posix_chown__doc__},
    84478773#endif /* HAVE_CHOWN */
    84488774#ifdef HAVE_LCHMOD
    8449         {"lchmod",      posix_lchmod, METH_VARARGS, posix_lchmod__doc__},
     8775    {"lchmod",          posix_lchmod, METH_VARARGS, posix_lchmod__doc__},
    84508776#endif /* HAVE_LCHMOD */
    84518777#ifdef HAVE_FCHOWN
    8452         {"fchown",      posix_fchown, METH_VARARGS, posix_fchown__doc__},
     8778    {"fchown",          posix_fchown, METH_VARARGS, posix_fchown__doc__},
    84538779#endif /* HAVE_FCHOWN */
    84548780#ifdef HAVE_LCHFLAGS
    8455         {"lchflags",    posix_lchflags, METH_VARARGS, posix_lchflags__doc__},
     8781    {"lchflags",        posix_lchflags, METH_VARARGS, posix_lchflags__doc__},
    84568782#endif /* HAVE_LCHFLAGS */
    84578783#ifdef HAVE_LCHOWN
    8458         {"lchown",      posix_lchown, METH_VARARGS, posix_lchown__doc__},
     8784    {"lchown",          posix_lchown, METH_VARARGS, posix_lchown__doc__},
    84598785#endif /* HAVE_LCHOWN */
    84608786#ifdef HAVE_CHROOT
    8461         {"chroot",      posix_chroot, METH_VARARGS, posix_chroot__doc__},
     8787    {"chroot",          posix_chroot, METH_VARARGS, posix_chroot__doc__},
    84628788#endif
    84638789#ifdef HAVE_CTERMID
    8464         {"ctermid",     posix_ctermid, METH_NOARGS, posix_ctermid__doc__},
     8790    {"ctermid",         posix_ctermid, METH_NOARGS, posix_ctermid__doc__},
    84658791#endif
    84668792#ifdef HAVE_GETCWD
    8467         {"getcwd",      posix_getcwd, METH_NOARGS, posix_getcwd__doc__},
     8793    {"getcwd",          posix_getcwd, METH_NOARGS, posix_getcwd__doc__},
    84688794#ifdef Py_USING_UNICODE
    8469         {"getcwdu",     posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__},
     8795    {"getcwdu",         posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__},
    84708796#endif
    84718797#endif
    84728798#ifdef HAVE_LINK
    8473         {"link",        posix_link, METH_VARARGS, posix_link__doc__},
     8799    {"link",            posix_link, METH_VARARGS, posix_link__doc__},
    84748800#endif /* HAVE_LINK */
    8475         {"listdir",     posix_listdir, METH_VARARGS, posix_listdir__doc__},
    8476         {"lstat",       posix_lstat, METH_VARARGS, posix_lstat__doc__},
    8477         {"mkdir",       posix_mkdir, METH_VARARGS, posix_mkdir__doc__},
     8801    {"listdir",         posix_listdir, METH_VARARGS, posix_listdir__doc__},
     8802    {"lstat",           posix_lstat, METH_VARARGS, posix_lstat__doc__},
     8803    {"mkdir",           posix_mkdir, METH_VARARGS, posix_mkdir__doc__},
    84788804#ifdef HAVE_NICE
    8479         {"nice",        posix_nice, METH_VARARGS, posix_nice__doc__},
     8805    {"nice",            posix_nice, METH_VARARGS, posix_nice__doc__},
    84808806#endif /* HAVE_NICE */
    84818807#ifdef HAVE_READLINK
    8482         {"readlink",    posix_readlink, METH_VARARGS, posix_readlink__doc__},
     8808    {"readlink",        posix_readlink, METH_VARARGS, posix_readlink__doc__},
    84838809#endif /* HAVE_READLINK */
    8484         {"rename",      posix_rename, METH_VARARGS, posix_rename__doc__},
    8485         {"rmdir",       posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
    8486         {"stat",        posix_stat, METH_VARARGS, posix_stat__doc__},
    8487         {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
     8810    {"rename",          posix_rename, METH_VARARGS, posix_rename__doc__},
     8811    {"rmdir",           posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
     8812    {"stat",            posix_stat, METH_VARARGS, posix_stat__doc__},
     8813    {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
    84888814#ifdef HAVE_SYMLINK
    8489         {"symlink",     posix_symlink, METH_VARARGS, posix_symlink__doc__},
     8815    {"symlink",         posix_symlink, METH_VARARGS, posix_symlink__doc__},
    84908816#endif /* HAVE_SYMLINK */
    84918817#ifdef HAVE_SYSTEM
    8492         {"system",      posix_system, METH_VARARGS, posix_system__doc__},
    8493 #endif
    8494         {"umask",       posix_umask, METH_VARARGS, posix_umask__doc__},
     8818    {"system",          posix_system, METH_VARARGS, posix_system__doc__},
     8819#endif
     8820    {"umask",           posix_umask, METH_VARARGS, posix_umask__doc__},
    84958821#ifdef HAVE_UNAME
    8496         {"uname",       posix_uname, METH_NOARGS, posix_uname__doc__},
     8822    {"uname",           posix_uname, METH_NOARGS, posix_uname__doc__},
    84978823#endif /* HAVE_UNAME */
    8498         {"unlink",      posix_unlink, METH_VARARGS, posix_unlink__doc__},
    8499         {"remove",      posix_unlink, METH_VARARGS, posix_remove__doc__},
    8500         {"utime",       posix_utime, METH_VARARGS, posix_utime__doc__},
     8824    {"unlink",          posix_unlink, METH_VARARGS, posix_unlink__doc__},
     8825    {"remove",          posix_unlink, METH_VARARGS, posix_remove__doc__},
     8826    {"utime",           posix_utime, METH_VARARGS, posix_utime__doc__},
    85018827#ifdef HAVE_TIMES
    8502         {"times",       posix_times, METH_NOARGS, posix_times__doc__},
     8828    {"times",           posix_times, METH_NOARGS, posix_times__doc__},
    85038829#endif /* HAVE_TIMES */
    8504         {"_exit",       posix__exit, METH_VARARGS, posix__exit__doc__},
     8830    {"_exit",           posix__exit, METH_VARARGS, posix__exit__doc__},
    85058831#ifdef HAVE_EXECV
    8506         {"execv",       posix_execv, METH_VARARGS, posix_execv__doc__},
    8507         {"execve",      posix_execve, METH_VARARGS, posix_execve__doc__},
     8832    {"execv",           posix_execv, METH_VARARGS, posix_execv__doc__},
     8833    {"execve",          posix_execve, METH_VARARGS, posix_execve__doc__},
    85088834#endif /* HAVE_EXECV */
    85098835#ifdef HAVE_SPAWNV
    8510         {"spawnv",      posix_spawnv, METH_VARARGS, posix_spawnv__doc__},
    8511         {"spawnve",     posix_spawnve, METH_VARARGS, posix_spawnve__doc__},
     8836    {"spawnv",          posix_spawnv, METH_VARARGS, posix_spawnv__doc__},
     8837    {"spawnve",         posix_spawnve, METH_VARARGS, posix_spawnve__doc__},
    85128838#if defined(PYOS_OS2)
    8513         {"spawnvp",     posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__},
    8514         {"spawnvpe",    posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__},
     8839    {"spawnvp",         posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__},
     8840    {"spawnvpe",        posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__},
    85158841#endif /* PYOS_OS2 */
    85168842#endif /* HAVE_SPAWNV */
    85178843#ifdef HAVE_FORK1
    8518         {"fork1",       posix_fork1, METH_NOARGS, posix_fork1__doc__},
     8844    {"fork1",       posix_fork1, METH_NOARGS, posix_fork1__doc__},
    85198845#endif /* HAVE_FORK1 */
    85208846#ifdef HAVE_FORK
    8521         {"fork",        posix_fork, METH_NOARGS, posix_fork__doc__},
     8847    {"fork",            posix_fork, METH_NOARGS, posix_fork__doc__},
    85228848#endif /* HAVE_FORK */
    85238849#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
    8524         {"openpty",     posix_openpty, METH_NOARGS, posix_openpty__doc__},
     8850    {"openpty",         posix_openpty, METH_NOARGS, posix_openpty__doc__},
    85258851#endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */
    85268852#ifdef HAVE_FORKPTY
    8527         {"forkpty",     posix_forkpty, METH_NOARGS, posix_forkpty__doc__},
     8853    {"forkpty",         posix_forkpty, METH_NOARGS, posix_forkpty__doc__},
    85288854#endif /* HAVE_FORKPTY */
    85298855#ifdef HAVE_GETEGID
    8530         {"getegid",     posix_getegid, METH_NOARGS, posix_getegid__doc__},
     8856    {"getegid",         posix_getegid, METH_NOARGS, posix_getegid__doc__},
    85318857#endif /* HAVE_GETEGID */
    85328858#ifdef HAVE_GETEUID
    8533         {"geteuid",     posix_geteuid, METH_NOARGS, posix_geteuid__doc__},
     8859    {"geteuid",         posix_geteuid, METH_NOARGS, posix_geteuid__doc__},
    85348860#endif /* HAVE_GETEUID */
    85358861#ifdef HAVE_GETGID
    8536         {"getgid",      posix_getgid, METH_NOARGS, posix_getgid__doc__},
     8862    {"getgid",          posix_getgid, METH_NOARGS, posix_getgid__doc__},
    85378863#endif /* HAVE_GETGID */
    85388864#ifdef HAVE_GETGROUPS
    8539         {"getgroups",   posix_getgroups, METH_NOARGS, posix_getgroups__doc__},
    8540 #endif
    8541         {"getpid",      posix_getpid, METH_NOARGS, posix_getpid__doc__},
     8865    {"getgroups",       posix_getgroups, METH_NOARGS, posix_getgroups__doc__},
     8866#endif
     8867    {"getpid",          posix_getpid, METH_NOARGS, posix_getpid__doc__},
    85428868#ifdef HAVE_GETPGRP
    8543         {"getpgrp",     posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__},
     8869    {"getpgrp",         posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__},
    85448870#endif /* HAVE_GETPGRP */
    85458871#ifdef HAVE_GETPPID
    8546         {"getppid",     posix_getppid, METH_NOARGS, posix_getppid__doc__},
     8872    {"getppid",         posix_getppid, METH_NOARGS, posix_getppid__doc__},
    85478873#endif /* HAVE_GETPPID */
    85488874#ifdef HAVE_GETUID
    8549         {"getuid",      posix_getuid, METH_NOARGS, posix_getuid__doc__},
     8875    {"getuid",          posix_getuid, METH_NOARGS, posix_getuid__doc__},
    85508876#endif /* HAVE_GETUID */
    85518877#ifdef HAVE_GETLOGIN
    8552         {"getlogin",    posix_getlogin, METH_NOARGS, posix_getlogin__doc__},
     8878    {"getlogin",        posix_getlogin, METH_NOARGS, posix_getlogin__doc__},
    85538879#endif
    85548880#ifdef HAVE_KILL
    8555         {"kill",        posix_kill, METH_VARARGS, posix_kill__doc__},
     8881    {"kill",            posix_kill, METH_VARARGS, posix_kill__doc__},
    85568882#endif /* HAVE_KILL */
    85578883#ifdef HAVE_KILLPG
    8558         {"killpg",      posix_killpg, METH_VARARGS, posix_killpg__doc__},
     8884    {"killpg",          posix_killpg, METH_VARARGS, posix_killpg__doc__},
    85598885#endif /* HAVE_KILLPG */
    85608886#ifdef HAVE_PLOCK
    8561         {"plock",       posix_plock, METH_VARARGS, posix_plock__doc__},
     8887    {"plock",           posix_plock, METH_VARARGS, posix_plock__doc__},
    85628888#endif /* HAVE_PLOCK */
    85638889#ifdef HAVE_POPEN
    8564         {"popen",       posix_popen, METH_VARARGS, posix_popen__doc__},
     8890    {"popen",           posix_popen, METH_VARARGS, posix_popen__doc__},
    85658891#ifdef MS_WINDOWS
    8566         {"popen2",      win32_popen2, METH_VARARGS},
    8567         {"popen3",      win32_popen3, METH_VARARGS},
    8568         {"popen4",      win32_popen4, METH_VARARGS},
    8569         {"startfile",   win32_startfile, METH_VARARGS, win32_startfile__doc__},
     8892    {"popen2",          win32_popen2, METH_VARARGS},
     8893    {"popen3",          win32_popen3, METH_VARARGS},
     8894    {"popen4",          win32_popen4, METH_VARARGS},
     8895    {"startfile",       win32_startfile, METH_VARARGS, win32_startfile__doc__},
     8896    {"kill",    win32_kill, METH_VARARGS, win32_kill__doc__},
    85708897#else
    85718898#if defined(PYOS_OS2) && defined(PYCC_GCC)
    8572         {"popen2",      os2emx_popen2, METH_VARARGS},
    8573         {"popen3",      os2emx_popen3, METH_VARARGS},
    8574         {"popen4",      os2emx_popen4, METH_VARARGS},
     8899    {"popen2",          os2emx_popen2, METH_VARARGS},
     8900    {"popen3",          os2emx_popen3, METH_VARARGS},
     8901    {"popen4",          os2emx_popen4, METH_VARARGS},
    85758902#endif
    85768903#endif
    85778904#endif /* HAVE_POPEN */
    85788905#ifdef HAVE_SETUID
    8579         {"setuid",      posix_setuid, METH_VARARGS, posix_setuid__doc__},
     8906    {"setuid",          posix_setuid, METH_VARARGS, posix_setuid__doc__},
    85808907#endif /* HAVE_SETUID */
    85818908#ifdef HAVE_SETEUID
    8582         {"seteuid",     posix_seteuid, METH_VARARGS, posix_seteuid__doc__},
     8909    {"seteuid",         posix_seteuid, METH_VARARGS, posix_seteuid__doc__},
    85838910#endif /* HAVE_SETEUID */
    85848911#ifdef HAVE_SETEGID
    8585         {"setegid",     posix_setegid, METH_VARARGS, posix_setegid__doc__},
     8912    {"setegid",         posix_setegid, METH_VARARGS, posix_setegid__doc__},
    85868913#endif /* HAVE_SETEGID */
    85878914#ifdef HAVE_SETREUID
    8588         {"setreuid",    posix_setreuid, METH_VARARGS, posix_setreuid__doc__},
     8915    {"setreuid",        posix_setreuid, METH_VARARGS, posix_setreuid__doc__},
    85898916#endif /* HAVE_SETREUID */
    85908917#ifdef HAVE_SETREGID
    8591         {"setregid",    posix_setregid, METH_VARARGS, posix_setregid__doc__},
     8918    {"setregid",        posix_setregid, METH_VARARGS, posix_setregid__doc__},
    85928919#endif /* HAVE_SETREGID */
    85938920#ifdef HAVE_SETGID
    8594         {"setgid",      posix_setgid, METH_VARARGS, posix_setgid__doc__},
     8921    {"setgid",          posix_setgid, METH_VARARGS, posix_setgid__doc__},
    85958922#endif /* HAVE_SETGID */
    85968923#ifdef HAVE_SETGROUPS
    8597         {"setgroups",   posix_setgroups, METH_O, posix_setgroups__doc__},
     8924    {"setgroups",       posix_setgroups, METH_O, posix_setgroups__doc__},
    85988925#endif /* HAVE_SETGROUPS */
     8926#ifdef HAVE_INITGROUPS
     8927    {"initgroups",      posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
     8928#endif /* HAVE_INITGROUPS */
    85998929#ifdef HAVE_GETPGID
    8600         {"getpgid",     posix_getpgid, METH_VARARGS, posix_getpgid__doc__},
     8930    {"getpgid",         posix_getpgid, METH_VARARGS, posix_getpgid__doc__},
    86018931#endif /* HAVE_GETPGID */
    86028932#ifdef HAVE_SETPGRP
    8603         {"setpgrp",     posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__},
     8933    {"setpgrp",         posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__},
    86048934#endif /* HAVE_SETPGRP */
    86058935#ifdef HAVE_WAIT
    8606         {"wait",        posix_wait, METH_NOARGS, posix_wait__doc__},
     8936    {"wait",            posix_wait, METH_NOARGS, posix_wait__doc__},
    86078937#endif /* HAVE_WAIT */
    86088938#ifdef HAVE_WAIT3
    8609         {"wait3",       posix_wait3, METH_VARARGS, posix_wait3__doc__},
     8939    {"wait3",           posix_wait3, METH_VARARGS, posix_wait3__doc__},
    86108940#endif /* HAVE_WAIT3 */
    86118941#ifdef HAVE_WAIT4
    8612         {"wait4",       posix_wait4, METH_VARARGS, posix_wait4__doc__},
     8942    {"wait4",           posix_wait4, METH_VARARGS, posix_wait4__doc__},
    86138943#endif /* HAVE_WAIT4 */
    86148944#if defined(HAVE_WAITPID) || defined(HAVE_CWAIT)
    8615         {"waitpid",     posix_waitpid, METH_VARARGS, posix_waitpid__doc__},
     8945    {"waitpid",         posix_waitpid, METH_VARARGS, posix_waitpid__doc__},
    86168946#endif /* HAVE_WAITPID */
    86178947#ifdef HAVE_GETSID
    8618         {"getsid",      posix_getsid, METH_VARARGS, posix_getsid__doc__},
     8948    {"getsid",          posix_getsid, METH_VARARGS, posix_getsid__doc__},
    86198949#endif /* HAVE_GETSID */
    86208950#ifdef HAVE_SETSID
    8621         {"setsid",      posix_setsid, METH_NOARGS, posix_setsid__doc__},
     8951    {"setsid",          posix_setsid, METH_NOARGS, posix_setsid__doc__},
    86228952#endif /* HAVE_SETSID */
    86238953#ifdef HAVE_SETPGID
    8624         {"setpgid",     posix_setpgid, METH_VARARGS, posix_setpgid__doc__},
     8954    {"setpgid",         posix_setpgid, METH_VARARGS, posix_setpgid__doc__},
    86258955#endif /* HAVE_SETPGID */
    86268956#ifdef HAVE_TCGETPGRP
    8627         {"tcgetpgrp",   posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__},
     8957    {"tcgetpgrp",       posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__},
    86288958#endif /* HAVE_TCGETPGRP */
    86298959#ifdef HAVE_TCSETPGRP
    8630         {"tcsetpgrp",   posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__},
     8960    {"tcsetpgrp",       posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__},
    86318961#endif /* HAVE_TCSETPGRP */
    8632         {"open",        posix_open, METH_VARARGS, posix_open__doc__},
    8633         {"close",       posix_close, METH_VARARGS, posix_close__doc__},
    8634         {"closerange",  posix_closerange, METH_VARARGS, posix_closerange__doc__},
    8635         {"dup",         posix_dup, METH_VARARGS, posix_dup__doc__},
    8636         {"dup2",        posix_dup2, METH_VARARGS, posix_dup2__doc__},
    8637         {"lseek",       posix_lseek, METH_VARARGS, posix_lseek__doc__},
    8638         {"read",        posix_read, METH_VARARGS, posix_read__doc__},
    8639         {"write",       posix_write, METH_VARARGS, posix_write__doc__},
    8640         {"fstat",       posix_fstat, METH_VARARGS, posix_fstat__doc__},
    8641         {"fdopen",      posix_fdopen, METH_VARARGS, posix_fdopen__doc__},
    8642         {"isatty",      posix_isatty, METH_VARARGS, posix_isatty__doc__},
     8962    {"open",            posix_open, METH_VARARGS, posix_open__doc__},
     8963    {"close",           posix_close, METH_VARARGS, posix_close__doc__},
     8964    {"closerange",      posix_closerange, METH_VARARGS, posix_closerange__doc__},
     8965    {"dup",             posix_dup, METH_VARARGS, posix_dup__doc__},
     8966    {"dup2",            posix_dup2, METH_VARARGS, posix_dup2__doc__},
     8967    {"lseek",           posix_lseek, METH_VARARGS, posix_lseek__doc__},
     8968    {"read",            posix_read, METH_VARARGS, posix_read__doc__},
     8969    {"write",           posix_write, METH_VARARGS, posix_write__doc__},
     8970    {"fstat",           posix_fstat, METH_VARARGS, posix_fstat__doc__},
     8971    {"fdopen",          posix_fdopen, METH_VARARGS, posix_fdopen__doc__},
     8972    {"isatty",          posix_isatty, METH_VARARGS, posix_isatty__doc__},
    86438973#ifdef HAVE_PIPE
    8644         {"pipe",        posix_pipe, METH_NOARGS, posix_pipe__doc__},
     8974    {"pipe",            posix_pipe, METH_NOARGS, posix_pipe__doc__},
    86458975#endif
    86468976#ifdef HAVE_MKFIFO
    8647         {"mkfifo",      posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__},
     8977    {"mkfifo",          posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__},
    86488978#endif
    86498979#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
    8650         {"mknod",       posix_mknod, METH_VARARGS, posix_mknod__doc__},
     8980    {"mknod",           posix_mknod, METH_VARARGS, posix_mknod__doc__},
    86518981#endif
    86528982#ifdef HAVE_DEVICE_MACROS
    8653         {"major",       posix_major, METH_VARARGS, posix_major__doc__},
    8654         {"minor",       posix_minor, METH_VARARGS, posix_minor__doc__},
    8655         {"makedev",     posix_makedev, METH_VARARGS, posix_makedev__doc__},
     8983    {"major",           posix_major, METH_VARARGS, posix_major__doc__},
     8984    {"minor",           posix_minor, METH_VARARGS, posix_minor__doc__},
     8985    {"makedev",         posix_makedev, METH_VARARGS, posix_makedev__doc__},
    86568986#endif
    86578987#ifdef HAVE_FTRUNCATE
    8658         {"ftruncate",   posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__},
     8988    {"ftruncate",       posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__},
    86598989#endif
    86608990#ifdef HAVE_PUTENV
    8661         {"putenv",      posix_putenv, METH_VARARGS, posix_putenv__doc__},
     8991    {"putenv",          posix_putenv, METH_VARARGS, posix_putenv__doc__},
    86628992#endif
    86638993#ifdef HAVE_UNSETENV
    8664         {"unsetenv",    posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__},
    8665 #endif
    8666         {"strerror",    posix_strerror, METH_VARARGS, posix_strerror__doc__},
     8994    {"unsetenv",        posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__},
     8995#endif
     8996    {"strerror",        posix_strerror, METH_VARARGS, posix_strerror__doc__},
    86678997#ifdef HAVE_FCHDIR
    8668         {"fchdir",      posix_fchdir, METH_O, posix_fchdir__doc__},
     8998    {"fchdir",          posix_fchdir, METH_O, posix_fchdir__doc__},
    86698999#endif
    86709000#ifdef HAVE_FSYNC
    8671         {"fsync",       posix_fsync, METH_O, posix_fsync__doc__},
     9001    {"fsync",       posix_fsync, METH_O, posix_fsync__doc__},
    86729002#endif
    86739003#ifdef HAVE_FDATASYNC
    8674         {"fdatasync",   posix_fdatasync,  METH_O, posix_fdatasync__doc__},
     9004    {"fdatasync",   posix_fdatasync,  METH_O, posix_fdatasync__doc__},
    86759005#endif
    86769006#ifdef HAVE_SYS_WAIT_H
    86779007#ifdef WCOREDUMP
    8678         {"WCOREDUMP",   posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__},
     9008    {"WCOREDUMP",       posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__},
    86799009#endif /* WCOREDUMP */
    86809010#ifdef WIFCONTINUED
    8681         {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__},
     9011    {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__},
    86829012#endif /* WIFCONTINUED */
    86839013#ifdef WIFSTOPPED
    8684         {"WIFSTOPPED",  posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__},
     9014    {"WIFSTOPPED",      posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__},
    86859015#endif /* WIFSTOPPED */
    86869016#ifdef WIFSIGNALED
    8687         {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__},
     9017    {"WIFSIGNALED",     posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__},
    86889018#endif /* WIFSIGNALED */
    86899019#ifdef WIFEXITED
    8690         {"WIFEXITED",   posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__},
     9020    {"WIFEXITED",       posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__},
    86919021#endif /* WIFEXITED */
    86929022#ifdef WEXITSTATUS
    8693         {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__},
     9023    {"WEXITSTATUS",     posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__},
    86949024#endif /* WEXITSTATUS */
    86959025#ifdef WTERMSIG
    8696         {"WTERMSIG",    posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__},
     9026    {"WTERMSIG",        posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__},
    86979027#endif /* WTERMSIG */
    86989028#ifdef WSTOPSIG
    8699         {"WSTOPSIG",    posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__},
     9029    {"WSTOPSIG",        posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__},
    87009030#endif /* WSTOPSIG */
    87019031#endif /* HAVE_SYS_WAIT_H */
    87029032#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
    8703         {"fstatvfs",    posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__},
     9033    {"fstatvfs",        posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__},
    87049034#endif
    87059035#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
    8706         {"statvfs",     posix_statvfs, METH_VARARGS, posix_statvfs__doc__},
     9036    {"statvfs",         posix_statvfs, METH_VARARGS, posix_statvfs__doc__},
    87079037#endif
    87089038#ifdef HAVE_TMPFILE
    8709         {"tmpfile",     posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__},
     9039    {"tmpfile",         posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__},
    87109040#endif
    87119041#ifdef HAVE_TEMPNAM
    8712         {"tempnam",     posix_tempnam, METH_VARARGS, posix_tempnam__doc__},
     9042    {"tempnam",         posix_tempnam, METH_VARARGS, posix_tempnam__doc__},
    87139043#endif
    87149044#ifdef HAVE_TMPNAM
    8715         {"tmpnam",      posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__},
     9045    {"tmpnam",          posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__},
    87169046#endif
    87179047#ifdef HAVE_CONFSTR
    8718         {"confstr",     posix_confstr, METH_VARARGS, posix_confstr__doc__},
     9048    {"confstr",         posix_confstr, METH_VARARGS, posix_confstr__doc__},
    87199049#endif
    87209050#ifdef HAVE_SYSCONF
    8721         {"sysconf",     posix_sysconf, METH_VARARGS, posix_sysconf__doc__},
     9051    {"sysconf",         posix_sysconf, METH_VARARGS, posix_sysconf__doc__},
    87229052#endif
    87239053#ifdef HAVE_FPATHCONF
    8724         {"fpathconf",   posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__},
     9054    {"fpathconf",       posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__},
    87259055#endif
    87269056#ifdef HAVE_PATHCONF
    8727         {"pathconf",    posix_pathconf, METH_VARARGS, posix_pathconf__doc__},
    8728 #endif
    8729         {"abort",       posix_abort, METH_NOARGS, posix_abort__doc__},
     9057    {"pathconf",        posix_pathconf, METH_VARARGS, posix_pathconf__doc__},
     9058#endif
     9059    {"abort",           posix_abort, METH_NOARGS, posix_abort__doc__},
    87309060#ifdef MS_WINDOWS
    8731         {"_getfullpathname",    posix__getfullpathname, METH_VARARGS, NULL},
     9061    {"_getfullpathname",        posix__getfullpathname, METH_VARARGS, NULL},
     9062    {"_isdir",                  posix__isdir, METH_VARARGS, posix__isdir__doc__},
    87329063#endif
    87339064#ifdef HAVE_GETLOADAVG
    8734         {"getloadavg",  posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__},
    8735 #endif
    8736  #ifdef MS_WINDOWS
    8737         {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__},
    8738  #endif
    8739  #ifdef __VMS
    8740         {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__},
    8741  #endif
    8742         {NULL,          NULL}            /* Sentinel */
     9065    {"getloadavg",      posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__},
     9066#endif
     9067#ifdef HAVE_SETRESUID
     9068    {"setresuid",       posix_setresuid, METH_VARARGS, posix_setresuid__doc__},
     9069#endif
     9070#ifdef HAVE_SETRESGID
     9071    {"setresgid",       posix_setresgid, METH_VARARGS, posix_setresgid__doc__},
     9072#endif
     9073#ifdef HAVE_GETRESUID
     9074    {"getresuid",       posix_getresuid, METH_NOARGS, posix_getresuid__doc__},
     9075#endif
     9076#ifdef HAVE_GETRESGID
     9077    {"getresgid",       posix_getresgid, METH_NOARGS, posix_getresgid__doc__},
     9078#endif
     9079    {"urandom",         posix_urandom,   METH_VARARGS, posix_urandom__doc__},
     9080    {NULL,              NULL}            /* Sentinel */
    87439081};
    87449082
     
    87479085ins(PyObject *module, char *symbol, long value)
    87489086{
    8749         return PyModule_AddIntConstant(module, symbol, value);
     9087    return PyModule_AddIntConstant(module, symbol, value);
    87509088}
    87519089
     
    87859123    default:
    87869124        PyOS_snprintf(tmp, sizeof(tmp),
    8787                       "%d-%d", values[QSV_VERSION_MAJOR],
     9125                      "%d-%d", values[QSV_VERSION_MAJOR],
    87889126                      values[QSV_VERSION_MINOR]);
    87899127        ver = &tmp[0];
     
    88079145{
    88089146#ifdef F_OK
    8809         if (ins(d, "F_OK", (long)F_OK)) return -1;
     9147    if (ins(d, "F_OK", (long)F_OK)) return -1;
    88109148#endif
    88119149#ifdef R_OK
    8812         if (ins(d, "R_OK", (long)R_OK)) return -1;
     9150    if (ins(d, "R_OK", (long)R_OK)) return -1;
    88139151#endif
    88149152#ifdef W_OK
    8815         if (ins(d, "W_OK", (long)W_OK)) return -1;
     9153    if (ins(d, "W_OK", (long)W_OK)) return -1;
    88169154#endif
    88179155#ifdef X_OK
    8818         if (ins(d, "X_OK", (long)X_OK)) return -1;
     9156    if (ins(d, "X_OK", (long)X_OK)) return -1;
    88199157#endif
    88209158#ifdef NGROUPS_MAX
    8821         if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1;
     9159    if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1;
    88229160#endif
    88239161#ifdef TMP_MAX
    8824         if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1;
     9162    if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1;
    88259163#endif
    88269164#ifdef WCONTINUED
    8827         if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1;
     9165    if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1;
    88289166#endif
    88299167#ifdef WNOHANG
    8830         if (ins(d, "WNOHANG", (long)WNOHANG)) return -1;
     9168    if (ins(d, "WNOHANG", (long)WNOHANG)) return -1;
    88319169#endif
    88329170#ifdef WUNTRACED
    8833         if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1;
     9171    if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1;
    88349172#endif
    88359173#ifdef O_RDONLY
    8836         if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1;
     9174    if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1;
    88379175#endif
    88389176#ifdef O_WRONLY
    8839         if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1;
     9177    if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1;
    88409178#endif
    88419179#ifdef O_RDWR
    8842         if (ins(d, "O_RDWR", (long)O_RDWR)) return -1;
     9180    if (ins(d, "O_RDWR", (long)O_RDWR)) return -1;
    88439181#endif
    88449182#ifdef O_NDELAY
    8845         if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1;
     9183    if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1;
    88469184#endif
    88479185#ifdef O_NONBLOCK
    8848         if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1;
     9186    if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1;
    88499187#endif
    88509188#ifdef O_APPEND
    8851         if (ins(d, "O_APPEND", (long)O_APPEND)) return -1;
     9189    if (ins(d, "O_APPEND", (long)O_APPEND)) return -1;
    88529190#endif
    88539191#ifdef O_DSYNC
    8854         if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1;
     9192    if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1;
    88559193#endif
    88569194#ifdef O_RSYNC
    8857         if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1;
     9195    if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1;
    88589196#endif
    88599197#ifdef O_SYNC
    8860         if (ins(d, "O_SYNC", (long)O_SYNC)) return -1;
     9198    if (ins(d, "O_SYNC", (long)O_SYNC)) return -1;
    88619199#endif
    88629200#ifdef O_NOCTTY
    8863         if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1;
     9201    if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1;
    88649202#endif
    88659203#ifdef O_CREAT
    8866         if (ins(d, "O_CREAT", (long)O_CREAT)) return -1;
     9204    if (ins(d, "O_CREAT", (long)O_CREAT)) return -1;
    88679205#endif
    88689206#ifdef O_EXCL
    8869         if (ins(d, "O_EXCL", (long)O_EXCL)) return -1;
     9207    if (ins(d, "O_EXCL", (long)O_EXCL)) return -1;
    88709208#endif
    88719209#ifdef O_TRUNC
    8872         if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1;
     9210    if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1;
    88739211#endif
    88749212#ifdef O_BINARY
    8875         if (ins(d, "O_BINARY", (long)O_BINARY)) return -1;
     9213    if (ins(d, "O_BINARY", (long)O_BINARY)) return -1;
    88769214#endif
    88779215#ifdef O_TEXT
    8878         if (ins(d, "O_TEXT", (long)O_TEXT)) return -1;
     9216    if (ins(d, "O_TEXT", (long)O_TEXT)) return -1;
    88799217#endif
    88809218#ifdef O_LARGEFILE
    8881         if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1;
     9219    if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1;
    88829220#endif
    88839221#ifdef O_SHLOCK
    8884         if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1;
     9222    if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1;
    88859223#endif
    88869224#ifdef O_EXLOCK
    8887         if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1;
     9225    if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1;
    88889226#endif
    88899227
    88909228/* MS Windows */
    88919229#ifdef O_NOINHERIT
    8892         /* Don't inherit in child processes. */
    8893         if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1;
     9230    /* Don't inherit in child processes. */
     9231    if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1;
    88949232#endif
    88959233#ifdef _O_SHORT_LIVED
    8896         /* Optimize for short life (keep in memory). */
    8897         /* MS forgot to define this one with a non-underscore form too. */
    8898         if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1;
     9234    /* Optimize for short life (keep in memory). */
     9235    /* MS forgot to define this one with a non-underscore form too. */
     9236    if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1;
    88999237#endif
    89009238#ifdef O_TEMPORARY
    8901         /* Automatically delete when last handle is closed. */
    8902         if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1;
     9239    /* Automatically delete when last handle is closed. */
     9240    if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1;
    89039241#endif
    89049242#ifdef O_RANDOM
    8905         /* Optimize for random access. */
    8906         if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1;
     9243    /* Optimize for random access. */
     9244    if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1;
    89079245#endif
    89089246#ifdef O_SEQUENTIAL
    8909         /* Optimize for sequential access. */
    8910         if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1;
     9247    /* Optimize for sequential access. */
     9248    if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1;
    89119249#endif
    89129250
    89139251/* GNU extensions. */
    89149252#ifdef O_ASYNC
    8915         /* Send a SIGIO signal whenever input or output
    8916            becomes available on file descriptor */
    8917         if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1;
     9253    /* Send a SIGIO signal whenever input or output
     9254       becomes available on file descriptor */
     9255    if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1;
    89189256#endif
    89199257#ifdef O_DIRECT
    8920         /* Direct disk access. */
    8921         if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1;
     9258    /* Direct disk access. */
     9259    if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1;
    89229260#endif
    89239261#ifdef O_DIRECTORY
    8924         /* Must be a directory. */
    8925         if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1;
     9262    /* Must be a directory.      */
     9263    if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1;
    89269264#endif
    89279265#ifdef O_NOFOLLOW
    8928         /* Do not follow links. */
    8929         if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1;
     9266    /* Do not follow links.      */
     9267    if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1;
    89309268#endif
    89319269#ifdef O_NOATIME
    8932         /* Do not update the access time. */
    8933         if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1;
    8934 #endif
    8935 
    8936         /* These come from sysexits.h */
     9270    /* Do not update the access time. */
     9271    if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1;
     9272#endif
     9273
     9274    /* These come from sysexits.h */
    89379275#ifdef EX_OK
    8938         if (ins(d, "EX_OK", (long)EX_OK)) return -1;
     9276    if (ins(d, "EX_OK", (long)EX_OK)) return -1;
    89399277#endif /* EX_OK */
    89409278#ifdef EX_USAGE
    8941         if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1;
     9279    if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1;
    89429280#endif /* EX_USAGE */
    89439281#ifdef EX_DATAERR
    8944         if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1;
     9282    if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1;
    89459283#endif /* EX_DATAERR */
    89469284#ifdef EX_NOINPUT
    8947         if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1;
     9285    if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1;
    89489286#endif /* EX_NOINPUT */
    89499287#ifdef EX_NOUSER
    8950         if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1;
     9288    if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1;
    89519289#endif /* EX_NOUSER */
    89529290#ifdef EX_NOHOST
    8953         if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1;
     9291    if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1;
    89549292#endif /* EX_NOHOST */
    89559293#ifdef EX_UNAVAILABLE
    8956         if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1;
     9294    if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1;
    89579295#endif /* EX_UNAVAILABLE */
    89589296#ifdef EX_SOFTWARE
    8959         if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1;
     9297    if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1;
    89609298#endif /* EX_SOFTWARE */
    89619299#ifdef EX_OSERR
    8962         if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1;
     9300    if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1;
    89639301#endif /* EX_OSERR */
    89649302#ifdef EX_OSFILE
    8965         if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1;
     9303    if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1;
    89669304#endif /* EX_OSFILE */
    89679305#ifdef EX_CANTCREAT
    8968         if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1;
     9306    if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1;
    89699307#endif /* EX_CANTCREAT */
    89709308#ifdef EX_IOERR
    8971         if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1;
     9309    if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1;
    89729310#endif /* EX_IOERR */
    89739311#ifdef EX_TEMPFAIL
    8974         if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1;
     9312    if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1;
    89759313#endif /* EX_TEMPFAIL */
    89769314#ifdef EX_PROTOCOL
    8977         if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1;
     9315    if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1;
    89789316#endif /* EX_PROTOCOL */
    89799317#ifdef EX_NOPERM
    8980         if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1;
     9318    if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1;
    89819319#endif /* EX_NOPERM */
    89829320#ifdef EX_CONFIG
    8983         if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1;
     9321    if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1;
    89849322#endif /* EX_CONFIG */
    89859323#ifdef EX_NOTFOUND
    8986         if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1;
     9324    if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1;
    89879325#endif /* EX_NOTFOUND */
    89889326
    89899327#ifdef HAVE_SPAWNV
    89909328#if defined(PYOS_OS2) && defined(PYCC_GCC)
    8991         if (ins(d, "P_WAIT", (long)P_WAIT)) return -1;
    8992         if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1;
    8993         if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1;
    8994         if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1;
    8995         if (ins(d, "P_SESSION", (long)P_SESSION)) return -1;
    8996         if (ins(d, "P_DETACH", (long)P_DETACH)) return -1;
    8997         if (ins(d, "P_PM", (long)P_PM)) return -1;
    8998         if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1;
    8999         if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1;
    9000         if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1;
    9001         if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1;
    9002         if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1;
    9003         if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1;
    9004         if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1;
    9005         if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1;
    9006         if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1;
    9007         if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1;
    9008         if (ins(d, "P_TILDE", (long)P_TILDE)) return -1;
    9009         if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1;
    9010         if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1;
     9329    if (ins(d, "P_WAIT", (long)P_WAIT)) return -1;
     9330    if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1;
     9331    if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1;
     9332    if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1;
     9333    if (ins(d, "P_SESSION", (long)P_SESSION)) return -1;
     9334    if (ins(d, "P_DETACH", (long)P_DETACH)) return -1;
     9335    if (ins(d, "P_PM", (long)P_PM)) return -1;
     9336    if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1;
     9337    if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1;
     9338    if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1;
     9339    if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1;
     9340    if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1;
     9341    if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1;
     9342    if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1;
     9343    if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1;
     9344    if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1;
     9345    if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1;
     9346    if (ins(d, "P_TILDE", (long)P_TILDE)) return -1;
     9347    if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1;
     9348    if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1;
    90119349#else
    9012         if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1;
    9013         if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1;
    9014         if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1;
    9015         if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1;
    9016         if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1;
     9350    if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1;
     9351    if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1;
     9352    if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1;
     9353    if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1;
     9354    if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1;
    90179355#endif
    90189356#endif
    90199357
    90209358#if defined(PYOS_OS2)
    9021         if (insertvalues(d)) return -1;
    9022 #endif
    9023         return 0;
     9359    if (insertvalues(d)) return -1;
     9360#endif
     9361    return 0;
    90249362}
    90259363
     
    90419379INITFUNC(void)
    90429380{
    9043         PyObject *m, *v;
    9044 
    9045         m = Py_InitModule3(MODNAME,
    9046                            posix_methods,
    9047                            posix__doc__);
    9048         if (m == NULL)
    9049                 return;
    9050 
    9051         /* Initialize environ dictionary */
    9052         v = convertenviron();
    9053         Py_XINCREF(v);
    9054         if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
    9055                 return;
    9056         Py_DECREF(v);
    9057 
    9058         if (all_ins(m))
    9059                 return;
    9060 
    9061         if (setup_confname_tables(m))
    9062                 return;
    9063 
    9064         Py_INCREF(PyExc_OSError);
    9065         PyModule_AddObject(m, "error", PyExc_OSError);
     9381    PyObject *m, *v;
     9382
     9383    m = Py_InitModule3(MODNAME,
     9384                       posix_methods,
     9385                       posix__doc__);
     9386    if (m == NULL)
     9387        return;
     9388
     9389    /* Initialize environ dictionary */
     9390    v = convertenviron();
     9391    Py_XINCREF(v);
     9392    if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
     9393        return;
     9394    Py_DECREF(v);
     9395
     9396    if (all_ins(m))
     9397        return;
     9398
     9399    if (setup_confname_tables(m))
     9400        return;
     9401
     9402    Py_INCREF(PyExc_OSError);
     9403    PyModule_AddObject(m, "error", PyExc_OSError);
    90669404
    90679405#ifdef HAVE_PUTENV
    9068         if (posix_putenv_garbage == NULL)
    9069                 posix_putenv_garbage = PyDict_New();
    9070 #endif
    9071 
    9072         if (!initialized) {
    9073                 stat_result_desc.name = MODNAME ".stat_result";
    9074                 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
    9075                 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
    9076                 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
    9077                 PyStructSequence_InitType(&StatResultType, &stat_result_desc);
    9078                 structseq_new = StatResultType.tp_new;
    9079                 StatResultType.tp_new = statresult_new;
    9080 
    9081                 statvfs_result_desc.name = MODNAME ".statvfs_result";
    9082                 PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc);
     9406    if (posix_putenv_garbage == NULL)
     9407        posix_putenv_garbage = PyDict_New();
     9408#endif
     9409
     9410    if (!initialized) {
     9411        stat_result_desc.name = MODNAME ".stat_result";
     9412        stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
     9413        stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
     9414        stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
     9415        PyStructSequence_InitType(&StatResultType, &stat_result_desc);
     9416        structseq_new = StatResultType.tp_new;
     9417        StatResultType.tp_new = statresult_new;
     9418
     9419        statvfs_result_desc.name = MODNAME ".statvfs_result";
     9420        PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc);
    90839421#ifdef NEED_TICKS_PER_SECOND
    90849422#  if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
    9085                 ticks_per_second = sysconf(_SC_CLK_TCK);
     9423        ticks_per_second = sysconf(_SC_CLK_TCK);
    90869424#  elif defined(HZ)
    9087                 ticks_per_second = HZ;
     9425        ticks_per_second = HZ;
    90889426#  else
    9089                 ticks_per_second = 60; /* magic fallback value; may be bogus */
     9427        ticks_per_second = 60; /* magic fallback value; may be bogus */
    90909428#  endif
    90919429#endif
    9092         }
    9093         Py_INCREF((PyObject*) &StatResultType);
    9094         PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);
    9095         Py_INCREF((PyObject*) &StatVFSResultType);
    9096         PyModule_AddObject(m, "statvfs_result",
    9097                            (PyObject*) &StatVFSResultType);
    9098         initialized = 1;
     9430    }
     9431    Py_INCREF((PyObject*) &StatResultType);
     9432    PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);
     9433    Py_INCREF((PyObject*) &StatVFSResultType);
     9434    PyModule_AddObject(m, "statvfs_result",
     9435                       (PyObject*) &StatVFSResultType);
     9436    initialized = 1;
    90999437
    91009438#ifdef __APPLE__
    9101         /*
    9102         * Step 2 of weak-linking support on Mac OS X.
    9103         *
    9104         * The code below removes functions that are not available on the
    9105          * currently active platform.
    9106         *
    9107         * This block allow one to use a python binary that was build on
    9108          * OSX 10.4 on OSX 10.3, without loosing access to new APIs on
    9109         * OSX 10.4.
    9110         */
     9439    /*
     9440    * Step 2 of weak-linking support on Mac OS X.
     9441    *
     9442    * The code below removes functions that are not available on the
     9443     * currently active platform.
     9444    *
     9445    * This block allow one to use a python binary that was build on
     9446     * OSX 10.4 on OSX 10.3, without loosing access to new APIs on
     9447    * OSX 10.4.
     9448    */
    91119449#ifdef HAVE_FSTATVFS
    9112         if (fstatvfs == NULL) {
    9113                 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
    9114                         return;
    9115                 }
    9116         }
     9450    if (fstatvfs == NULL) {
     9451        if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
     9452            return;
     9453        }
     9454    }
    91179455#endif /* HAVE_FSTATVFS */
    91189456
    91199457#ifdef HAVE_STATVFS
    9120         if (statvfs == NULL) {
    9121                 if (PyObject_DelAttrString(m, "statvfs") == -1) {
    9122                         return;
    9123                 }
    9124         }
     9458    if (statvfs == NULL) {
     9459        if (PyObject_DelAttrString(m, "statvfs") == -1) {
     9460            return;
     9461        }
     9462    }
    91259463#endif /* HAVE_STATVFS */
    91269464
    91279465# ifdef HAVE_LCHOWN
    9128         if (lchown == NULL) {
    9129                 if (PyObject_DelAttrString(m, "lchown") == -1) {
    9130                         return;
    9131                 }
    9132         }
     9466    if (lchown == NULL) {
     9467        if (PyObject_DelAttrString(m, "lchown") == -1) {
     9468            return;
     9469        }
     9470    }
    91339471#endif /* HAVE_LCHOWN */
    91349472
Note: See TracChangeset for help on using the changeset viewer.