]> git.proxmox.com Git - mirror_edk2.git/commitdiff
AppPkg/Applications/Python: Get Python startup process fully working for EDK II.
authordarylm503 <darylm503@6f19259b-4bc3-4df7-8a09-765794883524>
Thu, 26 Jan 2012 22:04:41 +0000 (22:04 +0000)
committerdarylm503 <darylm503@6f19259b-4bc3-4df7-8a09-765794883524>
Thu, 26 Jan 2012 22:04:41 +0000 (22:04 +0000)
AppPkg.dsc: Clean up and add Socket support.
Applications/Python/PythonCore.inf: Re-order source files.
Applications/Python/Efi/config.c: Add all mandatory modules.  Disable remaining.
Applications/Python/Efi/edk2module.c: EDK II port of posixmodule.c.
Applications/Python/Efi/getpath.c: Determine initial module search path.
Applications/Python/Ia32/pyconfig.h: Configuration macros for Ia32.
Applications/Python/Ipf/pyconfig.h: Configuration macros for Ipf.
Applications/Python/PyMod-2.7.2/Include/osdefs.h: Select appropriate directory and path separators for UEFI.
Applications/Python/PyMod-2.7.2/Lib/ntpath.py: Allow multi-character device names to left of colon.
Applications/Python/PyMod-2.7.2/Lib/os.py: Add edk2 as a supported OS.
Applications/Python/PyMod-2.7.2/Lib/site.py: UEFI-specific path and environment setup.
Applications/Python/PyMod-2.7.2/Modules/errnomodule.c: Sync with errno.h.
Applications/Python/PyMod-2.7.2/Modules/selectmodule.c: Add UEFI support.
Applications/Python/PyMod-2.7.2/Modules/socketmodule.h: Add UEFI support.
Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h: Add UEFI support.
Applications/Python/PyMod-2.7.2/Python/getcopyright.c: Add Intel copyright.
Applications/Python/X64/pyconfig.h: Configuration macros for X64.

Signed-off-by: darylm503
Reviewed-by: geekboy15a
Reviewed-by: jljusten
Reviewed-by: lpleahy
Reviewed-by: leegrosenbaum
git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@12957 6f19259b-4bc3-4df7-8a09-765794883524

17 files changed:
AppPkg/AppPkg.dsc
AppPkg/Applications/Python/Efi/config.c
AppPkg/Applications/Python/Efi/edk2module.c [new file with mode: 0644]
AppPkg/Applications/Python/Efi/getpath.c
AppPkg/Applications/Python/Ia32/pyconfig.h
AppPkg/Applications/Python/Ipf/pyconfig.h
AppPkg/Applications/Python/PyMod-2.7.2/Include/osdefs.h
AppPkg/Applications/Python/PyMod-2.7.2/Lib/ntpath.py [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Lib/os.py [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Lib/site.py [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Modules/errnomodule.c [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Modules/selectmodule.c [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Modules/socketmodule.h [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h
AppPkg/Applications/Python/PyMod-2.7.2/Python/getcopyright.c [new file with mode: 0644]
AppPkg/Applications/Python/PythonCore.inf
AppPkg/Applications/Python/X64/pyconfig.h

index 43a93369b9827a8b6d919b0d8581d0a074581847..60ff05fa4169f0e7268f25cbab65f021c1f9e66a 100644 (file)
@@ -71,6 +71,8 @@
   SortLib|ShellPkg/Library/UefiSortLib/UefiSortLib.inf\r
   PathLib|ShellPkg/Library/BasePathLib/BasePathLib.inf\r
 \r
+  CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf\r
+\r
 ###################################################################################################\r
 #\r
 # Components Section - list of the modules and components that will be processed by compilation\r
 #### After extracting the Python distribution, un-comment the following line to build Python.\r
 #  AppPkg/Applications/Python/PythonCore.inf\r
 \r
-##########\r
-#    Socket Applications - LibC based\r
-##########\r
-#  AppPkg/Applications/Sockets/DataSink/DataSink.inf\r
-#  AppPkg/Applications/Sockets/DataSource/DataSource.inf\r
-#  SocketPkg/Application/FtpNew/FTP.inf\r
-#  AppPkg/Applications/Sockets/GetHostByAddr/GetHostByAddr.inf\r
-#  AppPkg/Applications/Sockets/GetHostByDns/GetHostByDns.inf\r
-#  AppPkg/Applications/Sockets/GetHostByName/GetHostByName.inf\r
-#  AppPkg/Applications/Sockets/GetNetByAddr/GetNetByAddr.inf\r
-#  AppPkg/Applications/Sockets/GetNetByName/GetNetByName.inf\r
-#  AppPkg/Applications/Sockets/GetServByName/GetServByName.inf\r
-#  AppPkg/Applications/Sockets/GetServByPort/GetServByPort.inf\r
-#  AppPkg/Applications/Sockets/RecvDgram/RecvDgram.inf\r
-#  SocketPkg/Application/route/route.inf\r
-#  AppPkg/Applications/Sockets/SetHostName/SetHostName.inf\r
-#  AppPkg/Applications/Sockets/SetSockOpt/SetSockOpt.inf\r
-#  AppPkg/Applications/Sockets/TftpServer/TftpServer.inf\r
-#  AppPkg/Applications/Sockets/WebServer/WebServer.inf {\r
-#    <PcdsFixedAtBuild>\r
-#      gStdLibTokenSpaceGuid.WebServer_HttpPort|80\r
-#  }\r
 \r
 ##############################################################################\r
 #\r
-#  Include Boilerplate text required for building with the Standard Libraries.\r
-#\r
-##############################################################################\r
 # Specify whether we are running in an emulation environment, or not.\r
-# Define EMULATE if we are.\r
+# Define EMULATE if we are, else keep the DEFINE commented out.\r
 #\r
-#DEFINE  EMULATE = 1\r
+# DEFINE  EMULATE = 1\r
 \r
+##############################################################################\r
+#\r
+#  Include Boilerplate text required for building with the Standard Libraries.\r
+#\r
+##############################################################################\r
 !include StdLib/StdLib.inc\r
+!include AppPkg/Applications/Sockets/Sockets.inc\r
index 98e7e2a31efc0a16552124f1e0690db34c3dfd94..60df9b4dc30a5bbc4c31bc476507791e24e77070 100644 (file)
@@ -30,7 +30,7 @@ extern void initimageop(void);
 #endif\r
 extern void initmath(void);\r
 extern void init_md5(void);\r
-extern void initnt(void);\r
+extern void initedk2(void);\r
 extern void initoperator(void);\r
 extern void initsignal(void);\r
 extern void init_sha(void);\r
@@ -80,6 +80,9 @@ extern void init_ast(void);
 extern void init_io(void);\r
 extern void _PyWarnings_Init(void);\r
 \r
+extern void init_socket(void);\r
+extern void initselect(void);\r
+\r
 /* tools/freeze/makeconfig.py marker for additional "extern" */\r
 /* -- ADDMODULE MARKER 1 -- */\r
 \r
@@ -90,37 +93,60 @@ struct _inittab _PyImport_Inittab[] = {
 \r
     {"array", initarray},\r
     {"_ast", init_ast},\r
-#ifdef MS_WINDOWS\r
-#ifndef MS_WINI64\r
-    {"audioop", initaudioop},\r
-#endif\r
-#endif\r
     {"binascii", initbinascii},\r
-    //{"cmath", initcmath},\r
     {"errno", initerrno},\r
-\r
+    {"future_builtins", initfuture_builtins},\r
     {"gc", initgc},\r
     {"signal", initsignal},\r
-\r
-#if 0\r
-    {"future_builtins", initfuture_builtins},\r
-#ifndef MS_WINI64\r
-    {"imageop", initimageop},\r
-#endif\r
+    {"edk2", initedk2},\r
+    {"operator", initoperator},\r
+    {"_weakref", init_weakref},\r
     {"math", initmath},\r
+    {"time", inittime},\r
+    {"datetime", initdatetime},\r
+    {"cStringIO", initcStringIO},\r
+    {"_codecs", init_codecs},\r
+\r
+    /* CJK codecs */\r
+    {"_multibytecodec", init_multibytecodec},\r
+    {"_codecs_cn", init_codecs_cn},\r
+    {"_codecs_hk", init_codecs_hk},\r
+    {"_codecs_iso2022", init_codecs_iso2022},\r
+    {"_codecs_jp", init_codecs_jp},\r
+    {"_codecs_kr", init_codecs_kr},\r
+    {"_codecs_tw", init_codecs_tw},\r
+\r
+    {"_bisect", init_bisect},\r
     {"_md5", init_md5},\r
-    //{"nt", initnt}, /* Use the NT os functions, not posix */\r
-    {"operator", initoperator},\r
     {"_sha", init_sha},\r
     {"_sha256", init_sha256},\r
     {"_sha512", init_sha512},\r
+    {"_random", init_random},\r
+    {"_heapq", init_heapq},\r
+    {"itertools", inititertools},\r
+    {"_collections", init_collections},\r
+    {"_sre", init_sre},\r
+    {"parser", initparser},\r
+    {"_struct", init_struct},\r
+    {"cPickle", initcPickle},\r
+\r
     {"strop", initstrop},\r
-    {"time", inittime},\r
+    {"_functools", init_functools},\r
+    {"cmath", initcmath},\r
+    {"_json", init_json},\r
+\r
+    {"_socket", init_socket},\r
+    {"select", initselect},\r
+\r
+    {"xxsubtype", initxxsubtype},\r
+\r
+#if 0\r
+#ifndef MS_WINI64\r
+    {"imageop", initimageop},\r
+#endif\r
 #ifdef WITH_THREAD\r
     {"thread", initthread},\r
 #endif\r
-    {"cStringIO", initcStringIO},\r
-    {"cPickle", initcPickle},\r
 #ifdef WIN32\r
     {"msvcrt", initmsvcrt},\r
     {"_locale", init_locale},\r
@@ -128,42 +154,14 @@ struct _inittab _PyImport_Inittab[] = {
     /* XXX Should _subprocess go in a WIN32 block?  not WIN64? */\r
     //{"_subprocess", init_subprocess},\r
 \r
-    {"_codecs", init_codecs},\r
-    //{"_weakref", init_weakref},\r
     //{"_hotshot", init_hotshot},\r
-    {"_random", init_random},\r
-    {"_bisect", init_bisect},\r
-    {"_heapq", init_heapq},\r
     //{"_lsprof", init_lsprof},\r
-    {"itertools", inititertools},\r
-    {"_collections", init_collections},\r
-    {"_symtable", init_symtable},\r
     //{"mmap", initmmap},\r
-    {"_csv", init_csv},\r
-    {"_sre", init_sre},\r
-#endif\r
-\r
-    {"parser", initparser},\r
-\r
-#if 0\r
     //{"_winreg", init_winreg},\r
-    {"_struct", init_struct},\r
-    {"datetime", initdatetime},\r
-    {"_functools", init_functools},\r
-    {"_json", init_json},\r
-\r
-    {"xxsubtype", initxxsubtype},\r
-    //{"zipimport", initzipimport},\r
-    //{"zlib", initzlib},\r
-\r
-    /* CJK codecs */\r
-    {"_multibytecodec", init_multibytecodec},\r
-    {"_codecs_cn", init_codecs_cn},\r
-    {"_codecs_hk", init_codecs_hk},\r
-    {"_codecs_iso2022", init_codecs_iso2022},\r
-    {"_codecs_jp", init_codecs_jp},\r
-    {"_codecs_kr", init_codecs_kr},\r
-    {"_codecs_tw", init_codecs_tw},\r
+    {"_symtable", init_symtable},\r
+    {"_csv", init_csv},\r
+    {"zipimport", initzipimport},\r
+    {"zlib", initzlib},\r
 #endif\r
 \r
 /* tools/freeze/makeconfig.py marker for additional "_inittab" entries */\r
diff --git a/AppPkg/Applications/Python/Efi/edk2module.c b/AppPkg/Applications/Python/Efi/edk2module.c
new file mode 100644 (file)
index 0000000..451bf47
--- /dev/null
@@ -0,0 +1,7409 @@
+/** @file\r
+    OS-specific module implementation for EDK II and UEFI.\r
+    Derived from posixmodule.c in Python 2.7.2.\r
+\r
+    Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>\r
+    This program and the accompanying materials are licensed and made available under\r
+    the terms and conditions of the BSD License that accompanies this distribution.\r
+    The full text of the license may be found at\r
+    http://opensource.org/licenses/bsd-license.\r
+\r
+    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+**/\r
+#define PY_SSIZE_T_CLEAN\r
+\r
+#include "Python.h"\r
+#include "structseq.h"\r
+\r
+#include  <stdio.h>\r
+#include  <stdlib.h>\r
+#include  <wchar.h>\r
+#include  <sys/syslimits.h>\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+PyDoc_STRVAR(posix__doc__,\r
+"This module provides access to operating system functionality that is\n\\r
+standardized by the C Standard and the POSIX standard (a thinly\n\\r
+disguised Unix interface).  Refer to the library manual and\n\\r
+corresponding Unix manual entries for more information on calls.");\r
+\r
+#ifndef Py_USING_UNICODE\r
+  /* This is used in signatures of functions. */\r
+  #define Py_UNICODE void\r
+#endif\r
+\r
+#ifdef HAVE_SYS_TYPES_H\r
+  #include <sys/types.h>\r
+#endif /* HAVE_SYS_TYPES_H */\r
+\r
+#ifdef HAVE_SYS_STAT_H\r
+  #include <sys/stat.h>\r
+#endif /* HAVE_SYS_STAT_H */\r
+\r
+#ifdef HAVE_SYS_WAIT_H\r
+  #include <sys/wait.h>           /* For WNOHANG */\r
+#endif\r
+\r
+#ifdef HAVE_SIGNAL_H\r
+  #include <signal.h>\r
+#endif\r
+\r
+#ifdef HAVE_FCNTL_H\r
+  #include <fcntl.h>\r
+#endif /* HAVE_FCNTL_H */\r
+\r
+#ifdef HAVE_GRP_H\r
+  #include <grp.h>\r
+#endif\r
+\r
+#ifdef HAVE_SYSEXITS_H\r
+  #include <sysexits.h>\r
+#endif /* HAVE_SYSEXITS_H */\r
+\r
+#ifdef HAVE_SYS_LOADAVG_H\r
+  #include <sys/loadavg.h>\r
+#endif\r
+\r
+#ifdef HAVE_UTIME_H\r
+  #include <utime.h>\r
+#endif /* HAVE_UTIME_H */\r
+\r
+#ifdef HAVE_SYS_UTIME_H\r
+  #include <sys/utime.h>\r
+  #define HAVE_UTIME_H /* pretend we do for the rest of this file */\r
+#endif /* HAVE_SYS_UTIME_H */\r
+\r
+#ifdef HAVE_SYS_TIMES_H\r
+  #include <sys/times.h>\r
+#endif /* HAVE_SYS_TIMES_H */\r
+\r
+#ifdef HAVE_SYS_PARAM_H\r
+  #include <sys/param.h>\r
+#endif /* HAVE_SYS_PARAM_H */\r
+\r
+#ifdef HAVE_SYS_UTSNAME_H\r
+  #include <sys/utsname.h>\r
+#endif /* HAVE_SYS_UTSNAME_H */\r
+\r
+#ifdef HAVE_DIRENT_H\r
+  #include <dirent.h>\r
+  #define NAMLEN(dirent) wcslen((dirent)->FileName)\r
+#else\r
+  #define dirent direct\r
+  #define NAMLEN(dirent) (dirent)->d_namlen\r
+  #ifdef HAVE_SYS_NDIR_H\r
+    #include <sys/ndir.h>\r
+  #endif\r
+  #ifdef HAVE_SYS_DIR_H\r
+    #include <sys/dir.h>\r
+  #endif\r
+  #ifdef HAVE_NDIR_H\r
+    #include <ndir.h>\r
+  #endif\r
+#endif\r
+\r
+#ifndef MAXPATHLEN\r
+  #if defined(PATH_MAX) && PATH_MAX > 1024\r
+    #define MAXPATHLEN PATH_MAX\r
+  #else\r
+    #define MAXPATHLEN 1024\r
+  #endif\r
+#endif /* MAXPATHLEN */\r
+\r
+#define WAIT_TYPE int\r
+#define WAIT_STATUS_INT(s) (s)\r
+\r
+/* Issue #1983: pid_t can be longer than a C long on some systems */\r
+#if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT\r
+  #define PARSE_PID "i"\r
+  #define PyLong_FromPid PyInt_FromLong\r
+  #define PyLong_AsPid PyInt_AsLong\r
+#elif SIZEOF_PID_T == SIZEOF_LONG\r
+  #define PARSE_PID "l"\r
+  #define PyLong_FromPid PyInt_FromLong\r
+  #define PyLong_AsPid PyInt_AsLong\r
+#elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG\r
+  #define PARSE_PID "L"\r
+  #define PyLong_FromPid PyLong_FromLongLong\r
+  #define PyLong_AsPid PyInt_AsLongLong\r
+#else\r
+  #error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)"\r
+#endif /* SIZEOF_PID_T */\r
+\r
+/* Don't use the "_r" form if we don't need it (also, won't have a\r
+   prototype for it, at least on Solaris -- maybe others as well?). */\r
+#if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)\r
+  #define USE_CTERMID_R\r
+#endif\r
+\r
+#if defined(HAVE_TMPNAM_R) && defined(WITH_THREAD)\r
+  #define USE_TMPNAM_R\r
+#endif\r
+\r
+/* choose the appropriate stat and fstat functions and return structs */\r
+#undef STAT\r
+#undef FSTAT\r
+#undef STRUCT_STAT\r
+#define STAT stat\r
+#define FSTAT fstat\r
+#define STRUCT_STAT struct stat\r
+\r
+/* dummy version. _PyVerify_fd() is already defined in fileobject.h */\r
+#define _PyVerify_fd_dup2(A, B) (1)\r
+\r
+#ifndef UEFI_ENV\r
+/* Return a dictionary corresponding to the POSIX environment table */\r
+extern char **environ;\r
+\r
+static PyObject *\r
+convertenviron(void)\r
+{\r
+    PyObject *d;\r
+    char **e;\r
+    d = PyDict_New();\r
+    if (d == NULL)\r
+        return NULL;\r
+    if (environ == NULL)\r
+        return d;\r
+    /* This part ignores errors */\r
+    for (e = environ; *e != NULL; e++) {\r
+        PyObject *k;\r
+        PyObject *v;\r
+        char *p = strchr(*e, '=');\r
+        if (p == NULL)\r
+            continue;\r
+        k = PyString_FromStringAndSize(*e, (int)(p-*e));\r
+        if (k == NULL) {\r
+            PyErr_Clear();\r
+            continue;\r
+        }\r
+        v = PyString_FromString(p+1);\r
+        if (v == NULL) {\r
+            PyErr_Clear();\r
+            Py_DECREF(k);\r
+            continue;\r
+        }\r
+        if (PyDict_GetItem(d, k) == NULL) {\r
+            if (PyDict_SetItem(d, k, v) != 0)\r
+                PyErr_Clear();\r
+        }\r
+        Py_DECREF(k);\r
+        Py_DECREF(v);\r
+    }\r
+    return d;\r
+}\r
+#endif  /* UEFI_ENV */\r
+\r
+/* Set a POSIX-specific error from errno, and return NULL */\r
+\r
+static PyObject *\r
+posix_error(void)\r
+{\r
+    return PyErr_SetFromErrno(PyExc_OSError);\r
+}\r
+static PyObject *\r
+posix_error_with_filename(char* name)\r
+{\r
+    return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);\r
+}\r
+\r
+\r
+static PyObject *\r
+posix_error_with_allocated_filename(char* name)\r
+{\r
+    PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);\r
+    PyMem_Free(name);\r
+    return rc;\r
+}\r
+\r
+/* POSIX generic methods */\r
+\r
+static PyObject *\r
+posix_fildes(PyObject *fdobj, int (*func)(int))\r
+{\r
+    int fd;\r
+    int res;\r
+    fd = PyObject_AsFileDescriptor(fdobj);\r
+    if (fd < 0)\r
+        return NULL;\r
+    if (!_PyVerify_fd(fd))\r
+        return posix_error();\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = (*func)(fd);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+static PyObject *\r
+posix_1str(PyObject *args, char *format, int (*func)(const char*))\r
+{\r
+    char *path1 = NULL;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, format,\r
+                          Py_FileSystemDefaultEncoding, &path1))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = (*func)(path1);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error_with_allocated_filename(path1);\r
+    PyMem_Free(path1);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+static PyObject *\r
+posix_2str(PyObject *args,\r
+           char *format,\r
+           int (*func)(const char *, const char *))\r
+{\r
+    char *path1 = NULL, *path2 = NULL;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, format,\r
+                          Py_FileSystemDefaultEncoding, &path1,\r
+                          Py_FileSystemDefaultEncoding, &path2))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = (*func)(path1, path2);\r
+    Py_END_ALLOW_THREADS\r
+    PyMem_Free(path1);\r
+    PyMem_Free(path2);\r
+    if (res != 0)\r
+        /* XXX how to report both path1 and path2??? */\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+PyDoc_STRVAR(stat_result__doc__,\r
+"stat_result: Result from stat or lstat.\n\n\\r
+This object may be accessed either as a tuple of\n\\r
+  (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\\r
+or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\\r
+\n\\r
+Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\\r
+or st_flags, they are available as attributes only.\n\\r
+\n\\r
+See os.stat for more information.");\r
+\r
+static PyStructSequence_Field stat_result_fields[] = {\r
+    {"st_mode",    "protection bits"},\r
+    //{"st_ino",     "inode"},\r
+    //{"st_dev",     "device"},\r
+    //{"st_nlink",   "number of hard links"},\r
+    //{"st_uid",     "user ID of owner"},\r
+    //{"st_gid",     "group ID of owner"},\r
+    {"st_size",    "total size, in bytes"},\r
+    /* The NULL is replaced with PyStructSequence_UnnamedField later. */\r
+    {NULL,   "integer time of last access"},\r
+    {NULL,   "integer time of last modification"},\r
+    {NULL,   "integer time of last change"},\r
+    {"st_atime",   "time of last access"},\r
+    {"st_mtime",   "time of last modification"},\r
+    {"st_ctime",   "time of last change"},\r
+#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE\r
+    {"st_blksize", "blocksize for filesystem I/O"},\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_BLOCKS\r
+    {"st_blocks",  "number of blocks allocated"},\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_RDEV\r
+    {"st_rdev",    "device type (if inode device)"},\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_FLAGS\r
+    {"st_flags",   "user defined flags for file"},\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_GEN\r
+    {"st_gen",    "generation number"},\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME\r
+    {"st_birthtime",   "time of creation"},\r
+#endif\r
+    {0}\r
+};\r
+\r
+#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE\r
+#define ST_BLKSIZE_IDX 8\r
+#else\r
+#define ST_BLKSIZE_IDX 12\r
+#endif\r
+\r
+#ifdef HAVE_STRUCT_STAT_ST_BLOCKS\r
+#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)\r
+#else\r
+#define ST_BLOCKS_IDX ST_BLKSIZE_IDX\r
+#endif\r
+\r
+#ifdef HAVE_STRUCT_STAT_ST_RDEV\r
+#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)\r
+#else\r
+#define ST_RDEV_IDX ST_BLOCKS_IDX\r
+#endif\r
+\r
+#ifdef HAVE_STRUCT_STAT_ST_FLAGS\r
+#define ST_FLAGS_IDX (ST_RDEV_IDX+1)\r
+#else\r
+#define ST_FLAGS_IDX ST_RDEV_IDX\r
+#endif\r
+\r
+#ifdef HAVE_STRUCT_STAT_ST_GEN\r
+#define ST_GEN_IDX (ST_FLAGS_IDX+1)\r
+#else\r
+#define ST_GEN_IDX ST_FLAGS_IDX\r
+#endif\r
+\r
+#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME\r
+#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)\r
+#else\r
+#define ST_BIRTHTIME_IDX ST_GEN_IDX\r
+#endif\r
+\r
+static PyStructSequence_Desc stat_result_desc = {\r
+    "stat_result", /* name */\r
+    stat_result__doc__, /* doc */\r
+    stat_result_fields,\r
+    10\r
+};\r
+\r
+#ifndef UEFI_ENV   /* Not in UEFI */\r
+PyDoc_STRVAR(statvfs_result__doc__,\r
+"statvfs_result: Result from statvfs or fstatvfs.\n\n\\r
+This object may be accessed either as a tuple of\n\\r
+  (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\\r
+or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\\r
+\n\\r
+See os.statvfs for more information.");\r
+\r
+static PyStructSequence_Field statvfs_result_fields[] = {\r
+    {"f_bsize",  },\r
+    {"f_frsize", },\r
+    {"f_blocks", },\r
+    {"f_bfree",  },\r
+    {"f_bavail", },\r
+    {"f_files",  },\r
+    {"f_ffree",  },\r
+    {"f_favail", },\r
+    {"f_flag",   },\r
+    {"f_namemax",},\r
+    {0}\r
+};\r
+\r
+static PyStructSequence_Desc statvfs_result_desc = {\r
+    "statvfs_result", /* name */\r
+    statvfs_result__doc__, /* doc */\r
+    statvfs_result_fields,\r
+    10\r
+};\r
+#endif\r
+\r
+static int initialized;\r
+static PyTypeObject StatResultType;\r
+static PyTypeObject StatVFSResultType;\r
+static newfunc structseq_new;\r
+\r
+static PyObject *\r
+statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
+{\r
+    PyStructSequence *result;\r
+    int i;\r
+\r
+    result = (PyStructSequence*)structseq_new(type, args, kwds);\r
+    if (!result)\r
+        return NULL;\r
+    /* If we have been initialized from a tuple,\r
+       st_?time might be set to None. Initialize it\r
+       from the int slots.  */\r
+    for (i = 7; i <= 9; i++) {\r
+        if (result->ob_item[i+3] == Py_None) {\r
+            Py_DECREF(Py_None);\r
+            Py_INCREF(result->ob_item[i]);\r
+            result->ob_item[i+3] = result->ob_item[i];\r
+        }\r
+    }\r
+    return (PyObject*)result;\r
+}\r
+\r
+\r
+\r
+/* If true, st_?time is float. */\r
+#if defined(UEFI_ENV)\r
+  static int _stat_float_times = 0;\r
+#else\r
+  static int _stat_float_times = 1;\r
+#endif\r
+\r
+PyDoc_STRVAR(stat_float_times__doc__,\r
+"stat_float_times([newval]) -> oldval\n\n\\r
+Determine whether os.[lf]stat represents time stamps as float objects.\n\\r
+If newval is True, future calls to stat() return floats, if it is False,\n\\r
+future calls return ints. \n\\r
+If newval is omitted, return the current setting.\n");\r
+\r
+static PyObject*\r
+stat_float_times(PyObject* self, PyObject *args)\r
+{\r
+    int newval = -1;\r
+\r
+    if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval))\r
+        return NULL;\r
+    if (newval == -1)\r
+        /* Return old value */\r
+        return PyBool_FromLong(_stat_float_times);\r
+    _stat_float_times = newval;\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+static void\r
+fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)\r
+{\r
+    PyObject *fval,*ival;\r
+#if SIZEOF_TIME_T > SIZEOF_LONG\r
+    ival = PyLong_FromLongLong((PY_LONG_LONG)sec);\r
+#else\r
+    ival = PyInt_FromLong((long)sec);\r
+#endif\r
+    if (!ival)\r
+        return;\r
+    if (_stat_float_times) {\r
+        fval = PyFloat_FromDouble(sec + 1e-9*nsec);\r
+    } else {\r
+        fval = ival;\r
+        Py_INCREF(fval);\r
+    }\r
+    PyStructSequence_SET_ITEM(v, index, ival);\r
+    PyStructSequence_SET_ITEM(v, index+3, fval);\r
+}\r
+\r
+/* pack a system stat C structure into the Python stat tuple\r
+   (used by posix_stat() and posix_fstat()) */\r
+static PyObject*\r
+_pystat_fromstructstat(STRUCT_STAT *st)\r
+{\r
+    unsigned long ansec, mnsec, cnsec;\r
+    PyObject *v = PyStructSequence_New(&StatResultType);\r
+    if (v == NULL)\r
+        return NULL;\r
+\r
+    PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode));\r
+    PyStructSequence_SET_ITEM(v, 1,\r
+                              PyLong_FromLongLong((PY_LONG_LONG)st->st_size));\r
+\r
+    ansec = mnsec = cnsec = 0;\r
+    /* The index used by fill_time is the index of the integer time.\r
+       fill_time will add 3 to the index to get the floating time index.\r
+    */\r
+    fill_time(v, 2, st->st_atime, ansec);\r
+    fill_time(v, 3, st->st_mtime, mnsec);\r
+    fill_time(v, 4, st->st_mtime, cnsec);\r
+\r
+#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE\r
+    PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,\r
+                              PyInt_FromLong((long)st->st_blksize));\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_BLOCKS\r
+    PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,\r
+                              PyInt_FromLong((long)st->st_blocks));\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_RDEV\r
+    PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,\r
+                              PyInt_FromLong((long)st->st_rdev));\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_GEN\r
+    PyStructSequence_SET_ITEM(v, ST_GEN_IDX,\r
+                              PyInt_FromLong((long)st->st_gen));\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME\r
+    {\r
+      PyObject *val;\r
+      unsigned long bsec,bnsec;\r
+      bsec = (long)st->st_birthtime;\r
+#ifdef HAVE_STAT_TV_NSEC2\r
+      bnsec = st->st_birthtimespec.tv_nsec;\r
+#else\r
+      bnsec = 0;\r
+#endif\r
+      if (_stat_float_times) {\r
+        val = PyFloat_FromDouble(bsec + 1e-9*bnsec);\r
+      } else {\r
+        val = PyInt_FromLong((long)bsec);\r
+      }\r
+      PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,\r
+                                val);\r
+    }\r
+#endif\r
+#ifdef HAVE_STRUCT_STAT_ST_FLAGS\r
+    PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,\r
+                              PyInt_FromLong((long)st->st_flags));\r
+#endif\r
+\r
+    if (PyErr_Occurred()) {\r
+        Py_DECREF(v);\r
+        return NULL;\r
+    }\r
+\r
+    return v;\r
+}\r
+\r
+static PyObject *\r
+posix_do_stat(PyObject *self, PyObject *args,\r
+              char *format,\r
+              int (*statfunc)(const char *, STRUCT_STAT *),\r
+              char *wformat,\r
+              int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *))\r
+{\r
+    STRUCT_STAT st;\r
+    char *path = NULL;          /* pass this to stat; do not free() it */\r
+    char *pathfree = NULL;  /* this memory must be free'd */\r
+    int res;\r
+    PyObject *result;\r
+\r
+    if (!PyArg_ParseTuple(args, format,\r
+                          Py_FileSystemDefaultEncoding, &path))\r
+        return NULL;\r
+    pathfree = path;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = (*statfunc)(path, &st);\r
+    Py_END_ALLOW_THREADS\r
+\r
+    if (res != 0) {\r
+        result = posix_error_with_filename(pathfree);\r
+    }\r
+    else\r
+        result = _pystat_fromstructstat(&st);\r
+\r
+    PyMem_Free(pathfree);\r
+    return result;\r
+}\r
+\r
+/* POSIX methods */\r
+\r
+PyDoc_STRVAR(posix_access__doc__,\r
+"access(path, mode) -> True if granted, False otherwise\n\n\\r
+Use the real uid/gid to test for access to a path.  Note that most\n\\r
+operations will use the effective uid/gid, therefore this routine can\n\\r
+be used in a suid/sgid environment to test if the invoking user has the\n\\r
+specified access to the path.  The mode argument can be F_OK to test\n\\r
+existence, or the inclusive-OR of R_OK, W_OK, and X_OK.");\r
+\r
+static PyObject *\r
+posix_access(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    int mode;\r
+\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "eti:access",\r
+                          Py_FileSystemDefaultEncoding, &path, &mode))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = access(path, mode);\r
+    Py_END_ALLOW_THREADS\r
+    PyMem_Free(path);\r
+    return PyBool_FromLong(res == 0);\r
+}\r
+\r
+#ifndef F_OK\r
+  #define F_OK 0\r
+#endif\r
+#ifndef R_OK\r
+  #define R_OK 4\r
+#endif\r
+#ifndef W_OK\r
+  #define W_OK 2\r
+#endif\r
+#ifndef X_OK\r
+  #define X_OK 1\r
+#endif\r
+\r
+PyDoc_STRVAR(posix_chdir__doc__,\r
+"chdir(path)\n\n\\r
+Change the current working directory to the specified path.");\r
+\r
+static PyObject *\r
+posix_chdir(PyObject *self, PyObject *args)\r
+{\r
+    return posix_1str(args, "et:chdir", chdir);\r
+}\r
+\r
+PyDoc_STRVAR(posix_chmod__doc__,\r
+"chmod(path, mode)\n\n\\r
+Change the access permissions of a file.");\r
+\r
+static PyObject *\r
+posix_chmod(PyObject *self, PyObject *args)\r
+{\r
+    char *path = NULL;\r
+    int i;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,\r
+                          &path, &i))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = chmod(path, i);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error_with_allocated_filename(path);\r
+    PyMem_Free(path);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+#ifdef HAVE_FCHMOD\r
+PyDoc_STRVAR(posix_fchmod__doc__,\r
+"fchmod(fd, mode)\n\n\\r
+Change the access permissions of the file given by file\n\\r
+descriptor fd.");\r
+\r
+static PyObject *\r
+posix_fchmod(PyObject *self, PyObject *args)\r
+{\r
+    int fd, mode, res;\r
+    if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = fchmod(fd, mode);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+    Py_RETURN_NONE;\r
+}\r
+#endif /* HAVE_FCHMOD */\r
+\r
+#ifdef HAVE_LCHMOD\r
+PyDoc_STRVAR(posix_lchmod__doc__,\r
+"lchmod(path, mode)\n\n\\r
+Change the access permissions of a file. If path is a symlink, this\n\\r
+affects the link itself rather than the target.");\r
+\r
+static PyObject *\r
+posix_lchmod(PyObject *self, PyObject *args)\r
+{\r
+    char *path = NULL;\r
+    int i;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding,\r
+                          &path, &i))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = lchmod(path, i);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error_with_allocated_filename(path);\r
+    PyMem_Free(path);\r
+    Py_RETURN_NONE;\r
+}\r
+#endif /* HAVE_LCHMOD */\r
+\r
+\r
+#ifdef HAVE_CHFLAGS\r
+PyDoc_STRVAR(posix_chflags__doc__,\r
+"chflags(path, flags)\n\n\\r
+Set file flags.");\r
+\r
+static PyObject *\r
+posix_chflags(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    unsigned long flags;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "etk:chflags",\r
+                          Py_FileSystemDefaultEncoding, &path, &flags))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = chflags(path, flags);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error_with_allocated_filename(path);\r
+    PyMem_Free(path);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_CHFLAGS */\r
+\r
+#ifdef HAVE_LCHFLAGS\r
+PyDoc_STRVAR(posix_lchflags__doc__,\r
+"lchflags(path, flags)\n\n\\r
+Set file flags.\n\\r
+This function will not follow symbolic links.");\r
+\r
+static PyObject *\r
+posix_lchflags(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    unsigned long flags;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "etk:lchflags",\r
+                          Py_FileSystemDefaultEncoding, &path, &flags))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = lchflags(path, flags);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error_with_allocated_filename(path);\r
+    PyMem_Free(path);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_LCHFLAGS */\r
+\r
+#ifdef HAVE_CHROOT\r
+PyDoc_STRVAR(posix_chroot__doc__,\r
+"chroot(path)\n\n\\r
+Change root directory to path.");\r
+\r
+static PyObject *\r
+posix_chroot(PyObject *self, PyObject *args)\r
+{\r
+    return posix_1str(args, "et:chroot", chroot);\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_FSYNC\r
+PyDoc_STRVAR(posix_fsync__doc__,\r
+"fsync(fildes)\n\n\\r
+force write of file with filedescriptor to disk.");\r
+\r
+static PyObject *\r
+posix_fsync(PyObject *self, PyObject *fdobj)\r
+{\r
+    return posix_fildes(fdobj, fsync);\r
+}\r
+#endif /* HAVE_FSYNC */\r
+\r
+#ifdef HAVE_FDATASYNC\r
+\r
+#ifdef __hpux\r
+extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */\r
+#endif\r
+\r
+PyDoc_STRVAR(posix_fdatasync__doc__,\r
+"fdatasync(fildes)\n\n\\r
+force write of file with filedescriptor to disk.\n\\r
+ does not force update of metadata.");\r
+\r
+static PyObject *\r
+posix_fdatasync(PyObject *self, PyObject *fdobj)\r
+{\r
+    return posix_fildes(fdobj, fdatasync);\r
+}\r
+#endif /* HAVE_FDATASYNC */\r
+\r
+\r
+#ifdef HAVE_CHOWN\r
+PyDoc_STRVAR(posix_chown__doc__,\r
+"chown(path, uid, gid)\n\n\\r
+Change the owner and group id of path to the numeric uid and gid.");\r
+\r
+static PyObject *\r
+posix_chown(PyObject *self, PyObject *args)\r
+{\r
+    char *path = NULL;\r
+    long uid, gid;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "etll:chown",\r
+                          Py_FileSystemDefaultEncoding, &path,\r
+                          &uid, &gid))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = chown(path, (uid_t) uid, (gid_t) gid);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error_with_allocated_filename(path);\r
+    PyMem_Free(path);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_CHOWN */\r
+\r
+#ifdef HAVE_FCHOWN\r
+PyDoc_STRVAR(posix_fchown__doc__,\r
+"fchown(fd, uid, gid)\n\n\\r
+Change the owner and group id of the file given by file descriptor\n\\r
+fd to the numeric uid and gid.");\r
+\r
+static PyObject *\r
+posix_fchown(PyObject *self, PyObject *args)\r
+{\r
+    int fd;\r
+    long uid, gid;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = fchown(fd, (uid_t) uid, (gid_t) gid);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+    Py_RETURN_NONE;\r
+}\r
+#endif /* HAVE_FCHOWN */\r
+\r
+#ifdef HAVE_LCHOWN\r
+PyDoc_STRVAR(posix_lchown__doc__,\r
+"lchown(path, uid, gid)\n\n\\r
+Change the owner and group id of path to the numeric uid and gid.\n\\r
+This function will not follow symbolic links.");\r
+\r
+static PyObject *\r
+posix_lchown(PyObject *self, PyObject *args)\r
+{\r
+    char *path = NULL;\r
+    long uid, gid;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "etll:lchown",\r
+                          Py_FileSystemDefaultEncoding, &path,\r
+                          &uid, &gid))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = lchown(path, (uid_t) uid, (gid_t) gid);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error_with_allocated_filename(path);\r
+    PyMem_Free(path);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_LCHOWN */\r
+\r
+\r
+#ifdef HAVE_GETCWD\r
+PyDoc_STRVAR(posix_getcwd__doc__,\r
+"getcwd() -> path\n\n\\r
+Return a string representing the current working directory.");\r
+\r
+static PyObject *\r
+posix_getcwd(PyObject *self, PyObject *noargs)\r
+{\r
+    int bufsize_incr = 1024;\r
+    int bufsize = 0;\r
+    char *tmpbuf = NULL;\r
+    char *res = NULL;\r
+    PyObject *dynamic_return;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    do {\r
+        bufsize = bufsize + bufsize_incr;\r
+        tmpbuf = malloc(bufsize);\r
+        if (tmpbuf == NULL) {\r
+            break;\r
+        }\r
+        res = getcwd(tmpbuf, bufsize);\r
+        if (res == NULL) {\r
+            free(tmpbuf);\r
+        }\r
+    } while ((res == NULL) && (errno == ERANGE));\r
+    Py_END_ALLOW_THREADS\r
+\r
+    if (res == NULL)\r
+        return posix_error();\r
+\r
+    dynamic_return = PyString_FromString(tmpbuf);\r
+    free(tmpbuf);\r
+\r
+    return dynamic_return;\r
+}\r
+\r
+#ifdef Py_USING_UNICODE\r
+PyDoc_STRVAR(posix_getcwdu__doc__,\r
+"getcwdu() -> path\n\n\\r
+Return a unicode string representing the current working directory.");\r
+\r
+static PyObject *\r
+posix_getcwdu(PyObject *self, PyObject *noargs)\r
+{\r
+    char buf[1026];\r
+    char *res;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = getcwd(buf, sizeof buf);\r
+    Py_END_ALLOW_THREADS\r
+    if (res == NULL)\r
+        return posix_error();\r
+    return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict");\r
+}\r
+#endif /* Py_USING_UNICODE */\r
+#endif /* HAVE_GETCWD */\r
+\r
+\r
+PyDoc_STRVAR(posix_listdir__doc__,\r
+"listdir(path) -> list_of_strings\n\n\\r
+Return a list containing the names of the entries in the directory.\n\\r
+\n\\r
+    path: path of directory to list\n\\r
+\n\\r
+The list is in arbitrary order.  It does not include the special\n\\r
+entries '.' and '..' even if they are present in the directory.");\r
+\r
+static PyObject *\r
+posix_listdir(PyObject *self, PyObject *args)\r
+{\r
+    /* XXX Should redo this putting the (now four) versions of opendir\r
+       in separate files instead of having them all here... */\r
+\r
+    char           *name            = NULL;\r
+    char           *MBname;\r
+    PyObject       *d, *v;\r
+    DIR            *dirp;\r
+    struct dirent  *ep;\r
+    int             arg_is_unicode  = 1;\r
+\r
+    errno = 0;\r
+    if (!PyArg_ParseTuple(args, "U:listdir", &v)) {\r
+        arg_is_unicode = 0;\r
+        PyErr_Clear();\r
+    }\r
+    if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    dirp = opendir(name);\r
+    Py_END_ALLOW_THREADS\r
+    if (dirp == NULL) {\r
+        return posix_error_with_allocated_filename(name);\r
+    }\r
+    if ((d = PyList_New(0)) == NULL) {\r
+        Py_BEGIN_ALLOW_THREADS\r
+        closedir(dirp);\r
+        Py_END_ALLOW_THREADS\r
+        PyMem_Free(name);\r
+        return NULL;\r
+    }\r
+    if((MBname = malloc(NAME_MAX)) == NULL) {\r
+      Py_BEGIN_ALLOW_THREADS\r
+      closedir(dirp);\r
+      Py_END_ALLOW_THREADS\r
+      Py_DECREF(d);\r
+      PyMem_Free(name);\r
+      return NULL;\r
+    }\r
+    for (;;) {\r
+        errno = 0;\r
+        Py_BEGIN_ALLOW_THREADS\r
+        ep = readdir(dirp);\r
+        Py_END_ALLOW_THREADS\r
+        if (ep == NULL) {\r
+            if ((errno == 0) || (errno == EISDIR)) {\r
+                break;\r
+            } else {\r
+                Py_BEGIN_ALLOW_THREADS\r
+                closedir(dirp);\r
+                Py_END_ALLOW_THREADS\r
+                Py_DECREF(d);\r
+                return posix_error_with_allocated_filename(name);\r
+            }\r
+        }\r
+        if (ep->FileName[0] == L'.' &&\r
+            (NAMLEN(ep) == 1 ||\r
+             (ep->FileName[1] == L'.' && NAMLEN(ep) == 2)))\r
+            continue;\r
+        if(wcstombs(MBname, ep->FileName, NAME_MAX) == -1) {\r
+          free(MBname);\r
+          Py_BEGIN_ALLOW_THREADS\r
+          closedir(dirp);\r
+          Py_END_ALLOW_THREADS\r
+          Py_DECREF(d);\r
+          PyMem_Free(name);\r
+          return NULL;\r
+        }\r
+        v = PyString_FromStringAndSize(MBname, strlen(MBname));\r
+        if (v == NULL) {\r
+            Py_DECREF(d);\r
+            d = NULL;\r
+            break;\r
+        }\r
+#ifdef Py_USING_UNICODE\r
+        if (arg_is_unicode) {\r
+            PyObject *w;\r
+\r
+            w = PyUnicode_FromEncodedObject(v,\r
+                                            Py_FileSystemDefaultEncoding,\r
+                                            "strict");\r
+            if (w != NULL) {\r
+                Py_DECREF(v);\r
+                v = w;\r
+            }\r
+            else {\r
+                /* fall back to the original byte string, as\r
+                   discussed in patch #683592 */\r
+                PyErr_Clear();\r
+            }\r
+        }\r
+#endif\r
+        if (PyList_Append(d, v) != 0) {\r
+            Py_DECREF(v);\r
+            Py_DECREF(d);\r
+            d = NULL;\r
+            break;\r
+        }\r
+        Py_DECREF(v);\r
+    }\r
+    Py_BEGIN_ALLOW_THREADS\r
+    closedir(dirp);\r
+    Py_END_ALLOW_THREADS\r
+    PyMem_Free(name);\r
+    if(MBname != NULL) {\r
+      free(MBname);\r
+    }\r
+\r
+    return d;\r
+\r
+}  /* end of posix_listdir */\r
+\r
+#ifdef MS_WINDOWS\r
+/* A helper function for abspath on win32 */\r
+static PyObject *\r
+posix__getfullpathname(PyObject *self, PyObject *args)\r
+{\r
+    /* assume encoded strings won't more than double no of chars */\r
+    char inbuf[MAX_PATH*2];\r
+    char *inbufp = inbuf;\r
+    Py_ssize_t insize = sizeof(inbuf);\r
+    char outbuf[MAX_PATH*2];\r
+    char *temp;\r
+\r
+    PyUnicodeObject *po;\r
+    if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) {\r
+        Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);\r
+        Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf;\r
+        Py_UNICODE *wtemp;\r
+        DWORD result;\r
+        PyObject *v;\r
+        result = GetFullPathNameW(wpath,\r
+                                  sizeof(woutbuf)/sizeof(woutbuf[0]),\r
+                                  woutbuf, &wtemp);\r
+        if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) {\r
+            woutbufp = malloc(result * sizeof(Py_UNICODE));\r
+            if (!woutbufp)\r
+                return PyErr_NoMemory();\r
+            result = GetFullPathNameW(wpath, result, woutbufp, &wtemp);\r
+        }\r
+        if (result)\r
+            v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp));\r
+        else\r
+            v = win32_error_unicode("GetFullPathNameW", wpath);\r
+        if (woutbufp != woutbuf)\r
+            free(woutbufp);\r
+        return v;\r
+    }\r
+    /* Drop the argument parsing error as narrow strings\r
+       are also valid. */\r
+    PyErr_Clear();\r
+\r
+    if (!PyArg_ParseTuple (args, "et#:_getfullpathname",\r
+                           Py_FileSystemDefaultEncoding, &inbufp,\r
+                           &insize))\r
+        return NULL;\r
+    if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]),\r
+                         outbuf, &temp))\r
+        return win32_error("GetFullPathName", inbuf);\r
+    if (PyUnicode_Check(PyTuple_GetItem(args, 0))) {\r
+        return PyUnicode_Decode(outbuf, strlen(outbuf),\r
+                                Py_FileSystemDefaultEncoding, NULL);\r
+    }\r
+    return PyString_FromString(outbuf);\r
+} /* end of posix__getfullpathname */\r
+#endif /* MS_WINDOWS */\r
+\r
+PyDoc_STRVAR(posix_mkdir__doc__,\r
+"mkdir(path [, mode=0777])\n\n\\r
+Create a directory.");\r
+\r
+static PyObject *\r
+posix_mkdir(PyObject *self, PyObject *args)\r
+{\r
+    int res;\r
+    char *path = NULL;\r
+    int mode = 0777;\r
+\r
+    if (!PyArg_ParseTuple(args, "et|i:mkdir",\r
+                          Py_FileSystemDefaultEncoding, &path, &mode))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = mkdir(path, mode);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error_with_allocated_filename(path);\r
+    PyMem_Free(path);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+\r
+/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */\r
+#if defined(HAVE_SYS_RESOURCE_H)\r
+#include <sys/resource.h>\r
+#endif\r
+\r
+\r
+#ifdef HAVE_NICE\r
+PyDoc_STRVAR(posix_nice__doc__,\r
+"nice(inc) -> new_priority\n\n\\r
+Decrease the priority of process by inc and return the new priority.");\r
+\r
+static PyObject *\r
+posix_nice(PyObject *self, PyObject *args)\r
+{\r
+    int increment, value;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:nice", &increment))\r
+        return NULL;\r
+\r
+    /* There are two flavours of 'nice': one that returns the new\r
+       priority (as required by almost all standards out there) and the\r
+       Linux/FreeBSD/BSDI one, which returns '0' on success and advices\r
+       the use of getpriority() to get the new priority.\r
+\r
+       If we are of the nice family that returns the new priority, we\r
+       need to clear errno before the call, and check if errno is filled\r
+       before calling posix_error() on a returnvalue of -1, because the\r
+       -1 may be the actual new priority! */\r
+\r
+    errno = 0;\r
+    value = nice(increment);\r
+#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)\r
+    if (value == 0)\r
+        value = getpriority(PRIO_PROCESS, 0);\r
+#endif\r
+    if (value == -1 && errno != 0)\r
+        /* either nice() or getpriority() returned an error */\r
+        return posix_error();\r
+    return PyInt_FromLong((long) value);\r
+}\r
+#endif /* HAVE_NICE */\r
+\r
+PyDoc_STRVAR(posix_rename__doc__,\r
+"rename(old, new)\n\n\\r
+Rename a file or directory.");\r
+\r
+static PyObject *\r
+posix_rename(PyObject *self, PyObject *args)\r
+{\r
+    return posix_2str(args, "etet:rename", rename);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_rmdir__doc__,\r
+"rmdir(path)\n\n\\r
+Remove a directory.");\r
+\r
+static PyObject *\r
+posix_rmdir(PyObject *self, PyObject *args)\r
+{\r
+    return posix_1str(args, "et:rmdir", rmdir);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_stat__doc__,\r
+"stat(path) -> stat result\n\n\\r
+Perform a stat system call on the given path.");\r
+\r
+static PyObject *\r
+posix_stat(PyObject *self, PyObject *args)\r
+{\r
+    return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL);\r
+}\r
+\r
+\r
+#ifdef HAVE_SYSTEM\r
+PyDoc_STRVAR(posix_system__doc__,\r
+"system(command) -> exit_status\n\n\\r
+Execute the command (a string) in a subshell.");\r
+\r
+static PyObject *\r
+posix_system(PyObject *self, PyObject *args)\r
+{\r
+    char *command;\r
+    long sts;\r
+    if (!PyArg_ParseTuple(args, "s:system", &command))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    sts = system(command);\r
+    Py_END_ALLOW_THREADS\r
+    return PyInt_FromLong(sts);\r
+}\r
+#endif\r
+\r
+\r
+PyDoc_STRVAR(posix_umask__doc__,\r
+"umask(new_mask) -> old_mask\n\n\\r
+Set the current numeric umask and return the previous umask.");\r
+\r
+static PyObject *\r
+posix_umask(PyObject *self, PyObject *args)\r
+{\r
+    int i;\r
+    if (!PyArg_ParseTuple(args, "i:umask", &i))\r
+        return NULL;\r
+    i = (int)umask(i);\r
+    if (i < 0)\r
+        return posix_error();\r
+    return PyInt_FromLong((long)i);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_unlink__doc__,\r
+"unlink(path)\n\n\\r
+Remove a file (same as remove(path)).");\r
+\r
+PyDoc_STRVAR(posix_remove__doc__,\r
+"remove(path)\n\n\\r
+Remove a file (same as unlink(path)).");\r
+\r
+static PyObject *\r
+posix_unlink(PyObject *self, PyObject *args)\r
+{\r
+    return posix_1str(args, "et:remove", unlink);\r
+}\r
+\r
+\r
+static int\r
+extract_time(PyObject *t, time_t* sec, long* usec)\r
+{\r
+    time_t intval;\r
+    if (PyFloat_Check(t)) {\r
+        double tval = PyFloat_AsDouble(t);\r
+        PyObject *intobj = PyNumber_Long(t);\r
+        if (!intobj)\r
+            return -1;\r
+#if SIZEOF_TIME_T > SIZEOF_LONG\r
+        intval = PyInt_AsUnsignedLongLongMask(intobj);\r
+#else\r
+        intval = PyInt_AsLong(intobj);\r
+#endif\r
+        Py_DECREF(intobj);\r
+        if (intval == -1 && PyErr_Occurred())\r
+            return -1;\r
+        *sec = intval;\r
+        *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */\r
+        if (*usec < 0)\r
+            /* If rounding gave us a negative number,\r
+               truncate.  */\r
+            *usec = 0;\r
+        return 0;\r
+    }\r
+#if SIZEOF_TIME_T > SIZEOF_LONG\r
+    intval = PyInt_AsUnsignedLongLongMask(t);\r
+#else\r
+    intval = PyInt_AsLong(t);\r
+#endif\r
+    if (intval == -1 && PyErr_Occurred())\r
+        return -1;\r
+    *sec = intval;\r
+    *usec = 0;\r
+    return 0;\r
+}\r
+\r
+PyDoc_STRVAR(posix_utime__doc__,\r
+"utime(path, (atime, mtime))\n\\r
+utime(path, None)\n\n\\r
+Set the access and modified time of the file to the given values.  If the\n\\r
+second form is used, set the access and modified times to the current time.");\r
+\r
+static PyObject *\r
+posix_utime(PyObject *self, PyObject *args)\r
+{\r
+    char *path = NULL;\r
+    time_t atime, mtime;\r
+    long ausec, musec;\r
+    int res;\r
+    PyObject* arg;\r
+\r
+#if defined(HAVE_UTIMES)\r
+    struct timeval buf[2];\r
+#define ATIME buf[0].tv_sec\r
+#define MTIME buf[1].tv_sec\r
+#elif defined(HAVE_UTIME_H)\r
+/* XXX should define struct utimbuf instead, above */\r
+    struct utimbuf buf;\r
+#define ATIME buf.actime\r
+#define MTIME buf.modtime\r
+#define UTIME_ARG &buf\r
+#else /* HAVE_UTIMES */\r
+    time_t buf[2];\r
+#define ATIME buf[0]\r
+#define MTIME buf[1]\r
+#define UTIME_ARG buf\r
+#endif /* HAVE_UTIMES */\r
+\r
+\r
+    if (!PyArg_ParseTuple(args, "etO:utime",\r
+                          Py_FileSystemDefaultEncoding, &path, &arg))\r
+        return NULL;\r
+    if (arg == Py_None) {\r
+        /* optional time values not given */\r
+        Py_BEGIN_ALLOW_THREADS\r
+        res = utime(path, NULL);\r
+        Py_END_ALLOW_THREADS\r
+    }\r
+    else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "utime() arg 2 must be a tuple (atime, mtime)");\r
+        PyMem_Free(path);\r
+        return NULL;\r
+    }\r
+    else {\r
+        if (extract_time(PyTuple_GET_ITEM(arg, 0),\r
+                         &atime, &ausec) == -1) {\r
+            PyMem_Free(path);\r
+            return NULL;\r
+        }\r
+        if (extract_time(PyTuple_GET_ITEM(arg, 1),\r
+                         &mtime, &musec) == -1) {\r
+            PyMem_Free(path);\r
+            return NULL;\r
+        }\r
+        ATIME = atime;\r
+        MTIME = mtime;\r
+#ifdef HAVE_UTIMES\r
+        buf[0].tv_usec = ausec;\r
+        buf[1].tv_usec = musec;\r
+        Py_BEGIN_ALLOW_THREADS\r
+        res = utimes(path, buf);\r
+        Py_END_ALLOW_THREADS\r
+#else\r
+        Py_BEGIN_ALLOW_THREADS\r
+        res = utime(path, UTIME_ARG);\r
+        Py_END_ALLOW_THREADS\r
+#endif /* HAVE_UTIMES */\r
+    }\r
+    if (res < 0) {\r
+        return posix_error_with_allocated_filename(path);\r
+    }\r
+    PyMem_Free(path);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+#undef UTIME_ARG\r
+#undef ATIME\r
+#undef MTIME\r
+}\r
+\r
+\r
+/* Process operations */\r
+\r
+PyDoc_STRVAR(posix__exit__doc__,\r
+"_exit(status)\n\n\\r
+Exit to the system with specified status, without normal exit processing.");\r
+\r
+static PyObject *\r
+posix__exit(PyObject *self, PyObject *args)\r
+{\r
+    int sts;\r
+    if (!PyArg_ParseTuple(args, "i:_exit", &sts))\r
+        return NULL;\r
+    _Exit(sts);\r
+    return NULL; /* Make gcc -Wall happy */\r
+}\r
+\r
+#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)\r
+static void\r
+free_string_array(char **array, Py_ssize_t count)\r
+{\r
+    Py_ssize_t i;\r
+    for (i = 0; i < count; i++)\r
+        PyMem_Free(array[i]);\r
+    PyMem_DEL(array);\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_EXECV\r
+PyDoc_STRVAR(posix_execv__doc__,\r
+"execv(path, args)\n\n\\r
+Execute an executable path with arguments, replacing current process.\n\\r
+\n\\r
+    path: path of executable file\n\\r
+    args: tuple or list of strings");\r
+\r
+static PyObject *\r
+posix_execv(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    PyObject *argv;\r
+    char **argvlist;\r
+    Py_ssize_t i, argc;\r
+    PyObject *(*getitem)(PyObject *, Py_ssize_t);\r
+\r
+    /* execv has two arguments: (path, argv), where\r
+       argv is a list or tuple of strings. */\r
+\r
+    if (!PyArg_ParseTuple(args, "etO:execv",\r
+                          Py_FileSystemDefaultEncoding,\r
+                          &path, &argv))\r
+        return NULL;\r
+    if (PyList_Check(argv)) {\r
+        argc = PyList_Size(argv);\r
+        getitem = PyList_GetItem;\r
+    }\r
+    else if (PyTuple_Check(argv)) {\r
+        argc = PyTuple_Size(argv);\r
+        getitem = PyTuple_GetItem;\r
+    }\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list");\r
+        PyMem_Free(path);\r
+        return NULL;\r
+    }\r
+    if (argc < 1) {\r
+        PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");\r
+        PyMem_Free(path);\r
+        return NULL;\r
+    }\r
+\r
+    argvlist = PyMem_NEW(char *, argc+1);\r
+    if (argvlist == NULL) {\r
+        PyMem_Free(path);\r
+        return PyErr_NoMemory();\r
+    }\r
+    for (i = 0; i < argc; i++) {\r
+        if (!PyArg_Parse((*getitem)(argv, i), "et",\r
+                         Py_FileSystemDefaultEncoding,\r
+                         &argvlist[i])) {\r
+            free_string_array(argvlist, i);\r
+            PyErr_SetString(PyExc_TypeError,\r
+                            "execv() arg 2 must contain only strings");\r
+            PyMem_Free(path);\r
+            return NULL;\r
+\r
+        }\r
+    }\r
+    argvlist[argc] = NULL;\r
+\r
+    execv(path, argvlist);\r
+\r
+    /* If we get here it's definitely an error */\r
+\r
+    free_string_array(argvlist, argc);\r
+    PyMem_Free(path);\r
+    return posix_error();\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_execve__doc__,\r
+"execve(path, args, env)\n\n\\r
+Execute a path with arguments and environment, replacing current process.\n\\r
+\n\\r
+    path: path of executable file\n\\r
+    args: tuple or list of arguments\n\\r
+    env: dictionary of strings mapping to strings");\r
+\r
+static PyObject *\r
+posix_execve(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    PyObject *argv, *env;\r
+    char **argvlist;\r
+    char **envlist;\r
+    PyObject *key, *val, *keys=NULL, *vals=NULL;\r
+    Py_ssize_t i, pos, argc, envc;\r
+    PyObject *(*getitem)(PyObject *, Py_ssize_t);\r
+    Py_ssize_t lastarg = 0;\r
+\r
+    /* execve has three arguments: (path, argv, env), where\r
+       argv is a list or tuple of strings and env is a dictionary\r
+       like posix.environ. */\r
+\r
+    if (!PyArg_ParseTuple(args, "etOO:execve",\r
+                          Py_FileSystemDefaultEncoding,\r
+                          &path, &argv, &env))\r
+        return NULL;\r
+    if (PyList_Check(argv)) {\r
+        argc = PyList_Size(argv);\r
+        getitem = PyList_GetItem;\r
+    }\r
+    else if (PyTuple_Check(argv)) {\r
+        argc = PyTuple_Size(argv);\r
+        getitem = PyTuple_GetItem;\r
+    }\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "execve() arg 2 must be a tuple or list");\r
+        goto fail_0;\r
+    }\r
+    if (!PyMapping_Check(env)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "execve() arg 3 must be a mapping object");\r
+        goto fail_0;\r
+    }\r
+\r
+    argvlist = PyMem_NEW(char *, argc+1);\r
+    if (argvlist == NULL) {\r
+        PyErr_NoMemory();\r
+        goto fail_0;\r
+    }\r
+    for (i = 0; i < argc; i++) {\r
+        if (!PyArg_Parse((*getitem)(argv, i),\r
+                         "et;execve() arg 2 must contain only strings",\r
+                         Py_FileSystemDefaultEncoding,\r
+                         &argvlist[i]))\r
+        {\r
+            lastarg = i;\r
+            goto fail_1;\r
+        }\r
+    }\r
+    lastarg = argc;\r
+    argvlist[argc] = NULL;\r
+\r
+    i = PyMapping_Size(env);\r
+    if (i < 0)\r
+        goto fail_1;\r
+    envlist = PyMem_NEW(char *, i + 1);\r
+    if (envlist == NULL) {\r
+        PyErr_NoMemory();\r
+        goto fail_1;\r
+    }\r
+    envc = 0;\r
+    keys = PyMapping_Keys(env);\r
+    vals = PyMapping_Values(env);\r
+    if (!keys || !vals)\r
+        goto fail_2;\r
+    if (!PyList_Check(keys) || !PyList_Check(vals)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "execve(): env.keys() or env.values() is not a list");\r
+        goto fail_2;\r
+    }\r
+\r
+    for (pos = 0; pos < i; pos++) {\r
+        char *p, *k, *v;\r
+        size_t len;\r
+\r
+        key = PyList_GetItem(keys, pos);\r
+        val = PyList_GetItem(vals, pos);\r
+        if (!key || !val)\r
+            goto fail_2;\r
+\r
+        if (!PyArg_Parse(\r
+                    key,\r
+                    "s;execve() arg 3 contains a non-string key",\r
+                    &k) ||\r
+            !PyArg_Parse(\r
+                val,\r
+                "s;execve() arg 3 contains a non-string value",\r
+                &v))\r
+        {\r
+            goto fail_2;\r
+        }\r
+\r
+#if defined(PYOS_OS2)\r
+        /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */\r
+        if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) {\r
+#endif\r
+        len = PyString_Size(key) + PyString_Size(val) + 2;\r
+        p = PyMem_NEW(char, len);\r
+        if (p == NULL) {\r
+            PyErr_NoMemory();\r
+            goto fail_2;\r
+        }\r
+        PyOS_snprintf(p, len, "%s=%s", k, v);\r
+        envlist[envc++] = p;\r
+#if defined(PYOS_OS2)\r
+        }\r
+#endif\r
+    }\r
+    envlist[envc] = 0;\r
+\r
+    execve(path, argvlist, envlist);\r
+\r
+    /* If we get here it's definitely an error */\r
+\r
+    (void) posix_error();\r
+\r
+  fail_2:\r
+    while (--envc >= 0)\r
+        PyMem_DEL(envlist[envc]);\r
+    PyMem_DEL(envlist);\r
+  fail_1:\r
+    free_string_array(argvlist, lastarg);\r
+    Py_XDECREF(vals);\r
+    Py_XDECREF(keys);\r
+  fail_0:\r
+    PyMem_Free(path);\r
+    return NULL;\r
+}\r
+#endif /* HAVE_EXECV */\r
+\r
+\r
+#ifdef HAVE_SPAWNV\r
+PyDoc_STRVAR(posix_spawnv__doc__,\r
+"spawnv(mode, path, args)\n\n\\r
+Execute the program 'path' in a new process.\n\\r
+\n\\r
+    mode: mode of process creation\n\\r
+    path: path of executable file\n\\r
+    args: tuple or list of strings");\r
+\r
+static PyObject *\r
+posix_spawnv(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    PyObject *argv;\r
+    char **argvlist;\r
+    int mode, i;\r
+    Py_ssize_t argc;\r
+    Py_intptr_t spawnval;\r
+    PyObject *(*getitem)(PyObject *, Py_ssize_t);\r
+\r
+    /* spawnv has three arguments: (mode, path, argv), where\r
+       argv is a list or tuple of strings. */\r
+\r
+    if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode,\r
+                          Py_FileSystemDefaultEncoding,\r
+                          &path, &argv))\r
+        return NULL;\r
+    if (PyList_Check(argv)) {\r
+        argc = PyList_Size(argv);\r
+        getitem = PyList_GetItem;\r
+    }\r
+    else if (PyTuple_Check(argv)) {\r
+        argc = PyTuple_Size(argv);\r
+        getitem = PyTuple_GetItem;\r
+    }\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "spawnv() arg 2 must be a tuple or list");\r
+        PyMem_Free(path);\r
+        return NULL;\r
+    }\r
+\r
+    argvlist = PyMem_NEW(char *, argc+1);\r
+    if (argvlist == NULL) {\r
+        PyMem_Free(path);\r
+        return PyErr_NoMemory();\r
+    }\r
+    for (i = 0; i < argc; i++) {\r
+        if (!PyArg_Parse((*getitem)(argv, i), "et",\r
+                         Py_FileSystemDefaultEncoding,\r
+                         &argvlist[i])) {\r
+            free_string_array(argvlist, i);\r
+            PyErr_SetString(\r
+                PyExc_TypeError,\r
+                "spawnv() arg 2 must contain only strings");\r
+            PyMem_Free(path);\r
+            return NULL;\r
+        }\r
+    }\r
+    argvlist[argc] = NULL;\r
+\r
+#if defined(PYOS_OS2) && defined(PYCC_GCC)\r
+    Py_BEGIN_ALLOW_THREADS\r
+    spawnval = spawnv(mode, path, argvlist);\r
+    Py_END_ALLOW_THREADS\r
+#else\r
+    if (mode == _OLD_P_OVERLAY)\r
+        mode = _P_OVERLAY;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    spawnval = _spawnv(mode, path, argvlist);\r
+    Py_END_ALLOW_THREADS\r
+#endif\r
+\r
+    free_string_array(argvlist, argc);\r
+    PyMem_Free(path);\r
+\r
+    if (spawnval == -1)\r
+        return posix_error();\r
+    else\r
+#if SIZEOF_LONG == SIZEOF_VOID_P\r
+        return Py_BuildValue("l", (long) spawnval);\r
+#else\r
+        return Py_BuildValue("L", (PY_LONG_LONG) spawnval);\r
+#endif\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_spawnve__doc__,\r
+"spawnve(mode, path, args, env)\n\n\\r
+Execute the program 'path' in a new process.\n\\r
+\n\\r
+    mode: mode of process creation\n\\r
+    path: path of executable file\n\\r
+    args: tuple or list of arguments\n\\r
+    env: dictionary of strings mapping to strings");\r
+\r
+static PyObject *\r
+posix_spawnve(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    PyObject *argv, *env;\r
+    char **argvlist;\r
+    char **envlist;\r
+    PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;\r
+    int mode, pos, envc;\r
+    Py_ssize_t argc, i;\r
+    Py_intptr_t spawnval;\r
+    PyObject *(*getitem)(PyObject *, Py_ssize_t);\r
+    Py_ssize_t lastarg = 0;\r
+\r
+    /* spawnve has four arguments: (mode, path, argv, env), where\r
+       argv is a list or tuple of strings and env is a dictionary\r
+       like posix.environ. */\r
+\r
+    if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode,\r
+                          Py_FileSystemDefaultEncoding,\r
+                          &path, &argv, &env))\r
+        return NULL;\r
+    if (PyList_Check(argv)) {\r
+        argc = PyList_Size(argv);\r
+        getitem = PyList_GetItem;\r
+    }\r
+    else if (PyTuple_Check(argv)) {\r
+        argc = PyTuple_Size(argv);\r
+        getitem = PyTuple_GetItem;\r
+    }\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "spawnve() arg 2 must be a tuple or list");\r
+        goto fail_0;\r
+    }\r
+    if (!PyMapping_Check(env)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "spawnve() arg 3 must be a mapping object");\r
+        goto fail_0;\r
+    }\r
+\r
+    argvlist = PyMem_NEW(char *, argc+1);\r
+    if (argvlist == NULL) {\r
+        PyErr_NoMemory();\r
+        goto fail_0;\r
+    }\r
+    for (i = 0; i < argc; i++) {\r
+        if (!PyArg_Parse((*getitem)(argv, i),\r
+                     "et;spawnve() arg 2 must contain only strings",\r
+                         Py_FileSystemDefaultEncoding,\r
+                         &argvlist[i]))\r
+        {\r
+            lastarg = i;\r
+            goto fail_1;\r
+        }\r
+    }\r
+    lastarg = argc;\r
+    argvlist[argc] = NULL;\r
+\r
+    i = PyMapping_Size(env);\r
+    if (i < 0)\r
+        goto fail_1;\r
+    envlist = PyMem_NEW(char *, i + 1);\r
+    if (envlist == NULL) {\r
+        PyErr_NoMemory();\r
+        goto fail_1;\r
+    }\r
+    envc = 0;\r
+    keys = PyMapping_Keys(env);\r
+    vals = PyMapping_Values(env);\r
+    if (!keys || !vals)\r
+        goto fail_2;\r
+    if (!PyList_Check(keys) || !PyList_Check(vals)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "spawnve(): env.keys() or env.values() is not a list");\r
+        goto fail_2;\r
+    }\r
+\r
+    for (pos = 0; pos < i; pos++) {\r
+        char *p, *k, *v;\r
+        size_t len;\r
+\r
+        key = PyList_GetItem(keys, pos);\r
+        val = PyList_GetItem(vals, pos);\r
+        if (!key || !val)\r
+            goto fail_2;\r
+\r
+        if (!PyArg_Parse(\r
+                    key,\r
+                    "s;spawnve() arg 3 contains a non-string key",\r
+                    &k) ||\r
+            !PyArg_Parse(\r
+                val,\r
+                "s;spawnve() arg 3 contains a non-string value",\r
+                &v))\r
+        {\r
+            goto fail_2;\r
+        }\r
+        len = PyString_Size(key) + PyString_Size(val) + 2;\r
+        p = PyMem_NEW(char, len);\r
+        if (p == NULL) {\r
+            PyErr_NoMemory();\r
+            goto fail_2;\r
+        }\r
+        PyOS_snprintf(p, len, "%s=%s", k, v);\r
+        envlist[envc++] = p;\r
+    }\r
+    envlist[envc] = 0;\r
+\r
+#if defined(PYOS_OS2) && defined(PYCC_GCC)\r
+    Py_BEGIN_ALLOW_THREADS\r
+    spawnval = spawnve(mode, path, argvlist, envlist);\r
+    Py_END_ALLOW_THREADS\r
+#else\r
+    if (mode == _OLD_P_OVERLAY)\r
+        mode = _P_OVERLAY;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    spawnval = _spawnve(mode, path, argvlist, envlist);\r
+    Py_END_ALLOW_THREADS\r
+#endif\r
+\r
+    if (spawnval == -1)\r
+        (void) posix_error();\r
+    else\r
+#if SIZEOF_LONG == SIZEOF_VOID_P\r
+        res = Py_BuildValue("l", (long) spawnval);\r
+#else\r
+        res = Py_BuildValue("L", (PY_LONG_LONG) spawnval);\r
+#endif\r
+\r
+  fail_2:\r
+    while (--envc >= 0)\r
+        PyMem_DEL(envlist[envc]);\r
+    PyMem_DEL(envlist);\r
+  fail_1:\r
+    free_string_array(argvlist, lastarg);\r
+    Py_XDECREF(vals);\r
+    Py_XDECREF(keys);\r
+  fail_0:\r
+    PyMem_Free(path);\r
+    return res;\r
+}\r
+\r
+/* OS/2 supports spawnvp & spawnvpe natively */\r
+#if defined(PYOS_OS2)\r
+PyDoc_STRVAR(posix_spawnvp__doc__,\r
+"spawnvp(mode, file, args)\n\n\\r
+Execute the program 'file' in a new process, using the environment\n\\r
+search path to find the file.\n\\r
+\n\\r
+    mode: mode of process creation\n\\r
+    file: executable file name\n\\r
+    args: tuple or list of strings");\r
+\r
+static PyObject *\r
+posix_spawnvp(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    PyObject *argv;\r
+    char **argvlist;\r
+    int mode, i, argc;\r
+    Py_intptr_t spawnval;\r
+    PyObject *(*getitem)(PyObject *, Py_ssize_t);\r
+\r
+    /* spawnvp has three arguments: (mode, path, argv), where\r
+       argv is a list or tuple of strings. */\r
+\r
+    if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode,\r
+                          Py_FileSystemDefaultEncoding,\r
+                          &path, &argv))\r
+        return NULL;\r
+    if (PyList_Check(argv)) {\r
+        argc = PyList_Size(argv);\r
+        getitem = PyList_GetItem;\r
+    }\r
+    else if (PyTuple_Check(argv)) {\r
+        argc = PyTuple_Size(argv);\r
+        getitem = PyTuple_GetItem;\r
+    }\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "spawnvp() arg 2 must be a tuple or list");\r
+        PyMem_Free(path);\r
+        return NULL;\r
+    }\r
+\r
+    argvlist = PyMem_NEW(char *, argc+1);\r
+    if (argvlist == NULL) {\r
+        PyMem_Free(path);\r
+        return PyErr_NoMemory();\r
+    }\r
+    for (i = 0; i < argc; i++) {\r
+        if (!PyArg_Parse((*getitem)(argv, i), "et",\r
+                         Py_FileSystemDefaultEncoding,\r
+                         &argvlist[i])) {\r
+            free_string_array(argvlist, i);\r
+            PyErr_SetString(\r
+                PyExc_TypeError,\r
+                "spawnvp() arg 2 must contain only strings");\r
+            PyMem_Free(path);\r
+            return NULL;\r
+        }\r
+    }\r
+    argvlist[argc] = NULL;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+#if defined(PYCC_GCC)\r
+    spawnval = spawnvp(mode, path, argvlist);\r
+#else\r
+    spawnval = _spawnvp(mode, path, argvlist);\r
+#endif\r
+    Py_END_ALLOW_THREADS\r
+\r
+    free_string_array(argvlist, argc);\r
+    PyMem_Free(path);\r
+\r
+    if (spawnval == -1)\r
+        return posix_error();\r
+    else\r
+        return Py_BuildValue("l", (long) spawnval);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_spawnvpe__doc__,\r
+"spawnvpe(mode, file, args, env)\n\n\\r
+Execute the program 'file' in a new process, using the environment\n\\r
+search path to find the file.\n\\r
+\n\\r
+    mode: mode of process creation\n\\r
+    file: executable file name\n\\r
+    args: tuple or list of arguments\n\\r
+    env: dictionary of strings mapping to strings");\r
+\r
+static PyObject *\r
+posix_spawnvpe(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    PyObject *argv, *env;\r
+    char **argvlist;\r
+    char **envlist;\r
+    PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;\r
+    int mode, i, pos, argc, envc;\r
+    Py_intptr_t spawnval;\r
+    PyObject *(*getitem)(PyObject *, Py_ssize_t);\r
+    int lastarg = 0;\r
+\r
+    /* spawnvpe has four arguments: (mode, path, argv, env), where\r
+       argv is a list or tuple of strings and env is a dictionary\r
+       like posix.environ. */\r
+\r
+    if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode,\r
+                          Py_FileSystemDefaultEncoding,\r
+                          &path, &argv, &env))\r
+        return NULL;\r
+    if (PyList_Check(argv)) {\r
+        argc = PyList_Size(argv);\r
+        getitem = PyList_GetItem;\r
+    }\r
+    else if (PyTuple_Check(argv)) {\r
+        argc = PyTuple_Size(argv);\r
+        getitem = PyTuple_GetItem;\r
+    }\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "spawnvpe() arg 2 must be a tuple or list");\r
+        goto fail_0;\r
+    }\r
+    if (!PyMapping_Check(env)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "spawnvpe() arg 3 must be a mapping object");\r
+        goto fail_0;\r
+    }\r
+\r
+    argvlist = PyMem_NEW(char *, argc+1);\r
+    if (argvlist == NULL) {\r
+        PyErr_NoMemory();\r
+        goto fail_0;\r
+    }\r
+    for (i = 0; i < argc; i++) {\r
+        if (!PyArg_Parse((*getitem)(argv, i),\r
+                     "et;spawnvpe() arg 2 must contain only strings",\r
+                         Py_FileSystemDefaultEncoding,\r
+                         &argvlist[i]))\r
+        {\r
+            lastarg = i;\r
+            goto fail_1;\r
+        }\r
+    }\r
+    lastarg = argc;\r
+    argvlist[argc] = NULL;\r
+\r
+    i = PyMapping_Size(env);\r
+    if (i < 0)\r
+        goto fail_1;\r
+    envlist = PyMem_NEW(char *, i + 1);\r
+    if (envlist == NULL) {\r
+        PyErr_NoMemory();\r
+        goto fail_1;\r
+    }\r
+    envc = 0;\r
+    keys = PyMapping_Keys(env);\r
+    vals = PyMapping_Values(env);\r
+    if (!keys || !vals)\r
+        goto fail_2;\r
+    if (!PyList_Check(keys) || !PyList_Check(vals)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "spawnvpe(): env.keys() or env.values() is not a list");\r
+        goto fail_2;\r
+    }\r
+\r
+    for (pos = 0; pos < i; pos++) {\r
+        char *p, *k, *v;\r
+        size_t len;\r
+\r
+        key = PyList_GetItem(keys, pos);\r
+        val = PyList_GetItem(vals, pos);\r
+        if (!key || !val)\r
+            goto fail_2;\r
+\r
+        if (!PyArg_Parse(\r
+                    key,\r
+                    "s;spawnvpe() arg 3 contains a non-string key",\r
+                    &k) ||\r
+            !PyArg_Parse(\r
+                val,\r
+                "s;spawnvpe() arg 3 contains a non-string value",\r
+                &v))\r
+        {\r
+            goto fail_2;\r
+        }\r
+        len = PyString_Size(key) + PyString_Size(val) + 2;\r
+        p = PyMem_NEW(char, len);\r
+        if (p == NULL) {\r
+            PyErr_NoMemory();\r
+            goto fail_2;\r
+        }\r
+        PyOS_snprintf(p, len, "%s=%s", k, v);\r
+        envlist[envc++] = p;\r
+    }\r
+    envlist[envc] = 0;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+#if defined(PYCC_GCC)\r
+    spawnval = spawnvpe(mode, path, argvlist, envlist);\r
+#else\r
+    spawnval = _spawnvpe(mode, path, argvlist, envlist);\r
+#endif\r
+    Py_END_ALLOW_THREADS\r
+\r
+    if (spawnval == -1)\r
+        (void) posix_error();\r
+    else\r
+        res = Py_BuildValue("l", (long) spawnval);\r
+\r
+  fail_2:\r
+    while (--envc >= 0)\r
+        PyMem_DEL(envlist[envc]);\r
+    PyMem_DEL(envlist);\r
+  fail_1:\r
+    free_string_array(argvlist, lastarg);\r
+    Py_XDECREF(vals);\r
+    Py_XDECREF(keys);\r
+  fail_0:\r
+    PyMem_Free(path);\r
+    return res;\r
+}\r
+#endif /* PYOS_OS2 */\r
+#endif /* HAVE_SPAWNV */\r
+\r
+\r
+#ifdef HAVE_FORK1\r
+PyDoc_STRVAR(posix_fork1__doc__,\r
+"fork1() -> pid\n\n\\r
+Fork a child process with a single multiplexed (i.e., not bound) thread.\n\\r
+\n\\r
+Return 0 to child process and PID of child to parent process.");\r
+\r
+static PyObject *\r
+posix_fork1(PyObject *self, PyObject *noargs)\r
+{\r
+    pid_t pid;\r
+    int result = 0;\r
+    _PyImport_AcquireLock();\r
+    pid = fork1();\r
+    if (pid == 0) {\r
+        /* child: this clobbers and resets the import lock. */\r
+        PyOS_AfterFork();\r
+    } else {\r
+        /* parent: release the import lock. */\r
+        result = _PyImport_ReleaseLock();\r
+    }\r
+    if (pid == -1)\r
+        return posix_error();\r
+    if (result < 0) {\r
+        /* Don't clobber the OSError if the fork failed. */\r
+        PyErr_SetString(PyExc_RuntimeError,\r
+                        "not holding the import lock");\r
+        return NULL;\r
+    }\r
+    return PyLong_FromPid(pid);\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_FORK\r
+PyDoc_STRVAR(posix_fork__doc__,\r
+"fork() -> pid\n\n\\r
+Fork a child process.\n\\r
+Return 0 to child process and PID of child to parent process.");\r
+\r
+static PyObject *\r
+posix_fork(PyObject *self, PyObject *noargs)\r
+{\r
+    pid_t pid;\r
+    int result = 0;\r
+    _PyImport_AcquireLock();\r
+    pid = fork();\r
+    if (pid == 0) {\r
+        /* child: this clobbers and resets the import lock. */\r
+        PyOS_AfterFork();\r
+    } else {\r
+        /* parent: release the import lock. */\r
+        result = _PyImport_ReleaseLock();\r
+    }\r
+    if (pid == -1)\r
+        return posix_error();\r
+    if (result < 0) {\r
+        /* Don't clobber the OSError if the fork failed. */\r
+        PyErr_SetString(PyExc_RuntimeError,\r
+                        "not holding the import lock");\r
+        return NULL;\r
+    }\r
+    return PyLong_FromPid(pid);\r
+}\r
+#endif\r
+\r
+/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */\r
+/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */\r
+#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)\r
+#define DEV_PTY_FILE "/dev/ptc"\r
+#define HAVE_DEV_PTMX\r
+#else\r
+#define DEV_PTY_FILE "/dev/ptmx"\r
+#endif\r
+\r
+#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)\r
+#ifdef HAVE_PTY_H\r
+#include <pty.h>\r
+#else\r
+#ifdef HAVE_LIBUTIL_H\r
+#include <libutil.h>\r
+#else\r
+#ifdef HAVE_UTIL_H\r
+#include <util.h>\r
+#endif /* HAVE_UTIL_H */\r
+#endif /* HAVE_LIBUTIL_H */\r
+#endif /* HAVE_PTY_H */\r
+#ifdef HAVE_STROPTS_H\r
+#include <stropts.h>\r
+#endif\r
+#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX */\r
+\r
+#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)\r
+PyDoc_STRVAR(posix_openpty__doc__,\r
+"openpty() -> (master_fd, slave_fd)\n\n\\r
+Open a pseudo-terminal, returning open fd's for both master and slave end.\n");\r
+\r
+static PyObject *\r
+posix_openpty(PyObject *self, PyObject *noargs)\r
+{\r
+    int master_fd, slave_fd;\r
+#ifndef HAVE_OPENPTY\r
+    char * slave_name;\r
+#endif\r
+#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)\r
+    PyOS_sighandler_t sig_saved;\r
+#ifdef sun\r
+    extern char *ptsname(int fildes);\r
+#endif\r
+#endif\r
+\r
+#ifdef HAVE_OPENPTY\r
+    if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)\r
+        return posix_error();\r
+#elif defined(HAVE__GETPTY)\r
+    slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);\r
+    if (slave_name == NULL)\r
+        return posix_error();\r
+\r
+    slave_fd = open(slave_name, O_RDWR);\r
+    if (slave_fd < 0)\r
+        return posix_error();\r
+#else\r
+    master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */\r
+    if (master_fd < 0)\r
+        return posix_error();\r
+    sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);\r
+    /* change permission of slave */\r
+    if (grantpt(master_fd) < 0) {\r
+        PyOS_setsig(SIGCHLD, sig_saved);\r
+        return posix_error();\r
+    }\r
+    /* unlock slave */\r
+    if (unlockpt(master_fd) < 0) {\r
+        PyOS_setsig(SIGCHLD, sig_saved);\r
+        return posix_error();\r
+    }\r
+    PyOS_setsig(SIGCHLD, sig_saved);\r
+    slave_name = ptsname(master_fd); /* get name of slave */\r
+    if (slave_name == NULL)\r
+        return posix_error();\r
+    slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */\r
+    if (slave_fd < 0)\r
+        return posix_error();\r
+#if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC)\r
+    ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */\r
+    ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */\r
+#ifndef __hpux\r
+    ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */\r
+#endif /* __hpux */\r
+#endif /* HAVE_CYGWIN */\r
+#endif /* HAVE_OPENPTY */\r
+\r
+    return Py_BuildValue("(ii)", master_fd, slave_fd);\r
+\r
+}\r
+#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */\r
+\r
+#ifdef HAVE_FORKPTY\r
+PyDoc_STRVAR(posix_forkpty__doc__,\r
+"forkpty() -> (pid, master_fd)\n\n\\r
+Fork a new process with a new pseudo-terminal as controlling tty.\n\n\\r
+Like fork(), return 0 as pid to child process, and PID of child to parent.\n\\r
+To both, return fd of newly opened pseudo-terminal.\n");\r
+\r
+static PyObject *\r
+posix_forkpty(PyObject *self, PyObject *noargs)\r
+{\r
+    int master_fd = -1, result = 0;\r
+    pid_t pid;\r
+\r
+    _PyImport_AcquireLock();\r
+    pid = forkpty(&master_fd, NULL, NULL, NULL);\r
+    if (pid == 0) {\r
+        /* child: this clobbers and resets the import lock. */\r
+        PyOS_AfterFork();\r
+    } else {\r
+        /* parent: release the import lock. */\r
+        result = _PyImport_ReleaseLock();\r
+    }\r
+    if (pid == -1)\r
+        return posix_error();\r
+    if (result < 0) {\r
+        /* Don't clobber the OSError if the fork failed. */\r
+        PyErr_SetString(PyExc_RuntimeError,\r
+                        "not holding the import lock");\r
+        return NULL;\r
+    }\r
+    return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_GETEGID\r
+PyDoc_STRVAR(posix_getegid__doc__,\r
+"getegid() -> egid\n\n\\r
+Return the current process's effective group id.");\r
+\r
+static PyObject *\r
+posix_getegid(PyObject *self, PyObject *noargs)\r
+{\r
+    return PyInt_FromLong((long)getegid());\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_GETEUID\r
+PyDoc_STRVAR(posix_geteuid__doc__,\r
+"geteuid() -> euid\n\n\\r
+Return the current process's effective user id.");\r
+\r
+static PyObject *\r
+posix_geteuid(PyObject *self, PyObject *noargs)\r
+{\r
+    return PyInt_FromLong((long)geteuid());\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_GETGID\r
+PyDoc_STRVAR(posix_getgid__doc__,\r
+"getgid() -> gid\n\n\\r
+Return the current process's group id.");\r
+\r
+static PyObject *\r
+posix_getgid(PyObject *self, PyObject *noargs)\r
+{\r
+    return PyInt_FromLong((long)getgid());\r
+}\r
+#endif\r
+\r
+\r
+PyDoc_STRVAR(posix_getpid__doc__,\r
+"getpid() -> pid\n\n\\r
+Return the current process id");\r
+\r
+static PyObject *\r
+posix_getpid(PyObject *self, PyObject *noargs)\r
+{\r
+    return PyLong_FromPid(getpid());\r
+}\r
+\r
+\r
+#ifdef HAVE_GETGROUPS\r
+PyDoc_STRVAR(posix_getgroups__doc__,\r
+"getgroups() -> list of group IDs\n\n\\r
+Return list of supplemental group IDs for the process.");\r
+\r
+static PyObject *\r
+posix_getgroups(PyObject *self, PyObject *noargs)\r
+{\r
+    PyObject *result = NULL;\r
+\r
+#ifdef NGROUPS_MAX\r
+#define MAX_GROUPS NGROUPS_MAX\r
+#else\r
+    /* defined to be 16 on Solaris7, so this should be a small number */\r
+#define MAX_GROUPS 64\r
+#endif\r
+    gid_t grouplist[MAX_GROUPS];\r
+\r
+    /* On MacOSX getgroups(2) can return more than MAX_GROUPS results\r
+     * This is a helper variable to store the intermediate result when\r
+     * that happens.\r
+     *\r
+     * To keep the code readable the OSX behaviour is unconditional,\r
+     * according to the POSIX spec this should be safe on all unix-y\r
+     * systems.\r
+     */\r
+    gid_t* alt_grouplist = grouplist;\r
+    int n;\r
+\r
+    n = getgroups(MAX_GROUPS, grouplist);\r
+    if (n < 0) {\r
+        if (errno == EINVAL) {\r
+            n = getgroups(0, NULL);\r
+            if (n == -1) {\r
+                return posix_error();\r
+            }\r
+            if (n == 0) {\r
+                /* Avoid malloc(0) */\r
+                alt_grouplist = grouplist;\r
+            } else {\r
+                alt_grouplist = PyMem_Malloc(n * sizeof(gid_t));\r
+                if (alt_grouplist == NULL) {\r
+                    errno = EINVAL;\r
+                    return posix_error();\r
+                }\r
+                n = getgroups(n, alt_grouplist);\r
+                if (n == -1) {\r
+                    PyMem_Free(alt_grouplist);\r
+                    return posix_error();\r
+                }\r
+            }\r
+        } else {\r
+            return posix_error();\r
+        }\r
+    }\r
+    result = PyList_New(n);\r
+    if (result != NULL) {\r
+        int i;\r
+        for (i = 0; i < n; ++i) {\r
+            PyObject *o = PyInt_FromLong((long)alt_grouplist[i]);\r
+            if (o == NULL) {\r
+                Py_DECREF(result);\r
+                result = NULL;\r
+                break;\r
+            }\r
+            PyList_SET_ITEM(result, i, o);\r
+        }\r
+    }\r
+\r
+    if (alt_grouplist != grouplist) {\r
+        PyMem_Free(alt_grouplist);\r
+    }\r
+\r
+    return result;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_INITGROUPS\r
+PyDoc_STRVAR(posix_initgroups__doc__,\r
+"initgroups(username, gid) -> None\n\n\\r
+Call the system initgroups() to initialize the group access list with all of\n\\r
+the groups of which the specified username is a member, plus the specified\n\\r
+group id.");\r
+\r
+static PyObject *\r
+posix_initgroups(PyObject *self, PyObject *args)\r
+{\r
+    char *username;\r
+    long gid;\r
+\r
+    if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid))\r
+        return NULL;\r
+\r
+    if (initgroups(username, (gid_t) gid) == -1)\r
+        return PyErr_SetFromErrno(PyExc_OSError);\r
+\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_GETPGID\r
+PyDoc_STRVAR(posix_getpgid__doc__,\r
+"getpgid(pid) -> pgid\n\n\\r
+Call the system call getpgid().");\r
+\r
+static PyObject *\r
+posix_getpgid(PyObject *self, PyObject *args)\r
+{\r
+    pid_t pid, pgid;\r
+    if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid))\r
+        return NULL;\r
+    pgid = getpgid(pid);\r
+    if (pgid < 0)\r
+        return posix_error();\r
+    return PyLong_FromPid(pgid);\r
+}\r
+#endif /* HAVE_GETPGID */\r
+\r
+\r
+#ifdef HAVE_GETPGRP\r
+PyDoc_STRVAR(posix_getpgrp__doc__,\r
+"getpgrp() -> pgrp\n\n\\r
+Return the current process group id.");\r
+\r
+static PyObject *\r
+posix_getpgrp(PyObject *self, PyObject *noargs)\r
+{\r
+#ifdef GETPGRP_HAVE_ARG\r
+    return PyLong_FromPid(getpgrp(0));\r
+#else /* GETPGRP_HAVE_ARG */\r
+    return PyLong_FromPid(getpgrp());\r
+#endif /* GETPGRP_HAVE_ARG */\r
+}\r
+#endif /* HAVE_GETPGRP */\r
+\r
+\r
+#ifdef HAVE_SETPGRP\r
+PyDoc_STRVAR(posix_setpgrp__doc__,\r
+"setpgrp()\n\n\\r
+Make this process the process group leader.");\r
+\r
+static PyObject *\r
+posix_setpgrp(PyObject *self, PyObject *noargs)\r
+{\r
+#ifdef SETPGRP_HAVE_ARG\r
+    if (setpgrp(0, 0) < 0)\r
+#else /* SETPGRP_HAVE_ARG */\r
+    if (setpgrp() < 0)\r
+#endif /* SETPGRP_HAVE_ARG */\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+#endif /* HAVE_SETPGRP */\r
+\r
+#ifdef HAVE_GETPPID\r
+PyDoc_STRVAR(posix_getppid__doc__,\r
+"getppid() -> ppid\n\n\\r
+Return the parent's process id.");\r
+\r
+static PyObject *\r
+posix_getppid(PyObject *self, PyObject *noargs)\r
+{\r
+    return PyLong_FromPid(getppid());\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_GETLOGIN\r
+PyDoc_STRVAR(posix_getlogin__doc__,\r
+"getlogin() -> string\n\n\\r
+Return the actual login name.");\r
+\r
+static PyObject *\r
+posix_getlogin(PyObject *self, PyObject *noargs)\r
+{\r
+    PyObject *result = NULL;\r
+    char *name;\r
+    int old_errno = errno;\r
+\r
+    errno = 0;\r
+    name = getlogin();\r
+    if (name == NULL) {\r
+        if (errno)\r
+        posix_error();\r
+        else\r
+        PyErr_SetString(PyExc_OSError,\r
+                        "unable to determine login name");\r
+    }\r
+    else\r
+        result = PyString_FromString(name);\r
+    errno = old_errno;\r
+\r
+    return result;\r
+}\r
+#endif\r
+\r
+PyDoc_STRVAR(posix_getuid__doc__,\r
+"getuid() -> uid\n\n\\r
+Return the current process's user id.");\r
+\r
+static PyObject *\r
+posix_getuid(PyObject *self, PyObject *noargs)\r
+{\r
+    return PyInt_FromLong((long)getuid());\r
+}\r
+\r
+\r
+#ifdef HAVE_KILL\r
+PyDoc_STRVAR(posix_kill__doc__,\r
+"kill(pid, sig)\n\n\\r
+Kill a process with a signal.");\r
+\r
+static PyObject *\r
+posix_kill(PyObject *self, PyObject *args)\r
+{\r
+    pid_t pid;\r
+    int sig;\r
+    if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig))\r
+        return NULL;\r
+#if defined(PYOS_OS2) && !defined(PYCC_GCC)\r
+    if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) {\r
+        APIRET rc;\r
+        if ((rc = DosSendSignalException(pid, sig)) != NO_ERROR)\r
+            return os2_error(rc);\r
+\r
+    } else if (sig == XCPT_SIGNAL_KILLPROC) {\r
+        APIRET rc;\r
+        if ((rc = DosKillProcess(DKP_PROCESS, pid)) != NO_ERROR)\r
+            return os2_error(rc);\r
+\r
+    } else\r
+        return NULL; /* Unrecognized Signal Requested */\r
+#else\r
+    if (kill(pid, sig) == -1)\r
+        return posix_error();\r
+#endif\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_KILLPG\r
+PyDoc_STRVAR(posix_killpg__doc__,\r
+"killpg(pgid, sig)\n\n\\r
+Kill a process group with a signal.");\r
+\r
+static PyObject *\r
+posix_killpg(PyObject *self, PyObject *args)\r
+{\r
+    int sig;\r
+    pid_t pgid;\r
+    /* XXX some man pages make the `pgid` parameter an int, others\r
+       a pid_t. Since getpgrp() returns a pid_t, we assume killpg should\r
+       take the same type. Moreover, pid_t is always at least as wide as\r
+       int (else compilation of this module fails), which is safe. */\r
+    if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig))\r
+        return NULL;\r
+    if (killpg(pgid, sig) == -1)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_PLOCK\r
+\r
+#ifdef HAVE_SYS_LOCK_H\r
+#include <sys/lock.h>\r
+#endif\r
+\r
+PyDoc_STRVAR(posix_plock__doc__,\r
+"plock(op)\n\n\\r
+Lock program segments into memory.");\r
+\r
+static PyObject *\r
+posix_plock(PyObject *self, PyObject *args)\r
+{\r
+    int op;\r
+    if (!PyArg_ParseTuple(args, "i:plock", &op))\r
+        return NULL;\r
+    if (plock(op) == -1)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_POPEN\r
+PyDoc_STRVAR(posix_popen__doc__,\r
+"popen(command [, mode='r' [, bufsize]]) -> pipe\n\n\\r
+Open a pipe to/from a command returning a file object.");\r
+\r
+#if defined(PYOS_OS2)\r
+#if defined(PYCC_VACPP)\r
+static int\r
+async_system(const char *command)\r
+{\r
+    char errormsg[256], args[1024];\r
+    RESULTCODES rcodes;\r
+    APIRET rc;\r
+\r
+    char *shell = getenv("COMSPEC");\r
+    if (!shell)\r
+        shell = "cmd";\r
+\r
+    /* avoid overflowing the argument buffer */\r
+    if (strlen(shell) + 3 + strlen(command) >= 1024)\r
+        return ERROR_NOT_ENOUGH_MEMORY\r
+\r
+    args[0] = '\0';\r
+    strcat(args, shell);\r
+    strcat(args, "/c ");\r
+    strcat(args, command);\r
+\r
+    /* execute asynchronously, inheriting the environment */\r
+    rc = DosExecPgm(errormsg,\r
+                    sizeof(errormsg),\r
+                    EXEC_ASYNC,\r
+                    args,\r
+                    NULL,\r
+                    &rcodes,\r
+                    shell);\r
+    return rc;\r
+}\r
+\r
+static FILE *\r
+popen(const char *command, const char *mode, int pipesize, int *err)\r
+{\r
+    int oldfd, tgtfd;\r
+    HFILE pipeh[2];\r
+    APIRET rc;\r
+\r
+    /* mode determines which of stdin or stdout is reconnected to\r
+     * the pipe to the child\r
+     */\r
+    if (strchr(mode, 'r') != NULL) {\r
+        tgt_fd = 1;             /* stdout */\r
+    } else if (strchr(mode, 'w')) {\r
+        tgt_fd = 0;             /* stdin */\r
+    } else {\r
+        *err = ERROR_INVALID_ACCESS;\r
+        return NULL;\r
+    }\r
+\r
+    /* setup the pipe */\r
+    if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) {\r
+        *err = rc;\r
+        return NULL;\r
+    }\r
+\r
+    /* prevent other threads accessing stdio */\r
+    DosEnterCritSec();\r
+\r
+    /* reconnect stdio and execute child */\r
+    oldfd = dup(tgtfd);\r
+    close(tgtfd);\r
+    if (dup2(pipeh[tgtfd], tgtfd) == 0) {\r
+        DosClose(pipeh[tgtfd]);\r
+        rc = async_system(command);\r
+    }\r
+\r
+    /* restore stdio */\r
+    dup2(oldfd, tgtfd);\r
+    close(oldfd);\r
+\r
+    /* allow other threads access to stdio */\r
+    DosExitCritSec();\r
+\r
+    /* if execution of child was successful return file stream */\r
+    if (rc == NO_ERROR)\r
+        return fdopen(pipeh[1 - tgtfd], mode);\r
+    else {\r
+        DosClose(pipeh[1 - tgtfd]);\r
+        *err = rc;\r
+        return NULL;\r
+    }\r
+}\r
+\r
+static PyObject *\r
+posix_popen(PyObject *self, PyObject *args)\r
+{\r
+    char *name;\r
+    char *mode = "r";\r
+    int   err, bufsize = -1;\r
+    FILE *fp;\r
+    PyObject *f;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err);\r
+    Py_END_ALLOW_THREADS\r
+    if (fp == NULL)\r
+        return os2_error(err);\r
+\r
+    f = PyFile_FromFile(fp, name, mode, fclose);\r
+    if (f != NULL)\r
+        PyFile_SetBufSize(f, bufsize);\r
+    return f;\r
+}\r
+\r
+#elif defined(PYCC_GCC)\r
+\r
+/* standard posix version of popen() support */\r
+static PyObject *\r
+posix_popen(PyObject *self, PyObject *args)\r
+{\r
+    char *name;\r
+    char *mode = "r";\r
+    int bufsize = -1;\r
+    FILE *fp;\r
+    PyObject *f;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    fp = popen(name, mode);\r
+    Py_END_ALLOW_THREADS\r
+    if (fp == NULL)\r
+        return posix_error();\r
+    f = PyFile_FromFile(fp, name, mode, pclose);\r
+    if (f != NULL)\r
+        PyFile_SetBufSize(f, bufsize);\r
+    return f;\r
+}\r
+\r
+/* fork() under OS/2 has lots'o'warts\r
+ * EMX supports pipe() and spawn*() so we can synthesize popen[234]()\r
+ * most of this code is a ripoff of the win32 code, but using the\r
+ * capabilities of EMX's C library routines\r
+ */\r
+\r
+/* These tell _PyPopen() whether to return 1, 2, or 3 file objects. */\r
+#define POPEN_1 1\r
+#define POPEN_2 2\r
+#define POPEN_3 3\r
+#define POPEN_4 4\r
+\r
+static PyObject *_PyPopen(char *, int, int, int);\r
+static int _PyPclose(FILE *file);\r
+\r
+/*\r
+ * Internal dictionary mapping popen* file pointers to process handles,\r
+ * for use when retrieving the process exit code.  See _PyPclose() below\r
+ * for more information on this dictionary's use.\r
+ */\r
+static PyObject *_PyPopenProcs = NULL;\r
+\r
+/* os2emx version of popen2()\r
+ *\r
+ * The result of this function is a pipe (file) connected to the\r
+ * process's stdin, and a pipe connected to the process's stdout.\r
+ */\r
+\r
+static PyObject *\r
+os2emx_popen2(PyObject *self, PyObject  *args)\r
+{\r
+    PyObject *f;\r
+    int tm=0;\r
+\r
+    char *cmdstring;\r
+    char *mode = "t";\r
+    int bufsize = -1;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))\r
+        return NULL;\r
+\r
+    if (*mode == 't')\r
+        tm = O_TEXT;\r
+    else if (*mode != 'b') {\r
+        PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");\r
+        return NULL;\r
+    } else\r
+        tm = O_BINARY;\r
+\r
+    f = _PyPopen(cmdstring, tm, POPEN_2, bufsize);\r
+\r
+    return f;\r
+}\r
+\r
+/*\r
+ * Variation on os2emx.popen2\r
+ *\r
+ * The result of this function is 3 pipes - the process's stdin,\r
+ * stdout and stderr\r
+ */\r
+\r
+static PyObject *\r
+os2emx_popen3(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *f;\r
+    int tm = 0;\r
+\r
+    char *cmdstring;\r
+    char *mode = "t";\r
+    int bufsize = -1;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))\r
+        return NULL;\r
+\r
+    if (*mode == 't')\r
+        tm = O_TEXT;\r
+    else if (*mode != 'b') {\r
+        PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");\r
+        return NULL;\r
+    } else\r
+        tm = O_BINARY;\r
+\r
+    f = _PyPopen(cmdstring, tm, POPEN_3, bufsize);\r
+\r
+    return f;\r
+}\r
+\r
+/*\r
+ * Variation on os2emx.popen2\r
+ *\r
+ * The result of this function is 2 pipes - the processes stdin,\r
+ * and stdout+stderr combined as a single pipe.\r
+ */\r
+\r
+static PyObject *\r
+os2emx_popen4(PyObject *self, PyObject  *args)\r
+{\r
+    PyObject *f;\r
+    int tm = 0;\r
+\r
+    char *cmdstring;\r
+    char *mode = "t";\r
+    int bufsize = -1;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))\r
+        return NULL;\r
+\r
+    if (*mode == 't')\r
+        tm = O_TEXT;\r
+    else if (*mode != 'b') {\r
+        PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");\r
+        return NULL;\r
+    } else\r
+        tm = O_BINARY;\r
+\r
+    f = _PyPopen(cmdstring, tm, POPEN_4, bufsize);\r
+\r
+    return f;\r
+}\r
+\r
+/* a couple of structures for convenient handling of multiple\r
+ * file handles and pipes\r
+ */\r
+struct file_ref\r
+{\r
+    int handle;\r
+    int flags;\r
+};\r
+\r
+struct pipe_ref\r
+{\r
+    int rd;\r
+    int wr;\r
+};\r
+\r
+/* The following code is derived from the win32 code */\r
+\r
+static PyObject *\r
+_PyPopen(char *cmdstring, int mode, int n, int bufsize)\r
+{\r
+    struct file_ref stdio[3];\r
+    struct pipe_ref p_fd[3];\r
+    FILE *p_s[3];\r
+    int file_count, i, pipe_err;\r
+    pid_t pipe_pid;\r
+    char *shell, *sh_name, *opt, *rd_mode, *wr_mode;\r
+    PyObject *f, *p_f[3];\r
+\r
+    /* file modes for subsequent fdopen's on pipe handles */\r
+    if (mode == O_TEXT)\r
+    {\r
+        rd_mode = "rt";\r
+        wr_mode = "wt";\r
+    }\r
+    else\r
+    {\r
+        rd_mode = "rb";\r
+        wr_mode = "wb";\r
+    }\r
+\r
+    /* prepare shell references */\r
+    if ((shell = getenv("EMXSHELL")) == NULL)\r
+        if ((shell = getenv("COMSPEC")) == NULL)\r
+        {\r
+            errno = ENOENT;\r
+            return posix_error();\r
+        }\r
+\r
+    sh_name = _getname(shell);\r
+    if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0)\r
+        opt = "/c";\r
+    else\r
+        opt = "-c";\r
+\r
+    /* save current stdio fds + their flags, and set not inheritable */\r
+    i = pipe_err = 0;\r
+    while (pipe_err >= 0 && i < 3)\r
+    {\r
+        pipe_err = stdio[i].handle = dup(i);\r
+        stdio[i].flags = fcntl(i, F_GETFD, 0);\r
+        fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC);\r
+        i++;\r
+    }\r
+    if (pipe_err < 0)\r
+    {\r
+        /* didn't get them all saved - clean up and bail out */\r
+        int saved_err = errno;\r
+        while (i-- > 0)\r
+        {\r
+            close(stdio[i].handle);\r
+        }\r
+        errno = saved_err;\r
+        return posix_error();\r
+    }\r
+\r
+    /* create pipe ends */\r
+    file_count = 2;\r
+    if (n == POPEN_3)\r
+        file_count = 3;\r
+    i = pipe_err = 0;\r
+    while ((pipe_err == 0) && (i < file_count))\r
+        pipe_err = pipe((int *)&p_fd[i++]);\r
+    if (pipe_err < 0)\r
+    {\r
+        /* didn't get them all made - clean up and bail out */\r
+        while (i-- > 0)\r
+        {\r
+            close(p_fd[i].wr);\r
+            close(p_fd[i].rd);\r
+        }\r
+        errno = EPIPE;\r
+        return posix_error();\r
+    }\r
+\r
+    /* change the actual standard IO streams over temporarily,\r
+     * making the retained pipe ends non-inheritable\r
+     */\r
+    pipe_err = 0;\r
+\r
+    /* - stdin */\r
+    if (dup2(p_fd[0].rd, 0) == 0)\r
+    {\r
+        close(p_fd[0].rd);\r
+        i = fcntl(p_fd[0].wr, F_GETFD, 0);\r
+        fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC);\r
+        if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL)\r
+        {\r
+            close(p_fd[0].wr);\r
+            pipe_err = -1;\r
+        }\r
+    }\r
+    else\r
+    {\r
+        pipe_err = -1;\r
+    }\r
+\r
+    /* - stdout */\r
+    if (pipe_err == 0)\r
+    {\r
+        if (dup2(p_fd[1].wr, 1) == 1)\r
+        {\r
+            close(p_fd[1].wr);\r
+            i = fcntl(p_fd[1].rd, F_GETFD, 0);\r
+            fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC);\r
+            if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL)\r
+            {\r
+                close(p_fd[1].rd);\r
+                pipe_err = -1;\r
+            }\r
+        }\r
+        else\r
+        {\r
+            pipe_err = -1;\r
+        }\r
+    }\r
+\r
+    /* - stderr, as required */\r
+    if (pipe_err == 0)\r
+        switch (n)\r
+        {\r
+            case POPEN_3:\r
+            {\r
+                if (dup2(p_fd[2].wr, 2) == 2)\r
+                {\r
+                    close(p_fd[2].wr);\r
+                    i = fcntl(p_fd[2].rd, F_GETFD, 0);\r
+                    fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC);\r
+                    if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL)\r
+                    {\r
+                        close(p_fd[2].rd);\r
+                        pipe_err = -1;\r
+                    }\r
+                }\r
+                else\r
+                {\r
+                    pipe_err = -1;\r
+                }\r
+                break;\r
+            }\r
+\r
+            case POPEN_4:\r
+            {\r
+                if (dup2(1, 2) != 2)\r
+                {\r
+                    pipe_err = -1;\r
+                }\r
+                break;\r
+            }\r
+        }\r
+\r
+    /* spawn the child process */\r
+    if (pipe_err == 0)\r
+    {\r
+        pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0);\r
+        if (pipe_pid == -1)\r
+        {\r
+            pipe_err = -1;\r
+        }\r
+        else\r
+        {\r
+            /* save the PID into the FILE structure\r
+             * NOTE: this implementation doesn't actually\r
+             * take advantage of this, but do it for\r
+             * completeness - AIM Apr01\r
+             */\r
+            for (i = 0; i < file_count; i++)\r
+                p_s[i]->_pid = pipe_pid;\r
+        }\r
+    }\r
+\r
+    /* reset standard IO to normal */\r
+    for (i = 0; i < 3; i++)\r
+    {\r
+        dup2(stdio[i].handle, i);\r
+        fcntl(i, F_SETFD, stdio[i].flags);\r
+        close(stdio[i].handle);\r
+    }\r
+\r
+    /* if any remnant problems, clean up and bail out */\r
+    if (pipe_err < 0)\r
+    {\r
+        for (i = 0; i < 3; i++)\r
+        {\r
+            close(p_fd[i].rd);\r
+            close(p_fd[i].wr);\r
+        }\r
+        errno = EPIPE;\r
+        return posix_error_with_filename(cmdstring);\r
+    }\r
+\r
+    /* build tuple of file objects to return */\r
+    if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL)\r
+        PyFile_SetBufSize(p_f[0], bufsize);\r
+    if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL)\r
+        PyFile_SetBufSize(p_f[1], bufsize);\r
+    if (n == POPEN_3)\r
+    {\r
+        if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL)\r
+            PyFile_SetBufSize(p_f[0], bufsize);\r
+        f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]);\r
+    }\r
+    else\r
+        f = PyTuple_Pack(2, p_f[0], p_f[1]);\r
+\r
+    /*\r
+     * Insert the files we've created into the process dictionary\r
+     * all referencing the list with the process handle and the\r
+     * initial number of files (see description below in _PyPclose).\r
+     * Since if _PyPclose later tried to wait on a process when all\r
+     * handles weren't closed, it could create a deadlock with the\r
+     * child, we spend some energy here to try to ensure that we\r
+     * either insert all file handles into the dictionary or none\r
+     * at all.  It's a little clumsy with the various popen modes\r
+     * and variable number of files involved.\r
+     */\r
+    if (!_PyPopenProcs)\r
+    {\r
+        _PyPopenProcs = PyDict_New();\r
+    }\r
+\r
+    if (_PyPopenProcs)\r
+    {\r
+        PyObject *procObj, *pidObj, *intObj, *fileObj[3];\r
+        int ins_rc[3];\r
+\r
+        fileObj[0] = fileObj[1] = fileObj[2] = NULL;\r
+        ins_rc[0]  = ins_rc[1]  = ins_rc[2]  = 0;\r
+\r
+        procObj = PyList_New(2);\r
+        pidObj = PyLong_FromPid(pipe_pid);\r
+        intObj = PyInt_FromLong((long) file_count);\r
+\r
+        if (procObj && pidObj && intObj)\r
+        {\r
+            PyList_SetItem(procObj, 0, pidObj);\r
+            PyList_SetItem(procObj, 1, intObj);\r
+\r
+            fileObj[0] = PyLong_FromVoidPtr(p_s[0]);\r
+            if (fileObj[0])\r
+            {\r
+                ins_rc[0] = PyDict_SetItem(_PyPopenProcs,\r
+                                           fileObj[0],\r
+                                           procObj);\r
+            }\r
+            fileObj[1] = PyLong_FromVoidPtr(p_s[1]);\r
+            if (fileObj[1])\r
+            {\r
+                ins_rc[1] = PyDict_SetItem(_PyPopenProcs,\r
+                                           fileObj[1],\r
+                                           procObj);\r
+            }\r
+            if (file_count >= 3)\r
+            {\r
+                fileObj[2] = PyLong_FromVoidPtr(p_s[2]);\r
+                if (fileObj[2])\r
+                {\r
+                    ins_rc[2] = PyDict_SetItem(_PyPopenProcs,\r
+                                               fileObj[2],\r
+                                               procObj);\r
+                }\r
+            }\r
+\r
+            if (ins_rc[0] < 0 || !fileObj[0] ||\r
+                ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||\r
+                ins_rc[2] < 0 || (file_count > 2 && !fileObj[2]))\r
+            {\r
+                /* Something failed - remove any dictionary\r
+                 * entries that did make it.\r
+                 */\r
+                if (!ins_rc[0] && fileObj[0])\r
+                {\r
+                    PyDict_DelItem(_PyPopenProcs,\r
+                                   fileObj[0]);\r
+                }\r
+                if (!ins_rc[1] && fileObj[1])\r
+                {\r
+                    PyDict_DelItem(_PyPopenProcs,\r
+                                   fileObj[1]);\r
+                }\r
+                if (!ins_rc[2] && fileObj[2])\r
+                {\r
+                    PyDict_DelItem(_PyPopenProcs,\r
+                                   fileObj[2]);\r
+                }\r
+            }\r
+        }\r
+\r
+        /*\r
+         * Clean up our localized references for the dictionary keys\r
+         * and value since PyDict_SetItem will Py_INCREF any copies\r
+         * that got placed in the dictionary.\r
+         */\r
+        Py_XDECREF(procObj);\r
+        Py_XDECREF(fileObj[0]);\r
+        Py_XDECREF(fileObj[1]);\r
+        Py_XDECREF(fileObj[2]);\r
+    }\r
+\r
+    /* Child is launched. */\r
+    return f;\r
+}\r
+\r
+/*\r
+ * Wrapper for fclose() to use for popen* files, so we can retrieve the\r
+ * exit code for the child process and return as a result of the close.\r
+ *\r
+ * This function uses the _PyPopenProcs dictionary in order to map the\r
+ * input file pointer to information about the process that was\r
+ * originally created by the popen* call that created the file pointer.\r
+ * The dictionary uses the file pointer as a key (with one entry\r
+ * inserted for each file returned by the original popen* call) and a\r
+ * single list object as the value for all files from a single call.\r
+ * The list object contains the Win32 process handle at [0], and a file\r
+ * count at [1], which is initialized to the total number of file\r
+ * handles using that list.\r
+ *\r
+ * This function closes whichever handle it is passed, and decrements\r
+ * the file count in the dictionary for the process handle pointed to\r
+ * by this file.  On the last close (when the file count reaches zero),\r
+ * this function will wait for the child process and then return its\r
+ * exit code as the result of the close() operation.  This permits the\r
+ * files to be closed in any order - it is always the close() of the\r
+ * final handle that will return the exit code.\r
+ *\r
+ * NOTE: This function is currently called with the GIL released.\r
+ * hence we use the GILState API to manage our state.\r
+ */\r
+\r
+static int _PyPclose(FILE *file)\r
+{\r
+    int result;\r
+    int exit_code;\r
+    pid_t pipe_pid;\r
+    PyObject *procObj, *pidObj, *intObj, *fileObj;\r
+    int file_count;\r
+#ifdef WITH_THREAD\r
+    PyGILState_STATE state;\r
+#endif\r
+\r
+    /* Close the file handle first, to ensure it can't block the\r
+     * child from exiting if it's the last handle.\r
+     */\r
+    result = fclose(file);\r
+\r
+#ifdef WITH_THREAD\r
+    state = PyGILState_Ensure();\r
+#endif\r
+    if (_PyPopenProcs)\r
+    {\r
+        if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&\r
+            (procObj = PyDict_GetItem(_PyPopenProcs,\r
+                                      fileObj)) != NULL &&\r
+            (pidObj = PyList_GetItem(procObj,0)) != NULL &&\r
+            (intObj = PyList_GetItem(procObj,1)) != NULL)\r
+        {\r
+            pipe_pid = (pid_t) PyLong_AsPid(pidObj);\r
+            file_count = (int) PyInt_AsLong(intObj);\r
+\r
+            if (file_count > 1)\r
+            {\r
+                /* Still other files referencing process */\r
+                file_count--;\r
+                PyList_SetItem(procObj,1,\r
+                               PyInt_FromLong((long) file_count));\r
+            }\r
+            else\r
+            {\r
+                /* Last file for this process */\r
+                if (result != EOF &&\r
+                    waitpid(pipe_pid, &exit_code, 0) == pipe_pid)\r
+                {\r
+                    /* extract exit status */\r
+                    if (WIFEXITED(exit_code))\r
+                    {\r
+                        result = WEXITSTATUS(exit_code);\r
+                    }\r
+                    else\r
+                    {\r
+                        errno = EPIPE;\r
+                        result = -1;\r
+                    }\r
+                }\r
+                else\r
+                {\r
+                    /* Indicate failure - this will cause the file object\r
+                     * to raise an I/O error and translate the last\r
+                     * error code from errno.  We do have a problem with\r
+                     * last errors that overlap the normal errno table,\r
+                     * but that's a consistent problem with the file object.\r
+                     */\r
+                    result = -1;\r
+                }\r
+            }\r
+\r
+            /* Remove this file pointer from dictionary */\r
+            PyDict_DelItem(_PyPopenProcs, fileObj);\r
+\r
+            if (PyDict_Size(_PyPopenProcs) == 0)\r
+            {\r
+                Py_DECREF(_PyPopenProcs);\r
+                _PyPopenProcs = NULL;\r
+            }\r
+\r
+        } /* if object retrieval ok */\r
+\r
+        Py_XDECREF(fileObj);\r
+    } /* if _PyPopenProcs */\r
+\r
+#ifdef WITH_THREAD\r
+    PyGILState_Release(state);\r
+#endif\r
+    return result;\r
+}\r
+\r
+#endif /* PYCC_??? */\r
+\r
+#elif defined(MS_WINDOWS)\r
+\r
+/*\r
+ * Portable 'popen' replacement for Win32.\r
+ *\r
+ * Written by Bill Tutt <billtut@microsoft.com>.  Minor tweaks\r
+ * and 2.0 integration by Fredrik Lundh <fredrik@pythonware.com>\r
+ * Return code handling by David Bolen <db3l@fitlinxx.com>.\r
+ */\r
+\r
+#include <malloc.h>\r
+#include <io.h>\r
+#include <fcntl.h>\r
+\r
+/* These tell _PyPopen() wether to return 1, 2, or 3 file objects. */\r
+#define POPEN_1 1\r
+#define POPEN_2 2\r
+#define POPEN_3 3\r
+#define POPEN_4 4\r
+\r
+static PyObject *_PyPopen(char *, int, int);\r
+static int _PyPclose(FILE *file);\r
+\r
+/*\r
+ * Internal dictionary mapping popen* file pointers to process handles,\r
+ * for use when retrieving the process exit code.  See _PyPclose() below\r
+ * for more information on this dictionary's use.\r
+ */\r
+static PyObject *_PyPopenProcs = NULL;\r
+\r
+\r
+/* popen that works from a GUI.\r
+ *\r
+ * The result of this function is a pipe (file) connected to the\r
+ * processes stdin or stdout, depending on the requested mode.\r
+ */\r
+\r
+static PyObject *\r
+posix_popen(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *f;\r
+    int tm = 0;\r
+\r
+    char *cmdstring;\r
+    char *mode = "r";\r
+    int bufsize = -1;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize))\r
+        return NULL;\r
+\r
+    if (*mode == 'r')\r
+        tm = _O_RDONLY;\r
+    else if (*mode != 'w') {\r
+        PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'");\r
+        return NULL;\r
+    } else\r
+        tm = _O_WRONLY;\r
+\r
+    if (bufsize != -1) {\r
+        PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1");\r
+        return NULL;\r
+    }\r
+\r
+    if (*(mode+1) == 't')\r
+        f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);\r
+    else if (*(mode+1) == 'b')\r
+        f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1);\r
+    else\r
+        f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);\r
+\r
+    return f;\r
+}\r
+\r
+/* Variation on win32pipe.popen\r
+ *\r
+ * The result of this function is a pipe (file) connected to the\r
+ * process's stdin, and a pipe connected to the process's stdout.\r
+ */\r
+\r
+static PyObject *\r
+win32_popen2(PyObject *self, PyObject  *args)\r
+{\r
+    PyObject *f;\r
+    int tm=0;\r
+\r
+    char *cmdstring;\r
+    char *mode = "t";\r
+    int bufsize = -1;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))\r
+        return NULL;\r
+\r
+    if (*mode == 't')\r
+        tm = _O_TEXT;\r
+    else if (*mode != 'b') {\r
+        PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'");\r
+        return NULL;\r
+    } else\r
+        tm = _O_BINARY;\r
+\r
+    if (bufsize != -1) {\r
+        PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1");\r
+        return NULL;\r
+    }\r
+\r
+    f = _PyPopen(cmdstring, tm, POPEN_2);\r
+\r
+    return f;\r
+}\r
+\r
+/*\r
+ * Variation on <om win32pipe.popen>\r
+ *\r
+ * The result of this function is 3 pipes - the process's stdin,\r
+ * stdout and stderr\r
+ */\r
+\r
+static PyObject *\r
+win32_popen3(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *f;\r
+    int tm = 0;\r
+\r
+    char *cmdstring;\r
+    char *mode = "t";\r
+    int bufsize = -1;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))\r
+        return NULL;\r
+\r
+    if (*mode == 't')\r
+        tm = _O_TEXT;\r
+    else if (*mode != 'b') {\r
+        PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'");\r
+        return NULL;\r
+    } else\r
+        tm = _O_BINARY;\r
+\r
+    if (bufsize != -1) {\r
+        PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1");\r
+        return NULL;\r
+    }\r
+\r
+    f = _PyPopen(cmdstring, tm, POPEN_3);\r
+\r
+    return f;\r
+}\r
+\r
+/*\r
+ * Variation on win32pipe.popen\r
+ *\r
+ * The result of this function is 2 pipes - the processes stdin,\r
+ * and stdout+stderr combined as a single pipe.\r
+ */\r
+\r
+static PyObject *\r
+win32_popen4(PyObject *self, PyObject  *args)\r
+{\r
+    PyObject *f;\r
+    int tm = 0;\r
+\r
+    char *cmdstring;\r
+    char *mode = "t";\r
+    int bufsize = -1;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))\r
+        return NULL;\r
+\r
+    if (*mode == 't')\r
+        tm = _O_TEXT;\r
+    else if (*mode != 'b') {\r
+        PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'");\r
+        return NULL;\r
+    } else\r
+        tm = _O_BINARY;\r
+\r
+    if (bufsize != -1) {\r
+        PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1");\r
+        return NULL;\r
+    }\r
+\r
+    f = _PyPopen(cmdstring, tm, POPEN_4);\r
+\r
+    return f;\r
+}\r
+\r
+static BOOL\r
+_PyPopenCreateProcess(char *cmdstring,\r
+                      HANDLE hStdin,\r
+                      HANDLE hStdout,\r
+                      HANDLE hStderr,\r
+                      HANDLE *hProcess)\r
+{\r
+    PROCESS_INFORMATION piProcInfo;\r
+    STARTUPINFO siStartInfo;\r
+    DWORD dwProcessFlags = 0;  /* no NEW_CONSOLE by default for Ctrl+C handling */\r
+    char *s1,*s2, *s3 = " /c ";\r
+    const char *szConsoleSpawn = "w9xpopen.exe";\r
+    int i;\r
+    Py_ssize_t x;\r
+\r
+    if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) {\r
+        char *comshell;\r
+\r
+        s1 = (char *)alloca(i);\r
+        if (!(x = GetEnvironmentVariable("COMSPEC", s1, i)))\r
+            /* x < i, so x fits into an integer */\r
+            return (int)x;\r
+\r
+        /* Explicitly check if we are using COMMAND.COM.  If we are\r
+         * then use the w9xpopen hack.\r
+         */\r
+        comshell = s1 + x;\r
+        while (comshell >= s1 && *comshell != '\\')\r
+            --comshell;\r
+        ++comshell;\r
+\r
+        if (GetVersion() < 0x80000000 &&\r
+            _stricmp(comshell, "command.com") != 0) {\r
+            /* NT/2000 and not using command.com. */\r
+            x = i + strlen(s3) + strlen(cmdstring) + 1;\r
+            s2 = (char *)alloca(x);\r
+            ZeroMemory(s2, x);\r
+            PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring);\r
+        }\r
+        else {\r
+            /*\r
+             * Oh gag, we're on Win9x or using COMMAND.COM. Use\r
+             * the workaround listed in KB: Q150956\r
+             */\r
+            char modulepath[_MAX_PATH];\r
+            struct stat statinfo;\r
+            GetModuleFileName(NULL, modulepath, sizeof(modulepath));\r
+            for (x = i = 0; modulepath[i]; i++)\r
+                if (modulepath[i] == SEP)\r
+                    x = i+1;\r
+            modulepath[x] = '\0';\r
+            /* Create the full-name to w9xpopen, so we can test it exists */\r
+            strncat(modulepath,\r
+                    szConsoleSpawn,\r
+                    (sizeof(modulepath)/sizeof(modulepath[0]))\r
+                        -strlen(modulepath));\r
+            if (stat(modulepath, &statinfo) != 0) {\r
+                size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]);\r
+                /* Eeek - file-not-found - possibly an embedding\r
+                   situation - see if we can locate it in sys.prefix\r
+                */\r
+                strncpy(modulepath,\r
+                        Py_GetExecPrefix(),\r
+                        mplen);\r
+                modulepath[mplen-1] = '\0';\r
+                if (modulepath[strlen(modulepath)-1] != '\\')\r
+                    strcat(modulepath, "\\");\r
+                strncat(modulepath,\r
+                        szConsoleSpawn,\r
+                        mplen-strlen(modulepath));\r
+                /* No where else to look - raise an easily identifiable\r
+                   error, rather than leaving Windows to report\r
+                   "file not found" - as the user is probably blissfully\r
+                   unaware this shim EXE is used, and it will confuse them.\r
+                   (well, it confused me for a while ;-)\r
+                */\r
+                if (stat(modulepath, &statinfo) != 0) {\r
+                    PyErr_Format(PyExc_RuntimeError,\r
+                                 "Can not locate '%s' which is needed "\r
+                                 "for popen to work with your shell "\r
+                                 "or platform.",\r
+                                 szConsoleSpawn);\r
+                    return FALSE;\r
+                }\r
+            }\r
+            x = i + strlen(s3) + strlen(cmdstring) + 1 +\r
+                strlen(modulepath) +\r
+                strlen(szConsoleSpawn) + 1;\r
+\r
+            s2 = (char *)alloca(x);\r
+            ZeroMemory(s2, x);\r
+            /* To maintain correct argument passing semantics,\r
+               we pass the command-line as it stands, and allow\r
+               quoting to be applied.  w9xpopen.exe will then\r
+               use its argv vector, and re-quote the necessary\r
+               args for the ultimate child process.\r
+            */\r
+            PyOS_snprintf(\r
+                s2, x,\r
+                "\"%s\" %s%s%s",\r
+                modulepath,\r
+                s1,\r
+                s3,\r
+                cmdstring);\r
+            /* Not passing CREATE_NEW_CONSOLE has been known to\r
+               cause random failures on win9x.  Specifically a\r
+               dialog:\r
+               "Your program accessed mem currently in use at xxx"\r
+               and a hopeful warning about the stability of your\r
+               system.\r
+               Cost is Ctrl+C won't kill children, but anyone\r
+               who cares can have a go!\r
+            */\r
+            dwProcessFlags |= CREATE_NEW_CONSOLE;\r
+        }\r
+    }\r
+\r
+    /* Could be an else here to try cmd.exe / command.com in the path\r
+       Now we'll just error out.. */\r
+    else {\r
+        PyErr_SetString(PyExc_RuntimeError,\r
+                        "Cannot locate a COMSPEC environment variable to "\r
+                        "use as the shell");\r
+        return FALSE;\r
+    }\r
+\r
+    ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));\r
+    siStartInfo.cb = sizeof(STARTUPINFO);\r
+    siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;\r
+    siStartInfo.hStdInput = hStdin;\r
+    siStartInfo.hStdOutput = hStdout;\r
+    siStartInfo.hStdError = hStderr;\r
+    siStartInfo.wShowWindow = SW_HIDE;\r
+\r
+    if (CreateProcess(NULL,\r
+                      s2,\r
+                      NULL,\r
+                      NULL,\r
+                      TRUE,\r
+                      dwProcessFlags,\r
+                      NULL,\r
+                      NULL,\r
+                      &siStartInfo,\r
+                      &piProcInfo) ) {\r
+        /* Close the handles now so anyone waiting is woken. */\r
+        CloseHandle(piProcInfo.hThread);\r
+\r
+        /* Return process handle */\r
+        *hProcess = piProcInfo.hProcess;\r
+        return TRUE;\r
+    }\r
+    win32_error("CreateProcess", s2);\r
+    return FALSE;\r
+}\r
+\r
+/* The following code is based off of KB: Q190351 */\r
+\r
+static PyObject *\r
+_PyPopen(char *cmdstring, int mode, int n)\r
+{\r
+    HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr,\r
+        hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup,\r
+        hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */\r
+\r
+    SECURITY_ATTRIBUTES saAttr;\r
+    BOOL fSuccess;\r
+    int fd1, fd2, fd3;\r
+    FILE *f1, *f2, *f3;\r
+    long file_count;\r
+    PyObject *f;\r
+\r
+    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);\r
+    saAttr.bInheritHandle = TRUE;\r
+    saAttr.lpSecurityDescriptor = NULL;\r
+\r
+    if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))\r
+        return win32_error("CreatePipe", NULL);\r
+\r
+    /* Create new output read handle and the input write handle. Set\r
+     * the inheritance properties to FALSE. Otherwise, the child inherits\r
+     * these handles; resulting in non-closeable handles to the pipes\r
+     * being created. */\r
+     fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,\r
+                                GetCurrentProcess(), &hChildStdinWrDup, 0,\r
+                                FALSE,\r
+                                DUPLICATE_SAME_ACCESS);\r
+     if (!fSuccess)\r
+         return win32_error("DuplicateHandle", NULL);\r
+\r
+     /* Close the inheritable version of ChildStdin\r
+    that we're using. */\r
+     CloseHandle(hChildStdinWr);\r
+\r
+     if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))\r
+         return win32_error("CreatePipe", NULL);\r
+\r
+     fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,\r
+                                GetCurrentProcess(), &hChildStdoutRdDup, 0,\r
+                                FALSE, DUPLICATE_SAME_ACCESS);\r
+     if (!fSuccess)\r
+         return win32_error("DuplicateHandle", NULL);\r
+\r
+     /* Close the inheritable version of ChildStdout\r
+        that we're using. */\r
+     CloseHandle(hChildStdoutRd);\r
+\r
+     if (n != POPEN_4) {\r
+         if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0))\r
+             return win32_error("CreatePipe", NULL);\r
+         fSuccess = DuplicateHandle(GetCurrentProcess(),\r
+                                    hChildStderrRd,\r
+                                    GetCurrentProcess(),\r
+                                    &hChildStderrRdDup, 0,\r
+                                    FALSE, DUPLICATE_SAME_ACCESS);\r
+         if (!fSuccess)\r
+             return win32_error("DuplicateHandle", NULL);\r
+         /* Close the inheritable version of ChildStdErr that we're using. */\r
+         CloseHandle(hChildStderrRd);\r
+     }\r
+\r
+     switch (n) {\r
+     case POPEN_1:\r
+         switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) {\r
+         case _O_WRONLY | _O_TEXT:\r
+             /* Case for writing to child Stdin in text mode. */\r
+             fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);\r
+             f1 = _fdopen(fd1, "w");\r
+             f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose);\r
+             PyFile_SetBufSize(f, 0);\r
+             /* We don't care about these pipes anymore, so close them. */\r
+             CloseHandle(hChildStdoutRdDup);\r
+             CloseHandle(hChildStderrRdDup);\r
+             break;\r
+\r
+         case _O_RDONLY | _O_TEXT:\r
+             /* Case for reading from child Stdout in text mode. */\r
+             fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);\r
+             f1 = _fdopen(fd1, "r");\r
+             f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose);\r
+             PyFile_SetBufSize(f, 0);\r
+             /* We don't care about these pipes anymore, so close them. */\r
+             CloseHandle(hChildStdinWrDup);\r
+             CloseHandle(hChildStderrRdDup);\r
+             break;\r
+\r
+         case _O_RDONLY | _O_BINARY:\r
+             /* Case for readinig from child Stdout in binary mode. */\r
+             fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);\r
+             f1 = _fdopen(fd1, "rb");\r
+             f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose);\r
+             PyFile_SetBufSize(f, 0);\r
+             /* We don't care about these pipes anymore, so close them. */\r
+             CloseHandle(hChildStdinWrDup);\r
+             CloseHandle(hChildStderrRdDup);\r
+             break;\r
+\r
+         case _O_WRONLY | _O_BINARY:\r
+             /* Case for writing to child Stdin in binary mode. */\r
+             fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);\r
+             f1 = _fdopen(fd1, "wb");\r
+             f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose);\r
+             PyFile_SetBufSize(f, 0);\r
+             /* We don't care about these pipes anymore, so close them. */\r
+             CloseHandle(hChildStdoutRdDup);\r
+             CloseHandle(hChildStderrRdDup);\r
+             break;\r
+         }\r
+         file_count = 1;\r
+         break;\r
+\r
+     case POPEN_2:\r
+     case POPEN_4:\r
+     {\r
+         char *m1, *m2;\r
+         PyObject *p1, *p2;\r
+\r
+         if (mode & _O_TEXT) {\r
+             m1 = "r";\r
+             m2 = "w";\r
+         } else {\r
+             m1 = "rb";\r
+             m2 = "wb";\r
+         }\r
+\r
+         fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);\r
+         f1 = _fdopen(fd1, m2);\r
+         fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);\r
+         f2 = _fdopen(fd2, m1);\r
+         p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);\r
+         PyFile_SetBufSize(p1, 0);\r
+         p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);\r
+         PyFile_SetBufSize(p2, 0);\r
+\r
+         if (n != 4)\r
+             CloseHandle(hChildStderrRdDup);\r
+\r
+         f = PyTuple_Pack(2,p1,p2);\r
+         Py_XDECREF(p1);\r
+         Py_XDECREF(p2);\r
+         file_count = 2;\r
+         break;\r
+     }\r
+\r
+     case POPEN_3:\r
+     {\r
+         char *m1, *m2;\r
+         PyObject *p1, *p2, *p3;\r
+\r
+         if (mode & _O_TEXT) {\r
+             m1 = "r";\r
+             m2 = "w";\r
+         } else {\r
+             m1 = "rb";\r
+             m2 = "wb";\r
+         }\r
+\r
+         fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);\r
+         f1 = _fdopen(fd1, m2);\r
+         fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);\r
+         f2 = _fdopen(fd2, m1);\r
+         fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode);\r
+         f3 = _fdopen(fd3, m1);\r
+         p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);\r
+         p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);\r
+         p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose);\r
+         PyFile_SetBufSize(p1, 0);\r
+         PyFile_SetBufSize(p2, 0);\r
+         PyFile_SetBufSize(p3, 0);\r
+         f = PyTuple_Pack(3,p1,p2,p3);\r
+         Py_XDECREF(p1);\r
+         Py_XDECREF(p2);\r
+         Py_XDECREF(p3);\r
+         file_count = 3;\r
+         break;\r
+     }\r
+     }\r
+\r
+     if (n == POPEN_4) {\r
+         if (!_PyPopenCreateProcess(cmdstring,\r
+                                    hChildStdinRd,\r
+                                    hChildStdoutWr,\r
+                                    hChildStdoutWr,\r
+                                    &hProcess))\r
+             return NULL;\r
+     }\r
+     else {\r
+         if (!_PyPopenCreateProcess(cmdstring,\r
+                                    hChildStdinRd,\r
+                                    hChildStdoutWr,\r
+                                    hChildStderrWr,\r
+                                    &hProcess))\r
+             return NULL;\r
+     }\r
+\r
+     /*\r
+      * Insert the files we've created into the process dictionary\r
+      * all referencing the list with the process handle and the\r
+      * initial number of files (see description below in _PyPclose).\r
+      * Since if _PyPclose later tried to wait on a process when all\r
+      * handles weren't closed, it could create a deadlock with the\r
+      * child, we spend some energy here to try to ensure that we\r
+      * either insert all file handles into the dictionary or none\r
+      * at all.  It's a little clumsy with the various popen modes\r
+      * and variable number of files involved.\r
+      */\r
+     if (!_PyPopenProcs) {\r
+         _PyPopenProcs = PyDict_New();\r
+     }\r
+\r
+     if (_PyPopenProcs) {\r
+         PyObject *procObj, *hProcessObj, *intObj, *fileObj[3];\r
+         int ins_rc[3];\r
+\r
+         fileObj[0] = fileObj[1] = fileObj[2] = NULL;\r
+         ins_rc[0]  = ins_rc[1]  = ins_rc[2]  = 0;\r
+\r
+         procObj = PyList_New(2);\r
+         hProcessObj = PyLong_FromVoidPtr(hProcess);\r
+         intObj = PyInt_FromLong(file_count);\r
+\r
+         if (procObj && hProcessObj && intObj) {\r
+             PyList_SetItem(procObj,0,hProcessObj);\r
+             PyList_SetItem(procObj,1,intObj);\r
+\r
+             fileObj[0] = PyLong_FromVoidPtr(f1);\r
+             if (fileObj[0]) {\r
+                ins_rc[0] = PyDict_SetItem(_PyPopenProcs,\r
+                                           fileObj[0],\r
+                                           procObj);\r
+             }\r
+             if (file_count >= 2) {\r
+                 fileObj[1] = PyLong_FromVoidPtr(f2);\r
+                 if (fileObj[1]) {\r
+                    ins_rc[1] = PyDict_SetItem(_PyPopenProcs,\r
+                                               fileObj[1],\r
+                                               procObj);\r
+                 }\r
+             }\r
+             if (file_count >= 3) {\r
+                 fileObj[2] = PyLong_FromVoidPtr(f3);\r
+                 if (fileObj[2]) {\r
+                    ins_rc[2] = PyDict_SetItem(_PyPopenProcs,\r
+                                               fileObj[2],\r
+                                               procObj);\r
+                 }\r
+             }\r
+\r
+             if (ins_rc[0] < 0 || !fileObj[0] ||\r
+                 ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||\r
+                 ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) {\r
+                 /* Something failed - remove any dictionary\r
+                  * entries that did make it.\r
+                  */\r
+                 if (!ins_rc[0] && fileObj[0]) {\r
+                     PyDict_DelItem(_PyPopenProcs,\r
+                                    fileObj[0]);\r
+                 }\r
+                 if (!ins_rc[1] && fileObj[1]) {\r
+                     PyDict_DelItem(_PyPopenProcs,\r
+                                    fileObj[1]);\r
+                 }\r
+                 if (!ins_rc[2] && fileObj[2]) {\r
+                     PyDict_DelItem(_PyPopenProcs,\r
+                                    fileObj[2]);\r
+                 }\r
+             }\r
+         }\r
+\r
+         /*\r
+          * Clean up our localized references for the dictionary keys\r
+          * and value since PyDict_SetItem will Py_INCREF any copies\r
+          * that got placed in the dictionary.\r
+          */\r
+         Py_XDECREF(procObj);\r
+         Py_XDECREF(fileObj[0]);\r
+         Py_XDECREF(fileObj[1]);\r
+         Py_XDECREF(fileObj[2]);\r
+     }\r
+\r
+     /* Child is launched. Close the parents copy of those pipe\r
+      * handles that only the child should have open.  You need to\r
+      * make sure that no handles to the write end of the output pipe\r
+      * are maintained in this process or else the pipe will not close\r
+      * when the child process exits and the ReadFile will hang. */\r
+\r
+     if (!CloseHandle(hChildStdinRd))\r
+         return win32_error("CloseHandle", NULL);\r
+\r
+     if (!CloseHandle(hChildStdoutWr))\r
+         return win32_error("CloseHandle", NULL);\r
+\r
+     if ((n != 4) && (!CloseHandle(hChildStderrWr)))\r
+         return win32_error("CloseHandle", NULL);\r
+\r
+     return f;\r
+}\r
+\r
+/*\r
+ * Wrapper for fclose() to use for popen* files, so we can retrieve the\r
+ * exit code for the child process and return as a result of the close.\r
+ *\r
+ * This function uses the _PyPopenProcs dictionary in order to map the\r
+ * input file pointer to information about the process that was\r
+ * originally created by the popen* call that created the file pointer.\r
+ * The dictionary uses the file pointer as a key (with one entry\r
+ * inserted for each file returned by the original popen* call) and a\r
+ * single list object as the value for all files from a single call.\r
+ * The list object contains the Win32 process handle at [0], and a file\r
+ * count at [1], which is initialized to the total number of file\r
+ * handles using that list.\r
+ *\r
+ * This function closes whichever handle it is passed, and decrements\r
+ * the file count in the dictionary for the process handle pointed to\r
+ * by this file.  On the last close (when the file count reaches zero),\r
+ * this function will wait for the child process and then return its\r
+ * exit code as the result of the close() operation.  This permits the\r
+ * files to be closed in any order - it is always the close() of the\r
+ * final handle that will return the exit code.\r
+ *\r
+ * NOTE: This function is currently called with the GIL released.\r
+ * hence we use the GILState API to manage our state.\r
+ */\r
+\r
+static int _PyPclose(FILE *file)\r
+{\r
+    int result;\r
+    DWORD exit_code;\r
+    HANDLE hProcess;\r
+    PyObject *procObj, *hProcessObj, *intObj, *fileObj;\r
+    long file_count;\r
+#ifdef WITH_THREAD\r
+    PyGILState_STATE state;\r
+#endif\r
+\r
+    /* Close the file handle first, to ensure it can't block the\r
+     * child from exiting if it's the last handle.\r
+     */\r
+    result = fclose(file);\r
+#ifdef WITH_THREAD\r
+    state = PyGILState_Ensure();\r
+#endif\r
+    if (_PyPopenProcs) {\r
+        if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&\r
+            (procObj = PyDict_GetItem(_PyPopenProcs,\r
+                                      fileObj)) != NULL &&\r
+            (hProcessObj = PyList_GetItem(procObj,0)) != NULL &&\r
+            (intObj = PyList_GetItem(procObj,1)) != NULL) {\r
+\r
+            hProcess = PyLong_AsVoidPtr(hProcessObj);\r
+            file_count = PyInt_AsLong(intObj);\r
+\r
+            if (file_count > 1) {\r
+                /* Still other files referencing process */\r
+                file_count--;\r
+                PyList_SetItem(procObj,1,\r
+                               PyInt_FromLong(file_count));\r
+            } else {\r
+                /* Last file for this process */\r
+                if (result != EOF &&\r
+                    WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED &&\r
+                    GetExitCodeProcess(hProcess, &exit_code)) {\r
+                    /* Possible truncation here in 16-bit environments, but\r
+                     * real exit codes are just the lower byte in any event.\r
+                     */\r
+                    result = exit_code;\r
+                } else {\r
+                    /* Indicate failure - this will cause the file object\r
+                     * to raise an I/O error and translate the last Win32\r
+                     * error code from errno.  We do have a problem with\r
+                     * last errors that overlap the normal errno table,\r
+                     * but that's a consistent problem with the file object.\r
+                     */\r
+                    if (result != EOF) {\r
+                        /* If the error wasn't from the fclose(), then\r
+                         * set errno for the file object error handling.\r
+                         */\r
+                        errno = GetLastError();\r
+                    }\r
+                    result = -1;\r
+                }\r
+\r
+                /* Free up the native handle at this point */\r
+                CloseHandle(hProcess);\r
+            }\r
+\r
+            /* Remove this file pointer from dictionary */\r
+            PyDict_DelItem(_PyPopenProcs, fileObj);\r
+\r
+            if (PyDict_Size(_PyPopenProcs) == 0) {\r
+                Py_DECREF(_PyPopenProcs);\r
+                _PyPopenProcs = NULL;\r
+            }\r
+\r
+        } /* if object retrieval ok */\r
+\r
+        Py_XDECREF(fileObj);\r
+    } /* if _PyPopenProcs */\r
+\r
+#ifdef WITH_THREAD\r
+    PyGILState_Release(state);\r
+#endif\r
+    return result;\r
+}\r
+\r
+#else /* which OS? */\r
+static PyObject *\r
+posix_popen(PyObject *self, PyObject *args)\r
+{\r
+    char *name;\r
+    char *mode = "r";\r
+    int bufsize = -1;\r
+    FILE *fp;\r
+    PyObject *f;\r
+    if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))\r
+        return NULL;\r
+    /* Strip mode of binary or text modifiers */\r
+    if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0)\r
+        mode = "r";\r
+    else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0)\r
+        mode = "w";\r
+    Py_BEGIN_ALLOW_THREADS\r
+    fp = popen(name, mode);\r
+    Py_END_ALLOW_THREADS\r
+    if (fp == NULL)\r
+        return posix_error();\r
+    f = PyFile_FromFile(fp, name, mode, pclose);\r
+    if (f != NULL)\r
+        PyFile_SetBufSize(f, bufsize);\r
+    return f;\r
+}\r
+\r
+#endif /* PYOS_??? */\r
+#endif /* HAVE_POPEN */\r
+\r
+\r
+#ifdef HAVE_SETUID\r
+PyDoc_STRVAR(posix_setuid__doc__,\r
+"setuid(uid)\n\n\\r
+Set the current process's user id.");\r
+\r
+static PyObject *\r
+posix_setuid(PyObject *self, PyObject *args)\r
+{\r
+    long uid_arg;\r
+    uid_t uid;\r
+    if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg))\r
+        return NULL;\r
+    uid = uid_arg;\r
+    if (uid != uid_arg) {\r
+        PyErr_SetString(PyExc_OverflowError, "user id too big");\r
+        return NULL;\r
+    }\r
+    if (setuid(uid) < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_SETUID */\r
+\r
+\r
+#ifdef HAVE_SETEUID\r
+PyDoc_STRVAR(posix_seteuid__doc__,\r
+"seteuid(uid)\n\n\\r
+Set the current process's effective user id.");\r
+\r
+static PyObject *\r
+posix_seteuid (PyObject *self, PyObject *args)\r
+{\r
+    long euid_arg;\r
+    uid_t euid;\r
+    if (!PyArg_ParseTuple(args, "l", &euid_arg))\r
+        return NULL;\r
+    euid = euid_arg;\r
+    if (euid != euid_arg) {\r
+        PyErr_SetString(PyExc_OverflowError, "user id too big");\r
+        return NULL;\r
+    }\r
+    if (seteuid(euid) < 0) {\r
+        return posix_error();\r
+    } else {\r
+        Py_INCREF(Py_None);\r
+        return Py_None;\r
+    }\r
+}\r
+#endif /* HAVE_SETEUID */\r
+\r
+#ifdef HAVE_SETEGID\r
+PyDoc_STRVAR(posix_setegid__doc__,\r
+"setegid(gid)\n\n\\r
+Set the current process's effective group id.");\r
+\r
+static PyObject *\r
+posix_setegid (PyObject *self, PyObject *args)\r
+{\r
+    long egid_arg;\r
+    gid_t egid;\r
+    if (!PyArg_ParseTuple(args, "l", &egid_arg))\r
+        return NULL;\r
+    egid = egid_arg;\r
+    if (egid != egid_arg) {\r
+        PyErr_SetString(PyExc_OverflowError, "group id too big");\r
+        return NULL;\r
+    }\r
+    if (setegid(egid) < 0) {\r
+        return posix_error();\r
+    } else {\r
+        Py_INCREF(Py_None);\r
+        return Py_None;\r
+    }\r
+}\r
+#endif /* HAVE_SETEGID */\r
+\r
+#ifdef HAVE_SETREUID\r
+PyDoc_STRVAR(posix_setreuid__doc__,\r
+"setreuid(ruid, euid)\n\n\\r
+Set the current process's real and effective user ids.");\r
+\r
+static PyObject *\r
+posix_setreuid (PyObject *self, PyObject *args)\r
+{\r
+    long ruid_arg, euid_arg;\r
+    uid_t ruid, euid;\r
+    if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg))\r
+        return NULL;\r
+    if (ruid_arg == -1)\r
+        ruid = (uid_t)-1;  /* let the compiler choose how -1 fits */\r
+    else\r
+        ruid = ruid_arg;  /* otherwise, assign from our long */\r
+    if (euid_arg == -1)\r
+        euid = (uid_t)-1;\r
+    else\r
+        euid = euid_arg;\r
+    if ((euid_arg != -1 && euid != euid_arg) ||\r
+        (ruid_arg != -1 && ruid != ruid_arg)) {\r
+        PyErr_SetString(PyExc_OverflowError, "user id too big");\r
+        return NULL;\r
+    }\r
+    if (setreuid(ruid, euid) < 0) {\r
+        return posix_error();\r
+    } else {\r
+        Py_INCREF(Py_None);\r
+        return Py_None;\r
+    }\r
+}\r
+#endif /* HAVE_SETREUID */\r
+\r
+#ifdef HAVE_SETREGID\r
+PyDoc_STRVAR(posix_setregid__doc__,\r
+"setregid(rgid, egid)\n\n\\r
+Set the current process's real and effective group ids.");\r
+\r
+static PyObject *\r
+posix_setregid (PyObject *self, PyObject *args)\r
+{\r
+    long rgid_arg, egid_arg;\r
+    gid_t rgid, egid;\r
+    if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg))\r
+        return NULL;\r
+    if (rgid_arg == -1)\r
+        rgid = (gid_t)-1;  /* let the compiler choose how -1 fits */\r
+    else\r
+        rgid = rgid_arg;  /* otherwise, assign from our long */\r
+    if (egid_arg == -1)\r
+        egid = (gid_t)-1;\r
+    else\r
+        egid = egid_arg;\r
+    if ((egid_arg != -1 && egid != egid_arg) ||\r
+        (rgid_arg != -1 && rgid != rgid_arg)) {\r
+        PyErr_SetString(PyExc_OverflowError, "group id too big");\r
+        return NULL;\r
+    }\r
+    if (setregid(rgid, egid) < 0) {\r
+        return posix_error();\r
+    } else {\r
+        Py_INCREF(Py_None);\r
+        return Py_None;\r
+    }\r
+}\r
+#endif /* HAVE_SETREGID */\r
+\r
+#ifdef HAVE_SETGID\r
+PyDoc_STRVAR(posix_setgid__doc__,\r
+"setgid(gid)\n\n\\r
+Set the current process's group id.");\r
+\r
+static PyObject *\r
+posix_setgid(PyObject *self, PyObject *args)\r
+{\r
+    long gid_arg;\r
+    gid_t gid;\r
+    if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg))\r
+        return NULL;\r
+    gid = gid_arg;\r
+    if (gid != gid_arg) {\r
+        PyErr_SetString(PyExc_OverflowError, "group id too big");\r
+        return NULL;\r
+    }\r
+    if (setgid(gid) < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_SETGID */\r
+\r
+#ifdef HAVE_SETGROUPS\r
+PyDoc_STRVAR(posix_setgroups__doc__,\r
+"setgroups(list)\n\n\\r
+Set the groups of the current process to list.");\r
+\r
+static PyObject *\r
+posix_setgroups(PyObject *self, PyObject *groups)\r
+{\r
+    int i, len;\r
+    gid_t grouplist[MAX_GROUPS];\r
+\r
+    if (!PySequence_Check(groups)) {\r
+        PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");\r
+        return NULL;\r
+    }\r
+    len = PySequence_Size(groups);\r
+    if (len > MAX_GROUPS) {\r
+        PyErr_SetString(PyExc_ValueError, "too many groups");\r
+        return NULL;\r
+    }\r
+    for(i = 0; i < len; i++) {\r
+        PyObject *elem;\r
+        elem = PySequence_GetItem(groups, i);\r
+        if (!elem)\r
+            return NULL;\r
+        if (!PyInt_Check(elem)) {\r
+            if (!PyLong_Check(elem)) {\r
+                PyErr_SetString(PyExc_TypeError,\r
+                                "groups must be integers");\r
+                Py_DECREF(elem);\r
+                return NULL;\r
+            } else {\r
+                unsigned long x = PyLong_AsUnsignedLong(elem);\r
+                if (PyErr_Occurred()) {\r
+                    PyErr_SetString(PyExc_TypeError,\r
+                                    "group id too big");\r
+                    Py_DECREF(elem);\r
+                    return NULL;\r
+                }\r
+                grouplist[i] = x;\r
+                /* read back to see if it fits in gid_t */\r
+                if (grouplist[i] != x) {\r
+                    PyErr_SetString(PyExc_TypeError,\r
+                                    "group id too big");\r
+                    Py_DECREF(elem);\r
+                    return NULL;\r
+                }\r
+            }\r
+        } else {\r
+            long x  = PyInt_AsLong(elem);\r
+            grouplist[i] = x;\r
+            if (grouplist[i] != x) {\r
+                PyErr_SetString(PyExc_TypeError,\r
+                                "group id too big");\r
+                Py_DECREF(elem);\r
+                return NULL;\r
+            }\r
+        }\r
+        Py_DECREF(elem);\r
+    }\r
+\r
+    if (setgroups(len, grouplist) < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_SETGROUPS */\r
+\r
+#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)\r
+static PyObject *\r
+wait_helper(pid_t pid, int status, struct rusage *ru)\r
+{\r
+    PyObject *result;\r
+    static PyObject *struct_rusage;\r
+\r
+    if (pid == -1)\r
+        return posix_error();\r
+\r
+    if (struct_rusage == NULL) {\r
+        PyObject *m = PyImport_ImportModuleNoBlock("resource");\r
+        if (m == NULL)\r
+            return NULL;\r
+        struct_rusage = PyObject_GetAttrString(m, "struct_rusage");\r
+        Py_DECREF(m);\r
+        if (struct_rusage == NULL)\r
+            return NULL;\r
+    }\r
+\r
+    /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */\r
+    result = PyStructSequence_New((PyTypeObject*) struct_rusage);\r
+    if (!result)\r
+        return NULL;\r
+\r
+#ifndef doubletime\r
+#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)\r
+#endif\r
+\r
+    PyStructSequence_SET_ITEM(result, 0,\r
+                              PyFloat_FromDouble(doubletime(ru->ru_utime)));\r
+    PyStructSequence_SET_ITEM(result, 1,\r
+                              PyFloat_FromDouble(doubletime(ru->ru_stime)));\r
+#define SET_INT(result, index, value)\\r
+        PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value))\r
+    SET_INT(result, 2, ru->ru_maxrss);\r
+    SET_INT(result, 3, ru->ru_ixrss);\r
+    SET_INT(result, 4, ru->ru_idrss);\r
+    SET_INT(result, 5, ru->ru_isrss);\r
+    SET_INT(result, 6, ru->ru_minflt);\r
+    SET_INT(result, 7, ru->ru_majflt);\r
+    SET_INT(result, 8, ru->ru_nswap);\r
+    SET_INT(result, 9, ru->ru_inblock);\r
+    SET_INT(result, 10, ru->ru_oublock);\r
+    SET_INT(result, 11, ru->ru_msgsnd);\r
+    SET_INT(result, 12, ru->ru_msgrcv);\r
+    SET_INT(result, 13, ru->ru_nsignals);\r
+    SET_INT(result, 14, ru->ru_nvcsw);\r
+    SET_INT(result, 15, ru->ru_nivcsw);\r
+#undef SET_INT\r
+\r
+    if (PyErr_Occurred()) {\r
+        Py_DECREF(result);\r
+        return NULL;\r
+    }\r
+\r
+    return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);\r
+}\r
+#endif /* HAVE_WAIT3 || HAVE_WAIT4 */\r
+\r
+#ifdef HAVE_WAIT3\r
+PyDoc_STRVAR(posix_wait3__doc__,\r
+"wait3(options) -> (pid, status, rusage)\n\n\\r
+Wait for completion of a child process.");\r
+\r
+static PyObject *\r
+posix_wait3(PyObject *self, PyObject *args)\r
+{\r
+    pid_t pid;\r
+    int options;\r
+    struct rusage ru;\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:wait3", &options))\r
+        return NULL;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    pid = wait3(&status, options, &ru);\r
+    Py_END_ALLOW_THREADS\r
+\r
+    return wait_helper(pid, WAIT_STATUS_INT(status), &ru);\r
+}\r
+#endif /* HAVE_WAIT3 */\r
+\r
+#ifdef HAVE_WAIT4\r
+PyDoc_STRVAR(posix_wait4__doc__,\r
+"wait4(pid, options) -> (pid, status, rusage)\n\n\\r
+Wait for completion of a given child process.");\r
+\r
+static PyObject *\r
+posix_wait4(PyObject *self, PyObject *args)\r
+{\r
+    pid_t pid;\r
+    int options;\r
+    struct rusage ru;\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options))\r
+        return NULL;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    pid = wait4(pid, &status, options, &ru);\r
+    Py_END_ALLOW_THREADS\r
+\r
+    return wait_helper(pid, WAIT_STATUS_INT(status), &ru);\r
+}\r
+#endif /* HAVE_WAIT4 */\r
+\r
+#ifdef HAVE_WAITPID\r
+PyDoc_STRVAR(posix_waitpid__doc__,\r
+"waitpid(pid, options) -> (pid, status)\n\n\\r
+Wait for completion of a given child process.");\r
+\r
+static PyObject *\r
+posix_waitpid(PyObject *self, PyObject *args)\r
+{\r
+    pid_t pid;\r
+    int options;\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    pid = waitpid(pid, &status, options);\r
+    Py_END_ALLOW_THREADS\r
+    if (pid == -1)\r
+        return posix_error();\r
+\r
+    return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));\r
+}\r
+\r
+#elif defined(HAVE_CWAIT)\r
+\r
+/* MS C has a variant of waitpid() that's usable for most purposes. */\r
+PyDoc_STRVAR(posix_waitpid__doc__,\r
+"waitpid(pid, options) -> (pid, status << 8)\n\n"\r
+"Wait for completion of a given process.  options is ignored on Windows.");\r
+\r
+static PyObject *\r
+posix_waitpid(PyObject *self, PyObject *args)\r
+{\r
+    Py_intptr_t pid;\r
+    int status, options;\r
+\r
+    if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    pid = _cwait(&status, pid, options);\r
+    Py_END_ALLOW_THREADS\r
+    if (pid == -1)\r
+        return posix_error();\r
+\r
+    /* shift the status left a byte so this is more like the POSIX waitpid */\r
+    return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8);\r
+}\r
+#endif /* HAVE_WAITPID || HAVE_CWAIT */\r
+\r
+#ifdef HAVE_WAIT\r
+PyDoc_STRVAR(posix_wait__doc__,\r
+"wait() -> (pid, status)\n\n\\r
+Wait for completion of a child process.");\r
+\r
+static PyObject *\r
+posix_wait(PyObject *self, PyObject *noargs)\r
+{\r
+    pid_t pid;\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    pid = wait(&status);\r
+    Py_END_ALLOW_THREADS\r
+    if (pid == -1)\r
+        return posix_error();\r
+\r
+    return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));\r
+}\r
+#endif\r
+\r
+\r
+PyDoc_STRVAR(posix_lstat__doc__,\r
+"lstat(path) -> stat result\n\n\\r
+Like stat(path), but do not follow symbolic links.");\r
+\r
+static PyObject *\r
+posix_lstat(PyObject *self, PyObject *args)\r
+{\r
+#ifdef HAVE_LSTAT\r
+    return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL);\r
+#else /* !HAVE_LSTAT */\r
+    return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL);\r
+#endif /* !HAVE_LSTAT */\r
+}\r
+\r
+\r
+#ifdef HAVE_READLINK\r
+PyDoc_STRVAR(posix_readlink__doc__,\r
+"readlink(path) -> path\n\n\\r
+Return a string representing the path to which the symbolic link points.");\r
+\r
+static PyObject *\r
+posix_readlink(PyObject *self, PyObject *args)\r
+{\r
+    PyObject* v;\r
+    char buf[MAXPATHLEN];\r
+    char *path;\r
+    int n;\r
+#ifdef Py_USING_UNICODE\r
+    int arg_is_unicode = 0;\r
+#endif\r
+\r
+    if (!PyArg_ParseTuple(args, "et:readlink",\r
+                          Py_FileSystemDefaultEncoding, &path))\r
+        return NULL;\r
+#ifdef Py_USING_UNICODE\r
+    v = PySequence_GetItem(args, 0);\r
+    if (v == NULL) {\r
+        PyMem_Free(path);\r
+        return NULL;\r
+    }\r
+\r
+    if (PyUnicode_Check(v)) {\r
+        arg_is_unicode = 1;\r
+    }\r
+    Py_DECREF(v);\r
+#endif\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    n = readlink(path, buf, (int) sizeof buf);\r
+    Py_END_ALLOW_THREADS\r
+    if (n < 0)\r
+        return posix_error_with_allocated_filename(path);\r
+\r
+    PyMem_Free(path);\r
+    v = PyString_FromStringAndSize(buf, n);\r
+#ifdef Py_USING_UNICODE\r
+    if (arg_is_unicode) {\r
+        PyObject *w;\r
+\r
+        w = PyUnicode_FromEncodedObject(v,\r
+                                        Py_FileSystemDefaultEncoding,\r
+                                        "strict");\r
+        if (w != NULL) {\r
+            Py_DECREF(v);\r
+            v = w;\r
+        }\r
+        else {\r
+            /* fall back to the original byte string, as\r
+               discussed in patch #683592 */\r
+            PyErr_Clear();\r
+        }\r
+    }\r
+#endif\r
+    return v;\r
+}\r
+#endif /* HAVE_READLINK */\r
+\r
+\r
+#ifdef HAVE_SYMLINK\r
+PyDoc_STRVAR(posix_symlink__doc__,\r
+"symlink(src, dst)\n\n\\r
+Create a symbolic link pointing to src named dst.");\r
+\r
+static PyObject *\r
+posix_symlink(PyObject *self, PyObject *args)\r
+{\r
+    return posix_2str(args, "etet:symlink", symlink);\r
+}\r
+#endif /* HAVE_SYMLINK */\r
+\r
+\r
+#ifdef HAVE_TIMES\r
+#if defined(PYCC_VACPP) && defined(PYOS_OS2)\r
+static long\r
+system_uptime(void)\r
+{\r
+    ULONG     value = 0;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    DosQuerySysInfo(QSV_MS_COUNT, QSV_MS_COUNT, &value, sizeof(value));\r
+    Py_END_ALLOW_THREADS\r
+\r
+    return value;\r
+}\r
+\r
+static PyObject *\r
+posix_times(PyObject *self, PyObject *noargs)\r
+{\r
+    /* Currently Only Uptime is Provided -- Others Later */\r
+    return Py_BuildValue("ddddd",\r
+                         (double)0 /* t.tms_utime / HZ */,\r
+                         (double)0 /* t.tms_stime / HZ */,\r
+                         (double)0 /* t.tms_cutime / HZ */,\r
+                         (double)0 /* t.tms_cstime / HZ */,\r
+                         (double)system_uptime() / 1000);\r
+}\r
+#else /* not OS2 */\r
+#define NEED_TICKS_PER_SECOND\r
+static long ticks_per_second = -1;\r
+static PyObject *\r
+posix_times(PyObject *self, PyObject *noargs)\r
+{\r
+    struct tms t;\r
+    clock_t c;\r
+    errno = 0;\r
+    c = times(&t);\r
+    if (c == (clock_t) -1)\r
+        return posix_error();\r
+    return Py_BuildValue("ddddd",\r
+                         (double)t.tms_utime / ticks_per_second,\r
+                         (double)t.tms_stime / ticks_per_second,\r
+                         (double)t.tms_cutime / ticks_per_second,\r
+                         (double)t.tms_cstime / ticks_per_second,\r
+                         (double)c / ticks_per_second);\r
+}\r
+#endif /* not OS2 */\r
+#endif /* HAVE_TIMES */\r
+\r
+\r
+#ifdef HAVE_TIMES\r
+PyDoc_STRVAR(posix_times__doc__,\r
+"times() -> (utime, stime, cutime, cstime, elapsed_time)\n\n\\r
+Return a tuple of floating point numbers indicating process times.");\r
+#endif\r
+\r
+\r
+#ifdef HAVE_GETSID\r
+PyDoc_STRVAR(posix_getsid__doc__,\r
+"getsid(pid) -> sid\n\n\\r
+Call the system call getsid().");\r
+\r
+static PyObject *\r
+posix_getsid(PyObject *self, PyObject *args)\r
+{\r
+    pid_t pid;\r
+    int sid;\r
+    if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid))\r
+        return NULL;\r
+    sid = getsid(pid);\r
+    if (sid < 0)\r
+        return posix_error();\r
+    return PyInt_FromLong((long)sid);\r
+}\r
+#endif /* HAVE_GETSID */\r
+\r
+\r
+#ifdef HAVE_SETSID\r
+PyDoc_STRVAR(posix_setsid__doc__,\r
+"setsid()\n\n\\r
+Call the system call setsid().");\r
+\r
+static PyObject *\r
+posix_setsid(PyObject *self, PyObject *noargs)\r
+{\r
+    if (setsid() < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_SETSID */\r
+\r
+#ifdef HAVE_SETPGID\r
+PyDoc_STRVAR(posix_setpgid__doc__,\r
+"setpgid(pid, pgrp)\n\n\\r
+Call the system call setpgid().");\r
+\r
+static PyObject *\r
+posix_setpgid(PyObject *self, PyObject *args)\r
+{\r
+    pid_t pid;\r
+    int pgrp;\r
+    if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp))\r
+        return NULL;\r
+    if (setpgid(pid, pgrp) < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_SETPGID */\r
+\r
+\r
+#ifdef HAVE_TCGETPGRP\r
+PyDoc_STRVAR(posix_tcgetpgrp__doc__,\r
+"tcgetpgrp(fd) -> pgid\n\n\\r
+Return the process group associated with the terminal given by a fd.");\r
+\r
+static PyObject *\r
+posix_tcgetpgrp(PyObject *self, PyObject *args)\r
+{\r
+    int fd;\r
+    pid_t pgid;\r
+    if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd))\r
+        return NULL;\r
+    pgid = tcgetpgrp(fd);\r
+    if (pgid < 0)\r
+        return posix_error();\r
+    return PyLong_FromPid(pgid);\r
+}\r
+#endif /* HAVE_TCGETPGRP */\r
+\r
+\r
+#ifdef HAVE_TCSETPGRP\r
+PyDoc_STRVAR(posix_tcsetpgrp__doc__,\r
+"tcsetpgrp(fd, pgid)\n\n\\r
+Set the process group associated with the terminal given by a fd.");\r
+\r
+static PyObject *\r
+posix_tcsetpgrp(PyObject *self, PyObject *args)\r
+{\r
+    int fd;\r
+    pid_t pgid;\r
+    if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid))\r
+        return NULL;\r
+    if (tcsetpgrp(fd, pgid) < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* HAVE_TCSETPGRP */\r
+\r
+/* Functions acting on file descriptors */\r
+\r
+PyDoc_STRVAR(posix_open__doc__,\r
+"open(filename, flag [, mode=0777]) -> fd\n\n\\r
+Open a file (for low level IO).");\r
+\r
+static PyObject *\r
+posix_open(PyObject *self, PyObject *args)\r
+{\r
+    char *file = NULL;\r
+    int flag;\r
+    int mode = 0777;\r
+    int fd;\r
+\r
+    if (!PyArg_ParseTuple(args, "eti|i",\r
+                          Py_FileSystemDefaultEncoding, &file,\r
+                          &flag, &mode))\r
+        return NULL;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    fd = open(file, flag, mode);\r
+    Py_END_ALLOW_THREADS\r
+    if (fd < 0)\r
+        return posix_error_with_allocated_filename(file);\r
+    PyMem_Free(file);\r
+    return PyInt_FromLong((long)fd);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_close__doc__,\r
+"close(fd)\n\n\\r
+Close a file descriptor (for low level IO).");\r
+\r
+static PyObject *\r
+posix_close(PyObject *self, PyObject *args)\r
+{\r
+    int fd, res;\r
+    if (!PyArg_ParseTuple(args, "i:close", &fd))\r
+        return NULL;\r
+    if (!_PyVerify_fd(fd))\r
+        return posix_error();\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = close(fd);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_closerange__doc__,\r
+"closerange(fd_low, fd_high)\n\n\\r
+Closes all file descriptors in [fd_low, fd_high), ignoring errors.");\r
+\r
+static PyObject *\r
+posix_closerange(PyObject *self, PyObject *args)\r
+{\r
+    int fd_from, fd_to, i;\r
+    if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    for (i = fd_from; i < fd_to; i++)\r
+        if (_PyVerify_fd(i))\r
+            close(i);\r
+    Py_END_ALLOW_THREADS\r
+    Py_RETURN_NONE;\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_dup__doc__,\r
+"dup(fd) -> fd2\n\n\\r
+Return a duplicate of a file descriptor.");\r
+\r
+static PyObject *\r
+posix_dup(PyObject *self, PyObject *args)\r
+{\r
+    int fd;\r
+    if (!PyArg_ParseTuple(args, "i:dup", &fd))\r
+        return NULL;\r
+    if (!_PyVerify_fd(fd))\r
+        return posix_error();\r
+    Py_BEGIN_ALLOW_THREADS\r
+    fd = dup(fd);\r
+    Py_END_ALLOW_THREADS\r
+    if (fd < 0)\r
+        return posix_error();\r
+    return PyInt_FromLong((long)fd);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_dup2__doc__,\r
+"dup2(old_fd, new_fd)\n\n\\r
+Duplicate file descriptor.");\r
+\r
+static PyObject *\r
+posix_dup2(PyObject *self, PyObject *args)\r
+{\r
+    int fd, fd2, res;\r
+    if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2))\r
+        return NULL;\r
+    if (!_PyVerify_fd_dup2(fd, fd2))\r
+        return posix_error();\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = dup2(fd, fd2);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_lseek__doc__,\r
+"lseek(fd, pos, how) -> newpos\n\n\\r
+Set the current position of a file descriptor.");\r
+\r
+static PyObject *\r
+posix_lseek(PyObject *self, PyObject *args)\r
+{\r
+    int fd, how;\r
+    off_t pos, res;\r
+    PyObject *posobj;\r
+    if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how))\r
+        return NULL;\r
+#ifdef SEEK_SET\r
+    /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */\r
+    switch (how) {\r
+    case 0: how = SEEK_SET; break;\r
+    case 1: how = SEEK_CUR; break;\r
+    case 2: how = SEEK_END; break;\r
+    }\r
+#endif /* SEEK_END */\r
+\r
+#if !defined(HAVE_LARGEFILE_SUPPORT)\r
+    pos = PyInt_AsLong(posobj);\r
+#else\r
+    pos = PyLong_Check(posobj) ?\r
+        PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);\r
+#endif\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    if (!_PyVerify_fd(fd))\r
+        return posix_error();\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = lseek(fd, pos, how);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+\r
+#if !defined(HAVE_LARGEFILE_SUPPORT)\r
+    return PyInt_FromLong(res);\r
+#else\r
+    return PyLong_FromLongLong(res);\r
+#endif\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_read__doc__,\r
+"read(fd, buffersize) -> string\n\n\\r
+Read a file descriptor.");\r
+\r
+static PyObject *\r
+posix_read(PyObject *self, PyObject *args)\r
+{\r
+    int fd, size, n;\r
+    PyObject *buffer;\r
+    if (!PyArg_ParseTuple(args, "ii:read", &fd, &size))\r
+        return NULL;\r
+    if (size < 0) {\r
+        errno = EINVAL;\r
+        return posix_error();\r
+    }\r
+    buffer = PyString_FromStringAndSize((char *)NULL, size);\r
+    if (buffer == NULL)\r
+        return NULL;\r
+    if (!_PyVerify_fd(fd)) {\r
+        Py_DECREF(buffer);\r
+        return posix_error();\r
+    }\r
+    Py_BEGIN_ALLOW_THREADS\r
+    n = read(fd, PyString_AsString(buffer), size);\r
+    Py_END_ALLOW_THREADS\r
+    if (n < 0) {\r
+        Py_DECREF(buffer);\r
+        return posix_error();\r
+    }\r
+    if (n != size)\r
+        _PyString_Resize(&buffer, n);\r
+    return buffer;\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_write__doc__,\r
+"write(fd, string) -> byteswritten\n\n\\r
+Write a string to a file descriptor.");\r
+\r
+static PyObject *\r
+posix_write(PyObject *self, PyObject *args)\r
+{\r
+    Py_buffer pbuf;\r
+    int fd;\r
+    Py_ssize_t size;\r
+\r
+    if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf))\r
+        return NULL;\r
+    if (!_PyVerify_fd(fd)) {\r
+        PyBuffer_Release(&pbuf);\r
+        return posix_error();\r
+    }\r
+    Py_BEGIN_ALLOW_THREADS\r
+    size = write(fd, pbuf.buf, (size_t)pbuf.len);\r
+    Py_END_ALLOW_THREADS\r
+    PyBuffer_Release(&pbuf);\r
+    if (size < 0)\r
+        return posix_error();\r
+    return PyInt_FromSsize_t(size);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_fstat__doc__,\r
+"fstat(fd) -> stat result\n\n\\r
+Like stat(), but for an open file descriptor.");\r
+\r
+static PyObject *\r
+posix_fstat(PyObject *self, PyObject *args)\r
+{\r
+    int fd;\r
+    STRUCT_STAT st;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "i:fstat", &fd))\r
+        return NULL;\r
+    if (!_PyVerify_fd(fd))\r
+        return posix_error();\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = FSTAT(fd, &st);\r
+    Py_END_ALLOW_THREADS\r
+    if (res != 0) {\r
+      return posix_error();\r
+    }\r
+\r
+    return _pystat_fromstructstat(&st);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_fdopen__doc__,\r
+"fdopen(fd [, mode='r' [, bufsize]]) -> file_object\n\n\\r
+Return an open file object connected to a file descriptor.");\r
+\r
+static PyObject *\r
+posix_fdopen(PyObject *self, PyObject *args)\r
+{\r
+    int fd;\r
+    char *orgmode = "r";\r
+    int bufsize = -1;\r
+    FILE *fp;\r
+    PyObject *f;\r
+    char *mode;\r
+    if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize))\r
+        return NULL;\r
+\r
+    /* Sanitize mode.  See fileobject.c */\r
+    mode = PyMem_MALLOC(strlen(orgmode)+3);\r
+    if (!mode) {\r
+        PyErr_NoMemory();\r
+        return NULL;\r
+    }\r
+    strcpy(mode, orgmode);\r
+    if (_PyFile_SanitizeMode(mode)) {\r
+        PyMem_FREE(mode);\r
+        return NULL;\r
+    }\r
+    if (!_PyVerify_fd(fd))\r
+        return posix_error();\r
+    Py_BEGIN_ALLOW_THREADS\r
+#if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H)\r
+    if (mode[0] == 'a') {\r
+        /* try to make sure the O_APPEND flag is set */\r
+        int flags;\r
+        flags = fcntl(fd, F_GETFL);\r
+        if (flags != -1)\r
+            fcntl(fd, F_SETFL, flags | O_APPEND);\r
+        fp = fdopen(fd, mode);\r
+        if (fp == NULL && flags != -1)\r
+            /* restore old mode if fdopen failed */\r
+            fcntl(fd, F_SETFL, flags);\r
+    } else {\r
+        fp = fdopen(fd, mode);\r
+    }\r
+#else\r
+    fp = fdopen(fd, mode);\r
+#endif\r
+    Py_END_ALLOW_THREADS\r
+    PyMem_FREE(mode);\r
+    if (fp == NULL)\r
+        return posix_error();\r
+    f = PyFile_FromFile(fp, "<fdopen>", orgmode, fclose);\r
+    if (f != NULL)\r
+        PyFile_SetBufSize(f, bufsize);\r
+    return f;\r
+}\r
+\r
+PyDoc_STRVAR(posix_isatty__doc__,\r
+"isatty(fd) -> bool\n\n\\r
+Return True if the file descriptor 'fd' is an open file descriptor\n\\r
+connected to the slave end of a terminal.");\r
+\r
+static PyObject *\r
+posix_isatty(PyObject *self, PyObject *args)\r
+{\r
+    int fd;\r
+    if (!PyArg_ParseTuple(args, "i:isatty", &fd))\r
+        return NULL;\r
+    if (!_PyVerify_fd(fd))\r
+        return PyBool_FromLong(0);\r
+    return PyBool_FromLong(isatty(fd));\r
+}\r
+\r
+#ifdef HAVE_PIPE\r
+PyDoc_STRVAR(posix_pipe__doc__,\r
+"pipe() -> (read_end, write_end)\n\n\\r
+Create a pipe.");\r
+\r
+static PyObject *\r
+posix_pipe(PyObject *self, PyObject *noargs)\r
+{\r
+#if defined(PYOS_OS2)\r
+    HFILE read, write;\r
+    APIRET rc;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    rc = DosCreatePipe( &read, &write, 4096);\r
+    Py_END_ALLOW_THREADS\r
+    if (rc != NO_ERROR)\r
+        return os2_error(rc);\r
+\r
+    return Py_BuildValue("(ii)", read, write);\r
+#else\r
+#if !defined(MS_WINDOWS)\r
+    int fds[2];\r
+    int res;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = pipe(fds);\r
+    Py_END_ALLOW_THREADS\r
+    if (res != 0)\r
+        return posix_error();\r
+    return Py_BuildValue("(ii)", fds[0], fds[1]);\r
+#else /* MS_WINDOWS */\r
+    HANDLE read, write;\r
+    int read_fd, write_fd;\r
+    BOOL ok;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    ok = CreatePipe(&read, &write, NULL, 0);\r
+    Py_END_ALLOW_THREADS\r
+    if (!ok)\r
+        return win32_error("CreatePipe", NULL);\r
+    read_fd = _open_osfhandle((Py_intptr_t)read, 0);\r
+    write_fd = _open_osfhandle((Py_intptr_t)write, 1);\r
+    return Py_BuildValue("(ii)", read_fd, write_fd);\r
+#endif /* MS_WINDOWS */\r
+#endif\r
+}\r
+#endif  /* HAVE_PIPE */\r
+\r
+\r
+#ifdef HAVE_MKFIFO\r
+PyDoc_STRVAR(posix_mkfifo__doc__,\r
+"mkfifo(filename [, mode=0666])\n\n\\r
+Create a FIFO (a POSIX named pipe).");\r
+\r
+static PyObject *\r
+posix_mkfifo(PyObject *self, PyObject *args)\r
+{\r
+    char *filename;\r
+    int mode = 0666;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = mkfifo(filename, mode);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif\r
+\r
+\r
+#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)\r
+PyDoc_STRVAR(posix_mknod__doc__,\r
+"mknod(filename [, mode=0600, device])\n\n\\r
+Create a filesystem node (file, device special file or named pipe)\n\\r
+named filename. mode specifies both the permissions to use and the\n\\r
+type of node to be created, being combined (bitwise OR) with one of\n\\r
+S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. For S_IFCHR and S_IFBLK,\n\\r
+device defines the newly created device special file (probably using\n\\r
+os.makedev()), otherwise it is ignored.");\r
+\r
+\r
+static PyObject *\r
+posix_mknod(PyObject *self, PyObject *args)\r
+{\r
+    char *filename;\r
+    int mode = 0600;\r
+    int device = 0;\r
+    int res;\r
+    if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = mknod(filename, mode, device);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_DEVICE_MACROS\r
+PyDoc_STRVAR(posix_major__doc__,\r
+"major(device) -> major number\n\\r
+Extracts a device major number from a raw device number.");\r
+\r
+static PyObject *\r
+posix_major(PyObject *self, PyObject *args)\r
+{\r
+    int device;\r
+    if (!PyArg_ParseTuple(args, "i:major", &device))\r
+        return NULL;\r
+    return PyInt_FromLong((long)major(device));\r
+}\r
+\r
+PyDoc_STRVAR(posix_minor__doc__,\r
+"minor(device) -> minor number\n\\r
+Extracts a device minor number from a raw device number.");\r
+\r
+static PyObject *\r
+posix_minor(PyObject *self, PyObject *args)\r
+{\r
+    int device;\r
+    if (!PyArg_ParseTuple(args, "i:minor", &device))\r
+        return NULL;\r
+    return PyInt_FromLong((long)minor(device));\r
+}\r
+\r
+PyDoc_STRVAR(posix_makedev__doc__,\r
+"makedev(major, minor) -> device number\n\\r
+Composes a raw device number from the major and minor device numbers.");\r
+\r
+static PyObject *\r
+posix_makedev(PyObject *self, PyObject *args)\r
+{\r
+    int major, minor;\r
+    if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor))\r
+        return NULL;\r
+    return PyInt_FromLong((long)makedev(major, minor));\r
+}\r
+#endif /* device macros */\r
+\r
+\r
+#ifdef HAVE_FTRUNCATE\r
+PyDoc_STRVAR(posix_ftruncate__doc__,\r
+"ftruncate(fd, length)\n\n\\r
+Truncate a file to a specified length.");\r
+\r
+static PyObject *\r
+posix_ftruncate(PyObject *self, PyObject *args)\r
+{\r
+    int fd;\r
+    off_t length;\r
+    int res;\r
+    PyObject *lenobj;\r
+\r
+    if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj))\r
+        return NULL;\r
+\r
+#if !defined(HAVE_LARGEFILE_SUPPORT)\r
+    length = PyInt_AsLong(lenobj);\r
+#else\r
+    length = PyLong_Check(lenobj) ?\r
+        PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj);\r
+#endif\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = ftruncate(fd, length);\r
+    Py_END_ALLOW_THREADS\r
+    if (res < 0)\r
+        return posix_error();\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_PUTENV\r
+PyDoc_STRVAR(posix_putenv__doc__,\r
+"putenv(key, value)\n\n\\r
+Change or add an environment variable.");\r
+\r
+/* Save putenv() parameters as values here, so we can collect them when they\r
+ * get re-set with another call for the same key. */\r
+static PyObject *posix_putenv_garbage;\r
+\r
+static PyObject *\r
+posix_putenv(PyObject *self, PyObject *args)\r
+{\r
+    char *s1, *s2;\r
+    char *newenv;\r
+    PyObject *newstr;\r
+    size_t len;\r
+\r
+    if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2))\r
+        return NULL;\r
+\r
+#if defined(PYOS_OS2)\r
+    if (stricmp(s1, "BEGINLIBPATH") == 0) {\r
+        APIRET rc;\r
+\r
+        rc = DosSetExtLIBPATH(s2, BEGIN_LIBPATH);\r
+        if (rc != NO_ERROR)\r
+            return os2_error(rc);\r
+\r
+    } else if (stricmp(s1, "ENDLIBPATH") == 0) {\r
+        APIRET rc;\r
+\r
+        rc = DosSetExtLIBPATH(s2, END_LIBPATH);\r
+        if (rc != NO_ERROR)\r
+            return os2_error(rc);\r
+    } else {\r
+#endif\r
+\r
+    /* XXX This can leak memory -- not easy to fix :-( */\r
+    len = strlen(s1) + strlen(s2) + 2;\r
+    /* len includes space for a trailing \0; the size arg to\r
+       PyString_FromStringAndSize does not count that */\r
+    newstr = PyString_FromStringAndSize(NULL, (int)len - 1);\r
+    if (newstr == NULL)\r
+        return PyErr_NoMemory();\r
+    newenv = PyString_AS_STRING(newstr);\r
+    PyOS_snprintf(newenv, len, "%s=%s", s1, s2);\r
+    if (putenv(newenv)) {\r
+        Py_DECREF(newstr);\r
+        posix_error();\r
+        return NULL;\r
+    }\r
+    /* Install the first arg and newstr in posix_putenv_garbage;\r
+     * this will cause previous value to be collected.  This has to\r
+     * happen after the real putenv() call because the old value\r
+     * was still accessible until then. */\r
+    if (PyDict_SetItem(posix_putenv_garbage,\r
+                       PyTuple_GET_ITEM(args, 0), newstr)) {\r
+        /* really not much we can do; just leak */\r
+        PyErr_Clear();\r
+    }\r
+    else {\r
+        Py_DECREF(newstr);\r
+    }\r
+\r
+#if defined(PYOS_OS2)\r
+    }\r
+#endif\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* putenv */\r
+\r
+#ifdef HAVE_UNSETENV\r
+PyDoc_STRVAR(posix_unsetenv__doc__,\r
+"unsetenv(key)\n\n\\r
+Delete an environment variable.");\r
+\r
+static PyObject *\r
+posix_unsetenv(PyObject *self, PyObject *args)\r
+{\r
+    char *s1;\r
+\r
+    if (!PyArg_ParseTuple(args, "s:unsetenv", &s1))\r
+        return NULL;\r
+\r
+    unsetenv(s1);\r
+\r
+    /* Remove the key from posix_putenv_garbage;\r
+     * this will cause it to be collected.  This has to\r
+     * happen after the real unsetenv() call because the\r
+     * old value was still accessible until then.\r
+     */\r
+    if (PyDict_DelItem(posix_putenv_garbage,\r
+                       PyTuple_GET_ITEM(args, 0))) {\r
+        /* really not much we can do; just leak */\r
+        PyErr_Clear();\r
+    }\r
+\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+#endif /* unsetenv */\r
+\r
+PyDoc_STRVAR(posix_strerror__doc__,\r
+"strerror(code) -> string\n\n\\r
+Translate an error code to a message string.");\r
+\r
+static PyObject *\r
+posix_strerror(PyObject *self, PyObject *args)\r
+{\r
+    int code;\r
+    char *message;\r
+    if (!PyArg_ParseTuple(args, "i:strerror", &code))\r
+        return NULL;\r
+    message = strerror(code);\r
+    if (message == NULL) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                        "strerror() argument out of range");\r
+        return NULL;\r
+    }\r
+    return PyString_FromString(message);\r
+}\r
+\r
+\r
+#ifdef HAVE_SYS_WAIT_H\r
+\r
+#ifdef WCOREDUMP\r
+PyDoc_STRVAR(posix_WCOREDUMP__doc__,\r
+"WCOREDUMP(status) -> bool\n\n\\r
+Return True if the process returning 'status' was dumped to a core file.");\r
+\r
+static PyObject *\r
+posix_WCOREDUMP(PyObject *self, PyObject *args)\r
+{\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status)))\r
+        return NULL;\r
+\r
+    return PyBool_FromLong(WCOREDUMP(status));\r
+}\r
+#endif /* WCOREDUMP */\r
+\r
+#ifdef WIFCONTINUED\r
+PyDoc_STRVAR(posix_WIFCONTINUED__doc__,\r
+"WIFCONTINUED(status) -> bool\n\n\\r
+Return True if the process returning 'status' was continued from a\n\\r
+job control stop.");\r
+\r
+static PyObject *\r
+posix_WIFCONTINUED(PyObject *self, PyObject *args)\r
+{\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status)))\r
+        return NULL;\r
+\r
+    return PyBool_FromLong(WIFCONTINUED(status));\r
+}\r
+#endif /* WIFCONTINUED */\r
+\r
+#ifdef WIFSTOPPED\r
+PyDoc_STRVAR(posix_WIFSTOPPED__doc__,\r
+"WIFSTOPPED(status) -> bool\n\n\\r
+Return True if the process returning 'status' was stopped.");\r
+\r
+static PyObject *\r
+posix_WIFSTOPPED(PyObject *self, PyObject *args)\r
+{\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status)))\r
+        return NULL;\r
+\r
+    return PyBool_FromLong(WIFSTOPPED(status));\r
+}\r
+#endif /* WIFSTOPPED */\r
+\r
+#ifdef WIFSIGNALED\r
+PyDoc_STRVAR(posix_WIFSIGNALED__doc__,\r
+"WIFSIGNALED(status) -> bool\n\n\\r
+Return True if the process returning 'status' was terminated by a signal.");\r
+\r
+static PyObject *\r
+posix_WIFSIGNALED(PyObject *self, PyObject *args)\r
+{\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status)))\r
+        return NULL;\r
+\r
+    return PyBool_FromLong(WIFSIGNALED(status));\r
+}\r
+#endif /* WIFSIGNALED */\r
+\r
+#ifdef WIFEXITED\r
+PyDoc_STRVAR(posix_WIFEXITED__doc__,\r
+"WIFEXITED(status) -> bool\n\n\\r
+Return true if the process returning 'status' exited using the exit()\n\\r
+system call.");\r
+\r
+static PyObject *\r
+posix_WIFEXITED(PyObject *self, PyObject *args)\r
+{\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status)))\r
+        return NULL;\r
+\r
+    return PyBool_FromLong(WIFEXITED(status));\r
+}\r
+#endif /* WIFEXITED */\r
+\r
+#ifdef WEXITSTATUS\r
+PyDoc_STRVAR(posix_WEXITSTATUS__doc__,\r
+"WEXITSTATUS(status) -> integer\n\n\\r
+Return the process return code from 'status'.");\r
+\r
+static PyObject *\r
+posix_WEXITSTATUS(PyObject *self, PyObject *args)\r
+{\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status)))\r
+        return NULL;\r
+\r
+    return Py_BuildValue("i", WEXITSTATUS(status));\r
+}\r
+#endif /* WEXITSTATUS */\r
+\r
+#ifdef WTERMSIG\r
+PyDoc_STRVAR(posix_WTERMSIG__doc__,\r
+"WTERMSIG(status) -> integer\n\n\\r
+Return the signal that terminated the process that provided the 'status'\n\\r
+value.");\r
+\r
+static PyObject *\r
+posix_WTERMSIG(PyObject *self, PyObject *args)\r
+{\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status)))\r
+        return NULL;\r
+\r
+    return Py_BuildValue("i", WTERMSIG(status));\r
+}\r
+#endif /* WTERMSIG */\r
+\r
+#ifdef WSTOPSIG\r
+PyDoc_STRVAR(posix_WSTOPSIG__doc__,\r
+"WSTOPSIG(status) -> integer\n\n\\r
+Return the signal that stopped the process that provided\n\\r
+the 'status' value.");\r
+\r
+static PyObject *\r
+posix_WSTOPSIG(PyObject *self, PyObject *args)\r
+{\r
+    WAIT_TYPE status;\r
+    WAIT_STATUS_INT(status) = 0;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status)))\r
+        return NULL;\r
+\r
+    return Py_BuildValue("i", WSTOPSIG(status));\r
+}\r
+#endif /* WSTOPSIG */\r
+\r
+#endif /* HAVE_SYS_WAIT_H */\r
+\r
+\r
+#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)\r
+#ifdef _SCO_DS\r
+/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the\r
+   needed definitions in sys/statvfs.h */\r
+#define _SVID3\r
+#endif\r
+#include <sys/statvfs.h>\r
+\r
+static PyObject*\r
+_pystatvfs_fromstructstatvfs(struct statvfs st) {\r
+    PyObject *v = PyStructSequence_New(&StatVFSResultType);\r
+    if (v == NULL)\r
+        return NULL;\r
+\r
+#if !defined(HAVE_LARGEFILE_SUPPORT)\r
+    PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));\r
+    PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));\r
+    PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks));\r
+    PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree));\r
+    PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail));\r
+    PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files));\r
+    PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree));\r
+    PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail));\r
+    PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));\r
+    PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));\r
+#else\r
+    PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));\r
+    PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));\r
+    PyStructSequence_SET_ITEM(v, 2,\r
+                              PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks));\r
+    PyStructSequence_SET_ITEM(v, 3,\r
+                              PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree));\r
+    PyStructSequence_SET_ITEM(v, 4,\r
+                              PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail));\r
+    PyStructSequence_SET_ITEM(v, 5,\r
+                              PyLong_FromLongLong((PY_LONG_LONG) st.f_files));\r
+    PyStructSequence_SET_ITEM(v, 6,\r
+                              PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree));\r
+    PyStructSequence_SET_ITEM(v, 7,\r
+                              PyLong_FromLongLong((PY_LONG_LONG) st.f_favail));\r
+    PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));\r
+    PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));\r
+#endif\r
+\r
+    return v;\r
+}\r
+\r
+PyDoc_STRVAR(posix_fstatvfs__doc__,\r
+"fstatvfs(fd) -> statvfs result\n\n\\r
+Perform an fstatvfs system call on the given fd.");\r
+\r
+static PyObject *\r
+posix_fstatvfs(PyObject *self, PyObject *args)\r
+{\r
+    int fd, res;\r
+    struct statvfs st;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = fstatvfs(fd, &st);\r
+    Py_END_ALLOW_THREADS\r
+    if (res != 0)\r
+        return posix_error();\r
+\r
+    return _pystatvfs_fromstructstatvfs(st);\r
+}\r
+#endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */\r
+\r
+\r
+#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)\r
+#include <sys/statvfs.h>\r
+\r
+PyDoc_STRVAR(posix_statvfs__doc__,\r
+"statvfs(path) -> statvfs result\n\n\\r
+Perform a statvfs system call on the given path.");\r
+\r
+static PyObject *\r
+posix_statvfs(PyObject *self, PyObject *args)\r
+{\r
+    char *path;\r
+    int res;\r
+    struct statvfs st;\r
+    if (!PyArg_ParseTuple(args, "s:statvfs", &path))\r
+        return NULL;\r
+    Py_BEGIN_ALLOW_THREADS\r
+    res = statvfs(path, &st);\r
+    Py_END_ALLOW_THREADS\r
+    if (res != 0)\r
+        return posix_error_with_filename(path);\r
+\r
+    return _pystatvfs_fromstructstatvfs(st);\r
+}\r
+#endif /* HAVE_STATVFS */\r
+\r
+\r
+#ifdef HAVE_TEMPNAM\r
+PyDoc_STRVAR(posix_tempnam__doc__,\r
+"tempnam([dir[, prefix]]) -> string\n\n\\r
+Return a unique name for a temporary file.\n\\r
+The directory and a prefix may be specified as strings; they may be omitted\n\\r
+or None if not needed.");\r
+\r
+static PyObject *\r
+posix_tempnam(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *result = NULL;\r
+    char *dir = NULL;\r
+    char *pfx = NULL;\r
+    char *name;\r
+\r
+    if (!PyArg_ParseTuple(args, "|zz:tempnam", &dir, &pfx))\r
+    return NULL;\r
+\r
+    if (PyErr_Warn(PyExc_RuntimeWarning,\r
+                   "tempnam is a potential security risk to your program") < 0)\r
+        return NULL;\r
+\r
+    if (PyErr_WarnPy3k("tempnam has been removed in 3.x; "\r
+                       "use the tempfile module", 1) < 0)\r
+        return NULL;\r
+\r
+    name = tempnam(dir, pfx);\r
+    if (name == NULL)\r
+        return PyErr_NoMemory();\r
+    result = PyString_FromString(name);\r
+    free(name);\r
+    return result;\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_TMPFILE\r
+PyDoc_STRVAR(posix_tmpfile__doc__,\r
+"tmpfile() -> file object\n\n\\r
+Create a temporary file with no directory entries.");\r
+\r
+static PyObject *\r
+posix_tmpfile(PyObject *self, PyObject *noargs)\r
+{\r
+    FILE *fp;\r
+\r
+    if (PyErr_WarnPy3k("tmpfile has been removed in 3.x; "\r
+                       "use the tempfile module", 1) < 0)\r
+        return NULL;\r
+\r
+    fp = tmpfile();\r
+    if (fp == NULL)\r
+        return posix_error();\r
+    return PyFile_FromFile(fp, "<tmpfile>", "w+b", fclose);\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_TMPNAM\r
+PyDoc_STRVAR(posix_tmpnam__doc__,\r
+"tmpnam() -> string\n\n\\r
+Return a unique name for a temporary file.");\r
+\r
+static PyObject *\r
+posix_tmpnam(PyObject *self, PyObject *noargs)\r
+{\r
+    char buffer[L_tmpnam];\r
+    char *name;\r
+\r
+    if (PyErr_Warn(PyExc_RuntimeWarning,\r
+                   "tmpnam is a potential security risk to your program") < 0)\r
+        return NULL;\r
+\r
+    if (PyErr_WarnPy3k("tmpnam has been removed in 3.x; "\r
+                       "use the tempfile module", 1) < 0)\r
+        return NULL;\r
+\r
+#ifdef USE_TMPNAM_R\r
+    name = tmpnam_r(buffer);\r
+#else\r
+    name = tmpnam(buffer);\r
+#endif\r
+    if (name == NULL) {\r
+        PyObject *err = Py_BuildValue("is", 0,\r
+#ifdef USE_TMPNAM_R\r
+                                      "unexpected NULL from tmpnam_r"\r
+#else\r
+                                      "unexpected NULL from tmpnam"\r
+#endif\r
+                                      );\r
+        PyErr_SetObject(PyExc_OSError, err);\r
+        Py_XDECREF(err);\r
+        return NULL;\r
+    }\r
+    return PyString_FromString(buffer);\r
+}\r
+#endif\r
+\r
+\r
+/* This is used for fpathconf(), pathconf(), confstr() and sysconf().\r
+ * It maps strings representing configuration variable names to\r
+ * integer values, allowing those functions to be called with the\r
+ * magic names instead of polluting the module's namespace with tons of\r
+ * rarely-used constants.  There are three separate tables that use\r
+ * these definitions.\r
+ *\r
+ * This code is always included, even if none of the interfaces that\r
+ * need it are included.  The #if hackery needed to avoid it would be\r
+ * sufficiently pervasive that it's not worth the loss of readability.\r
+ */\r
+struct constdef {\r
+    char *name;\r
+    long value;\r
+};\r
+\r
+static int\r
+conv_confname(PyObject *arg, int *valuep, struct constdef *table,\r
+              size_t tablesize)\r
+{\r
+    if (PyInt_Check(arg)) {\r
+        *valuep = PyInt_AS_LONG(arg);\r
+        return 1;\r
+    }\r
+    if (PyString_Check(arg)) {\r
+        /* look up the value in the table using a binary search */\r
+        size_t lo = 0;\r
+        size_t mid;\r
+        size_t hi = tablesize;\r
+        int cmp;\r
+        char *confname = PyString_AS_STRING(arg);\r
+        while (lo < hi) {\r
+            mid = (lo + hi) / 2;\r
+            cmp = strcmp(confname, table[mid].name);\r
+            if (cmp < 0)\r
+                hi = mid;\r
+            else if (cmp > 0)\r
+                lo = mid + 1;\r
+            else {\r
+                *valuep = table[mid].value;\r
+                return 1;\r
+            }\r
+        }\r
+        PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");\r
+    }\r
+    else\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "configuration names must be strings or integers");\r
+    return 0;\r
+}\r
+\r
+\r
+#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)\r
+static struct constdef  posix_constants_pathconf[] = {\r
+#ifdef _PC_ABI_AIO_XFER_MAX\r
+    {"PC_ABI_AIO_XFER_MAX",     _PC_ABI_AIO_XFER_MAX},\r
+#endif\r
+#ifdef _PC_ABI_ASYNC_IO\r
+    {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},\r
+#endif\r
+#ifdef _PC_ASYNC_IO\r
+    {"PC_ASYNC_IO",     _PC_ASYNC_IO},\r
+#endif\r
+#ifdef _PC_CHOWN_RESTRICTED\r
+    {"PC_CHOWN_RESTRICTED",     _PC_CHOWN_RESTRICTED},\r
+#endif\r
+#ifdef _PC_FILESIZEBITS\r
+    {"PC_FILESIZEBITS", _PC_FILESIZEBITS},\r
+#endif\r
+#ifdef _PC_LAST\r
+    {"PC_LAST", _PC_LAST},\r
+#endif\r
+#ifdef _PC_LINK_MAX\r
+    {"PC_LINK_MAX",     _PC_LINK_MAX},\r
+#endif\r
+#ifdef _PC_MAX_CANON\r
+    {"PC_MAX_CANON",    _PC_MAX_CANON},\r
+#endif\r
+#ifdef _PC_MAX_INPUT\r
+    {"PC_MAX_INPUT",    _PC_MAX_INPUT},\r
+#endif\r
+#ifdef _PC_NAME_MAX\r
+    {"PC_NAME_MAX",     _PC_NAME_MAX},\r
+#endif\r
+#ifdef _PC_NO_TRUNC\r
+    {"PC_NO_TRUNC",     _PC_NO_TRUNC},\r
+#endif\r
+#ifdef _PC_PATH_MAX\r
+    {"PC_PATH_MAX",     _PC_PATH_MAX},\r
+#endif\r
+#ifdef _PC_PIPE_BUF\r
+    {"PC_PIPE_BUF",     _PC_PIPE_BUF},\r
+#endif\r
+#ifdef _PC_PRIO_IO\r
+    {"PC_PRIO_IO",      _PC_PRIO_IO},\r
+#endif\r
+#ifdef _PC_SOCK_MAXBUF\r
+    {"PC_SOCK_MAXBUF",  _PC_SOCK_MAXBUF},\r
+#endif\r
+#ifdef _PC_SYNC_IO\r
+    {"PC_SYNC_IO",      _PC_SYNC_IO},\r
+#endif\r
+#ifdef _PC_VDISABLE\r
+    {"PC_VDISABLE",     _PC_VDISABLE},\r
+#endif\r
+};\r
+\r
+static int\r
+conv_path_confname(PyObject *arg, int *valuep)\r
+{\r
+    return conv_confname(arg, valuep, posix_constants_pathconf,\r
+                         sizeof(posix_constants_pathconf)\r
+                           / sizeof(struct constdef));\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_FPATHCONF\r
+PyDoc_STRVAR(posix_fpathconf__doc__,\r
+"fpathconf(fd, name) -> integer\n\n\\r
+Return the configuration limit name for the file descriptor fd.\n\\r
+If there is no limit, return -1.");\r
+\r
+static PyObject *\r
+posix_fpathconf(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *result = NULL;\r
+    int name, fd;\r
+\r
+    if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd,\r
+                         conv_path_confname, &name)) {\r
+        long limit;\r
+\r
+        errno = 0;\r
+        limit = fpathconf(fd, name);\r
+        if (limit == -1 && errno != 0)\r
+            posix_error();\r
+        else\r
+            result = PyInt_FromLong(limit);\r
+    }\r
+    return result;\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_PATHCONF\r
+PyDoc_STRVAR(posix_pathconf__doc__,\r
+"pathconf(path, name) -> integer\n\n\\r
+Return the configuration limit name for the file or directory path.\n\\r
+If there is no limit, return -1.");\r
+\r
+static PyObject *\r
+posix_pathconf(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *result = NULL;\r
+    int name;\r
+    char *path;\r
+\r
+    if (PyArg_ParseTuple(args, "sO&:pathconf", &path,\r
+                         conv_path_confname, &name)) {\r
+    long limit;\r
+\r
+    errno = 0;\r
+    limit = pathconf(path, name);\r
+    if (limit == -1 && errno != 0) {\r
+        if (errno == EINVAL)\r
+            /* could be a path or name problem */\r
+            posix_error();\r
+        else\r
+            posix_error_with_filename(path);\r
+    }\r
+    else\r
+        result = PyInt_FromLong(limit);\r
+    }\r
+    return result;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_CONFSTR\r
+static struct constdef posix_constants_confstr[] = {\r
+#ifdef _CS_ARCHITECTURE\r
+    {"CS_ARCHITECTURE", _CS_ARCHITECTURE},\r
+#endif\r
+#ifdef _CS_HOSTNAME\r
+    {"CS_HOSTNAME",     _CS_HOSTNAME},\r
+#endif\r
+#ifdef _CS_HW_PROVIDER\r
+    {"CS_HW_PROVIDER",  _CS_HW_PROVIDER},\r
+#endif\r
+#ifdef _CS_HW_SERIAL\r
+    {"CS_HW_SERIAL",    _CS_HW_SERIAL},\r
+#endif\r
+#ifdef _CS_INITTAB_NAME\r
+    {"CS_INITTAB_NAME", _CS_INITTAB_NAME},\r
+#endif\r
+#ifdef _CS_LFS64_CFLAGS\r
+    {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},\r
+#endif\r
+#ifdef _CS_LFS64_LDFLAGS\r
+    {"CS_LFS64_LDFLAGS",        _CS_LFS64_LDFLAGS},\r
+#endif\r
+#ifdef _CS_LFS64_LIBS\r
+    {"CS_LFS64_LIBS",   _CS_LFS64_LIBS},\r
+#endif\r
+#ifdef _CS_LFS64_LINTFLAGS\r
+    {"CS_LFS64_LINTFLAGS",      _CS_LFS64_LINTFLAGS},\r
+#endif\r
+#ifdef _CS_LFS_CFLAGS\r
+    {"CS_LFS_CFLAGS",   _CS_LFS_CFLAGS},\r
+#endif\r
+#ifdef _CS_LFS_LDFLAGS\r
+    {"CS_LFS_LDFLAGS",  _CS_LFS_LDFLAGS},\r
+#endif\r
+#ifdef _CS_LFS_LIBS\r
+    {"CS_LFS_LIBS",     _CS_LFS_LIBS},\r
+#endif\r
+#ifdef _CS_LFS_LINTFLAGS\r
+    {"CS_LFS_LINTFLAGS",        _CS_LFS_LINTFLAGS},\r
+#endif\r
+#ifdef _CS_MACHINE\r
+    {"CS_MACHINE",      _CS_MACHINE},\r
+#endif\r
+#ifdef _CS_PATH\r
+    {"CS_PATH", _CS_PATH},\r
+#endif\r
+#ifdef _CS_RELEASE\r
+    {"CS_RELEASE",      _CS_RELEASE},\r
+#endif\r
+#ifdef _CS_SRPC_DOMAIN\r
+    {"CS_SRPC_DOMAIN",  _CS_SRPC_DOMAIN},\r
+#endif\r
+#ifdef _CS_SYSNAME\r
+    {"CS_SYSNAME",      _CS_SYSNAME},\r
+#endif\r
+#ifdef _CS_VERSION\r
+    {"CS_VERSION",      _CS_VERSION},\r
+#endif\r
+#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS\r
+    {"CS_XBS5_ILP32_OFF32_CFLAGS",      _CS_XBS5_ILP32_OFF32_CFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS\r
+    {"CS_XBS5_ILP32_OFF32_LDFLAGS",     _CS_XBS5_ILP32_OFF32_LDFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_ILP32_OFF32_LIBS\r
+    {"CS_XBS5_ILP32_OFF32_LIBS",        _CS_XBS5_ILP32_OFF32_LIBS},\r
+#endif\r
+#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS\r
+    {"CS_XBS5_ILP32_OFF32_LINTFLAGS",   _CS_XBS5_ILP32_OFF32_LINTFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS\r
+    {"CS_XBS5_ILP32_OFFBIG_CFLAGS",     _CS_XBS5_ILP32_OFFBIG_CFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS\r
+    {"CS_XBS5_ILP32_OFFBIG_LDFLAGS",    _CS_XBS5_ILP32_OFFBIG_LDFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS\r
+    {"CS_XBS5_ILP32_OFFBIG_LIBS",       _CS_XBS5_ILP32_OFFBIG_LIBS},\r
+#endif\r
+#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS\r
+    {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS",  _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_LP64_OFF64_CFLAGS\r
+    {"CS_XBS5_LP64_OFF64_CFLAGS",       _CS_XBS5_LP64_OFF64_CFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS\r
+    {"CS_XBS5_LP64_OFF64_LDFLAGS",      _CS_XBS5_LP64_OFF64_LDFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_LP64_OFF64_LIBS\r
+    {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},\r
+#endif\r
+#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS\r
+    {"CS_XBS5_LP64_OFF64_LINTFLAGS",    _CS_XBS5_LP64_OFF64_LINTFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS\r
+    {"CS_XBS5_LPBIG_OFFBIG_CFLAGS",     _CS_XBS5_LPBIG_OFFBIG_CFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS\r
+    {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS",    _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},\r
+#endif\r
+#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS\r
+    {"CS_XBS5_LPBIG_OFFBIG_LIBS",       _CS_XBS5_LPBIG_OFFBIG_LIBS},\r
+#endif\r
+#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS\r
+    {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS",  _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},\r
+#endif\r
+#ifdef _MIPS_CS_AVAIL_PROCESSORS\r
+    {"MIPS_CS_AVAIL_PROCESSORS",        _MIPS_CS_AVAIL_PROCESSORS},\r
+#endif\r
+#ifdef _MIPS_CS_BASE\r
+    {"MIPS_CS_BASE",    _MIPS_CS_BASE},\r
+#endif\r
+#ifdef _MIPS_CS_HOSTID\r
+    {"MIPS_CS_HOSTID",  _MIPS_CS_HOSTID},\r
+#endif\r
+#ifdef _MIPS_CS_HW_NAME\r
+    {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},\r
+#endif\r
+#ifdef _MIPS_CS_NUM_PROCESSORS\r
+    {"MIPS_CS_NUM_PROCESSORS",  _MIPS_CS_NUM_PROCESSORS},\r
+#endif\r
+#ifdef _MIPS_CS_OSREL_MAJ\r
+    {"MIPS_CS_OSREL_MAJ",       _MIPS_CS_OSREL_MAJ},\r
+#endif\r
+#ifdef _MIPS_CS_OSREL_MIN\r
+    {"MIPS_CS_OSREL_MIN",       _MIPS_CS_OSREL_MIN},\r
+#endif\r
+#ifdef _MIPS_CS_OSREL_PATCH\r
+    {"MIPS_CS_OSREL_PATCH",     _MIPS_CS_OSREL_PATCH},\r
+#endif\r
+#ifdef _MIPS_CS_OS_NAME\r
+    {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},\r
+#endif\r
+#ifdef _MIPS_CS_OS_PROVIDER\r
+    {"MIPS_CS_OS_PROVIDER",     _MIPS_CS_OS_PROVIDER},\r
+#endif\r
+#ifdef _MIPS_CS_PROCESSORS\r
+    {"MIPS_CS_PROCESSORS",      _MIPS_CS_PROCESSORS},\r
+#endif\r
+#ifdef _MIPS_CS_SERIAL\r
+    {"MIPS_CS_SERIAL",  _MIPS_CS_SERIAL},\r
+#endif\r
+#ifdef _MIPS_CS_VENDOR\r
+    {"MIPS_CS_VENDOR",  _MIPS_CS_VENDOR},\r
+#endif\r
+};\r
+\r
+static int\r
+conv_confstr_confname(PyObject *arg, int *valuep)\r
+{\r
+    return conv_confname(arg, valuep, posix_constants_confstr,\r
+                         sizeof(posix_constants_confstr)\r
+                           / sizeof(struct constdef));\r
+}\r
+\r
+PyDoc_STRVAR(posix_confstr__doc__,\r
+"confstr(name) -> string\n\n\\r
+Return a string-valued system configuration variable.");\r
+\r
+static PyObject *\r
+posix_confstr(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *result = NULL;\r
+    int name;\r
+    char buffer[256];\r
+\r
+    if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) {\r
+    int len;\r
+\r
+    errno = 0;\r
+    len = confstr(name, buffer, sizeof(buffer));\r
+    if (len == 0) {\r
+        if (errno) {\r
+        posix_error();\r
+        }\r
+        else {\r
+        result = Py_None;\r
+        Py_INCREF(Py_None);\r
+        }\r
+    }\r
+    else {\r
+        if ((unsigned int)len >= sizeof(buffer)) {\r
+        result = PyString_FromStringAndSize(NULL, len-1);\r
+        if (result != NULL)\r
+            confstr(name, PyString_AS_STRING(result), len);\r
+        }\r
+        else\r
+        result = PyString_FromStringAndSize(buffer, len-1);\r
+    }\r
+    }\r
+    return result;\r
+}\r
+#endif\r
+\r
+\r
+#ifdef HAVE_SYSCONF\r
+static struct constdef posix_constants_sysconf[] = {\r
+#ifdef _SC_2_CHAR_TERM\r
+    {"SC_2_CHAR_TERM",  _SC_2_CHAR_TERM},\r
+#endif\r
+#ifdef _SC_2_C_BIND\r
+    {"SC_2_C_BIND",     _SC_2_C_BIND},\r
+#endif\r
+#ifdef _SC_2_C_DEV\r
+    {"SC_2_C_DEV",      _SC_2_C_DEV},\r
+#endif\r
+#ifdef _SC_2_C_VERSION\r
+    {"SC_2_C_VERSION",  _SC_2_C_VERSION},\r
+#endif\r
+#ifdef _SC_2_FORT_DEV\r
+    {"SC_2_FORT_DEV",   _SC_2_FORT_DEV},\r
+#endif\r
+#ifdef _SC_2_FORT_RUN\r
+    {"SC_2_FORT_RUN",   _SC_2_FORT_RUN},\r
+#endif\r
+#ifdef _SC_2_LOCALEDEF\r
+    {"SC_2_LOCALEDEF",  _SC_2_LOCALEDEF},\r
+#endif\r
+#ifdef _SC_2_SW_DEV\r
+    {"SC_2_SW_DEV",     _SC_2_SW_DEV},\r
+#endif\r
+#ifdef _SC_2_UPE\r
+    {"SC_2_UPE",        _SC_2_UPE},\r
+#endif\r
+#ifdef _SC_2_VERSION\r
+    {"SC_2_VERSION",    _SC_2_VERSION},\r
+#endif\r
+#ifdef _SC_ABI_ASYNCHRONOUS_IO\r
+    {"SC_ABI_ASYNCHRONOUS_IO",  _SC_ABI_ASYNCHRONOUS_IO},\r
+#endif\r
+#ifdef _SC_ACL\r
+    {"SC_ACL",  _SC_ACL},\r
+#endif\r
+#ifdef _SC_AIO_LISTIO_MAX\r
+    {"SC_AIO_LISTIO_MAX",       _SC_AIO_LISTIO_MAX},\r
+#endif\r
+#ifdef _SC_AIO_MAX\r
+    {"SC_AIO_MAX",      _SC_AIO_MAX},\r
+#endif\r
+#ifdef _SC_AIO_PRIO_DELTA_MAX\r
+    {"SC_AIO_PRIO_DELTA_MAX",   _SC_AIO_PRIO_DELTA_MAX},\r
+#endif\r
+#ifdef _SC_ARG_MAX\r
+    {"SC_ARG_MAX",      _SC_ARG_MAX},\r
+#endif\r
+#ifdef _SC_ASYNCHRONOUS_IO\r
+    {"SC_ASYNCHRONOUS_IO",      _SC_ASYNCHRONOUS_IO},\r
+#endif\r
+#ifdef _SC_ATEXIT_MAX\r
+    {"SC_ATEXIT_MAX",   _SC_ATEXIT_MAX},\r
+#endif\r
+#ifdef _SC_AUDIT\r
+    {"SC_AUDIT",        _SC_AUDIT},\r
+#endif\r
+#ifdef _SC_AVPHYS_PAGES\r
+    {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},\r
+#endif\r
+#ifdef _SC_BC_BASE_MAX\r
+    {"SC_BC_BASE_MAX",  _SC_BC_BASE_MAX},\r
+#endif\r
+#ifdef _SC_BC_DIM_MAX\r
+    {"SC_BC_DIM_MAX",   _SC_BC_DIM_MAX},\r
+#endif\r
+#ifdef _SC_BC_SCALE_MAX\r
+    {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},\r
+#endif\r
+#ifdef _SC_BC_STRING_MAX\r
+    {"SC_BC_STRING_MAX",        _SC_BC_STRING_MAX},\r
+#endif\r
+#ifdef _SC_CAP\r
+    {"SC_CAP",  _SC_CAP},\r
+#endif\r
+#ifdef _SC_CHARCLASS_NAME_MAX\r
+    {"SC_CHARCLASS_NAME_MAX",   _SC_CHARCLASS_NAME_MAX},\r
+#endif\r
+#ifdef _SC_CHAR_BIT\r
+    {"SC_CHAR_BIT",     _SC_CHAR_BIT},\r
+#endif\r
+#ifdef _SC_CHAR_MAX\r
+    {"SC_CHAR_MAX",     _SC_CHAR_MAX},\r
+#endif\r
+#ifdef _SC_CHAR_MIN\r
+    {"SC_CHAR_MIN",     _SC_CHAR_MIN},\r
+#endif\r
+#ifdef _SC_CHILD_MAX\r
+    {"SC_CHILD_MAX",    _SC_CHILD_MAX},\r
+#endif\r
+#ifdef _SC_CLK_TCK\r
+    {"SC_CLK_TCK",      _SC_CLK_TCK},\r
+#endif\r
+#ifdef _SC_COHER_BLKSZ\r
+    {"SC_COHER_BLKSZ",  _SC_COHER_BLKSZ},\r
+#endif\r
+#ifdef _SC_COLL_WEIGHTS_MAX\r
+    {"SC_COLL_WEIGHTS_MAX",     _SC_COLL_WEIGHTS_MAX},\r
+#endif\r
+#ifdef _SC_DCACHE_ASSOC\r
+    {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},\r
+#endif\r
+#ifdef _SC_DCACHE_BLKSZ\r
+    {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},\r
+#endif\r
+#ifdef _SC_DCACHE_LINESZ\r
+    {"SC_DCACHE_LINESZ",        _SC_DCACHE_LINESZ},\r
+#endif\r
+#ifdef _SC_DCACHE_SZ\r
+    {"SC_DCACHE_SZ",    _SC_DCACHE_SZ},\r
+#endif\r
+#ifdef _SC_DCACHE_TBLKSZ\r
+    {"SC_DCACHE_TBLKSZ",        _SC_DCACHE_TBLKSZ},\r
+#endif\r
+#ifdef _SC_DELAYTIMER_MAX\r
+    {"SC_DELAYTIMER_MAX",       _SC_DELAYTIMER_MAX},\r
+#endif\r
+#ifdef _SC_EQUIV_CLASS_MAX\r
+    {"SC_EQUIV_CLASS_MAX",      _SC_EQUIV_CLASS_MAX},\r
+#endif\r
+#ifdef _SC_EXPR_NEST_MAX\r
+    {"SC_EXPR_NEST_MAX",        _SC_EXPR_NEST_MAX},\r
+#endif\r
+#ifdef _SC_FSYNC\r
+    {"SC_FSYNC",        _SC_FSYNC},\r
+#endif\r
+#ifdef _SC_GETGR_R_SIZE_MAX\r
+    {"SC_GETGR_R_SIZE_MAX",     _SC_GETGR_R_SIZE_MAX},\r
+#endif\r
+#ifdef _SC_GETPW_R_SIZE_MAX\r
+    {"SC_GETPW_R_SIZE_MAX",     _SC_GETPW_R_SIZE_MAX},\r
+#endif\r
+#ifdef _SC_ICACHE_ASSOC\r
+    {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},\r
+#endif\r
+#ifdef _SC_ICACHE_BLKSZ\r
+    {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},\r
+#endif\r
+#ifdef _SC_ICACHE_LINESZ\r
+    {"SC_ICACHE_LINESZ",        _SC_ICACHE_LINESZ},\r
+#endif\r
+#ifdef _SC_ICACHE_SZ\r
+    {"SC_ICACHE_SZ",    _SC_ICACHE_SZ},\r
+#endif\r
+#ifdef _SC_INF\r
+    {"SC_INF",  _SC_INF},\r
+#endif\r
+#ifdef _SC_INT_MAX\r
+    {"SC_INT_MAX",      _SC_INT_MAX},\r
+#endif\r
+#ifdef _SC_INT_MIN\r
+    {"SC_INT_MIN",      _SC_INT_MIN},\r
+#endif\r
+#ifdef _SC_IOV_MAX\r
+    {"SC_IOV_MAX",      _SC_IOV_MAX},\r
+#endif\r
+#ifdef _SC_IP_SECOPTS\r
+    {"SC_IP_SECOPTS",   _SC_IP_SECOPTS},\r
+#endif\r
+#ifdef _SC_JOB_CONTROL\r
+    {"SC_JOB_CONTROL",  _SC_JOB_CONTROL},\r
+#endif\r
+#ifdef _SC_KERN_POINTERS\r
+    {"SC_KERN_POINTERS",        _SC_KERN_POINTERS},\r
+#endif\r
+#ifdef _SC_KERN_SIM\r
+    {"SC_KERN_SIM",     _SC_KERN_SIM},\r
+#endif\r
+#ifdef _SC_LINE_MAX\r
+    {"SC_LINE_MAX",     _SC_LINE_MAX},\r
+#endif\r
+#ifdef _SC_LOGIN_NAME_MAX\r
+    {"SC_LOGIN_NAME_MAX",       _SC_LOGIN_NAME_MAX},\r
+#endif\r
+#ifdef _SC_LOGNAME_MAX\r
+    {"SC_LOGNAME_MAX",  _SC_LOGNAME_MAX},\r
+#endif\r
+#ifdef _SC_LONG_BIT\r
+    {"SC_LONG_BIT",     _SC_LONG_BIT},\r
+#endif\r
+#ifdef _SC_MAC\r
+    {"SC_MAC",  _SC_MAC},\r
+#endif\r
+#ifdef _SC_MAPPED_FILES\r
+    {"SC_MAPPED_FILES", _SC_MAPPED_FILES},\r
+#endif\r
+#ifdef _SC_MAXPID\r
+    {"SC_MAXPID",       _SC_MAXPID},\r
+#endif\r
+#ifdef _SC_MB_LEN_MAX\r
+    {"SC_MB_LEN_MAX",   _SC_MB_LEN_MAX},\r
+#endif\r
+#ifdef _SC_MEMLOCK\r
+    {"SC_MEMLOCK",      _SC_MEMLOCK},\r
+#endif\r
+#ifdef _SC_MEMLOCK_RANGE\r
+    {"SC_MEMLOCK_RANGE",        _SC_MEMLOCK_RANGE},\r
+#endif\r
+#ifdef _SC_MEMORY_PROTECTION\r
+    {"SC_MEMORY_PROTECTION",    _SC_MEMORY_PROTECTION},\r
+#endif\r
+#ifdef _SC_MESSAGE_PASSING\r
+    {"SC_MESSAGE_PASSING",      _SC_MESSAGE_PASSING},\r
+#endif\r
+#ifdef _SC_MMAP_FIXED_ALIGNMENT\r
+    {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},\r
+#endif\r
+#ifdef _SC_MQ_OPEN_MAX\r
+    {"SC_MQ_OPEN_MAX",  _SC_MQ_OPEN_MAX},\r
+#endif\r
+#ifdef _SC_MQ_PRIO_MAX\r
+    {"SC_MQ_PRIO_MAX",  _SC_MQ_PRIO_MAX},\r
+#endif\r
+#ifdef _SC_NACLS_MAX\r
+    {"SC_NACLS_MAX",    _SC_NACLS_MAX},\r
+#endif\r
+#ifdef _SC_NGROUPS_MAX\r
+    {"SC_NGROUPS_MAX",  _SC_NGROUPS_MAX},\r
+#endif\r
+#ifdef _SC_NL_ARGMAX\r
+    {"SC_NL_ARGMAX",    _SC_NL_ARGMAX},\r
+#endif\r
+#ifdef _SC_NL_LANGMAX\r
+    {"SC_NL_LANGMAX",   _SC_NL_LANGMAX},\r
+#endif\r
+#ifdef _SC_NL_MSGMAX\r
+    {"SC_NL_MSGMAX",    _SC_NL_MSGMAX},\r
+#endif\r
+#ifdef _SC_NL_NMAX\r
+    {"SC_NL_NMAX",      _SC_NL_NMAX},\r
+#endif\r
+#ifdef _SC_NL_SETMAX\r
+    {"SC_NL_SETMAX",    _SC_NL_SETMAX},\r
+#endif\r
+#ifdef _SC_NL_TEXTMAX\r
+    {"SC_NL_TEXTMAX",   _SC_NL_TEXTMAX},\r
+#endif\r
+#ifdef _SC_NPROCESSORS_CONF\r
+    {"SC_NPROCESSORS_CONF",     _SC_NPROCESSORS_CONF},\r
+#endif\r
+#ifdef _SC_NPROCESSORS_ONLN\r
+    {"SC_NPROCESSORS_ONLN",     _SC_NPROCESSORS_ONLN},\r
+#endif\r
+#ifdef _SC_NPROC_CONF\r
+    {"SC_NPROC_CONF",   _SC_NPROC_CONF},\r
+#endif\r
+#ifdef _SC_NPROC_ONLN\r
+    {"SC_NPROC_ONLN",   _SC_NPROC_ONLN},\r
+#endif\r
+#ifdef _SC_NZERO\r
+    {"SC_NZERO",        _SC_NZERO},\r
+#endif\r
+#ifdef _SC_OPEN_MAX\r
+    {"SC_OPEN_MAX",     _SC_OPEN_MAX},\r
+#endif\r
+#ifdef _SC_PAGESIZE\r
+    {"SC_PAGESIZE",     _SC_PAGESIZE},\r
+#endif\r
+#ifdef _SC_PAGE_SIZE\r
+    {"SC_PAGE_SIZE",    _SC_PAGE_SIZE},\r
+#endif\r
+#ifdef _SC_PASS_MAX\r
+    {"SC_PASS_MAX",     _SC_PASS_MAX},\r
+#endif\r
+#ifdef _SC_PHYS_PAGES\r
+    {"SC_PHYS_PAGES",   _SC_PHYS_PAGES},\r
+#endif\r
+#ifdef _SC_PII\r
+    {"SC_PII",  _SC_PII},\r
+#endif\r
+#ifdef _SC_PII_INTERNET\r
+    {"SC_PII_INTERNET", _SC_PII_INTERNET},\r
+#endif\r
+#ifdef _SC_PII_INTERNET_DGRAM\r
+    {"SC_PII_INTERNET_DGRAM",   _SC_PII_INTERNET_DGRAM},\r
+#endif\r
+#ifdef _SC_PII_INTERNET_STREAM\r
+    {"SC_PII_INTERNET_STREAM",  _SC_PII_INTERNET_STREAM},\r
+#endif\r
+#ifdef _SC_PII_OSI\r
+    {"SC_PII_OSI",      _SC_PII_OSI},\r
+#endif\r
+#ifdef _SC_PII_OSI_CLTS\r
+    {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},\r
+#endif\r
+#ifdef _SC_PII_OSI_COTS\r
+    {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},\r
+#endif\r
+#ifdef _SC_PII_OSI_M\r
+    {"SC_PII_OSI_M",    _SC_PII_OSI_M},\r
+#endif\r
+#ifdef _SC_PII_SOCKET\r
+    {"SC_PII_SOCKET",   _SC_PII_SOCKET},\r
+#endif\r
+#ifdef _SC_PII_XTI\r
+    {"SC_PII_XTI",      _SC_PII_XTI},\r
+#endif\r
+#ifdef _SC_POLL\r
+    {"SC_POLL", _SC_POLL},\r
+#endif\r
+#ifdef _SC_PRIORITIZED_IO\r
+    {"SC_PRIORITIZED_IO",       _SC_PRIORITIZED_IO},\r
+#endif\r
+#ifdef _SC_PRIORITY_SCHEDULING\r
+    {"SC_PRIORITY_SCHEDULING",  _SC_PRIORITY_SCHEDULING},\r
+#endif\r
+#ifdef _SC_REALTIME_SIGNALS\r
+    {"SC_REALTIME_SIGNALS",     _SC_REALTIME_SIGNALS},\r
+#endif\r
+#ifdef _SC_RE_DUP_MAX\r
+    {"SC_RE_DUP_MAX",   _SC_RE_DUP_MAX},\r
+#endif\r
+#ifdef _SC_RTSIG_MAX\r
+    {"SC_RTSIG_MAX",    _SC_RTSIG_MAX},\r
+#endif\r
+#ifdef _SC_SAVED_IDS\r
+    {"SC_SAVED_IDS",    _SC_SAVED_IDS},\r
+#endif\r
+#ifdef _SC_SCHAR_MAX\r
+    {"SC_SCHAR_MAX",    _SC_SCHAR_MAX},\r
+#endif\r
+#ifdef _SC_SCHAR_MIN\r
+    {"SC_SCHAR_MIN",    _SC_SCHAR_MIN},\r
+#endif\r
+#ifdef _SC_SELECT\r
+    {"SC_SELECT",       _SC_SELECT},\r
+#endif\r
+#ifdef _SC_SEMAPHORES\r
+    {"SC_SEMAPHORES",   _SC_SEMAPHORES},\r
+#endif\r
+#ifdef _SC_SEM_NSEMS_MAX\r
+    {"SC_SEM_NSEMS_MAX",        _SC_SEM_NSEMS_MAX},\r
+#endif\r
+#ifdef _SC_SEM_VALUE_MAX\r
+    {"SC_SEM_VALUE_MAX",        _SC_SEM_VALUE_MAX},\r
+#endif\r
+#ifdef _SC_SHARED_MEMORY_OBJECTS\r
+    {"SC_SHARED_MEMORY_OBJECTS",        _SC_SHARED_MEMORY_OBJECTS},\r
+#endif\r
+#ifdef _SC_SHRT_MAX\r
+    {"SC_SHRT_MAX",     _SC_SHRT_MAX},\r
+#endif\r
+#ifdef _SC_SHRT_MIN\r
+    {"SC_SHRT_MIN",     _SC_SHRT_MIN},\r
+#endif\r
+#ifdef _SC_SIGQUEUE_MAX\r
+    {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},\r
+#endif\r
+#ifdef _SC_SIGRT_MAX\r
+    {"SC_SIGRT_MAX",    _SC_SIGRT_MAX},\r
+#endif\r
+#ifdef _SC_SIGRT_MIN\r
+    {"SC_SIGRT_MIN",    _SC_SIGRT_MIN},\r
+#endif\r
+#ifdef _SC_SOFTPOWER\r
+    {"SC_SOFTPOWER",    _SC_SOFTPOWER},\r
+#endif\r
+#ifdef _SC_SPLIT_CACHE\r
+    {"SC_SPLIT_CACHE",  _SC_SPLIT_CACHE},\r
+#endif\r
+#ifdef _SC_SSIZE_MAX\r
+    {"SC_SSIZE_MAX",    _SC_SSIZE_MAX},\r
+#endif\r
+#ifdef _SC_STACK_PROT\r
+    {"SC_STACK_PROT",   _SC_STACK_PROT},\r
+#endif\r
+#ifdef _SC_STREAM_MAX\r
+    {"SC_STREAM_MAX",   _SC_STREAM_MAX},\r
+#endif\r
+#ifdef _SC_SYNCHRONIZED_IO\r
+    {"SC_SYNCHRONIZED_IO",      _SC_SYNCHRONIZED_IO},\r
+#endif\r
+#ifdef _SC_THREADS\r
+    {"SC_THREADS",      _SC_THREADS},\r
+#endif\r
+#ifdef _SC_THREAD_ATTR_STACKADDR\r
+    {"SC_THREAD_ATTR_STACKADDR",        _SC_THREAD_ATTR_STACKADDR},\r
+#endif\r
+#ifdef _SC_THREAD_ATTR_STACKSIZE\r
+    {"SC_THREAD_ATTR_STACKSIZE",        _SC_THREAD_ATTR_STACKSIZE},\r
+#endif\r
+#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS\r
+    {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},\r
+#endif\r
+#ifdef _SC_THREAD_KEYS_MAX\r
+    {"SC_THREAD_KEYS_MAX",      _SC_THREAD_KEYS_MAX},\r
+#endif\r
+#ifdef _SC_THREAD_PRIORITY_SCHEDULING\r
+    {"SC_THREAD_PRIORITY_SCHEDULING",   _SC_THREAD_PRIORITY_SCHEDULING},\r
+#endif\r
+#ifdef _SC_THREAD_PRIO_INHERIT\r
+    {"SC_THREAD_PRIO_INHERIT",  _SC_THREAD_PRIO_INHERIT},\r
+#endif\r
+#ifdef _SC_THREAD_PRIO_PROTECT\r
+    {"SC_THREAD_PRIO_PROTECT",  _SC_THREAD_PRIO_PROTECT},\r
+#endif\r
+#ifdef _SC_THREAD_PROCESS_SHARED\r
+    {"SC_THREAD_PROCESS_SHARED",        _SC_THREAD_PROCESS_SHARED},\r
+#endif\r
+#ifdef _SC_THREAD_SAFE_FUNCTIONS\r
+    {"SC_THREAD_SAFE_FUNCTIONS",        _SC_THREAD_SAFE_FUNCTIONS},\r
+#endif\r
+#ifdef _SC_THREAD_STACK_MIN\r
+    {"SC_THREAD_STACK_MIN",     _SC_THREAD_STACK_MIN},\r
+#endif\r
+#ifdef _SC_THREAD_THREADS_MAX\r
+    {"SC_THREAD_THREADS_MAX",   _SC_THREAD_THREADS_MAX},\r
+#endif\r
+#ifdef _SC_TIMERS\r
+    {"SC_TIMERS",       _SC_TIMERS},\r
+#endif\r
+#ifdef _SC_TIMER_MAX\r
+    {"SC_TIMER_MAX",    _SC_TIMER_MAX},\r
+#endif\r
+#ifdef _SC_TTY_NAME_MAX\r
+    {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},\r
+#endif\r
+#ifdef _SC_TZNAME_MAX\r
+    {"SC_TZNAME_MAX",   _SC_TZNAME_MAX},\r
+#endif\r
+#ifdef _SC_T_IOV_MAX\r
+    {"SC_T_IOV_MAX",    _SC_T_IOV_MAX},\r
+#endif\r
+#ifdef _SC_UCHAR_MAX\r
+    {"SC_UCHAR_MAX",    _SC_UCHAR_MAX},\r
+#endif\r
+#ifdef _SC_UINT_MAX\r
+    {"SC_UINT_MAX",     _SC_UINT_MAX},\r
+#endif\r
+#ifdef _SC_UIO_MAXIOV\r
+    {"SC_UIO_MAXIOV",   _SC_UIO_MAXIOV},\r
+#endif\r
+#ifdef _SC_ULONG_MAX\r
+    {"SC_ULONG_MAX",    _SC_ULONG_MAX},\r
+#endif\r
+#ifdef _SC_USHRT_MAX\r
+    {"SC_USHRT_MAX",    _SC_USHRT_MAX},\r
+#endif\r
+#ifdef _SC_VERSION\r
+    {"SC_VERSION",      _SC_VERSION},\r
+#endif\r
+#ifdef _SC_WORD_BIT\r
+    {"SC_WORD_BIT",     _SC_WORD_BIT},\r
+#endif\r
+#ifdef _SC_XBS5_ILP32_OFF32\r
+    {"SC_XBS5_ILP32_OFF32",     _SC_XBS5_ILP32_OFF32},\r
+#endif\r
+#ifdef _SC_XBS5_ILP32_OFFBIG\r
+    {"SC_XBS5_ILP32_OFFBIG",    _SC_XBS5_ILP32_OFFBIG},\r
+#endif\r
+#ifdef _SC_XBS5_LP64_OFF64\r
+    {"SC_XBS5_LP64_OFF64",      _SC_XBS5_LP64_OFF64},\r
+#endif\r
+#ifdef _SC_XBS5_LPBIG_OFFBIG\r
+    {"SC_XBS5_LPBIG_OFFBIG",    _SC_XBS5_LPBIG_OFFBIG},\r
+#endif\r
+#ifdef _SC_XOPEN_CRYPT\r
+    {"SC_XOPEN_CRYPT",  _SC_XOPEN_CRYPT},\r
+#endif\r
+#ifdef _SC_XOPEN_ENH_I18N\r
+    {"SC_XOPEN_ENH_I18N",       _SC_XOPEN_ENH_I18N},\r
+#endif\r
+#ifdef _SC_XOPEN_LEGACY\r
+    {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},\r
+#endif\r
+#ifdef _SC_XOPEN_REALTIME\r
+    {"SC_XOPEN_REALTIME",       _SC_XOPEN_REALTIME},\r
+#endif\r
+#ifdef _SC_XOPEN_REALTIME_THREADS\r
+    {"SC_XOPEN_REALTIME_THREADS",       _SC_XOPEN_REALTIME_THREADS},\r
+#endif\r
+#ifdef _SC_XOPEN_SHM\r
+    {"SC_XOPEN_SHM",    _SC_XOPEN_SHM},\r
+#endif\r
+#ifdef _SC_XOPEN_UNIX\r
+    {"SC_XOPEN_UNIX",   _SC_XOPEN_UNIX},\r
+#endif\r
+#ifdef _SC_XOPEN_VERSION\r
+    {"SC_XOPEN_VERSION",        _SC_XOPEN_VERSION},\r
+#endif\r
+#ifdef _SC_XOPEN_XCU_VERSION\r
+    {"SC_XOPEN_XCU_VERSION",    _SC_XOPEN_XCU_VERSION},\r
+#endif\r
+#ifdef _SC_XOPEN_XPG2\r
+    {"SC_XOPEN_XPG2",   _SC_XOPEN_XPG2},\r
+#endif\r
+#ifdef _SC_XOPEN_XPG3\r
+    {"SC_XOPEN_XPG3",   _SC_XOPEN_XPG3},\r
+#endif\r
+#ifdef _SC_XOPEN_XPG4\r
+    {"SC_XOPEN_XPG4",   _SC_XOPEN_XPG4},\r
+#endif\r
+};\r
+\r
+static int\r
+conv_sysconf_confname(PyObject *arg, int *valuep)\r
+{\r
+    return conv_confname(arg, valuep, posix_constants_sysconf,\r
+                         sizeof(posix_constants_sysconf)\r
+                           / sizeof(struct constdef));\r
+}\r
+\r
+PyDoc_STRVAR(posix_sysconf__doc__,\r
+"sysconf(name) -> integer\n\n\\r
+Return an integer-valued system configuration variable.");\r
+\r
+static PyObject *\r
+posix_sysconf(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *result = NULL;\r
+    int name;\r
+\r
+    if (PyArg_ParseTuple(args, "O&:sysconf", conv_sysconf_confname, &name)) {\r
+        int value;\r
+\r
+        errno = 0;\r
+        value = sysconf(name);\r
+        if (value == -1 && errno != 0)\r
+            posix_error();\r
+        else\r
+            result = PyInt_FromLong(value);\r
+    }\r
+    return result;\r
+}\r
+#endif\r
+\r
+\r
+/* This code is used to ensure that the tables of configuration value names\r
+ * are in sorted order as required by conv_confname(), and also to build the\r
+ * the exported dictionaries that are used to publish information about the\r
+ * names available on the host platform.\r
+ *\r
+ * Sorting the table at runtime ensures that the table is properly ordered\r
+ * when used, even for platforms we're not able to test on.  It also makes\r
+ * it easier to add additional entries to the tables.\r
+ */\r
+\r
+static int\r
+cmp_constdefs(const void *v1,  const void *v2)\r
+{\r
+    const struct constdef *c1 =\r
+    (const struct constdef *) v1;\r
+    const struct constdef *c2 =\r
+    (const struct constdef *) v2;\r
+\r
+    return strcmp(c1->name, c2->name);\r
+}\r
+\r
+static int\r
+setup_confname_table(struct constdef *table, size_t tablesize,\r
+                     char *tablename, PyObject *module)\r
+{\r
+    PyObject *d = NULL;\r
+    size_t i;\r
+\r
+    qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);\r
+    d = PyDict_New();\r
+    if (d == NULL)\r
+        return -1;\r
+\r
+    for (i=0; i < tablesize; ++i) {\r
+        PyObject *o = PyInt_FromLong(table[i].value);\r
+        if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {\r
+            Py_XDECREF(o);\r
+            Py_DECREF(d);\r
+            return -1;\r
+        }\r
+        Py_DECREF(o);\r
+    }\r
+    return PyModule_AddObject(module, tablename, d);\r
+}\r
+\r
+/* Return -1 on failure, 0 on success. */\r
+static int\r
+setup_confname_tables(PyObject *module)\r
+{\r
+#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)\r
+    if (setup_confname_table(posix_constants_pathconf,\r
+                             sizeof(posix_constants_pathconf)\r
+                               / sizeof(struct constdef),\r
+                             "pathconf_names", module))\r
+        return -1;\r
+#endif\r
+#ifdef HAVE_CONFSTR\r
+    if (setup_confname_table(posix_constants_confstr,\r
+                             sizeof(posix_constants_confstr)\r
+                               / sizeof(struct constdef),\r
+                             "confstr_names", module))\r
+        return -1;\r
+#endif\r
+#ifdef HAVE_SYSCONF\r
+    if (setup_confname_table(posix_constants_sysconf,\r
+                             sizeof(posix_constants_sysconf)\r
+                               / sizeof(struct constdef),\r
+                             "sysconf_names", module))\r
+        return -1;\r
+#endif\r
+    return 0;\r
+}\r
+\r
+\r
+PyDoc_STRVAR(posix_abort__doc__,\r
+"abort() -> does not return!\n\n\\r
+Abort the interpreter immediately.  This 'dumps core' or otherwise fails\n\\r
+in the hardest way possible on the hosting operating system.");\r
+\r
+static PyObject *\r
+posix_abort(PyObject *self, PyObject *noargs)\r
+{\r
+    abort();\r
+    /*NOTREACHED*/\r
+    Py_FatalError("abort() called from Python code didn't abort!");\r
+    return NULL;\r
+}\r
+\r
+#ifdef HAVE_SETRESUID\r
+PyDoc_STRVAR(posix_setresuid__doc__,\r
+"setresuid(ruid, euid, suid)\n\n\\r
+Set the current process's real, effective, and saved user ids.");\r
+\r
+static PyObject*\r
+posix_setresuid (PyObject *self, PyObject *args)\r
+{\r
+    /* We assume uid_t is no larger than a long. */\r
+    long ruid, euid, suid;\r
+    if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid))\r
+        return NULL;\r
+    if (setresuid(ruid, euid, suid) < 0)\r
+        return posix_error();\r
+    Py_RETURN_NONE;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_SETRESGID\r
+PyDoc_STRVAR(posix_setresgid__doc__,\r
+"setresgid(rgid, egid, sgid)\n\n\\r
+Set the current process's real, effective, and saved group ids.");\r
+\r
+static PyObject*\r
+posix_setresgid (PyObject *self, PyObject *args)\r
+{\r
+    /* We assume uid_t is no larger than a long. */\r
+    long rgid, egid, sgid;\r
+    if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid))\r
+        return NULL;\r
+    if (setresgid(rgid, egid, sgid) < 0)\r
+        return posix_error();\r
+    Py_RETURN_NONE;\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_GETRESUID\r
+PyDoc_STRVAR(posix_getresuid__doc__,\r
+"getresuid() -> (ruid, euid, suid)\n\n\\r
+Get tuple of the current process's real, effective, and saved user ids.");\r
+\r
+static PyObject*\r
+posix_getresuid (PyObject *self, PyObject *noargs)\r
+{\r
+    uid_t ruid, euid, suid;\r
+    long l_ruid, l_euid, l_suid;\r
+    if (getresuid(&ruid, &euid, &suid) < 0)\r
+        return posix_error();\r
+    /* Force the values into long's as we don't know the size of uid_t. */\r
+    l_ruid = ruid;\r
+    l_euid = euid;\r
+    l_suid = suid;\r
+    return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid);\r
+}\r
+#endif\r
+\r
+#ifdef HAVE_GETRESGID\r
+PyDoc_STRVAR(posix_getresgid__doc__,\r
+"getresgid() -> (rgid, egid, sgid)\n\n\\r
+Get tuple of the current process's real, effective, and saved group ids.");\r
+\r
+static PyObject*\r
+posix_getresgid (PyObject *self, PyObject *noargs)\r
+{\r
+    uid_t rgid, egid, sgid;\r
+    long l_rgid, l_egid, l_sgid;\r
+    if (getresgid(&rgid, &egid, &sgid) < 0)\r
+        return posix_error();\r
+    /* Force the values into long's as we don't know the size of uid_t. */\r
+    l_rgid = rgid;\r
+    l_egid = egid;\r
+    l_sgid = sgid;\r
+    return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid);\r
+}\r
+#endif\r
+\r
+static PyMethodDef posix_methods[] = {\r
+    {"access",          posix_access,     METH_VARARGS, posix_access__doc__},\r
+#ifdef HAVE_TTYNAME\r
+    {"ttyname",         posix_ttyname, METH_VARARGS, posix_ttyname__doc__},\r
+#endif\r
+    {"chdir",           posix_chdir,      METH_VARARGS, posix_chdir__doc__},\r
+#ifdef HAVE_CHFLAGS\r
+    {"chflags",         posix_chflags, METH_VARARGS, posix_chflags__doc__},\r
+#endif /* HAVE_CHFLAGS */\r
+    {"chmod",           posix_chmod,      METH_VARARGS, posix_chmod__doc__},\r
+#ifdef HAVE_FCHMOD\r
+    {"fchmod",          posix_fchmod, METH_VARARGS, posix_fchmod__doc__},\r
+#endif /* HAVE_FCHMOD */\r
+#ifdef HAVE_CHOWN\r
+    {"chown",           posix_chown, METH_VARARGS, posix_chown__doc__},\r
+#endif /* HAVE_CHOWN */\r
+#ifdef HAVE_LCHMOD\r
+    {"lchmod",          posix_lchmod, METH_VARARGS, posix_lchmod__doc__},\r
+#endif /* HAVE_LCHMOD */\r
+#ifdef HAVE_FCHOWN\r
+    {"fchown",          posix_fchown, METH_VARARGS, posix_fchown__doc__},\r
+#endif /* HAVE_FCHOWN */\r
+#ifdef HAVE_LCHFLAGS\r
+    {"lchflags",        posix_lchflags, METH_VARARGS, posix_lchflags__doc__},\r
+#endif /* HAVE_LCHFLAGS */\r
+#ifdef HAVE_LCHOWN\r
+    {"lchown",          posix_lchown, METH_VARARGS, posix_lchown__doc__},\r
+#endif /* HAVE_LCHOWN */\r
+#ifdef HAVE_CHROOT\r
+    {"chroot",          posix_chroot, METH_VARARGS, posix_chroot__doc__},\r
+#endif\r
+#ifdef HAVE_CTERMID\r
+    {"ctermid",         posix_ctermid, METH_NOARGS, posix_ctermid__doc__},\r
+#endif\r
+#ifdef HAVE_GETCWD\r
+    {"getcwd",          posix_getcwd,     METH_NOARGS,  posix_getcwd__doc__},\r
+#ifdef Py_USING_UNICODE\r
+    {"getcwdu",         posix_getcwdu,    METH_NOARGS,  posix_getcwdu__doc__},\r
+#endif\r
+#endif\r
+#ifdef HAVE_LINK\r
+    {"link",            posix_link, METH_VARARGS, posix_link__doc__},\r
+#endif /* HAVE_LINK */\r
+    {"listdir",         posix_listdir,    METH_VARARGS, posix_listdir__doc__},\r
+    {"lstat",           posix_lstat,      METH_VARARGS, posix_lstat__doc__},\r
+    {"mkdir",           posix_mkdir,      METH_VARARGS, posix_mkdir__doc__},\r
+#ifdef HAVE_NICE\r
+    {"nice",            posix_nice, METH_VARARGS, posix_nice__doc__},\r
+#endif /* HAVE_NICE */\r
+#ifdef HAVE_READLINK\r
+    {"readlink",        posix_readlink, METH_VARARGS, posix_readlink__doc__},\r
+#endif /* HAVE_READLINK */\r
+    {"rename",          posix_rename,     METH_VARARGS, posix_rename__doc__},\r
+    {"rmdir",           posix_rmdir,      METH_VARARGS, posix_rmdir__doc__},\r
+    {"stat",            posix_stat,       METH_VARARGS, posix_stat__doc__},\r
+    //{"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},\r
+#ifdef HAVE_SYMLINK\r
+    {"symlink",         posix_symlink, METH_VARARGS, posix_symlink__doc__},\r
+#endif /* HAVE_SYMLINK */\r
+#ifdef HAVE_SYSTEM\r
+    {"system",          posix_system, METH_VARARGS, posix_system__doc__},\r
+#endif\r
+    {"umask",           posix_umask,      METH_VARARGS, posix_umask__doc__},\r
+#ifdef HAVE_UNAME\r
+    {"uname",           posix_uname, METH_NOARGS, posix_uname__doc__},\r
+#endif /* HAVE_UNAME */\r
+    {"unlink",          posix_unlink,     METH_VARARGS, posix_unlink__doc__},\r
+    {"remove",          posix_unlink,     METH_VARARGS, posix_remove__doc__},\r
+    {"utime",           posix_utime,      METH_VARARGS, posix_utime__doc__},\r
+#ifdef HAVE_TIMES\r
+    {"times",           posix_times, METH_NOARGS, posix_times__doc__},\r
+#endif /* HAVE_TIMES */\r
+    {"_exit",           posix__exit,      METH_VARARGS, posix__exit__doc__},\r
+#ifdef HAVE_EXECV\r
+    {"execv",           posix_execv, METH_VARARGS, posix_execv__doc__},\r
+    {"execve",          posix_execve, METH_VARARGS, posix_execve__doc__},\r
+#endif /* HAVE_EXECV */\r
+#ifdef HAVE_SPAWNV\r
+    {"spawnv",          posix_spawnv, METH_VARARGS, posix_spawnv__doc__},\r
+    {"spawnve",         posix_spawnve, METH_VARARGS, posix_spawnve__doc__},\r
+#if defined(PYOS_OS2)\r
+    {"spawnvp",         posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__},\r
+    {"spawnvpe",        posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__},\r
+#endif /* PYOS_OS2 */\r
+#endif /* HAVE_SPAWNV */\r
+#ifdef HAVE_FORK1\r
+    {"fork1",       posix_fork1, METH_NOARGS, posix_fork1__doc__},\r
+#endif /* HAVE_FORK1 */\r
+#ifdef HAVE_FORK\r
+    {"fork",            posix_fork, METH_NOARGS, posix_fork__doc__},\r
+#endif /* HAVE_FORK */\r
+#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)\r
+    {"openpty",         posix_openpty, METH_NOARGS, posix_openpty__doc__},\r
+#endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */\r
+#ifdef HAVE_FORKPTY\r
+    {"forkpty",         posix_forkpty, METH_NOARGS, posix_forkpty__doc__},\r
+#endif /* HAVE_FORKPTY */\r
+#ifdef HAVE_GETEGID\r
+    {"getegid",         posix_getegid, METH_NOARGS, posix_getegid__doc__},\r
+#endif /* HAVE_GETEGID */\r
+#ifdef HAVE_GETEUID\r
+    {"geteuid",         posix_geteuid, METH_NOARGS, posix_geteuid__doc__},\r
+#endif /* HAVE_GETEUID */\r
+#ifdef HAVE_GETGID\r
+    {"getgid",          posix_getgid, METH_NOARGS, posix_getgid__doc__},\r
+#endif /* HAVE_GETGID */\r
+#ifdef HAVE_GETGROUPS\r
+    {"getgroups",       posix_getgroups, METH_NOARGS, posix_getgroups__doc__},\r
+#endif\r
+    {"getpid",          posix_getpid,     METH_NOARGS,  posix_getpid__doc__},\r
+#ifdef HAVE_GETPGRP\r
+    {"getpgrp",         posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__},\r
+#endif /* HAVE_GETPGRP */\r
+#ifdef HAVE_GETPPID\r
+    {"getppid",         posix_getppid, METH_NOARGS, posix_getppid__doc__},\r
+#endif /* HAVE_GETPPID */\r
+#ifdef HAVE_GETUID\r
+    {"getuid",          posix_getuid, METH_NOARGS, posix_getuid__doc__},\r
+#endif /* HAVE_GETUID */\r
+#ifdef HAVE_GETLOGIN\r
+    {"getlogin",        posix_getlogin, METH_NOARGS, posix_getlogin__doc__},\r
+#endif\r
+#ifdef HAVE_KILL\r
+    {"kill",            posix_kill, METH_VARARGS, posix_kill__doc__},\r
+#endif /* HAVE_KILL */\r
+#ifdef HAVE_KILLPG\r
+    {"killpg",          posix_killpg, METH_VARARGS, posix_killpg__doc__},\r
+#endif /* HAVE_KILLPG */\r
+#ifdef HAVE_PLOCK\r
+    {"plock",           posix_plock, METH_VARARGS, posix_plock__doc__},\r
+#endif /* HAVE_PLOCK */\r
+#ifdef HAVE_POPEN\r
+    {"popen",           posix_popen, METH_VARARGS, posix_popen__doc__},\r
+#ifdef MS_WINDOWS\r
+    {"popen2",          win32_popen2, METH_VARARGS},\r
+    {"popen3",          win32_popen3, METH_VARARGS},\r
+    {"popen4",          win32_popen4, METH_VARARGS},\r
+    {"startfile",       win32_startfile, METH_VARARGS, win32_startfile__doc__},\r
+    {"kill",    win32_kill, METH_VARARGS, win32_kill__doc__},\r
+#else\r
+#if defined(PYOS_OS2) && defined(PYCC_GCC)\r
+    {"popen2",          os2emx_popen2, METH_VARARGS},\r
+    {"popen3",          os2emx_popen3, METH_VARARGS},\r
+    {"popen4",          os2emx_popen4, METH_VARARGS},\r
+#endif\r
+#endif\r
+#endif /* HAVE_POPEN */\r
+#ifdef HAVE_SETUID\r
+    {"setuid",          posix_setuid, METH_VARARGS, posix_setuid__doc__},\r
+#endif /* HAVE_SETUID */\r
+#ifdef HAVE_SETEUID\r
+    {"seteuid",         posix_seteuid, METH_VARARGS, posix_seteuid__doc__},\r
+#endif /* HAVE_SETEUID */\r
+#ifdef HAVE_SETEGID\r
+    {"setegid",         posix_setegid, METH_VARARGS, posix_setegid__doc__},\r
+#endif /* HAVE_SETEGID */\r
+#ifdef HAVE_SETREUID\r
+    {"setreuid",        posix_setreuid, METH_VARARGS, posix_setreuid__doc__},\r
+#endif /* HAVE_SETREUID */\r
+#ifdef HAVE_SETREGID\r
+    {"setregid",        posix_setregid, METH_VARARGS, posix_setregid__doc__},\r
+#endif /* HAVE_SETREGID */\r
+#ifdef HAVE_SETGID\r
+    {"setgid",          posix_setgid, METH_VARARGS, posix_setgid__doc__},\r
+#endif /* HAVE_SETGID */\r
+#ifdef HAVE_SETGROUPS\r
+    {"setgroups",       posix_setgroups, METH_O, posix_setgroups__doc__},\r
+#endif /* HAVE_SETGROUPS */\r
+#ifdef HAVE_INITGROUPS\r
+    {"initgroups",      posix_initgroups, METH_VARARGS, posix_initgroups__doc__},\r
+#endif /* HAVE_INITGROUPS */\r
+#ifdef HAVE_GETPGID\r
+    {"getpgid",         posix_getpgid, METH_VARARGS, posix_getpgid__doc__},\r
+#endif /* HAVE_GETPGID */\r
+#ifdef HAVE_SETPGRP\r
+    {"setpgrp",         posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__},\r
+#endif /* HAVE_SETPGRP */\r
+#ifdef HAVE_WAIT\r
+    {"wait",            posix_wait, METH_NOARGS, posix_wait__doc__},\r
+#endif /* HAVE_WAIT */\r
+#ifdef HAVE_WAIT3\r
+    {"wait3",           posix_wait3, METH_VARARGS, posix_wait3__doc__},\r
+#endif /* HAVE_WAIT3 */\r
+#ifdef HAVE_WAIT4\r
+    {"wait4",           posix_wait4, METH_VARARGS, posix_wait4__doc__},\r
+#endif /* HAVE_WAIT4 */\r
+#if defined(HAVE_WAITPID) || defined(HAVE_CWAIT)\r
+    {"waitpid",         posix_waitpid, METH_VARARGS, posix_waitpid__doc__},\r
+#endif /* HAVE_WAITPID */\r
+#ifdef HAVE_GETSID\r
+    {"getsid",          posix_getsid, METH_VARARGS, posix_getsid__doc__},\r
+#endif /* HAVE_GETSID */\r
+#ifdef HAVE_SETSID\r
+    {"setsid",          posix_setsid, METH_NOARGS, posix_setsid__doc__},\r
+#endif /* HAVE_SETSID */\r
+#ifdef HAVE_SETPGID\r
+    {"setpgid",         posix_setpgid, METH_VARARGS, posix_setpgid__doc__},\r
+#endif /* HAVE_SETPGID */\r
+#ifdef HAVE_TCGETPGRP\r
+    {"tcgetpgrp",       posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__},\r
+#endif /* HAVE_TCGETPGRP */\r
+#ifdef HAVE_TCSETPGRP\r
+    {"tcsetpgrp",       posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__},\r
+#endif /* HAVE_TCSETPGRP */\r
+    {"open",            posix_open,       METH_VARARGS, posix_open__doc__},\r
+    {"close",           posix_close,      METH_VARARGS, posix_close__doc__},\r
+    {"closerange",      posix_closerange, METH_VARARGS, posix_closerange__doc__},\r
+    {"dup",             posix_dup,        METH_VARARGS, posix_dup__doc__},\r
+    {"dup2",            posix_dup2,       METH_VARARGS, posix_dup2__doc__},\r
+    {"lseek",           posix_lseek,      METH_VARARGS, posix_lseek__doc__},\r
+    {"read",            posix_read,       METH_VARARGS, posix_read__doc__},\r
+    {"write",           posix_write,      METH_VARARGS, posix_write__doc__},\r
+    {"fstat",           posix_fstat,      METH_VARARGS, posix_fstat__doc__},\r
+    {"fdopen",          posix_fdopen,     METH_VARARGS, posix_fdopen__doc__},\r
+    {"isatty",          posix_isatty,     METH_VARARGS, posix_isatty__doc__},\r
+#ifdef HAVE_PIPE\r
+    {"pipe",            posix_pipe, METH_NOARGS, posix_pipe__doc__},\r
+#endif\r
+#ifdef HAVE_MKFIFO\r
+    {"mkfifo",          posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__},\r
+#endif\r
+#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)\r
+    {"mknod",           posix_mknod, METH_VARARGS, posix_mknod__doc__},\r
+#endif\r
+#ifdef HAVE_DEVICE_MACROS\r
+    {"major",           posix_major, METH_VARARGS, posix_major__doc__},\r
+    {"minor",           posix_minor, METH_VARARGS, posix_minor__doc__},\r
+    {"makedev",         posix_makedev, METH_VARARGS, posix_makedev__doc__},\r
+#endif\r
+#ifdef HAVE_FTRUNCATE\r
+    {"ftruncate",       posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__},\r
+#endif\r
+#ifdef HAVE_PUTENV\r
+    {"putenv",          posix_putenv, METH_VARARGS, posix_putenv__doc__},\r
+#endif\r
+#ifdef HAVE_UNSETENV\r
+    {"unsetenv",        posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__},\r
+#endif\r
+    {"strerror",        posix_strerror,   METH_VARARGS, posix_strerror__doc__},\r
+#ifdef HAVE_FCHDIR\r
+    {"fchdir",          posix_fchdir, METH_O, posix_fchdir__doc__},\r
+#endif\r
+#ifdef HAVE_FSYNC\r
+    {"fsync",       posix_fsync, METH_O, posix_fsync__doc__},\r
+#endif\r
+#ifdef HAVE_FDATASYNC\r
+    {"fdatasync",   posix_fdatasync,  METH_O, posix_fdatasync__doc__},\r
+#endif\r
+#ifdef HAVE_SYS_WAIT_H\r
+#ifdef WCOREDUMP\r
+    {"WCOREDUMP",       posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__},\r
+#endif /* WCOREDUMP */\r
+#ifdef WIFCONTINUED\r
+    {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__},\r
+#endif /* WIFCONTINUED */\r
+#ifdef WIFSTOPPED\r
+    {"WIFSTOPPED",      posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__},\r
+#endif /* WIFSTOPPED */\r
+#ifdef WIFSIGNALED\r
+    {"WIFSIGNALED",     posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__},\r
+#endif /* WIFSIGNALED */\r
+#ifdef WIFEXITED\r
+    {"WIFEXITED",       posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__},\r
+#endif /* WIFEXITED */\r
+#ifdef WEXITSTATUS\r
+    {"WEXITSTATUS",     posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__},\r
+#endif /* WEXITSTATUS */\r
+#ifdef WTERMSIG\r
+    {"WTERMSIG",        posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__},\r
+#endif /* WTERMSIG */\r
+#ifdef WSTOPSIG\r
+    {"WSTOPSIG",        posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__},\r
+#endif /* WSTOPSIG */\r
+#endif /* HAVE_SYS_WAIT_H */\r
+#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)\r
+    {"fstatvfs",        posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__},\r
+#endif\r
+#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)\r
+    {"statvfs",         posix_statvfs, METH_VARARGS, posix_statvfs__doc__},\r
+#endif\r
+#ifdef HAVE_TMPFILE\r
+    {"tmpfile",         posix_tmpfile,    METH_NOARGS,  posix_tmpfile__doc__},\r
+#endif\r
+#ifdef HAVE_TEMPNAM\r
+    {"tempnam",         posix_tempnam,    METH_VARARGS, posix_tempnam__doc__},\r
+#endif\r
+#ifdef HAVE_TMPNAM\r
+    {"tmpnam",          posix_tmpnam,     METH_NOARGS,  posix_tmpnam__doc__},\r
+#endif\r
+#ifdef HAVE_CONFSTR\r
+    {"confstr",         posix_confstr, METH_VARARGS, posix_confstr__doc__},\r
+#endif\r
+#ifdef HAVE_SYSCONF\r
+    {"sysconf",         posix_sysconf, METH_VARARGS, posix_sysconf__doc__},\r
+#endif\r
+#ifdef HAVE_FPATHCONF\r
+    {"fpathconf",       posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__},\r
+#endif\r
+#ifdef HAVE_PATHCONF\r
+    {"pathconf",        posix_pathconf, METH_VARARGS, posix_pathconf__doc__},\r
+#endif\r
+    {"abort",           posix_abort,      METH_NOARGS,  posix_abort__doc__},\r
+#ifdef HAVE_SETRESUID\r
+    {"setresuid",       posix_setresuid, METH_VARARGS, posix_setresuid__doc__},\r
+#endif\r
+#ifdef HAVE_SETRESGID\r
+    {"setresgid",       posix_setresgid, METH_VARARGS, posix_setresgid__doc__},\r
+#endif\r
+#ifdef HAVE_GETRESUID\r
+    {"getresuid",       posix_getresuid, METH_NOARGS, posix_getresuid__doc__},\r
+#endif\r
+#ifdef HAVE_GETRESGID\r
+    {"getresgid",       posix_getresgid, METH_NOARGS, posix_getresgid__doc__},\r
+#endif\r
+\r
+    {NULL,              NULL}            /* Sentinel */\r
+};\r
+\r
+\r
+static int\r
+ins(PyObject *module, char *symbol, long value)\r
+{\r
+    return PyModule_AddIntConstant(module, symbol, value);\r
+}\r
+\r
+static int\r
+all_ins(PyObject *d)\r
+{\r
+#ifdef F_OK\r
+    if (ins(d, "F_OK", (long)F_OK)) return -1;\r
+#endif\r
+#ifdef R_OK\r
+    if (ins(d, "R_OK", (long)R_OK)) return -1;\r
+#endif\r
+#ifdef W_OK\r
+    if (ins(d, "W_OK", (long)W_OK)) return -1;\r
+#endif\r
+#ifdef X_OK\r
+    if (ins(d, "X_OK", (long)X_OK)) return -1;\r
+#endif\r
+#ifdef NGROUPS_MAX\r
+    if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1;\r
+#endif\r
+#ifdef TMP_MAX\r
+    if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1;\r
+#endif\r
+#ifdef WCONTINUED\r
+    if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1;\r
+#endif\r
+#ifdef WNOHANG\r
+    if (ins(d, "WNOHANG", (long)WNOHANG)) return -1;\r
+#endif\r
+#ifdef WUNTRACED\r
+    if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1;\r
+#endif\r
+#ifdef O_RDONLY\r
+    if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1;\r
+#endif\r
+#ifdef O_WRONLY\r
+    if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1;\r
+#endif\r
+#ifdef O_RDWR\r
+    if (ins(d, "O_RDWR", (long)O_RDWR)) return -1;\r
+#endif\r
+#ifdef O_NDELAY\r
+    if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1;\r
+#endif\r
+#ifdef O_NONBLOCK\r
+    if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1;\r
+#endif\r
+#ifdef O_APPEND\r
+    if (ins(d, "O_APPEND", (long)O_APPEND)) return -1;\r
+#endif\r
+#ifdef O_DSYNC\r
+    if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1;\r
+#endif\r
+#ifdef O_RSYNC\r
+    if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1;\r
+#endif\r
+#ifdef O_SYNC\r
+    if (ins(d, "O_SYNC", (long)O_SYNC)) return -1;\r
+#endif\r
+#ifdef O_NOCTTY\r
+    if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1;\r
+#endif\r
+#ifdef O_CREAT\r
+    if (ins(d, "O_CREAT", (long)O_CREAT)) return -1;\r
+#endif\r
+#ifdef O_EXCL\r
+    if (ins(d, "O_EXCL", (long)O_EXCL)) return -1;\r
+#endif\r
+#ifdef O_TRUNC\r
+    if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1;\r
+#endif\r
+#ifdef O_BINARY\r
+    if (ins(d, "O_BINARY", (long)O_BINARY)) return -1;\r
+#endif\r
+#ifdef O_TEXT\r
+    if (ins(d, "O_TEXT", (long)O_TEXT)) return -1;\r
+#endif\r
+#ifdef O_LARGEFILE\r
+    if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1;\r
+#endif\r
+#ifdef O_SHLOCK\r
+    if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1;\r
+#endif\r
+#ifdef O_EXLOCK\r
+    if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1;\r
+#endif\r
+\r
+/* MS Windows */\r
+#ifdef O_NOINHERIT\r
+    /* Don't inherit in child processes. */\r
+    if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1;\r
+#endif\r
+#ifdef _O_SHORT_LIVED\r
+    /* Optimize for short life (keep in memory). */\r
+    /* MS forgot to define this one with a non-underscore form too. */\r
+    if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1;\r
+#endif\r
+#ifdef O_TEMPORARY\r
+    /* Automatically delete when last handle is closed. */\r
+    if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1;\r
+#endif\r
+#ifdef O_RANDOM\r
+    /* Optimize for random access. */\r
+    if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1;\r
+#endif\r
+#ifdef O_SEQUENTIAL\r
+    /* Optimize for sequential access. */\r
+    if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1;\r
+#endif\r
+\r
+/* GNU extensions. */\r
+#ifdef O_ASYNC\r
+    /* Send a SIGIO signal whenever input or output\r
+       becomes available on file descriptor */\r
+    if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1;\r
+#endif\r
+#ifdef O_DIRECT\r
+    /* Direct disk access. */\r
+    if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1;\r
+#endif\r
+#ifdef O_DIRECTORY\r
+    /* Must be a directory.      */\r
+    if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1;\r
+#endif\r
+#ifdef O_NOFOLLOW\r
+    /* Do not follow links.      */\r
+    if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1;\r
+#endif\r
+#ifdef O_NOATIME\r
+    /* Do not update the access time. */\r
+    if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1;\r
+#endif\r
+\r
+    /* These come from sysexits.h */\r
+#ifdef EX_OK\r
+    if (ins(d, "EX_OK", (long)EX_OK)) return -1;\r
+#endif /* EX_OK */\r
+#ifdef EX_USAGE\r
+    if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1;\r
+#endif /* EX_USAGE */\r
+#ifdef EX_DATAERR\r
+    if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1;\r
+#endif /* EX_DATAERR */\r
+#ifdef EX_NOINPUT\r
+    if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1;\r
+#endif /* EX_NOINPUT */\r
+#ifdef EX_NOUSER\r
+    if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1;\r
+#endif /* EX_NOUSER */\r
+#ifdef EX_NOHOST\r
+    if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1;\r
+#endif /* EX_NOHOST */\r
+#ifdef EX_UNAVAILABLE\r
+    if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1;\r
+#endif /* EX_UNAVAILABLE */\r
+#ifdef EX_SOFTWARE\r
+    if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1;\r
+#endif /* EX_SOFTWARE */\r
+#ifdef EX_OSERR\r
+    if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1;\r
+#endif /* EX_OSERR */\r
+#ifdef EX_OSFILE\r
+    if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1;\r
+#endif /* EX_OSFILE */\r
+#ifdef EX_CANTCREAT\r
+    if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1;\r
+#endif /* EX_CANTCREAT */\r
+#ifdef EX_IOERR\r
+    if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1;\r
+#endif /* EX_IOERR */\r
+#ifdef EX_TEMPFAIL\r
+    if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1;\r
+#endif /* EX_TEMPFAIL */\r
+#ifdef EX_PROTOCOL\r
+    if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1;\r
+#endif /* EX_PROTOCOL */\r
+#ifdef EX_NOPERM\r
+    if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1;\r
+#endif /* EX_NOPERM */\r
+#ifdef EX_CONFIG\r
+    if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1;\r
+#endif /* EX_CONFIG */\r
+#ifdef EX_NOTFOUND\r
+    if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1;\r
+#endif /* EX_NOTFOUND */\r
+\r
+#ifdef HAVE_SPAWNV\r
+#if defined(PYOS_OS2) && defined(PYCC_GCC)\r
+    if (ins(d, "P_WAIT", (long)P_WAIT)) return -1;\r
+    if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1;\r
+    if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1;\r
+    if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1;\r
+    if (ins(d, "P_SESSION", (long)P_SESSION)) return -1;\r
+    if (ins(d, "P_DETACH", (long)P_DETACH)) return -1;\r
+    if (ins(d, "P_PM", (long)P_PM)) return -1;\r
+    if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1;\r
+    if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1;\r
+    if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1;\r
+    if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1;\r
+    if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1;\r
+    if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1;\r
+    if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1;\r
+    if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1;\r
+    if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1;\r
+    if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1;\r
+    if (ins(d, "P_TILDE", (long)P_TILDE)) return -1;\r
+    if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1;\r
+    if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1;\r
+#else\r
+    if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1;\r
+    if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1;\r
+    if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1;\r
+    if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1;\r
+    if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1;\r
+#endif\r
+#endif\r
+  return 0;\r
+}\r
+\r
+#define INITFUNC initedk2\r
+#define MODNAME "edk2"\r
+\r
+PyMODINIT_FUNC\r
+INITFUNC(void)\r
+{\r
+    PyObject *m, *v;\r
+\r
+    m = Py_InitModule3(MODNAME,\r
+                       posix_methods,\r
+                       posix__doc__);\r
+    if (m == NULL)\r
+        return;\r
+\r
+#ifndef UEFI_ENV\r
+    /* Initialize environ dictionary */\r
+    v = convertenviron();\r
+    Py_XINCREF(v);\r
+    if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)\r
+        return;\r
+    Py_DECREF(v);\r
+#endif  /* UEFI_ENV */\r
+\r
+    if (all_ins(m))\r
+        return;\r
+\r
+    if (setup_confname_tables(m))\r
+        return;\r
+\r
+    Py_INCREF(PyExc_OSError);\r
+    PyModule_AddObject(m, "error", PyExc_OSError);\r
+\r
+#ifdef HAVE_PUTENV\r
+    if (posix_putenv_garbage == NULL)\r
+        posix_putenv_garbage = PyDict_New();\r
+#endif\r
+\r
+    if (!initialized) {\r
+        stat_result_desc.name = MODNAME ".stat_result";\r
+        stat_result_desc.fields[2].name = PyStructSequence_UnnamedField;\r
+        stat_result_desc.fields[3].name = PyStructSequence_UnnamedField;\r
+        stat_result_desc.fields[4].name = PyStructSequence_UnnamedField;\r
+        PyStructSequence_InitType(&StatResultType, &stat_result_desc);\r
+        structseq_new = StatResultType.tp_new;\r
+        StatResultType.tp_new = statresult_new;\r
+\r
+        //statvfs_result_desc.name = MODNAME ".statvfs_result";\r
+        //PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc);\r
+#ifdef NEED_TICKS_PER_SECOND\r
+#  if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)\r
+        ticks_per_second = sysconf(_SC_CLK_TCK);\r
+#  elif defined(HZ)\r
+        ticks_per_second = HZ;\r
+#  else\r
+        ticks_per_second = 60; /* magic fallback value; may be bogus */\r
+#  endif\r
+#endif\r
+    }\r
+    Py_INCREF((PyObject*) &StatResultType);\r
+    PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);\r
+    //Py_INCREF((PyObject*) &StatVFSResultType);\r
+    //PyModule_AddObject(m, "statvfs_result",\r
+    //                   (PyObject*) &StatVFSResultType);\r
+    initialized = 1;\r
+\r
+}\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+\r
index ba837bf52219e16d4b566b2ca03d1efde4ee0a23..5a8c52002715129a467652bcf488eb98c733a6f3 100644 (file)
@@ -32,6 +32,7 @@
 **/\r
 #include <Python.h>\r
 #include <osdefs.h>\r
+#include  <ctype.h>\r
 \r
 #ifdef __cplusplus\r
  extern "C" {\r
@@ -126,15 +127,12 @@ isfile(char *filename)
 {\r
     struct stat buf;\r
     if (stat(filename, &buf) != 0) {\r
-      //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d] Not Found: file = \"%s\"\n", __func__, __LINE__, filename);\r
       return 0;\r
     }\r
     //if (!S_ISREG(buf.st_mode))\r
     if (S_ISDIR(buf.st_mode)) {\r
-      //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d] Is DIR: file = \"%s\"\n", __func__, __LINE__, filename);\r
       return 0;\r
     }\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d] SUCCESS: file = \"%s\"\n", __func__, __LINE__, filename);\r
     return 1;\r
 }\r
 \r
@@ -159,11 +157,9 @@ ismodule(char *filename)
     if (strlen(filename) < MAXPATHLEN) {\r
         strcat(filename, Py_OptimizeFlag ? "o" : "c");\r
         if (isfile(filename)) {\r
-          //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: file = \"%s\"\n", __func__, __LINE__, filename);\r
           return 1;\r
         }\r
     }\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d] FAIL: file = \"%s\"\n", __func__, __LINE__, filename);\r
     return 0;\r
 }\r
 \r
@@ -304,7 +300,6 @@ isxfile(char *filename)
     char        *newbn;\r
     int          bnlen;\r
 \r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d] ENTER: file = \"%s\"\n", __func__, __LINE__, filename);\r
     bn = basename(filename);            // Separate off the file name component\r
     reduce(filename);                   // and isolate the path component\r
     bnlen = strlen(bn);\r
@@ -315,22 +310,17 @@ isxfile(char *filename)
       bnlen += 4;\r
     }\r
     else if(strcmp(newbn, ".efi") != 0) {\r
-      //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: Bad extension\n", __func__, __LINE__);\r
       return 0;                         // File can not be executable.\r
     }\r
     joinpath(filename, bn);             // Stitch path and file name back together\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: file = \"%s\"\n", __func__, __LINE__, filename);\r
 \r
     if (stat(filename, &buf) != 0) {    // Now, verify that file exists\r
-      //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: Does not exist\n", __func__, __LINE__);\r
       return 0;\r
     }\r
     if(S_ISDIR(buf.st_mode)) {          // And it is not a directory.\r
-      //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: Is a directory\n", __func__, __LINE__);\r
       return 0;\r
     }\r
 \r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d] EXIT: file = \"%s\"\n", __func__, __LINE__, filename);\r
     return 1;\r
 }\r
 \r
@@ -390,17 +380,12 @@ set_volume(char *Dest, char *path)
 {\r
   size_t    VolLen;\r
 \r
-  //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d] ENTER: path = \"%s\"\n", __func__, __LINE__, path);\r
   if(is_absolute(path)) {\r
     VolLen = strcspn(path, "/\\:");\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: VolLen = %d\n", __func__, __LINE__, VolLen);\r
     if((VolLen != 0) && (path[VolLen] == ':')) {\r
       (void) strncpyX(Dest, path, VolLen + 1);\r
-      //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: VolLen = %d, Dest = \"%s\" path = \"%s\"\n",\r
-      //                                      __func__, __LINE__, VolLen, Dest, path);\r
     }\r
   }\r
-  //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d] EXIT: Dest = \"%s\"\n", __func__, __LINE__, Dest);\r
 }\r
 \r
 \r
@@ -481,16 +466,10 @@ calculate_path(void)
     char *prog = Py_GetProgramName();\r
     char argv0_path[MAXPATHLEN+1];\r
     char zip_path[MAXPATHLEN+1];\r
-    //int pfound, efound; /* 1 if found; -1 if found build directory */\r
     char *buf;\r
     size_t bufsz;\r
     size_t prefixsz;\r
     char *defpath;\r
-    //uint32_t nsexeclength = MAXPATHLEN;\r
-\r
-    //unixify(path);\r
-    //unixify(rtpypath);\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]:\nENTER prog=\"%s\"\n      path=\"%s\"\n", __func__, __LINE__, prog, path);\r
 \r
 \r
 /* ###########################################################################\r
@@ -520,7 +499,6 @@ calculate_path(void)
                 strncpy(progpath, path, MAXPATHLEN);\r
 \r
         joinpath(progpath, prog);\r
-        //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: progpath = \"%s\"\n", __func__, __LINE__, progpath);\r
         if (isxfile(progpath))\r
                 break;\r
 \r
@@ -539,10 +517,7 @@ calculate_path(void)
     argv0_path[MAXPATHLEN] = '\0';\r
     set_volume(volume_name, argv0_path);\r
 \r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: volume_name = \"%s\"\n", __func__, __LINE__, volume_name);\r
     reduce(argv0_path);\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: progpath = \"%s\"\n", __func__, __LINE__, progpath);\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: argv0_path = \"%s\"\n", __func__, __LINE__, argv0_path);\r
     /* At this point, argv0_path is guaranteed to be less than\r
        MAXPATHLEN bytes long.\r
     */\r
@@ -552,17 +527,9 @@ calculate_path(void)
       This is the full path to the platform independent libraries.\r
 ########################################################################### */\r
 \r
-    //if (!(pfound = search_for_prefix(argv0_path, home))) {\r
-    //    if (!Py_FrozenFlag)\r
-    //        fprintf(stderr,\r
-    //            "Could not find platform independent libraries <prefix>\n");\r
         strncpy(prefix, volume_name, MAXPATHLEN);\r
         joinpath(prefix, PREFIX);\r
         joinpath(prefix, lib_python);\r
-    //}\r
-    //else\r
-    //    reduce(prefix);\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: V = \"%s\", Prefix = \"%s\"\n", __func__, __LINE__, volume_name, prefix);\r
 \r
 /* ###########################################################################\r
       Build the FULL path to the zipped-up Python library.\r
@@ -570,37 +537,20 @@ calculate_path(void)
 \r
     strncpy(zip_path, prefix, MAXPATHLEN);\r
     zip_path[MAXPATHLEN] = '\0';\r
-    //if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */\r
-        reduce(zip_path);\r
-        //reduce(zip_path);\r
-    //}\r
-    //else\r
-    //    strncpy(zip_path, PREFIX, MAXPATHLEN);\r
+    reduce(zip_path);\r
     joinpath(zip_path, "python00.zip");\r
     bufsz = strlen(zip_path);   /* Replace "00" with version */\r
     zip_path[bufsz - 6] = VERSION[0];\r
     zip_path[bufsz - 5] = VERSION[1];\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: Zip_path = \"%s\"\n", __func__, __LINE__, zip_path);\r
 \r
 /* ###########################################################################\r
       Build the FULL path to dynamically loadable libraries.\r
 ########################################################################### */\r
 \r
-    //if (!(efound = search_for_exec_prefix(argv0_path, home))) {\r
-    //    if (!Py_FrozenFlag)\r
-    //        fprintf(stderr,\r
-    //            "Could not find platform dependent libraries <exec_prefix>\n");\r
         strncpy(exec_prefix, volume_name, MAXPATHLEN);\r
         joinpath(exec_prefix, EXEC_PREFIX);\r
         joinpath(exec_prefix, lib_python);\r
-        joinpath(exec_prefix, "dynaload");\r
-    //}\r
-    /* If we found EXEC_PREFIX do *not* reduce it!  (Yet.) */\r
-    //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: Exec_prefix = \"%s\"\n", __func__, __LINE__, exec_prefix);\r
-\r
-    //if ((!pfound || !efound) && !Py_FrozenFlag)\r
-    //    fprintf(stderr,\r
-    //            "Consider setting $PYTHONHOME to <prefix>[%c<exec_prefix>]\n", DELIM);\r
+        joinpath(exec_prefix, "lib-dynload");\r
 \r
 /* ###########################################################################\r
       Build the module search path.\r
@@ -611,7 +561,6 @@ calculate_path(void)
      * If we're loading relative to the build directory,\r
      * return the compiled-in defaults instead.\r
      */\r
-    //if (pfound > 0) {\r
     reduce(prefix);\r
     reduce(prefix);\r
     /* The prefix is the root directory, but reduce() chopped\r
@@ -624,11 +573,6 @@ calculate_path(void)
       prefix[bufsz] = SEP;\r
       prefix[bufsz+1] = 0;\r
     }\r
-    //}\r
-    //else\r
-    //    strncpy(prefix, PREFIX, MAXPATHLEN);\r
-\r
-//if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: prefix = \"%s\"\n", __func__, __LINE__, prefix);\r
 \r
     /* Calculate size of return buffer.\r
      */\r
@@ -655,7 +599,6 @@ calculate_path(void)
         }\r
         defpath = delim + 1;\r
     }\r
-//if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: defpath = \"%s\"\n", __func__, __LINE__, defpath);\r
 \r
     bufsz += strlen(zip_path) + 1;\r
     bufsz += strlen(exec_prefix) + 1;\r
@@ -670,7 +613,6 @@ calculate_path(void)
         module_search_path = PYTHONPATH;\r
     }\r
     else {\r
-      //if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]:\n", __func__, __LINE__);\r
         /* Run-time value of $PYTHONPATH goes first */\r
         if (rtpypath) {\r
             strcpy(buf, rtpypath);\r
@@ -678,12 +620,10 @@ calculate_path(void)
         }\r
         else\r
             buf[0] = '\0';\r
-//if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: RTpath = \"%s\"\n", __func__, __LINE__, buf);\r
 \r
         /* Next is the default zip path */\r
         strcat(buf, zip_path);\r
         strcat(buf, delimiter);\r
-//if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: +Zip = \"%s\"\n", __func__, __LINE__, buf);\r
 \r
         /* Next goes merge of compile-time $PYTHONPATH with\r
          * dynamically located prefix.\r
@@ -710,17 +650,13 @@ calculate_path(void)
             defpath = delim + 1;\r
         }\r
         strcat(buf, delimiter);\r
-//if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: +Merge = \"%s\"\n", __func__, __LINE__, buf);\r
 \r
         /* Finally, on goes the directory for dynamic-load modules */\r
         strcat(buf, exec_prefix);\r
 \r
         /* And publish the results */\r
         module_search_path = buf;\r
-//if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: module_search_path = \"%s\"\n", __func__, __LINE__, module_search_path);\r
     }\r
-\r
-    //if (efound > 0) {\r
         /*  At this point, exec_prefix is set to VOL:/Efi/StdLib/lib/python.27/dynalib.\r
             We want to get back to the root value, so we have to remove the final three\r
             segments to get VOL:/Efi/StdLib.  Because we don't know what VOL is, and\r
@@ -737,9 +673,6 @@ calculate_path(void)
           exec_prefix[bufsz] = SEP;\r
           exec_prefix[bufsz+1] = 0;\r
         }\r
-    //}\r
-    //else\r
-    //    strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN);\r
     if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: module_search_path = \"%s\"\n", __func__, __LINE__, module_search_path);\r
     if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: prefix             = \"%s\"\n", __func__, __LINE__, prefix);\r
     if (Py_VerboseFlag) PySys_WriteStderr("%s[%d]: exec_prefix        = \"%s\"\n", __func__, __LINE__, exec_prefix);\r
index 866c0f0b13d05a7033a6c62bec248e88e6860bc7..6b05e4e161d51c0a24aeda481b14a9f078945bf2 100644 (file)
     THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
     WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
 **/\r
-\r
-\r
 #ifndef Py_PYCONFIG_H\r
 #define Py_PYCONFIG_H\r
 \r
-#define PLATFORM    "UEFI 2.3 Ia32"\r
+#include  <Uefi.h>\r
+\r
+/* Define to indicate that code is being built to run in the UEFI Environment. */\r
+#define UEFI_ENV    EFI_SYSTEM_TABLE_REVISION\r
 \r
-//#ifndef PYTHONPATH\r
-//# define PYTHONPATH "/Efi/StdLib/lib/python.27;/Efi/StdLib/lib/python.27/lib-dynload"\r
-//#endif\r
+#define PLATFORM    "UEFI"\r
 \r
 /* Define if building universal (internal helper macro) */\r
 #undef AC_APPLE_UNIVERSAL_BUILD\r
 \r
 /* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.\r
    */\r
-#undef HAVE_DIRENT_H\r
+#define HAVE_DIRENT_H   1\r
 \r
 /* Define to 1 if you have the <dlfcn.h> header file. */\r
 #undef HAVE_DLFCN_H\r
 #undef HAVE_GETPAGESIZE\r
 \r
 /* Define to 1 if you have the `getpeername' function. */\r
-#undef HAVE_GETPEERNAME\r
+#define HAVE_GETPEERNAME  1\r
 \r
 /* Define to 1 if you have the `getpgid' function. */\r
 #undef HAVE_GETPGID\r
 #undef HAVE_PLOCK\r
 \r
 /* Define to 1 if you have the `poll' function. */\r
-#undef HAVE_POLL\r
+#define HAVE_POLL         1\r
 \r
 /* Define to 1 if you have the <poll.h> header file. */\r
-#define HAVE_POLL_H     1\r
+#undef HAVE_POLL_H\r
 \r
 /* Define to 1 if you have the <process.h> header file. */\r
 #undef HAVE_PROCESS_H\r
 #undef HAVE_READLINK\r
 \r
 /* Define to 1 if you have the `realpath' function. */\r
-#undef HAVE_REALPATH\r
+#define HAVE_REALPATH   1\r
 \r
 /* Define if you have readline 2.1 */\r
 #undef HAVE_RL_CALLBACK\r
 #undef HAVE_ROUND\r
 \r
 /* Define to 1 if you have the `select' function. */\r
-#undef HAVE_SELECT\r
+#define HAVE_SELECT       1\r
 \r
 /* Define to 1 if you have the `sem_getvalue' function. */\r
 #undef HAVE_SEM_GETVALUE\r
 #define HAVE_TEMPNAM                    1\r
 \r
 /* Define to 1 if you have the <termios.h> header file. */\r
-#define HAVE_TERMIOS_H                  1\r
+#undef HAVE_TERMIOS_H\r
 \r
 /* Define to 1 if you have the <term.h> header file. */\r
 #undef HAVE_TERM_H\r
 #undef HAVE_UTIMES\r
 \r
 /* Define to 1 if you have the <utime.h> header file. */\r
-#undef HAVE_UTIME_H\r
+#define HAVE_UTIME_H    1\r
 \r
 /* Define to 1 if you have the `wait3' function. */\r
 #undef HAVE_WAIT3\r
index cad7132c8c2a1a5813b4d65116e8fdd0a6b25a07..3d8d03bd22dd33425ca3c3e2bf84df55b6314ef6 100644 (file)
@@ -1,9 +1,24 @@
-/* pyconfig.h.in.  Generated from configure.in by autoheader.  */\r
-\r
-\r
+/** @file\r
+    Manually generated Python Configuration file for EDK II.\r
+\r
+    Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>\r
+    This program and the accompanying materials are licensed and made available under\r
+    the terms and conditions of the BSD License that accompanies this distribution.\r
+    The full text of the license may be found at\r
+    http://opensource.org/licenses/bsd-license.\r
+\r
+    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+**/\r
 #ifndef Py_PYCONFIG_H\r
 #define Py_PYCONFIG_H\r
 \r
+#include  <Uefi.h>\r
+\r
+/* Define to indicate that code is being built to run in the UEFI Environment. */\r
+#define UEFI_ENV    EFI_SYSTEM_TABLE_REVISION\r
+\r
+#define PLATFORM    "UEFI"\r
 \r
 /* Define if building universal (internal helper macro) */\r
 #undef AC_APPLE_UNIVERSAL_BUILD\r
 #undef HAVE_BROKEN_POLL\r
 \r
 /* Define if the Posix semaphores do not work on your system */\r
-#define HAVE_BROKEN_POSIX_SEMAPHORES\r
+#define HAVE_BROKEN_POSIX_SEMAPHORES  1\r
 \r
 /* Define if pthread_sigmask() does not work on your system. */\r
-#define HAVE_BROKEN_PTHREAD_SIGMASK\r
+#define HAVE_BROKEN_PTHREAD_SIGMASK   1\r
 \r
 /* define to 1 if your sem_getvalue is broken. */\r
-#undef HAVE_BROKEN_SEM_GETVALUE\r
+#define HAVE_BROKEN_SEM_GETVALUE      1\r
 \r
 /* Define this if you have the type _Bool. */\r
-#define HAVE_C99_BOOL\r
+#define HAVE_C99_BOOL                 1\r
 \r
 /* Define to 1 if you have the `chflags' function. */\r
 #undef HAVE_CHFLAGS\r
 #undef HAVE_CHROOT\r
 \r
 /* Define to 1 if you have the `clock' function. */\r
-#define HAVE_CLOCK\r
+#define HAVE_CLOCK                    1\r
 \r
 /* Define to 1 if you have the `confstr' function. */\r
 #undef HAVE_CONFSTR\r
 #undef HAVE_CONIO_H\r
 \r
 /* Define to 1 if you have the `copysign' function. */\r
-#define HAVE_COPYSIGN   1\r
+#undef HAVE_COPYSIGN\r
 \r
 /* Define to 1 if you have the `ctermid' function. */\r
 #undef HAVE_CTERMID\r
 \r
 /* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.\r
    */\r
-#undef HAVE_DIRENT_H\r
+#define HAVE_DIRENT_H   1\r
 \r
 /* Define to 1 if you have the <dlfcn.h> header file. */\r
 #undef HAVE_DLFCN_H\r
 #undef HAVE_GETADDRINFO\r
 \r
 /* Define to 1 if you have the `getcwd' function. */\r
-#undef HAVE_GETCWD\r
+#define HAVE_GETCWD   1\r
 \r
 /* Define this if you have flockfile(), getc_unlocked(), and funlockfile() */\r
-#define HAVE_GETC_UNLOCKED\r
+#undef HAVE_GETC_UNLOCKED\r
 \r
 /* Define to 1 if you have the `getgroups' function. */\r
 #undef HAVE_GETGROUPS\r
 #undef HAVE_GETPAGESIZE\r
 \r
 /* Define to 1 if you have the `getpeername' function. */\r
-#undef HAVE_GETPEERNAME\r
+#define HAVE_GETPEERNAME  1\r
 \r
 /* Define to 1 if you have the `getpgid' function. */\r
 #undef HAVE_GETPGID\r
 #undef HAVE_IEEEFP_H\r
 \r
 /* Define if you have the 'inet_aton' function. */\r
-#undef HAVE_INET_ATON\r
+#define HAVE_INET_ATON    1\r
 \r
 /* Define if you have the 'inet_pton' function. */\r
-#undef HAVE_INET_PTON\r
+#define HAVE_INET_PTON    1\r
 \r
 /* Define to 1 if you have the `initgroups' function. */\r
 #undef HAVE_INITGROUPS\r
 #undef HAVE_KQUEUE\r
 \r
 /* Define to 1 if you have the <langinfo.h> header file. */\r
-#define HAVE_LANGINFO_H   1\r
+#undef HAVE_LANGINFO_H   /* non-functional in EFI. */\r
 \r
 /* Defined to enable large file support when an off_t is bigger than a long\r
    and long long is available and at least as big as an off_t. You may need to\r
 #undef HAVE_LOG1P\r
 \r
 /* Define this if you have the type long double. */\r
-#define HAVE_LONG_DOUBLE\r
+#undef HAVE_LONG_DOUBLE\r
 \r
 /* Define this if you have the type long long. */\r
-#define HAVE_LONG_LONG\r
+#define HAVE_LONG_LONG  1\r
 \r
 /* Define to 1 if you have the `lstat' function. */\r
 #define HAVE_LSTAT      1\r
 #undef HAVE_PLOCK\r
 \r
 /* Define to 1 if you have the `poll' function. */\r
-#undef HAVE_POLL\r
+#define HAVE_POLL         1\r
 \r
 /* Define to 1 if you have the <poll.h> header file. */\r
 #undef HAVE_POLL_H\r
 #undef HAVE_PROCESS_H\r
 \r
 /* Define if your compiler supports function prototype */\r
-#define HAVE_PROTOTYPES\r
+#define HAVE_PROTOTYPES   1\r
 \r
 /* Define if you have GNU PTH threads. */\r
 #undef HAVE_PTH\r
 #undef HAVE_READLINK\r
 \r
 /* Define to 1 if you have the `realpath' function. */\r
-#undef HAVE_REALPATH\r
+#define HAVE_REALPATH   1\r
 \r
 /* Define if you have readline 2.1 */\r
 #undef HAVE_RL_CALLBACK\r
 #undef HAVE_ROUND\r
 \r
 /* Define to 1 if you have the `select' function. */\r
-#undef HAVE_SELECT\r
+#define HAVE_SELECT       1\r
 \r
 /* Define to 1 if you have the `sem_getvalue' function. */\r
 #undef HAVE_SEM_GETVALUE\r
 #undef HAVE_SETUID\r
 \r
 /* Define to 1 if you have the `setvbuf' function. */\r
-#undef HAVE_SETVBUF\r
+#define HAVE_SETVBUF    1\r
 \r
 /* Define to 1 if you have the <shadow.h> header file. */\r
 #undef HAVE_SHADOW_H\r
 #undef HAVE_SPAWN_H\r
 \r
 /* Define if your compiler provides ssize_t */\r
-#undef HAVE_SSIZE_T\r
+#define HAVE_SSIZE_T    1\r
 \r
 /* Define to 1 if you have the `statvfs' function. */\r
 #undef HAVE_STATVFS\r
 \r
 /* Define if your compiler supports variable length function prototypes (e.g.\r
    void fprintf(FILE *, char *, ...);) *and* <stdarg.h> */\r
-#define HAVE_STDARG_PROTOTYPES\r
+#define HAVE_STDARG_PROTOTYPES          1\r
 \r
 /* Define to 1 if you have the <stdint.h> header file. */\r
 #define HAVE_STDINT_H   1\r
 #define HAVE_SYS_PARAM_H    1\r
 \r
 /* Define to 1 if you have the <sys/poll.h> header file. */\r
-#undef HAVE_SYS_POLL_H\r
+#define HAVE_SYS_POLL_H                 1\r
 \r
 /* Define to 1 if you have the <sys/resource.h> header file. */\r
 #define HAVE_SYS_RESOURCE_H   1\r
 \r
 /* Define to 1 if you have the <sys/select.h> header file. */\r
-#undef HAVE_SYS_SELECT_H\r
+#define HAVE_SYS_SELECT_H               1\r
 \r
 /* Define to 1 if you have the <sys/socket.h> header file. */\r
-#undef HAVE_SYS_SOCKET_H\r
+#define HAVE_SYS_SOCKET_H               1\r
 \r
 /* Define to 1 if you have the <sys/statvfs.h> header file. */\r
 #undef HAVE_SYS_STATVFS_H\r
 #define HAVE_TEMPNAM      1\r
 \r
 /* Define to 1 if you have the <termios.h> header file. */\r
-#define HAVE_TERMIOS_H    1\r
+#undef HAVE_TERMIOS_H\r
 \r
 /* Define to 1 if you have the <term.h> header file. */\r
 #undef HAVE_TERM_H\r
 #undef HAVE_UNAME\r
 \r
 /* Define to 1 if you have the <unistd.h> header file. */\r
-#undef HAVE_UNISTD_H\r
+#define HAVE_UNISTD_H                   1\r
 \r
 /* Define to 1 if you have the `unsetenv' function. */\r
 #undef HAVE_UNSETENV\r
 /* Define if you have a useable wchar_t type defined in wchar.h; useable means\r
    wchar_t must be an unsigned type with at least 16 bits. (see\r
    Include/unicodeobject.h). */\r
-#define HAVE_USABLE_WCHAR_T\r
+#define HAVE_USABLE_WCHAR_T             1\r
 \r
 /* Define to 1 if you have the <util.h> header file. */\r
 #undef HAVE_UTIL_H\r
 #undef HAVE_UTIMES\r
 \r
 /* Define to 1 if you have the <utime.h> header file. */\r
-#undef HAVE_UTIME_H\r
+#define HAVE_UTIME_H    1\r
 \r
 /* Define to 1 if you have the `wait3' function. */\r
 #undef HAVE_WAIT3\r
 #undef HAVE_WAITPID\r
 \r
 /* Define if the compiler provides a wchar.h header file. */\r
-#define HAVE_WCHAR_H\r
+#define HAVE_WCHAR_H    1\r
 \r
 /* Define to 1 if you have the `wcscoll' function. */\r
-#undef HAVE_WCSCOLL\r
+#define HAVE_WCSCOLL    1\r
 \r
 /* Define if tzset() actually switches the local timezone in a meaningful way.\r
    */\r
-#define HAVE_WORKING_TZSET\r
+#undef HAVE_WORKING_TZSET\r
 \r
 /* Define if the zlib library has inflateCopy */\r
 #undef HAVE_ZLIB_COPY\r
 #undef MVWDELCH_IS_EXPRESSION\r
 \r
 /* Define to the address where bug reports for this package should be sent. */\r
-#undef PACKAGE_BUGREPORT\r
+#define PACKAGE_BUGREPORT   "edk2-devel@lists.sourceforge.net"\r
 \r
 /* Define to the full name of this package. */\r
-#define PACKAGE_NAME    EDK II Python Package\r
+#define PACKAGE_NAME    "EDK II Python Package"\r
 \r
 /* Define to the full name and version of this package. */\r
-#define PACKAGE_STRING  EDK II Python Package V0.1\r
+#define PACKAGE_STRING  "EDK II Python Package V0.2"\r
 \r
 /* Define to the one symbol short name of this package. */\r
-#define PACKAGE_TARNAME   UDK_Python\r
+#define PACKAGE_TARNAME   "EADK_Python"\r
 \r
 /* Define to the home page for this package. */\r
-#define PACKAGE_URL   http://edk2.tianocore.org/toolkit/python\r
+#define PACKAGE_URL   "http://edk2.tianocore.org/toolkit/python"\r
 \r
 /* Define to the version of this package. */\r
-#undef PACKAGE_VERSION  V0.1\r
+#define PACKAGE_VERSION  "V0.2"\r
 \r
 /* Define if POSIX semaphores aren't enabled on your system */\r
-#define POSIX_SEMAPHORES_NOT_ENABLED\r
+#define POSIX_SEMAPHORES_NOT_ENABLED    1\r
 \r
 /* Defined if PTHREAD_SCOPE_SYSTEM supported. */\r
 #undef PTHREAD_SYSTEM_SCHED_SUPPORTED\r
 #undef PYLONG_BITS_IN_DIGIT\r
 \r
 /* Define to printf format modifier for long long type */\r
-#undef PY_FORMAT_LONG_LONG\r
+#define PY_FORMAT_LONG_LONG   "ll"\r
 \r
 /* Define to printf format modifier for Py_ssize_t */\r
-#undef PY_FORMAT_SIZE_T\r
+#define PY_FORMAT_SIZE_T    "z"\r
 \r
 /* Define as the integral type used for Unicode representation. */\r
-#undef PY_UNICODE_TYPE\r
+#define PY_UNICODE_TYPE     wchar_t\r
 \r
 /* Define if you want to build an interpreter with many run-time checks. */\r
 #undef Py_DEBUG\r
 #undef SIGNED_RIGHT_SHIFT_ZERO_FILLS\r
 \r
 /* The size of `double', as computed by sizeof. */\r
-#undef SIZEOF_DOUBLE\r
+#define SIZEOF_DOUBLE     8\r
 \r
 /* The size of `float', as computed by sizeof. */\r
-#undef SIZEOF_FLOAT\r
+#define SIZEOF_FLOAT      4\r
 \r
 /* The size of `fpos_t', as computed by sizeof. */\r
-#undef SIZEOF_FPOS_T\r
+#define SIZEOF_FPOS_T     8\r
 \r
 /* The size of `int', as computed by sizeof. */\r
-#undef SIZEOF_INT\r
+#define SIZEOF_INT        4\r
 \r
 /* The size of `long', as computed by sizeof. */\r
-#undef SIZEOF_LONG\r
+#if defined(_MSC_VER)           /* Handle Microsoft VC++ compiler specifics. */\r
+#define SIZEOF_LONG       4\r
+#else\r
+#define SIZEOF_LONG       8\r
+#endif\r
 \r
 /* The size of `long double', as computed by sizeof. */\r
 #undef SIZEOF_LONG_DOUBLE\r
 \r
 /* The size of `long long', as computed by sizeof. */\r
-#undef SIZEOF_LONG_LONG\r
+#define SIZEOF_LONG_LONG  8\r
 \r
 /* The size of `off_t', as computed by sizeof. */\r
-#undef SIZEOF_OFF_T\r
+#define SIZEOF_OFF_T      8\r
 \r
 /* The size of `pid_t', as computed by sizeof. */\r
-#undef SIZEOF_PID_T\r
+#define SIZEOF_PID_T      4\r
 \r
 /* The size of `pthread_t', as computed by sizeof. */\r
 #undef SIZEOF_PTHREAD_T\r
 \r
 /* The size of `short', as computed by sizeof. */\r
-#undef SIZEOF_SHORT\r
+#define SIZEOF_SHORT      2\r
 \r
 /* The size of `size_t', as computed by sizeof. */\r
-#undef SIZEOF_SIZE_T\r
+#define SIZEOF_SIZE_T     8\r
 \r
 /* The size of `time_t', as computed by sizeof. */\r
-#undef SIZEOF_TIME_T\r
+#define SIZEOF_TIME_T     4\r
 \r
 /* The size of `uintptr_t', as computed by sizeof. */\r
-#undef SIZEOF_UINTPTR_T\r
+#define SIZEOF_UINTPTR_T  8\r
 \r
 /* The size of `void *', as computed by sizeof. */\r
-#undef SIZEOF_VOID_P\r
+#define SIZEOF_VOID_P     8\r
 \r
 /* The size of `wchar_t', as computed by sizeof. */\r
-#undef SIZEOF_WCHAR_T\r
+#define SIZEOF_WCHAR_T    2\r
 \r
 /* The size of `_Bool', as computed by sizeof. */\r
-#undef SIZEOF__BOOL\r
+#define SIZEOF__BOOL      1\r
 \r
 /* Define to 1 if you have the ANSI C header files. */\r
 #define STDC_HEADERS    1\r
 #undef __EXTENSIONS__\r
 \r
 /* Define to 'long' if <time.h> doesn't define. */\r
-#undef clock_t\r
+//#undef clock_t\r
 \r
 /* Define to empty if `const' does not conform to ANSI C. */\r
-#undef const\r
+//#undef const\r
 \r
 /* Define to `int' if <sys/types.h> doesn't define. */\r
-#undef gid_t\r
+//#undef gid_t\r
 \r
 /* Define to the type of a signed integer type of width exactly 32 bits if\r
    such a type exists and the standard includes do not define it. */\r
-#undef int32_t\r
+//#undef int32_t\r
 \r
 /* Define to the type of a signed integer type of width exactly 64 bits if\r
    such a type exists and the standard includes do not define it. */\r
-#undef int64_t\r
+//#undef int64_t\r
 \r
 /* Define to `int' if <sys/types.h> does not define. */\r
-#undef mode_t\r
+//#undef mode_t\r
 \r
 /* Define to `long int' if <sys/types.h> does not define. */\r
-#undef off_t\r
+//#undef off_t\r
 \r
 /* Define to `int' if <sys/types.h> does not define. */\r
-#undef pid_t\r
+//#undef pid_t\r
 \r
 /* Define to empty if the keyword does not work. */\r
-#undef signed\r
+//#undef signed\r
 \r
 /* Define to `unsigned int' if <sys/types.h> does not define. */\r
-#undef size_t\r
+//#undef size_t\r
 \r
 /* Define to `int' if <sys/socket.h> does not define. */\r
-#undef socklen_t\r
+//#undef socklen_t\r
 \r
 /* Define to `int' if <sys/types.h> doesn't define. */\r
-#undef uid_t\r
+//#undef uid_t\r
 \r
 /* Define to the type of an unsigned integer type of width exactly 32 bits if\r
    such a type exists and the standard includes do not define it. */\r
-#undef uint32_t\r
+//#undef uint32_t\r
 \r
 /* Define to the type of an unsigned integer type of width exactly 64 bits if\r
    such a type exists and the standard includes do not define it. */\r
-#undef uint64_t\r
+//#undef uint64_t\r
 \r
 /* Define to empty if the keyword does not work. */\r
-#undef volatile\r
-\r
-\r
-/* Define the macros needed if on a UnixWare 7.x system. */\r
-#if defined(__USLC__) && defined(__SCO_VERSION__)\r
-#define STRICT_SYSV_CURSES /* Don't use ncurses extensions */\r
-#endif\r
+//#undef volatile\r
 \r
 #endif /*Py_PYCONFIG_H*/\r
-\r
index 4d25a8faa2a86f211eb34f43d8ac3e102045b723..f6bfdb01cca74571f4b76b1f3649a8d6ef9f84f1 100644 (file)
@@ -18,7 +18,7 @@ extern "C" {
 \r
 \r
 /* Mod by chrish: QNX has WATCOM, but isn't DOS */\r
-#if !defined(__QNX__) && !defined(EFIAPI)\r
+#if !defined(__QNX__) && !defined(UEFI_ENV)\r
 #if defined(MS_WINDOWS) || defined(__BORLANDC__) || defined(__WATCOMC__) || defined(__DJGPP__) || defined(PYOS_OS2)\r
 #if defined(PYOS_OS2) && defined(PYCC_GCC)\r
 #define MAXPATHLEN 260\r
@@ -57,8 +57,9 @@ extern "C" {
 \r
 /* Search path entry delimiter */\r
 #ifndef DELIM\r
-  #ifdef  EFIAPI\r
+  #ifdef  UEFI_ENV\r
     #define DELIM   ';'\r
+    #define DELIM_STR   ";"\r
   #else\r
     #define DELIM   ':'\r
   #endif\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/ntpath.py b/AppPkg/Applications/Python/PyMod-2.7.2/Lib/ntpath.py
new file mode 100644 (file)
index 0000000..970a603
--- /dev/null
@@ -0,0 +1,528 @@
+# Module 'ntpath' -- common operations on WinNT/Win95 pathnames\r
+"""Common pathname manipulations, WindowsNT/95 version.\r
+\r
+Instead of importing this module directly, import os and refer to this\r
+module as os.path.\r
+"""\r
+\r
+import os\r
+import sys\r
+import stat\r
+import genericpath\r
+import warnings\r
+\r
+from genericpath import *\r
+\r
+__all__ = ["normcase","isabs","join","splitdrive","split","splitext",\r
+           "basename","dirname","commonprefix","getsize","getmtime",\r
+           "getatime","getctime", "islink","exists","lexists","isdir","isfile",\r
+           "ismount","walk","expanduser","expandvars","normpath","abspath",\r
+           "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",\r
+           "extsep","devnull","realpath","supports_unicode_filenames","relpath"]\r
+\r
+# strings representing various path-related bits and pieces\r
+curdir = '.'\r
+pardir = '..'\r
+extsep = '.'\r
+sep = '\\'\r
+pathsep = ';'\r
+altsep = '/'\r
+defpath = '.;C:\\bin'\r
+if 'ce' in sys.builtin_module_names:\r
+    defpath = '\\Windows'\r
+elif 'os2' in sys.builtin_module_names:\r
+    # OS/2 w/ VACPP\r
+    altsep = '/'\r
+devnull = 'nul'\r
+\r
+# Normalize the case of a pathname and map slashes to backslashes.\r
+# Other normalizations (such as optimizing '../' away) are not done\r
+# (this is done by normpath).\r
+\r
+def normcase(s):\r
+    """Normalize case of pathname.\r
+\r
+    Makes all characters lowercase and all slashes into backslashes."""\r
+    return s.replace("/", "\\").lower()\r
+\r
+\r
+# Return whether a path is absolute.\r
+# Trivial in Posix, harder on the Mac or MS-DOS.\r
+# For DOS it is absolute if it starts with a slash or backslash (current\r
+# volume), or if a pathname after the volume letter and colon / UNC resource\r
+# starts with a slash or backslash.\r
+\r
+def isabs(s):\r
+    """Test whether a path is absolute"""\r
+    s = splitdrive(s)[1]\r
+    return s != '' and s[:1] in '/\\'\r
+\r
+\r
+# Join two (or more) paths.\r
+\r
+def join(a, *p):\r
+    """Join two or more pathname components, inserting "\\" as needed.\r
+    If any component is an absolute path, all previous path components\r
+    will be discarded."""\r
+    path = a\r
+    for b in p:\r
+        b_wins = 0  # set to 1 iff b makes path irrelevant\r
+        if path == "":\r
+            b_wins = 1\r
+\r
+        elif isabs(b):\r
+            # This probably wipes out path so far.  However, it's more\r
+            # complicated if path begins with a drive letter:\r
+            #     1. join('c:', '/a') == 'c:/a'\r
+            #     2. join('c:/', '/a') == 'c:/a'\r
+            # But\r
+            #     3. join('c:/a', '/b') == '/b'\r
+            #     4. join('c:', 'd:/') = 'd:/'\r
+            #     5. join('c:/', 'd:/') = 'd:/'\r
+            if path[1:2] != ":" or b[1:2] == ":":\r
+                # Path doesn't start with a drive letter, or cases 4 and 5.\r
+                b_wins = 1\r
+\r
+            # Else path has a drive letter, and b doesn't but is absolute.\r
+            elif len(path) > 3 or (len(path) == 3 and\r
+                                   path[-1] not in "/\\"):\r
+                # case 3\r
+                b_wins = 1\r
+\r
+        if b_wins:\r
+            path = b\r
+        else:\r
+            # Join, and ensure there's a separator.\r
+            assert len(path) > 0\r
+            if path[-1] in "/\\":\r
+                if b and b[0] in "/\\":\r
+                    path += b[1:]\r
+                else:\r
+                    path += b\r
+            elif path[-1] == ":":\r
+                path += b\r
+            elif b:\r
+                if b[0] in "/\\":\r
+                    path += b\r
+                else:\r
+                    path += "\\" + b\r
+            else:\r
+                # path is not empty and does not end with a backslash,\r
+                # but b is empty; since, e.g., split('a/') produces\r
+                # ('a', ''), it's best if join() adds a backslash in\r
+                # this case.\r
+                path += '\\'\r
+\r
+    return path\r
+\r
+\r
+# Split a path in a drive specification (a drive letter followed by a\r
+# colon) and the path specification.\r
+# It is always true that drivespec + pathspec == p\r
+def splitdrive(p):\r
+    """Split a pathname into drive and path specifiers. Returns a 2-tuple\r
+"(drive,path)";  either part may be empty"""\r
+    pparts = p.split(':', 2)\r
+    numparts = len(pparts)\r
+    if numparts == 2:\r
+        return pparts[0] + ':', pparts[1]\r
+    else:\r
+        if numparts == 1:\r
+          return '', pparts[0]\r
+    return '', p\r
+\r
+\r
+# Parse UNC paths\r
+def splitunc(p):\r
+    """Split a pathname into UNC mount point and relative path specifiers.\r
+\r
+    Return a 2-tuple (unc, rest); either part may be empty.\r
+    If unc is not empty, it has the form '//host/mount' (or similar\r
+    using backslashes).  unc+rest is always the input path.\r
+    Paths containing drive letters never have an UNC part.\r
+    """\r
+    if len(p.split(':', 2)) > 1:\r
+        return '', p # Drive letter present\r
+    firstTwo = p[0:2]\r
+    if firstTwo == '//' or firstTwo == '\\\\':\r
+        # is a UNC path:\r
+        # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter\r
+        # \\machine\mountpoint\directories...\r
+        #           directory ^^^^^^^^^^^^^^^\r
+        normp = normcase(p)\r
+        index = normp.find('\\', 2)\r
+        if index == -1:\r
+            ##raise RuntimeError, 'illegal UNC path: "' + p + '"'\r
+            return ("", p)\r
+        index = normp.find('\\', index + 1)\r
+        if index == -1:\r
+            index = len(p)\r
+        return p[:index], p[index:]\r
+    return '', p\r
+\r
+\r
+# Split a path in head (everything up to the last '/') and tail (the\r
+# rest).  After the trailing '/' is stripped, the invariant\r
+# join(head, tail) == p holds.\r
+# The resulting head won't end in '/' unless it is the root.\r
+\r
+def split(p):\r
+    """Split a pathname.\r
+\r
+    Return tuple (head, tail) where tail is everything after the final slash.\r
+    Either part may be empty."""\r
+\r
+    d, p = splitdrive(p)\r
+    # set i to index beyond p's last slash\r
+    i = len(p)\r
+    while i and p[i-1] not in '/\\':\r
+        i = i - 1\r
+    head, tail = p[:i], p[i:]  # now tail has no slashes\r
+    # remove trailing slashes from head, unless it's all slashes\r
+    head2 = head\r
+    while head2 and head2[-1] in '/\\':\r
+        head2 = head2[:-1]\r
+    head = head2 or head\r
+    return d + head, tail\r
+\r
+\r
+# Split a path in root and extension.\r
+# The extension is everything starting at the last dot in the last\r
+# pathname component; the root is everything before that.\r
+# It is always true that root + ext == p.\r
+\r
+def splitext(p):\r
+    return genericpath._splitext(p, sep, altsep, extsep)\r
+splitext.__doc__ = genericpath._splitext.__doc__\r
+\r
+\r
+# Return the tail (basename) part of a path.\r
+\r
+def basename(p):\r
+    """Returns the final component of a pathname"""\r
+    return split(p)[1]\r
+\r
+\r
+# Return the head (dirname) part of a path.\r
+\r
+def dirname(p):\r
+    """Returns the directory component of a pathname"""\r
+    return split(p)[0]\r
+\r
+# Is a path a symbolic link?\r
+# This will always return false on systems where posix.lstat doesn't exist.\r
+\r
+def islink(path):\r
+    """Test for symbolic link.\r
+    On WindowsNT/95 and OS/2 always returns false\r
+    """\r
+    return False\r
+\r
+# alias exists to lexists\r
+lexists = exists\r
+\r
+# Is a path a mount point?  Either a root (with or without drive letter)\r
+# or an UNC path with at most a / or \ after the mount point.\r
+\r
+def ismount(path):\r
+    """Test whether a path is a mount point (defined as root of drive)"""\r
+    unc, rest = splitunc(path)\r
+    if unc:\r
+        return rest in ("", "/", "\\")\r
+    p = splitdrive(path)[1]\r
+    return len(p) == 1 and p[0] in '/\\'\r
+\r
+\r
+# Directory tree walk.\r
+# For each directory under top (including top itself, but excluding\r
+# '.' and '..'), func(arg, dirname, filenames) is called, where\r
+# dirname is the name of the directory and filenames is the list\r
+# of files (and subdirectories etc.) in the directory.\r
+# The func may modify the filenames list, to implement a filter,\r
+# or to impose a different order of visiting.\r
+\r
+def walk(top, func, arg):\r
+    """Directory tree walk with callback function.\r
+\r
+    For each directory in the directory tree rooted at top (including top\r
+    itself, but excluding '.' and '..'), call func(arg, dirname, fnames).\r
+    dirname is the name of the directory, and fnames a list of the names of\r
+    the files and subdirectories in dirname (excluding '.' and '..').  func\r
+    may modify the fnames list in-place (e.g. via del or slice assignment),\r
+    and walk will only recurse into the subdirectories whose names remain in\r
+    fnames; this can be used to implement a filter, or to impose a specific\r
+    order of visiting.  No semantics are defined for, or required of, arg,\r
+    beyond that arg is always passed to func.  It can be used, e.g., to pass\r
+    a filename pattern, or a mutable object designed to accumulate\r
+    statistics.  Passing None for arg is common."""\r
+    warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",\r
+                      stacklevel=2)\r
+    try:\r
+        names = os.listdir(top)\r
+    except os.error:\r
+        return\r
+    func(arg, top, names)\r
+    for name in names:\r
+        name = join(top, name)\r
+        if isdir(name):\r
+            walk(name, func, arg)\r
+\r
+\r
+# Expand paths beginning with '~' or '~user'.\r
+# '~' means $HOME; '~user' means that user's home directory.\r
+# If the path doesn't begin with '~', or if the user or $HOME is unknown,\r
+# the path is returned unchanged (leaving error reporting to whatever\r
+# function is called with the expanded path as argument).\r
+# See also module 'glob' for expansion of *, ? and [...] in pathnames.\r
+# (A function should also be defined to do full *sh-style environment\r
+# variable expansion.)\r
+\r
+def expanduser(path):\r
+    """Expand ~ and ~user constructs.\r
+\r
+    If user or $HOME is unknown, do nothing."""\r
+    if path[:1] != '~':\r
+        return path\r
+    i, n = 1, len(path)\r
+    while i < n and path[i] not in '/\\':\r
+        i = i + 1\r
+\r
+    if 'HOME' in os.environ:\r
+        userhome = os.environ['HOME']\r
+    elif 'USERPROFILE' in os.environ:\r
+        userhome = os.environ['USERPROFILE']\r
+    elif not 'HOMEPATH' in os.environ:\r
+        return path\r
+    else:\r
+        try:\r
+            drive = os.environ['HOMEDRIVE']\r
+        except KeyError:\r
+            drive = ''\r
+        userhome = join(drive, os.environ['HOMEPATH'])\r
+\r
+    if i != 1: #~user\r
+        userhome = join(dirname(userhome), path[1:i])\r
+\r
+    return userhome + path[i:]\r
+\r
+\r
+# Expand paths containing shell variable substitutions.\r
+# The following rules apply:\r
+#       - no expansion within single quotes\r
+#       - '$$' is translated into '$'\r
+#       - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%\r
+#       - ${varname} is accepted.\r
+#       - $varname is accepted.\r
+#       - %varname% is accepted.\r
+#       - varnames can be made out of letters, digits and the characters '_-'\r
+#         (though is not verified in the ${varname} and %varname% cases)\r
+# XXX With COMMAND.COM you can use any characters in a variable name,\r
+# XXX except '^|<>='.\r
+\r
+def expandvars(path):\r
+    """Expand shell variables of the forms $var, ${var} and %var%.\r
+\r
+    Unknown variables are left unchanged."""\r
+    if '$' not in path and '%' not in path:\r
+        return path\r
+    import string\r
+    varchars = string.ascii_letters + string.digits + '_-'\r
+    res = ''\r
+    index = 0\r
+    pathlen = len(path)\r
+    while index < pathlen:\r
+        c = path[index]\r
+        if c == '\'':   # no expansion within single quotes\r
+            path = path[index + 1:]\r
+            pathlen = len(path)\r
+            try:\r
+                index = path.index('\'')\r
+                res = res + '\'' + path[:index + 1]\r
+            except ValueError:\r
+                res = res + path\r
+                index = pathlen - 1\r
+        elif c == '%':  # variable or '%'\r
+            if path[index + 1:index + 2] == '%':\r
+                res = res + c\r
+                index = index + 1\r
+            else:\r
+                path = path[index+1:]\r
+                pathlen = len(path)\r
+                try:\r
+                    index = path.index('%')\r
+                except ValueError:\r
+                    res = res + '%' + path\r
+                    index = pathlen - 1\r
+                else:\r
+                    var = path[:index]\r
+                    if var in os.environ:\r
+                        res = res + os.environ[var]\r
+                    else:\r
+                        res = res + '%' + var + '%'\r
+        elif c == '$':  # variable or '$$'\r
+            if path[index + 1:index + 2] == '$':\r
+                res = res + c\r
+                index = index + 1\r
+            elif path[index + 1:index + 2] == '{':\r
+                path = path[index+2:]\r
+                pathlen = len(path)\r
+                try:\r
+                    index = path.index('}')\r
+                    var = path[:index]\r
+                    if var in os.environ:\r
+                        res = res + os.environ[var]\r
+                    else:\r
+                        res = res + '${' + var + '}'\r
+                except ValueError:\r
+                    res = res + '${' + path\r
+                    index = pathlen - 1\r
+            else:\r
+                var = ''\r
+                index = index + 1\r
+                c = path[index:index + 1]\r
+                while c != '' and c in varchars:\r
+                    var = var + c\r
+                    index = index + 1\r
+                    c = path[index:index + 1]\r
+                if var in os.environ:\r
+                    res = res + os.environ[var]\r
+                else:\r
+                    res = res + '$' + var\r
+                if c != '':\r
+                    index = index - 1\r
+        else:\r
+            res = res + c\r
+        index = index + 1\r
+    return res\r
+\r
+\r
+# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.\r
+# Previously, this function also truncated pathnames to 8+3 format,\r
+# but as this module is called "ntpath", that's obviously wrong!\r
+\r
+def normpath(path):\r
+    """Normalize path, eliminating double slashes, etc."""\r
+    # Preserve unicode (if path is unicode)\r
+    backslash, dot = (u'\\', u'.') if isinstance(path, unicode) else ('\\', '.')\r
+    if path.startswith(('\\\\.\\', '\\\\?\\')):\r
+        # in the case of paths with these prefixes:\r
+        # \\.\ -> device names\r
+        # \\?\ -> literal paths\r
+        # do not do any normalization, but return the path unchanged\r
+        return path\r
+    path = path.replace("/", "\\")\r
+    prefix, path = splitdrive(path)\r
+    # We need to be careful here. If the prefix is empty, and the path starts\r
+    # with a backslash, it could either be an absolute path on the current\r
+    # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It\r
+    # is therefore imperative NOT to collapse multiple backslashes blindly in\r
+    # that case.\r
+    # The code below preserves multiple backslashes when there is no drive\r
+    # letter. This means that the invalid filename \\\a\b is preserved\r
+    # unchanged, where a\\\b is normalised to a\b. It's not clear that there\r
+    # is any better behaviour for such edge cases.\r
+    if prefix == '':\r
+        # No drive letter - preserve initial backslashes\r
+        while path[:1] == "\\":\r
+            prefix = prefix + backslash\r
+            path = path[1:]\r
+    else:\r
+        # We have a drive letter - collapse initial backslashes\r
+        if path.startswith("\\"):\r
+            prefix = prefix + backslash\r
+            path = path.lstrip("\\")\r
+    comps = path.split("\\")\r
+    i = 0\r
+    while i < len(comps):\r
+        if comps[i] in ('.', ''):\r
+            del comps[i]\r
+        elif comps[i] == '..':\r
+            if i > 0 and comps[i-1] != '..':\r
+                del comps[i-1:i+1]\r
+                i -= 1\r
+            elif i == 0 and prefix.endswith("\\"):\r
+                del comps[i]\r
+            else:\r
+                i += 1\r
+        else:\r
+            i += 1\r
+    # If the path is now empty, substitute '.'\r
+    if not prefix and not comps:\r
+        comps.append(dot)\r
+    return prefix + backslash.join(comps)\r
+\r
+\r
+# Return an absolute path.\r
+try:\r
+    from nt import _getfullpathname\r
+\r
+except ImportError: # not running on Windows - mock up something sensible\r
+    def abspath(path):\r
+        """Return the absolute version of a path."""\r
+        if not isabs(path):\r
+            if isinstance(path, unicode):\r
+                cwd = os.getcwdu()\r
+            else:\r
+                cwd = os.getcwd()\r
+            path = join(cwd, path)\r
+        return normpath(path)\r
+\r
+else:  # use native Windows method on Windows\r
+    def abspath(path):\r
+        """Return the absolute version of a path."""\r
+\r
+        if path: # Empty path must return current working directory.\r
+            try:\r
+                path = _getfullpathname(path)\r
+            except WindowsError:\r
+                pass # Bad path - return unchanged.\r
+        elif isinstance(path, unicode):\r
+            path = os.getcwdu()\r
+        else:\r
+            path = os.getcwd()\r
+        return normpath(path)\r
+\r
+# realpath is a no-op on systems without islink support\r
+realpath = abspath\r
+# Win9x family and earlier have no Unicode filename support.\r
+supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and\r
+                              sys.getwindowsversion()[3] >= 2)\r
+\r
+def _abspath_split(path):\r
+    abs = abspath(normpath(path))\r
+    prefix, rest = splitunc(abs)\r
+    is_unc = bool(prefix)\r
+    if not is_unc:\r
+        prefix, rest = splitdrive(abs)\r
+    return is_unc, prefix, [x for x in rest.split(sep) if x]\r
+\r
+def relpath(path, start=curdir):\r
+    """Return a relative version of a path"""\r
+\r
+    if not path:\r
+        raise ValueError("no path specified")\r
+\r
+    start_is_unc, start_prefix, start_list = _abspath_split(start)\r
+    path_is_unc, path_prefix, path_list = _abspath_split(path)\r
+\r
+    if path_is_unc ^ start_is_unc:\r
+        raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"\r
+                                                            % (path, start))\r
+    if path_prefix.lower() != start_prefix.lower():\r
+        if path_is_unc:\r
+            raise ValueError("path is on UNC root %s, start on UNC root %s"\r
+                                                % (path_prefix, start_prefix))\r
+        else:\r
+            raise ValueError("path is on drive %s, start on drive %s"\r
+                                                % (path_prefix, start_prefix))\r
+    # Work out how much of the filepath is shared by start and path.\r
+    i = 0\r
+    for e1, e2 in zip(start_list, path_list):\r
+        if e1.lower() != e2.lower():\r
+            break\r
+        i += 1\r
+\r
+    rel_list = [pardir] * (len(start_list)-i) + path_list[i:]\r
+    if not rel_list:\r
+        return curdir\r
+    return join(*rel_list)\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/os.py b/AppPkg/Applications/Python/PyMod-2.7.2/Lib/os.py
new file mode 100644 (file)
index 0000000..413e4ae
--- /dev/null
@@ -0,0 +1,773 @@
+"""OS routines for Mac, NT, Posix, or UEFI depending on what system we're on.\r
+\r
+This exports:\r
+  - all functions from edk2, posix, nt, os2, or ce, e.g. unlink, stat, etc.\r
+  - os.path is one of the modules uefipath, posixpath, or ntpath\r
+  - os.name is 'edk2', 'posix', 'nt', 'os2', 'ce' or 'riscos'\r
+  - os.curdir is a string representing the current directory ('.' or ':')\r
+  - os.pardir is a string representing the parent directory ('..' or '::')\r
+  - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')\r
+  - os.extsep is the extension separator ('.' or '/')\r
+  - os.altsep is the alternate pathname separator (None or '/')\r
+  - os.pathsep is the component separator used in $PATH etc\r
+  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')\r
+  - os.defpath is the default search path for executables\r
+  - os.devnull is the file path of the null device ('/dev/null', etc.)\r
+\r
+Programs that import and use 'os' stand a better chance of being\r
+portable between different platforms.  Of course, they must then\r
+only use functions that are defined by all platforms (e.g., unlink\r
+and opendir), and leave all pathname manipulation to os.path\r
+(e.g., split and join).\r
+"""\r
+\r
+#'\r
+\r
+import sys, errno\r
+\r
+_names = sys.builtin_module_names\r
+\r
+# Note:  more names are added to __all__ later.\r
+__all__ = ["altsep", "curdir", "pardir", "sep", "extsep", "pathsep", "linesep",\r
+           "defpath", "name", "path", "devnull",\r
+           "SEEK_SET", "SEEK_CUR", "SEEK_END"]\r
+\r
+def _get_exports_list(module):\r
+    try:\r
+        return list(module.__all__)\r
+    except AttributeError:\r
+        return [n for n in dir(module) if n[0] != '_']\r
+\r
+if 'posix' in _names:\r
+    name = 'posix'\r
+    linesep = '\n'\r
+    from posix import *\r
+    try:\r
+        from posix import _exit\r
+    except ImportError:\r
+        pass\r
+    import posixpath as path\r
+\r
+    import posix\r
+    __all__.extend(_get_exports_list(posix))\r
+    del posix\r
+\r
+elif 'nt' in _names:\r
+    name = 'nt'\r
+    linesep = '\r\n'\r
+    from nt import *\r
+    try:\r
+        from nt import _exit\r
+    except ImportError:\r
+        pass\r
+    import ntpath as path\r
+\r
+    import nt\r
+    __all__.extend(_get_exports_list(nt))\r
+    del nt\r
+\r
+elif 'os2' in _names:\r
+    name = 'os2'\r
+    linesep = '\r\n'\r
+    from os2 import *\r
+    try:\r
+        from os2 import _exit\r
+    except ImportError:\r
+        pass\r
+    if sys.version.find('EMX GCC') == -1:\r
+        import ntpath as path\r
+    else:\r
+        import os2emxpath as path\r
+        from _emx_link import link\r
+\r
+    import os2\r
+    __all__.extend(_get_exports_list(os2))\r
+    del os2\r
+\r
+elif 'ce' in _names:\r
+    name = 'ce'\r
+    linesep = '\r\n'\r
+    from ce import *\r
+    try:\r
+        from ce import _exit\r
+    except ImportError:\r
+        pass\r
+    # We can use the standard Windows path.\r
+    import ntpath as path\r
+\r
+    import ce\r
+    __all__.extend(_get_exports_list(ce))\r
+    del ce\r
+\r
+elif 'riscos' in _names:\r
+    name = 'riscos'\r
+    linesep = '\n'\r
+    from riscos import *\r
+    try:\r
+        from riscos import _exit\r
+    except ImportError:\r
+        pass\r
+    import riscospath as path\r
+\r
+    import riscos\r
+    __all__.extend(_get_exports_list(riscos))\r
+    del riscos\r
+\r
+elif 'edk2' in _names:\r
+    name = 'edk2'\r
+    linesep = '\n'\r
+    from edk2 import *\r
+    try:\r
+        from edk2 import _exit\r
+    except ImportError:\r
+        pass\r
+    import ntpath as path\r
+\r
+    import edk2\r
+    __all__.extend(_get_exports_list(edk2))\r
+    del edk2\r
+\r
+else:\r
+    raise ImportError, 'no os specific module found'\r
+\r
+sys.modules['os.path'] = path\r
+from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,\r
+    devnull)\r
+\r
+del _names\r
+\r
+# Python uses fixed values for the SEEK_ constants; they are mapped\r
+# to native constants if necessary in posixmodule.c\r
+SEEK_SET = 0\r
+SEEK_CUR = 1\r
+SEEK_END = 2\r
+\r
+#'\r
+\r
+# Super directory utilities.\r
+# (Inspired by Eric Raymond; the doc strings are mostly his)\r
+\r
+def makedirs(name, mode=0777):\r
+    """makedirs(path [, mode=0777])\r
+\r
+    Super-mkdir; create a leaf directory and all intermediate ones.\r
+    Works like mkdir, except that any intermediate path segment (not\r
+    just the rightmost) will be created if it does not exist.  This is\r
+    recursive.\r
+\r
+    """\r
+    head, tail = path.split(name)\r
+    if not tail:\r
+        head, tail = path.split(head)\r
+    if head and tail and not path.exists(head):\r
+        try:\r
+            makedirs(head, mode)\r
+        except OSError, e:\r
+            # be happy if someone already created the path\r
+            if e.errno != errno.EEXIST:\r
+                raise\r
+        if tail == curdir:           # xxx/newdir/. exists if xxx/newdir exists\r
+            return\r
+    mkdir(name, mode)\r
+\r
+def removedirs(name):\r
+    """removedirs(path)\r
+\r
+    Super-rmdir; remove a leaf directory and all empty intermediate\r
+    ones.  Works like rmdir except that, if the leaf directory is\r
+    successfully removed, directories corresponding to rightmost path\r
+    segments will be pruned away until either the whole path is\r
+    consumed or an error occurs.  Errors during this latter phase are\r
+    ignored -- they generally mean that a directory was not empty.\r
+\r
+    """\r
+    rmdir(name)\r
+    head, tail = path.split(name)\r
+    if not tail:\r
+        head, tail = path.split(head)\r
+    while head and tail:\r
+        try:\r
+            rmdir(head)\r
+        except error:\r
+            break\r
+        head, tail = path.split(head)\r
+\r
+def renames(old, new):\r
+    """renames(old, new)\r
+\r
+    Super-rename; create directories as necessary and delete any left\r
+    empty.  Works like rename, except creation of any intermediate\r
+    directories needed to make the new pathname good is attempted\r
+    first.  After the rename, directories corresponding to rightmost\r
+    path segments of the old name will be pruned way until either the\r
+    whole path is consumed or a nonempty directory is found.\r
+\r
+    Note: this function can fail with the new directory structure made\r
+    if you lack permissions needed to unlink the leaf directory or\r
+    file.\r
+\r
+    """\r
+    head, tail = path.split(new)\r
+    if head and tail and not path.exists(head):\r
+        makedirs(head)\r
+    rename(old, new)\r
+    head, tail = path.split(old)\r
+    if head and tail:\r
+        try:\r
+            removedirs(head)\r
+        except error:\r
+            pass\r
+\r
+__all__.extend(["makedirs", "removedirs", "renames"])\r
+\r
+def walk(top, topdown=True, onerror=None, followlinks=False):\r
+    """Directory tree generator.\r
+\r
+    For each directory in the directory tree rooted at top (including top\r
+    itself, but excluding '.' and '..'), yields a 3-tuple\r
+\r
+        dirpath, dirnames, filenames\r
+\r
+    dirpath is a string, the path to the directory.  dirnames is a list of\r
+    the names of the subdirectories in dirpath (excluding '.' and '..').\r
+    filenames is a list of the names of the non-directory files in dirpath.\r
+    Note that the names in the lists are just names, with no path components.\r
+    To get a full path (which begins with top) to a file or directory in\r
+    dirpath, do os.path.join(dirpath, name).\r
+\r
+    If optional arg 'topdown' is true or not specified, the triple for a\r
+    directory is generated before the triples for any of its subdirectories\r
+    (directories are generated top down).  If topdown is false, the triple\r
+    for a directory is generated after the triples for all of its\r
+    subdirectories (directories are generated bottom up).\r
+\r
+    When topdown is true, the caller can modify the dirnames list in-place\r
+    (e.g., via del or slice assignment), and walk will only recurse into the\r
+    subdirectories whose names remain in dirnames; this can be used to prune\r
+    the search, or to impose a specific order of visiting.  Modifying\r
+    dirnames when topdown is false is ineffective, since the directories in\r
+    dirnames have already been generated by the time dirnames itself is\r
+    generated.\r
+\r
+    By default errors from the os.listdir() call are ignored.  If\r
+    optional arg 'onerror' is specified, it should be a function; it\r
+    will be called with one argument, an os.error instance.  It can\r
+    report the error to continue with the walk, or raise the exception\r
+    to abort the walk.  Note that the filename is available as the\r
+    filename attribute of the exception object.\r
+\r
+    By default, os.walk does not follow symbolic links to subdirectories on\r
+    systems that support them.  In order to get this functionality, set the\r
+    optional argument 'followlinks' to true.\r
+\r
+    Caution:  if you pass a relative pathname for top, don't change the\r
+    current working directory between resumptions of walk.  walk never\r
+    changes the current directory, and assumes that the client doesn't\r
+    either.\r
+\r
+    Example:\r
+\r
+    import os\r
+    from os.path import join, getsize\r
+    for root, dirs, files in os.walk('python/Lib/email'):\r
+        print root, "consumes",\r
+        print sum([getsize(join(root, name)) for name in files]),\r
+        print "bytes in", len(files), "non-directory files"\r
+        if 'CVS' in dirs:\r
+            dirs.remove('CVS')  # don't visit CVS directories\r
+    """\r
+\r
+    islink, join, isdir = path.islink, path.join, path.isdir\r
+\r
+    # We may not have read permission for top, in which case we can't\r
+    # get a list of the files the directory contains.  os.path.walk\r
+    # always suppressed the exception then, rather than blow up for a\r
+    # minor reason when (say) a thousand readable directories are still\r
+    # left to visit.  That logic is copied here.\r
+    try:\r
+        # Note that listdir and error are globals in this module due\r
+        # to earlier import-*.\r
+        names = listdir(top)\r
+    except error, err:\r
+        if onerror is not None:\r
+            onerror(err)\r
+        return\r
+\r
+    dirs, nondirs = [], []\r
+    for name in names:\r
+        if isdir(join(top, name)):\r
+            dirs.append(name)\r
+        else:\r
+            nondirs.append(name)\r
+\r
+    if topdown:\r
+        yield top, dirs, nondirs\r
+    for name in dirs:\r
+        new_path = join(top, name)\r
+        if followlinks or not islink(new_path):\r
+            for x in walk(new_path, topdown, onerror, followlinks):\r
+                yield x\r
+    if not topdown:\r
+        yield top, dirs, nondirs\r
+\r
+__all__.append("walk")\r
+\r
+# Make sure os.environ exists, at least\r
+try:\r
+    environ\r
+except NameError:\r
+    environ = {}\r
+\r
+def execl(file, *args):\r
+    """execl(file, *args)\r
+\r
+    Execute the executable file with argument list args, replacing the\r
+    current process. """\r
+    execv(file, args)\r
+\r
+def execle(file, *args):\r
+    """execle(file, *args, env)\r
+\r
+    Execute the executable file with argument list args and\r
+    environment env, replacing the current process. """\r
+    env = args[-1]\r
+    execve(file, args[:-1], env)\r
+\r
+def execlp(file, *args):\r
+    """execlp(file, *args)\r
+\r
+    Execute the executable file (which is searched for along $PATH)\r
+    with argument list args, replacing the current process. """\r
+    execvp(file, args)\r
+\r
+def execlpe(file, *args):\r
+    """execlpe(file, *args, env)\r
+\r
+    Execute the executable file (which is searched for along $PATH)\r
+    with argument list args and environment env, replacing the current\r
+    process. """\r
+    env = args[-1]\r
+    execvpe(file, args[:-1], env)\r
+\r
+def execvp(file, args):\r
+    """execvp(file, args)\r
+\r
+    Execute the executable file (which is searched for along $PATH)\r
+    with argument list args, replacing the current process.\r
+    args may be a list or tuple of strings. """\r
+    _execvpe(file, args)\r
+\r
+def execvpe(file, args, env):\r
+    """execvpe(file, args, env)\r
+\r
+    Execute the executable file (which is searched for along $PATH)\r
+    with argument list args and environment env , replacing the\r
+    current process.\r
+    args may be a list or tuple of strings. """\r
+    _execvpe(file, args, env)\r
+\r
+__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])\r
+\r
+def _execvpe(file, args, env=None):\r
+    if env is not None:\r
+        func = execve\r
+        argrest = (args, env)\r
+    else:\r
+        func = execv\r
+        argrest = (args,)\r
+        env = environ\r
+\r
+    head, tail = path.split(file)\r
+    if head:\r
+        func(file, *argrest)\r
+        return\r
+    if 'PATH' in env:\r
+        envpath = env['PATH']\r
+    else:\r
+        envpath = defpath\r
+    PATH = envpath.split(pathsep)\r
+    saved_exc = None\r
+    saved_tb = None\r
+    for dir in PATH:\r
+        fullname = path.join(dir, file)\r
+        try:\r
+            func(fullname, *argrest)\r
+        except error, e:\r
+            tb = sys.exc_info()[2]\r
+            if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR\r
+                and saved_exc is None):\r
+                saved_exc = e\r
+                saved_tb = tb\r
+    if saved_exc:\r
+        raise error, saved_exc, saved_tb\r
+    raise error, e, tb\r
+\r
+# Change environ to automatically call putenv() if it exists\r
+try:\r
+    # This will fail if there's no putenv\r
+    putenv\r
+except NameError:\r
+    pass\r
+else:\r
+    import UserDict\r
+\r
+    # Fake unsetenv() for Windows\r
+    # not sure about os2 here but\r
+    # I'm guessing they are the same.\r
+\r
+    if name in ('os2', 'nt'):\r
+        def unsetenv(key):\r
+            putenv(key, "")\r
+\r
+    if name == "riscos":\r
+        # On RISC OS, all env access goes through getenv and putenv\r
+        from riscosenviron import _Environ\r
+    elif name in ('os2', 'nt'):  # Where Env Var Names Must Be UPPERCASE\r
+        # But we store them as upper case\r
+        class _Environ(UserDict.IterableUserDict):\r
+            def __init__(self, environ):\r
+                UserDict.UserDict.__init__(self)\r
+                data = self.data\r
+                for k, v in environ.items():\r
+                    data[k.upper()] = v\r
+            def __setitem__(self, key, item):\r
+                putenv(key, item)\r
+                self.data[key.upper()] = item\r
+            def __getitem__(self, key):\r
+                return self.data[key.upper()]\r
+            try:\r
+                unsetenv\r
+            except NameError:\r
+                def __delitem__(self, key):\r
+                    del self.data[key.upper()]\r
+            else:\r
+                def __delitem__(self, key):\r
+                    unsetenv(key)\r
+                    del self.data[key.upper()]\r
+                def clear(self):\r
+                    for key in self.data.keys():\r
+                        unsetenv(key)\r
+                        del self.data[key]\r
+                def pop(self, key, *args):\r
+                    unsetenv(key)\r
+                    return self.data.pop(key.upper(), *args)\r
+            def has_key(self, key):\r
+                return key.upper() in self.data\r
+            def __contains__(self, key):\r
+                return key.upper() in self.data\r
+            def get(self, key, failobj=None):\r
+                return self.data.get(key.upper(), failobj)\r
+            def update(self, dict=None, **kwargs):\r
+                if dict:\r
+                    try:\r
+                        keys = dict.keys()\r
+                    except AttributeError:\r
+                        # List of (key, value)\r
+                        for k, v in dict:\r
+                            self[k] = v\r
+                    else:\r
+                        # got keys\r
+                        # cannot use items(), since mappings\r
+                        # may not have them.\r
+                        for k in keys:\r
+                            self[k] = dict[k]\r
+                if kwargs:\r
+                    self.update(kwargs)\r
+            def copy(self):\r
+                return dict(self)\r
+\r
+    else:  # Where Env Var Names Can Be Mixed Case\r
+        class _Environ(UserDict.IterableUserDict):\r
+            def __init__(self, environ):\r
+                UserDict.UserDict.__init__(self)\r
+                self.data = environ\r
+            def __setitem__(self, key, item):\r
+                putenv(key, item)\r
+                self.data[key] = item\r
+            def update(self,  dict=None, **kwargs):\r
+                if dict:\r
+                    try:\r
+                        keys = dict.keys()\r
+                    except AttributeError:\r
+                        # List of (key, value)\r
+                        for k, v in dict:\r
+                            self[k] = v\r
+                    else:\r
+                        # got keys\r
+                        # cannot use items(), since mappings\r
+                        # may not have them.\r
+                        for k in keys:\r
+                            self[k] = dict[k]\r
+                if kwargs:\r
+                    self.update(kwargs)\r
+            try:\r
+                unsetenv\r
+            except NameError:\r
+                pass\r
+            else:\r
+                def __delitem__(self, key):\r
+                    unsetenv(key)\r
+                    del self.data[key]\r
+                def clear(self):\r
+                    for key in self.data.keys():\r
+                        unsetenv(key)\r
+                        del self.data[key]\r
+                def pop(self, key, *args):\r
+                    unsetenv(key)\r
+                    return self.data.pop(key, *args)\r
+            def copy(self):\r
+                return dict(self)\r
+\r
+\r
+    environ = _Environ(environ)\r
+\r
+def getenv(key, default=None):\r
+    """Get an environment variable, return None if it doesn't exist.\r
+    The optional second argument can specify an alternate default."""\r
+    return environ.get(key, default)\r
+__all__.append("getenv")\r
+\r
+def _exists(name):\r
+    return name in globals()\r
+\r
+# Supply spawn*() (probably only for Unix)\r
+if _exists("fork") and not _exists("spawnv") and _exists("execv"):\r
+\r
+    P_WAIT = 0\r
+    P_NOWAIT = P_NOWAITO = 1\r
+\r
+    # XXX Should we support P_DETACH?  I suppose it could fork()**2\r
+    # and close the std I/O streams.  Also, P_OVERLAY is the same\r
+    # as execv*()?\r
+\r
+    def _spawnvef(mode, file, args, env, func):\r
+        # Internal helper; func is the exec*() function to use\r
+        pid = fork()\r
+        if not pid:\r
+            # Child\r
+            try:\r
+                if env is None:\r
+                    func(file, args)\r
+                else:\r
+                    func(file, args, env)\r
+            except:\r
+                _exit(127)\r
+        else:\r
+            # Parent\r
+            if mode == P_NOWAIT:\r
+                return pid # Caller is responsible for waiting!\r
+            while 1:\r
+                wpid, sts = waitpid(pid, 0)\r
+                if WIFSTOPPED(sts):\r
+                    continue\r
+                elif WIFSIGNALED(sts):\r
+                    return -WTERMSIG(sts)\r
+                elif WIFEXITED(sts):\r
+                    return WEXITSTATUS(sts)\r
+                else:\r
+                    raise error, "Not stopped, signaled or exited???"\r
+\r
+    def spawnv(mode, file, args):\r
+        """spawnv(mode, file, args) -> integer\r
+\r
+Execute file with arguments from args in a subprocess.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+        return _spawnvef(mode, file, args, None, execv)\r
+\r
+    def spawnve(mode, file, args, env):\r
+        """spawnve(mode, file, args, env) -> integer\r
+\r
+Execute file with arguments from args in a subprocess with the\r
+specified environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+        return _spawnvef(mode, file, args, env, execve)\r
+\r
+    # Note: spawnvp[e] is't currently supported on Windows\r
+\r
+    def spawnvp(mode, file, args):\r
+        """spawnvp(mode, file, args) -> integer\r
+\r
+Execute file (which is looked for along $PATH) with arguments from\r
+args in a subprocess.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+        return _spawnvef(mode, file, args, None, execvp)\r
+\r
+    def spawnvpe(mode, file, args, env):\r
+        """spawnvpe(mode, file, args, env) -> integer\r
+\r
+Execute file (which is looked for along $PATH) with arguments from\r
+args in a subprocess with the supplied environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+        return _spawnvef(mode, file, args, env, execvpe)\r
+\r
+if _exists("spawnv"):\r
+    # These aren't supplied by the basic Windows code\r
+    # but can be easily implemented in Python\r
+\r
+    def spawnl(mode, file, *args):\r
+        """spawnl(mode, file, *args) -> integer\r
+\r
+Execute file with arguments from args in a subprocess.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+        return spawnv(mode, file, args)\r
+\r
+    def spawnle(mode, file, *args):\r
+        """spawnle(mode, file, *args, env) -> integer\r
+\r
+Execute file with arguments from args in a subprocess with the\r
+supplied environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+        env = args[-1]\r
+        return spawnve(mode, file, args[:-1], env)\r
+\r
+\r
+    __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])\r
+\r
+\r
+if _exists("spawnvp"):\r
+    # At the moment, Windows doesn't implement spawnvp[e],\r
+    # so it won't have spawnlp[e] either.\r
+    def spawnlp(mode, file, *args):\r
+        """spawnlp(mode, file, *args) -> integer\r
+\r
+Execute file (which is looked for along $PATH) with arguments from\r
+args in a subprocess with the supplied environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+        return spawnvp(mode, file, args)\r
+\r
+    def spawnlpe(mode, file, *args):\r
+        """spawnlpe(mode, file, *args, env) -> integer\r
+\r
+Execute file (which is looked for along $PATH) with arguments from\r
+args in a subprocess with the supplied environment.\r
+If mode == P_NOWAIT return the pid of the process.\r
+If mode == P_WAIT return the process's exit code if it exits normally;\r
+otherwise return -SIG, where SIG is the signal that killed it. """\r
+        env = args[-1]\r
+        return spawnvpe(mode, file, args[:-1], env)\r
+\r
+\r
+    __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])\r
+\r
+\r
+# Supply popen2 etc. (for Unix)\r
+if _exists("fork"):\r
+    if not _exists("popen2"):\r
+        def popen2(cmd, mode="t", bufsize=-1):\r
+            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'\r
+            may be a sequence, in which case arguments will be passed directly to\r
+            the program without shell intervention (as with os.spawnv()).  If 'cmd'\r
+            is a string it will be passed to the shell (as with os.system()). If\r
+            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The\r
+            file objects (child_stdin, child_stdout) are returned."""\r
+            import warnings\r
+            msg = "os.popen2 is deprecated.  Use the subprocess module."\r
+            warnings.warn(msg, DeprecationWarning, stacklevel=2)\r
+\r
+            import subprocess\r
+            PIPE = subprocess.PIPE\r
+            p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),\r
+                                 bufsize=bufsize, stdin=PIPE, stdout=PIPE,\r
+                                 close_fds=True)\r
+            return p.stdin, p.stdout\r
+        __all__.append("popen2")\r
+\r
+    if not _exists("popen3"):\r
+        def popen3(cmd, mode="t", bufsize=-1):\r
+            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'\r
+            may be a sequence, in which case arguments will be passed directly to\r
+            the program without shell intervention (as with os.spawnv()).  If 'cmd'\r
+            is a string it will be passed to the shell (as with os.system()). If\r
+            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The\r
+            file objects (child_stdin, child_stdout, child_stderr) are returned."""\r
+            import warnings\r
+            msg = "os.popen3 is deprecated.  Use the subprocess module."\r
+            warnings.warn(msg, DeprecationWarning, stacklevel=2)\r
+\r
+            import subprocess\r
+            PIPE = subprocess.PIPE\r
+            p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),\r
+                                 bufsize=bufsize, stdin=PIPE, stdout=PIPE,\r
+                                 stderr=PIPE, close_fds=True)\r
+            return p.stdin, p.stdout, p.stderr\r
+        __all__.append("popen3")\r
+\r
+    if not _exists("popen4"):\r
+        def popen4(cmd, mode="t", bufsize=-1):\r
+            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'\r
+            may be a sequence, in which case arguments will be passed directly to\r
+            the program without shell intervention (as with os.spawnv()).  If 'cmd'\r
+            is a string it will be passed to the shell (as with os.system()). If\r
+            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The\r
+            file objects (child_stdin, child_stdout_stderr) are returned."""\r
+            import warnings\r
+            msg = "os.popen4 is deprecated.  Use the subprocess module."\r
+            warnings.warn(msg, DeprecationWarning, stacklevel=2)\r
+\r
+            import subprocess\r
+            PIPE = subprocess.PIPE\r
+            p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),\r
+                                 bufsize=bufsize, stdin=PIPE, stdout=PIPE,\r
+                                 stderr=subprocess.STDOUT, close_fds=True)\r
+            return p.stdin, p.stdout\r
+        __all__.append("popen4")\r
+\r
+import copy_reg as _copy_reg\r
+\r
+def _make_stat_result(tup, dict):\r
+    return stat_result(tup, dict)\r
+\r
+def _pickle_stat_result(sr):\r
+    (type, args) = sr.__reduce__()\r
+    return (_make_stat_result, args)\r
+\r
+try:\r
+    _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)\r
+except NameError: # stat_result may not exist\r
+    pass\r
+\r
+def _make_statvfs_result(tup, dict):\r
+    return statvfs_result(tup, dict)\r
+\r
+def _pickle_statvfs_result(sr):\r
+    (type, args) = sr.__reduce__()\r
+    return (_make_statvfs_result, args)\r
+\r
+try:\r
+    _copy_reg.pickle(statvfs_result, _pickle_statvfs_result,\r
+                     _make_statvfs_result)\r
+except NameError: # statvfs_result may not exist\r
+    pass\r
+\r
+if not _exists("urandom"):\r
+    def urandom(n):\r
+        """urandom(n) -> str\r
+\r
+        Return a string of n random bytes suitable for cryptographic use.\r
+\r
+        """\r
+        try:\r
+            _urandomfd = open("/dev/urandom", O_RDONLY)\r
+        except (OSError, IOError):\r
+            raise NotImplementedError("/dev/urandom (or equivalent) not found")\r
+        try:\r
+            bs = b""\r
+            while n > len(bs):\r
+                bs += read(_urandomfd, n - len(bs))\r
+        finally:\r
+            close(_urandomfd)\r
+        return bs\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Lib/site.py b/AppPkg/Applications/Python/PyMod-2.7.2/Lib/site.py
new file mode 100644 (file)
index 0000000..de366e8
--- /dev/null
@@ -0,0 +1,536 @@
+"""Append module search paths for third-party packages to sys.path.\r
+\r
+****************************************************************\r
+* This module is automatically imported during initialization. *\r
+****************************************************************\r
+\r
+This is a UEFI-specific version of site.py.\r
+\r
+In earlier versions of Python (up to 1.5a3), scripts or modules that\r
+needed to use site-specific modules would place ``import site''\r
+somewhere near the top of their code.  Because of the automatic\r
+import, this is no longer necessary (but code that does it still\r
+works).\r
+\r
+This will append site-specific paths to the module search path.  It\r
+starts with sys.prefix and sys.exec_prefix (if different) and appends\r
+lib/python<version>/site-packages as well as lib/site-python.\r
+The resulting directories, if they exist, are appended to sys.path,\r
+and also inspected for path configuration files.\r
+\r
+A path configuration file is a file whose name has the form\r
+<package>.pth; its contents are additional directories (one per line)\r
+to be added to sys.path.  Non-existing directories (or\r
+non-directories) are never added to sys.path; no directory is added to\r
+sys.path more than once.  Blank lines and lines beginning with\r
+'#' are skipped. Lines starting with 'import' are executed.\r
+\r
+For example, suppose sys.prefix and sys.exec_prefix are set to\r
+/Efi/StdLib and there is a directory /Efi/StdLib/lib/python2.7/site-packages\r
+with three subdirectories, foo, bar and spam, and two path\r
+configuration files, foo.pth and bar.pth.  Assume foo.pth contains the\r
+following:\r
+\r
+  # foo package configuration\r
+  foo\r
+  bar\r
+  bletch\r
+\r
+and bar.pth contains:\r
+\r
+  # bar package configuration\r
+  bar\r
+\r
+Then the following directories are added to sys.path, in this order:\r
+\r
+  /Efi/StdLib/lib/python2.7/site-packages/bar\r
+  /Efi/StdLib/lib/python2.7/site-packages/foo\r
+\r
+Note that bletch is omitted because it doesn't exist; bar precedes foo\r
+because bar.pth comes alphabetically before foo.pth; and spam is\r
+omitted because it is not mentioned in either path configuration file.\r
+\r
+After these path manipulations, an attempt is made to import a module\r
+named sitecustomize, which can perform arbitrary additional\r
+site-specific customizations.  If this import fails with an\r
+ImportError exception, it is silently ignored.\r
+\r
+Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>\r
+This program and the accompanying materials are licensed and made available under\r
+the terms and conditions of the BSD License that accompanies this distribution.\r
+The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+"""\r
+\r
+import sys\r
+import os\r
+import __builtin__\r
+import traceback\r
+\r
+# Prefixes for site-packages; add additional prefixes like /usr/local here\r
+PREFIXES = [sys.prefix, sys.exec_prefix]\r
+# Enable per user site-packages directory\r
+# set it to False to disable the feature or True to force the feature\r
+ENABLE_USER_SITE = False\r
+\r
+# for distutils.commands.install\r
+# These values are initialized by the getuserbase() and getusersitepackages()\r
+# functions, through the main() function when Python starts.\r
+USER_SITE = None\r
+USER_BASE = None\r
+\r
+\r
+def makepath(*paths):\r
+    dir = os.path.join(*paths)\r
+    try:\r
+        dir = os.path.abspath(dir)\r
+    except OSError:\r
+        pass\r
+    return dir, os.path.normcase(dir)\r
+\r
+\r
+def abs__file__():\r
+    """Set all module' __file__ attribute to an absolute path"""\r
+    for m in sys.modules.values():\r
+        if hasattr(m, '__loader__'):\r
+            continue   # don't mess with a PEP 302-supplied __file__\r
+        try:\r
+            m.__file__ = os.path.abspath(m.__file__)\r
+        except (AttributeError, OSError):\r
+            pass\r
+\r
+\r
+def removeduppaths():\r
+    """ Remove duplicate entries from sys.path along with making them\r
+    absolute"""\r
+    # This ensures that the initial path provided by the interpreter contains\r
+    # only absolute pathnames, even if we're running from the build directory.\r
+    L = []\r
+    known_paths = set()\r
+    for dir in sys.path:\r
+        # Filter out duplicate paths (on case-insensitive file systems also\r
+        # if they only differ in case); turn relative paths into absolute\r
+        # paths.\r
+        dir, dircase = makepath(dir)\r
+        if not dircase in known_paths:\r
+            L.append(dir)\r
+            known_paths.add(dircase)\r
+    sys.path[:] = L\r
+    return known_paths\r
+\r
+\r
+def _init_pathinfo():\r
+    """Return a set containing all existing directory entries from sys.path"""\r
+    d = set()\r
+    for dir in sys.path:\r
+        try:\r
+            if os.path.isdir(dir):\r
+                dir, dircase = makepath(dir)\r
+                d.add(dircase)\r
+        except TypeError:\r
+            continue\r
+    return d\r
+\r
+\r
+def addpackage(sitedir, name, known_paths):\r
+    """Process a .pth file within the site-packages directory:\r
+       For each line in the file, either combine it with sitedir to a path\r
+       and add that to known_paths, or execute it if it starts with 'import '.\r
+    """\r
+    if known_paths is None:\r
+        _init_pathinfo()\r
+        reset = 1\r
+    else:\r
+        reset = 0\r
+    fullname = os.path.join(sitedir, name)\r
+    try:\r
+        f = open(fullname, "rU")\r
+    except IOError:\r
+        return\r
+    with f:\r
+        for n, line in enumerate(f):\r
+            if line.startswith("#"):\r
+                continue\r
+            try:\r
+                if line.startswith(("import ", "import\t")):\r
+                    exec line\r
+                    continue\r
+                line = line.rstrip()\r
+                dir, dircase = makepath(sitedir, line)\r
+                if not dircase in known_paths and os.path.exists(dir):\r
+                    sys.path.append(dir)\r
+                    known_paths.add(dircase)\r
+            except Exception as err:\r
+                print >>sys.stderr, "Error processing line {:d} of {}:\n".format(\r
+                    n+1, fullname)\r
+                for record in traceback.format_exception(*sys.exc_info()):\r
+                    for line in record.splitlines():\r
+                        print >>sys.stderr, '  '+line\r
+                print >>sys.stderr, "\nRemainder of file ignored"\r
+                break\r
+    if reset:\r
+        known_paths = None\r
+    return known_paths\r
+\r
+\r
+def addsitedir(sitedir, known_paths=None):\r
+    """Add 'sitedir' argument to sys.path if missing and handle .pth files in\r
+    'sitedir'"""\r
+    if known_paths is None:\r
+        known_paths = _init_pathinfo()\r
+        reset = 1\r
+    else:\r
+        reset = 0\r
+    sitedir, sitedircase = makepath(sitedir)\r
+    if not sitedircase in known_paths:\r
+        sys.path.append(sitedir)        # Add path component\r
+    try:\r
+        names = os.listdir(sitedir)\r
+    except os.error:\r
+        return\r
+    dotpth = os.extsep + "pth"\r
+    names = [name for name in names if name.endswith(dotpth)]\r
+    for name in sorted(names):\r
+        addpackage(sitedir, name, known_paths)\r
+    if reset:\r
+        known_paths = None\r
+    return known_paths\r
+\r
+\r
+def check_enableusersite():\r
+    """Check if user site directory is safe for inclusion\r
+\r
+    The function tests for the command line flag (including environment var),\r
+    process uid/gid equal to effective uid/gid.\r
+\r
+    None: Disabled for security reasons\r
+    False: Disabled by user (command line option)\r
+    True: Safe and enabled\r
+    """\r
+    if sys.flags.no_user_site:\r
+        return False\r
+\r
+    if hasattr(os, "getuid") and hasattr(os, "geteuid"):\r
+        # check process uid == effective uid\r
+        if os.geteuid() != os.getuid():\r
+            return None\r
+    if hasattr(os, "getgid") and hasattr(os, "getegid"):\r
+        # check process gid == effective gid\r
+        if os.getegid() != os.getgid():\r
+            return None\r
+\r
+    return True\r
+\r
+def getuserbase():\r
+    """Returns the `user base` directory path.\r
+\r
+    The `user base` directory can be used to store data. If the global\r
+    variable ``USER_BASE`` is not initialized yet, this function will also set\r
+    it.\r
+    """\r
+    global USER_BASE\r
+    if USER_BASE is not None:\r
+        return USER_BASE\r
+    from sysconfig import get_config_var\r
+    USER_BASE = get_config_var('userbase')\r
+    return USER_BASE\r
+\r
+def getusersitepackages():\r
+    """Returns the user-specific site-packages directory path.\r
+\r
+    If the global variable ``USER_SITE`` is not initialized yet, this\r
+    function will also set it.\r
+    """\r
+    global USER_SITE\r
+    user_base = getuserbase() # this will also set USER_BASE\r
+\r
+    if USER_SITE is not None:\r
+        return USER_SITE\r
+\r
+    from sysconfig import get_path\r
+    import os\r
+\r
+    USER_SITE = get_path('purelib', '%s_user' % os.name)\r
+    return USER_SITE\r
+\r
+def addusersitepackages(known_paths):\r
+    """Add a per user site-package to sys.path\r
+\r
+    Each user has its own python directory with site-packages in the\r
+    home directory.\r
+    """\r
+    # get the per user site-package path\r
+    # this call will also make sure USER_BASE and USER_SITE are set\r
+    user_site = getusersitepackages()\r
+\r
+    if ENABLE_USER_SITE and os.path.isdir(user_site):\r
+        addsitedir(user_site, known_paths)\r
+    return known_paths\r
+\r
+def getsitepackages():\r
+    """Returns a list containing all global site-packages directories\r
+    (and possibly site-python).\r
+\r
+    For each directory present in the global ``PREFIXES``, this function\r
+    will find its `site-packages` subdirectory depending on the system\r
+    environment, and will return a list of full paths.\r
+    """\r
+    sitepackages = []\r
+    seen = set()\r
+\r
+    for prefix in PREFIXES:\r
+        if not prefix or prefix in seen:\r
+            continue\r
+        seen.add(prefix)\r
+\r
+        sitepackages.append(os.path.join(prefix, "lib",\r
+                                    "python." + sys.version[0] + sys.version[2],\r
+                                    "site-packages"))\r
+        sitepackages.append(os.path.join(prefix, "lib", "site-python"))\r
+    return sitepackages\r
+\r
+def addsitepackages(known_paths):\r
+    """Add site-packages (and possibly site-python) to sys.path"""\r
+    for sitedir in getsitepackages():\r
+        if os.path.isdir(sitedir):\r
+            addsitedir(sitedir, known_paths)\r
+\r
+    return known_paths\r
+\r
+def setBEGINLIBPATH():\r
+    """The UEFI port has optional extension modules that do double duty\r
+    as DLLs (even though they have .efi file extensions) for other extensions.\r
+    The library search path needs to be amended so these will be found\r
+    during module import.  Use BEGINLIBPATH so that these are at the start\r
+    of the library search path.\r
+\r
+    """\r
+    dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")\r
+    libpath = os.environ['BEGINLIBPATH'].split(os.path.pathsep)\r
+    if libpath[-1]:\r
+        libpath.append(dllpath)\r
+    else:\r
+        libpath[-1] = dllpath\r
+    os.environ['BEGINLIBPATH'] = os.path.pathsep.join(libpath)\r
+\r
+\r
+def setquit():\r
+    """Define new builtins 'quit' and 'exit'.\r
+\r
+    These are objects which make the interpreter exit when called.\r
+    The repr of each object contains a hint at how it works.\r
+\r
+    """\r
+    eof = 'Ctrl-D (i.e. EOF)'\r
+\r
+    class Quitter(object):\r
+        def __init__(self, name):\r
+            self.name = name\r
+        def __repr__(self):\r
+            return 'Use %s() or %s to exit' % (self.name, eof)\r
+        def __call__(self, code=None):\r
+            # Shells like IDLE catch the SystemExit, but listen when their\r
+            # stdin wrapper is closed.\r
+            try:\r
+                sys.stdin.close()\r
+            except:\r
+                pass\r
+            raise SystemExit(code)\r
+    __builtin__.quit = Quitter('quit')\r
+    __builtin__.exit = Quitter('exit')\r
+\r
+\r
+class _Printer(object):\r
+    """interactive prompt objects for printing the license text, a list of\r
+    contributors and the copyright notice."""\r
+\r
+    MAXLINES = 23\r
+\r
+    def __init__(self, name, data, files=(), dirs=()):\r
+        self.__name = name\r
+        self.__data = data\r
+        self.__files = files\r
+        self.__dirs = dirs\r
+        self.__lines = None\r
+\r
+    def __setup(self):\r
+        if self.__lines:\r
+            return\r
+        data = None\r
+        for dir in self.__dirs:\r
+            for filename in self.__files:\r
+                filename = os.path.join(dir, filename)\r
+                try:\r
+                    fp = file(filename, "rU")\r
+                    data = fp.read()\r
+                    fp.close()\r
+                    break\r
+                except IOError:\r
+                    pass\r
+            if data:\r
+                break\r
+        if not data:\r
+            data = self.__data\r
+        self.__lines = data.split('\n')\r
+        self.__linecnt = len(self.__lines)\r
+\r
+    def __repr__(self):\r
+        self.__setup()\r
+        if len(self.__lines) <= self.MAXLINES:\r
+            return "\n".join(self.__lines)\r
+        else:\r
+            return "Type %s() to see the full %s text" % ((self.__name,)*2)\r
+\r
+    def __call__(self):\r
+        self.__setup()\r
+        prompt = 'Hit Return for more, or q (and Return) to quit: '\r
+        lineno = 0\r
+        while 1:\r
+            try:\r
+                for i in range(lineno, lineno + self.MAXLINES):\r
+                    print self.__lines[i]\r
+            except IndexError:\r
+                break\r
+            else:\r
+                lineno += self.MAXLINES\r
+                key = None\r
+                while key is None:\r
+                    key = raw_input(prompt)\r
+                    if key not in ('', 'q'):\r
+                        key = None\r
+                if key == 'q':\r
+                    break\r
+\r
+def setcopyright():\r
+    """Set 'copyright' and 'credits' in __builtin__"""\r
+    __builtin__.copyright = _Printer("copyright", sys.copyright)\r
+    __builtin__.credits = _Printer("credits", """\\r
+    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\r
+    for supporting Python development.  See www.python.org for more information.""")\r
+    here = os.path.dirname(os.__file__)\r
+    __builtin__.license = _Printer(\r
+        "license", "See http://www.python.org/%.3s/license.html" % sys.version,\r
+        ["LICENSE.txt", "LICENSE"],\r
+        [os.path.join(here, os.pardir), here, os.curdir])\r
+\r
+\r
+class _Helper(object):\r
+    """Define the builtin 'help'.\r
+    This is a wrapper around pydoc.help (with a twist).\r
+\r
+    """\r
+\r
+    def __repr__(self):\r
+        return "Type help() for interactive help, " \\r
+               "or help(object) for help about object."\r
+\r
+    def __call__(self, *args, **kwds):\r
+        import pydoc\r
+        return pydoc.help(*args, **kwds)\r
+\r
+def sethelper():\r
+    __builtin__.help = _Helper()\r
+\r
+####\r
+# Keep around for future mbcs support.\r
+####\r
+#def aliasmbcs():\r
+#    """On Windows, some default encodings are not provided by Python,\r
+#    while they are always available as "mbcs" in each locale. Make\r
+#    them usable by aliasing to "mbcs" in such a case."""\r
+#    if sys.platform == 'win32':\r
+#        import locale, codecs\r
+#        enc = locale.getdefaultlocale()[1]\r
+#        if enc.startswith('cp'):            # "cp***" ?\r
+#            try:\r
+#                codecs.lookup(enc)\r
+#            except LookupError:\r
+#                import encodings\r
+#                encodings._cache[enc] = encodings._unknown\r
+#                encodings.aliases.aliases[enc] = 'mbcs'\r
+\r
+def setencoding():\r
+    """Set the string encoding used by the Unicode implementation.  The\r
+    default is 'ascii', but if you're willing to experiment, you can\r
+    change this."""\r
+    encoding = "ascii" # Default value set by _PyUnicode_Init()\r
+    if 0:\r
+        # Enable to support locale aware default string encodings.\r
+        import locale\r
+        loc = locale.getdefaultlocale()\r
+        if loc[1]:\r
+            encoding = loc[1]\r
+    if 0:\r
+        # Enable to switch off string to Unicode coercion and implicit\r
+        # Unicode to string conversion.\r
+        encoding = "undefined"\r
+    if encoding != "ascii":\r
+        # On Non-Unicode builds this will raise an AttributeError...\r
+        sys.setdefaultencoding(encoding) # Needs Python Unicode build !\r
+\r
+\r
+def execsitecustomize():\r
+    """Run custom site specific code, if available."""\r
+    try:\r
+        import sitecustomize\r
+    except ImportError:\r
+        pass\r
+    except Exception:\r
+        if sys.flags.verbose:\r
+            sys.excepthook(*sys.exc_info())\r
+        else:\r
+            print >>sys.stderr, \\r
+                "'import sitecustomize' failed; use -v for traceback"\r
+\r
+\r
+def execusercustomize():\r
+    """Run custom user specific code, if available."""\r
+    try:\r
+        import usercustomize\r
+    except ImportError:\r
+        pass\r
+    except Exception:\r
+        if sys.flags.verbose:\r
+            sys.excepthook(*sys.exc_info())\r
+        else:\r
+            print>>sys.stderr, \\r
+                "'import usercustomize' failed; use -v for traceback"\r
+\r
+\r
+def main():\r
+    abs__file__()\r
+    known_paths = removeduppaths()\r
+    setquit()\r
+    setcopyright()\r
+    sethelper()\r
+#    aliasmbcs()\r
+    setencoding()\r
+    execsitecustomize()\r
+    # Remove sys.setdefaultencoding() so that users cannot change the\r
+    # encoding after initialization.  The test for presence is needed when\r
+    # this module is run as a script, because this code is executed twice.\r
+    if hasattr(sys, "setdefaultencoding"):\r
+        del sys.setdefaultencoding\r
+\r
+main()\r
+\r
+def _script():\r
+    help = """\\r
+    %s\r
+\r
+    Path elements are normally separated by '%s'.\r
+    """\r
+    print "sys.path = ["\r
+    for dir in sys.path:\r
+        print "    %r," % (dir,)\r
+    print "]"\r
+\r
+    import textwrap\r
+    print textwrap.dedent(help % (sys.argv[0], os.pathsep))\r
+    sys.exit(0)\r
+\r
+if __name__ == '__main__':\r
+    _script()\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/errnomodule.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/errnomodule.c
new file mode 100644 (file)
index 0000000..a325389
--- /dev/null
@@ -0,0 +1,845 @@
+\r
+/* Errno module\r
+\r
+    Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>\r
+    This program and the accompanying materials are licensed and made available under\r
+    the terms and conditions of the BSD License that accompanies this distribution.\r
+    The full text of the license may be found at\r
+    http://opensource.org/licenses/bsd-license.\r
+\r
+    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+*/\r
+\r
+#include "Python.h"\r
+\r
+/* Windows socket errors (WSA*)  */\r
+#ifdef MS_WINDOWS\r
+#include <windows.h>\r
+#endif\r
+\r
+/*\r
+ * Pull in the system error definitions\r
+ */\r
+\r
+static PyMethodDef errno_methods[] = {\r
+    {NULL,              NULL}\r
+};\r
+\r
+/* Helper function doing the dictionary inserting */\r
+\r
+static void\r
+_inscode(PyObject *d, PyObject *de, char *name, int code)\r
+{\r
+    PyObject *u = PyString_FromString(name);\r
+    PyObject *v = PyInt_FromLong((long) code);\r
+\r
+    /* Don't bother checking for errors; they'll be caught at the end\r
+     * of the module initialization function by the caller of\r
+     * initerrno().\r
+     */\r
+    if (u && v) {\r
+        /* insert in modules dict */\r
+        PyDict_SetItem(d, u, v);\r
+        /* insert in errorcode dict */\r
+        PyDict_SetItem(de, v, u);\r
+    }\r
+    Py_XDECREF(u);\r
+    Py_XDECREF(v);\r
+}\r
+\r
+PyDoc_STRVAR(errno__doc__,\r
+"This module makes available standard errno system symbols.\n\\r
+\n\\r
+The value of each symbol is the corresponding integer value,\n\\r
+e.g., on most systems, errno.ENOENT equals the integer 2.\n\\r
+\n\\r
+The dictionary errno.errorcode maps numeric codes to symbol names,\n\\r
+e.g., errno.errorcode[2] could be the string 'ENOENT'.\n\\r
+\n\\r
+Symbols that are not relevant to the underlying system are not defined.\n\\r
+\n\\r
+To map error codes to error messages, use the function os.strerror(),\n\\r
+e.g. os.strerror(2) could return 'No such file or directory'.");\r
+\r
+PyMODINIT_FUNC\r
+initerrno(void)\r
+{\r
+    PyObject *m, *d, *de;\r
+    m = Py_InitModule3("errno", errno_methods, errno__doc__);\r
+    if (m == NULL)\r
+        return;\r
+    d = PyModule_GetDict(m);\r
+    de = PyDict_New();\r
+    if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0)\r
+        return;\r
+\r
+/* Macro so I don't have to edit each and every line below... */\r
+#define inscode(d, ds, de, name, code, comment) _inscode(d, de, name, code)\r
+\r
+    /*\r
+     * The names and comments are borrowed from linux/include/errno.h,\r
+     * which should be pretty all-inclusive\r
+     */\r
+\r
+#ifdef ENODEV\r
+    inscode(d, ds, de, "ENODEV", ENODEV, "No such device");\r
+#endif\r
+#ifdef ENOCSI\r
+    inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available");\r
+#endif\r
+#ifdef EHOSTUNREACH\r
+    inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host");\r
+#else\r
+#ifdef WSAEHOSTUNREACH\r
+    inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");\r
+#endif\r
+#endif\r
+#ifdef ENOMSG\r
+    inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type");\r
+#endif\r
+#ifdef EUCLEAN\r
+    inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning");\r
+#endif\r
+#ifdef EL2NSYNC\r
+    inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized");\r
+#endif\r
+#ifdef EL2HLT\r
+    inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted");\r
+#endif\r
+#ifdef ENODATA\r
+    inscode(d, ds, de, "ENODATA", ENODATA, "No data available");\r
+#endif\r
+#ifdef ENOTBLK\r
+    inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required");\r
+#endif\r
+#ifdef ENOSYS\r
+    inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented");\r
+#endif\r
+#ifdef EPIPE\r
+    inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe");\r
+#endif\r
+#ifdef EINVAL\r
+    inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument");\r
+#else\r
+#ifdef WSAEINVAL\r
+    inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument");\r
+#endif\r
+#endif\r
+#ifdef EOVERFLOW\r
+    inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type");\r
+#endif\r
+#ifdef EADV\r
+    inscode(d, ds, de, "EADV", EADV, "Advertise error");\r
+#endif\r
+#ifdef EINTR\r
+    inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call");\r
+#else\r
+#ifdef WSAEINTR\r
+    inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call");\r
+#endif\r
+#endif\r
+#ifdef EUSERS\r
+    inscode(d, ds, de, "EUSERS", EUSERS, "Too many users");\r
+#else\r
+#ifdef WSAEUSERS\r
+    inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users");\r
+#endif\r
+#endif\r
+#ifdef ENOTEMPTY\r
+    inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty");\r
+#else\r
+#ifdef WSAENOTEMPTY\r
+    inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty");\r
+#endif\r
+#endif\r
+#ifdef ENOBUFS\r
+    inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available");\r
+#else\r
+#ifdef WSAENOBUFS\r
+    inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available");\r
+#endif\r
+#endif\r
+#ifdef EPROTO\r
+    inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error");\r
+#endif\r
+#ifdef EREMOTE\r
+    inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote");\r
+#else\r
+#ifdef WSAEREMOTE\r
+    inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote");\r
+#endif\r
+#endif\r
+#ifdef ENAVAIL\r
+    inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available");\r
+#endif\r
+#ifdef ECHILD\r
+    inscode(d, ds, de, "ECHILD", ECHILD, "No child processes");\r
+#endif\r
+#ifdef ELOOP\r
+    inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered");\r
+#else\r
+#ifdef WSAELOOP\r
+    inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered");\r
+#endif\r
+#endif\r
+#ifdef EXDEV\r
+    inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link");\r
+#endif\r
+#ifdef E2BIG\r
+    inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long");\r
+#endif\r
+#ifdef ESRCH\r
+    inscode(d, ds, de, "ESRCH", ESRCH, "No such process");\r
+#endif\r
+#ifdef EMSGSIZE\r
+    inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long");\r
+#else\r
+#ifdef WSAEMSGSIZE\r
+    inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long");\r
+#endif\r
+#endif\r
+#ifdef EAFNOSUPPORT\r
+    inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol");\r
+#else\r
+#ifdef WSAEAFNOSUPPORT\r
+    inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");\r
+#endif\r
+#endif\r
+#ifdef EBADR\r
+    inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor");\r
+#endif\r
+#ifdef EHOSTDOWN\r
+    inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down");\r
+#else\r
+#ifdef WSAEHOSTDOWN\r
+    inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down");\r
+#endif\r
+#endif\r
+#ifdef EPFNOSUPPORT\r
+    inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported");\r
+#else\r
+#ifdef WSAEPFNOSUPPORT\r
+    inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");\r
+#endif\r
+#endif\r
+#ifdef ENOPROTOOPT\r
+    inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available");\r
+#else\r
+#ifdef WSAENOPROTOOPT\r
+    inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");\r
+#endif\r
+#endif\r
+#ifdef EBUSY\r
+    inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy");\r
+#endif\r
+#ifdef EWOULDBLOCK\r
+    inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block");\r
+#else\r
+#ifdef WSAEWOULDBLOCK\r
+    inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");\r
+#endif\r
+#endif\r
+#ifdef EBADFD\r
+    inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state");\r
+#endif\r
+#ifdef EDOTDOT\r
+    inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error");\r
+#endif\r
+#ifdef EISCONN\r
+    inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected");\r
+#else\r
+#ifdef WSAEISCONN\r
+    inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected");\r
+#endif\r
+#endif\r
+#ifdef ENOANO\r
+    inscode(d, ds, de, "ENOANO", ENOANO, "No anode");\r
+#endif\r
+#ifdef ESHUTDOWN\r
+    inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown");\r
+#else\r
+#ifdef WSAESHUTDOWN\r
+    inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");\r
+#endif\r
+#endif\r
+#ifdef ECHRNG\r
+    inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range");\r
+#endif\r
+#ifdef ELIBBAD\r
+    inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library");\r
+#endif\r
+#ifdef ENONET\r
+    inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network");\r
+#endif\r
+#ifdef EBADE\r
+    inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange");\r
+#endif\r
+#ifdef EBADF\r
+    inscode(d, ds, de, "EBADF", EBADF, "Bad file number");\r
+#else\r
+#ifdef WSAEBADF\r
+    inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number");\r
+#endif\r
+#endif\r
+#ifdef EMULTIHOP\r
+    inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted");\r
+#endif\r
+#ifdef EIO\r
+    inscode(d, ds, de, "EIO", EIO, "I/O error");\r
+#endif\r
+#ifdef EUNATCH\r
+    inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached");\r
+#endif\r
+#ifdef EPROTOTYPE\r
+    inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket");\r
+#else\r
+#ifdef WSAEPROTOTYPE\r
+    inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");\r
+#endif\r
+#endif\r
+#ifdef ENOSPC\r
+    inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device");\r
+#endif\r
+#ifdef ENOEXEC\r
+    inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error");\r
+#endif\r
+#ifdef EALREADY\r
+    inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress");\r
+#else\r
+#ifdef WSAEALREADY\r
+    inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress");\r
+#endif\r
+#endif\r
+#ifdef ENETDOWN\r
+    inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down");\r
+#else\r
+#ifdef WSAENETDOWN\r
+    inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down");\r
+#endif\r
+#endif\r
+#ifdef ENOTNAM\r
+    inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file");\r
+#endif\r
+#ifdef EACCES\r
+    inscode(d, ds, de, "EACCES", EACCES, "Permission denied");\r
+#else\r
+#ifdef WSAEACCES\r
+    inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied");\r
+#endif\r
+#endif\r
+#ifdef ELNRNG\r
+    inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range");\r
+#endif\r
+#ifdef EILSEQ\r
+    inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence");\r
+#endif\r
+#ifdef ENOTDIR\r
+    inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory");\r
+#endif\r
+#ifdef ENOTUNIQ\r
+    inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network");\r
+#endif\r
+#ifdef EPERM\r
+    inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted");\r
+#endif\r
+#ifdef EDOM\r
+    inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func");\r
+#endif\r
+#ifdef EXFULL\r
+    inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full");\r
+#endif\r
+#ifdef ECONNREFUSED\r
+    inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused");\r
+#else\r
+#ifdef WSAECONNREFUSED\r
+    inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused");\r
+#endif\r
+#endif\r
+#ifdef EISDIR\r
+    inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory");\r
+#endif\r
+#ifdef EPROTONOSUPPORT\r
+    inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported");\r
+#else\r
+#ifdef WSAEPROTONOSUPPORT\r
+    inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");\r
+#endif\r
+#endif\r
+#ifdef EROFS\r
+    inscode(d, ds, de, "EROFS", EROFS, "Read-only file system");\r
+#endif\r
+#ifdef EADDRNOTAVAIL\r
+    inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address");\r
+#else\r
+#ifdef WSAEADDRNOTAVAIL\r
+    inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");\r
+#endif\r
+#endif\r
+#ifdef EIDRM\r
+    inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed");\r
+#endif\r
+#ifdef ECOMM\r
+    inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send");\r
+#endif\r
+#ifdef ESRMNT\r
+    inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error");\r
+#endif\r
+#ifdef EREMOTEIO\r
+    inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error");\r
+#endif\r
+#ifdef EL3RST\r
+    inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset");\r
+#endif\r
+#ifdef EBADMSG\r
+    inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message");\r
+#endif\r
+#ifdef ENFILE\r
+    inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow");\r
+#endif\r
+#ifdef ELIBMAX\r
+    inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries");\r
+#endif\r
+#ifdef ESPIPE\r
+    inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek");\r
+#endif\r
+#ifdef ENOLINK\r
+    inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed");\r
+#endif\r
+#ifdef ENETRESET\r
+    inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset");\r
+#else\r
+#ifdef WSAENETRESET\r
+    inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset");\r
+#endif\r
+#endif\r
+#ifdef ETIMEDOUT\r
+    inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out");\r
+#else\r
+#ifdef WSAETIMEDOUT\r
+    inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out");\r
+#endif\r
+#endif\r
+#ifdef ENOENT\r
+    inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory");\r
+#endif\r
+#ifdef EEXIST\r
+    inscode(d, ds, de, "EEXIST", EEXIST, "File exists");\r
+#endif\r
+#ifdef EDQUOT\r
+    inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded");\r
+#else\r
+#ifdef WSAEDQUOT\r
+    inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded");\r
+#endif\r
+#endif\r
+#ifdef ENOSTR\r
+    inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream");\r
+#endif\r
+#ifdef EBADSLT\r
+    inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot");\r
+#endif\r
+#ifdef EBADRQC\r
+    inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code");\r
+#endif\r
+#ifdef ELIBACC\r
+    inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library");\r
+#endif\r
+#ifdef EFAULT\r
+    inscode(d, ds, de, "EFAULT", EFAULT, "Bad address");\r
+#else\r
+#ifdef WSAEFAULT\r
+    inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address");\r
+#endif\r
+#endif\r
+#ifdef EFBIG\r
+    inscode(d, ds, de, "EFBIG", EFBIG, "File too large");\r
+#endif\r
+#ifdef EDEADLK\r
+    inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur");\r
+#endif\r
+#ifdef ENOTCONN\r
+    inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected");\r
+#else\r
+#ifdef WSAENOTCONN\r
+    inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");\r
+#endif\r
+#endif\r
+#ifdef EDESTADDRREQ\r
+    inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required");\r
+#else\r
+#ifdef WSAEDESTADDRREQ\r
+    inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");\r
+#endif\r
+#endif\r
+#ifdef ELIBSCN\r
+    inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted");\r
+#endif\r
+#ifdef ENOLCK\r
+    inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available");\r
+#endif\r
+#ifdef EISNAM\r
+    inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file");\r
+#endif\r
+#ifdef ECONNABORTED\r
+    inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort");\r
+#else\r
+#ifdef WSAECONNABORTED\r
+    inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort");\r
+#endif\r
+#endif\r
+#ifdef ENETUNREACH\r
+    inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable");\r
+#else\r
+#ifdef WSAENETUNREACH\r
+    inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable");\r
+#endif\r
+#endif\r
+#ifdef ESTALE\r
+    inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle");\r
+#else\r
+#ifdef WSAESTALE\r
+    inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle");\r
+#endif\r
+#endif\r
+#ifdef ENOSR\r
+    inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources");\r
+#endif\r
+#ifdef ENOMEM\r
+    inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory");\r
+#endif\r
+#ifdef ENOTSOCK\r
+    inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket");\r
+#else\r
+#ifdef WSAENOTSOCK\r
+    inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");\r
+#endif\r
+#endif\r
+#ifdef ESTRPIPE\r
+    inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error");\r
+#endif\r
+#ifdef EMLINK\r
+    inscode(d, ds, de, "EMLINK", EMLINK, "Too many links");\r
+#endif\r
+#ifdef ERANGE\r
+    inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable");\r
+#endif\r
+#ifdef ELIBEXEC\r
+    inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly");\r
+#endif\r
+#ifdef EL3HLT\r
+    inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted");\r
+#endif\r
+#ifdef ECONNRESET\r
+    inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer");\r
+#else\r
+#ifdef WSAECONNRESET\r
+    inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer");\r
+#endif\r
+#endif\r
+#ifdef EADDRINUSE\r
+    inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use");\r
+#else\r
+#ifdef WSAEADDRINUSE\r
+    inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use");\r
+#endif\r
+#endif\r
+#ifdef EOPNOTSUPP\r
+    inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint");\r
+#else\r
+#ifdef WSAEOPNOTSUPP\r
+    inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");\r
+#endif\r
+#endif\r
+#ifdef EREMCHG\r
+    inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed");\r
+#endif\r
+#ifdef EAGAIN\r
+    inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again");\r
+#endif\r
+#ifdef ENAMETOOLONG\r
+    inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long");\r
+#else\r
+#ifdef WSAENAMETOOLONG\r
+    inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long");\r
+#endif\r
+#endif\r
+#ifdef ENOTTY\r
+    inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter");\r
+#endif\r
+#ifdef ERESTART\r
+    inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted");\r
+#endif\r
+#ifdef ESOCKTNOSUPPORT\r
+    inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported");\r
+#else\r
+#ifdef WSAESOCKTNOSUPPORT\r
+    inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");\r
+#endif\r
+#endif\r
+#ifdef ETIME\r
+    inscode(d, ds, de, "ETIME", ETIME, "Timer expired");\r
+#endif\r
+#ifdef EBFONT\r
+    inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format");\r
+#endif\r
+#ifdef EDEADLOCK\r
+    inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK");\r
+#endif\r
+#ifdef ETOOMANYREFS\r
+    inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice");\r
+#else\r
+#ifdef WSAETOOMANYREFS\r
+    inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");\r
+#endif\r
+#endif\r
+#ifdef EMFILE\r
+    inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files");\r
+#else\r
+#ifdef WSAEMFILE\r
+    inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files");\r
+#endif\r
+#endif\r
+#ifdef ETXTBSY\r
+    inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy");\r
+#endif\r
+#ifdef EINPROGRESS\r
+    inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress");\r
+#else\r
+#ifdef WSAEINPROGRESS\r
+    inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress");\r
+#endif\r
+#endif\r
+#ifdef ENXIO\r
+    inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address");\r
+#endif\r
+#ifdef ENOPKG\r
+    inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed");\r
+#endif\r
+#ifdef WSASY\r
+    inscode(d, ds, de, "WSASY", WSASY, "Error WSASY");\r
+#endif\r
+#ifdef WSAEHOSTDOWN\r
+    inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down");\r
+#endif\r
+#ifdef WSAENETDOWN\r
+    inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down");\r
+#endif\r
+#ifdef WSAENOTSOCK\r
+    inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");\r
+#endif\r
+#ifdef WSAEHOSTUNREACH\r
+    inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");\r
+#endif\r
+#ifdef WSAELOOP\r
+    inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered");\r
+#endif\r
+#ifdef WSAEMFILE\r
+    inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files");\r
+#endif\r
+#ifdef WSAESTALE\r
+    inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle");\r
+#endif\r
+#ifdef WSAVERNOTSUPPORTED\r
+    inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED");\r
+#endif\r
+#ifdef WSAENETUNREACH\r
+    inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable");\r
+#endif\r
+#ifdef WSAEPROCLIM\r
+    inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM");\r
+#endif\r
+#ifdef WSAEFAULT\r
+    inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address");\r
+#endif\r
+#ifdef WSANOTINITIALISED\r
+    inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED");\r
+#endif\r
+#ifdef WSAEUSERS\r
+    inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users");\r
+#endif\r
+#ifdef WSAMAKEASYNCREPL\r
+    inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL");\r
+#endif\r
+#ifdef WSAENOPROTOOPT\r
+    inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");\r
+#endif\r
+#ifdef WSAECONNABORTED\r
+    inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort");\r
+#endif\r
+#ifdef WSAENAMETOOLONG\r
+    inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long");\r
+#endif\r
+#ifdef WSAENOTEMPTY\r
+    inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty");\r
+#endif\r
+#ifdef WSAESHUTDOWN\r
+    inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");\r
+#endif\r
+#ifdef WSAEAFNOSUPPORT\r
+    inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");\r
+#endif\r
+#ifdef WSAETOOMANYREFS\r
+    inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");\r
+#endif\r
+#ifdef WSAEACCES\r
+    inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied");\r
+#endif\r
+#ifdef WSATR\r
+    inscode(d, ds, de, "WSATR", WSATR, "Error WSATR");\r
+#endif\r
+#ifdef WSABASEERR\r
+    inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR");\r
+#endif\r
+#ifdef WSADESCRIPTIO\r
+    inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO");\r
+#endif\r
+#ifdef WSAEMSGSIZE\r
+    inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long");\r
+#endif\r
+#ifdef WSAEBADF\r
+    inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number");\r
+#endif\r
+#ifdef WSAECONNRESET\r
+    inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer");\r
+#endif\r
+#ifdef WSAGETSELECTERRO\r
+    inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO");\r
+#endif\r
+#ifdef WSAETIMEDOUT\r
+    inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out");\r
+#endif\r
+#ifdef WSAENOBUFS\r
+    inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available");\r
+#endif\r
+#ifdef WSAEDISCON\r
+    inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON");\r
+#endif\r
+#ifdef WSAEINTR\r
+    inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call");\r
+#endif\r
+#ifdef WSAEPROTOTYPE\r
+    inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");\r
+#endif\r
+#ifdef WSAHOS\r
+    inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS");\r
+#endif\r
+#ifdef WSAEADDRINUSE\r
+    inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use");\r
+#endif\r
+#ifdef WSAEADDRNOTAVAIL\r
+    inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");\r
+#endif\r
+#ifdef WSAEALREADY\r
+    inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress");\r
+#endif\r
+#ifdef WSAEPROTONOSUPPORT\r
+    inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");\r
+#endif\r
+#ifdef WSASYSNOTREADY\r
+    inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY");\r
+#endif\r
+#ifdef WSAEWOULDBLOCK\r
+    inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");\r
+#endif\r
+#ifdef WSAEPFNOSUPPORT\r
+    inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");\r
+#endif\r
+#ifdef WSAEOPNOTSUPP\r
+    inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");\r
+#endif\r
+#ifdef WSAEISCONN\r
+    inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected");\r
+#endif\r
+#ifdef WSAEDQUOT\r
+    inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded");\r
+#endif\r
+#ifdef WSAENOTCONN\r
+    inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");\r
+#endif\r
+#ifdef WSAEREMOTE\r
+    inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote");\r
+#endif\r
+#ifdef WSAEINVAL\r
+    inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument");\r
+#endif\r
+#ifdef WSAEINPROGRESS\r
+    inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress");\r
+#endif\r
+#ifdef WSAGETSELECTEVEN\r
+    inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN");\r
+#endif\r
+#ifdef WSAESOCKTNOSUPPORT\r
+    inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");\r
+#endif\r
+#ifdef WSAGETASYNCERRO\r
+    inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO");\r
+#endif\r
+#ifdef WSAMAKESELECTREPL\r
+    inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL");\r
+#endif\r
+#ifdef WSAGETASYNCBUFLE\r
+    inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE");\r
+#endif\r
+#ifdef WSAEDESTADDRREQ\r
+    inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");\r
+#endif\r
+#ifdef WSAECONNREFUSED\r
+    inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused");\r
+#endif\r
+#ifdef WSAENETRESET\r
+    inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset");\r
+#endif\r
+#ifdef WSAN\r
+    inscode(d, ds, de, "WSAN", WSAN, "Error WSAN");\r
+#endif\r
+\r
+/* These symbols are added for EDK II support.  */\r
+#ifdef EMINERRORVAL\r
+  inscode(d, ds, de, "EMINERRORVAL", EMINERRORVAL, "Lowest valid error value");\r
+#endif\r
+#ifdef ENOTSUP\r
+  inscode(d, ds, de, "ENOTSUP", ENOTSUP, "Operation not supported");\r
+#endif\r
+#ifdef EBADRPC\r
+  inscode(d, ds, de, "EBADRPC", EBADRPC, "RPC struct is bad");\r
+#endif\r
+#ifdef ERPCMISMATCH\r
+  inscode(d, ds, de, "ERPCMISMATCH", ERPCMISMATCH, "RPC version wrong");\r
+#endif\r
+#ifdef EPROGUNAVAIL\r
+  inscode(d, ds, de, "EPROGUNAVAIL", EPROGUNAVAIL, "RPC prog. not avail");\r
+#endif\r
+#ifdef EPROGMISMATCH\r
+  inscode(d, ds, de, "EPROGMISMATCH", EPROGMISMATCH, "Program version wrong");\r
+#endif\r
+#ifdef EPROCUNAVAIL\r
+  inscode(d, ds, de, "EPROCUNAVAIL", EPROCUNAVAIL, "Bad procedure for program");\r
+#endif\r
+#ifdef EFTYPE\r
+  inscode(d, ds, de, "EFTYPE", EFTYPE, "Inappropriate file type or format");\r
+#endif\r
+#ifdef EAUTH\r
+  inscode(d, ds, de, "EAUTH", EAUTH, "Authentication error");\r
+#endif\r
+#ifdef ENEEDAUTH\r
+  inscode(d, ds, de, "ENEEDAUTH", ENEEDAUTH, "Need authenticator");\r
+#endif\r
+#ifdef ECANCELED\r
+  inscode(d, ds, de, "ECANCELED", ECANCELED, "Operation canceled");\r
+#endif\r
+#ifdef ENOATTR\r
+  inscode(d, ds, de, "ENOATTR", ENOATTR, "Attribute not found");\r
+#endif\r
+#ifdef EDOOFUS\r
+  inscode(d, ds, de, "EDOOFUS", EDOOFUS, "Programming Error");\r
+#endif\r
+#ifdef EBUFSIZE\r
+  inscode(d, ds, de, "EBUFSIZE", EBUFSIZE, "Buffer too small to hold result");\r
+#endif\r
+#ifdef EMAXERRORVAL\r
+  inscode(d, ds, de, "EMAXERRORVAL", EMAXERRORVAL, "One more than the highest defined error value");\r
+#endif\r
+\r
+    Py_DECREF(de);\r
+}\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/selectmodule.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/selectmodule.c
new file mode 100644 (file)
index 0000000..d1fe57c
--- /dev/null
@@ -0,0 +1,1912 @@
+/* select - Module containing unix select(2) call.\r
+   Under Unix, the file descriptors are small integers.\r
+   Under Win32, select only exists for sockets, and sockets may\r
+   have any value except INVALID_SOCKET.\r
+   Under BeOS, we suffer the same dichotomy as Win32; sockets can be anything\r
+   >= 0.\r
+*/\r
+\r
+#include "Python.h"\r
+#include <structmember.h>\r
+\r
+#ifdef __APPLE__\r
+    /* Perform runtime testing for a broken poll on OSX to make it easier\r
+     * to use the same binary on multiple releases of the OS.\r
+     */\r
+#undef HAVE_BROKEN_POLL\r
+#endif\r
+\r
+/* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.\r
+   64 is too small (too many people have bumped into that limit).\r
+   Here we boost it.\r
+   Users who want even more than the boosted limit should #define\r
+   FD_SETSIZE higher before this; e.g., via compiler /D switch.\r
+*/\r
+#if defined(MS_WINDOWS) && !defined(FD_SETSIZE)\r
+#define FD_SETSIZE 512\r
+#endif\r
+\r
+#if defined(HAVE_POLL_H)\r
+#include <poll.h>\r
+#elif defined(HAVE_SYS_POLL_H)\r
+#include <sys/poll.h>\r
+#endif\r
+\r
+#ifdef __sgi\r
+/* This is missing from unistd.h */\r
+extern void bzero(void *, int);\r
+#endif\r
+\r
+#ifdef HAVE_SYS_TYPES_H\r
+#include <sys/types.h>\r
+#endif\r
+\r
+#if defined(PYOS_OS2) && !defined(PYCC_GCC)\r
+#include <sys/time.h>\r
+#include <utils.h>\r
+#endif\r
+\r
+#ifdef MS_WINDOWS\r
+#  include <winsock2.h>\r
+#else\r
+#  define SOCKET int\r
+#  ifdef __BEOS__\r
+#    include <net/socket.h>\r
+#  elif defined(__VMS)\r
+#    include <socket.h>\r
+#  endif\r
+#endif\r
+\r
+static PyObject *SelectError;\r
+\r
+/* list of Python objects and their file descriptor */\r
+typedef struct {\r
+    PyObject *obj;                           /* owned reference */\r
+    SOCKET fd;\r
+    int sentinel;                            /* -1 == sentinel */\r
+} pylist;\r
+\r
+static void\r
+reap_obj(pylist fd2obj[FD_SETSIZE + 1])\r
+{\r
+    int i;\r
+    for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {\r
+        Py_XDECREF(fd2obj[i].obj);\r
+        fd2obj[i].obj = NULL;\r
+    }\r
+    fd2obj[0].sentinel = -1;\r
+}\r
+\r
+\r
+/* returns -1 and sets the Python exception if an error occurred, otherwise\r
+   returns a number >= 0\r
+*/\r
+static int\r
+seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])\r
+{\r
+    int i;\r
+    int max = -1;\r
+    int index = 0;\r
+    int len = -1;\r
+    PyObject* fast_seq = NULL;\r
+    PyObject* o = NULL;\r
+\r
+    fd2obj[0].obj = (PyObject*)0;            /* set list to zero size */\r
+    FD_ZERO(set);\r
+\r
+    fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");\r
+    if (!fast_seq)\r
+        return -1;\r
+\r
+    len = PySequence_Fast_GET_SIZE(fast_seq);\r
+\r
+    for (i = 0; i < len; i++)  {\r
+        SOCKET v;\r
+\r
+        /* any intervening fileno() calls could decr this refcnt */\r
+        if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))\r
+            return -1;\r
+\r
+        Py_INCREF(o);\r
+        v = PyObject_AsFileDescriptor( o );\r
+        if (v == -1) goto finally;\r
+\r
+#if defined(_MSC_VER) && !defined(UEFI_ENV)\r
+        max = 0;                             /* not used for Win32 */\r
+#else  /* !_MSC_VER */\r
+        if (v < 0 || v >= FD_SETSIZE) {\r
+            PyErr_SetString(PyExc_ValueError,\r
+                        "filedescriptor out of range in select()");\r
+            goto finally;\r
+        }\r
+        if (v > max)\r
+            max = v;\r
+#endif /* _MSC_VER */\r
+        FD_SET(v, set);\r
+\r
+        /* add object and its file descriptor to the list */\r
+        if (index >= FD_SETSIZE) {\r
+            PyErr_SetString(PyExc_ValueError,\r
+                          "too many file descriptors in select()");\r
+            goto finally;\r
+        }\r
+        fd2obj[index].obj = o;\r
+        fd2obj[index].fd = v;\r
+        fd2obj[index].sentinel = 0;\r
+        fd2obj[++index].sentinel = -1;\r
+    }\r
+    Py_DECREF(fast_seq);\r
+    return max+1;\r
+\r
+  finally:\r
+    Py_XDECREF(o);\r
+    Py_DECREF(fast_seq);\r
+    return -1;\r
+}\r
+\r
+/* returns NULL and sets the Python exception if an error occurred */\r
+static PyObject *\r
+set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])\r
+{\r
+    int i, j, count=0;\r
+    PyObject *list, *o;\r
+    SOCKET fd;\r
+\r
+    for (j = 0; fd2obj[j].sentinel >= 0; j++) {\r
+        if (FD_ISSET(fd2obj[j].fd, set))\r
+            count++;\r
+    }\r
+    list = PyList_New(count);\r
+    if (!list)\r
+        return NULL;\r
+\r
+    i = 0;\r
+    for (j = 0; fd2obj[j].sentinel >= 0; j++) {\r
+        fd = fd2obj[j].fd;\r
+        if (FD_ISSET(fd, set)) {\r
+#if !defined(_MSC_VER) || defined(UEFI_ENV)\r
+            if (fd > FD_SETSIZE) {\r
+                PyErr_SetString(PyExc_SystemError,\r
+               "filedescriptor out of range returned in select()");\r
+                goto finally;\r
+            }\r
+#endif\r
+            o = fd2obj[j].obj;\r
+            fd2obj[j].obj = NULL;\r
+            /* transfer ownership */\r
+            if (PyList_SetItem(list, i, o) < 0)\r
+                goto finally;\r
+\r
+            i++;\r
+        }\r
+    }\r
+    return list;\r
+  finally:\r
+    Py_DECREF(list);\r
+    return NULL;\r
+}\r
+\r
+#undef SELECT_USES_HEAP\r
+#if FD_SETSIZE > 1024\r
+#define SELECT_USES_HEAP\r
+#endif /* FD_SETSIZE > 1024 */\r
+\r
+static PyObject *\r
+select_select(PyObject *self, PyObject *args)\r
+{\r
+#ifdef SELECT_USES_HEAP\r
+    pylist *rfd2obj, *wfd2obj, *efd2obj;\r
+#else  /* !SELECT_USES_HEAP */\r
+    /* XXX: All this should probably be implemented as follows:\r
+     * - find the highest descriptor we're interested in\r
+     * - add one\r
+     * - that's the size\r
+     * See: Stevens, APitUE, $12.5.1\r
+     */\r
+    pylist rfd2obj[FD_SETSIZE + 1];\r
+    pylist wfd2obj[FD_SETSIZE + 1];\r
+    pylist efd2obj[FD_SETSIZE + 1];\r
+#endif /* SELECT_USES_HEAP */\r
+    PyObject *ifdlist, *ofdlist, *efdlist;\r
+    PyObject *ret = NULL;\r
+    PyObject *tout = Py_None;\r
+    fd_set ifdset, ofdset, efdset;\r
+    double timeout;\r
+    struct timeval tv, *tvp;\r
+    long seconds;\r
+    int imax, omax, emax, max;\r
+    int n;\r
+\r
+    /* convert arguments */\r
+    if (!PyArg_UnpackTuple(args, "select", 3, 4,\r
+                          &ifdlist, &ofdlist, &efdlist, &tout))\r
+        return NULL;\r
+\r
+    if (tout == Py_None)\r
+        tvp = (struct timeval *)0;\r
+    else if (!PyNumber_Check(tout)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "timeout must be a float or None");\r
+        return NULL;\r
+    }\r
+    else {\r
+        timeout = PyFloat_AsDouble(tout);\r
+        if (timeout == -1 && PyErr_Occurred())\r
+            return NULL;\r
+        if (timeout > (double)LONG_MAX) {\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "timeout period too long");\r
+            return NULL;\r
+        }\r
+        seconds = (long)timeout;\r
+        timeout = timeout - (double)seconds;\r
+        tv.tv_sec = seconds;\r
+        tv.tv_usec = (long)(timeout * 1E6);\r
+        tvp = &tv;\r
+    }\r
+\r
+\r
+#ifdef SELECT_USES_HEAP\r
+    /* Allocate memory for the lists */\r
+    rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);\r
+    wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);\r
+    efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);\r
+    if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {\r
+        if (rfd2obj) PyMem_DEL(rfd2obj);\r
+        if (wfd2obj) PyMem_DEL(wfd2obj);\r
+        if (efd2obj) PyMem_DEL(efd2obj);\r
+        return PyErr_NoMemory();\r
+    }\r
+#endif /* SELECT_USES_HEAP */\r
+    /* Convert sequences to fd_sets, and get maximum fd number\r
+     * propagates the Python exception set in seq2set()\r
+     */\r
+    rfd2obj[0].sentinel = -1;\r
+    wfd2obj[0].sentinel = -1;\r
+    efd2obj[0].sentinel = -1;\r
+    if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)\r
+        goto finally;\r
+    if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)\r
+        goto finally;\r
+    if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)\r
+        goto finally;\r
+    max = imax;\r
+    if (omax > max) max = omax;\r
+    if (emax > max) max = emax;\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    n = select(max, &ifdset, &ofdset, &efdset, tvp);\r
+    Py_END_ALLOW_THREADS\r
+\r
+#ifdef MS_WINDOWS\r
+    if (n == SOCKET_ERROR) {\r
+        PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());\r
+    }\r
+#else\r
+    if (n < 0) {\r
+        PyErr_SetFromErrno(SelectError);\r
+    }\r
+#endif\r
+    else {\r
+        /* any of these three calls can raise an exception.  it's more\r
+           convenient to test for this after all three calls... but\r
+           is that acceptable?\r
+        */\r
+        ifdlist = set2list(&ifdset, rfd2obj);\r
+        ofdlist = set2list(&ofdset, wfd2obj);\r
+        efdlist = set2list(&efdset, efd2obj);\r
+        if (PyErr_Occurred())\r
+            ret = NULL;\r
+        else\r
+            ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);\r
+\r
+        Py_DECREF(ifdlist);\r
+        Py_DECREF(ofdlist);\r
+        Py_DECREF(efdlist);\r
+    }\r
+\r
+  finally:\r
+    reap_obj(rfd2obj);\r
+    reap_obj(wfd2obj);\r
+    reap_obj(efd2obj);\r
+#ifdef SELECT_USES_HEAP\r
+    PyMem_DEL(rfd2obj);\r
+    PyMem_DEL(wfd2obj);\r
+    PyMem_DEL(efd2obj);\r
+#endif /* SELECT_USES_HEAP */\r
+    return ret;\r
+}\r
+\r
+#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)\r
+/*\r
+ * poll() support\r
+ */\r
+\r
+typedef struct {\r
+    PyObject_HEAD\r
+    PyObject *dict;\r
+    int ufd_uptodate;\r
+    int ufd_len;\r
+    struct pollfd *ufds;\r
+} pollObject;\r
+\r
+static PyTypeObject poll_Type;\r
+\r
+/* Update the malloc'ed array of pollfds to match the dictionary\r
+   contained within a pollObject.  Return 1 on success, 0 on an error.\r
+*/\r
+\r
+static int\r
+update_ufd_array(pollObject *self)\r
+{\r
+    Py_ssize_t i, pos;\r
+    PyObject *key, *value;\r
+    struct pollfd *old_ufds = self->ufds;\r
+\r
+    self->ufd_len = PyDict_Size(self->dict);\r
+    PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);\r
+    if (self->ufds == NULL) {\r
+        self->ufds = old_ufds;\r
+        PyErr_NoMemory();\r
+        return 0;\r
+    }\r
+\r
+    i = pos = 0;\r
+    while (PyDict_Next(self->dict, &pos, &key, &value)) {\r
+        self->ufds[i].fd = PyInt_AsLong(key);\r
+        self->ufds[i].events = (short)PyInt_AsLong(value);\r
+        i++;\r
+    }\r
+    self->ufd_uptodate = 1;\r
+    return 1;\r
+}\r
+\r
+PyDoc_STRVAR(poll_register_doc,\r
+"register(fd [, eventmask] ) -> None\n\n\\r
+Register a file descriptor with the polling object.\n\\r
+fd -- either an integer, or an object with a fileno() method returning an\n\\r
+      int.\n\\r
+events -- an optional bitmask describing the type of events to check for");\r
+\r
+static PyObject *\r
+poll_register(pollObject *self, PyObject *args)\r
+{\r
+    PyObject *o, *key, *value;\r
+    int fd, events = POLLIN | POLLPRI | POLLOUT;\r
+    int err;\r
+\r
+    if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {\r
+        return NULL;\r
+    }\r
+\r
+    fd = PyObject_AsFileDescriptor(o);\r
+    if (fd == -1) return NULL;\r
+\r
+    /* Add entry to the internal dictionary: the key is the\r
+       file descriptor, and the value is the event mask. */\r
+    key = PyInt_FromLong(fd);\r
+    if (key == NULL)\r
+        return NULL;\r
+    value = PyInt_FromLong(events);\r
+    if (value == NULL) {\r
+        Py_DECREF(key);\r
+        return NULL;\r
+    }\r
+    err = PyDict_SetItem(self->dict, key, value);\r
+    Py_DECREF(key);\r
+    Py_DECREF(value);\r
+    if (err < 0)\r
+        return NULL;\r
+\r
+    self->ufd_uptodate = 0;\r
+\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+PyDoc_STRVAR(poll_modify_doc,\r
+"modify(fd, eventmask) -> None\n\n\\r
+Modify an already registered file descriptor.\n\\r
+fd -- either an integer, or an object with a fileno() method returning an\n\\r
+      int.\n\\r
+events -- an optional bitmask describing the type of events to check for");\r
+\r
+static PyObject *\r
+poll_modify(pollObject *self, PyObject *args)\r
+{\r
+    PyObject *o, *key, *value;\r
+    int fd, events;\r
+    int err;\r
+\r
+    if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) {\r
+        return NULL;\r
+    }\r
+\r
+    fd = PyObject_AsFileDescriptor(o);\r
+    if (fd == -1) return NULL;\r
+\r
+    /* Modify registered fd */\r
+    key = PyInt_FromLong(fd);\r
+    if (key == NULL)\r
+        return NULL;\r
+    if (PyDict_GetItem(self->dict, key) == NULL) {\r
+        errno = ENOENT;\r
+        PyErr_SetFromErrno(PyExc_IOError);\r
+        return NULL;\r
+    }\r
+    value = PyInt_FromLong(events);\r
+    if (value == NULL) {\r
+        Py_DECREF(key);\r
+        return NULL;\r
+    }\r
+    err = PyDict_SetItem(self->dict, key, value);\r
+    Py_DECREF(key);\r
+    Py_DECREF(value);\r
+    if (err < 0)\r
+        return NULL;\r
+\r
+    self->ufd_uptodate = 0;\r
+\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+\r
+PyDoc_STRVAR(poll_unregister_doc,\r
+"unregister(fd) -> None\n\n\\r
+Remove a file descriptor being tracked by the polling object.");\r
+\r
+static PyObject *\r
+poll_unregister(pollObject *self, PyObject *o)\r
+{\r
+    PyObject *key;\r
+    int fd;\r
+\r
+    fd = PyObject_AsFileDescriptor( o );\r
+    if (fd == -1)\r
+        return NULL;\r
+\r
+    /* Check whether the fd is already in the array */\r
+    key = PyInt_FromLong(fd);\r
+    if (key == NULL)\r
+        return NULL;\r
+\r
+    if (PyDict_DelItem(self->dict, key) == -1) {\r
+        Py_DECREF(key);\r
+        /* This will simply raise the KeyError set by PyDict_DelItem\r
+           if the file descriptor isn't registered. */\r
+        return NULL;\r
+    }\r
+\r
+    Py_DECREF(key);\r
+    self->ufd_uptodate = 0;\r
+\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+PyDoc_STRVAR(poll_poll_doc,\r
+"poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\\r
+Polls the set of registered file descriptors, returning a list containing \n\\r
+any descriptors that have events or errors to report.");\r
+\r
+static PyObject *\r
+poll_poll(pollObject *self, PyObject *args)\r
+{\r
+    PyObject *result_list = NULL, *tout = NULL;\r
+    int timeout = 0, poll_result, i, j;\r
+    PyObject *value = NULL, *num = NULL;\r
+\r
+    if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {\r
+        return NULL;\r
+    }\r
+\r
+    /* Check values for timeout */\r
+    if (tout == NULL || tout == Py_None)\r
+        timeout = -1;\r
+    else if (!PyNumber_Check(tout)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "timeout must be an integer or None");\r
+        return NULL;\r
+    }\r
+    else {\r
+        tout = PyNumber_Int(tout);\r
+        if (!tout)\r
+            return NULL;\r
+        timeout = PyInt_AsLong(tout);\r
+        Py_DECREF(tout);\r
+        if (timeout == -1 && PyErr_Occurred())\r
+            return NULL;\r
+    }\r
+\r
+    /* Ensure the ufd array is up to date */\r
+    if (!self->ufd_uptodate)\r
+        if (update_ufd_array(self) == 0)\r
+            return NULL;\r
+\r
+    /* call poll() */\r
+    Py_BEGIN_ALLOW_THREADS\r
+    poll_result = poll(self->ufds, self->ufd_len, timeout);\r
+    Py_END_ALLOW_THREADS\r
+\r
+    if (poll_result < 0) {\r
+        PyErr_SetFromErrno(SelectError);\r
+        return NULL;\r
+    }\r
+\r
+    /* build the result list */\r
+\r
+    result_list = PyList_New(poll_result);\r
+    if (!result_list)\r
+        return NULL;\r
+    else {\r
+        for (i = 0, j = 0; j < poll_result; j++) {\r
+            /* skip to the next fired descriptor */\r
+            while (!self->ufds[i].revents) {\r
+                i++;\r
+            }\r
+            /* if we hit a NULL return, set value to NULL\r
+               and break out of loop; code at end will\r
+               clean up result_list */\r
+            value = PyTuple_New(2);\r
+            if (value == NULL)\r
+                goto error;\r
+            num = PyInt_FromLong(self->ufds[i].fd);\r
+            if (num == NULL) {\r
+                Py_DECREF(value);\r
+                goto error;\r
+            }\r
+            PyTuple_SET_ITEM(value, 0, num);\r
+\r
+            /* The &0xffff is a workaround for AIX.  'revents'\r
+               is a 16-bit short, and IBM assigned POLLNVAL\r
+               to be 0x8000, so the conversion to int results\r
+               in a negative number. See SF bug #923315. */\r
+            num = PyInt_FromLong(self->ufds[i].revents & 0xffff);\r
+            if (num == NULL) {\r
+                Py_DECREF(value);\r
+                goto error;\r
+            }\r
+            PyTuple_SET_ITEM(value, 1, num);\r
+            if ((PyList_SetItem(result_list, j, value)) == -1) {\r
+                Py_DECREF(value);\r
+                goto error;\r
+            }\r
+            i++;\r
+        }\r
+    }\r
+    return result_list;\r
+\r
+  error:\r
+    Py_DECREF(result_list);\r
+    return NULL;\r
+}\r
+\r
+static PyMethodDef poll_methods[] = {\r
+    {"register",        (PyCFunction)poll_register,\r
+     METH_VARARGS,  poll_register_doc},\r
+    {"modify",          (PyCFunction)poll_modify,\r
+     METH_VARARGS,  poll_modify_doc},\r
+    {"unregister",      (PyCFunction)poll_unregister,\r
+     METH_O,        poll_unregister_doc},\r
+    {"poll",            (PyCFunction)poll_poll,\r
+     METH_VARARGS,  poll_poll_doc},\r
+    {NULL,              NULL}           /* sentinel */\r
+};\r
+\r
+static pollObject *\r
+newPollObject(void)\r
+{\r
+    pollObject *self;\r
+    self = PyObject_New(pollObject, &poll_Type);\r
+    if (self == NULL)\r
+        return NULL;\r
+    /* ufd_uptodate is a Boolean, denoting whether the\r
+       array pointed to by ufds matches the contents of the dictionary. */\r
+    self->ufd_uptodate = 0;\r
+    self->ufds = NULL;\r
+    self->dict = PyDict_New();\r
+    if (self->dict == NULL) {\r
+        Py_DECREF(self);\r
+        return NULL;\r
+    }\r
+    return self;\r
+}\r
+\r
+static void\r
+poll_dealloc(pollObject *self)\r
+{\r
+    if (self->ufds != NULL)\r
+        PyMem_DEL(self->ufds);\r
+    Py_XDECREF(self->dict);\r
+    PyObject_Del(self);\r
+}\r
+\r
+static PyObject *\r
+poll_getattr(pollObject *self, char *name)\r
+{\r
+    return Py_FindMethod(poll_methods, (PyObject *)self, name);\r
+}\r
+\r
+static PyTypeObject poll_Type = {\r
+    /* The ob_type field must be initialized in the module init function\r
+     * to be portable to Windows without using C++. */\r
+    PyVarObject_HEAD_INIT(NULL, 0)\r
+    "select.poll",              /*tp_name*/\r
+    sizeof(pollObject),         /*tp_basicsize*/\r
+    0,                          /*tp_itemsize*/\r
+    /* methods */\r
+    (destructor)poll_dealloc, /*tp_dealloc*/\r
+    0,                          /*tp_print*/\r
+    (getattrfunc)poll_getattr, /*tp_getattr*/\r
+    0,                      /*tp_setattr*/\r
+    0,                          /*tp_compare*/\r
+    0,                          /*tp_repr*/\r
+    0,                          /*tp_as_number*/\r
+    0,                          /*tp_as_sequence*/\r
+    0,                          /*tp_as_mapping*/\r
+    0,                          /*tp_hash*/\r
+};\r
+\r
+PyDoc_STRVAR(poll_doc,\r
+"Returns a polling object, which supports registering and\n\\r
+unregistering file descriptors, and then polling them for I/O events.");\r
+\r
+static PyObject *\r
+select_poll(PyObject *self, PyObject *unused)\r
+{\r
+    return (PyObject *)newPollObject();\r
+}\r
+\r
+#ifdef __APPLE__\r
+/*\r
+ * On some systems poll() sets errno on invalid file descriptors. We test\r
+ * for this at runtime because this bug may be fixed or introduced between\r
+ * OS releases.\r
+ */\r
+static int select_have_broken_poll(void)\r
+{\r
+    int poll_test;\r
+    int filedes[2];\r
+\r
+    struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };\r
+\r
+    /* Create a file descriptor to make invalid */\r
+    if (pipe(filedes) < 0) {\r
+        return 1;\r
+    }\r
+    poll_struct.fd = filedes[0];\r
+    close(filedes[0]);\r
+    close(filedes[1]);\r
+    poll_test = poll(&poll_struct, 1, 0);\r
+    if (poll_test < 0) {\r
+        return 1;\r
+    } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {\r
+        return 1;\r
+    }\r
+    return 0;\r
+}\r
+#endif /* __APPLE__ */\r
+\r
+#endif /* HAVE_POLL */\r
+\r
+#ifdef HAVE_EPOLL\r
+/* **************************************************************************\r
+ *                      epoll interface for Linux 2.6\r
+ *\r
+ * Written by Christian Heimes\r
+ * Inspired by Twisted's _epoll.pyx and select.poll()\r
+ */\r
+\r
+#ifdef HAVE_SYS_EPOLL_H\r
+#include <sys/epoll.h>\r
+#endif\r
+\r
+typedef struct {\r
+    PyObject_HEAD\r
+    SOCKET epfd;                        /* epoll control file descriptor */\r
+} pyEpoll_Object;\r
+\r
+static PyTypeObject pyEpoll_Type;\r
+#define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type))\r
+\r
+static PyObject *\r
+pyepoll_err_closed(void)\r
+{\r
+    PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd");\r
+    return NULL;\r
+}\r
+\r
+static int\r
+pyepoll_internal_close(pyEpoll_Object *self)\r
+{\r
+    int save_errno = 0;\r
+    if (self->epfd >= 0) {\r
+        int epfd = self->epfd;\r
+        self->epfd = -1;\r
+        Py_BEGIN_ALLOW_THREADS\r
+        if (close(epfd) < 0)\r
+            save_errno = errno;\r
+        Py_END_ALLOW_THREADS\r
+    }\r
+    return save_errno;\r
+}\r
+\r
+static PyObject *\r
+newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd)\r
+{\r
+    pyEpoll_Object *self;\r
+\r
+    if (sizehint == -1) {\r
+        sizehint = FD_SETSIZE-1;\r
+    }\r
+    else if (sizehint < 1) {\r
+        PyErr_Format(PyExc_ValueError,\r
+                     "sizehint must be greater zero, got %d",\r
+                     sizehint);\r
+        return NULL;\r
+    }\r
+\r
+    assert(type != NULL && type->tp_alloc != NULL);\r
+    self = (pyEpoll_Object *) type->tp_alloc(type, 0);\r
+    if (self == NULL)\r
+        return NULL;\r
+\r
+    if (fd == -1) {\r
+        Py_BEGIN_ALLOW_THREADS\r
+        self->epfd = epoll_create(sizehint);\r
+        Py_END_ALLOW_THREADS\r
+    }\r
+    else {\r
+        self->epfd = fd;\r
+    }\r
+    if (self->epfd < 0) {\r
+        Py_DECREF(self);\r
+        PyErr_SetFromErrno(PyExc_IOError);\r
+        return NULL;\r
+    }\r
+    return (PyObject *)self;\r
+}\r
+\r
+\r
+static PyObject *\r
+pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
+{\r
+    int sizehint = -1;\r
+    static char *kwlist[] = {"sizehint", NULL};\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist,\r
+                                     &sizehint))\r
+        return NULL;\r
+\r
+    return newPyEpoll_Object(type, sizehint, -1);\r
+}\r
+\r
+\r
+static void\r
+pyepoll_dealloc(pyEpoll_Object *self)\r
+{\r
+    (void)pyepoll_internal_close(self);\r
+    Py_TYPE(self)->tp_free(self);\r
+}\r
+\r
+static PyObject*\r
+pyepoll_close(pyEpoll_Object *self)\r
+{\r
+    errno = pyepoll_internal_close(self);\r
+    if (errno < 0) {\r
+        PyErr_SetFromErrno(PyExc_IOError);\r
+        return NULL;\r
+    }\r
+    Py_RETURN_NONE;\r
+}\r
+\r
+PyDoc_STRVAR(pyepoll_close_doc,\r
+"close() -> None\n\\r
+\n\\r
+Close the epoll control file descriptor. Further operations on the epoll\n\\r
+object will raise an exception.");\r
+\r
+static PyObject*\r
+pyepoll_get_closed(pyEpoll_Object *self)\r
+{\r
+    if (self->epfd < 0)\r
+        Py_RETURN_TRUE;\r
+    else\r
+        Py_RETURN_FALSE;\r
+}\r
+\r
+static PyObject*\r
+pyepoll_fileno(pyEpoll_Object *self)\r
+{\r
+    if (self->epfd < 0)\r
+        return pyepoll_err_closed();\r
+    return PyInt_FromLong(self->epfd);\r
+}\r
+\r
+PyDoc_STRVAR(pyepoll_fileno_doc,\r
+"fileno() -> int\n\\r
+\n\\r
+Return the epoll control file descriptor.");\r
+\r
+static PyObject*\r
+pyepoll_fromfd(PyObject *cls, PyObject *args)\r
+{\r
+    SOCKET fd;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:fromfd", &fd))\r
+        return NULL;\r
+\r
+    return newPyEpoll_Object((PyTypeObject*)cls, -1, fd);\r
+}\r
+\r
+PyDoc_STRVAR(pyepoll_fromfd_doc,\r
+"fromfd(fd) -> epoll\n\\r
+\n\\r
+Create an epoll object from a given control fd.");\r
+\r
+static PyObject *\r
+pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events)\r
+{\r
+    struct epoll_event ev;\r
+    int result;\r
+    int fd;\r
+\r
+    if (epfd < 0)\r
+        return pyepoll_err_closed();\r
+\r
+    fd = PyObject_AsFileDescriptor(pfd);\r
+    if (fd == -1) {\r
+        return NULL;\r
+    }\r
+\r
+    switch(op) {\r
+        case EPOLL_CTL_ADD:\r
+        case EPOLL_CTL_MOD:\r
+        ev.events = events;\r
+        ev.data.fd = fd;\r
+        Py_BEGIN_ALLOW_THREADS\r
+        result = epoll_ctl(epfd, op, fd, &ev);\r
+        Py_END_ALLOW_THREADS\r
+        break;\r
+        case EPOLL_CTL_DEL:\r
+        /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL\r
+         * operation required a non-NULL pointer in event, even\r
+         * though this argument is ignored. */\r
+        Py_BEGIN_ALLOW_THREADS\r
+        result = epoll_ctl(epfd, op, fd, &ev);\r
+        if (errno == EBADF) {\r
+            /* fd already closed */\r
+            result = 0;\r
+            errno = 0;\r
+        }\r
+        Py_END_ALLOW_THREADS\r
+        break;\r
+        default:\r
+        result = -1;\r
+        errno = EINVAL;\r
+    }\r
+\r
+    if (result < 0) {\r
+        PyErr_SetFromErrno(PyExc_IOError);\r
+        return NULL;\r
+    }\r
+    Py_RETURN_NONE;\r
+}\r
+\r
+static PyObject *\r
+pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds)\r
+{\r
+    PyObject *pfd;\r
+    unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;\r
+    static char *kwlist[] = {"fd", "eventmask", NULL};\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,\r
+                                     &pfd, &events)) {\r
+        return NULL;\r
+    }\r
+\r
+    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);\r
+}\r
+\r
+PyDoc_STRVAR(pyepoll_register_doc,\r
+"register(fd[, eventmask]) -> None\n\\r
+\n\\r
+Registers a new fd or modifies an already registered fd.\n\\r
+fd is the target file descriptor of the operation.\n\\r
+events is a bit set composed of the various EPOLL constants; the default\n\\r
+is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\\r
+\n\\r
+The epoll interface supports all file descriptors that support poll.");\r
+\r
+static PyObject *\r
+pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds)\r
+{\r
+    PyObject *pfd;\r
+    unsigned int events;\r
+    static char *kwlist[] = {"fd", "eventmask", NULL};\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,\r
+                                     &pfd, &events)) {\r
+        return NULL;\r
+    }\r
+\r
+    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);\r
+}\r
+\r
+PyDoc_STRVAR(pyepoll_modify_doc,\r
+"modify(fd, eventmask) -> None\n\\r
+\n\\r
+fd is the target file descriptor of the operation\n\\r
+events is a bit set composed of the various EPOLL constants");\r
+\r
+static PyObject *\r
+pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds)\r
+{\r
+    PyObject *pfd;\r
+    static char *kwlist[] = {"fd", NULL};\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,\r
+                                     &pfd)) {\r
+        return NULL;\r
+    }\r
+\r
+    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);\r
+}\r
+\r
+PyDoc_STRVAR(pyepoll_unregister_doc,\r
+"unregister(fd) -> None\n\\r
+\n\\r
+fd is the target file descriptor of the operation.");\r
+\r
+static PyObject *\r
+pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)\r
+{\r
+    double dtimeout = -1.;\r
+    int timeout;\r
+    int maxevents = -1;\r
+    int nfds, i;\r
+    PyObject *elist = NULL, *etuple = NULL;\r
+    struct epoll_event *evs = NULL;\r
+    static char *kwlist[] = {"timeout", "maxevents", NULL};\r
+\r
+    if (self->epfd < 0)\r
+        return pyepoll_err_closed();\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist,\r
+                                     &dtimeout, &maxevents)) {\r
+        return NULL;\r
+    }\r
+\r
+    if (dtimeout < 0) {\r
+        timeout = -1;\r
+    }\r
+    else if (dtimeout * 1000.0 > INT_MAX) {\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "timeout is too large");\r
+        return NULL;\r
+    }\r
+    else {\r
+        timeout = (int)(dtimeout * 1000.0);\r
+    }\r
+\r
+    if (maxevents == -1) {\r
+        maxevents = FD_SETSIZE-1;\r
+    }\r
+    else if (maxevents < 1) {\r
+        PyErr_Format(PyExc_ValueError,\r
+                     "maxevents must be greater than 0, got %d",\r
+                     maxevents);\r
+        return NULL;\r
+    }\r
+\r
+    evs = PyMem_New(struct epoll_event, maxevents);\r
+    if (evs == NULL) {\r
+        Py_DECREF(self);\r
+        PyErr_NoMemory();\r
+        return NULL;\r
+    }\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    nfds = epoll_wait(self->epfd, evs, maxevents, timeout);\r
+    Py_END_ALLOW_THREADS\r
+    if (nfds < 0) {\r
+        PyErr_SetFromErrno(PyExc_IOError);\r
+        goto error;\r
+    }\r
+\r
+    elist = PyList_New(nfds);\r
+    if (elist == NULL) {\r
+        goto error;\r
+    }\r
+\r
+    for (i = 0; i < nfds; i++) {\r
+        etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);\r
+        if (etuple == NULL) {\r
+            Py_CLEAR(elist);\r
+            goto error;\r
+        }\r
+        PyList_SET_ITEM(elist, i, etuple);\r
+    }\r
+\r
+    error:\r
+    PyMem_Free(evs);\r
+    return elist;\r
+}\r
+\r
+PyDoc_STRVAR(pyepoll_poll_doc,\r
+"poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\\r
+\n\\r
+Wait for events on the epoll file descriptor for a maximum time of timeout\n\\r
+in seconds (as float). -1 makes poll wait indefinitely.\n\\r
+Up to maxevents are returned to the caller.");\r
+\r
+static PyMethodDef pyepoll_methods[] = {\r
+    {"fromfd",          (PyCFunction)pyepoll_fromfd,\r
+     METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},\r
+    {"close",           (PyCFunction)pyepoll_close,     METH_NOARGS,\r
+     pyepoll_close_doc},\r
+    {"fileno",          (PyCFunction)pyepoll_fileno,    METH_NOARGS,\r
+     pyepoll_fileno_doc},\r
+    {"modify",          (PyCFunction)pyepoll_modify,\r
+     METH_VARARGS | METH_KEYWORDS,      pyepoll_modify_doc},\r
+    {"register",        (PyCFunction)pyepoll_register,\r
+     METH_VARARGS | METH_KEYWORDS,      pyepoll_register_doc},\r
+    {"unregister",      (PyCFunction)pyepoll_unregister,\r
+     METH_VARARGS | METH_KEYWORDS,      pyepoll_unregister_doc},\r
+    {"poll",            (PyCFunction)pyepoll_poll,\r
+     METH_VARARGS | METH_KEYWORDS,      pyepoll_poll_doc},\r
+    {NULL,      NULL},\r
+};\r
+\r
+static PyGetSetDef pyepoll_getsetlist[] = {\r
+    {"closed", (getter)pyepoll_get_closed, NULL,\r
+     "True if the epoll handler is closed"},\r
+    {0},\r
+};\r
+\r
+PyDoc_STRVAR(pyepoll_doc,\r
+"select.epoll([sizehint=-1])\n\\r
+\n\\r
+Returns an epolling object\n\\r
+\n\\r
+sizehint must be a positive integer or -1 for the default size. The\n\\r
+sizehint is used to optimize internal data structures. It doesn't limit\n\\r
+the maximum number of monitored events.");\r
+\r
+static PyTypeObject pyEpoll_Type = {\r
+    PyVarObject_HEAD_INIT(NULL, 0)\r
+    "select.epoll",                                     /* tp_name */\r
+    sizeof(pyEpoll_Object),                             /* tp_basicsize */\r
+    0,                                                  /* tp_itemsize */\r
+    (destructor)pyepoll_dealloc,                        /* tp_dealloc */\r
+    0,                                                  /* tp_print */\r
+    0,                                                  /* tp_getattr */\r
+    0,                                                  /* tp_setattr */\r
+    0,                                                  /* tp_compare */\r
+    0,                                                  /* tp_repr */\r
+    0,                                                  /* tp_as_number */\r
+    0,                                                  /* tp_as_sequence */\r
+    0,                                                  /* tp_as_mapping */\r
+    0,                                                  /* tp_hash */\r
+    0,                                                  /* tp_call */\r
+    0,                                                  /* tp_str */\r
+    PyObject_GenericGetAttr,                            /* tp_getattro */\r
+    0,                                                  /* tp_setattro */\r
+    0,                                                  /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,                                 /* tp_flags */\r
+    pyepoll_doc,                                        /* tp_doc */\r
+    0,                                                  /* tp_traverse */\r
+    0,                                                  /* tp_clear */\r
+    0,                                                  /* tp_richcompare */\r
+    0,                                                  /* tp_weaklistoffset */\r
+    0,                                                  /* tp_iter */\r
+    0,                                                  /* tp_iternext */\r
+    pyepoll_methods,                                    /* tp_methods */\r
+    0,                                                  /* tp_members */\r
+    pyepoll_getsetlist,                                 /* tp_getset */\r
+    0,                                                  /* tp_base */\r
+    0,                                                  /* tp_dict */\r
+    0,                                                  /* tp_descr_get */\r
+    0,                                                  /* tp_descr_set */\r
+    0,                                                  /* tp_dictoffset */\r
+    0,                                                  /* tp_init */\r
+    0,                                                  /* tp_alloc */\r
+    pyepoll_new,                                        /* tp_new */\r
+    0,                                                  /* tp_free */\r
+};\r
+\r
+#endif /* HAVE_EPOLL */\r
+\r
+#ifdef HAVE_KQUEUE\r
+/* **************************************************************************\r
+ *                      kqueue interface for BSD\r
+ *\r
+ * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\r
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\r
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\r
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\r
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\r
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\r
+ * SUCH DAMAGE.\r
+ */\r
+\r
+#ifdef HAVE_SYS_EVENT_H\r
+#include <sys/event.h>\r
+#endif\r
+\r
+PyDoc_STRVAR(kqueue_event_doc,\r
+"kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\\r
+\n\\r
+This object is the equivalent of the struct kevent for the C API.\n\\r
+\n\\r
+See the kqueue manpage for more detailed information about the meaning\n\\r
+of the arguments.\n\\r
+\n\\r
+One minor note: while you might hope that udata could store a\n\\r
+reference to a python object, it cannot, because it is impossible to\n\\r
+keep a proper reference count of the object once it's passed into the\n\\r
+kernel. Therefore, I have restricted it to only storing an integer.  I\n\\r
+recommend ignoring it and simply using the 'ident' field to key off\n\\r
+of. You could also set up a dictionary on the python side to store a\n\\r
+udata->object mapping.");\r
+\r
+typedef struct {\r
+    PyObject_HEAD\r
+    struct kevent e;\r
+} kqueue_event_Object;\r
+\r
+static PyTypeObject kqueue_event_Type;\r
+\r
+#define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type))\r
+\r
+typedef struct {\r
+    PyObject_HEAD\r
+    SOCKET kqfd;                /* kqueue control fd */\r
+} kqueue_queue_Object;\r
+\r
+static PyTypeObject kqueue_queue_Type;\r
+\r
+#define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type))\r
+\r
+#if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P)\r
+#   error uintptr_t does not match void *!\r
+#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)\r
+#   define T_UINTPTRT         T_ULONGLONG\r
+#   define T_INTPTRT          T_LONGLONG\r
+#   define PyLong_AsUintptr_t PyLong_AsUnsignedLongLong\r
+#   define UINTPTRT_FMT_UNIT  "K"\r
+#   define INTPTRT_FMT_UNIT   "L"\r
+#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG)\r
+#   define T_UINTPTRT         T_ULONG\r
+#   define T_INTPTRT          T_LONG\r
+#   define PyLong_AsUintptr_t PyLong_AsUnsignedLong\r
+#   define UINTPTRT_FMT_UNIT  "k"\r
+#   define INTPTRT_FMT_UNIT   "l"\r
+#elif (SIZEOF_UINTPTR_T == SIZEOF_INT)\r
+#   define T_UINTPTRT         T_UINT\r
+#   define T_INTPTRT          T_INT\r
+#   define PyLong_AsUintptr_t PyLong_AsUnsignedLong\r
+#   define UINTPTRT_FMT_UNIT  "I"\r
+#   define INTPTRT_FMT_UNIT   "i"\r
+#else\r
+#   error uintptr_t does not match int, long, or long long!\r
+#endif\r
+\r
+/* Unfortunately, we can't store python objects in udata, because\r
+ * kevents in the kernel can be removed without warning, which would\r
+ * forever lose the refcount on the object stored with it.\r
+ */\r
+\r
+#define KQ_OFF(x) offsetof(kqueue_event_Object, x)\r
+static struct PyMemberDef kqueue_event_members[] = {\r
+    {"ident",           T_UINTPTRT,     KQ_OFF(e.ident)},\r
+    {"filter",          T_SHORT,        KQ_OFF(e.filter)},\r
+    {"flags",           T_USHORT,       KQ_OFF(e.flags)},\r
+    {"fflags",          T_UINT,         KQ_OFF(e.fflags)},\r
+    {"data",            T_INTPTRT,      KQ_OFF(e.data)},\r
+    {"udata",           T_UINTPTRT,     KQ_OFF(e.udata)},\r
+    {NULL} /* Sentinel */\r
+};\r
+#undef KQ_OFF\r
+\r
+static PyObject *\r
+\r
+kqueue_event_repr(kqueue_event_Object *s)\r
+{\r
+    char buf[1024];\r
+    PyOS_snprintf(\r
+        buf, sizeof(buf),\r
+        "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "\r
+        "data=0x%zd udata=%p>",\r
+        (size_t)(s->e.ident), s->e.filter, s->e.flags,\r
+        s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata);\r
+    return PyString_FromString(buf);\r
+}\r
+\r
+static int\r
+kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds)\r
+{\r
+    PyObject *pfd;\r
+    static char *kwlist[] = {"ident", "filter", "flags", "fflags",\r
+                             "data", "udata", NULL};\r
+    static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent";\r
+\r
+    EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,\r
+        &pfd, &(self->e.filter), &(self->e.flags),\r
+        &(self->e.fflags), &(self->e.data), &(self->e.udata))) {\r
+        return -1;\r
+    }\r
+\r
+    if (PyLong_Check(pfd)) {\r
+        self->e.ident = PyLong_AsUintptr_t(pfd);\r
+    }\r
+    else {\r
+        self->e.ident = PyObject_AsFileDescriptor(pfd);\r
+    }\r
+    if (PyErr_Occurred()) {\r
+        return -1;\r
+    }\r
+    return 0;\r
+}\r
+\r
+static PyObject *\r
+kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,\r
+                         int op)\r
+{\r
+    Py_intptr_t result = 0;\r
+\r
+    if (!kqueue_event_Check(o)) {\r
+        if (op == Py_EQ || op == Py_NE) {\r
+            PyObject *res = op == Py_EQ ? Py_False : Py_True;\r
+            Py_INCREF(res);\r
+            return res;\r
+        }\r
+        PyErr_Format(PyExc_TypeError,\r
+            "can't compare %.200s to %.200s",\r
+            Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name);\r
+        return NULL;\r
+    }\r
+    if (((result = s->e.ident - o->e.ident) == 0) &&\r
+        ((result = s->e.filter - o->e.filter) == 0) &&\r
+        ((result = s->e.flags - o->e.flags) == 0) &&\r
+        ((result = s->e.fflags - o->e.fflags) == 0) &&\r
+        ((result = s->e.data - o->e.data) == 0) &&\r
+        ((result = s->e.udata - o->e.udata) == 0)\r
+       ) {\r
+        result = 0;\r
+    }\r
+\r
+    switch (op) {\r
+        case Py_EQ:\r
+        result = (result == 0);\r
+        break;\r
+        case Py_NE:\r
+        result = (result != 0);\r
+        break;\r
+        case Py_LE:\r
+        result = (result <= 0);\r
+        break;\r
+        case Py_GE:\r
+        result = (result >= 0);\r
+        break;\r
+        case Py_LT:\r
+        result = (result < 0);\r
+        break;\r
+        case Py_GT:\r
+        result = (result > 0);\r
+        break;\r
+    }\r
+    return PyBool_FromLong((long)result);\r
+}\r
+\r
+static PyTypeObject kqueue_event_Type = {\r
+    PyVarObject_HEAD_INIT(NULL, 0)\r
+    "select.kevent",                                    /* tp_name */\r
+    sizeof(kqueue_event_Object),                        /* tp_basicsize */\r
+    0,                                                  /* tp_itemsize */\r
+    0,                                                  /* tp_dealloc */\r
+    0,                                                  /* tp_print */\r
+    0,                                                  /* tp_getattr */\r
+    0,                                                  /* tp_setattr */\r
+    0,                                                  /* tp_compare */\r
+    (reprfunc)kqueue_event_repr,                        /* tp_repr */\r
+    0,                                                  /* tp_as_number */\r
+    0,                                                  /* tp_as_sequence */\r
+    0,                                                  /* tp_as_mapping */\r
+    0,                                                  /* tp_hash */\r
+    0,                                                  /* tp_call */\r
+    0,                                                  /* tp_str */\r
+    0,                                                  /* tp_getattro */\r
+    0,                                                  /* tp_setattro */\r
+    0,                                                  /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,                                 /* tp_flags */\r
+    kqueue_event_doc,                                   /* tp_doc */\r
+    0,                                                  /* tp_traverse */\r
+    0,                                                  /* tp_clear */\r
+    (richcmpfunc)kqueue_event_richcompare,              /* tp_richcompare */\r
+    0,                                                  /* tp_weaklistoffset */\r
+    0,                                                  /* tp_iter */\r
+    0,                                                  /* tp_iternext */\r
+    0,                                                  /* tp_methods */\r
+    kqueue_event_members,                               /* tp_members */\r
+    0,                                                  /* tp_getset */\r
+    0,                                                  /* tp_base */\r
+    0,                                                  /* tp_dict */\r
+    0,                                                  /* tp_descr_get */\r
+    0,                                                  /* tp_descr_set */\r
+    0,                                                  /* tp_dictoffset */\r
+    (initproc)kqueue_event_init,                        /* tp_init */\r
+    0,                                                  /* tp_alloc */\r
+    0,                                                  /* tp_new */\r
+    0,                                                  /* tp_free */\r
+};\r
+\r
+static PyObject *\r
+kqueue_queue_err_closed(void)\r
+{\r
+    PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd");\r
+    return NULL;\r
+}\r
+\r
+static int\r
+kqueue_queue_internal_close(kqueue_queue_Object *self)\r
+{\r
+    int save_errno = 0;\r
+    if (self->kqfd >= 0) {\r
+        int kqfd = self->kqfd;\r
+        self->kqfd = -1;\r
+        Py_BEGIN_ALLOW_THREADS\r
+        if (close(kqfd) < 0)\r
+            save_errno = errno;\r
+        Py_END_ALLOW_THREADS\r
+    }\r
+    return save_errno;\r
+}\r
+\r
+static PyObject *\r
+newKqueue_Object(PyTypeObject *type, SOCKET fd)\r
+{\r
+    kqueue_queue_Object *self;\r
+    assert(type != NULL && type->tp_alloc != NULL);\r
+    self = (kqueue_queue_Object *) type->tp_alloc(type, 0);\r
+    if (self == NULL) {\r
+        return NULL;\r
+    }\r
+\r
+    if (fd == -1) {\r
+        Py_BEGIN_ALLOW_THREADS\r
+        self->kqfd = kqueue();\r
+        Py_END_ALLOW_THREADS\r
+    }\r
+    else {\r
+        self->kqfd = fd;\r
+    }\r
+    if (self->kqfd < 0) {\r
+        Py_DECREF(self);\r
+        PyErr_SetFromErrno(PyExc_IOError);\r
+        return NULL;\r
+    }\r
+    return (PyObject *)self;\r
+}\r
+\r
+static PyObject *\r
+kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
+{\r
+\r
+    if ((args != NULL && PyObject_Size(args)) ||\r
+                    (kwds != NULL && PyObject_Size(kwds))) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                        "select.kqueue doesn't accept arguments");\r
+        return NULL;\r
+    }\r
+\r
+    return newKqueue_Object(type, -1);\r
+}\r
+\r
+static void\r
+kqueue_queue_dealloc(kqueue_queue_Object *self)\r
+{\r
+    kqueue_queue_internal_close(self);\r
+    Py_TYPE(self)->tp_free(self);\r
+}\r
+\r
+static PyObject*\r
+kqueue_queue_close(kqueue_queue_Object *self)\r
+{\r
+    errno = kqueue_queue_internal_close(self);\r
+    if (errno < 0) {\r
+        PyErr_SetFromErrno(PyExc_IOError);\r
+        return NULL;\r
+    }\r
+    Py_RETURN_NONE;\r
+}\r
+\r
+PyDoc_STRVAR(kqueue_queue_close_doc,\r
+"close() -> None\n\\r
+\n\\r
+Close the kqueue control file descriptor. Further operations on the kqueue\n\\r
+object will raise an exception.");\r
+\r
+static PyObject*\r
+kqueue_queue_get_closed(kqueue_queue_Object *self)\r
+{\r
+    if (self->kqfd < 0)\r
+        Py_RETURN_TRUE;\r
+    else\r
+        Py_RETURN_FALSE;\r
+}\r
+\r
+static PyObject*\r
+kqueue_queue_fileno(kqueue_queue_Object *self)\r
+{\r
+    if (self->kqfd < 0)\r
+        return kqueue_queue_err_closed();\r
+    return PyInt_FromLong(self->kqfd);\r
+}\r
+\r
+PyDoc_STRVAR(kqueue_queue_fileno_doc,\r
+"fileno() -> int\n\\r
+\n\\r
+Return the kqueue control file descriptor.");\r
+\r
+static PyObject*\r
+kqueue_queue_fromfd(PyObject *cls, PyObject *args)\r
+{\r
+    SOCKET fd;\r
+\r
+    if (!PyArg_ParseTuple(args, "i:fromfd", &fd))\r
+        return NULL;\r
+\r
+    return newKqueue_Object((PyTypeObject*)cls, fd);\r
+}\r
+\r
+PyDoc_STRVAR(kqueue_queue_fromfd_doc,\r
+"fromfd(fd) -> kqueue\n\\r
+\n\\r
+Create a kqueue object from a given control fd.");\r
+\r
+static PyObject *\r
+kqueue_queue_control(kqueue_queue_Object *self, PyObject *args)\r
+{\r
+    int nevents = 0;\r
+    int gotevents = 0;\r
+    int nchanges = 0;\r
+    int i = 0;\r
+    PyObject *otimeout = NULL;\r
+    PyObject *ch = NULL;\r
+    PyObject *it = NULL, *ei = NULL;\r
+    PyObject *result = NULL;\r
+    struct kevent *evl = NULL;\r
+    struct kevent *chl = NULL;\r
+    struct timespec timeoutspec;\r
+    struct timespec *ptimeoutspec;\r
+\r
+    if (self->kqfd < 0)\r
+        return kqueue_queue_err_closed();\r
+\r
+    if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))\r
+        return NULL;\r
+\r
+    if (nevents < 0) {\r
+        PyErr_Format(PyExc_ValueError,\r
+            "Length of eventlist must be 0 or positive, got %d",\r
+            nevents);\r
+        return NULL;\r
+    }\r
+\r
+    if (otimeout == Py_None || otimeout == NULL) {\r
+        ptimeoutspec = NULL;\r
+    }\r
+    else if (PyNumber_Check(otimeout)) {\r
+        double timeout;\r
+        long seconds;\r
+\r
+        timeout = PyFloat_AsDouble(otimeout);\r
+        if (timeout == -1 && PyErr_Occurred())\r
+            return NULL;\r
+        if (timeout > (double)LONG_MAX) {\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "timeout period too long");\r
+            return NULL;\r
+        }\r
+        if (timeout < 0) {\r
+            PyErr_SetString(PyExc_ValueError,\r
+                            "timeout must be positive or None");\r
+            return NULL;\r
+        }\r
+\r
+        seconds = (long)timeout;\r
+        timeout = timeout - (double)seconds;\r
+        timeoutspec.tv_sec = seconds;\r
+        timeoutspec.tv_nsec = (long)(timeout * 1E9);\r
+        ptimeoutspec = &timeoutspec;\r
+    }\r
+    else {\r
+        PyErr_Format(PyExc_TypeError,\r
+            "timeout argument must be an number "\r
+            "or None, got %.200s",\r
+            Py_TYPE(otimeout)->tp_name);\r
+        return NULL;\r
+    }\r
+\r
+    if (ch != NULL && ch != Py_None) {\r
+        it = PyObject_GetIter(ch);\r
+        if (it == NULL) {\r
+            PyErr_SetString(PyExc_TypeError,\r
+                            "changelist is not iterable");\r
+            return NULL;\r
+        }\r
+        nchanges = PyObject_Size(ch);\r
+        if (nchanges < 0) {\r
+            goto error;\r
+        }\r
+\r
+        chl = PyMem_New(struct kevent, nchanges);\r
+        if (chl == NULL) {\r
+            PyErr_NoMemory();\r
+            goto error;\r
+        }\r
+        i = 0;\r
+        while ((ei = PyIter_Next(it)) != NULL) {\r
+            if (!kqueue_event_Check(ei)) {\r
+                Py_DECREF(ei);\r
+                PyErr_SetString(PyExc_TypeError,\r
+                    "changelist must be an iterable of "\r
+                    "select.kevent objects");\r
+                goto error;\r
+            } else {\r
+                chl[i++] = ((kqueue_event_Object *)ei)->e;\r
+            }\r
+            Py_DECREF(ei);\r
+        }\r
+    }\r
+    Py_CLEAR(it);\r
+\r
+    /* event list */\r
+    if (nevents) {\r
+        evl = PyMem_New(struct kevent, nevents);\r
+        if (evl == NULL) {\r
+            PyErr_NoMemory();\r
+            goto error;\r
+        }\r
+    }\r
+\r
+    Py_BEGIN_ALLOW_THREADS\r
+    gotevents = kevent(self->kqfd, chl, nchanges,\r
+                       evl, nevents, ptimeoutspec);\r
+    Py_END_ALLOW_THREADS\r
+\r
+    if (gotevents == -1) {\r
+        PyErr_SetFromErrno(PyExc_OSError);\r
+        goto error;\r
+    }\r
+\r
+    result = PyList_New(gotevents);\r
+    if (result == NULL) {\r
+        goto error;\r
+    }\r
+\r
+    for (i = 0; i < gotevents; i++) {\r
+        kqueue_event_Object *ch;\r
+\r
+        ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);\r
+        if (ch == NULL) {\r
+            goto error;\r
+        }\r
+        ch->e = evl[i];\r
+        PyList_SET_ITEM(result, i, (PyObject *)ch);\r
+    }\r
+    PyMem_Free(chl);\r
+    PyMem_Free(evl);\r
+    return result;\r
+\r
+    error:\r
+    PyMem_Free(chl);\r
+    PyMem_Free(evl);\r
+    Py_XDECREF(result);\r
+    Py_XDECREF(it);\r
+    return NULL;\r
+}\r
+\r
+PyDoc_STRVAR(kqueue_queue_control_doc,\r
+"control(changelist, max_events[, timeout=None]) -> eventlist\n\\r
+\n\\r
+Calls the kernel kevent function.\n\\r
+- changelist must be a list of kevent objects describing the changes\n\\r
+  to be made to the kernel's watch list or None.\n\\r
+- max_events lets you specify the maximum number of events that the\n\\r
+  kernel will return.\n\\r
+- timeout is the maximum time to wait in seconds, or else None,\n\\r
+  to wait forever. timeout accepts floats for smaller timeouts, too.");\r
+\r
+\r
+static PyMethodDef kqueue_queue_methods[] = {\r
+    {"fromfd",          (PyCFunction)kqueue_queue_fromfd,\r
+     METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},\r
+    {"close",           (PyCFunction)kqueue_queue_close,        METH_NOARGS,\r
+     kqueue_queue_close_doc},\r
+    {"fileno",          (PyCFunction)kqueue_queue_fileno,       METH_NOARGS,\r
+     kqueue_queue_fileno_doc},\r
+    {"control",         (PyCFunction)kqueue_queue_control,\r
+     METH_VARARGS ,     kqueue_queue_control_doc},\r
+    {NULL,      NULL},\r
+};\r
+\r
+static PyGetSetDef kqueue_queue_getsetlist[] = {\r
+    {"closed", (getter)kqueue_queue_get_closed, NULL,\r
+     "True if the kqueue handler is closed"},\r
+    {0},\r
+};\r
+\r
+PyDoc_STRVAR(kqueue_queue_doc,\r
+"Kqueue syscall wrapper.\n\\r
+\n\\r
+For example, to start watching a socket for input:\n\\r
+>>> kq = kqueue()\n\\r
+>>> sock = socket()\n\\r
+>>> sock.connect((host, port))\n\\r
+>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\\r
+\n\\r
+To wait one second for it to become writeable:\n\\r
+>>> kq.control(None, 1, 1000)\n\\r
+\n\\r
+To stop listening:\n\\r
+>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)");\r
+\r
+static PyTypeObject kqueue_queue_Type = {\r
+    PyVarObject_HEAD_INIT(NULL, 0)\r
+    "select.kqueue",                                    /* tp_name */\r
+    sizeof(kqueue_queue_Object),                        /* tp_basicsize */\r
+    0,                                                  /* tp_itemsize */\r
+    (destructor)kqueue_queue_dealloc,                   /* tp_dealloc */\r
+    0,                                                  /* tp_print */\r
+    0,                                                  /* tp_getattr */\r
+    0,                                                  /* tp_setattr */\r
+    0,                                                  /* tp_compare */\r
+    0,                                                  /* tp_repr */\r
+    0,                                                  /* tp_as_number */\r
+    0,                                                  /* tp_as_sequence */\r
+    0,                                                  /* tp_as_mapping */\r
+    0,                                                  /* tp_hash */\r
+    0,                                                  /* tp_call */\r
+    0,                                                  /* tp_str */\r
+    0,                                                  /* tp_getattro */\r
+    0,                                                  /* tp_setattro */\r
+    0,                                                  /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,                                 /* tp_flags */\r
+    kqueue_queue_doc,                                   /* tp_doc */\r
+    0,                                                  /* tp_traverse */\r
+    0,                                                  /* tp_clear */\r
+    0,                                                  /* tp_richcompare */\r
+    0,                                                  /* tp_weaklistoffset */\r
+    0,                                                  /* tp_iter */\r
+    0,                                                  /* tp_iternext */\r
+    kqueue_queue_methods,                               /* tp_methods */\r
+    0,                                                  /* tp_members */\r
+    kqueue_queue_getsetlist,                            /* tp_getset */\r
+    0,                                                  /* tp_base */\r
+    0,                                                  /* tp_dict */\r
+    0,                                                  /* tp_descr_get */\r
+    0,                                                  /* tp_descr_set */\r
+    0,                                                  /* tp_dictoffset */\r
+    0,                                                  /* tp_init */\r
+    0,                                                  /* tp_alloc */\r
+    kqueue_queue_new,                                   /* tp_new */\r
+    0,                                                  /* tp_free */\r
+};\r
+\r
+#endif /* HAVE_KQUEUE */\r
+/* ************************************************************************ */\r
+\r
+PyDoc_STRVAR(select_doc,\r
+"select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\\r
+\n\\r
+Wait until one or more file descriptors are ready for some kind of I/O.\n\\r
+The first three arguments are sequences of file descriptors to be waited for:\n\\r
+rlist -- wait until ready for reading\n\\r
+wlist -- wait until ready for writing\n\\r
+xlist -- wait for an ``exceptional condition''\n\\r
+If only one kind of condition is required, pass [] for the other lists.\n\\r
+A file descriptor is either a socket or file object, or a small integer\n\\r
+gotten from a fileno() method call on one of those.\n\\r
+\n\\r
+The optional 4th argument specifies a timeout in seconds; it may be\n\\r
+a floating point number to specify fractions of seconds.  If it is absent\n\\r
+or None, the call will never time out.\n\\r
+\n\\r
+The return value is a tuple of three lists corresponding to the first three\n\\r
+arguments; each contains the subset of the corresponding file descriptors\n\\r
+that are ready.\n\\r
+\n\\r
+*** IMPORTANT NOTICE ***\n\\r
+On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\\r
+descriptors can be used.");\r
+\r
+static PyMethodDef select_methods[] = {\r
+    {"select",          select_select,  METH_VARARGS,   select_doc},\r
+#ifdef HAVE_POLL\r
+    {"poll",            select_poll,    METH_NOARGS,    poll_doc},\r
+#endif /* HAVE_POLL */\r
+    {0,         0},     /* sentinel */\r
+};\r
+\r
+PyDoc_STRVAR(module_doc,\r
+"This module supports asynchronous I/O on multiple file descriptors.\n\\r
+\n\\r
+*** IMPORTANT NOTICE ***\n\\r
+On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors.");\r
+\r
+PyMODINIT_FUNC\r
+initselect(void)\r
+{\r
+    PyObject *m;\r
+    m = Py_InitModule3("select", select_methods, module_doc);\r
+    if (m == NULL)\r
+        return;\r
+\r
+    SelectError = PyErr_NewException("select.error", NULL, NULL);\r
+    Py_INCREF(SelectError);\r
+    PyModule_AddObject(m, "error", SelectError);\r
+\r
+#ifdef PIPE_BUF\r
+#ifdef HAVE_BROKEN_PIPE_BUF\r
+#undef PIPE_BUF\r
+#define PIPE_BUF 512\r
+#endif\r
+    PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF);\r
+#endif\r
+\r
+#if defined(HAVE_POLL)\r
+#ifdef __APPLE__\r
+    if (select_have_broken_poll()) {\r
+        if (PyObject_DelAttrString(m, "poll") == -1) {\r
+            PyErr_Clear();\r
+        }\r
+    } else {\r
+#else\r
+    {\r
+#endif\r
+        Py_TYPE(&poll_Type) = &PyType_Type;\r
+        PyModule_AddIntConstant(m, "POLLIN", POLLIN);\r
+        PyModule_AddIntConstant(m, "POLLPRI", POLLPRI);\r
+        PyModule_AddIntConstant(m, "POLLOUT", POLLOUT);\r
+        PyModule_AddIntConstant(m, "POLLERR", POLLERR);\r
+        PyModule_AddIntConstant(m, "POLLHUP", POLLHUP);\r
+        PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL);\r
+\r
+#ifdef POLLRDNORM\r
+        PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM);\r
+#endif\r
+#ifdef POLLRDBAND\r
+        PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND);\r
+#endif\r
+#ifdef POLLWRNORM\r
+        PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM);\r
+#endif\r
+#ifdef POLLWRBAND\r
+        PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND);\r
+#endif\r
+#ifdef POLLMSG\r
+        PyModule_AddIntConstant(m, "POLLMSG", POLLMSG);\r
+#endif\r
+    }\r
+#endif /* HAVE_POLL */\r
+\r
+#ifdef HAVE_EPOLL\r
+    Py_TYPE(&pyEpoll_Type) = &PyType_Type;\r
+    if (PyType_Ready(&pyEpoll_Type) < 0)\r
+        return;\r
+\r
+    Py_INCREF(&pyEpoll_Type);\r
+    PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);\r
+\r
+    PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN);\r
+    PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT);\r
+    PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI);\r
+    PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR);\r
+    PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP);\r
+    PyModule_AddIntConstant(m, "EPOLLET", EPOLLET);\r
+#ifdef EPOLLONESHOT\r
+    /* Kernel 2.6.2+ */\r
+    PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT);\r
+#endif\r
+    /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */\r
+    PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM);\r
+    PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND);\r
+    PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM);\r
+    PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND);\r
+    PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG);\r
+#endif /* HAVE_EPOLL */\r
+\r
+#ifdef HAVE_KQUEUE\r
+    kqueue_event_Type.tp_new = PyType_GenericNew;\r
+    Py_TYPE(&kqueue_event_Type) = &PyType_Type;\r
+    if(PyType_Ready(&kqueue_event_Type) < 0)\r
+        return;\r
+\r
+    Py_INCREF(&kqueue_event_Type);\r
+    PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);\r
+\r
+    Py_TYPE(&kqueue_queue_Type) = &PyType_Type;\r
+    if(PyType_Ready(&kqueue_queue_Type) < 0)\r
+        return;\r
+    Py_INCREF(&kqueue_queue_Type);\r
+    PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);\r
+\r
+    /* event filters */\r
+    PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);\r
+    PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);\r
+    PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);\r
+    PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);\r
+    PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);\r
+#ifdef EVFILT_NETDEV\r
+    PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);\r
+#endif\r
+    PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);\r
+    PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);\r
+\r
+    /* event flags */\r
+    PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);\r
+    PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);\r
+    PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);\r
+    PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);\r
+    PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);\r
+    PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);\r
+\r
+    PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);\r
+    PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);\r
+\r
+    PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);\r
+    PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);\r
+\r
+    /* READ WRITE filter flag */\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);\r
+\r
+    /* VNODE filter flags  */\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);\r
+\r
+    /* PROC filter flags  */\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);\r
+\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);\r
+\r
+    /* NETDEV filter flags */\r
+#ifdef EVFILT_NETDEV\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);\r
+    PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);\r
+#endif\r
+\r
+#endif /* HAVE_KQUEUE */\r
+}\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/socketmodule.h b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/socketmodule.h
new file mode 100644 (file)
index 0000000..56ee422
--- /dev/null
@@ -0,0 +1,250 @@
+/* Socket module header file */\r
+\r
+/* Includes needed for the sockaddr_* symbols below */\r
+#ifndef MS_WINDOWS\r
+#ifdef __VMS\r
+#   include <socket.h>\r
+# else\r
+#   include <sys/socket.h>\r
+# endif\r
+# include <netinet/in.h>\r
+# if !(defined(UEFI_ENV) || defined(__BEOS__) || defined(__CYGWIN__) || (defined(PYOS_OS2) && defined(PYCC_VACPP)))\r
+#  include <netinet/tcp.h>\r
+# endif\r
+\r
+#else /* MS_WINDOWS */\r
+# include <winsock2.h>\r
+# include <ws2tcpip.h>\r
+/* VC6 is shipped with old platform headers, and does not have MSTcpIP.h\r
+ * Separate SDKs have all the functions we want, but older ones don't have\r
+ * any version information.\r
+ * I use SIO_GET_MULTICAST_FILTER to detect a decent SDK.\r
+ */\r
+# ifdef SIO_GET_MULTICAST_FILTER\r
+#  include <MSTcpIP.h> /* for SIO_RCVALL */\r
+#  define HAVE_ADDRINFO\r
+#  define HAVE_SOCKADDR_STORAGE\r
+#  define HAVE_GETADDRINFO\r
+#  define HAVE_GETNAMEINFO\r
+#  define ENABLE_IPV6\r
+# else\r
+typedef int socklen_t;\r
+# endif /* IPPROTO_IPV6 */\r
+#endif /* MS_WINDOWS */\r
+\r
+#ifdef HAVE_SYS_UN_H\r
+# include <sys/un.h>\r
+#else\r
+# undef AF_UNIX\r
+#endif\r
+\r
+#ifdef HAVE_LINUX_NETLINK_H\r
+# ifdef HAVE_ASM_TYPES_H\r
+#  include <asm/types.h>\r
+# endif\r
+# include <linux/netlink.h>\r
+#else\r
+#  undef AF_NETLINK\r
+#endif\r
+\r
+#ifdef HAVE_BLUETOOTH_BLUETOOTH_H\r
+#include <bluetooth/bluetooth.h>\r
+#include <bluetooth/rfcomm.h>\r
+#include <bluetooth/l2cap.h>\r
+#include <bluetooth/sco.h>\r
+#include <bluetooth/hci.h>\r
+#endif\r
+\r
+#ifdef HAVE_BLUETOOTH_H\r
+#include <bluetooth.h>\r
+#endif\r
+\r
+#ifdef HAVE_NETPACKET_PACKET_H\r
+# include <sys/ioctl.h>\r
+# include <net/if.h>\r
+# include <netpacket/packet.h>\r
+#endif\r
+\r
+#ifdef HAVE_LINUX_TIPC_H\r
+# include <linux/tipc.h>\r
+#endif\r
+\r
+#ifndef Py__SOCKET_H\r
+#define Py__SOCKET_H\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/* Python module and C API name */\r
+#define PySocket_MODULE_NAME    "_socket"\r
+#define PySocket_CAPI_NAME      "CAPI"\r
+#define PySocket_CAPSULE_NAME  (PySocket_MODULE_NAME "." PySocket_CAPI_NAME)\r
+\r
+/* Abstract the socket file descriptor type */\r
+#ifdef MS_WINDOWS\r
+typedef SOCKET SOCKET_T;\r
+#       ifdef MS_WIN64\r
+#               define SIZEOF_SOCKET_T 8\r
+#       else\r
+#               define SIZEOF_SOCKET_T 4\r
+#       endif\r
+#else\r
+typedef int SOCKET_T;\r
+#       define SIZEOF_SOCKET_T SIZEOF_INT\r
+#endif\r
+\r
+/* Socket address */\r
+typedef union sock_addr {\r
+    struct sockaddr_in in;\r
+#ifdef AF_UNIX\r
+    struct sockaddr_un un;\r
+#endif\r
+#ifdef AF_NETLINK\r
+    struct sockaddr_nl nl;\r
+#endif\r
+#ifdef ENABLE_IPV6\r
+    struct sockaddr_in6 in6;\r
+    struct sockaddr_storage storage;\r
+#endif\r
+#ifdef HAVE_BLUETOOTH_BLUETOOTH_H\r
+    struct sockaddr_l2 bt_l2;\r
+    struct sockaddr_rc bt_rc;\r
+    struct sockaddr_sco bt_sco;\r
+    struct sockaddr_hci bt_hci;\r
+#endif\r
+#ifdef HAVE_NETPACKET_PACKET_H\r
+    struct sockaddr_ll ll;\r
+#endif\r
+} sock_addr_t;\r
+\r
+/* The object holding a socket.  It holds some extra information,\r
+   like the address family, which is used to decode socket address\r
+   arguments properly. */\r
+\r
+typedef struct {\r
+    PyObject_HEAD\r
+    SOCKET_T sock_fd;           /* Socket file descriptor */\r
+    int sock_family;            /* Address family, e.g., AF_INET */\r
+    int sock_type;              /* Socket type, e.g., SOCK_STREAM */\r
+    int sock_proto;             /* Protocol type, usually 0 */\r
+    PyObject *(*errorhandler)(void); /* Error handler; checks\r
+                                        errno, returns NULL and\r
+                                        sets a Python exception */\r
+    double sock_timeout;                 /* Operation timeout in seconds;\r
+                                        0.0 means non-blocking */\r
+} PySocketSockObject;\r
+\r
+/* --- C API ----------------------------------------------------*/\r
+\r
+/* Short explanation of what this C API export mechanism does\r
+   and how it works:\r
+\r
+    The _ssl module needs access to the type object defined in\r
+    the _socket module. Since cross-DLL linking introduces a lot of\r
+    problems on many platforms, the "trick" is to wrap the\r
+    C API of a module in a struct which then gets exported to\r
+    other modules via a PyCapsule.\r
+\r
+    The code in socketmodule.c defines this struct (which currently\r
+    only contains the type object reference, but could very\r
+    well also include other C APIs needed by other modules)\r
+    and exports it as PyCapsule via the module dictionary\r
+    under the name "CAPI".\r
+\r
+    Other modules can now include the socketmodule.h file\r
+    which defines the needed C APIs to import and set up\r
+    a static copy of this struct in the importing module.\r
+\r
+    After initialization, the importing module can then\r
+    access the C APIs from the _socket module by simply\r
+    referring to the static struct, e.g.\r
+\r
+    Load _socket module and its C API; this sets up the global\r
+    PySocketModule:\r
+\r
+    if (PySocketModule_ImportModuleAndAPI())\r
+        return;\r
+\r
+\r
+    Now use the C API as if it were defined in the using\r
+    module:\r
+\r
+    if (!PyArg_ParseTuple(args, "O!|zz:ssl",\r
+\r
+                          PySocketModule.Sock_Type,\r
+\r
+                          (PyObject*)&Sock,\r
+                          &key_file, &cert_file))\r
+        return NULL;\r
+\r
+    Support could easily be extended to export more C APIs/symbols\r
+    this way. Currently, only the type object is exported,\r
+    other candidates would be socket constructors and socket\r
+    access functions.\r
+\r
+*/\r
+\r
+/* C API for usage by other Python modules */\r
+typedef struct {\r
+    PyTypeObject *Sock_Type;\r
+    PyObject *error;\r
+} PySocketModule_APIObject;\r
+\r
+/* XXX The net effect of the following appears to be to define a function\r
+   XXX named PySocketModule_APIObject in _ssl.c.  It's unclear why it isn't\r
+   XXX defined there directly.\r
+\r
+   >>> It's defined here because other modules might also want to use\r
+   >>> the C API.\r
+\r
+*/\r
+#ifndef PySocket_BUILDING_SOCKET\r
+\r
+/* --- C API ----------------------------------------------------*/\r
+\r
+/* Interfacestructure to C API for other modules.\r
+   Call PySocketModule_ImportModuleAndAPI() to initialize this\r
+   structure. After that usage is simple:\r
+\r
+   if (!PyArg_ParseTuple(args, "O!|zz:ssl",\r
+                         &PySocketModule.Sock_Type, (PyObject*)&Sock,\r
+                         &key_file, &cert_file))\r
+     return NULL;\r
+   ...\r
+*/\r
+\r
+static\r
+PySocketModule_APIObject PySocketModule;\r
+\r
+/* You *must* call this before using any of the functions in\r
+   PySocketModule and check its outcome; otherwise all accesses will\r
+   result in a segfault. Returns 0 on success. */\r
+\r
+#ifndef DPRINTF\r
+# define DPRINTF if (0) printf\r
+#endif\r
+\r
+static\r
+int PySocketModule_ImportModuleAndAPI(void)\r
+{\r
+    void *api;\r
+\r
+  DPRINTF(" Loading capsule %s\n", PySocket_CAPSULE_NAME);\r
+  api = PyCapsule_Import(PySocket_CAPSULE_NAME, 1);\r
+    if (api == NULL)\r
+        goto onError;\r
+    memcpy(&PySocketModule, api, sizeof(PySocketModule));\r
+    DPRINTF(" API object loaded and initialized.\n");\r
+    return 0;\r
+\r
+ onError:\r
+    DPRINTF(" not found.\n");\r
+    return -1;\r
+}\r
+\r
+#endif /* !PySocket_BUILDING_SOCKET */\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif /* !Py__SOCKET_H */\r
index 46f89878d6f15c6cf1482090e28f05483d533da9..9f4d1a6f9e35a93555056aa648f5ce2a57369f66 100644 (file)
@@ -161,8 +161,8 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
 #  define fdopen(fd,mode) NULL /* No fdopen() */\r
 #endif\r
 \r
-#if (defined(_MSC_VER) && (_MSC_VER > 600))\r
-#  if defined(_WIN32_WCE) || defined(_EFI_STDLIB)\r
+#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined(UEFI_ENV)\r
+#  if defined(_WIN32_WCE)\r
 #    define fdopen(fd,mode) NULL /* No fdopen() */\r
 #    ifndef _PTRDIFF_T_DEFINED\r
        typedef int ptrdiff_t;\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Python/getcopyright.c b/AppPkg/Applications/Python/PyMod-2.7.2/Python/getcopyright.c
new file mode 100644 (file)
index 0000000..66ebc75
--- /dev/null
@@ -0,0 +1,36 @@
+/* Return the copyright string.  This is updated manually.\r
+\r
+    Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>\r
+    This program and the accompanying materials are licensed and made available under\r
+    the terms and conditions of the BSD License that accompanies this distribution.\r
+    The full text of the license may be found at\r
+    http://opensource.org/licenses/bsd-license.\r
+\r
+    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+*/\r
+\r
+#include "Python.h"\r
+\r
+static char cprt[] =\r
+"\\r
+Copyright (c) 2010-2011 Intel Corporation.\n\\r
+All Rights Reserved.\n\\r
+\n\\r
+Copyright (c) 2001-2011 Python Software Foundation.\n\\r
+All Rights Reserved.\n\\r
+\n\\r
+Copyright (c) 2000 BeOpen.com.\n\\r
+All Rights Reserved.\n\\r
+\n\\r
+Copyright (c) 1995-2001 Corporation for National Research Initiatives.\n\\r
+All Rights Reserved.\n\\r
+\n\\r
+Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\n\\r
+All Rights Reserved.";\r
+\r
+const char *\r
+Py_GetCopyright(void)\r
+{\r
+  return cprt;\r
+}\r
index 15fac14c66421fe15acd1289d7c73419fdbcadb6..28b6e9d59c5782365d6d8a25ddef8ecdb0969f2f 100644 (file)
   LibString\r
   LibStdio\r
   LibGdtoa\r
-  LibWchar\r
   LibMath\r
+  LibWchar\r
   LibGen\r
   LibNetUtil\r
-  DevShell\r
   BsdSocketLib\r
   EfiSocketLib\r
+  DevShell\r
 \r
 [Sources]\r
 #EFI -- EFI specific code\r
   Efi/config.c\r
-  Efi/getpath.c\r
   Efi/edk2module.c\r
+  Efi/getpath.c\r
 \r
 #Parser\r
   Python-2.7.2/Parser/acceler.c\r
   Python-2.7.2/Parser/tokenizer.c\r
 \r
 #Python\r
+  PyMod-2.7.2/Python/getcopyright.c\r
+  PyMod-2.7.2/Python/import.c\r
+  PyMod-2.7.2/Python/marshal.c\r
+\r
   Python-2.7.2/Python/_warnings.c\r
   Python-2.7.2/Python/asdl.c\r
   Python-2.7.2/Python/ast.c\r
   Python-2.7.2/Python/future.c\r
   Python-2.7.2/Python/getargs.c\r
   Python-2.7.2/Python/getcompiler.c\r
-  Python-2.7.2/Python/getcopyright.c\r
   Python-2.7.2/Python/getopt.c\r
   Python-2.7.2/Python/getplatform.c\r
   Python-2.7.2/Python/getversion.c\r
   Python-2.7.2/Python/graminit.c\r
-  Python-2.7.2/Python/import.c\r
   Python-2.7.2/Python/importdl.c\r
-  Python-2.7.2/Python/marshal.c\r
   Python-2.7.2/Python/modsupport.c\r
   Python-2.7.2/Python/mysnprintf.c\r
   Python-2.7.2/Python/mystrtoul.c\r
   Python-2.7.2/Modules/python.c\r
   Python-2.7.2/Modules/getbuildinfo.c\r
 \r
-  Python-2.7.2/Modules/arraymodule.c\r
-  Python-2.7.2/Modules/binascii.c\r
-  Python-2.7.2/Modules/errnomodule.c\r
-  Python-2.7.2/Modules/gcmodule.c\r
-  Python-2.7.2/Modules/signalmodule.c\r
-  Python-2.7.2/Modules/operator.c\r
-  Python-2.7.2/Modules/_weakref.c\r
-  Python-2.7.2/Modules/mathmodule.c\r
-  Python-2.7.2/Modules/_math.c\r
-  Python-2.7.2/Modules/timemodule.c\r
-  Python-2.7.2/Modules/datetimemodule.c\r
-  Python-2.7.2/Modules/cStringIO.c\r
-  Python-2.7.2/Modules/_codecsmodule.c\r
-  Python-2.7.2/Modules/_randommodule.c\r
-  Python-2.7.2/Modules/xxsubtype.c\r
+  PyMod-2.7.2/Modules/_sre.c\r
+  PyMod-2.7.2/Modules/errnomodule.c\r
+  PyMod-2.7.2/Modules/selectmodule.c\r
 \r
-  Python-2.7.2/Modules/_heapqmodule.c\r
-  Python-2.7.2/Modules/itertoolsmodule.c\r
+  Python-2.7.2/Modules/_bisectmodule.c\r
+  Python-2.7.2/Modules/_codecsmodule.c\r
   Python-2.7.2/Modules/_collectionsmodule.c\r
-  Python-2.7.2/Modules/_sre.c\r
-  Python-2.7.2/Modules/parsermodule.c\r
-  Python-2.7.2/Modules/_struct.c\r
-  Python-2.7.2/Modules/cPickle.c\r
   Python-2.7.2/Modules/_functoolsmodule.c\r
-  Python-2.7.2/Modules/cmathmodule.c\r
+  Python-2.7.2/Modules/_heapqmodule.c\r
   Python-2.7.2/Modules/_json.c\r
-\r
-  Python-2.7.2/Modules/_bisectmodule.c\r
+  Python-2.7.2/Modules/_math.c\r
+  Python-2.7.2/Modules/_randommodule.c\r
+  Python-2.7.2/Modules/_struct.c\r
+  Python-2.7.2/Modules/_weakref.c\r
+  Python-2.7.2/Modules/arraymodule.c\r
+  Python-2.7.2/Modules/binascii.c\r
+  Python-2.7.2/Modules/cmathmodule.c\r
+  Python-2.7.2/Modules/cPickle.c\r
+  Python-2.7.2/Modules/cStringIO.c\r
+  Python-2.7.2/Modules/datetimemodule.c\r
   Python-2.7.2/Modules/future_builtins.c\r
+  Python-2.7.2/Modules/gcmodule.c\r
+  Python-2.7.2/Modules/itertoolsmodule.c\r
+  Python-2.7.2/Modules/mathmodule.c\r
   Python-2.7.2/Modules/md5.c\r
   Python-2.7.2/Modules/md5module.c\r
+  Python-2.7.2/Modules/operator.c\r
+  Python-2.7.2/Modules/parsermodule.c\r
   Python-2.7.2/Modules/shamodule.c\r
   Python-2.7.2/Modules/sha256module.c\r
   Python-2.7.2/Modules/sha512module.c\r
-  Python-2.7.2/Modules/stropmodule.c\r
-\r
-  # Socket related modules\r
-#  Python-$(PYTHON_VERSION)/Modules/getaddrinfo.c       # included by socketmodule.c\r
-#  Python-$(PYTHON_VERSION)/Modules/getnameinfo.c       # included by socketmodule.c\r
-  Python-2.7.2/Modules/selectmodule.c\r
+  Python-2.7.2/Modules/signalmodule.c\r
   Python-2.7.2/Modules/socketmodule.c\r
+  Python-2.7.2/Modules/stropmodule.c\r
+  Python-2.7.2/Modules/timemodule.c\r
+  Python-2.7.2/Modules/xxsubtype.c\r
 \r
 #  Python-$(PYTHON_VERSION)/Modules/imageop.c\r
 #  Python-$(PYTHON_VERSION)/Modules/_csv.c\r
index 41b06827f577bd5f680d7a75e6c43767b832d2d2..ef95d1be62712ebe4f6ca5036d4fe97417fc9225 100644 (file)
     THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
     WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
 **/\r
-\r
-\r
 #ifndef Py_PYCONFIG_H\r
 #define Py_PYCONFIG_H\r
 \r
-#define PLATFORM    "UEFI 2.3 X64"\r
+#include  <Uefi.h>\r
+\r
+/* Define to indicate that code is being built to run in the UEFI Environment. */\r
+#define UEFI_ENV    EFI_SYSTEM_TABLE_REVISION\r
 \r
-//#ifndef PYTHONPATH\r
-//# define PYTHONPATH "/Efi/StdLib/lib/python.27;/Efi/StdLib/lib/python.27/lib-dynload"\r
-//#endif\r
+#define PLATFORM    "UEFI"\r
 \r
 /* Define if building universal (internal helper macro) */\r
 #undef AC_APPLE_UNIVERSAL_BUILD\r
 \r
 /* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.\r
    */\r
-#undef HAVE_DIRENT_H\r
+#define HAVE_DIRENT_H   1\r
 \r
 /* Define to 1 if you have the <dlfcn.h> header file. */\r
 #undef HAVE_DLFCN_H\r
 #undef HAVE_GETPAGESIZE\r
 \r
 /* Define to 1 if you have the `getpeername' function. */\r
-#undef HAVE_GETPEERNAME\r
+#define HAVE_GETPEERNAME  1\r
 \r
 /* Define to 1 if you have the `getpgid' function. */\r
 #undef HAVE_GETPGID\r
 #undef HAVE_PLOCK\r
 \r
 /* Define to 1 if you have the `poll' function. */\r
-#undef HAVE_POLL\r
+#define HAVE_POLL         1\r
 \r
 /* Define to 1 if you have the <poll.h> header file. */\r
-#define HAVE_POLL_H     1\r
+#undef HAVE_POLL_H\r
 \r
 /* Define to 1 if you have the <process.h> header file. */\r
 #undef HAVE_PROCESS_H\r
 #undef HAVE_READLINK\r
 \r
 /* Define to 1 if you have the `realpath' function. */\r
-#undef HAVE_REALPATH\r
+#define HAVE_REALPATH   1\r
 \r
 /* Define if you have readline 2.1 */\r
 #undef HAVE_RL_CALLBACK\r
 #undef HAVE_ROUND\r
 \r
 /* Define to 1 if you have the `select' function. */\r
-#undef HAVE_SELECT\r
+#define HAVE_SELECT       1\r
 \r
 /* Define to 1 if you have the `sem_getvalue' function. */\r
 #undef HAVE_SEM_GETVALUE\r
 #define HAVE_TEMPNAM      1\r
 \r
 /* Define to 1 if you have the <termios.h> header file. */\r
-#define HAVE_TERMIOS_H    1\r
+#undef HAVE_TERMIOS_H\r
 \r
 /* Define to 1 if you have the <term.h> header file. */\r
 #undef HAVE_TERM_H\r
 #undef HAVE_UTIMES\r
 \r
 /* Define to 1 if you have the <utime.h> header file. */\r
-#undef HAVE_UTIME_H\r
+#define HAVE_UTIME_H    1\r
 \r
 /* Define to 1 if you have the `wait3' function. */\r
 #undef HAVE_WAIT3\r