PageRenderTime 83ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/Modules/posixmodule.c

http://unladen-swallow.googlecode.com/
C | 9117 lines | 8157 code | 540 blank | 420 comment | 866 complexity | 45aba128b4b8ee359a4c42560351554e MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /* POSIX module implementation */
  2. /* This file is also used for Windows NT/MS-Win and OS/2. In that case the
  3. module actually calls itself 'nt' or 'os2', not 'posix', and a few
  4. functions are either unimplemented or implemented differently. The source
  5. assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
  6. of the compiler used. Different compilers define their own feature
  7. test macro, e.g. '__BORLANDC__' or '_MSC_VER'. For OS/2, the compiler
  8. independent macro PYOS_OS2 should be defined. On OS/2 the default
  9. compiler is assumed to be IBM's VisualAge C++ (VACPP). PYCC_GCC is used
  10. as the compiler specific macro for the EMX port of gcc to OS/2. */
  11. /* See also ../Dos/dosmodule.c */
  12. #ifdef __APPLE__
  13. /*
  14. * Step 1 of support for weak-linking a number of symbols existing on
  15. * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
  16. * at the end of this file for more information.
  17. */
  18. # pragma weak lchown
  19. # pragma weak statvfs
  20. # pragma weak fstatvfs
  21. #endif /* __APPLE__ */
  22. #define PY_SSIZE_T_CLEAN
  23. #include "Python.h"
  24. #include "structseq.h"
  25. #if defined(__VMS)
  26. # include <unixio.h>
  27. #endif /* defined(__VMS) */
  28. #ifdef __cplusplus
  29. extern "C" {
  30. #endif
  31. PyDoc_STRVAR(posix__doc__,
  32. "This module provides access to operating system functionality that is\n\
  33. standardized by the C Standard and the POSIX standard (a thinly\n\
  34. disguised Unix interface). Refer to the library manual and\n\
  35. corresponding Unix manual entries for more information on calls.");
  36. #ifndef Py_USING_UNICODE
  37. /* This is used in signatures of functions. */
  38. #define Py_UNICODE void
  39. #endif
  40. #if defined(PYOS_OS2)
  41. #define INCL_DOS
  42. #define INCL_DOSERRORS
  43. #define INCL_DOSPROCESS
  44. #define INCL_NOPMAPI
  45. #include <os2.h>
  46. #if defined(PYCC_GCC)
  47. #include <ctype.h>
  48. #include <io.h>
  49. #include <stdio.h>
  50. #include <process.h>
  51. #endif
  52. #include "osdefs.h"
  53. #endif
  54. #ifdef HAVE_SYS_TYPES_H
  55. #include <sys/types.h>
  56. #endif /* HAVE_SYS_TYPES_H */
  57. #ifdef HAVE_SYS_STAT_H
  58. #include <sys/stat.h>
  59. #endif /* HAVE_SYS_STAT_H */
  60. #ifdef HAVE_SYS_WAIT_H
  61. #include <sys/wait.h> /* For WNOHANG */
  62. #endif
  63. #ifdef HAVE_SIGNAL_H
  64. #include <signal.h>
  65. #endif
  66. #ifdef HAVE_FCNTL_H
  67. #include <fcntl.h>
  68. #endif /* HAVE_FCNTL_H */
  69. #ifdef HAVE_GRP_H
  70. #include <grp.h>
  71. #endif
  72. #ifdef HAVE_SYSEXITS_H
  73. #include <sysexits.h>
  74. #endif /* HAVE_SYSEXITS_H */
  75. #ifdef HAVE_SYS_LOADAVG_H
  76. #include <sys/loadavg.h>
  77. #endif
  78. /* Various compilers have only certain posix functions */
  79. /* XXX Gosh I wish these were all moved into pyconfig.h */
  80. #if defined(PYCC_VACPP) && defined(PYOS_OS2)
  81. #include <process.h>
  82. #else
  83. #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
  84. #define HAVE_GETCWD 1
  85. #define HAVE_OPENDIR 1
  86. #define HAVE_SYSTEM 1
  87. #if defined(__OS2__)
  88. #define HAVE_EXECV 1
  89. #define HAVE_WAIT 1
  90. #endif
  91. #include <process.h>
  92. #else
  93. #ifdef __BORLANDC__ /* Borland compiler */
  94. #define HAVE_EXECV 1
  95. #define HAVE_GETCWD 1
  96. #define HAVE_OPENDIR 1
  97. #define HAVE_PIPE 1
  98. #define HAVE_POPEN 1
  99. #define HAVE_SYSTEM 1
  100. #define HAVE_WAIT 1
  101. #else
  102. #ifdef _MSC_VER /* Microsoft compiler */
  103. #define HAVE_GETCWD 1
  104. #define HAVE_SPAWNV 1
  105. #define HAVE_EXECV 1
  106. #define HAVE_PIPE 1
  107. #define HAVE_POPEN 1
  108. #define HAVE_SYSTEM 1
  109. #define HAVE_CWAIT 1
  110. #define HAVE_FSYNC 1
  111. #define fsync _commit
  112. #else
  113. #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS)
  114. /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */
  115. #else /* all other compilers */
  116. /* Unix functions that the configure script doesn't check for */
  117. #define HAVE_EXECV 1
  118. #define HAVE_FORK 1
  119. #if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
  120. #define HAVE_FORK1 1
  121. #endif
  122. #define HAVE_GETCWD 1
  123. #define HAVE_GETEGID 1
  124. #define HAVE_GETEUID 1
  125. #define HAVE_GETGID 1
  126. #define HAVE_GETPPID 1
  127. #define HAVE_GETUID 1
  128. #define HAVE_KILL 1
  129. #define HAVE_OPENDIR 1
  130. #define HAVE_PIPE 1
  131. #ifndef __rtems__
  132. #define HAVE_POPEN 1
  133. #endif
  134. #define HAVE_SYSTEM 1
  135. #define HAVE_WAIT 1
  136. #define HAVE_TTYNAME 1
  137. #endif /* PYOS_OS2 && PYCC_GCC && __VMS */
  138. #endif /* _MSC_VER */
  139. #endif /* __BORLANDC__ */
  140. #endif /* ! __WATCOMC__ || __QNX__ */
  141. #endif /* ! __IBMC__ */
  142. #ifndef _MSC_VER
  143. #if defined(__sgi)&&_COMPILER_VERSION>=700
  144. /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
  145. (default) */
  146. extern char *ctermid_r(char *);
  147. #endif
  148. #ifndef HAVE_UNISTD_H
  149. #if defined(PYCC_VACPP)
  150. extern int mkdir(char *);
  151. #else
  152. #if ( defined(__WATCOMC__) || defined(_MSC_VER) ) && !defined(__QNX__)
  153. extern int mkdir(const char *);
  154. #else
  155. extern int mkdir(const char *, mode_t);
  156. #endif
  157. #endif
  158. #if defined(__IBMC__) || defined(__IBMCPP__)
  159. extern int chdir(char *);
  160. extern int rmdir(char *);
  161. #else
  162. extern int chdir(const char *);
  163. extern int rmdir(const char *);
  164. #endif
  165. #ifdef __BORLANDC__
  166. extern int chmod(const char *, int);
  167. #else
  168. extern int chmod(const char *, mode_t);
  169. #endif
  170. /*#ifdef HAVE_FCHMOD
  171. extern int fchmod(int, mode_t);
  172. #endif*/
  173. /*#ifdef HAVE_LCHMOD
  174. extern int lchmod(const char *, mode_t);
  175. #endif*/
  176. extern int chown(const char *, uid_t, gid_t);
  177. extern char *getcwd(char *, int);
  178. extern char *strerror(int);
  179. extern int link(const char *, const char *);
  180. extern int rename(const char *, const char *);
  181. extern int stat(const char *, struct stat *);
  182. extern int unlink(const char *);
  183. extern int pclose(FILE *);
  184. #ifdef HAVE_SYMLINK
  185. extern int symlink(const char *, const char *);
  186. #endif /* HAVE_SYMLINK */
  187. #ifdef HAVE_LSTAT
  188. extern int lstat(const char *, struct stat *);
  189. #endif /* HAVE_LSTAT */
  190. #endif /* !HAVE_UNISTD_H */
  191. #endif /* !_MSC_VER */
  192. #ifdef HAVE_UTIME_H
  193. #include <utime.h>
  194. #endif /* HAVE_UTIME_H */
  195. #ifdef HAVE_SYS_UTIME_H
  196. #include <sys/utime.h>
  197. #define HAVE_UTIME_H /* pretend we do for the rest of this file */
  198. #endif /* HAVE_SYS_UTIME_H */
  199. #ifdef HAVE_SYS_TIMES_H
  200. #include <sys/times.h>
  201. #endif /* HAVE_SYS_TIMES_H */
  202. #ifdef HAVE_SYS_PARAM_H
  203. #include <sys/param.h>
  204. #endif /* HAVE_SYS_PARAM_H */
  205. #ifdef HAVE_SYS_UTSNAME_H
  206. #include <sys/utsname.h>
  207. #endif /* HAVE_SYS_UTSNAME_H */
  208. #ifdef HAVE_DIRENT_H
  209. #include <dirent.h>
  210. #define NAMLEN(dirent) strlen((dirent)->d_name)
  211. #else
  212. #if defined(__WATCOMC__) && !defined(__QNX__)
  213. #include <direct.h>
  214. #define NAMLEN(dirent) strlen((dirent)->d_name)
  215. #else
  216. #define dirent direct
  217. #define NAMLEN(dirent) (dirent)->d_namlen
  218. #endif
  219. #ifdef HAVE_SYS_NDIR_H
  220. #include <sys/ndir.h>
  221. #endif
  222. #ifdef HAVE_SYS_DIR_H
  223. #include <sys/dir.h>
  224. #endif
  225. #ifdef HAVE_NDIR_H
  226. #include <ndir.h>
  227. #endif
  228. #endif
  229. #ifdef _MSC_VER
  230. #ifdef HAVE_DIRECT_H
  231. #include <direct.h>
  232. #endif
  233. #ifdef HAVE_IO_H
  234. #include <io.h>
  235. #endif
  236. #ifdef HAVE_PROCESS_H
  237. #include <process.h>
  238. #endif
  239. #include "osdefs.h"
  240. #include <windows.h>
  241. #include <shellapi.h> /* for ShellExecute() */
  242. #define popen _popen
  243. #define pclose _pclose
  244. #endif /* _MSC_VER */
  245. #if defined(PYCC_VACPP) && defined(PYOS_OS2)
  246. #include <io.h>
  247. #endif /* OS2 */
  248. #ifndef MAXPATHLEN
  249. #if defined(PATH_MAX) && PATH_MAX > 1024
  250. #define MAXPATHLEN PATH_MAX
  251. #else
  252. #define MAXPATHLEN 1024
  253. #endif
  254. #endif /* MAXPATHLEN */
  255. #ifdef UNION_WAIT
  256. /* Emulate some macros on systems that have a union instead of macros */
  257. #ifndef WIFEXITED
  258. #define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
  259. #endif
  260. #ifndef WEXITSTATUS
  261. #define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
  262. #endif
  263. #ifndef WTERMSIG
  264. #define WTERMSIG(u_wait) ((u_wait).w_termsig)
  265. #endif
  266. #define WAIT_TYPE union wait
  267. #define WAIT_STATUS_INT(s) (s.w_status)
  268. #else /* !UNION_WAIT */
  269. #define WAIT_TYPE int
  270. #define WAIT_STATUS_INT(s) (s)
  271. #endif /* UNION_WAIT */
  272. /* Issue #1983: pid_t can be longer than a C long on some systems */
  273. #if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT
  274. #define PARSE_PID "i"
  275. #define PyLong_FromPid PyInt_FromLong
  276. #define PyLong_AsPid PyInt_AsLong
  277. #elif SIZEOF_PID_T == SIZEOF_LONG
  278. #define PARSE_PID "l"
  279. #define PyLong_FromPid PyInt_FromLong
  280. #define PyLong_AsPid PyInt_AsLong
  281. #elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
  282. #define PARSE_PID "L"
  283. #define PyLong_FromPid PyLong_FromLongLong
  284. #define PyLong_AsPid PyInt_AsLongLong
  285. #else
  286. #error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)"
  287. #endif /* SIZEOF_PID_T */
  288. /* Don't use the "_r" form if we don't need it (also, won't have a
  289. prototype for it, at least on Solaris -- maybe others as well?). */
  290. #if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)
  291. #define USE_CTERMID_R
  292. #endif
  293. #if defined(HAVE_TMPNAM_R) && defined(WITH_THREAD)
  294. #define USE_TMPNAM_R
  295. #endif
  296. /* choose the appropriate stat and fstat functions and return structs */
  297. #undef STAT
  298. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  299. # define STAT win32_stat
  300. # define FSTAT win32_fstat
  301. # define STRUCT_STAT struct win32_stat
  302. #else
  303. # define STAT stat
  304. # define FSTAT fstat
  305. # define STRUCT_STAT struct stat
  306. #endif
  307. #if defined(MAJOR_IN_MKDEV)
  308. #include <sys/mkdev.h>
  309. #else
  310. #if defined(MAJOR_IN_SYSMACROS)
  311. #include <sys/sysmacros.h>
  312. #endif
  313. #if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
  314. #include <sys/mkdev.h>
  315. #endif
  316. #endif
  317. /* Return a dictionary corresponding to the POSIX environment table */
  318. #ifdef WITH_NEXT_FRAMEWORK
  319. /* On Darwin/MacOSX a shared library or framework has no access to
  320. ** environ directly, we must obtain it with _NSGetEnviron().
  321. */
  322. #include <crt_externs.h>
  323. static char **environ;
  324. #elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
  325. extern char **environ;
  326. #endif /* !_MSC_VER */
  327. static PyObject *
  328. convertenviron(void)
  329. {
  330. PyObject *d;
  331. char **e;
  332. d = PyDict_New();
  333. if (d == NULL)
  334. return NULL;
  335. #ifdef WITH_NEXT_FRAMEWORK
  336. if (environ == NULL)
  337. environ = *_NSGetEnviron();
  338. #endif
  339. if (environ == NULL)
  340. return d;
  341. /* This part ignores errors */
  342. for (e = environ; *e != NULL; e++) {
  343. PyObject *k;
  344. PyObject *v;
  345. char *p = strchr(*e, '=');
  346. if (p == NULL)
  347. continue;
  348. k = PyString_FromStringAndSize(*e, (int)(p-*e));
  349. if (k == NULL) {
  350. PyErr_Clear();
  351. continue;
  352. }
  353. v = PyString_FromString(p+1);
  354. if (v == NULL) {
  355. PyErr_Clear();
  356. Py_DECREF(k);
  357. continue;
  358. }
  359. if (PyDict_GetItem(d, k) == NULL) {
  360. if (PyDict_SetItem(d, k, v) != 0)
  361. PyErr_Clear();
  362. }
  363. Py_DECREF(k);
  364. Py_DECREF(v);
  365. }
  366. #if defined(PYOS_OS2)
  367. {
  368. APIRET rc;
  369. char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */
  370. rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH);
  371. if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
  372. PyObject *v = PyString_FromString(buffer);
  373. PyDict_SetItemString(d, "BEGINLIBPATH", v);
  374. Py_DECREF(v);
  375. }
  376. rc = DosQueryExtLIBPATH(buffer, END_LIBPATH);
  377. if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */
  378. PyObject *v = PyString_FromString(buffer);
  379. PyDict_SetItemString(d, "ENDLIBPATH", v);
  380. Py_DECREF(v);
  381. }
  382. }
  383. #endif
  384. return d;
  385. }
  386. /* Set a POSIX-specific error from errno, and return NULL */
  387. static PyObject *
  388. posix_error(void)
  389. {
  390. return PyErr_SetFromErrno(PyExc_OSError);
  391. }
  392. static PyObject *
  393. posix_error_with_filename(char* name)
  394. {
  395. return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
  396. }
  397. #ifdef Py_WIN_WIDE_FILENAMES
  398. static PyObject *
  399. posix_error_with_unicode_filename(Py_UNICODE* name)
  400. {
  401. return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name);
  402. }
  403. #endif /* Py_WIN_WIDE_FILENAMES */
  404. static PyObject *
  405. posix_error_with_allocated_filename(char* name)
  406. {
  407. PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
  408. PyMem_Free(name);
  409. return rc;
  410. }
  411. #ifdef MS_WINDOWS
  412. static PyObject *
  413. win32_error(char* function, char* filename)
  414. {
  415. /* XXX We should pass the function name along in the future.
  416. (_winreg.c also wants to pass the function name.)
  417. This would however require an additional param to the
  418. Windows error object, which is non-trivial.
  419. */
  420. errno = GetLastError();
  421. if (filename)
  422. return PyErr_SetFromWindowsErrWithFilename(errno, filename);
  423. else
  424. return PyErr_SetFromWindowsErr(errno);
  425. }
  426. #ifdef Py_WIN_WIDE_FILENAMES
  427. static PyObject *
  428. win32_error_unicode(char* function, Py_UNICODE* filename)
  429. {
  430. /* XXX - see win32_error for comments on 'function' */
  431. errno = GetLastError();
  432. if (filename)
  433. return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename);
  434. else
  435. return PyErr_SetFromWindowsErr(errno);
  436. }
  437. static PyObject *_PyUnicode_FromFileSystemEncodedObject(register PyObject *obj)
  438. {
  439. }
  440. static int
  441. convert_to_unicode(PyObject **param)
  442. {
  443. if (PyUnicode_CheckExact(*param))
  444. Py_INCREF(*param);
  445. else if (PyUnicode_Check(*param))
  446. /* For a Unicode subtype that's not a Unicode object,
  447. return a true Unicode object with the same data. */
  448. *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param),
  449. PyUnicode_GET_SIZE(*param));
  450. else
  451. *param = PyUnicode_FromEncodedObject(*param,
  452. Py_FileSystemDefaultEncoding,
  453. "strict");
  454. return (*param) != NULL;
  455. }
  456. #endif /* Py_WIN_WIDE_FILENAMES */
  457. #endif
  458. #if defined(PYOS_OS2)
  459. /**********************************************************************
  460. * Helper Function to Trim and Format OS/2 Messages
  461. **********************************************************************/
  462. static void
  463. os2_formatmsg(char *msgbuf, int msglen, char *reason)
  464. {
  465. msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
  466. if (strlen(msgbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
  467. char *lastc = &msgbuf[ strlen(msgbuf)-1 ];
  468. while (lastc > msgbuf && isspace(Py_CHARMASK(*lastc)))
  469. *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
  470. }
  471. /* Add Optional Reason Text */
  472. if (reason) {
  473. strcat(msgbuf, " : ");
  474. strcat(msgbuf, reason);
  475. }
  476. }
  477. /**********************************************************************
  478. * Decode an OS/2 Operating System Error Code
  479. *
  480. * A convenience function to lookup an OS/2 error code and return a
  481. * text message we can use to raise a Python exception.
  482. *
  483. * Notes:
  484. * The messages for errors returned from the OS/2 kernel reside in
  485. * the file OSO001.MSG in the \OS2 directory hierarchy.
  486. *
  487. **********************************************************************/
  488. static char *
  489. os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason)
  490. {
  491. APIRET rc;
  492. ULONG msglen;
  493. /* Retrieve Kernel-Related Error Message from OSO001.MSG File */
  494. Py_BEGIN_ALLOW_THREADS
  495. rc = DosGetMessage(NULL, 0, msgbuf, msgbuflen,
  496. errorcode, "oso001.msg", &msglen);
  497. Py_END_ALLOW_THREADS
  498. if (rc == NO_ERROR)
  499. os2_formatmsg(msgbuf, msglen, reason);
  500. else
  501. PyOS_snprintf(msgbuf, msgbuflen,
  502. "unknown OS error #%d", errorcode);
  503. return msgbuf;
  504. }
  505. /* Set an OS/2-specific error and return NULL. OS/2 kernel
  506. errors are not in a global variable e.g. 'errno' nor are
  507. they congruent with posix error numbers. */
  508. static PyObject * os2_error(int code)
  509. {
  510. char text[1024];
  511. PyObject *v;
  512. os2_strerror(text, sizeof(text), code, "");
  513. v = Py_BuildValue("(is)", code, text);
  514. if (v != NULL) {
  515. PyErr_SetObject(PyExc_OSError, v);
  516. Py_DECREF(v);
  517. }
  518. return NULL; /* Signal to Python that an Exception is Pending */
  519. }
  520. #endif /* OS2 */
  521. /* POSIX generic methods */
  522. static PyObject *
  523. posix_fildes(PyObject *fdobj, int (*func)(int))
  524. {
  525. int fd;
  526. int res;
  527. fd = PyObject_AsFileDescriptor(fdobj);
  528. if (fd < 0)
  529. return NULL;
  530. Py_BEGIN_ALLOW_THREADS
  531. res = (*func)(fd);
  532. Py_END_ALLOW_THREADS
  533. if (res < 0)
  534. return posix_error();
  535. Py_INCREF(Py_None);
  536. return Py_None;
  537. }
  538. #ifdef Py_WIN_WIDE_FILENAMES
  539. static int
  540. unicode_file_names(void)
  541. {
  542. static int canusewide = -1;
  543. if (canusewide == -1) {
  544. /* As per doc for ::GetVersion(), this is the correct test for
  545. the Windows NT family. */
  546. canusewide = (GetVersion() < 0x80000000) ? 1 : 0;
  547. }
  548. return canusewide;
  549. }
  550. #endif
  551. static PyObject *
  552. posix_1str(PyObject *args, char *format, int (*func)(const char*))
  553. {
  554. char *path1 = NULL;
  555. int res;
  556. if (!PyArg_ParseTuple(args, format,
  557. Py_FileSystemDefaultEncoding, &path1))
  558. return NULL;
  559. Py_BEGIN_ALLOW_THREADS
  560. res = (*func)(path1);
  561. Py_END_ALLOW_THREADS
  562. if (res < 0)
  563. return posix_error_with_allocated_filename(path1);
  564. PyMem_Free(path1);
  565. Py_INCREF(Py_None);
  566. return Py_None;
  567. }
  568. static PyObject *
  569. posix_2str(PyObject *args,
  570. char *format,
  571. int (*func)(const char *, const char *))
  572. {
  573. char *path1 = NULL, *path2 = NULL;
  574. int res;
  575. if (!PyArg_ParseTuple(args, format,
  576. Py_FileSystemDefaultEncoding, &path1,
  577. Py_FileSystemDefaultEncoding, &path2))
  578. return NULL;
  579. Py_BEGIN_ALLOW_THREADS
  580. res = (*func)(path1, path2);
  581. Py_END_ALLOW_THREADS
  582. PyMem_Free(path1);
  583. PyMem_Free(path2);
  584. if (res != 0)
  585. /* XXX how to report both path1 and path2??? */
  586. return posix_error();
  587. Py_INCREF(Py_None);
  588. return Py_None;
  589. }
  590. #ifdef Py_WIN_WIDE_FILENAMES
  591. static PyObject*
  592. win32_1str(PyObject* args, char* func,
  593. char* format, BOOL (__stdcall *funcA)(LPCSTR),
  594. char* wformat, BOOL (__stdcall *funcW)(LPWSTR))
  595. {
  596. PyObject *uni;
  597. char *ansi;
  598. BOOL result;
  599. if (unicode_file_names()) {
  600. if (!PyArg_ParseTuple(args, wformat, &uni))
  601. PyErr_Clear();
  602. else {
  603. Py_BEGIN_ALLOW_THREADS
  604. result = funcW(PyUnicode_AsUnicode(uni));
  605. Py_END_ALLOW_THREADS
  606. if (!result)
  607. return win32_error_unicode(func, PyUnicode_AsUnicode(uni));
  608. Py_INCREF(Py_None);
  609. return Py_None;
  610. }
  611. }
  612. if (!PyArg_ParseTuple(args, format, &ansi))
  613. return NULL;
  614. Py_BEGIN_ALLOW_THREADS
  615. result = funcA(ansi);
  616. Py_END_ALLOW_THREADS
  617. if (!result)
  618. return win32_error(func, ansi);
  619. Py_INCREF(Py_None);
  620. return Py_None;
  621. }
  622. /* This is a reimplementation of the C library's chdir function,
  623. but one that produces Win32 errors instead of DOS error codes.
  624. chdir is essentially a wrapper around SetCurrentDirectory; however,
  625. it also needs to set "magic" environment variables indicating
  626. the per-drive current directory, which are of the form =<drive>: */
  627. BOOL __stdcall
  628. win32_chdir(LPCSTR path)
  629. {
  630. char new_path[MAX_PATH+1];
  631. int result;
  632. char env[4] = "=x:";
  633. if(!SetCurrentDirectoryA(path))
  634. return FALSE;
  635. result = GetCurrentDirectoryA(MAX_PATH+1, new_path);
  636. if (!result)
  637. return FALSE;
  638. /* In the ANSI API, there should not be any paths longer
  639. than MAX_PATH. */
  640. assert(result <= MAX_PATH+1);
  641. if (strncmp(new_path, "\\\\", 2) == 0 ||
  642. strncmp(new_path, "//", 2) == 0)
  643. /* UNC path, nothing to do. */
  644. return TRUE;
  645. env[1] = new_path[0];
  646. return SetEnvironmentVariableA(env, new_path);
  647. }
  648. /* The Unicode version differs from the ANSI version
  649. since the current directory might exceed MAX_PATH characters */
  650. BOOL __stdcall
  651. win32_wchdir(LPCWSTR path)
  652. {
  653. wchar_t _new_path[MAX_PATH+1], *new_path = _new_path;
  654. int result;
  655. wchar_t env[4] = L"=x:";
  656. if(!SetCurrentDirectoryW(path))
  657. return FALSE;
  658. result = GetCurrentDirectoryW(MAX_PATH+1, new_path);
  659. if (!result)
  660. return FALSE;
  661. if (result > MAX_PATH+1) {
  662. new_path = malloc(result * sizeof(wchar_t));
  663. if (!new_path) {
  664. SetLastError(ERROR_OUTOFMEMORY);
  665. return FALSE;
  666. }
  667. result = GetCurrentDirectoryW(result, new_path);
  668. if (!result) {
  669. free(new_path);
  670. return FALSE;
  671. }
  672. }
  673. if (wcsncmp(new_path, L"\\\\", 2) == 0 ||
  674. wcsncmp(new_path, L"//", 2) == 0)
  675. /* UNC path, nothing to do. */
  676. return TRUE;
  677. env[1] = new_path[0];
  678. result = SetEnvironmentVariableW(env, new_path);
  679. if (new_path != _new_path)
  680. free(new_path);
  681. return result;
  682. }
  683. #endif
  684. #ifdef MS_WINDOWS
  685. /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
  686. - time stamps are restricted to second resolution
  687. - file modification times suffer from forth-and-back conversions between
  688. UTC and local time
  689. Therefore, we implement our own stat, based on the Win32 API directly.
  690. */
  691. #define HAVE_STAT_NSEC 1
  692. struct win32_stat{
  693. int st_dev;
  694. __int64 st_ino;
  695. unsigned short st_mode;
  696. int st_nlink;
  697. int st_uid;
  698. int st_gid;
  699. int st_rdev;
  700. __int64 st_size;
  701. int st_atime;
  702. int st_atime_nsec;
  703. int st_mtime;
  704. int st_mtime_nsec;
  705. int st_ctime;
  706. int st_ctime_nsec;
  707. };
  708. static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
  709. static void
  710. FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out)
  711. {
  712. /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
  713. /* Cannot simply cast and dereference in_ptr,
  714. since it might not be aligned properly */
  715. __int64 in;
  716. memcpy(&in, in_ptr, sizeof(in));
  717. *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
  718. /* XXX Win32 supports time stamps past 2038; we currently don't */
  719. *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int);
  720. }
  721. static void
  722. time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr)
  723. {
  724. /* XXX endianness */
  725. __int64 out;
  726. out = time_in + secs_between_epochs;
  727. out = out * 10000000 + nsec_in / 100;
  728. memcpy(out_ptr, &out, sizeof(out));
  729. }
  730. /* Below, we *know* that ugo+r is 0444 */
  731. #if _S_IREAD != 0400
  732. #error Unsupported C library
  733. #endif
  734. static int
  735. attributes_to_mode(DWORD attr)
  736. {
  737. int m = 0;
  738. if (attr & FILE_ATTRIBUTE_DIRECTORY)
  739. m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
  740. else
  741. m |= _S_IFREG;
  742. if (attr & FILE_ATTRIBUTE_READONLY)
  743. m |= 0444;
  744. else
  745. m |= 0666;
  746. return m;
  747. }
  748. static int
  749. attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result)
  750. {
  751. memset(result, 0, sizeof(*result));
  752. result->st_mode = attributes_to_mode(info->dwFileAttributes);
  753. result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
  754. FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
  755. FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  756. FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  757. return 0;
  758. }
  759. /* Emulate GetFileAttributesEx[AW] on Windows 95 */
  760. static int checked = 0;
  761. static BOOL (CALLBACK *gfaxa)(LPCSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
  762. static BOOL (CALLBACK *gfaxw)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
  763. static void
  764. check_gfax()
  765. {
  766. HINSTANCE hKernel32;
  767. if (checked)
  768. return;
  769. checked = 1;
  770. hKernel32 = GetModuleHandle("KERNEL32");
  771. *(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA");
  772. *(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW");
  773. }
  774. static BOOL
  775. attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
  776. {
  777. HANDLE hFindFile;
  778. WIN32_FIND_DATAA FileData;
  779. hFindFile = FindFirstFileA(pszFile, &FileData);
  780. if (hFindFile == INVALID_HANDLE_VALUE)
  781. return FALSE;
  782. FindClose(hFindFile);
  783. pfad->dwFileAttributes = FileData.dwFileAttributes;
  784. pfad->ftCreationTime = FileData.ftCreationTime;
  785. pfad->ftLastAccessTime = FileData.ftLastAccessTime;
  786. pfad->ftLastWriteTime = FileData.ftLastWriteTime;
  787. pfad->nFileSizeHigh = FileData.nFileSizeHigh;
  788. pfad->nFileSizeLow = FileData.nFileSizeLow;
  789. return TRUE;
  790. }
  791. static BOOL
  792. attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
  793. {
  794. HANDLE hFindFile;
  795. WIN32_FIND_DATAW FileData;
  796. hFindFile = FindFirstFileW(pszFile, &FileData);
  797. if (hFindFile == INVALID_HANDLE_VALUE)
  798. return FALSE;
  799. FindClose(hFindFile);
  800. pfad->dwFileAttributes = FileData.dwFileAttributes;
  801. pfad->ftCreationTime = FileData.ftCreationTime;
  802. pfad->ftLastAccessTime = FileData.ftLastAccessTime;
  803. pfad->ftLastWriteTime = FileData.ftLastWriteTime;
  804. pfad->nFileSizeHigh = FileData.nFileSizeHigh;
  805. pfad->nFileSizeLow = FileData.nFileSizeLow;
  806. return TRUE;
  807. }
  808. static BOOL WINAPI
  809. Py_GetFileAttributesExA(LPCSTR pszFile,
  810. GET_FILEEX_INFO_LEVELS level,
  811. LPVOID pv)
  812. {
  813. BOOL result;
  814. LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;
  815. /* First try to use the system's implementation, if that is
  816. available and either succeeds to gives an error other than
  817. that it isn't implemented. */
  818. check_gfax();
  819. if (gfaxa) {
  820. result = gfaxa(pszFile, level, pv);
  821. if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
  822. return result;
  823. }
  824. /* It's either not present, or not implemented.
  825. Emulate using FindFirstFile. */
  826. if (level != GetFileExInfoStandard) {
  827. SetLastError(ERROR_INVALID_PARAMETER);
  828. return FALSE;
  829. }
  830. /* Use GetFileAttributes to validate that the file name
  831. does not contain wildcards (which FindFirstFile would
  832. accept). */
  833. if (GetFileAttributesA(pszFile) == 0xFFFFFFFF)
  834. return FALSE;
  835. return attributes_from_dir(pszFile, pfad);
  836. }
  837. static BOOL WINAPI
  838. Py_GetFileAttributesExW(LPCWSTR pszFile,
  839. GET_FILEEX_INFO_LEVELS level,
  840. LPVOID pv)
  841. {
  842. BOOL result;
  843. LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;
  844. /* First try to use the system's implementation, if that is
  845. available and either succeeds to gives an error other than
  846. that it isn't implemented. */
  847. check_gfax();
  848. if (gfaxa) {
  849. result = gfaxw(pszFile, level, pv);
  850. if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
  851. return result;
  852. }
  853. /* It's either not present, or not implemented.
  854. Emulate using FindFirstFile. */
  855. if (level != GetFileExInfoStandard) {
  856. SetLastError(ERROR_INVALID_PARAMETER);
  857. return FALSE;
  858. }
  859. /* Use GetFileAttributes to validate that the file name
  860. does not contain wildcards (which FindFirstFile would
  861. accept). */
  862. if (GetFileAttributesW(pszFile) == 0xFFFFFFFF)
  863. return FALSE;
  864. return attributes_from_dir_w(pszFile, pfad);
  865. }
  866. static int
  867. win32_stat(const char* path, struct win32_stat *result)
  868. {
  869. WIN32_FILE_ATTRIBUTE_DATA info;
  870. int code;
  871. char *dot;
  872. /* XXX not supported on Win95 and NT 3.x */
  873. if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
  874. if (GetLastError() != ERROR_SHARING_VIOLATION) {
  875. /* Protocol violation: we explicitly clear errno, instead of
  876. setting it to a POSIX error. Callers should use GetLastError. */
  877. errno = 0;
  878. return -1;
  879. } else {
  880. /* Could not get attributes on open file. Fall back to
  881. reading the directory. */
  882. if (!attributes_from_dir(path, &info)) {
  883. /* Very strange. This should not fail now */
  884. errno = 0;
  885. return -1;
  886. }
  887. }
  888. }
  889. code = attribute_data_to_stat(&info, result);
  890. if (code != 0)
  891. return code;
  892. /* Set S_IFEXEC if it is an .exe, .bat, ... */
  893. dot = strrchr(path, '.');
  894. if (dot) {
  895. if (stricmp(dot, ".bat") == 0 ||
  896. stricmp(dot, ".cmd") == 0 ||
  897. stricmp(dot, ".exe") == 0 ||
  898. stricmp(dot, ".com") == 0)
  899. result->st_mode |= 0111;
  900. }
  901. return code;
  902. }
  903. static int
  904. win32_wstat(const wchar_t* path, struct win32_stat *result)
  905. {
  906. int code;
  907. const wchar_t *dot;
  908. WIN32_FILE_ATTRIBUTE_DATA info;
  909. /* XXX not supported on Win95 and NT 3.x */
  910. if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
  911. if (GetLastError() != ERROR_SHARING_VIOLATION) {
  912. /* Protocol violation: we explicitly clear errno, instead of
  913. setting it to a POSIX error. Callers should use GetLastError. */
  914. errno = 0;
  915. return -1;
  916. } else {
  917. /* Could not get attributes on open file. Fall back to
  918. reading the directory. */
  919. if (!attributes_from_dir_w(path, &info)) {
  920. /* Very strange. This should not fail now */
  921. errno = 0;
  922. return -1;
  923. }
  924. }
  925. }
  926. code = attribute_data_to_stat(&info, result);
  927. if (code < 0)
  928. return code;
  929. /* Set IFEXEC if it is an .exe, .bat, ... */
  930. dot = wcsrchr(path, '.');
  931. if (dot) {
  932. if (_wcsicmp(dot, L".bat") == 0 ||
  933. _wcsicmp(dot, L".cmd") == 0 ||
  934. _wcsicmp(dot, L".exe") == 0 ||
  935. _wcsicmp(dot, L".com") == 0)
  936. result->st_mode |= 0111;
  937. }
  938. return code;
  939. }
  940. static int
  941. win32_fstat(int file_number, struct win32_stat *result)
  942. {
  943. BY_HANDLE_FILE_INFORMATION info;
  944. HANDLE h;
  945. int type;
  946. h = (HANDLE)_get_osfhandle(file_number);
  947. /* Protocol violation: we explicitly clear errno, instead of
  948. setting it to a POSIX error. Callers should use GetLastError. */
  949. errno = 0;
  950. if (h == INVALID_HANDLE_VALUE) {
  951. /* This is really a C library error (invalid file handle).
  952. We set the Win32 error to the closes one matching. */
  953. SetLastError(ERROR_INVALID_HANDLE);
  954. return -1;
  955. }
  956. memset(result, 0, sizeof(*result));
  957. type = GetFileType(h);
  958. if (type == FILE_TYPE_UNKNOWN) {
  959. DWORD error = GetLastError();
  960. if (error != 0) {
  961. return -1;
  962. }
  963. /* else: valid but unknown file */
  964. }
  965. if (type != FILE_TYPE_DISK) {
  966. if (type == FILE_TYPE_CHAR)
  967. result->st_mode = _S_IFCHR;
  968. else if (type == FILE_TYPE_PIPE)
  969. result->st_mode = _S_IFIFO;
  970. return 0;
  971. }
  972. if (!GetFileInformationByHandle(h, &info)) {
  973. return -1;
  974. }
  975. /* similar to stat() */
  976. result->st_mode = attributes_to_mode(info.dwFileAttributes);
  977. result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow;
  978. FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
  979. FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  980. FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  981. /* specific to fstat() */
  982. result->st_nlink = info.nNumberOfLinks;
  983. result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
  984. return 0;
  985. }
  986. #endif /* MS_WINDOWS */
  987. PyDoc_STRVAR(stat_result__doc__,
  988. "stat_result: Result from stat or lstat.\n\n\
  989. This object may be accessed either as a tuple of\n\
  990. (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
  991. or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
  992. \n\
  993. Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
  994. or st_flags, they are available as attributes only.\n\
  995. \n\
  996. See os.stat for more information.");
  997. static PyStructSequence_Field stat_result_fields[] = {
  998. {"st_mode", "protection bits"},
  999. {"st_ino", "inode"},
  1000. {"st_dev", "device"},
  1001. {"st_nlink", "number of hard links"},
  1002. {"st_uid", "user ID of owner"},
  1003. {"st_gid", "group ID of owner"},
  1004. {"st_size", "total size, in bytes"},
  1005. /* The NULL is replaced with PyStructSequence_UnnamedField later. */
  1006. {NULL, "integer time of last access"},
  1007. {NULL, "integer time of last modification"},
  1008. {NULL, "integer time of last change"},
  1009. {"st_atime", "time of last access"},
  1010. {"st_mtime", "time of last modification"},
  1011. {"st_ctime", "time of last change"},
  1012. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1013. {"st_blksize", "blocksize for filesystem I/O"},
  1014. #endif
  1015. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1016. {"st_blocks", "number of blocks allocated"},
  1017. #endif
  1018. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1019. {"st_rdev", "device type (if inode device)"},
  1020. #endif
  1021. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1022. {"st_flags", "user defined flags for file"},
  1023. #endif
  1024. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1025. {"st_gen", "generation number"},
  1026. #endif
  1027. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1028. {"st_birthtime", "time of creation"},
  1029. #endif
  1030. {0}
  1031. };
  1032. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1033. #define ST_BLKSIZE_IDX 13
  1034. #else
  1035. #define ST_BLKSIZE_IDX 12
  1036. #endif
  1037. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1038. #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
  1039. #else
  1040. #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
  1041. #endif
  1042. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1043. #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
  1044. #else
  1045. #define ST_RDEV_IDX ST_BLOCKS_IDX
  1046. #endif
  1047. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1048. #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
  1049. #else
  1050. #define ST_FLAGS_IDX ST_RDEV_IDX
  1051. #endif
  1052. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1053. #define ST_GEN_IDX (ST_FLAGS_IDX+1)
  1054. #else
  1055. #define ST_GEN_IDX ST_FLAGS_IDX
  1056. #endif
  1057. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1058. #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
  1059. #else
  1060. #define ST_BIRTHTIME_IDX ST_GEN_IDX
  1061. #endif
  1062. static PyStructSequence_Desc stat_result_desc = {
  1063. "stat_result", /* name */
  1064. stat_result__doc__, /* doc */
  1065. stat_result_fields,
  1066. 10
  1067. };
  1068. PyDoc_STRVAR(statvfs_result__doc__,
  1069. "statvfs_result: Result from statvfs or fstatvfs.\n\n\
  1070. This object may be accessed either as a tuple of\n\
  1071. (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
  1072. or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
  1073. \n\
  1074. See os.statvfs for more information.");
  1075. static PyStructSequence_Field statvfs_result_fields[] = {
  1076. {"f_bsize", },
  1077. {"f_frsize", },
  1078. {"f_blocks", },
  1079. {"f_bfree", },
  1080. {"f_bavail", },
  1081. {"f_files", },
  1082. {"f_ffree", },
  1083. {"f_favail", },
  1084. {"f_flag", },
  1085. {"f_namemax",},
  1086. {0}
  1087. };
  1088. static PyStructSequence_Desc statvfs_result_desc = {
  1089. "statvfs_result", /* name */
  1090. statvfs_result__doc__, /* doc */
  1091. statvfs_result_fields,
  1092. 10
  1093. };
  1094. static int initialized;
  1095. static PyTypeObject StatResultType;
  1096. static PyTypeObject StatVFSResultType;
  1097. static newfunc structseq_new;
  1098. static PyObject *
  1099. statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1100. {
  1101. PyStructSequence *result;
  1102. int i;
  1103. result = (PyStructSequence*)structseq_new(type, args, kwds);
  1104. if (!result)
  1105. return NULL;
  1106. /* If we have been initialized from a tuple,
  1107. st_?time might be set to None. Initialize it
  1108. from the int slots. */
  1109. for (i = 7; i <= 9; i++) {
  1110. if (result->ob_item[i+3] == Py_None) {
  1111. Py_DECREF(Py_None);
  1112. Py_INCREF(result->ob_item[i]);
  1113. result->ob_item[i+3] = result->ob_item[i];
  1114. }
  1115. }
  1116. return (PyObject*)result;
  1117. }
  1118. /* If true, st_?time is float. */
  1119. static int _stat_float_times = 1;
  1120. PyDoc_STRVAR(stat_float_times__doc__,
  1121. "stat_float_times([newval]) -> oldval\n\n\
  1122. Determine whether os.[lf]stat represents time stamps as float objects.\n\
  1123. If newval is True, future calls to stat() return floats, if it is False,\n\
  1124. future calls return ints. \n\
  1125. If newval is omitted, return the current setting.\n");
  1126. static PyObject*
  1127. stat_float_times(PyObject* self, PyObject *args)
  1128. {
  1129. int newval = -1;
  1130. if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval))
  1131. return NULL;
  1132. if (newval == -1)
  1133. /* Return old value */
  1134. return PyBool_FromLong(_stat_float_times);
  1135. _stat_float_times = newval;
  1136. Py_INCREF(Py_None);
  1137. return Py_None;
  1138. }
  1139. static void
  1140. fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
  1141. {
  1142. PyObject *fval,*ival;
  1143. #if SIZEOF_TIME_T > SIZEOF_LONG
  1144. ival = PyLong_FromLongLong((PY_LONG_LONG)sec);
  1145. #else
  1146. ival = PyInt_FromLong((long)sec);
  1147. #endif
  1148. if (!ival)
  1149. return;
  1150. if (_stat_float_times) {
  1151. fval = PyFloat_FromDouble(sec + 1e-9*nsec);
  1152. } else {
  1153. fval = ival;
  1154. Py_INCREF(fval);
  1155. }
  1156. PyStructSequence_SET_ITEM(v, index, ival);
  1157. PyStructSequence_SET_ITEM(v, index+3, fval);
  1158. }
  1159. /* pack a system stat C structure into the Python stat tuple
  1160. (used by posix_stat() and posix_fstat()) */
  1161. static PyObject*
  1162. _pystat_fromstructstat(STRUCT_STAT *st)
  1163. {
  1164. unsigned long ansec, mnsec, cnsec;
  1165. PyObject *v = PyStructSequence_New(&StatResultType);
  1166. if (v == NULL)
  1167. return NULL;
  1168. PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode));
  1169. #ifdef HAVE_LARGEFILE_SUPPORT
  1170. PyStructSequence_SET_ITEM(v, 1,
  1171. PyLong_FromLongLong((PY_LONG_LONG)st->st_ino));
  1172. #else
  1173. PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino));
  1174. #endif
  1175. #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS)
  1176. PyStructSequence_SET_ITEM(v, 2,
  1177. PyLong_FromLongLong((PY_LONG_LONG)st->st_dev));
  1178. #else
  1179. PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev));
  1180. #endif
  1181. PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink));
  1182. PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long)st->st_uid));
  1183. PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long)st->st_gid));
  1184. #ifdef HAVE_LARGEFILE_SUPPORT
  1185. PyStructSequence_SET_ITEM(v, 6,
  1186. PyLong_FromLongLong((PY_LONG_LONG)st->st_size));
  1187. #else
  1188. PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size));
  1189. #endif
  1190. #if defined(HAVE_STAT_TV_NSEC)
  1191. ansec = st->st_atim.tv_nsec;
  1192. mnsec = st->st_mtim.tv_nsec;
  1193. cnsec = st->st_ctim.tv_nsec;
  1194. #elif defined(HAVE_STAT_TV_NSEC2)
  1195. ansec = st->st_atimespec.tv_nsec;
  1196. mnsec = st->st_mtimespec.tv_nsec;
  1197. cnsec = st->st_ctimespec.tv_nsec;
  1198. #elif defined(HAVE_STAT_NSEC)
  1199. ansec = st->st_atime_nsec;
  1200. mnsec = st->st_mtime_nsec;
  1201. cnsec = st->st_ctime_nsec;
  1202. #else
  1203. ansec = mnsec = cnsec = 0;
  1204. #endif
  1205. fill_time(v, 7, st->st_atime, ansec);
  1206. fill_time(v, 8, st->st_mtime, mnsec);
  1207. fill_time(v, 9, st->st_ctime, cnsec);
  1208. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1209. PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
  1210. PyInt_FromLong((long)st->st_blksize));
  1211. #endif
  1212. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1213. PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
  1214. PyInt_FromLong((long)st->st_blocks));
  1215. #endif
  1216. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1217. PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
  1218. PyInt_FromLong((long)st->st_rdev));
  1219. #endif
  1220. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1221. PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
  1222. PyInt_FromLong((long)st->st_gen));
  1223. #endif
  1224. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1225. {
  1226. PyObject *val;
  1227. unsigned long bsec,bnsec;
  1228. bsec = (long)st->st_birthtime;
  1229. #ifdef HAVE_STAT_TV_NSEC2
  1230. bnsec = st->st_birthtimespec.tv_nsec;
  1231. #else
  1232. bnsec = 0;
  1233. #endif
  1234. if (_stat_float_times) {
  1235. val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
  1236. } else {
  1237. val = PyInt_FromLong((long)bsec);
  1238. }
  1239. PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
  1240. val);
  1241. }
  1242. #endif
  1243. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1244. PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
  1245. PyInt_FromLong((long)st->st_flags));
  1246. #endif
  1247. if (PyErr_Occurred()) {
  1248. Py_DECREF(v);
  1249. return NULL;
  1250. }
  1251. return v;
  1252. }
  1253. #ifdef MS_WINDOWS
  1254. /* IsUNCRoot -- test whether the supplied path is of the form \\SERVER\SHARE\,
  1255. where / can be used in place of \ and the trailing slash is optional.
  1256. Both SERVER and SHARE must have at least one character.
  1257. */
  1258. #define ISSLASHA(c) ((c) == '\\' || (c) == '/')
  1259. #define ISSLASHW(c) ((c) == L'\\' || (c) == L'/')
  1260. #ifndef ARRAYSIZE
  1261. #define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
  1262. #endif
  1263. static BOOL
  1264. IsUNCRootA(char *path, int pathlen)
  1265. {
  1266. #define ISSLASH ISSLASHA
  1267. int i, share;
  1268. if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
  1269. /* minimum UNCRoot is \\x\y */
  1270. return FALSE;
  1271. for (i = 2; i < pathlen ; i++)
  1272. if (ISSLASH(path[i])) break;
  1273. if (i == 2 || i == pathlen)
  1274. /* do not allow \\\SHARE or \\SERVER */
  1275. return FALSE;
  1276. share = i+1;
  1277. for (i = share; i < pathlen; i++)
  1278. if (ISSLASH(path[i])) break;
  1279. return (i != share && (i == pathlen || i == pathlen-1));
  1280. #undef ISSLASH
  1281. }
  1282. #ifdef Py_WIN_WIDE_FILENAMES
  1283. static BOOL
  1284. IsUNCRootW(Py_UNICODE *path, int pathlen)
  1285. {
  1286. #define ISSLASH ISSLASHW
  1287. int i, share;
  1288. if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
  1289. /* minimum UNCRoot is \\x\y */
  1290. return FALSE;
  1291. for (i = 2; i < pathlen ; i++)
  1292. if (ISSLASH(path[i])) break;
  1293. if (i == 2 || i == pathlen)
  1294. /* do not allow \\\SHARE or \\SERVER */
  1295. return FALSE;
  1296. share = i+1;
  1297. for (i = share; i < pathlen; i++)
  1298. if (ISSLASH(path[i])) break;
  1299. return (i != share && (i == pathlen || i == pathlen-1));
  1300. #undef ISSLASH
  1301. }
  1302. #endif /* Py_WIN_WIDE_FILENAMES */
  1303. #endif /* MS_WINDOWS */
  1304. static PyObject *
  1305. posix_do_stat(PyObject *self, PyObject *args,
  1306. char *format,
  1307. #ifdef __VMS
  1308. int (*statfunc)(const char *, STRUCT_STAT *, ...),
  1309. #else
  1310. int (*statfunc)(const char *, STRUCT_STAT *),
  1311. #endif
  1312. char *wformat,
  1313. int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *))
  1314. {
  1315. STRUCT_STAT st;
  1316. char *path = NULL; /* pass this to stat; do not free() it */
  1317. char *pathfree = NULL; /* this memory must be free'd */
  1318. int res;
  1319. PyObject *result;
  1320. #ifdef Py_WIN_WIDE_FILENAMES
  1321. /* If on wide-character-capable OS see if argument
  1322. is Unicode and if so use wide API. */
  1323. if (unicode_file_names()) {
  1324. PyUnicodeObject *po;
  1325. if (PyArg_ParseTuple(args, wformat, &po)) {
  1326. Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
  1327. Py_BEGIN_ALLOW_THREADS
  1328. /* PyUnicode_AS_UNICODE result OK without
  1329. thread lock as it is a simple dereference. */
  1330. res = wstatfunc(wpath, &st);
  1331. Py_END_ALLOW_THREADS
  1332. if (res != 0)
  1333. return win32_error_unicode("stat", wpath);
  1334. return _pystat_fromstructstat(&st);
  1335. }
  1336. /* Drop the argument parsing error as narrow strings
  1337. are also valid. */
  1338. PyErr_Clear();
  1339. }
  1340. #endif
  1341. if (!PyArg_ParseTuple(args, format,
  1342. Py_FileSystemDefaultEncoding, &path))
  1343. return NULL;
  1344. pathfree = path;
  1345. Py_BEGIN_ALLOW_THREADS
  1346. res = (*statfunc)(path, &st);
  1347. Py_END_ALLOW_THREADS
  1348. if (res != 0) {
  1349. #ifdef MS_WINDOWS
  1350. result = win32_error("stat", pathfree);
  1351. #else
  1352. result = posix_error_with_filename(pathfree);
  1353. #endif
  1354. }
  1355. else
  1356. result = _pystat_fromstructstat(&st);
  1357. PyMem_Free(pathfree);
  1358. return result;
  1359. }
  1360. /* POSIX methods */
  1361. PyDoc_STRVAR(posix_access__doc__,
  1362. "access(path, mode) -> True if granted, False otherwise\n\n\
  1363. Use the real uid/gid to test for access to a path. Note that most\n\
  1364. operations will use the effective uid/gid, therefore this routine can\n\
  1365. be used in a suid/sgid environment to test if the invoking user has the\n\
  1366. specified access to the path. The mode argument can be F_OK to test\n\
  1367. existence, or the inclusive-OR of R_OK, W_OK, and X_OK.");
  1368. static PyObject *
  1369. posix_access(PyObject *self, PyObject *args)
  1370. {
  1371. char *path;
  1372. int mode;
  1373. #ifdef Py_WIN_WIDE_FILENAMES
  1374. DWORD attr;
  1375. if (unicode_file_names()) {
  1376. PyUnicodeObject *po;
  1377. if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) {
  1378. Py_BEGIN_ALLOW_THREADS
  1379. /* PyUnicode_AS_UNICODE OK without thread lock as
  1380. it is a simple dereference. */
  1381. attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
  1382. Py_END_ALLOW_THREADS
  1383. goto finish;
  1384. }
  1385. /* Drop the argument parsing error as narrow strings
  1386. are also valid. */
  1387. PyErr_Clear();
  1388. }
  1389. if (!PyArg_ParseTuple(args, "eti:access",
  1390. Py_FileSystemDefaultEncoding, &path, &mode))
  1391. return 0;
  1392. Py_BEGIN_ALLOW_THREADS
  1393. attr = GetFileAttributesA(path);
  1394. Py_END_ALLOW_THREADS
  1395. PyMem_Free(path);
  1396. finish:
  1397. if (attr == 0xFFFFFFFF)
  1398. /* File does not exist, or cannot read attributes */
  1399. return PyBool_FromLong(0);
  1400. /* Access is possible if either write access wasn't requested, or
  1401. the file isn't read-only, or if it's a directory, as there are
  1402. no read-only directories on Windows. */
  1403. return PyBool_FromLong(!(mode & 2)
  1404. || !(attr & FILE_ATTRIBUTE_READONLY)
  1405. || (attr & FILE_ATTRIBUTE_DIRECTORY));
  1406. #else
  1407. int res;
  1408. if (!PyArg_ParseTuple(args, "eti:access",
  1409. Py_FileSystemDefaultEncoding, &path, &mode))
  1410. return NULL;
  1411. Py_BEGIN_ALLOW_THREADS
  1412. res = access(path, mode);
  1413. Py_END_ALLOW_THREADS
  1414. PyMem_Free(path);
  1415. return PyBool_FromLong(res == 0);
  1416. #endif
  1417. }
  1418. #ifndef F_OK
  1419. #define F_OK 0
  1420. #endif
  1421. #ifndef R_OK
  1422. #define R_OK 4
  1423. #endif
  1424. #ifndef W_OK
  1425. #define W_OK 2
  1426. #endif
  1427. #ifndef X_OK
  1428. #define X_OK 1
  1429. #endif
  1430. #ifdef HAVE_TTYNAME
  1431. PyDoc_STRVAR(posix_ttyname__doc__,
  1432. "ttyname(fd) -> string\n\n\
  1433. Return the name of the terminal device connected to 'fd'.");
  1434. static PyObject *
  1435. posix_ttyname(PyObject *self, PyObject *args)
  1436. {
  1437. int id;
  1438. char *ret;
  1439. if (!PyArg_ParseTuple(args, "i:ttyname", &id))
  1440. return NULL;
  1441. #if defined(__VMS)
  1442. /* file descriptor 0 only, the default input device (stdin) */
  1443. if (id == 0) {
  1444. ret = ttyname();
  1445. }
  1446. else {
  1447. ret = NULL;
  1448. }
  1449. #else
  1450. ret = ttyname(id);
  1451. #endif
  1452. if (ret == NULL)
  1453. return posix_error();
  1454. return PyString_FromString(ret);
  1455. }
  1456. #endif
  1457. #ifdef HAVE_CTERMID
  1458. PyDoc_STRVAR(posix_ctermid__doc__,
  1459. "ctermid() -> string\n\n\
  1460. Return the name of the controlling terminal for this process.");
  1461. static PyObject *
  1462. posix_ctermid(PyObject *self, PyObject *noargs)
  1463. {
  1464. char *ret;
  1465. char buffer[L_ctermid];
  1466. #ifdef USE_CTERMID_R
  1467. ret = ctermid_r(buffer);
  1468. #else
  1469. ret = ctermid(buffer);
  1470. #endif
  1471. if (ret == NULL)
  1472. return posix_error();
  1473. return PyString_FromString(buffer);
  1474. }
  1475. #endif
  1476. PyDoc_STRVAR(posix_chdir__doc__,
  1477. "chdir(path)\n\n\
  1478. Change the current working directory to the specified path.");
  1479. static PyObject *
  1480. posix_chdir(PyObject *self, PyObject *args)
  1481. {
  1482. #ifdef MS_WINDOWS
  1483. return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir);
  1484. #elif defined(PYOS_OS2) && defined(PYCC_GCC)
  1485. return posix_1str(args, "et:chdir", _chdir2);
  1486. #elif defined(__VMS)
  1487. return posix_1str(args, "et:chdir", (int (*)(const char *))chdir);
  1488. #else
  1489. return posix_1str(args, "et:chdir", chdir);
  1490. #endif
  1491. }
  1492. #ifdef HAVE_FCHDIR
  1493. PyDoc_STRVAR(posix_fchdir__doc__,
  1494. "fchdir(fildes)\n\n\
  1495. Change to the directory of the given file descriptor. fildes must be\n\
  1496. opened on a directory, not a file.");
  1497. static PyObject *
  1498. posix_fchdir(PyObject *self, PyObject *fdobj)
  1499. {
  1500. return posix_fildes(fdobj, fchdir);
  1501. }
  1502. #endif /* HAVE_FCHDIR */
  1503. PyDoc_STRVAR(posix_chmod__doc__,
  1504. "chmod(path, mode)\n\n\
  1505. Change the access permissions of a file.");
  1506. static PyObject *
  1507. posix_chmod(PyObject *self, PyObject *args)
  1508. {
  1509. char *path = NULL;
  1510. int i;
  1511. int res;
  1512. #ifdef Py_WIN_WIDE_FILENAMES
  1513. DWORD attr;
  1514. if (unicode_file_names()) {
  1515. PyUnicodeObject *po;
  1516. if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) {
  1517. Py_BEGIN_ALLOW_THREADS
  1518. attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
  1519. if (attr != 0xFFFFFFFF) {
  1520. if (i & _S_IWRITE)
  1521. attr &= ~FILE_ATTRIBUTE_READONLY;
  1522. else
  1523. attr |= FILE_ATTRIBUTE_READONLY;
  1524. res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr);
  1525. }
  1526. else
  1527. res = 0;
  1528. Py_END_ALLOW_THREADS
  1529. if (!res)
  1530. return win32_error_unicode("chmod",
  1531. PyUnicode_AS_UNICODE(po));
  1532. Py_INCREF(Py_None);
  1533. return Py_None;
  1534. }
  1535. /* Drop the argument parsing error as narrow strings
  1536. are also valid. */
  1537. PyErr_Clear();
  1538. }
  1539. if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
  1540. &path, &i))
  1541. return NULL;
  1542. Py_BEGIN_ALLOW_THREADS
  1543. attr = GetFileAttributesA(path);
  1544. if (attr != 0xFFFFFFFF) {
  1545. if (i & _S_IWRITE)
  1546. attr &= ~FILE_ATTRIBUTE_READONLY;
  1547. else
  1548. attr |= FILE_ATTRIBUTE_READONLY;
  1549. res = SetFileAttributesA(path, attr);
  1550. }
  1551. else
  1552. res = 0;
  1553. Py_END_ALLOW_THREADS
  1554. if (!res) {
  1555. win32_error("chmod", path);
  1556. PyMem_Free(path);
  1557. return NULL;
  1558. }
  1559. PyMem_Free(path);
  1560. Py_INCREF(Py_None);
  1561. return Py_None;
  1562. #else /* Py_WIN_WIDE_FILENAMES */
  1563. if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
  1564. &path, &i))
  1565. return NULL;
  1566. Py_BEGIN_ALLOW_THREADS
  1567. res = chmod(path, i);
  1568. Py_END_ALLOW_THREADS
  1569. if (res < 0)
  1570. return posix_error_with_allocated_filename(path);
  1571. PyMem_Free(path);
  1572. Py_INCREF(Py_None);
  1573. return Py_None;
  1574. #endif
  1575. }
  1576. #ifdef HAVE_FCHMOD
  1577. PyDoc_STRVAR(posix_fchmod__doc__,
  1578. "fchmod(fd, mode)\n\n\
  1579. Change the access permissions of the file given by file\n\
  1580. descriptor fd.");
  1581. static PyObject *
  1582. posix_fchmod(PyObject *self, PyObject *args)
  1583. {
  1584. int fd, mode, res;
  1585. if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode))
  1586. return NULL;
  1587. Py_BEGIN_ALLOW_THREADS
  1588. res = fchmod(fd, mode);
  1589. Py_END_ALLOW_THREADS
  1590. if (res < 0)
  1591. return posix_error();
  1592. Py_RETURN_NONE;
  1593. }
  1594. #endif /* HAVE_FCHMOD */
  1595. #ifdef HAVE_LCHMOD
  1596. PyDoc_STRVAR(posix_lchmod__doc__,
  1597. "lchmod(path, mode)\n\n\
  1598. Change the access permissions of a file. If path is a symlink, this\n\
  1599. affects the link itself rather than the target.");
  1600. static PyObject *
  1601. posix_lchmod(PyObject *self, PyObject *args)
  1602. {
  1603. char *path = NULL;
  1604. int i;
  1605. int res;
  1606. if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding,
  1607. &path, &i))
  1608. return NULL;
  1609. Py_BEGIN_ALLOW_THREADS
  1610. res = lchmod(path, i);
  1611. Py_END_ALLOW_THREADS
  1612. if (res < 0)
  1613. return posix_error_with_allocated_filename(path);
  1614. PyMem_Free(path);
  1615. Py_RETURN_NONE;
  1616. }
  1617. #endif /* HAVE_LCHMOD */
  1618. #ifdef HAVE_CHFLAGS
  1619. PyDoc_STRVAR(posix_chflags__doc__,
  1620. "chflags(path, flags)\n\n\
  1621. Set file flags.");
  1622. static PyObject *
  1623. posix_chflags(PyObject *self, PyObject *args)
  1624. {
  1625. char *path;
  1626. unsigned long flags;
  1627. int res;
  1628. if (!PyArg_ParseTuple(args, "etk:chflags",
  1629. Py_FileSystemDefaultEncoding, &path, &flags))
  1630. return NULL;
  1631. Py_BEGIN_ALLOW_THREADS
  1632. res = chflags(path, flags);
  1633. Py_END_ALLOW_THREADS
  1634. if (res < 0)
  1635. return posix_error_with_allocated_filename(path);
  1636. PyMem_Free(path);
  1637. Py_INCREF(Py_None);
  1638. return Py_None;
  1639. }
  1640. #endif /* HAVE_CHFLAGS */
  1641. #ifdef HAVE_LCHFLAGS
  1642. PyDoc_STRVAR(posix_lchflags__doc__,
  1643. "lchflags(path, flags)\n\n\
  1644. Set file flags.\n\
  1645. This function will not follow symbolic links.");
  1646. static PyObject *
  1647. posix_lchflags(PyObject *self, PyObject *args)
  1648. {
  1649. char *path;
  1650. unsigned long flags;
  1651. int res;
  1652. if (!PyArg_ParseTuple(args, "etk:lchflags",
  1653. Py_FileSystemDefaultEncoding, &path, &flags))
  1654. return NULL;
  1655. Py_BEGIN_ALLOW_THREADS
  1656. res = lchflags(path, flags);
  1657. Py_END_ALLOW_THREADS
  1658. if (res < 0)
  1659. return posix_error_with_allocated_filename(path);
  1660. PyMem_Free(path);
  1661. Py_INCREF(Py_None);
  1662. return Py_None;
  1663. }
  1664. #endif /* HAVE_LCHFLAGS */
  1665. #ifdef HAVE_CHROOT
  1666. PyDoc_STRVAR(posix_chroot__doc__,
  1667. "chroot(path)\n\n\
  1668. Change root directory to path.");
  1669. static PyObject *
  1670. posix_chroot(PyObject *self, PyObject *args)
  1671. {
  1672. return posix_1str(args, "et:chroot", chroot);
  1673. }
  1674. #endif
  1675. #ifdef HAVE_FSYNC
  1676. PyDoc_STRVAR(posix_fsync__doc__,
  1677. "fsync(fildes)\n\n\
  1678. force write of file with filedescriptor to disk.");
  1679. static PyObject *
  1680. posix_fsync(PyObject *self, PyObject *fdobj)
  1681. {
  1682. return posix_fildes(fdobj, fsync);
  1683. }
  1684. #endif /* HAVE_FSYNC */
  1685. #ifdef HAVE_FDATASYNC
  1686. #ifdef __hpux
  1687. extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
  1688. #endif
  1689. PyDoc_STRVAR(posix_fdatasync__doc__,
  1690. "fdatasync(fildes)\n\n\
  1691. force write of file with filedescriptor to disk.\n\
  1692. does not force update of metadata.");
  1693. static PyObject *
  1694. posix_fdatasync(PyObject *self, PyObject *fdobj)
  1695. {
  1696. return posix_fildes(fdobj, fdatasync);
  1697. }
  1698. #endif /* HAVE_FDATASYNC */
  1699. #ifdef HAVE_CHOWN
  1700. PyDoc_STRVAR(posix_chown__doc__,
  1701. "chown(path, uid, gid)\n\n\
  1702. Change the owner and group id of path to the numeric uid and gid.");
  1703. static PyObject *
  1704. posix_chown(PyObject *self, PyObject *args)
  1705. {
  1706. char *path = NULL;
  1707. long uid, gid;
  1708. int res;
  1709. if (!PyArg_ParseTuple(args, "etll:chown",
  1710. Py_FileSystemDefaultEncoding, &path,
  1711. &uid, &gid))
  1712. return NULL;
  1713. Py_BEGIN_ALLOW_THREADS
  1714. res = chown(path, (uid_t) uid, (gid_t) gid);
  1715. Py_END_ALLOW_THREADS
  1716. if (res < 0)
  1717. return posix_error_with_allocated_filename(path);
  1718. PyMem_Free(path);
  1719. Py_INCREF(Py_None);
  1720. return Py_None;
  1721. }
  1722. #endif /* HAVE_CHOWN */
  1723. #ifdef HAVE_FCHOWN
  1724. PyDoc_STRVAR(posix_fchown__doc__,
  1725. "fchown(fd, uid, gid)\n\n\
  1726. Change the owner and group id of the file given by file descriptor\n\
  1727. fd to the numeric uid and gid.");
  1728. static PyObject *
  1729. posix_fchown(PyObject *self, PyObject *args)
  1730. {
  1731. int fd, uid, gid;
  1732. int res;
  1733. if (!PyArg_ParseTuple(args, "iii:chown", &fd, &uid, &gid))
  1734. return NULL;
  1735. Py_BEGIN_ALLOW_THREADS
  1736. res = fchown(fd, (uid_t) uid, (gid_t) gid);
  1737. Py_END_ALLOW_THREADS
  1738. if (res < 0)
  1739. return posix_error();
  1740. Py_RETURN_NONE;
  1741. }
  1742. #endif /* HAVE_FCHOWN */
  1743. #ifdef HAVE_LCHOWN
  1744. PyDoc_STRVAR(posix_lchown__doc__,
  1745. "lchown(path, uid, gid)\n\n\
  1746. Change the owner and group id of path to the numeric uid and gid.\n\
  1747. This function will not follow symbolic links.");
  1748. static PyObject *
  1749. posix_lchown(PyObject *self, PyObject *args)
  1750. {
  1751. char *path = NULL;
  1752. int uid, gid;
  1753. int res;
  1754. if (!PyArg_ParseTuple(args, "etii:lchown",
  1755. Py_FileSystemDefaultEncoding, &path,
  1756. &uid, &gid))
  1757. return NULL;
  1758. Py_BEGIN_ALLOW_THREADS
  1759. res = lchown(path, (uid_t) uid, (gid_t) gid);
  1760. Py_END_ALLOW_THREADS
  1761. if (res < 0)
  1762. return posix_error_with_allocated_filename(path);
  1763. PyMem_Free(path);
  1764. Py_INCREF(Py_None);
  1765. return Py_None;
  1766. }
  1767. #endif /* HAVE_LCHOWN */
  1768. #ifdef HAVE_GETCWD
  1769. PyDoc_STRVAR(posix_getcwd__doc__,
  1770. "getcwd() -> path\n\n\
  1771. Return a string representing the current working directory.");
  1772. static PyObject *
  1773. posix_getcwd(PyObject *self, PyObject *noargs)
  1774. {
  1775. int bufsize_incr = 1024;
  1776. int bufsize = 0;
  1777. char *tmpbuf = NULL;
  1778. char *res = NULL;
  1779. PyObject *dynamic_return;
  1780. Py_BEGIN_ALLOW_THREADS
  1781. do {
  1782. bufsize = bufsize + bufsize_incr;
  1783. tmpbuf = malloc(bufsize);
  1784. if (tmpbuf == NULL) {
  1785. break;
  1786. }
  1787. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  1788. res = _getcwd2(tmpbuf, bufsize);
  1789. #else
  1790. res = getcwd(tmpbuf, bufsize);
  1791. #endif
  1792. if (res == NULL) {
  1793. free(tmpbuf);
  1794. }
  1795. } while ((res == NULL) && (errno == ERANGE));
  1796. Py_END_ALLOW_THREADS
  1797. if (res == NULL)
  1798. return posix_error();
  1799. dynamic_return = PyString_FromString(tmpbuf);
  1800. free(tmpbuf);
  1801. return dynamic_return;
  1802. }
  1803. #ifdef Py_USING_UNICODE
  1804. PyDoc_STRVAR(posix_getcwdu__doc__,
  1805. "getcwdu() -> path\n\n\
  1806. Return a unicode string representing the current working directory.");
  1807. static PyObject *
  1808. posix_getcwdu(PyObject *self, PyObject *noargs)
  1809. {
  1810. char buf[1026];
  1811. char *res;
  1812. #ifdef Py_WIN_WIDE_FILENAMES
  1813. DWORD len;
  1814. if (unicode_file_names()) {
  1815. wchar_t wbuf[1026];
  1816. wchar_t *wbuf2 = wbuf;
  1817. PyObject *resobj;
  1818. Py_BEGIN_ALLOW_THREADS
  1819. len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf);
  1820. /* If the buffer is large enough, len does not include the
  1821. terminating \0. If the buffer is too small, len includes
  1822. the space needed for the terminator. */
  1823. if (len >= sizeof wbuf/ sizeof wbuf[0]) {
  1824. wbuf2 = malloc(len * sizeof(wchar_t));
  1825. if (wbuf2)
  1826. len = GetCurrentDirectoryW(len, wbuf2);
  1827. }
  1828. Py_END_ALLOW_THREADS
  1829. if (!wbuf2) {
  1830. PyErr_NoMemory();
  1831. return NULL;
  1832. }
  1833. if (!len) {
  1834. if (wbuf2 != wbuf) free(wbuf2);
  1835. return win32_error("getcwdu", NULL);
  1836. }
  1837. resobj = PyUnicode_FromWideChar(wbuf2, len);
  1838. if (wbuf2 != wbuf) free(wbuf2);
  1839. return resobj;
  1840. }
  1841. #endif
  1842. Py_BEGIN_ALLOW_THREADS
  1843. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  1844. res = _getcwd2(buf, sizeof buf);
  1845. #else
  1846. res = getcwd(buf, sizeof buf);
  1847. #endif
  1848. Py_END_ALLOW_THREADS
  1849. if (res == NULL)
  1850. return posix_error();
  1851. return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict");
  1852. }
  1853. #endif
  1854. #endif
  1855. #ifdef HAVE_LINK
  1856. PyDoc_STRVAR(posix_link__doc__,
  1857. "link(src, dst)\n\n\
  1858. Create a hard link to a file.");
  1859. static PyObject *
  1860. posix_link(PyObject *self, PyObject *args)
  1861. {
  1862. return posix_2str(args, "etet:link", link);
  1863. }
  1864. #endif /* HAVE_LINK */
  1865. PyDoc_STRVAR(posix_listdir__doc__,
  1866. "listdir(path) -> list_of_strings\n\n\
  1867. Return a list containing the names of the entries in the directory.\n\
  1868. \n\
  1869. path: path of directory to list\n\
  1870. \n\
  1871. The list is in arbitrary order. It does not include the special\n\
  1872. entries '.' and '..' even if they are present in the directory.");
  1873. static PyObject *
  1874. posix_listdir(PyObject *self, PyObject *args)
  1875. {
  1876. /* XXX Should redo this putting the (now four) versions of opendir
  1877. in separate files instead of having them all here... */
  1878. #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
  1879. PyObject *d, *v;
  1880. HANDLE hFindFile;
  1881. BOOL result;
  1882. WIN32_FIND_DATA FileData;
  1883. char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */
  1884. char *bufptr = namebuf;
  1885. Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */
  1886. #ifdef Py_WIN_WIDE_FILENAMES
  1887. /* If on wide-character-capable OS see if argument
  1888. is Unicode and if so use wide API. */
  1889. if (unicode_file_names()) {
  1890. PyObject *po;
  1891. if (PyArg_ParseTuple(args, "U:listdir", &po)) {
  1892. WIN32_FIND_DATAW wFileData;
  1893. Py_UNICODE *wnamebuf;
  1894. Py_UNICODE wch;
  1895. /* Overallocate for \\*.*\0 */
  1896. len = PyUnicode_GET_SIZE(po);
  1897. wnamebuf = malloc((len + 5) * sizeof(wchar_t));
  1898. if (!wnamebuf) {
  1899. PyErr_NoMemory();
  1900. return NULL;
  1901. }
  1902. wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po));
  1903. wch = len > 0 ? wnamebuf[len-1] : '\0';
  1904. if (wch != L'/' && wch != L'\\' && wch != L':')
  1905. wnamebuf[len++] = L'\\';
  1906. wcscpy(wnamebuf + len, L"*.*");
  1907. if ((d = PyList_New(0)) == NULL) {
  1908. free(wnamebuf);
  1909. return NULL;
  1910. }
  1911. hFindFile = FindFirstFileW(wnamebuf, &wFileData);
  1912. if (hFindFile == INVALID_HANDLE_VALUE) {
  1913. int error = GetLastError();
  1914. if (error == ERROR_FILE_NOT_FOUND) {
  1915. free(wnamebuf);
  1916. return d;
  1917. }
  1918. Py_DECREF(d);
  1919. win32_error_unicode("FindFirstFileW", wnamebuf);
  1920. free(wnamebuf);
  1921. return NULL;
  1922. }
  1923. do {
  1924. /* Skip over . and .. */
  1925. if (wcscmp(wFileData.cFileName, L".") != 0 &&
  1926. wcscmp(wFileData.cFileName, L"..") != 0) {
  1927. v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName));
  1928. if (v == NULL) {
  1929. Py_DECREF(d);
  1930. d = NULL;
  1931. break;
  1932. }
  1933. if (PyList_Append(d, v) != 0) {
  1934. Py_DECREF(v);
  1935. Py_DECREF(d);
  1936. d = NULL;
  1937. break;
  1938. }
  1939. Py_DECREF(v);
  1940. }
  1941. Py_BEGIN_ALLOW_THREADS
  1942. result = FindNextFileW(hFindFile, &wFileData);
  1943. Py_END_ALLOW_THREADS
  1944. /* FindNextFile sets error to ERROR_NO_MORE_FILES if
  1945. it got to the end of the directory. */
  1946. if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
  1947. Py_DECREF(d);
  1948. win32_error_unicode("FindNextFileW", wnamebuf);
  1949. FindClose(hFindFile);
  1950. free(wnamebuf);
  1951. return NULL;
  1952. }
  1953. } while (result == TRUE);
  1954. if (FindClose(hFindFile) == FALSE) {
  1955. Py_DECREF(d);
  1956. win32_error_unicode("FindClose", wnamebuf);
  1957. free(wnamebuf);
  1958. return NULL;
  1959. }
  1960. free(wnamebuf);
  1961. return d;
  1962. }
  1963. /* Drop the argument parsing error as narrow strings
  1964. are also valid. */
  1965. PyErr_Clear();
  1966. }
  1967. #endif
  1968. if (!PyArg_ParseTuple(args, "et#:listdir",
  1969. Py_FileSystemDefaultEncoding, &bufptr, &len))
  1970. return NULL;
  1971. if (len > 0) {
  1972. char ch = namebuf[len-1];
  1973. if (ch != SEP && ch != ALTSEP && ch != ':')
  1974. namebuf[len++] = '/';
  1975. }
  1976. strcpy(namebuf + len, "*.*");
  1977. if ((d = PyList_New(0)) == NULL)
  1978. return NULL;
  1979. hFindFile = FindFirstFile(namebuf, &FileData);
  1980. if (hFindFile == INVALID_HANDLE_VALUE) {
  1981. int error = GetLastError();
  1982. if (error == ERROR_FILE_NOT_FOUND)
  1983. return d;
  1984. Py_DECREF(d);
  1985. return win32_error("FindFirstFile", namebuf);
  1986. }
  1987. do {
  1988. /* Skip over . and .. */
  1989. if (strcmp(FileData.cFileName, ".") != 0 &&
  1990. strcmp(FileData.cFileName, "..") != 0) {
  1991. v = PyString_FromString(FileData.cFileName);
  1992. if (v == NULL) {
  1993. Py_DECREF(d);
  1994. d = NULL;
  1995. break;
  1996. }
  1997. if (PyList_Append(d, v) != 0) {
  1998. Py_DECREF(v);
  1999. Py_DECREF(d);
  2000. d = NULL;
  2001. break;
  2002. }
  2003. Py_DECREF(v);
  2004. }
  2005. Py_BEGIN_ALLOW_THREADS
  2006. result = FindNextFile(hFindFile, &FileData);
  2007. Py_END_ALLOW_THREADS
  2008. /* FindNextFile sets error to ERROR_NO_MORE_FILES if
  2009. it got to the end of the directory. */
  2010. if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
  2011. Py_DECREF(d);
  2012. win32_error("FindNextFile", namebuf);
  2013. FindClose(hFindFile);
  2014. return NULL;
  2015. }
  2016. } while (result == TRUE);
  2017. if (FindClose(hFindFile) == FALSE) {
  2018. Py_DECREF(d);
  2019. return win32_error("FindClose", namebuf);
  2020. }
  2021. return d;
  2022. #elif defined(PYOS_OS2)
  2023. #ifndef MAX_PATH
  2024. #define MAX_PATH CCHMAXPATH
  2025. #endif
  2026. char *name, *pt;
  2027. Py_ssize_t len;
  2028. PyObject *d, *v;
  2029. char namebuf[MAX_PATH+5];
  2030. HDIR hdir = 1;
  2031. ULONG srchcnt = 1;
  2032. FILEFINDBUF3 ep;
  2033. APIRET rc;
  2034. if (!PyArg_ParseTuple(args, "t#:listdir", &name, &len))
  2035. return NULL;
  2036. if (len >= MAX_PATH) {
  2037. PyErr_SetString(PyExc_ValueError, "path too long");
  2038. return NULL;
  2039. }
  2040. strcpy(namebuf, name);
  2041. for (pt = namebuf; *pt; pt++)
  2042. if (*pt == ALTSEP)
  2043. *pt = SEP;
  2044. if (namebuf[len-1] != SEP)
  2045. namebuf[len++] = SEP;
  2046. strcpy(namebuf + len, "*.*");
  2047. if ((d = PyList_New(0)) == NULL)
  2048. return NULL;
  2049. rc = DosFindFirst(namebuf, /* Wildcard Pattern to Match */
  2050. &hdir, /* Handle to Use While Search Directory */
  2051. FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
  2052. &ep, sizeof(ep), /* Structure to Receive Directory Entry */
  2053. &srchcnt, /* Max and Actual Count of Entries Per Iteration */
  2054. FIL_STANDARD); /* Format of Entry (EAs or Not) */
  2055. if (rc != NO_ERROR) {
  2056. errno = ENOENT;
  2057. return posix_error_with_filename(name);
  2058. }
  2059. if (srchcnt > 0) { /* If Directory is NOT Totally Empty, */
  2060. do {
  2061. if (ep.achName[0] == '.'
  2062. && (ep.achName[1] == '\0' || (ep.achName[1] == '.' && ep.achName[2] == '\0')))
  2063. continue; /* Skip Over "." and ".." Names */
  2064. strcpy(namebuf, ep.achName);
  2065. /* Leave Case of Name Alone -- In Native Form */
  2066. /* (Removed Forced Lowercasing Code) */
  2067. v = PyString_FromString(namebuf);
  2068. if (v == NULL) {
  2069. Py_DECREF(d);
  2070. d = NULL;
  2071. break;
  2072. }
  2073. if (PyList_Append(d, v) != 0) {
  2074. Py_DECREF(v);
  2075. Py_DECREF(d);
  2076. d = NULL;
  2077. break;
  2078. }
  2079. Py_DECREF(v);
  2080. } while (DosFindNext(hdir, &ep, sizeof(ep), &srchcnt) == NO_ERROR && srchcnt > 0);
  2081. }
  2082. return d;
  2083. #else
  2084. char *name = NULL;
  2085. PyObject *d, *v;
  2086. DIR *dirp;
  2087. struct dirent *ep;
  2088. int arg_is_unicode = 1;
  2089. errno = 0;
  2090. if (!PyArg_ParseTuple(args, "U:listdir", &v)) {
  2091. arg_is_unicode = 0;
  2092. PyErr_Clear();
  2093. }
  2094. if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name))
  2095. return NULL;
  2096. if ((dirp = opendir(name)) == NULL) {
  2097. return posix_error_with_allocated_filename(name);
  2098. }
  2099. if ((d = PyList_New(0)) == NULL) {
  2100. closedir(dirp);
  2101. PyMem_Free(name);
  2102. return NULL;
  2103. }
  2104. for (;;) {
  2105. errno = 0;
  2106. Py_BEGIN_ALLOW_THREADS
  2107. ep = readdir(dirp);
  2108. Py_END_ALLOW_THREADS
  2109. if (ep == NULL) {
  2110. if (errno == 0) {
  2111. break;
  2112. } else {
  2113. closedir(dirp);
  2114. Py_DECREF(d);
  2115. return posix_error_with_allocated_filename(name);
  2116. }
  2117. }
  2118. if (ep->d_name[0] == '.' &&
  2119. (NAMLEN(ep) == 1 ||
  2120. (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
  2121. continue;
  2122. v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep));
  2123. if (v == NULL) {
  2124. Py_DECREF(d);
  2125. d = NULL;
  2126. break;
  2127. }
  2128. #ifdef Py_USING_UNICODE
  2129. if (arg_is_unicode) {
  2130. PyObject *w;
  2131. w = PyUnicode_FromEncodedObject(v,
  2132. Py_FileSystemDefaultEncoding,
  2133. "strict");
  2134. if (w != NULL) {
  2135. Py_DECREF(v);
  2136. v = w;
  2137. }
  2138. else {
  2139. /* fall back to the original byte string, as
  2140. discussed in patch #683592 */
  2141. PyErr_Clear();
  2142. }
  2143. }
  2144. #endif
  2145. if (PyList_Append(d, v) != 0) {
  2146. Py_DECREF(v);
  2147. Py_DECREF(d);
  2148. d = NULL;
  2149. break;
  2150. }
  2151. Py_DECREF(v);
  2152. }
  2153. closedir(dirp);
  2154. PyMem_Free(name);
  2155. return d;
  2156. #endif /* which OS */
  2157. } /* end of posix_listdir */
  2158. #ifdef MS_WINDOWS
  2159. /* A helper function for abspath on win32 */
  2160. static PyObject *
  2161. posix__getfullpathname(PyObject *self, PyObject *args)
  2162. {
  2163. /* assume encoded strings won't more than double no of chars */
  2164. char inbuf[MAX_PATH*2];
  2165. char *inbufp = inbuf;
  2166. Py_ssize_t insize = sizeof(inbuf);
  2167. char outbuf[MAX_PATH*2];
  2168. char *temp;
  2169. #ifdef Py_WIN_WIDE_FILENAMES
  2170. if (unicode_file_names()) {
  2171. PyUnicodeObject *po;
  2172. if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) {
  2173. Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
  2174. Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf;
  2175. Py_UNICODE *wtemp;
  2176. DWORD result;
  2177. PyObject *v;
  2178. result = GetFullPathNameW(wpath,
  2179. sizeof(woutbuf)/sizeof(woutbuf[0]),
  2180. woutbuf, &wtemp);
  2181. if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) {
  2182. woutbufp = malloc(result * sizeof(Py_UNICODE));
  2183. if (!woutbufp)
  2184. return PyErr_NoMemory();
  2185. result = GetFullPathNameW(wpath, result, woutbufp, &wtemp);
  2186. }
  2187. if (result)
  2188. v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp));
  2189. else
  2190. v = win32_error_unicode("GetFullPathNameW", wpath);
  2191. if (woutbufp != woutbuf)
  2192. free(woutbufp);
  2193. return v;
  2194. }
  2195. /* Drop the argument parsing error as narrow strings
  2196. are also valid. */
  2197. PyErr_Clear();
  2198. }
  2199. #endif
  2200. if (!PyArg_ParseTuple (args, "et#:_getfullpathname",
  2201. Py_FileSystemDefaultEncoding, &inbufp,
  2202. &insize))
  2203. return NULL;
  2204. if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]),
  2205. outbuf, &temp))
  2206. return win32_error("GetFullPathName", inbuf);
  2207. if (PyUnicode_Check(PyTuple_GetItem(args, 0))) {
  2208. return PyUnicode_Decode(outbuf, strlen(outbuf),
  2209. Py_FileSystemDefaultEncoding, NULL);
  2210. }
  2211. return PyString_FromString(outbuf);
  2212. } /* end of posix__getfullpathname */
  2213. #endif /* MS_WINDOWS */
  2214. PyDoc_STRVAR(posix_mkdir__doc__,
  2215. "mkdir(path [, mode=0777])\n\n\
  2216. Create a directory.");
  2217. static PyObject *
  2218. posix_mkdir(PyObject *self, PyObject *args)
  2219. {
  2220. int res;
  2221. char *path = NULL;
  2222. int mode = 0777;
  2223. #ifdef Py_WIN_WIDE_FILENAMES
  2224. if (unicode_file_names()) {
  2225. PyUnicodeObject *po;
  2226. if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) {
  2227. Py_BEGIN_ALLOW_THREADS
  2228. /* PyUnicode_AS_UNICODE OK without thread lock as
  2229. it is a simple dereference. */
  2230. res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL);
  2231. Py_END_ALLOW_THREADS
  2232. if (!res)
  2233. return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po));
  2234. Py_INCREF(Py_None);
  2235. return Py_None;
  2236. }
  2237. /* Drop the argument parsing error as narrow strings
  2238. are also valid. */
  2239. PyErr_Clear();
  2240. }
  2241. if (!PyArg_ParseTuple(args, "et|i:mkdir",
  2242. Py_FileSystemDefaultEncoding, &path, &mode))
  2243. return NULL;
  2244. Py_BEGIN_ALLOW_THREADS
  2245. /* PyUnicode_AS_UNICODE OK without thread lock as
  2246. it is a simple dereference. */
  2247. res = CreateDirectoryA(path, NULL);
  2248. Py_END_ALLOW_THREADS
  2249. if (!res) {
  2250. win32_error("mkdir", path);
  2251. PyMem_Free(path);
  2252. return NULL;
  2253. }
  2254. PyMem_Free(path);
  2255. Py_INCREF(Py_None);
  2256. return Py_None;
  2257. #else
  2258. if (!PyArg_ParseTuple(args, "et|i:mkdir",
  2259. Py_FileSystemDefaultEncoding, &path, &mode))
  2260. return NULL;
  2261. Py_BEGIN_ALLOW_THREADS
  2262. #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
  2263. res = mkdir(path);
  2264. #else
  2265. res = mkdir(path, mode);
  2266. #endif
  2267. Py_END_ALLOW_THREADS
  2268. if (res < 0)
  2269. return posix_error_with_allocated_filename(path);
  2270. PyMem_Free(path);
  2271. Py_INCREF(Py_None);
  2272. return Py_None;
  2273. #endif
  2274. }
  2275. /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
  2276. #if defined(HAVE_SYS_RESOURCE_H)
  2277. #include <sys/resource.h>
  2278. #endif
  2279. #ifdef HAVE_NICE
  2280. PyDoc_STRVAR(posix_nice__doc__,
  2281. "nice(inc) -> new_priority\n\n\
  2282. Decrease the priority of process by inc and return the new priority.");
  2283. static PyObject *
  2284. posix_nice(PyObject *self, PyObject *args)
  2285. {
  2286. int increment, value;
  2287. if (!PyArg_ParseTuple(args, "i:nice", &increment))
  2288. return NULL;
  2289. /* There are two flavours of 'nice': one that returns the new
  2290. priority (as required by almost all standards out there) and the
  2291. Linux/FreeBSD/BSDI one, which returns '0' on success and advices
  2292. the use of getpriority() to get the new priority.
  2293. If we are of the nice family that returns the new priority, we
  2294. need to clear errno before the call, and check if errno is filled
  2295. before calling posix_error() on a returnvalue of -1, because the
  2296. -1 may be the actual new priority! */
  2297. errno = 0;
  2298. value = nice(increment);
  2299. #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
  2300. if (value == 0)
  2301. value = getpriority(PRIO_PROCESS, 0);
  2302. #endif
  2303. if (value == -1 && errno != 0)
  2304. /* either nice() or getpriority() returned an error */
  2305. return posix_error();
  2306. return PyInt_FromLong((long) value);
  2307. }
  2308. #endif /* HAVE_NICE */
  2309. PyDoc_STRVAR(posix_rename__doc__,
  2310. "rename(old, new)\n\n\
  2311. Rename a file or directory.");
  2312. static PyObject *
  2313. posix_rename(PyObject *self, PyObject *args)
  2314. {
  2315. #ifdef MS_WINDOWS
  2316. PyObject *o1, *o2;
  2317. char *p1, *p2;
  2318. BOOL result;
  2319. if (unicode_file_names()) {
  2320. if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2))
  2321. goto error;
  2322. if (!convert_to_unicode(&o1))
  2323. goto error;
  2324. if (!convert_to_unicode(&o2)) {
  2325. Py_DECREF(o1);
  2326. goto error;
  2327. }
  2328. Py_BEGIN_ALLOW_THREADS
  2329. result = MoveFileW(PyUnicode_AsUnicode(o1),
  2330. PyUnicode_AsUnicode(o2));
  2331. Py_END_ALLOW_THREADS
  2332. Py_DECREF(o1);
  2333. Py_DECREF(o2);
  2334. if (!result)
  2335. return win32_error("rename", NULL);
  2336. Py_INCREF(Py_None);
  2337. return Py_None;
  2338. error:
  2339. PyErr_Clear();
  2340. }
  2341. if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2))
  2342. return NULL;
  2343. Py_BEGIN_ALLOW_THREADS
  2344. result = MoveFileA(p1, p2);
  2345. Py_END_ALLOW_THREADS
  2346. if (!result)
  2347. return win32_error("rename", NULL);
  2348. Py_INCREF(Py_None);
  2349. return Py_None;
  2350. #else
  2351. return posix_2str(args, "etet:rename", rename);
  2352. #endif
  2353. }
  2354. PyDoc_STRVAR(posix_rmdir__doc__,
  2355. "rmdir(path)\n\n\
  2356. Remove a directory.");
  2357. static PyObject *
  2358. posix_rmdir(PyObject *self, PyObject *args)
  2359. {
  2360. #ifdef MS_WINDOWS
  2361. return win32_1str(args, "rmdir", "s:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW);
  2362. #else
  2363. return posix_1str(args, "et:rmdir", rmdir);
  2364. #endif
  2365. }
  2366. PyDoc_STRVAR(posix_stat__doc__,
  2367. "stat(path) -> stat result\n\n\
  2368. Perform a stat system call on the given path.");
  2369. static PyObject *
  2370. posix_stat(PyObject *self, PyObject *args)
  2371. {
  2372. #ifdef MS_WINDOWS
  2373. return posix_do_stat(self, args, "et:stat", STAT, "U:stat", win32_wstat);
  2374. #else
  2375. return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL);
  2376. #endif
  2377. }
  2378. #ifdef HAVE_SYSTEM
  2379. PyDoc_STRVAR(posix_system__doc__,
  2380. "system(command) -> exit_status\n\n\
  2381. Execute the command (a string) in a subshell.");
  2382. static PyObject *
  2383. posix_system(PyObject *self, PyObject *args)
  2384. {
  2385. char *command;
  2386. long sts;
  2387. if (!PyArg_ParseTuple(args, "s:system", &command))
  2388. return NULL;
  2389. Py_BEGIN_ALLOW_THREADS
  2390. sts = system(command);
  2391. Py_END_ALLOW_THREADS
  2392. return PyInt_FromLong(sts);
  2393. }
  2394. #endif
  2395. PyDoc_STRVAR(posix_umask__doc__,
  2396. "umask(new_mask) -> old_mask\n\n\
  2397. Set the current numeric umask and return the previous umask.");
  2398. static PyObject *
  2399. posix_umask(PyObject *self, PyObject *args)
  2400. {
  2401. int i;
  2402. if (!PyArg_ParseTuple(args, "i:umask", &i))
  2403. return NULL;
  2404. i = (int)umask(i);
  2405. if (i < 0)
  2406. return posix_error();
  2407. return PyInt_FromLong((long)i);
  2408. }
  2409. PyDoc_STRVAR(posix_unlink__doc__,
  2410. "unlink(path)\n\n\
  2411. Remove a file (same as remove(path)).");
  2412. PyDoc_STRVAR(posix_remove__doc__,
  2413. "remove(path)\n\n\
  2414. Remove a file (same as unlink(path)).");
  2415. static PyObject *
  2416. posix_unlink(PyObject *self, PyObject *args)
  2417. {
  2418. #ifdef MS_WINDOWS
  2419. return win32_1str(args, "remove", "s:remove", DeleteFileA, "U:remove", DeleteFileW);
  2420. #else
  2421. return posix_1str(args, "et:remove", unlink);
  2422. #endif
  2423. }
  2424. #ifdef HAVE_UNAME
  2425. PyDoc_STRVAR(posix_uname__doc__,
  2426. "uname() -> (sysname, nodename, release, version, machine)\n\n\
  2427. Return a tuple identifying the current operating system.");
  2428. static PyObject *
  2429. posix_uname(PyObject *self, PyObject *noargs)
  2430. {
  2431. struct utsname u;
  2432. int res;
  2433. Py_BEGIN_ALLOW_THREADS
  2434. res = uname(&u);
  2435. Py_END_ALLOW_THREADS
  2436. if (res < 0)
  2437. return posix_error();
  2438. return Py_BuildValue("(sssss)",
  2439. u.sysname,
  2440. u.nodename,
  2441. u.release,
  2442. u.version,
  2443. u.machine);
  2444. }
  2445. #endif /* HAVE_UNAME */
  2446. static int
  2447. extract_time(PyObject *t, long* sec, long* usec)
  2448. {
  2449. long intval;
  2450. if (PyFloat_Check(t)) {
  2451. double tval = PyFloat_AsDouble(t);
  2452. PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t);
  2453. if (!intobj)
  2454. return -1;
  2455. intval = PyInt_AsLong(intobj);
  2456. Py_DECREF(intobj);
  2457. if (intval == -1 && PyErr_Occurred())
  2458. return -1;
  2459. *sec = intval;
  2460. *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */
  2461. if (*usec < 0)
  2462. /* If rounding gave us a negative number,
  2463. truncate. */
  2464. *usec = 0;
  2465. return 0;
  2466. }
  2467. intval = PyInt_AsLong(t);
  2468. if (intval == -1 && PyErr_Occurred())
  2469. return -1;
  2470. *sec = intval;
  2471. *usec = 0;
  2472. return 0;
  2473. }
  2474. PyDoc_STRVAR(posix_utime__doc__,
  2475. "utime(path, (atime, mtime))\n\
  2476. utime(path, None)\n\n\
  2477. Set the access and modified time of the file to the given values. If the\n\
  2478. second form is used, set the access and modified times to the current time.");
  2479. static PyObject *
  2480. posix_utime(PyObject *self, PyObject *args)
  2481. {
  2482. #ifdef Py_WIN_WIDE_FILENAMES
  2483. PyObject *arg;
  2484. PyUnicodeObject *obwpath;
  2485. wchar_t *wpath = NULL;
  2486. char *apath = NULL;
  2487. HANDLE hFile;
  2488. long atimesec, mtimesec, ausec, musec;
  2489. FILETIME atime, mtime;
  2490. PyObject *result = NULL;
  2491. if (unicode_file_names()) {
  2492. if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) {
  2493. wpath = PyUnicode_AS_UNICODE(obwpath);
  2494. Py_BEGIN_ALLOW_THREADS
  2495. hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0,
  2496. NULL, OPEN_EXISTING,
  2497. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2498. Py_END_ALLOW_THREADS
  2499. if (hFile == INVALID_HANDLE_VALUE)
  2500. return win32_error_unicode("utime", wpath);
  2501. } else
  2502. /* Drop the argument parsing error as narrow strings
  2503. are also valid. */
  2504. PyErr_Clear();
  2505. }
  2506. if (!wpath) {
  2507. if (!PyArg_ParseTuple(args, "etO:utime",
  2508. Py_FileSystemDefaultEncoding, &apath, &arg))
  2509. return NULL;
  2510. Py_BEGIN_ALLOW_THREADS
  2511. hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0,
  2512. NULL, OPEN_EXISTING,
  2513. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2514. Py_END_ALLOW_THREADS
  2515. if (hFile == INVALID_HANDLE_VALUE) {
  2516. win32_error("utime", apath);
  2517. PyMem_Free(apath);
  2518. return NULL;
  2519. }
  2520. PyMem_Free(apath);
  2521. }
  2522. if (arg == Py_None) {
  2523. SYSTEMTIME now;
  2524. GetSystemTime(&now);
  2525. if (!SystemTimeToFileTime(&now, &mtime) ||
  2526. !SystemTimeToFileTime(&now, &atime)) {
  2527. win32_error("utime", NULL);
  2528. goto done;
  2529. }
  2530. }
  2531. else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
  2532. PyErr_SetString(PyExc_TypeError,
  2533. "utime() arg 2 must be a tuple (atime, mtime)");
  2534. goto done;
  2535. }
  2536. else {
  2537. if (extract_time(PyTuple_GET_ITEM(arg, 0),
  2538. &atimesec, &ausec) == -1)
  2539. goto done;
  2540. time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime);
  2541. if (extract_time(PyTuple_GET_ITEM(arg, 1),
  2542. &mtimesec, &musec) == -1)
  2543. goto done;
  2544. time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime);
  2545. }
  2546. if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
  2547. /* Avoid putting the file name into the error here,
  2548. as that may confuse the user into believing that
  2549. something is wrong with the file, when it also
  2550. could be the time stamp that gives a problem. */
  2551. win32_error("utime", NULL);
  2552. }
  2553. Py_INCREF(Py_None);
  2554. result = Py_None;
  2555. done:
  2556. CloseHandle(hFile);
  2557. return result;
  2558. #else /* Py_WIN_WIDE_FILENAMES */
  2559. char *path = NULL;
  2560. long atime, mtime, ausec, musec;
  2561. int res;
  2562. PyObject* arg;
  2563. #if defined(HAVE_UTIMES)
  2564. struct timeval buf[2];
  2565. #define ATIME buf[0].tv_sec
  2566. #define MTIME buf[1].tv_sec
  2567. #elif defined(HAVE_UTIME_H)
  2568. /* XXX should define struct utimbuf instead, above */
  2569. struct utimbuf buf;
  2570. #define ATIME buf.actime
  2571. #define MTIME buf.modtime
  2572. #define UTIME_ARG &buf
  2573. #else /* HAVE_UTIMES */
  2574. time_t buf[2];
  2575. #define ATIME buf[0]
  2576. #define MTIME buf[1]
  2577. #define UTIME_ARG buf
  2578. #endif /* HAVE_UTIMES */
  2579. if (!PyArg_ParseTuple(args, "etO:utime",
  2580. Py_FileSystemDefaultEncoding, &path, &arg))
  2581. return NULL;
  2582. if (arg == Py_None) {
  2583. /* optional time values not given */
  2584. Py_BEGIN_ALLOW_THREADS
  2585. res = utime(path, NULL);
  2586. Py_END_ALLOW_THREADS
  2587. }
  2588. else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
  2589. PyErr_SetString(PyExc_TypeError,
  2590. "utime() arg 2 must be a tuple (atime, mtime)");
  2591. PyMem_Free(path);
  2592. return NULL;
  2593. }
  2594. else {
  2595. if (extract_time(PyTuple_GET_ITEM(arg, 0),
  2596. &atime, &ausec) == -1) {
  2597. PyMem_Free(path);
  2598. return NULL;
  2599. }
  2600. if (extract_time(PyTuple_GET_ITEM(arg, 1),
  2601. &mtime, &musec) == -1) {
  2602. PyMem_Free(path);
  2603. return NULL;
  2604. }
  2605. ATIME = atime;
  2606. MTIME = mtime;
  2607. #ifdef HAVE_UTIMES
  2608. buf[0].tv_usec = ausec;
  2609. buf[1].tv_usec = musec;
  2610. Py_BEGIN_ALLOW_THREADS
  2611. res = utimes(path, buf);
  2612. Py_END_ALLOW_THREADS
  2613. #else
  2614. Py_BEGIN_ALLOW_THREADS
  2615. res = utime(path, UTIME_ARG);
  2616. Py_END_ALLOW_THREADS
  2617. #endif /* HAVE_UTIMES */
  2618. }
  2619. if (res < 0) {
  2620. return posix_error_with_allocated_filename(path);
  2621. }
  2622. PyMem_Free(path);
  2623. Py_INCREF(Py_None);
  2624. return Py_None;
  2625. #undef UTIME_ARG
  2626. #undef ATIME
  2627. #undef MTIME
  2628. #endif /* Py_WIN_WIDE_FILENAMES */
  2629. }
  2630. /* Process operations */
  2631. PyDoc_STRVAR(posix__exit__doc__,
  2632. "_exit(status)\n\n\
  2633. Exit to the system with specified status, without normal exit processing.");
  2634. static PyObject *
  2635. posix__exit(PyObject *self, PyObject *args)
  2636. {
  2637. int sts;
  2638. if (!PyArg_ParseTuple(args, "i:_exit", &sts))
  2639. return NULL;
  2640. _exit(sts);
  2641. return NULL; /* Make gcc -Wall happy */
  2642. }
  2643. #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
  2644. static void
  2645. free_string_array(char **array, Py_ssize_t count)
  2646. {
  2647. Py_ssize_t i;
  2648. for (i = 0; i < count; i++)
  2649. PyMem_Free(array[i]);
  2650. PyMem_DEL(array);
  2651. }
  2652. #endif
  2653. #ifdef HAVE_EXECV
  2654. PyDoc_STRVAR(posix_execv__doc__,
  2655. "execv(path, args)\n\n\
  2656. Execute an executable path with arguments, replacing current process.\n\
  2657. \n\
  2658. path: path of executable file\n\
  2659. args: tuple or list of strings");
  2660. static PyObject *
  2661. posix_execv(PyObject *self, PyObject *args)
  2662. {
  2663. char *path;
  2664. PyObject *argv;
  2665. char **argvlist;
  2666. Py_ssize_t i, argc;
  2667. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  2668. /* execv has two arguments: (path, argv), where
  2669. argv is a list or tuple of strings. */
  2670. if (!PyArg_ParseTuple(args, "etO:execv",
  2671. Py_FileSystemDefaultEncoding,
  2672. &path, &argv))
  2673. return NULL;
  2674. if (PyList_Check(argv)) {
  2675. argc = PyList_Size(argv);
  2676. getitem = PyList_GetItem;
  2677. }
  2678. else if (PyTuple_Check(argv)) {
  2679. argc = PyTuple_Size(argv);
  2680. getitem = PyTuple_GetItem;
  2681. }
  2682. else {
  2683. PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list");
  2684. PyMem_Free(path);
  2685. return NULL;
  2686. }
  2687. argvlist = PyMem_NEW(char *, argc+1);
  2688. if (argvlist == NULL) {
  2689. PyMem_Free(path);
  2690. return PyErr_NoMemory();
  2691. }
  2692. for (i = 0; i < argc; i++) {
  2693. if (!PyArg_Parse((*getitem)(argv, i), "et",
  2694. Py_FileSystemDefaultEncoding,
  2695. &argvlist[i])) {
  2696. free_string_array(argvlist, i);
  2697. PyErr_SetString(PyExc_TypeError,
  2698. "execv() arg 2 must contain only strings");
  2699. PyMem_Free(path);
  2700. return NULL;
  2701. }
  2702. }
  2703. argvlist[argc] = NULL;
  2704. execv(path, argvlist);
  2705. /* If we get here it's definitely an error */
  2706. free_string_array(argvlist, argc);
  2707. PyMem_Free(path);
  2708. return posix_error();
  2709. }
  2710. PyDoc_STRVAR(posix_execve__doc__,
  2711. "execve(path, args, env)\n\n\
  2712. Execute a path with arguments and environment, replacing current process.\n\
  2713. \n\
  2714. path: path of executable file\n\
  2715. args: tuple or list of arguments\n\
  2716. env: dictionary of strings mapping to strings");
  2717. static PyObject *
  2718. posix_execve(PyObject *self, PyObject *args)
  2719. {
  2720. char *path;
  2721. PyObject *argv, *env;
  2722. char **argvlist;
  2723. char **envlist;
  2724. PyObject *key, *val, *keys=NULL, *vals=NULL;
  2725. Py_ssize_t i, pos, argc, envc;
  2726. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  2727. Py_ssize_t lastarg = 0;
  2728. /* execve has three arguments: (path, argv, env), where
  2729. argv is a list or tuple of strings and env is a dictionary
  2730. like posix.environ. */
  2731. if (!PyArg_ParseTuple(args, "etOO:execve",
  2732. Py_FileSystemDefaultEncoding,
  2733. &path, &argv, &env))
  2734. return NULL;
  2735. if (PyList_Check(argv)) {
  2736. argc = PyList_Size(argv);
  2737. getitem = PyList_GetItem;
  2738. }
  2739. else if (PyTuple_Check(argv)) {
  2740. argc = PyTuple_Size(argv);
  2741. getitem = PyTuple_GetItem;
  2742. }
  2743. else {
  2744. PyErr_SetString(PyExc_TypeError,
  2745. "execve() arg 2 must be a tuple or list");
  2746. goto fail_0;
  2747. }
  2748. if (!PyMapping_Check(env)) {
  2749. PyErr_SetString(PyExc_TypeError,
  2750. "execve() arg 3 must be a mapping object");
  2751. goto fail_0;
  2752. }
  2753. argvlist = PyMem_NEW(char *, argc+1);
  2754. if (argvlist == NULL) {
  2755. PyErr_NoMemory();
  2756. goto fail_0;
  2757. }
  2758. for (i = 0; i < argc; i++) {
  2759. if (!PyArg_Parse((*getitem)(argv, i),
  2760. "et;execve() arg 2 must contain only strings",
  2761. Py_FileSystemDefaultEncoding,
  2762. &argvlist[i]))
  2763. {
  2764. lastarg = i;
  2765. goto fail_1;
  2766. }
  2767. }
  2768. lastarg = argc;
  2769. argvlist[argc] = NULL;
  2770. i = PyMapping_Size(env);
  2771. if (i < 0)
  2772. goto fail_1;
  2773. envlist = PyMem_NEW(char *, i + 1);
  2774. if (envlist == NULL) {
  2775. PyErr_NoMemory();
  2776. goto fail_1;
  2777. }
  2778. envc = 0;
  2779. keys = PyMapping_Keys(env);
  2780. vals = PyMapping_Values(env);
  2781. if (!keys || !vals)
  2782. goto fail_2;
  2783. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  2784. PyErr_SetString(PyExc_TypeError,
  2785. "execve(): env.keys() or env.values() is not a list");
  2786. goto fail_2;
  2787. }
  2788. for (pos = 0; pos < i; pos++) {
  2789. char *p, *k, *v;
  2790. size_t len;
  2791. key = PyList_GetItem(keys, pos);
  2792. val = PyList_GetItem(vals, pos);
  2793. if (!key || !val)
  2794. goto fail_2;
  2795. if (!PyArg_Parse(
  2796. key,
  2797. "s;execve() arg 3 contains a non-string key",
  2798. &k) ||
  2799. !PyArg_Parse(
  2800. val,
  2801. "s;execve() arg 3 contains a non-string value",
  2802. &v))
  2803. {
  2804. goto fail_2;
  2805. }
  2806. #if defined(PYOS_OS2)
  2807. /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */
  2808. if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) {
  2809. #endif
  2810. len = PyString_Size(key) + PyString_Size(val) + 2;
  2811. p = PyMem_NEW(char, len);
  2812. if (p == NULL) {
  2813. PyErr_NoMemory();
  2814. goto fail_2;
  2815. }
  2816. PyOS_snprintf(p, len, "%s=%s", k, v);
  2817. envlist[envc++] = p;
  2818. #if defined(PYOS_OS2)
  2819. }
  2820. #endif
  2821. }
  2822. envlist[envc] = 0;
  2823. execve(path, argvlist, envlist);
  2824. /* If we get here it's definitely an error */
  2825. (void) posix_error();
  2826. fail_2:
  2827. while (--envc >= 0)
  2828. PyMem_DEL(envlist[envc]);
  2829. PyMem_DEL(envlist);
  2830. fail_1:
  2831. free_string_array(argvlist, lastarg);
  2832. Py_XDECREF(vals);
  2833. Py_XDECREF(keys);
  2834. fail_0:
  2835. PyMem_Free(path);
  2836. return NULL;
  2837. }
  2838. #endif /* HAVE_EXECV */
  2839. #ifdef HAVE_SPAWNV
  2840. PyDoc_STRVAR(posix_spawnv__doc__,
  2841. "spawnv(mode, path, args)\n\n\
  2842. Execute the program 'path' in a new process.\n\
  2843. \n\
  2844. mode: mode of process creation\n\
  2845. path: path of executable file\n\
  2846. args: tuple or list of strings");
  2847. static PyObject *
  2848. posix_spawnv(PyObject *self, PyObject *args)
  2849. {
  2850. char *path;
  2851. PyObject *argv;
  2852. char **argvlist;
  2853. int mode, i;
  2854. Py_ssize_t argc;
  2855. Py_intptr_t spawnval;
  2856. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  2857. /* spawnv has three arguments: (mode, path, argv), where
  2858. argv is a list or tuple of strings. */
  2859. if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode,
  2860. Py_FileSystemDefaultEncoding,
  2861. &path, &argv))
  2862. return NULL;
  2863. if (PyList_Check(argv)) {
  2864. argc = PyList_Size(argv);
  2865. getitem = PyList_GetItem;
  2866. }
  2867. else if (PyTuple_Check(argv)) {
  2868. argc = PyTuple_Size(argv);
  2869. getitem = PyTuple_GetItem;
  2870. }
  2871. else {
  2872. PyErr_SetString(PyExc_TypeError,
  2873. "spawnv() arg 2 must be a tuple or list");
  2874. PyMem_Free(path);
  2875. return NULL;
  2876. }
  2877. argvlist = PyMem_NEW(char *, argc+1);
  2878. if (argvlist == NULL) {
  2879. PyMem_Free(path);
  2880. return PyErr_NoMemory();
  2881. }
  2882. for (i = 0; i < argc; i++) {
  2883. if (!PyArg_Parse((*getitem)(argv, i), "et",
  2884. Py_FileSystemDefaultEncoding,
  2885. &argvlist[i])) {
  2886. free_string_array(argvlist, i);
  2887. PyErr_SetString(
  2888. PyExc_TypeError,
  2889. "spawnv() arg 2 must contain only strings");
  2890. PyMem_Free(path);
  2891. return NULL;
  2892. }
  2893. }
  2894. argvlist[argc] = NULL;
  2895. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  2896. Py_BEGIN_ALLOW_THREADS
  2897. spawnval = spawnv(mode, path, argvlist);
  2898. Py_END_ALLOW_THREADS
  2899. #else
  2900. if (mode == _OLD_P_OVERLAY)
  2901. mode = _P_OVERLAY;
  2902. Py_BEGIN_ALLOW_THREADS
  2903. spawnval = _spawnv(mode, path, argvlist);
  2904. Py_END_ALLOW_THREADS
  2905. #endif
  2906. free_string_array(argvlist, argc);
  2907. PyMem_Free(path);
  2908. if (spawnval == -1)
  2909. return posix_error();
  2910. else
  2911. #if SIZEOF_LONG == SIZEOF_VOID_P
  2912. return Py_BuildValue("l", (long) spawnval);
  2913. #else
  2914. return Py_BuildValue("L", (PY_LONG_LONG) spawnval);
  2915. #endif
  2916. }
  2917. PyDoc_STRVAR(posix_spawnve__doc__,
  2918. "spawnve(mode, path, args, env)\n\n\
  2919. Execute the program 'path' in a new process.\n\
  2920. \n\
  2921. mode: mode of process creation\n\
  2922. path: path of executable file\n\
  2923. args: tuple or list of arguments\n\
  2924. env: dictionary of strings mapping to strings");
  2925. static PyObject *
  2926. posix_spawnve(PyObject *self, PyObject *args)
  2927. {
  2928. char *path;
  2929. PyObject *argv, *env;
  2930. char **argvlist;
  2931. char **envlist;
  2932. PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;
  2933. int mode, pos, envc;
  2934. Py_ssize_t argc, i;
  2935. Py_intptr_t spawnval;
  2936. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  2937. Py_ssize_t lastarg = 0;
  2938. /* spawnve has four arguments: (mode, path, argv, env), where
  2939. argv is a list or tuple of strings and env is a dictionary
  2940. like posix.environ. */
  2941. if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode,
  2942. Py_FileSystemDefaultEncoding,
  2943. &path, &argv, &env))
  2944. return NULL;
  2945. if (PyList_Check(argv)) {
  2946. argc = PyList_Size(argv);
  2947. getitem = PyList_GetItem;
  2948. }
  2949. else if (PyTuple_Check(argv)) {
  2950. argc = PyTuple_Size(argv);
  2951. getitem = PyTuple_GetItem;
  2952. }
  2953. else {
  2954. PyErr_SetString(PyExc_TypeError,
  2955. "spawnve() arg 2 must be a tuple or list");
  2956. goto fail_0;
  2957. }
  2958. if (!PyMapping_Check(env)) {
  2959. PyErr_SetString(PyExc_TypeError,
  2960. "spawnve() arg 3 must be a mapping object");
  2961. goto fail_0;
  2962. }
  2963. argvlist = PyMem_NEW(char *, argc+1);
  2964. if (argvlist == NULL) {
  2965. PyErr_NoMemory();
  2966. goto fail_0;
  2967. }
  2968. for (i = 0; i < argc; i++) {
  2969. if (!PyArg_Parse((*getitem)(argv, i),
  2970. "et;spawnve() arg 2 must contain only strings",
  2971. Py_FileSystemDefaultEncoding,
  2972. &argvlist[i]))
  2973. {
  2974. lastarg = i;
  2975. goto fail_1;
  2976. }
  2977. }
  2978. lastarg = argc;
  2979. argvlist[argc] = NULL;
  2980. i = PyMapping_Size(env);
  2981. if (i < 0)
  2982. goto fail_1;
  2983. envlist = PyMem_NEW(char *, i + 1);
  2984. if (envlist == NULL) {
  2985. PyErr_NoMemory();
  2986. goto fail_1;
  2987. }
  2988. envc = 0;
  2989. keys = PyMapping_Keys(env);
  2990. vals = PyMapping_Values(env);
  2991. if (!keys || !vals)
  2992. goto fail_2;
  2993. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  2994. PyErr_SetString(PyExc_TypeError,
  2995. "spawnve(): env.keys() or env.values() is not a list");
  2996. goto fail_2;
  2997. }
  2998. for (pos = 0; pos < i; pos++) {
  2999. char *p, *k, *v;
  3000. size_t len;
  3001. key = PyList_GetItem(keys, pos);
  3002. val = PyList_GetItem(vals, pos);
  3003. if (!key || !val)
  3004. goto fail_2;
  3005. if (!PyArg_Parse(
  3006. key,
  3007. "s;spawnve() arg 3 contains a non-string key",
  3008. &k) ||
  3009. !PyArg_Parse(
  3010. val,
  3011. "s;spawnve() arg 3 contains a non-string value",
  3012. &v))
  3013. {
  3014. goto fail_2;
  3015. }
  3016. len = PyString_Size(key) + PyString_Size(val) + 2;
  3017. p = PyMem_NEW(char, len);
  3018. if (p == NULL) {
  3019. PyErr_NoMemory();
  3020. goto fail_2;
  3021. }
  3022. PyOS_snprintf(p, len, "%s=%s", k, v);
  3023. envlist[envc++] = p;
  3024. }
  3025. envlist[envc] = 0;
  3026. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  3027. Py_BEGIN_ALLOW_THREADS
  3028. spawnval = spawnve(mode, path, argvlist, envlist);
  3029. Py_END_ALLOW_THREADS
  3030. #else
  3031. if (mode == _OLD_P_OVERLAY)
  3032. mode = _P_OVERLAY;
  3033. Py_BEGIN_ALLOW_THREADS
  3034. spawnval = _spawnve(mode, path, argvlist, envlist);
  3035. Py_END_ALLOW_THREADS
  3036. #endif
  3037. if (spawnval == -1)
  3038. (void) posix_error();
  3039. else
  3040. #if SIZEOF_LONG == SIZEOF_VOID_P
  3041. res = Py_BuildValue("l", (long) spawnval);
  3042. #else
  3043. res = Py_BuildValue("L", (PY_LONG_LONG) spawnval);
  3044. #endif
  3045. fail_2:
  3046. while (--envc >= 0)
  3047. PyMem_DEL(envlist[envc]);
  3048. PyMem_DEL(envlist);
  3049. fail_1:
  3050. free_string_array(argvlist, lastarg);
  3051. Py_XDECREF(vals);
  3052. Py_XDECREF(keys);
  3053. fail_0:
  3054. PyMem_Free(path);
  3055. return res;
  3056. }
  3057. /* OS/2 supports spawnvp & spawnvpe natively */
  3058. #if defined(PYOS_OS2)
  3059. PyDoc_STRVAR(posix_spawnvp__doc__,
  3060. "spawnvp(mode, file, args)\n\n\
  3061. Execute the program 'file' in a new process, using the environment\n\
  3062. search path to find the file.\n\
  3063. \n\
  3064. mode: mode of process creation\n\
  3065. file: executable file name\n\
  3066. args: tuple or list of strings");
  3067. static PyObject *
  3068. posix_spawnvp(PyObject *self, PyObject *args)
  3069. {
  3070. char *path;
  3071. PyObject *argv;
  3072. char **argvlist;
  3073. int mode, i, argc;
  3074. Py_intptr_t spawnval;
  3075. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  3076. /* spawnvp has three arguments: (mode, path, argv), where
  3077. argv is a list or tuple of strings. */
  3078. if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode,
  3079. Py_FileSystemDefaultEncoding,
  3080. &path, &argv))
  3081. return NULL;
  3082. if (PyList_Check(argv)) {
  3083. argc = PyList_Size(argv);
  3084. getitem = PyList_GetItem;
  3085. }
  3086. else if (PyTuple_Check(argv)) {
  3087. argc = PyTuple_Size(argv);
  3088. getitem = PyTuple_GetItem;
  3089. }
  3090. else {
  3091. PyErr_SetString(PyExc_TypeError,
  3092. "spawnvp() arg 2 must be a tuple or list");
  3093. PyMem_Free(path);
  3094. return NULL;
  3095. }
  3096. argvlist = PyMem_NEW(char *, argc+1);
  3097. if (argvlist == NULL) {
  3098. PyMem_Free(path);
  3099. return PyErr_NoMemory();
  3100. }
  3101. for (i = 0; i < argc; i++) {
  3102. if (!PyArg_Parse((*getitem)(argv, i), "et",
  3103. Py_FileSystemDefaultEncoding,
  3104. &argvlist[i])) {
  3105. free_string_array(argvlist, i);
  3106. PyErr_SetString(
  3107. PyExc_TypeError,
  3108. "spawnvp() arg 2 must contain only strings");
  3109. PyMem_Free(path);
  3110. return NULL;
  3111. }
  3112. }
  3113. argvlist[argc] = NULL;
  3114. Py_BEGIN_ALLOW_THREADS
  3115. #if defined(PYCC_GCC)
  3116. spawnval = spawnvp(mode, path, argvlist);
  3117. #else
  3118. spawnval = _spawnvp(mode, path, argvlist);
  3119. #endif
  3120. Py_END_ALLOW_THREADS
  3121. free_string_array(argvlist, argc);
  3122. PyMem_Free(path);
  3123. if (spawnval == -1)
  3124. return posix_error();
  3125. else
  3126. return Py_BuildValue("l", (long) spawnval);
  3127. }
  3128. PyDoc_STRVAR(posix_spawnvpe__doc__,
  3129. "spawnvpe(mode, file, args, env)\n\n\
  3130. Execute the program 'file' in a new process, using the environment\n\
  3131. search path to find the file.\n\
  3132. \n\
  3133. mode: mode of process creation\n\
  3134. file: executable file name\n\
  3135. args: tuple or list of arguments\n\
  3136. env: dictionary of strings mapping to strings");
  3137. static PyObject *
  3138. posix_spawnvpe(PyObject *self, PyObject *args)
  3139. {
  3140. char *path;
  3141. PyObject *argv, *env;
  3142. char **argvlist;
  3143. char **envlist;
  3144. PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL;
  3145. int mode, i, pos, argc, envc;
  3146. Py_intptr_t spawnval;
  3147. PyObject *(*getitem)(PyObject *, Py_ssize_t);
  3148. int lastarg = 0;
  3149. /* spawnvpe has four arguments: (mode, path, argv, env), where
  3150. argv is a list or tuple of strings and env is a dictionary
  3151. like posix.environ. */
  3152. if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode,
  3153. Py_FileSystemDefaultEncoding,
  3154. &path, &argv, &env))
  3155. return NULL;
  3156. if (PyList_Check(argv)) {
  3157. argc = PyList_Size(argv);
  3158. getitem = PyList_GetItem;
  3159. }
  3160. else if (PyTuple_Check(argv)) {
  3161. argc = PyTuple_Size(argv);
  3162. getitem = PyTuple_GetItem;
  3163. }
  3164. else {
  3165. PyErr_SetString(PyExc_TypeError,
  3166. "spawnvpe() arg 2 must be a tuple or list");
  3167. goto fail_0;
  3168. }
  3169. if (!PyMapping_Check(env)) {
  3170. PyErr_SetString(PyExc_TypeError,
  3171. "spawnvpe() arg 3 must be a mapping object");
  3172. goto fail_0;
  3173. }
  3174. argvlist = PyMem_NEW(char *, argc+1);
  3175. if (argvlist == NULL) {
  3176. PyErr_NoMemory();
  3177. goto fail_0;
  3178. }
  3179. for (i = 0; i < argc; i++) {
  3180. if (!PyArg_Parse((*getitem)(argv, i),
  3181. "et;spawnvpe() arg 2 must contain only strings",
  3182. Py_FileSystemDefaultEncoding,
  3183. &argvlist[i]))
  3184. {
  3185. lastarg = i;
  3186. goto fail_1;
  3187. }
  3188. }
  3189. lastarg = argc;
  3190. argvlist[argc] = NULL;
  3191. i = PyMapping_Size(env);
  3192. if (i < 0)
  3193. goto fail_1;
  3194. envlist = PyMem_NEW(char *, i + 1);
  3195. if (envlist == NULL) {
  3196. PyErr_NoMemory();
  3197. goto fail_1;
  3198. }
  3199. envc = 0;
  3200. keys = PyMapping_Keys(env);
  3201. vals = PyMapping_Values(env);
  3202. if (!keys || !vals)
  3203. goto fail_2;
  3204. if (!PyList_Check(keys) || !PyList_Check(vals)) {
  3205. PyErr_SetString(PyExc_TypeError,
  3206. "spawnvpe(): env.keys() or env.values() is not a list");
  3207. goto fail_2;
  3208. }
  3209. for (pos = 0; pos < i; pos++) {
  3210. char *p, *k, *v;
  3211. size_t len;
  3212. key = PyList_GetItem(keys, pos);
  3213. val = PyList_GetItem(vals, pos);
  3214. if (!key || !val)
  3215. goto fail_2;
  3216. if (!PyArg_Parse(
  3217. key,
  3218. "s;spawnvpe() arg 3 contains a non-string key",
  3219. &k) ||
  3220. !PyArg_Parse(
  3221. val,
  3222. "s;spawnvpe() arg 3 contains a non-string value",
  3223. &v))
  3224. {
  3225. goto fail_2;
  3226. }
  3227. len = PyString_Size(key) + PyString_Size(val) + 2;
  3228. p = PyMem_NEW(char, len);
  3229. if (p == NULL) {
  3230. PyErr_NoMemory();
  3231. goto fail_2;
  3232. }
  3233. PyOS_snprintf(p, len, "%s=%s", k, v);
  3234. envlist[envc++] = p;
  3235. }
  3236. envlist[envc] = 0;
  3237. Py_BEGIN_ALLOW_THREADS
  3238. #if defined(PYCC_GCC)
  3239. spawnval = spawnvpe(mode, path, argvlist, envlist);
  3240. #else
  3241. spawnval = _spawnvpe(mode, path, argvlist, envlist);
  3242. #endif
  3243. Py_END_ALLOW_THREADS
  3244. if (spawnval == -1)
  3245. (void) posix_error();
  3246. else
  3247. res = Py_BuildValue("l", (long) spawnval);
  3248. fail_2:
  3249. while (--envc >= 0)
  3250. PyMem_DEL(envlist[envc]);
  3251. PyMem_DEL(envlist);
  3252. fail_1:
  3253. free_string_array(argvlist, lastarg);
  3254. Py_XDECREF(vals);
  3255. Py_XDECREF(keys);
  3256. fail_0:
  3257. PyMem_Free(path);
  3258. return res;
  3259. }
  3260. #endif /* PYOS_OS2 */
  3261. #endif /* HAVE_SPAWNV */
  3262. #ifdef HAVE_FORK1
  3263. PyDoc_STRVAR(posix_fork1__doc__,
  3264. "fork1() -> pid\n\n\
  3265. Fork a child process with a single multiplexed (i.e., not bound) thread.\n\
  3266. \n\
  3267. Return 0 to child process and PID of child to parent process.");
  3268. static PyObject *
  3269. posix_fork1(PyObject *self, PyObject *noargs)
  3270. {
  3271. pid_t pid;
  3272. int result;
  3273. _PyImport_AcquireLock();
  3274. pid = fork1();
  3275. result = _PyImport_ReleaseLock();
  3276. if (pid == -1)
  3277. return posix_error();
  3278. if (pid == 0)
  3279. PyOS_AfterFork();
  3280. if (result < 0) {
  3281. /* Don't clobber the OSError if the fork failed. */
  3282. PyErr_SetString(PyExc_RuntimeError,
  3283. "not holding the import lock");
  3284. return NULL;
  3285. }
  3286. return PyLong_FromPid(pid);
  3287. }
  3288. #endif
  3289. #ifdef HAVE_FORK
  3290. PyDoc_STRVAR(posix_fork__doc__,
  3291. "fork() -> pid\n\n\
  3292. Fork a child process.\n\
  3293. Return 0 to child process and PID of child to parent process.");
  3294. static PyObject *
  3295. posix_fork(PyObject *self, PyObject *noargs)
  3296. {
  3297. pid_t pid;
  3298. int result;
  3299. _PyImport_AcquireLock();
  3300. pid = fork();
  3301. result = _PyImport_ReleaseLock();
  3302. if (pid == -1)
  3303. return posix_error();
  3304. if (pid == 0)
  3305. PyOS_AfterFork();
  3306. if (result < 0) {
  3307. /* Don't clobber the OSError if the fork failed. */
  3308. PyErr_SetString(PyExc_RuntimeError,
  3309. "not holding the import lock");
  3310. return NULL;
  3311. }
  3312. return PyLong_FromPid(pid);
  3313. }
  3314. #endif
  3315. /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
  3316. /* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
  3317. #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
  3318. #define DEV_PTY_FILE "/dev/ptc"
  3319. #define HAVE_DEV_PTMX
  3320. #else
  3321. #define DEV_PTY_FILE "/dev/ptmx"
  3322. #endif
  3323. #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
  3324. #ifdef HAVE_PTY_H
  3325. #include <pty.h>
  3326. #else
  3327. #ifdef HAVE_LIBUTIL_H
  3328. #include <libutil.h>
  3329. #endif /* HAVE_LIBUTIL_H */
  3330. #endif /* HAVE_PTY_H */
  3331. #ifdef HAVE_STROPTS_H
  3332. #include <stropts.h>
  3333. #endif
  3334. #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX */
  3335. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  3336. PyDoc_STRVAR(posix_openpty__doc__,
  3337. "openpty() -> (master_fd, slave_fd)\n\n\
  3338. Open a pseudo-terminal, returning open fd's for both master and slave end.\n");
  3339. static PyObject *
  3340. posix_openpty(PyObject *self, PyObject *noargs)
  3341. {
  3342. int master_fd, slave_fd;
  3343. #ifndef HAVE_OPENPTY
  3344. char * slave_name;
  3345. #endif
  3346. #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
  3347. PyOS_sighandler_t sig_saved;
  3348. #ifdef sun
  3349. extern char *ptsname(int fildes);
  3350. #endif
  3351. #endif
  3352. #ifdef HAVE_OPENPTY
  3353. if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
  3354. return posix_error();
  3355. #elif defined(HAVE__GETPTY)
  3356. slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
  3357. if (slave_name == NULL)
  3358. return posix_error();
  3359. slave_fd = open(slave_name, O_RDWR);
  3360. if (slave_fd < 0)
  3361. return posix_error();
  3362. #else
  3363. master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
  3364. if (master_fd < 0)
  3365. return posix_error();
  3366. sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
  3367. /* change permission of slave */
  3368. if (grantpt(master_fd) < 0) {
  3369. PyOS_setsig(SIGCHLD, sig_saved);
  3370. return posix_error();
  3371. }
  3372. /* unlock slave */
  3373. if (unlockpt(master_fd) < 0) {
  3374. PyOS_setsig(SIGCHLD, sig_saved);
  3375. return posix_error();
  3376. }
  3377. PyOS_setsig(SIGCHLD, sig_saved);
  3378. slave_name = ptsname(master_fd); /* get name of slave */
  3379. if (slave_name == NULL)
  3380. return posix_error();
  3381. slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
  3382. if (slave_fd < 0)
  3383. return posix_error();
  3384. #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC)
  3385. ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
  3386. ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
  3387. #ifndef __hpux
  3388. ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
  3389. #endif /* __hpux */
  3390. #endif /* HAVE_CYGWIN */
  3391. #endif /* HAVE_OPENPTY */
  3392. return Py_BuildValue("(ii)", master_fd, slave_fd);
  3393. }
  3394. #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
  3395. #ifdef HAVE_FORKPTY
  3396. PyDoc_STRVAR(posix_forkpty__doc__,
  3397. "forkpty() -> (pid, master_fd)\n\n\
  3398. Fork a new process with a new pseudo-terminal as controlling tty.\n\n\
  3399. Like fork(), return 0 as pid to child process, and PID of child to parent.\n\
  3400. To both, return fd of newly opened pseudo-terminal.\n");
  3401. static PyObject *
  3402. posix_forkpty(PyObject *self, PyObject *noargs)
  3403. {
  3404. int master_fd = -1, result;
  3405. pid_t pid;
  3406. _PyImport_AcquireLock();
  3407. pid = forkpty(&master_fd, NULL, NULL, NULL);
  3408. result = _PyImport_ReleaseLock();
  3409. if (pid == -1)
  3410. return posix_error();
  3411. if (pid == 0)
  3412. PyOS_AfterFork();
  3413. if (result < 0) {
  3414. /* Don't clobber the OSError if the fork failed. */
  3415. PyErr_SetString(PyExc_RuntimeError,
  3416. "not holding the import lock");
  3417. return NULL;
  3418. }
  3419. return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
  3420. }
  3421. #endif
  3422. #ifdef HAVE_GETEGID
  3423. PyDoc_STRVAR(posix_getegid__doc__,
  3424. "getegid() -> egid\n\n\
  3425. Return the current process's effective group id.");
  3426. static PyObject *
  3427. posix_getegid(PyObject *self, PyObject *noargs)
  3428. {
  3429. return PyInt_FromLong((long)getegid());
  3430. }
  3431. #endif
  3432. #ifdef HAVE_GETEUID
  3433. PyDoc_STRVAR(posix_geteuid__doc__,
  3434. "geteuid() -> euid\n\n\
  3435. Return the current process's effective user id.");
  3436. static PyObject *
  3437. posix_geteuid(PyObject *self, PyObject *noargs)
  3438. {
  3439. return PyInt_FromLong((long)geteuid());
  3440. }
  3441. #endif
  3442. #ifdef HAVE_GETGID
  3443. PyDoc_STRVAR(posix_getgid__doc__,
  3444. "getgid() -> gid\n\n\
  3445. Return the current process's group id.");
  3446. static PyObject *
  3447. posix_getgid(PyObject *self, PyObject *noargs)
  3448. {
  3449. return PyInt_FromLong((long)getgid());
  3450. }
  3451. #endif
  3452. PyDoc_STRVAR(posix_getpid__doc__,
  3453. "getpid() -> pid\n\n\
  3454. Return the current process id");
  3455. static PyObject *
  3456. posix_getpid(PyObject *self, PyObject *noargs)
  3457. {
  3458. return PyLong_FromPid(getpid());
  3459. }
  3460. #ifdef HAVE_GETGROUPS
  3461. PyDoc_STRVAR(posix_getgroups__doc__,
  3462. "getgroups() -> list of group IDs\n\n\
  3463. Return list of supplemental group IDs for the process.");
  3464. static PyObject *
  3465. posix_getgroups(PyObject *self, PyObject *noargs)
  3466. {
  3467. PyObject *result = NULL;
  3468. #ifdef NGROUPS_MAX
  3469. #define MAX_GROUPS NGROUPS_MAX
  3470. #else
  3471. /* defined to be 16 on Solaris7, so this should be a small number */
  3472. #define MAX_GROUPS 64
  3473. #endif
  3474. gid_t grouplist[MAX_GROUPS];
  3475. int n;
  3476. n = getgroups(MAX_GROUPS, grouplist);
  3477. if (n < 0)
  3478. posix_error();
  3479. else {
  3480. result = PyList_New(n);
  3481. if (result != NULL) {
  3482. int i;
  3483. for (i = 0; i < n; ++i) {
  3484. PyObject *o = PyInt_FromLong((long)grouplist[i]);
  3485. if (o == NULL) {
  3486. Py_DECREF(result);
  3487. result = NULL;
  3488. break;
  3489. }
  3490. PyList_SET_ITEM(result, i, o);
  3491. }
  3492. }
  3493. }
  3494. return result;
  3495. }
  3496. #endif
  3497. #ifdef HAVE_GETPGID
  3498. PyDoc_STRVAR(posix_getpgid__doc__,
  3499. "getpgid(pid) -> pgid\n\n\
  3500. Call the system call getpgid().");
  3501. static PyObject *
  3502. posix_getpgid(PyObject *self, PyObject *args)
  3503. {
  3504. pid_t pid, pgid;
  3505. if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid))
  3506. return NULL;
  3507. pgid = getpgid(pid);
  3508. if (pgid < 0)
  3509. return posix_error();
  3510. return PyLong_FromPid(pgid);
  3511. }
  3512. #endif /* HAVE_GETPGID */
  3513. #ifdef HAVE_GETPGRP
  3514. PyDoc_STRVAR(posix_getpgrp__doc__,
  3515. "getpgrp() -> pgrp\n\n\
  3516. Return the current process group id.");
  3517. static PyObject *
  3518. posix_getpgrp(PyObject *self, PyObject *noargs)
  3519. {
  3520. #ifdef GETPGRP_HAVE_ARG
  3521. return PyLong_FromPid(getpgrp(0));
  3522. #else /* GETPGRP_HAVE_ARG */
  3523. return PyLong_FromPid(getpgrp());
  3524. #endif /* GETPGRP_HAVE_ARG */
  3525. }
  3526. #endif /* HAVE_GETPGRP */
  3527. #ifdef HAVE_SETPGRP
  3528. PyDoc_STRVAR(posix_setpgrp__doc__,
  3529. "setpgrp()\n\n\
  3530. Make this process a session leader.");
  3531. static PyObject *
  3532. posix_setpgrp(PyObject *self, PyObject *noargs)
  3533. {
  3534. #ifdef SETPGRP_HAVE_ARG
  3535. if (setpgrp(0, 0) < 0)
  3536. #else /* SETPGRP_HAVE_ARG */
  3537. if (setpgrp() < 0)
  3538. #endif /* SETPGRP_HAVE_ARG */
  3539. return posix_error();
  3540. Py_INCREF(Py_None);
  3541. return Py_None;
  3542. }
  3543. #endif /* HAVE_SETPGRP */
  3544. #ifdef HAVE_GETPPID
  3545. PyDoc_STRVAR(posix_getppid__doc__,
  3546. "getppid() -> ppid\n\n\
  3547. Return the parent's process id.");
  3548. static PyObject *
  3549. posix_getppid(PyObject *self, PyObject *noargs)
  3550. {
  3551. return PyLong_FromPid(getppid());
  3552. }
  3553. #endif
  3554. #ifdef HAVE_GETLOGIN
  3555. PyDoc_STRVAR(posix_getlogin__doc__,
  3556. "getlogin() -> string\n\n\
  3557. Return the actual login name.");
  3558. static PyObject *
  3559. posix_getlogin(PyObject *self, PyObject *noargs)
  3560. {
  3561. PyObject *result = NULL;
  3562. char *name;
  3563. int old_errno = errno;
  3564. errno = 0;
  3565. name = getlogin();
  3566. if (name == NULL) {
  3567. if (errno)
  3568. posix_error();
  3569. else
  3570. PyErr_SetString(PyExc_OSError,
  3571. "unable to determine login name");
  3572. }
  3573. else
  3574. result = PyString_FromString(name);
  3575. errno = old_errno;
  3576. return result;
  3577. }
  3578. #endif
  3579. #ifdef HAVE_GETUID
  3580. PyDoc_STRVAR(posix_getuid__doc__,
  3581. "getuid() -> uid\n\n\
  3582. Return the current process's user id.");
  3583. static PyObject *
  3584. posix_getuid(PyObject *self, PyObject *noargs)
  3585. {
  3586. return PyInt_FromLong((long)getuid());
  3587. }
  3588. #endif
  3589. #ifdef HAVE_KILL
  3590. PyDoc_STRVAR(posix_kill__doc__,
  3591. "kill(pid, sig)\n\n\
  3592. Kill a process with a signal.");
  3593. static PyObject *
  3594. posix_kill(PyObject *self, PyObject *args)
  3595. {
  3596. pid_t pid;
  3597. int sig;
  3598. if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig))
  3599. return NULL;
  3600. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  3601. if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) {
  3602. APIRET rc;
  3603. if ((rc = DosSendSignalException(pid, sig)) != NO_ERROR)
  3604. return os2_error(rc);
  3605. } else if (sig == XCPT_SIGNAL_KILLPROC) {
  3606. APIRET rc;
  3607. if ((rc = DosKillProcess(DKP_PROCESS, pid)) != NO_ERROR)
  3608. return os2_error(rc);
  3609. } else
  3610. return NULL; /* Unrecognized Signal Requested */
  3611. #else
  3612. if (kill(pid, sig) == -1)
  3613. return posix_error();
  3614. #endif
  3615. Py_INCREF(Py_None);
  3616. return Py_None;
  3617. }
  3618. #endif
  3619. #ifdef HAVE_KILLPG
  3620. PyDoc_STRVAR(posix_killpg__doc__,
  3621. "killpg(pgid, sig)\n\n\
  3622. Kill a process group with a signal.");
  3623. static PyObject *
  3624. posix_killpg(PyObject *self, PyObject *args)
  3625. {
  3626. int sig;
  3627. pid_t pgid;
  3628. /* XXX some man pages make the `pgid` parameter an int, others
  3629. a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
  3630. take the same type. Moreover, pid_t is always at least as wide as
  3631. int (else compilation of this module fails), which is safe. */
  3632. if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig))
  3633. return NULL;
  3634. if (killpg(pgid, sig) == -1)
  3635. return posix_error();
  3636. Py_INCREF(Py_None);
  3637. return Py_None;
  3638. }
  3639. #endif
  3640. #ifdef HAVE_PLOCK
  3641. #ifdef HAVE_SYS_LOCK_H
  3642. #include <sys/lock.h>
  3643. #endif
  3644. PyDoc_STRVAR(posix_plock__doc__,
  3645. "plock(op)\n\n\
  3646. Lock program segments into memory.");
  3647. static PyObject *
  3648. posix_plock(PyObject *self, PyObject *args)
  3649. {
  3650. int op;
  3651. if (!PyArg_ParseTuple(args, "i:plock", &op))
  3652. return NULL;
  3653. if (plock(op) == -1)
  3654. return posix_error();
  3655. Py_INCREF(Py_None);
  3656. return Py_None;
  3657. }
  3658. #endif
  3659. #ifdef HAVE_POPEN
  3660. PyDoc_STRVAR(posix_popen__doc__,
  3661. "popen(command [, mode='r' [, bufsize]]) -> pipe\n\n\
  3662. Open a pipe to/from a command returning a file object.");
  3663. #if defined(PYOS_OS2)
  3664. #if defined(PYCC_VACPP)
  3665. static int
  3666. async_system(const char *command)
  3667. {
  3668. char errormsg[256], args[1024];
  3669. RESULTCODES rcodes;
  3670. APIRET rc;
  3671. char *shell = getenv("COMSPEC");
  3672. if (!shell)
  3673. shell = "cmd";
  3674. /* avoid overflowing the argument buffer */
  3675. if (strlen(shell) + 3 + strlen(command) >= 1024)
  3676. return ERROR_NOT_ENOUGH_MEMORY
  3677. args[0] = '\0';
  3678. strcat(args, shell);
  3679. strcat(args, "/c ");
  3680. strcat(args, command);
  3681. /* execute asynchronously, inheriting the environment */
  3682. rc = DosExecPgm(errormsg,
  3683. sizeof(errormsg),
  3684. EXEC_ASYNC,
  3685. args,
  3686. NULL,
  3687. &rcodes,
  3688. shell);
  3689. return rc;
  3690. }
  3691. static FILE *
  3692. popen(const char *command, const char *mode, int pipesize, int *err)
  3693. {
  3694. int oldfd, tgtfd;
  3695. HFILE pipeh[2];
  3696. APIRET rc;
  3697. /* mode determines which of stdin or stdout is reconnected to
  3698. * the pipe to the child
  3699. */
  3700. if (strchr(mode, 'r') != NULL) {
  3701. tgt_fd = 1; /* stdout */
  3702. } else if (strchr(mode, 'w')) {
  3703. tgt_fd = 0; /* stdin */
  3704. } else {
  3705. *err = ERROR_INVALID_ACCESS;
  3706. return NULL;
  3707. }
  3708. /* setup the pipe */
  3709. if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) {
  3710. *err = rc;
  3711. return NULL;
  3712. }
  3713. /* prevent other threads accessing stdio */
  3714. DosEnterCritSec();
  3715. /* reconnect stdio and execute child */
  3716. oldfd = dup(tgtfd);
  3717. close(tgtfd);
  3718. if (dup2(pipeh[tgtfd], tgtfd) == 0) {
  3719. DosClose(pipeh[tgtfd]);
  3720. rc = async_system(command);
  3721. }
  3722. /* restore stdio */
  3723. dup2(oldfd, tgtfd);
  3724. close(oldfd);
  3725. /* allow other threads access to stdio */
  3726. DosExitCritSec();
  3727. /* if execution of child was successful return file stream */
  3728. if (rc == NO_ERROR)
  3729. return fdopen(pipeh[1 - tgtfd], mode);
  3730. else {
  3731. DosClose(pipeh[1 - tgtfd]);
  3732. *err = rc;
  3733. return NULL;
  3734. }
  3735. }
  3736. static PyObject *
  3737. posix_popen(PyObject *self, PyObject *args)
  3738. {
  3739. char *name;
  3740. char *mode = "r";
  3741. int err, bufsize = -1;
  3742. FILE *fp;
  3743. PyObject *f;
  3744. if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
  3745. return NULL;
  3746. Py_BEGIN_ALLOW_THREADS
  3747. fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err);
  3748. Py_END_ALLOW_THREADS
  3749. if (fp == NULL)
  3750. return os2_error(err);
  3751. f = PyFile_FromFile(fp, name, mode, fclose);
  3752. if (f != NULL)
  3753. PyFile_SetBufSize(f, bufsize);
  3754. return f;
  3755. }
  3756. #elif defined(PYCC_GCC)
  3757. /* standard posix version of popen() support */
  3758. static PyObject *
  3759. posix_popen(PyObject *self, PyObject *args)
  3760. {
  3761. char *name;
  3762. char *mode = "r";
  3763. int bufsize = -1;
  3764. FILE *fp;
  3765. PyObject *f;
  3766. if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
  3767. return NULL;
  3768. Py_BEGIN_ALLOW_THREADS
  3769. fp = popen(name, mode);
  3770. Py_END_ALLOW_THREADS
  3771. if (fp == NULL)
  3772. return posix_error();
  3773. f = PyFile_FromFile(fp, name, mode, pclose);
  3774. if (f != NULL)
  3775. PyFile_SetBufSize(f, bufsize);
  3776. return f;
  3777. }
  3778. /* fork() under OS/2 has lots'o'warts
  3779. * EMX supports pipe() and spawn*() so we can synthesize popen[234]()
  3780. * most of this code is a ripoff of the win32 code, but using the
  3781. * capabilities of EMX's C library routines
  3782. */
  3783. /* These tell _PyPopen() whether to return 1, 2, or 3 file objects. */
  3784. #define POPEN_1 1
  3785. #define POPEN_2 2
  3786. #define POPEN_3 3
  3787. #define POPEN_4 4
  3788. static PyObject *_PyPopen(char *, int, int, int);
  3789. static int _PyPclose(FILE *file);
  3790. /*
  3791. * Internal dictionary mapping popen* file pointers to process handles,
  3792. * for use when retrieving the process exit code. See _PyPclose() below
  3793. * for more information on this dictionary's use.
  3794. */
  3795. static PyObject *_PyPopenProcs = NULL;
  3796. /* os2emx version of popen2()
  3797. *
  3798. * The result of this function is a pipe (file) connected to the
  3799. * process's stdin, and a pipe connected to the process's stdout.
  3800. */
  3801. static PyObject *
  3802. os2emx_popen2(PyObject *self, PyObject *args)
  3803. {
  3804. PyObject *f;
  3805. int tm=0;
  3806. char *cmdstring;
  3807. char *mode = "t";
  3808. int bufsize = -1;
  3809. if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))
  3810. return NULL;
  3811. if (*mode == 't')
  3812. tm = O_TEXT;
  3813. else if (*mode != 'b') {
  3814. PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
  3815. return NULL;
  3816. } else
  3817. tm = O_BINARY;
  3818. f = _PyPopen(cmdstring, tm, POPEN_2, bufsize);
  3819. return f;
  3820. }
  3821. /*
  3822. * Variation on os2emx.popen2
  3823. *
  3824. * The result of this function is 3 pipes - the process's stdin,
  3825. * stdout and stderr
  3826. */
  3827. static PyObject *
  3828. os2emx_popen3(PyObject *self, PyObject *args)
  3829. {
  3830. PyObject *f;
  3831. int tm = 0;
  3832. char *cmdstring;
  3833. char *mode = "t";
  3834. int bufsize = -1;
  3835. if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))
  3836. return NULL;
  3837. if (*mode == 't')
  3838. tm = O_TEXT;
  3839. else if (*mode != 'b') {
  3840. PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
  3841. return NULL;
  3842. } else
  3843. tm = O_BINARY;
  3844. f = _PyPopen(cmdstring, tm, POPEN_3, bufsize);
  3845. return f;
  3846. }
  3847. /*
  3848. * Variation on os2emx.popen2
  3849. *
  3850. * The result of this function is 2 pipes - the processes stdin,
  3851. * and stdout+stderr combined as a single pipe.
  3852. */
  3853. static PyObject *
  3854. os2emx_popen4(PyObject *self, PyObject *args)
  3855. {
  3856. PyObject *f;
  3857. int tm = 0;
  3858. char *cmdstring;
  3859. char *mode = "t";
  3860. int bufsize = -1;
  3861. if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))
  3862. return NULL;
  3863. if (*mode == 't')
  3864. tm = O_TEXT;
  3865. else if (*mode != 'b') {
  3866. PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'");
  3867. return NULL;
  3868. } else
  3869. tm = O_BINARY;
  3870. f = _PyPopen(cmdstring, tm, POPEN_4, bufsize);
  3871. return f;
  3872. }
  3873. /* a couple of structures for convenient handling of multiple
  3874. * file handles and pipes
  3875. */
  3876. struct file_ref
  3877. {
  3878. int handle;
  3879. int flags;
  3880. };
  3881. struct pipe_ref
  3882. {
  3883. int rd;
  3884. int wr;
  3885. };
  3886. /* The following code is derived from the win32 code */
  3887. static PyObject *
  3888. _PyPopen(char *cmdstring, int mode, int n, int bufsize)
  3889. {
  3890. struct file_ref stdio[3];
  3891. struct pipe_ref p_fd[3];
  3892. FILE *p_s[3];
  3893. int file_count, i, pipe_err;
  3894. pid_t pipe_pid;
  3895. char *shell, *sh_name, *opt, *rd_mode, *wr_mode;
  3896. PyObject *f, *p_f[3];
  3897. /* file modes for subsequent fdopen's on pipe handles */
  3898. if (mode == O_TEXT)
  3899. {
  3900. rd_mode = "rt";
  3901. wr_mode = "wt";
  3902. }
  3903. else
  3904. {
  3905. rd_mode = "rb";
  3906. wr_mode = "wb";
  3907. }
  3908. /* prepare shell references */
  3909. if ((shell = getenv("EMXSHELL")) == NULL)
  3910. if ((shell = getenv("COMSPEC")) == NULL)
  3911. {
  3912. errno = ENOENT;
  3913. return posix_error();
  3914. }
  3915. sh_name = _getname(shell);
  3916. if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0)
  3917. opt = "/c";
  3918. else
  3919. opt = "-c";
  3920. /* save current stdio fds + their flags, and set not inheritable */
  3921. i = pipe_err = 0;
  3922. while (pipe_err >= 0 && i < 3)
  3923. {
  3924. pipe_err = stdio[i].handle = dup(i);
  3925. stdio[i].flags = fcntl(i, F_GETFD, 0);
  3926. fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC);
  3927. i++;
  3928. }
  3929. if (pipe_err < 0)
  3930. {
  3931. /* didn't get them all saved - clean up and bail out */
  3932. int saved_err = errno;
  3933. while (i-- > 0)
  3934. {
  3935. close(stdio[i].handle);
  3936. }
  3937. errno = saved_err;
  3938. return posix_error();
  3939. }
  3940. /* create pipe ends */
  3941. file_count = 2;
  3942. if (n == POPEN_3)
  3943. file_count = 3;
  3944. i = pipe_err = 0;
  3945. while ((pipe_err == 0) && (i < file_count))
  3946. pipe_err = pipe((int *)&p_fd[i++]);
  3947. if (pipe_err < 0)
  3948. {
  3949. /* didn't get them all made - clean up and bail out */
  3950. while (i-- > 0)
  3951. {
  3952. close(p_fd[i].wr);
  3953. close(p_fd[i].rd);
  3954. }
  3955. errno = EPIPE;
  3956. return posix_error();
  3957. }
  3958. /* change the actual standard IO streams over temporarily,
  3959. * making the retained pipe ends non-inheritable
  3960. */
  3961. pipe_err = 0;
  3962. /* - stdin */
  3963. if (dup2(p_fd[0].rd, 0) == 0)
  3964. {
  3965. close(p_fd[0].rd);
  3966. i = fcntl(p_fd[0].wr, F_GETFD, 0);
  3967. fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC);
  3968. if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL)
  3969. {
  3970. close(p_fd[0].wr);
  3971. pipe_err = -1;
  3972. }
  3973. }
  3974. else
  3975. {
  3976. pipe_err = -1;
  3977. }
  3978. /* - stdout */
  3979. if (pipe_err == 0)
  3980. {
  3981. if (dup2(p_fd[1].wr, 1) == 1)
  3982. {
  3983. close(p_fd[1].wr);
  3984. i = fcntl(p_fd[1].rd, F_GETFD, 0);
  3985. fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC);
  3986. if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL)
  3987. {
  3988. close(p_fd[1].rd);
  3989. pipe_err = -1;
  3990. }
  3991. }
  3992. else
  3993. {
  3994. pipe_err = -1;
  3995. }
  3996. }
  3997. /* - stderr, as required */
  3998. if (pipe_err == 0)
  3999. switch (n)
  4000. {
  4001. case POPEN_3:
  4002. {
  4003. if (dup2(p_fd[2].wr, 2) == 2)
  4004. {
  4005. close(p_fd[2].wr);
  4006. i = fcntl(p_fd[2].rd, F_GETFD, 0);
  4007. fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC);
  4008. if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL)
  4009. {
  4010. close(p_fd[2].rd);
  4011. pipe_err = -1;
  4012. }
  4013. }
  4014. else
  4015. {
  4016. pipe_err = -1;
  4017. }
  4018. break;
  4019. }
  4020. case POPEN_4:
  4021. {
  4022. if (dup2(1, 2) != 2)
  4023. {
  4024. pipe_err = -1;
  4025. }
  4026. break;
  4027. }
  4028. }
  4029. /* spawn the child process */
  4030. if (pipe_err == 0)
  4031. {
  4032. pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0);
  4033. if (pipe_pid == -1)
  4034. {
  4035. pipe_err = -1;
  4036. }
  4037. else
  4038. {
  4039. /* save the PID into the FILE structure
  4040. * NOTE: this implementation doesn't actually
  4041. * take advantage of this, but do it for
  4042. * completeness - AIM Apr01
  4043. */
  4044. for (i = 0; i < file_count; i++)
  4045. p_s[i]->_pid = pipe_pid;
  4046. }
  4047. }
  4048. /* reset standard IO to normal */
  4049. for (i = 0; i < 3; i++)
  4050. {
  4051. dup2(stdio[i].handle, i);
  4052. fcntl(i, F_SETFD, stdio[i].flags);
  4053. close(stdio[i].handle);
  4054. }
  4055. /* if any remnant problems, clean up and bail out */
  4056. if (pipe_err < 0)
  4057. {
  4058. for (i = 0; i < 3; i++)
  4059. {
  4060. close(p_fd[i].rd);
  4061. close(p_fd[i].wr);
  4062. }
  4063. errno = EPIPE;
  4064. return posix_error_with_filename(cmdstring);
  4065. }
  4066. /* build tuple of file objects to return */
  4067. if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL)
  4068. PyFile_SetBufSize(p_f[0], bufsize);
  4069. if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL)
  4070. PyFile_SetBufSize(p_f[1], bufsize);
  4071. if (n == POPEN_3)
  4072. {
  4073. if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL)
  4074. PyFile_SetBufSize(p_f[0], bufsize);
  4075. f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]);
  4076. }
  4077. else
  4078. f = PyTuple_Pack(2, p_f[0], p_f[1]);
  4079. /*
  4080. * Insert the files we've created into the process dictionary
  4081. * all referencing the list with the process handle and the
  4082. * initial number of files (see description below in _PyPclose).
  4083. * Since if _PyPclose later tried to wait on a process when all
  4084. * handles weren't closed, it could create a deadlock with the
  4085. * child, we spend some energy here to try to ensure that we
  4086. * either insert all file handles into the dictionary or none
  4087. * at all. It's a little clumsy with the various popen modes
  4088. * and variable number of files involved.
  4089. */
  4090. if (!_PyPopenProcs)
  4091. {
  4092. _PyPopenProcs = PyDict_New();
  4093. }
  4094. if (_PyPopenProcs)
  4095. {
  4096. PyObject *procObj, *pidObj, *intObj, *fileObj[3];
  4097. int ins_rc[3];
  4098. fileObj[0] = fileObj[1] = fileObj[2] = NULL;
  4099. ins_rc[0] = ins_rc[1] = ins_rc[2] = 0;
  4100. procObj = PyList_New(2);
  4101. pidObj = PyLong_FromPid(pipe_pid);
  4102. intObj = PyInt_FromLong((long) file_count);
  4103. if (procObj && pidObj && intObj)
  4104. {
  4105. PyList_SetItem(procObj, 0, pidObj);
  4106. PyList_SetItem(procObj, 1, intObj);
  4107. fileObj[0] = PyLong_FromVoidPtr(p_s[0]);
  4108. if (fileObj[0])
  4109. {
  4110. ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
  4111. fileObj[0],
  4112. procObj);
  4113. }
  4114. fileObj[1] = PyLong_FromVoidPtr(p_s[1]);
  4115. if (fileObj[1])
  4116. {
  4117. ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
  4118. fileObj[1],
  4119. procObj);
  4120. }
  4121. if (file_count >= 3)
  4122. {
  4123. fileObj[2] = PyLong_FromVoidPtr(p_s[2]);
  4124. if (fileObj[2])
  4125. {
  4126. ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
  4127. fileObj[2],
  4128. procObj);
  4129. }
  4130. }
  4131. if (ins_rc[0] < 0 || !fileObj[0] ||
  4132. ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
  4133. ins_rc[2] < 0 || (file_count > 2 && !fileObj[2]))
  4134. {
  4135. /* Something failed - remove any dictionary
  4136. * entries that did make it.
  4137. */
  4138. if (!ins_rc[0] && fileObj[0])
  4139. {
  4140. PyDict_DelItem(_PyPopenProcs,
  4141. fileObj[0]);
  4142. }
  4143. if (!ins_rc[1] && fileObj[1])
  4144. {
  4145. PyDict_DelItem(_PyPopenProcs,
  4146. fileObj[1]);
  4147. }
  4148. if (!ins_rc[2] && fileObj[2])
  4149. {
  4150. PyDict_DelItem(_PyPopenProcs,
  4151. fileObj[2]);
  4152. }
  4153. }
  4154. }
  4155. /*
  4156. * Clean up our localized references for the dictionary keys
  4157. * and value since PyDict_SetItem will Py_INCREF any copies
  4158. * that got placed in the dictionary.
  4159. */
  4160. Py_XDECREF(procObj);
  4161. Py_XDECREF(fileObj[0]);
  4162. Py_XDECREF(fileObj[1]);
  4163. Py_XDECREF(fileObj[2]);
  4164. }
  4165. /* Child is launched. */
  4166. return f;
  4167. }
  4168. /*
  4169. * Wrapper for fclose() to use for popen* files, so we can retrieve the
  4170. * exit code for the child process and return as a result of the close.
  4171. *
  4172. * This function uses the _PyPopenProcs dictionary in order to map the
  4173. * input file pointer to information about the process that was
  4174. * originally created by the popen* call that created the file pointer.
  4175. * The dictionary uses the file pointer as a key (with one entry
  4176. * inserted for each file returned by the original popen* call) and a
  4177. * single list object as the value for all files from a single call.
  4178. * The list object contains the Win32 process handle at [0], and a file
  4179. * count at [1], which is initialized to the total number of file
  4180. * handles using that list.
  4181. *
  4182. * This function closes whichever handle it is passed, and decrements
  4183. * the file count in the dictionary for the process handle pointed to
  4184. * by this file. On the last close (when the file count reaches zero),
  4185. * this function will wait for the child process and then return its
  4186. * exit code as the result of the close() operation. This permits the
  4187. * files to be closed in any order - it is always the close() of the
  4188. * final handle that will return the exit code.
  4189. *
  4190. * NOTE: This function is currently called with the GIL released.
  4191. * hence we use the GILState API to manage our state.
  4192. */
  4193. static int _PyPclose(FILE *file)
  4194. {
  4195. int result;
  4196. int exit_code;
  4197. pid_t pipe_pid;
  4198. PyObject *procObj, *pidObj, *intObj, *fileObj;
  4199. int file_count;
  4200. #ifdef WITH_THREAD
  4201. PyGILState_STATE state;
  4202. #endif
  4203. /* Close the file handle first, to ensure it can't block the
  4204. * child from exiting if it's the last handle.
  4205. */
  4206. result = fclose(file);
  4207. #ifdef WITH_THREAD
  4208. state = PyGILState_Ensure();
  4209. #endif
  4210. if (_PyPopenProcs)
  4211. {
  4212. if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&
  4213. (procObj = PyDict_GetItem(_PyPopenProcs,
  4214. fileObj)) != NULL &&
  4215. (pidObj = PyList_GetItem(procObj,0)) != NULL &&
  4216. (intObj = PyList_GetItem(procObj,1)) != NULL)
  4217. {
  4218. pipe_pid = (pid_t) PyLong_AsPid(pidObj);
  4219. file_count = (int) PyInt_AsLong(intObj);
  4220. if (file_count > 1)
  4221. {
  4222. /* Still other files referencing process */
  4223. file_count--;
  4224. PyList_SetItem(procObj,1,
  4225. PyInt_FromLong((long) file_count));
  4226. }
  4227. else
  4228. {
  4229. /* Last file for this process */
  4230. if (result != EOF &&
  4231. waitpid(pipe_pid, &exit_code, 0) == pipe_pid)
  4232. {
  4233. /* extract exit status */
  4234. if (WIFEXITED(exit_code))
  4235. {
  4236. result = WEXITSTATUS(exit_code);
  4237. }
  4238. else
  4239. {
  4240. errno = EPIPE;
  4241. result = -1;
  4242. }
  4243. }
  4244. else
  4245. {
  4246. /* Indicate failure - this will cause the file object
  4247. * to raise an I/O error and translate the last
  4248. * error code from errno. We do have a problem with
  4249. * last errors that overlap the normal errno table,
  4250. * but that's a consistent problem with the file object.
  4251. */
  4252. result = -1;
  4253. }
  4254. }
  4255. /* Remove this file pointer from dictionary */
  4256. PyDict_DelItem(_PyPopenProcs, fileObj);
  4257. if (PyDict_Size(_PyPopenProcs) == 0)
  4258. {
  4259. Py_DECREF(_PyPopenProcs);
  4260. _PyPopenProcs = NULL;
  4261. }
  4262. } /* if object retrieval ok */
  4263. Py_XDECREF(fileObj);
  4264. } /* if _PyPopenProcs */
  4265. #ifdef WITH_THREAD
  4266. PyGILState_Release(state);
  4267. #endif
  4268. return result;
  4269. }
  4270. #endif /* PYCC_??? */
  4271. #elif defined(MS_WINDOWS)
  4272. /*
  4273. * Portable 'popen' replacement for Win32.
  4274. *
  4275. * Written by Bill Tutt <billtut@microsoft.com>. Minor tweaks
  4276. * and 2.0 integration by Fredrik Lundh <fredrik@pythonware.com>
  4277. * Return code handling by David Bolen <db3l@fitlinxx.com>.
  4278. */
  4279. #include <malloc.h>
  4280. #include <io.h>
  4281. #include <fcntl.h>
  4282. /* These tell _PyPopen() wether to return 1, 2, or 3 file objects. */
  4283. #define POPEN_1 1
  4284. #define POPEN_2 2
  4285. #define POPEN_3 3
  4286. #define POPEN_4 4
  4287. static PyObject *_PyPopen(char *, int, int);
  4288. static int _PyPclose(FILE *file);
  4289. /*
  4290. * Internal dictionary mapping popen* file pointers to process handles,
  4291. * for use when retrieving the process exit code. See _PyPclose() below
  4292. * for more information on this dictionary's use.
  4293. */
  4294. static PyObject *_PyPopenProcs = NULL;
  4295. /* popen that works from a GUI.
  4296. *
  4297. * The result of this function is a pipe (file) connected to the
  4298. * processes stdin or stdout, depending on the requested mode.
  4299. */
  4300. static PyObject *
  4301. posix_popen(PyObject *self, PyObject *args)
  4302. {
  4303. PyObject *f;
  4304. int tm = 0;
  4305. char *cmdstring;
  4306. char *mode = "r";
  4307. int bufsize = -1;
  4308. if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize))
  4309. return NULL;
  4310. if (*mode == 'r')
  4311. tm = _O_RDONLY;
  4312. else if (*mode != 'w') {
  4313. PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'");
  4314. return NULL;
  4315. } else
  4316. tm = _O_WRONLY;
  4317. if (bufsize != -1) {
  4318. PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1");
  4319. return NULL;
  4320. }
  4321. if (*(mode+1) == 't')
  4322. f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);
  4323. else if (*(mode+1) == 'b')
  4324. f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1);
  4325. else
  4326. f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1);
  4327. return f;
  4328. }
  4329. /* Variation on win32pipe.popen
  4330. *
  4331. * The result of this function is a pipe (file) connected to the
  4332. * process's stdin, and a pipe connected to the process's stdout.
  4333. */
  4334. static PyObject *
  4335. win32_popen2(PyObject *self, PyObject *args)
  4336. {
  4337. PyObject *f;
  4338. int tm=0;
  4339. char *cmdstring;
  4340. char *mode = "t";
  4341. int bufsize = -1;
  4342. if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize))
  4343. return NULL;
  4344. if (*mode == 't')
  4345. tm = _O_TEXT;
  4346. else if (*mode != 'b') {
  4347. PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'");
  4348. return NULL;
  4349. } else
  4350. tm = _O_BINARY;
  4351. if (bufsize != -1) {
  4352. PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1");
  4353. return NULL;
  4354. }
  4355. f = _PyPopen(cmdstring, tm, POPEN_2);
  4356. return f;
  4357. }
  4358. /*
  4359. * Variation on <om win32pipe.popen>
  4360. *
  4361. * The result of this function is 3 pipes - the process's stdin,
  4362. * stdout and stderr
  4363. */
  4364. static PyObject *
  4365. win32_popen3(PyObject *self, PyObject *args)
  4366. {
  4367. PyObject *f;
  4368. int tm = 0;
  4369. char *cmdstring;
  4370. char *mode = "t";
  4371. int bufsize = -1;
  4372. if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize))
  4373. return NULL;
  4374. if (*mode == 't')
  4375. tm = _O_TEXT;
  4376. else if (*mode != 'b') {
  4377. PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'");
  4378. return NULL;
  4379. } else
  4380. tm = _O_BINARY;
  4381. if (bufsize != -1) {
  4382. PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1");
  4383. return NULL;
  4384. }
  4385. f = _PyPopen(cmdstring, tm, POPEN_3);
  4386. return f;
  4387. }
  4388. /*
  4389. * Variation on win32pipe.popen
  4390. *
  4391. * The result of this function is 2 pipes - the processes stdin,
  4392. * and stdout+stderr combined as a single pipe.
  4393. */
  4394. static PyObject *
  4395. win32_popen4(PyObject *self, PyObject *args)
  4396. {
  4397. PyObject *f;
  4398. int tm = 0;
  4399. char *cmdstring;
  4400. char *mode = "t";
  4401. int bufsize = -1;
  4402. if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize))
  4403. return NULL;
  4404. if (*mode == 't')
  4405. tm = _O_TEXT;
  4406. else if (*mode != 'b') {
  4407. PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'");
  4408. return NULL;
  4409. } else
  4410. tm = _O_BINARY;
  4411. if (bufsize != -1) {
  4412. PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1");
  4413. return NULL;
  4414. }
  4415. f = _PyPopen(cmdstring, tm, POPEN_4);
  4416. return f;
  4417. }
  4418. static BOOL
  4419. _PyPopenCreateProcess(char *cmdstring,
  4420. HANDLE hStdin,
  4421. HANDLE hStdout,
  4422. HANDLE hStderr,
  4423. HANDLE *hProcess)
  4424. {
  4425. PROCESS_INFORMATION piProcInfo;
  4426. STARTUPINFO siStartInfo;
  4427. DWORD dwProcessFlags = 0; /* no NEW_CONSOLE by default for Ctrl+C handling */
  4428. char *s1,*s2, *s3 = " /c ";
  4429. const char *szConsoleSpawn = "w9xpopen.exe";
  4430. int i;
  4431. Py_ssize_t x;
  4432. if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) {
  4433. char *comshell;
  4434. s1 = (char *)alloca(i);
  4435. if (!(x = GetEnvironmentVariable("COMSPEC", s1, i)))
  4436. /* x < i, so x fits into an integer */
  4437. return (int)x;
  4438. /* Explicitly check if we are using COMMAND.COM. If we are
  4439. * then use the w9xpopen hack.
  4440. */
  4441. comshell = s1 + x;
  4442. while (comshell >= s1 && *comshell != '\\')
  4443. --comshell;
  4444. ++comshell;
  4445. if (GetVersion() < 0x80000000 &&
  4446. _stricmp(comshell, "command.com") != 0) {
  4447. /* NT/2000 and not using command.com. */
  4448. x = i + strlen(s3) + strlen(cmdstring) + 1;
  4449. s2 = (char *)alloca(x);
  4450. ZeroMemory(s2, x);
  4451. PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring);
  4452. }
  4453. else {
  4454. /*
  4455. * Oh gag, we're on Win9x or using COMMAND.COM. Use
  4456. * the workaround listed in KB: Q150956
  4457. */
  4458. char modulepath[_MAX_PATH];
  4459. struct stat statinfo;
  4460. GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  4461. for (x = i = 0; modulepath[i]; i++)
  4462. if (modulepath[i] == SEP)
  4463. x = i+1;
  4464. modulepath[x] = '\0';
  4465. /* Create the full-name to w9xpopen, so we can test it exists */
  4466. strncat(modulepath,
  4467. szConsoleSpawn,
  4468. (sizeof(modulepath)/sizeof(modulepath[0]))
  4469. -strlen(modulepath));
  4470. if (stat(modulepath, &statinfo) != 0) {
  4471. size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]);
  4472. /* Eeek - file-not-found - possibly an embedding
  4473. situation - see if we can locate it in sys.prefix
  4474. */
  4475. strncpy(modulepath,
  4476. Py_GetExecPrefix(),
  4477. mplen);
  4478. modulepath[mplen-1] = '\0';
  4479. if (modulepath[strlen(modulepath)-1] != '\\')
  4480. strcat(modulepath, "\\");
  4481. strncat(modulepath,
  4482. szConsoleSpawn,
  4483. mplen-strlen(modulepath));
  4484. /* No where else to look - raise an easily identifiable
  4485. error, rather than leaving Windows to report
  4486. "file not found" - as the user is probably blissfully
  4487. unaware this shim EXE is used, and it will confuse them.
  4488. (well, it confused me for a while ;-)
  4489. */
  4490. if (stat(modulepath, &statinfo) != 0) {
  4491. PyErr_Format(PyExc_RuntimeError,
  4492. "Can not locate '%s' which is needed "
  4493. "for popen to work with your shell "
  4494. "or platform.",
  4495. szConsoleSpawn);
  4496. return FALSE;
  4497. }
  4498. }
  4499. x = i + strlen(s3) + strlen(cmdstring) + 1 +
  4500. strlen(modulepath) +
  4501. strlen(szConsoleSpawn) + 1;
  4502. s2 = (char *)alloca(x);
  4503. ZeroMemory(s2, x);
  4504. /* To maintain correct argument passing semantics,
  4505. we pass the command-line as it stands, and allow
  4506. quoting to be applied. w9xpopen.exe will then
  4507. use its argv vector, and re-quote the necessary
  4508. args for the ultimate child process.
  4509. */
  4510. PyOS_snprintf(
  4511. s2, x,
  4512. "\"%s\" %s%s%s",
  4513. modulepath,
  4514. s1,
  4515. s3,
  4516. cmdstring);
  4517. /* Not passing CREATE_NEW_CONSOLE has been known to
  4518. cause random failures on win9x. Specifically a
  4519. dialog:
  4520. "Your program accessed mem currently in use at xxx"
  4521. and a hopeful warning about the stability of your
  4522. system.
  4523. Cost is Ctrl+C won't kill children, but anyone
  4524. who cares can have a go!
  4525. */
  4526. dwProcessFlags |= CREATE_NEW_CONSOLE;
  4527. }
  4528. }
  4529. /* Could be an else here to try cmd.exe / command.com in the path
  4530. Now we'll just error out.. */
  4531. else {
  4532. PyErr_SetString(PyExc_RuntimeError,
  4533. "Cannot locate a COMSPEC environment variable to "
  4534. "use as the shell");
  4535. return FALSE;
  4536. }
  4537. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  4538. siStartInfo.cb = sizeof(STARTUPINFO);
  4539. siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4540. siStartInfo.hStdInput = hStdin;
  4541. siStartInfo.hStdOutput = hStdout;
  4542. siStartInfo.hStdError = hStderr;
  4543. siStartInfo.wShowWindow = SW_HIDE;
  4544. if (CreateProcess(NULL,
  4545. s2,
  4546. NULL,
  4547. NULL,
  4548. TRUE,
  4549. dwProcessFlags,
  4550. NULL,
  4551. NULL,
  4552. &siStartInfo,
  4553. &piProcInfo) ) {
  4554. /* Close the handles now so anyone waiting is woken. */
  4555. CloseHandle(piProcInfo.hThread);
  4556. /* Return process handle */
  4557. *hProcess = piProcInfo.hProcess;
  4558. return TRUE;
  4559. }
  4560. win32_error("CreateProcess", s2);
  4561. return FALSE;
  4562. }
  4563. /* The following code is based off of KB: Q190351 */
  4564. static PyObject *
  4565. _PyPopen(char *cmdstring, int mode, int n)
  4566. {
  4567. HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr,
  4568. hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup,
  4569. hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */
  4570. SECURITY_ATTRIBUTES saAttr;
  4571. BOOL fSuccess;
  4572. int fd1, fd2, fd3;
  4573. FILE *f1, *f2, *f3;
  4574. long file_count;
  4575. PyObject *f;
  4576. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  4577. saAttr.bInheritHandle = TRUE;
  4578. saAttr.lpSecurityDescriptor = NULL;
  4579. if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
  4580. return win32_error("CreatePipe", NULL);
  4581. /* Create new output read handle and the input write handle. Set
  4582. * the inheritance properties to FALSE. Otherwise, the child inherits
  4583. * these handles; resulting in non-closeable handles to the pipes
  4584. * being created. */
  4585. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
  4586. GetCurrentProcess(), &hChildStdinWrDup, 0,
  4587. FALSE,
  4588. DUPLICATE_SAME_ACCESS);
  4589. if (!fSuccess)
  4590. return win32_error("DuplicateHandle", NULL);
  4591. /* Close the inheritable version of ChildStdin
  4592. that we're using. */
  4593. CloseHandle(hChildStdinWr);
  4594. if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
  4595. return win32_error("CreatePipe", NULL);
  4596. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
  4597. GetCurrentProcess(), &hChildStdoutRdDup, 0,
  4598. FALSE, DUPLICATE_SAME_ACCESS);
  4599. if (!fSuccess)
  4600. return win32_error("DuplicateHandle", NULL);
  4601. /* Close the inheritable version of ChildStdout
  4602. that we're using. */
  4603. CloseHandle(hChildStdoutRd);
  4604. if (n != POPEN_4) {
  4605. if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0))
  4606. return win32_error("CreatePipe", NULL);
  4607. fSuccess = DuplicateHandle(GetCurrentProcess(),
  4608. hChildStderrRd,
  4609. GetCurrentProcess(),
  4610. &hChildStderrRdDup, 0,
  4611. FALSE, DUPLICATE_SAME_ACCESS);
  4612. if (!fSuccess)
  4613. return win32_error("DuplicateHandle", NULL);
  4614. /* Close the inheritable version of ChildStdErr that we're using. */
  4615. CloseHandle(hChildStderrRd);
  4616. }
  4617. switch (n) {
  4618. case POPEN_1:
  4619. switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) {
  4620. case _O_WRONLY | _O_TEXT:
  4621. /* Case for writing to child Stdin in text mode. */
  4622. fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
  4623. f1 = _fdopen(fd1, "w");
  4624. f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose);
  4625. PyFile_SetBufSize(f, 0);
  4626. /* We don't care about these pipes anymore, so close them. */
  4627. CloseHandle(hChildStdoutRdDup);
  4628. CloseHandle(hChildStderrRdDup);
  4629. break;
  4630. case _O_RDONLY | _O_TEXT:
  4631. /* Case for reading from child Stdout in text mode. */
  4632. fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
  4633. f1 = _fdopen(fd1, "r");
  4634. f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose);
  4635. PyFile_SetBufSize(f, 0);
  4636. /* We don't care about these pipes anymore, so close them. */
  4637. CloseHandle(hChildStdinWrDup);
  4638. CloseHandle(hChildStderrRdDup);
  4639. break;
  4640. case _O_RDONLY | _O_BINARY:
  4641. /* Case for readinig from child Stdout in binary mode. */
  4642. fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
  4643. f1 = _fdopen(fd1, "rb");
  4644. f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose);
  4645. PyFile_SetBufSize(f, 0);
  4646. /* We don't care about these pipes anymore, so close them. */
  4647. CloseHandle(hChildStdinWrDup);
  4648. CloseHandle(hChildStderrRdDup);
  4649. break;
  4650. case _O_WRONLY | _O_BINARY:
  4651. /* Case for writing to child Stdin in binary mode. */
  4652. fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
  4653. f1 = _fdopen(fd1, "wb");
  4654. f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose);
  4655. PyFile_SetBufSize(f, 0);
  4656. /* We don't care about these pipes anymore, so close them. */
  4657. CloseHandle(hChildStdoutRdDup);
  4658. CloseHandle(hChildStderrRdDup);
  4659. break;
  4660. }
  4661. file_count = 1;
  4662. break;
  4663. case POPEN_2:
  4664. case POPEN_4:
  4665. {
  4666. char *m1, *m2;
  4667. PyObject *p1, *p2;
  4668. if (mode & _O_TEXT) {
  4669. m1 = "r";
  4670. m2 = "w";
  4671. } else {
  4672. m1 = "rb";
  4673. m2 = "wb";
  4674. }
  4675. fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
  4676. f1 = _fdopen(fd1, m2);
  4677. fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
  4678. f2 = _fdopen(fd2, m1);
  4679. p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
  4680. PyFile_SetBufSize(p1, 0);
  4681. p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
  4682. PyFile_SetBufSize(p2, 0);
  4683. if (n != 4)
  4684. CloseHandle(hChildStderrRdDup);
  4685. f = PyTuple_Pack(2,p1,p2);
  4686. Py_XDECREF(p1);
  4687. Py_XDECREF(p2);
  4688. file_count = 2;
  4689. break;
  4690. }
  4691. case POPEN_3:
  4692. {
  4693. char *m1, *m2;
  4694. PyObject *p1, *p2, *p3;
  4695. if (mode & _O_TEXT) {
  4696. m1 = "r";
  4697. m2 = "w";
  4698. } else {
  4699. m1 = "rb";
  4700. m2 = "wb";
  4701. }
  4702. fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode);
  4703. f1 = _fdopen(fd1, m2);
  4704. fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode);
  4705. f2 = _fdopen(fd2, m1);
  4706. fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode);
  4707. f3 = _fdopen(fd3, m1);
  4708. p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
  4709. p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
  4710. p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose);
  4711. PyFile_SetBufSize(p1, 0);
  4712. PyFile_SetBufSize(p2, 0);
  4713. PyFile_SetBufSize(p3, 0);
  4714. f = PyTuple_Pack(3,p1,p2,p3);
  4715. Py_XDECREF(p1);
  4716. Py_XDECREF(p2);
  4717. Py_XDECREF(p3);
  4718. file_count = 3;
  4719. break;
  4720. }
  4721. }
  4722. if (n == POPEN_4) {
  4723. if (!_PyPopenCreateProcess(cmdstring,
  4724. hChildStdinRd,
  4725. hChildStdoutWr,
  4726. hChildStdoutWr,
  4727. &hProcess))
  4728. return NULL;
  4729. }
  4730. else {
  4731. if (!_PyPopenCreateProcess(cmdstring,
  4732. hChildStdinRd,
  4733. hChildStdoutWr,
  4734. hChildStderrWr,
  4735. &hProcess))
  4736. return NULL;
  4737. }
  4738. /*
  4739. * Insert the files we've created into the process dictionary
  4740. * all referencing the list with the process handle and the
  4741. * initial number of files (see description below in _PyPclose).
  4742. * Since if _PyPclose later tried to wait on a process when all
  4743. * handles weren't closed, it could create a deadlock with the
  4744. * child, we spend some energy here to try to ensure that we
  4745. * either insert all file handles into the dictionary or none
  4746. * at all. It's a little clumsy with the various popen modes
  4747. * and variable number of files involved.
  4748. */
  4749. if (!_PyPopenProcs) {
  4750. _PyPopenProcs = PyDict_New();
  4751. }
  4752. if (_PyPopenProcs) {
  4753. PyObject *procObj, *hProcessObj, *intObj, *fileObj[3];
  4754. int ins_rc[3];
  4755. fileObj[0] = fileObj[1] = fileObj[2] = NULL;
  4756. ins_rc[0] = ins_rc[1] = ins_rc[2] = 0;
  4757. procObj = PyList_New(2);
  4758. hProcessObj = PyLong_FromVoidPtr(hProcess);
  4759. intObj = PyInt_FromLong(file_count);
  4760. if (procObj && hProcessObj && intObj) {
  4761. PyList_SetItem(procObj,0,hProcessObj);
  4762. PyList_SetItem(procObj,1,intObj);
  4763. fileObj[0] = PyLong_FromVoidPtr(f1);
  4764. if (fileObj[0]) {
  4765. ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
  4766. fileObj[0],
  4767. procObj);
  4768. }
  4769. if (file_count >= 2) {
  4770. fileObj[1] = PyLong_FromVoidPtr(f2);
  4771. if (fileObj[1]) {
  4772. ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
  4773. fileObj[1],
  4774. procObj);
  4775. }
  4776. }
  4777. if (file_count >= 3) {
  4778. fileObj[2] = PyLong_FromVoidPtr(f3);
  4779. if (fileObj[2]) {
  4780. ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
  4781. fileObj[2],
  4782. procObj);
  4783. }
  4784. }
  4785. if (ins_rc[0] < 0 || !fileObj[0] ||
  4786. ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
  4787. ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) {
  4788. /* Something failed - remove any dictionary
  4789. * entries that did make it.
  4790. */
  4791. if (!ins_rc[0] && fileObj[0]) {
  4792. PyDict_DelItem(_PyPopenProcs,
  4793. fileObj[0]);
  4794. }
  4795. if (!ins_rc[1] && fileObj[1]) {
  4796. PyDict_DelItem(_PyPopenProcs,
  4797. fileObj[1]);
  4798. }
  4799. if (!ins_rc[2] && fileObj[2]) {
  4800. PyDict_DelItem(_PyPopenProcs,
  4801. fileObj[2]);
  4802. }
  4803. }
  4804. }
  4805. /*
  4806. * Clean up our localized references for the dictionary keys
  4807. * and value since PyDict_SetItem will Py_INCREF any copies
  4808. * that got placed in the dictionary.
  4809. */
  4810. Py_XDECREF(procObj);
  4811. Py_XDECREF(fileObj[0]);
  4812. Py_XDECREF(fileObj[1]);
  4813. Py_XDECREF(fileObj[2]);
  4814. }
  4815. /* Child is launched. Close the parents copy of those pipe
  4816. * handles that only the child should have open. You need to
  4817. * make sure that no handles to the write end of the output pipe
  4818. * are maintained in this process or else the pipe will not close
  4819. * when the child process exits and the ReadFile will hang. */
  4820. if (!CloseHandle(hChildStdinRd))
  4821. return win32_error("CloseHandle", NULL);
  4822. if (!CloseHandle(hChildStdoutWr))
  4823. return win32_error("CloseHandle", NULL);
  4824. if ((n != 4) && (!CloseHandle(hChildStderrWr)))
  4825. return win32_error("CloseHandle", NULL);
  4826. return f;
  4827. }
  4828. /*
  4829. * Wrapper for fclose() to use for popen* files, so we can retrieve the
  4830. * exit code for the child process and return as a result of the close.
  4831. *
  4832. * This function uses the _PyPopenProcs dictionary in order to map the
  4833. * input file pointer to information about the process that was
  4834. * originally created by the popen* call that created the file pointer.
  4835. * The dictionary uses the file pointer as a key (with one entry
  4836. * inserted for each file returned by the original popen* call) and a
  4837. * single list object as the value for all files from a single call.
  4838. * The list object contains the Win32 process handle at [0], and a file
  4839. * count at [1], which is initialized to the total number of file
  4840. * handles using that list.
  4841. *
  4842. * This function closes whichever handle it is passed, and decrements
  4843. * the file count in the dictionary for the process handle pointed to
  4844. * by this file. On the last close (when the file count reaches zero),
  4845. * this function will wait for the child process and then return its
  4846. * exit code as the result of the close() operation. This permits the
  4847. * files to be closed in any order - it is always the close() of the
  4848. * final handle that will return the exit code.
  4849. *
  4850. * NOTE: This function is currently called with the GIL released.
  4851. * hence we use the GILState API to manage our state.
  4852. */
  4853. static int _PyPclose(FILE *file)
  4854. {
  4855. int result;
  4856. DWORD exit_code;
  4857. HANDLE hProcess;
  4858. PyObject *procObj, *hProcessObj, *intObj, *fileObj;
  4859. long file_count;
  4860. #ifdef WITH_THREAD
  4861. PyGILState_STATE state;
  4862. #endif
  4863. /* Close the file handle first, to ensure it can't block the
  4864. * child from exiting if it's the last handle.
  4865. */
  4866. result = fclose(file);
  4867. #ifdef WITH_THREAD
  4868. state = PyGILState_Ensure();
  4869. #endif
  4870. if (_PyPopenProcs) {
  4871. if ((fileObj = PyLong_FromVoidPtr(file)) != NULL &&
  4872. (procObj = PyDict_GetItem(_PyPopenProcs,
  4873. fileObj)) != NULL &&
  4874. (hProcessObj = PyList_GetItem(procObj,0)) != NULL &&
  4875. (intObj = PyList_GetItem(procObj,1)) != NULL) {
  4876. hProcess = PyLong_AsVoidPtr(hProcessObj);
  4877. file_count = PyInt_AsLong(intObj);
  4878. if (file_count > 1) {
  4879. /* Still other files referencing process */
  4880. file_count--;
  4881. PyList_SetItem(procObj,1,
  4882. PyInt_FromLong(file_count));
  4883. } else {
  4884. /* Last file for this process */
  4885. if (result != EOF &&
  4886. WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED &&
  4887. GetExitCodeProcess(hProcess, &exit_code)) {
  4888. /* Possible truncation here in 16-bit environments, but
  4889. * real exit codes are just the lower byte in any event.
  4890. */
  4891. result = exit_code;
  4892. } else {
  4893. /* Indicate failure - this will cause the file object
  4894. * to raise an I/O error and translate the last Win32
  4895. * error code from errno. We do have a problem with
  4896. * last errors that overlap the normal errno table,
  4897. * but that's a consistent problem with the file object.
  4898. */
  4899. if (result != EOF) {
  4900. /* If the error wasn't from the fclose(), then
  4901. * set errno for the file object error handling.
  4902. */
  4903. errno = GetLastError();
  4904. }
  4905. result = -1;
  4906. }
  4907. /* Free up the native handle at this point */
  4908. CloseHandle(hProcess);
  4909. }
  4910. /* Remove this file pointer from dictionary */
  4911. PyDict_DelItem(_PyPopenProcs, fileObj);
  4912. if (PyDict_Size(_PyPopenProcs) == 0) {
  4913. Py_DECREF(_PyPopenProcs);
  4914. _PyPopenProcs = NULL;
  4915. }
  4916. } /* if object retrieval ok */
  4917. Py_XDECREF(fileObj);
  4918. } /* if _PyPopenProcs */
  4919. #ifdef WITH_THREAD
  4920. PyGILState_Release(state);
  4921. #endif
  4922. return result;
  4923. }
  4924. #else /* which OS? */
  4925. static PyObject *
  4926. posix_popen(PyObject *self, PyObject *args)
  4927. {
  4928. char *name;
  4929. char *mode = "r";
  4930. int bufsize = -1;
  4931. FILE *fp;
  4932. PyObject *f;
  4933. if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize))
  4934. return NULL;
  4935. /* Strip mode of binary or text modifiers */
  4936. if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0)
  4937. mode = "r";
  4938. else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0)
  4939. mode = "w";
  4940. Py_BEGIN_ALLOW_THREADS
  4941. fp = popen(name, mode);
  4942. Py_END_ALLOW_THREADS
  4943. if (fp == NULL)
  4944. return posix_error();
  4945. f = PyFile_FromFile(fp, name, mode, pclose);
  4946. if (f != NULL)
  4947. PyFile_SetBufSize(f, bufsize);
  4948. return f;
  4949. }
  4950. #endif /* PYOS_??? */
  4951. #endif /* HAVE_POPEN */
  4952. #ifdef HAVE_SETUID
  4953. PyDoc_STRVAR(posix_setuid__doc__,
  4954. "setuid(uid)\n\n\
  4955. Set the current process's user id.");
  4956. static PyObject *
  4957. posix_setuid(PyObject *self, PyObject *args)
  4958. {
  4959. long uid_arg;
  4960. uid_t uid;
  4961. if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg))
  4962. return NULL;
  4963. uid = uid_arg;
  4964. if (uid != uid_arg) {
  4965. PyErr_SetString(PyExc_OverflowError, "user id too big");
  4966. return NULL;
  4967. }
  4968. if (setuid(uid) < 0)
  4969. return posix_error();
  4970. Py_INCREF(Py_None);
  4971. return Py_None;
  4972. }
  4973. #endif /* HAVE_SETUID */
  4974. #ifdef HAVE_SETEUID
  4975. PyDoc_STRVAR(posix_seteuid__doc__,
  4976. "seteuid(uid)\n\n\
  4977. Set the current process's effective user id.");
  4978. static PyObject *
  4979. posix_seteuid (PyObject *self, PyObject *args)
  4980. {
  4981. long euid_arg;
  4982. uid_t euid;
  4983. if (!PyArg_ParseTuple(args, "l", &euid_arg))
  4984. return NULL;
  4985. euid = euid_arg;
  4986. if (euid != euid_arg) {
  4987. PyErr_SetString(PyExc_OverflowError, "user id too big");
  4988. return NULL;
  4989. }
  4990. if (seteuid(euid) < 0) {
  4991. return posix_error();
  4992. } else {
  4993. Py_INCREF(Py_None);
  4994. return Py_None;
  4995. }
  4996. }
  4997. #endif /* HAVE_SETEUID */
  4998. #ifdef HAVE_SETEGID
  4999. PyDoc_STRVAR(posix_setegid__doc__,
  5000. "setegid(gid)\n\n\
  5001. Set the current process's effective group id.");
  5002. static PyObject *
  5003. posix_setegid (PyObject *self, PyObject *args)
  5004. {
  5005. long egid_arg;
  5006. gid_t egid;
  5007. if (!PyArg_ParseTuple(args, "l", &egid_arg))
  5008. return NULL;
  5009. egid = egid_arg;
  5010. if (egid != egid_arg) {
  5011. PyErr_SetString(PyExc_OverflowError, "group id too big");
  5012. return NULL;
  5013. }
  5014. if (setegid(egid) < 0) {
  5015. return posix_error();
  5016. } else {
  5017. Py_INCREF(Py_None);
  5018. return Py_None;
  5019. }
  5020. }
  5021. #endif /* HAVE_SETEGID */
  5022. #ifdef HAVE_SETREUID
  5023. PyDoc_STRVAR(posix_setreuid__doc__,
  5024. "setreuid(ruid, euid)\n\n\
  5025. Set the current process's real and effective user ids.");
  5026. static PyObject *
  5027. posix_setreuid (PyObject *self, PyObject *args)
  5028. {
  5029. long ruid_arg, euid_arg;
  5030. uid_t ruid, euid;
  5031. if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg))
  5032. return NULL;
  5033. ruid = ruid_arg;
  5034. euid = euid_arg;
  5035. if (euid != euid_arg || ruid != ruid_arg) {
  5036. PyErr_SetString(PyExc_OverflowError, "user id too big");
  5037. return NULL;
  5038. }
  5039. if (setreuid(ruid, euid) < 0) {
  5040. return posix_error();
  5041. } else {
  5042. Py_INCREF(Py_None);
  5043. return Py_None;
  5044. }
  5045. }
  5046. #endif /* HAVE_SETREUID */
  5047. #ifdef HAVE_SETREGID
  5048. PyDoc_STRVAR(posix_setregid__doc__,
  5049. "setregid(rgid, egid)\n\n\
  5050. Set the current process's real and effective group ids.");
  5051. static PyObject *
  5052. posix_setregid (PyObject *self, PyObject *args)
  5053. {
  5054. long rgid_arg, egid_arg;
  5055. gid_t rgid, egid;
  5056. if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg))
  5057. return NULL;
  5058. rgid = rgid_arg;
  5059. egid = egid_arg;
  5060. if (egid != egid_arg || rgid != rgid_arg) {
  5061. PyErr_SetString(PyExc_OverflowError, "group id too big");
  5062. return NULL;
  5063. }
  5064. if (setregid(rgid, egid) < 0) {
  5065. return posix_error();
  5066. } else {
  5067. Py_INCREF(Py_None);
  5068. return Py_None;
  5069. }
  5070. }
  5071. #endif /* HAVE_SETREGID */
  5072. #ifdef HAVE_SETGID
  5073. PyDoc_STRVAR(posix_setgid__doc__,
  5074. "setgid(gid)\n\n\
  5075. Set the current process's group id.");
  5076. static PyObject *
  5077. posix_setgid(PyObject *self, PyObject *args)
  5078. {
  5079. long gid_arg;
  5080. gid_t gid;
  5081. if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg))
  5082. return NULL;
  5083. gid = gid_arg;
  5084. if (gid != gid_arg) {
  5085. PyErr_SetString(PyExc_OverflowError, "group id too big");
  5086. return NULL;
  5087. }
  5088. if (setgid(gid) < 0)
  5089. return posix_error();
  5090. Py_INCREF(Py_None);
  5091. return Py_None;
  5092. }
  5093. #endif /* HAVE_SETGID */
  5094. #ifdef HAVE_SETGROUPS
  5095. PyDoc_STRVAR(posix_setgroups__doc__,
  5096. "setgroups(list)\n\n\
  5097. Set the groups of the current process to list.");
  5098. static PyObject *
  5099. posix_setgroups(PyObject *self, PyObject *groups)
  5100. {
  5101. int i, len;
  5102. gid_t grouplist[MAX_GROUPS];
  5103. if (!PySequence_Check(groups)) {
  5104. PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
  5105. return NULL;
  5106. }
  5107. len = PySequence_Size(groups);
  5108. if (len > MAX_GROUPS) {
  5109. PyErr_SetString(PyExc_ValueError, "too many groups");
  5110. return NULL;
  5111. }
  5112. for(i = 0; i < len; i++) {
  5113. PyObject *elem;
  5114. elem = PySequence_GetItem(groups, i);
  5115. if (!elem)
  5116. return NULL;
  5117. if (!PyInt_Check(elem)) {
  5118. if (!PyLong_Check(elem)) {
  5119. PyErr_SetString(PyExc_TypeError,
  5120. "groups must be integers");
  5121. Py_DECREF(elem);
  5122. return NULL;
  5123. } else {
  5124. unsigned long x = PyLong_AsUnsignedLong(elem);
  5125. if (PyErr_Occurred()) {
  5126. PyErr_SetString(PyExc_TypeError,
  5127. "group id too big");
  5128. Py_DECREF(elem);
  5129. return NULL;
  5130. }
  5131. grouplist[i] = x;
  5132. /* read back to see if it fits in gid_t */
  5133. if (grouplist[i] != x) {
  5134. PyErr_SetString(PyExc_TypeError,
  5135. "group id too big");
  5136. Py_DECREF(elem);
  5137. return NULL;
  5138. }
  5139. }
  5140. } else {
  5141. long x = PyInt_AsLong(elem);
  5142. grouplist[i] = x;
  5143. if (grouplist[i] != x) {
  5144. PyErr_SetString(PyExc_TypeError,
  5145. "group id too big");
  5146. Py_DECREF(elem);
  5147. return NULL;
  5148. }
  5149. }
  5150. Py_DECREF(elem);
  5151. }
  5152. if (setgroups(len, grouplist) < 0)
  5153. return posix_error();
  5154. Py_INCREF(Py_None);
  5155. return Py_None;
  5156. }
  5157. #endif /* HAVE_SETGROUPS */
  5158. #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
  5159. static PyObject *
  5160. wait_helper(pid_t pid, int status, struct rusage *ru)
  5161. {
  5162. PyObject *result;
  5163. static PyObject *struct_rusage;
  5164. if (pid == -1)
  5165. return posix_error();
  5166. if (struct_rusage == NULL) {
  5167. PyObject *m = PyImport_ImportModuleNoBlock("resource");
  5168. if (m == NULL)
  5169. return NULL;
  5170. struct_rusage = PyObject_GetAttrString(m, "struct_rusage");
  5171. Py_DECREF(m);
  5172. if (struct_rusage == NULL)
  5173. return NULL;
  5174. }
  5175. /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
  5176. result = PyStructSequence_New((PyTypeObject*) struct_rusage);
  5177. if (!result)
  5178. return NULL;
  5179. #ifndef doubletime
  5180. #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
  5181. #endif
  5182. PyStructSequence_SET_ITEM(result, 0,
  5183. PyFloat_FromDouble(doubletime(ru->ru_utime)));
  5184. PyStructSequence_SET_ITEM(result, 1,
  5185. PyFloat_FromDouble(doubletime(ru->ru_stime)));
  5186. #define SET_INT(result, index, value)\
  5187. PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value))
  5188. SET_INT(result, 2, ru->ru_maxrss);
  5189. SET_INT(result, 3, ru->ru_ixrss);
  5190. SET_INT(result, 4, ru->ru_idrss);
  5191. SET_INT(result, 5, ru->ru_isrss);
  5192. SET_INT(result, 6, ru->ru_minflt);
  5193. SET_INT(result, 7, ru->ru_majflt);
  5194. SET_INT(result, 8, ru->ru_nswap);
  5195. SET_INT(result, 9, ru->ru_inblock);
  5196. SET_INT(result, 10, ru->ru_oublock);
  5197. SET_INT(result, 11, ru->ru_msgsnd);
  5198. SET_INT(result, 12, ru->ru_msgrcv);
  5199. SET_INT(result, 13, ru->ru_nsignals);
  5200. SET_INT(result, 14, ru->ru_nvcsw);
  5201. SET_INT(result, 15, ru->ru_nivcsw);
  5202. #undef SET_INT
  5203. if (PyErr_Occurred()) {
  5204. Py_DECREF(result);
  5205. return NULL;
  5206. }
  5207. return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
  5208. }
  5209. #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
  5210. #ifdef HAVE_WAIT3
  5211. PyDoc_STRVAR(posix_wait3__doc__,
  5212. "wait3(options) -> (pid, status, rusage)\n\n\
  5213. Wait for completion of a child process.");
  5214. static PyObject *
  5215. posix_wait3(PyObject *self, PyObject *args)
  5216. {
  5217. pid_t pid;
  5218. int options;
  5219. struct rusage ru;
  5220. WAIT_TYPE status;
  5221. WAIT_STATUS_INT(status) = 0;
  5222. if (!PyArg_ParseTuple(args, "i:wait3", &options))
  5223. return NULL;
  5224. Py_BEGIN_ALLOW_THREADS
  5225. pid = wait3(&status, options, &ru);
  5226. Py_END_ALLOW_THREADS
  5227. return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
  5228. }
  5229. #endif /* HAVE_WAIT3 */
  5230. #ifdef HAVE_WAIT4
  5231. PyDoc_STRVAR(posix_wait4__doc__,
  5232. "wait4(pid, options) -> (pid, status, rusage)\n\n\
  5233. Wait for completion of a given child process.");
  5234. static PyObject *
  5235. posix_wait4(PyObject *self, PyObject *args)
  5236. {
  5237. pid_t pid;
  5238. int options;
  5239. struct rusage ru;
  5240. WAIT_TYPE status;
  5241. WAIT_STATUS_INT(status) = 0;
  5242. if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options))
  5243. return NULL;
  5244. Py_BEGIN_ALLOW_THREADS
  5245. pid = wait4(pid, &status, options, &ru);
  5246. Py_END_ALLOW_THREADS
  5247. return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
  5248. }
  5249. #endif /* HAVE_WAIT4 */
  5250. #ifdef HAVE_WAITPID
  5251. PyDoc_STRVAR(posix_waitpid__doc__,
  5252. "waitpid(pid, options) -> (pid, status)\n\n\
  5253. Wait for completion of a given child process.");
  5254. static PyObject *
  5255. posix_waitpid(PyObject *self, PyObject *args)
  5256. {
  5257. pid_t pid;
  5258. int options;
  5259. WAIT_TYPE status;
  5260. WAIT_STATUS_INT(status) = 0;
  5261. if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))
  5262. return NULL;
  5263. Py_BEGIN_ALLOW_THREADS
  5264. pid = waitpid(pid, &status, options);
  5265. Py_END_ALLOW_THREADS
  5266. if (pid == -1)
  5267. return posix_error();
  5268. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  5269. }
  5270. #elif defined(HAVE_CWAIT)
  5271. /* MS C has a variant of waitpid() that's usable for most purposes. */
  5272. PyDoc_STRVAR(posix_waitpid__doc__,
  5273. "waitpid(pid, options) -> (pid, status << 8)\n\n"
  5274. "Wait for completion of a given process. options is ignored on Windows.");
  5275. static PyObject *
  5276. posix_waitpid(PyObject *self, PyObject *args)
  5277. {
  5278. Py_intptr_t pid;
  5279. int status, options;
  5280. if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options))
  5281. return NULL;
  5282. Py_BEGIN_ALLOW_THREADS
  5283. pid = _cwait(&status, pid, options);
  5284. Py_END_ALLOW_THREADS
  5285. if (pid == -1)
  5286. return posix_error();
  5287. /* shift the status left a byte so this is more like the POSIX waitpid */
  5288. return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8);
  5289. }
  5290. #endif /* HAVE_WAITPID || HAVE_CWAIT */
  5291. #ifdef HAVE_WAIT
  5292. PyDoc_STRVAR(posix_wait__doc__,
  5293. "wait() -> (pid, status)\n\n\
  5294. Wait for completion of a child process.");
  5295. static PyObject *
  5296. posix_wait(PyObject *self, PyObject *noargs)
  5297. {
  5298. pid_t pid;
  5299. WAIT_TYPE status;
  5300. WAIT_STATUS_INT(status) = 0;
  5301. Py_BEGIN_ALLOW_THREADS
  5302. pid = wait(&status);
  5303. Py_END_ALLOW_THREADS
  5304. if (pid == -1)
  5305. return posix_error();
  5306. return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
  5307. }
  5308. #endif
  5309. PyDoc_STRVAR(posix_lstat__doc__,
  5310. "lstat(path) -> stat result\n\n\
  5311. Like stat(path), but do not follow symbolic links.");
  5312. static PyObject *
  5313. posix_lstat(PyObject *self, PyObject *args)
  5314. {
  5315. #ifdef HAVE_LSTAT
  5316. return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL);
  5317. #else /* !HAVE_LSTAT */
  5318. #ifdef MS_WINDOWS
  5319. return posix_do_stat(self, args, "et:lstat", STAT, "U:lstat", win32_wstat);
  5320. #else
  5321. return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL);
  5322. #endif
  5323. #endif /* !HAVE_LSTAT */
  5324. }
  5325. #ifdef HAVE_READLINK
  5326. PyDoc_STRVAR(posix_readlink__doc__,
  5327. "readlink(path) -> path\n\n\
  5328. Return a string representing the path to which the symbolic link points.");
  5329. static PyObject *
  5330. posix_readlink(PyObject *self, PyObject *args)
  5331. {
  5332. PyObject* v;
  5333. char buf[MAXPATHLEN];
  5334. char *path;
  5335. int n;
  5336. #ifdef Py_USING_UNICODE
  5337. int arg_is_unicode = 0;
  5338. #endif
  5339. if (!PyArg_ParseTuple(args, "et:readlink",
  5340. Py_FileSystemDefaultEncoding, &path))
  5341. return NULL;
  5342. #ifdef Py_USING_UNICODE
  5343. v = PySequence_GetItem(args, 0);
  5344. if (v == NULL) {
  5345. PyMem_Free(path);
  5346. return NULL;
  5347. }
  5348. if (PyUnicode_Check(v)) {
  5349. arg_is_unicode = 1;
  5350. }
  5351. Py_DECREF(v);
  5352. #endif
  5353. Py_BEGIN_ALLOW_THREADS
  5354. n = readlink(path, buf, (int) sizeof buf);
  5355. Py_END_ALLOW_THREADS
  5356. if (n < 0)
  5357. return posix_error_with_allocated_filename(path);
  5358. PyMem_Free(path);
  5359. v = PyString_FromStringAndSize(buf, n);
  5360. #ifdef Py_USING_UNICODE
  5361. if (arg_is_unicode) {
  5362. PyObject *w;
  5363. w = PyUnicode_FromEncodedObject(v,
  5364. Py_FileSystemDefaultEncoding,
  5365. "strict");
  5366. if (w != NULL) {
  5367. Py_DECREF(v);
  5368. v = w;
  5369. }
  5370. else {
  5371. /* fall back to the original byte string, as
  5372. discussed in patch #683592 */
  5373. PyErr_Clear();
  5374. }
  5375. }
  5376. #endif
  5377. return v;
  5378. }
  5379. #endif /* HAVE_READLINK */
  5380. #ifdef HAVE_SYMLINK
  5381. PyDoc_STRVAR(posix_symlink__doc__,
  5382. "symlink(src, dst)\n\n\
  5383. Create a symbolic link pointing to src named dst.");
  5384. static PyObject *
  5385. posix_symlink(PyObject *self, PyObject *args)
  5386. {
  5387. return posix_2str(args, "etet:symlink", symlink);
  5388. }
  5389. #endif /* HAVE_SYMLINK */
  5390. #ifdef HAVE_TIMES
  5391. #if defined(PYCC_VACPP) && defined(PYOS_OS2)
  5392. static long
  5393. system_uptime(void)
  5394. {
  5395. ULONG value = 0;
  5396. Py_BEGIN_ALLOW_THREADS
  5397. DosQuerySysInfo(QSV_MS_COUNT, QSV_MS_COUNT, &value, sizeof(value));
  5398. Py_END_ALLOW_THREADS
  5399. return value;
  5400. }
  5401. static PyObject *
  5402. posix_times(PyObject *self, PyObject *noargs)
  5403. {
  5404. /* Currently Only Uptime is Provided -- Others Later */
  5405. return Py_BuildValue("ddddd",
  5406. (double)0 /* t.tms_utime / HZ */,
  5407. (double)0 /* t.tms_stime / HZ */,
  5408. (double)0 /* t.tms_cutime / HZ */,
  5409. (double)0 /* t.tms_cstime / HZ */,
  5410. (double)system_uptime() / 1000);
  5411. }
  5412. #else /* not OS2 */
  5413. #define NEED_TICKS_PER_SECOND
  5414. static long ticks_per_second = -1;
  5415. static PyObject *
  5416. posix_times(PyObject *self, PyObject *noargs)
  5417. {
  5418. struct tms t;
  5419. clock_t c;
  5420. errno = 0;
  5421. c = times(&t);
  5422. if (c == (clock_t) -1)
  5423. return posix_error();
  5424. return Py_BuildValue("ddddd",
  5425. (double)t.tms_utime / ticks_per_second,
  5426. (double)t.tms_stime / ticks_per_second,
  5427. (double)t.tms_cutime / ticks_per_second,
  5428. (double)t.tms_cstime / ticks_per_second,
  5429. (double)c / ticks_per_second);
  5430. }
  5431. #endif /* not OS2 */
  5432. #endif /* HAVE_TIMES */
  5433. #ifdef MS_WINDOWS
  5434. #define HAVE_TIMES /* so the method table will pick it up */
  5435. static PyObject *
  5436. posix_times(PyObject *self, PyObject *noargs)
  5437. {
  5438. FILETIME create, exit, kernel, user;
  5439. HANDLE hProc;
  5440. hProc = GetCurrentProcess();
  5441. GetProcessTimes(hProc, &create, &exit, &kernel, &user);
  5442. /* The fields of a FILETIME structure are the hi and lo part
  5443. of a 64-bit value expressed in 100 nanosecond units.
  5444. 1e7 is one second in such units; 1e-7 the inverse.
  5445. 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
  5446. */
  5447. return Py_BuildValue(
  5448. "ddddd",
  5449. (double)(user.dwHighDateTime*429.4967296 +
  5450. user.dwLowDateTime*1e-7),
  5451. (double)(kernel.dwHighDateTime*429.4967296 +
  5452. kernel.dwLowDateTime*1e-7),
  5453. (double)0,
  5454. (double)0,
  5455. (double)0);
  5456. }
  5457. #endif /* MS_WINDOWS */
  5458. #ifdef HAVE_TIMES
  5459. PyDoc_STRVAR(posix_times__doc__,
  5460. "times() -> (utime, stime, cutime, cstime, elapsed_time)\n\n\
  5461. Return a tuple of floating point numbers indicating process times.");
  5462. #endif
  5463. #ifdef HAVE_GETSID
  5464. PyDoc_STRVAR(posix_getsid__doc__,
  5465. "getsid(pid) -> sid\n\n\
  5466. Call the system call getsid().");
  5467. static PyObject *
  5468. posix_getsid(PyObject *self, PyObject *args)
  5469. {
  5470. pid_t pid;
  5471. int sid;
  5472. if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid))
  5473. return NULL;
  5474. sid = getsid(pid);
  5475. if (sid < 0)
  5476. return posix_error();
  5477. return PyInt_FromLong((long)sid);
  5478. }
  5479. #endif /* HAVE_GETSID */
  5480. #ifdef HAVE_SETSID
  5481. PyDoc_STRVAR(posix_setsid__doc__,
  5482. "setsid()\n\n\
  5483. Call the system call setsid().");
  5484. static PyObject *
  5485. posix_setsid(PyObject *self, PyObject *noargs)
  5486. {
  5487. if (setsid() < 0)
  5488. return posix_error();
  5489. Py_INCREF(Py_None);
  5490. return Py_None;
  5491. }
  5492. #endif /* HAVE_SETSID */
  5493. #ifdef HAVE_SETPGID
  5494. PyDoc_STRVAR(posix_setpgid__doc__,
  5495. "setpgid(pid, pgrp)\n\n\
  5496. Call the system call setpgid().");
  5497. static PyObject *
  5498. posix_setpgid(PyObject *self, PyObject *args)
  5499. {
  5500. pid_t pid;
  5501. int pgrp;
  5502. if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp))
  5503. return NULL;
  5504. if (setpgid(pid, pgrp) < 0)
  5505. return posix_error();
  5506. Py_INCREF(Py_None);
  5507. return Py_None;
  5508. }
  5509. #endif /* HAVE_SETPGID */
  5510. #ifdef HAVE_TCGETPGRP
  5511. PyDoc_STRVAR(posix_tcgetpgrp__doc__,
  5512. "tcgetpgrp(fd) -> pgid\n\n\
  5513. Return the process group associated with the terminal given by a fd.");
  5514. static PyObject *
  5515. posix_tcgetpgrp(PyObject *self, PyObject *args)
  5516. {
  5517. int fd;
  5518. pid_t pgid;
  5519. if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd))
  5520. return NULL;
  5521. pgid = tcgetpgrp(fd);
  5522. if (pgid < 0)
  5523. return posix_error();
  5524. return PyLong_FromPid(pgid);
  5525. }
  5526. #endif /* HAVE_TCGETPGRP */
  5527. #ifdef HAVE_TCSETPGRP
  5528. PyDoc_STRVAR(posix_tcsetpgrp__doc__,
  5529. "tcsetpgrp(fd, pgid)\n\n\
  5530. Set the process group associated with the terminal given by a fd.");
  5531. static PyObject *
  5532. posix_tcsetpgrp(PyObject *self, PyObject *args)
  5533. {
  5534. int fd;
  5535. pid_t pgid;
  5536. if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid))
  5537. return NULL;
  5538. if (tcsetpgrp(fd, pgid) < 0)
  5539. return posix_error();
  5540. Py_INCREF(Py_None);
  5541. return Py_None;
  5542. }
  5543. #endif /* HAVE_TCSETPGRP */
  5544. /* Functions acting on file descriptors */
  5545. PyDoc_STRVAR(posix_open__doc__,
  5546. "open(filename, flag [, mode=0777]) -> fd\n\n\
  5547. Open a file (for low level IO).");
  5548. static PyObject *
  5549. posix_open(PyObject *self, PyObject *args)
  5550. {
  5551. char *file = NULL;
  5552. int flag;
  5553. int mode = 0777;
  5554. int fd;
  5555. #ifdef MS_WINDOWS
  5556. if (unicode_file_names()) {
  5557. PyUnicodeObject *po;
  5558. if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) {
  5559. Py_BEGIN_ALLOW_THREADS
  5560. /* PyUnicode_AS_UNICODE OK without thread
  5561. lock as it is a simple dereference. */
  5562. fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode);
  5563. Py_END_ALLOW_THREADS
  5564. if (fd < 0)
  5565. return posix_error();
  5566. return PyInt_FromLong((long)fd);
  5567. }
  5568. /* Drop the argument parsing error as narrow strings
  5569. are also valid. */
  5570. PyErr_Clear();
  5571. }
  5572. #endif
  5573. if (!PyArg_ParseTuple(args, "eti|i",
  5574. Py_FileSystemDefaultEncoding, &file,
  5575. &flag, &mode))
  5576. return NULL;
  5577. Py_BEGIN_ALLOW_THREADS
  5578. fd = open(file, flag, mode);
  5579. Py_END_ALLOW_THREADS
  5580. if (fd < 0)
  5581. return posix_error_with_allocated_filename(file);
  5582. PyMem_Free(file);
  5583. return PyInt_FromLong((long)fd);
  5584. }
  5585. PyDoc_STRVAR(posix_close__doc__,
  5586. "close(fd)\n\n\
  5587. Close a file descriptor (for low level IO).");
  5588. static PyObject *
  5589. posix_close(PyObject *self, PyObject *args)
  5590. {
  5591. int fd, res;
  5592. if (!PyArg_ParseTuple(args, "i:close", &fd))
  5593. return NULL;
  5594. Py_BEGIN_ALLOW_THREADS
  5595. res = close(fd);
  5596. Py_END_ALLOW_THREADS
  5597. if (res < 0)
  5598. return posix_error();
  5599. Py_INCREF(Py_None);
  5600. return Py_None;
  5601. }
  5602. PyDoc_STRVAR(posix_closerange__doc__,
  5603. "closerange(fd_low, fd_high)\n\n\
  5604. Closes all file descriptors in [fd_low, fd_high), ignoring errors.");
  5605. static PyObject *
  5606. posix_closerange(PyObject *self, PyObject *args)
  5607. {
  5608. int fd_from, fd_to, i;
  5609. if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to))
  5610. return NULL;
  5611. Py_BEGIN_ALLOW_THREADS
  5612. for (i = fd_from; i < fd_to; i++)
  5613. close(i);
  5614. Py_END_ALLOW_THREADS
  5615. Py_RETURN_NONE;
  5616. }
  5617. PyDoc_STRVAR(posix_dup__doc__,
  5618. "dup(fd) -> fd2\n\n\
  5619. Return a duplicate of a file descriptor.");
  5620. static PyObject *
  5621. posix_dup(PyObject *self, PyObject *args)
  5622. {
  5623. int fd;
  5624. if (!PyArg_ParseTuple(args, "i:dup", &fd))
  5625. return NULL;
  5626. Py_BEGIN_ALLOW_THREADS
  5627. fd = dup(fd);
  5628. Py_END_ALLOW_THREADS
  5629. if (fd < 0)
  5630. return posix_error();
  5631. return PyInt_FromLong((long)fd);
  5632. }
  5633. PyDoc_STRVAR(posix_dup2__doc__,
  5634. "dup2(old_fd, new_fd)\n\n\
  5635. Duplicate file descriptor.");
  5636. static PyObject *
  5637. posix_dup2(PyObject *self, PyObject *args)
  5638. {
  5639. int fd, fd2, res;
  5640. if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2))
  5641. return NULL;
  5642. Py_BEGIN_ALLOW_THREADS
  5643. res = dup2(fd, fd2);
  5644. Py_END_ALLOW_THREADS
  5645. if (res < 0)
  5646. return posix_error();
  5647. Py_INCREF(Py_None);
  5648. return Py_None;
  5649. }
  5650. PyDoc_STRVAR(posix_lseek__doc__,
  5651. "lseek(fd, pos, how) -> newpos\n\n\
  5652. Set the current position of a file descriptor.");
  5653. static PyObject *
  5654. posix_lseek(PyObject *self, PyObject *args)
  5655. {
  5656. int fd, how;
  5657. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  5658. PY_LONG_LONG pos, res;
  5659. #else
  5660. off_t pos, res;
  5661. #endif
  5662. PyObject *posobj;
  5663. if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how))
  5664. return NULL;
  5665. #ifdef SEEK_SET
  5666. /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
  5667. switch (how) {
  5668. case 0: how = SEEK_SET; break;
  5669. case 1: how = SEEK_CUR; break;
  5670. case 2: how = SEEK_END; break;
  5671. }
  5672. #endif /* SEEK_END */
  5673. #if !defined(HAVE_LARGEFILE_SUPPORT)
  5674. pos = PyInt_AsLong(posobj);
  5675. #else
  5676. pos = PyLong_Check(posobj) ?
  5677. PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
  5678. #endif
  5679. if (PyErr_Occurred())
  5680. return NULL;
  5681. Py_BEGIN_ALLOW_THREADS
  5682. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  5683. res = _lseeki64(fd, pos, how);
  5684. #else
  5685. res = lseek(fd, pos, how);
  5686. #endif
  5687. Py_END_ALLOW_THREADS
  5688. if (res < 0)
  5689. return posix_error();
  5690. #if !defined(HAVE_LARGEFILE_SUPPORT)
  5691. return PyInt_FromLong(res);
  5692. #else
  5693. return PyLong_FromLongLong(res);
  5694. #endif
  5695. }
  5696. PyDoc_STRVAR(posix_read__doc__,
  5697. "read(fd, buffersize) -> string\n\n\
  5698. Read a file descriptor.");
  5699. static PyObject *
  5700. posix_read(PyObject *self, PyObject *args)
  5701. {
  5702. int fd, size, n;
  5703. PyObject *buffer;
  5704. if (!PyArg_ParseTuple(args, "ii:read", &fd, &size))
  5705. return NULL;
  5706. if (size < 0) {
  5707. errno = EINVAL;
  5708. return posix_error();
  5709. }
  5710. buffer = PyString_FromStringAndSize((char *)NULL, size);
  5711. if (buffer == NULL)
  5712. return NULL;
  5713. Py_BEGIN_ALLOW_THREADS
  5714. n = read(fd, PyString_AsString(buffer), size);
  5715. Py_END_ALLOW_THREADS
  5716. if (n < 0) {
  5717. Py_DECREF(buffer);
  5718. return posix_error();
  5719. }
  5720. if (n != size)
  5721. _PyString_Resize(&buffer, n);
  5722. return buffer;
  5723. }
  5724. PyDoc_STRVAR(posix_write__doc__,
  5725. "write(fd, string) -> byteswritten\n\n\
  5726. Write a string to a file descriptor.");
  5727. static PyObject *
  5728. posix_write(PyObject *self, PyObject *args)
  5729. {
  5730. Py_buffer pbuf;
  5731. int fd;
  5732. Py_ssize_t size;
  5733. if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf))
  5734. return NULL;
  5735. Py_BEGIN_ALLOW_THREADS
  5736. size = write(fd, pbuf.buf, (size_t)pbuf.len);
  5737. Py_END_ALLOW_THREADS
  5738. PyBuffer_Release(&pbuf);
  5739. if (size < 0)
  5740. return posix_error();
  5741. return PyInt_FromSsize_t(size);
  5742. }
  5743. PyDoc_STRVAR(posix_fstat__doc__,
  5744. "fstat(fd) -> stat result\n\n\
  5745. Like stat(), but for an open file descriptor.");
  5746. static PyObject *
  5747. posix_fstat(PyObject *self, PyObject *args)
  5748. {
  5749. int fd;
  5750. STRUCT_STAT st;
  5751. int res;
  5752. if (!PyArg_ParseTuple(args, "i:fstat", &fd))
  5753. return NULL;
  5754. #ifdef __VMS
  5755. /* on OpenVMS we must ensure that all bytes are written to the file */
  5756. fsync(fd);
  5757. #endif
  5758. Py_BEGIN_ALLOW_THREADS
  5759. res = FSTAT(fd, &st);
  5760. Py_END_ALLOW_THREADS
  5761. if (res != 0) {
  5762. #ifdef MS_WINDOWS
  5763. return win32_error("fstat", NULL);
  5764. #else
  5765. return posix_error();
  5766. #endif
  5767. }
  5768. return _pystat_fromstructstat(&st);
  5769. }
  5770. PyDoc_STRVAR(posix_fdopen__doc__,
  5771. "fdopen(fd [, mode='r' [, bufsize]]) -> file_object\n\n\
  5772. Return an open file object connected to a file descriptor.");
  5773. static PyObject *
  5774. posix_fdopen(PyObject *self, PyObject *args)
  5775. {
  5776. int fd;
  5777. char *orgmode = "r";
  5778. int bufsize = -1;
  5779. FILE *fp;
  5780. PyObject *f;
  5781. char *mode;
  5782. if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize))
  5783. return NULL;
  5784. /* Sanitize mode. See fileobject.c */
  5785. mode = PyMem_MALLOC(strlen(orgmode)+3);
  5786. if (!mode) {
  5787. PyErr_NoMemory();
  5788. return NULL;
  5789. }
  5790. strcpy(mode, orgmode);
  5791. if (_PyFile_SanitizeMode(mode)) {
  5792. PyMem_FREE(mode);
  5793. return NULL;
  5794. }
  5795. Py_BEGIN_ALLOW_THREADS
  5796. #if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H)
  5797. if (mode[0] == 'a') {
  5798. /* try to make sure the O_APPEND flag is set */
  5799. int flags;
  5800. flags = fcntl(fd, F_GETFL);
  5801. if (flags != -1)
  5802. fcntl(fd, F_SETFL, flags | O_APPEND);
  5803. fp = fdopen(fd, mode);
  5804. if (fp == NULL && flags != -1)
  5805. /* restore old mode if fdopen failed */
  5806. fcntl(fd, F_SETFL, flags);
  5807. } else {
  5808. fp = fdopen(fd, mode);
  5809. }
  5810. #else
  5811. fp = fdopen(fd, mode);
  5812. #endif
  5813. Py_END_ALLOW_THREADS
  5814. PyMem_FREE(mode);
  5815. if (fp == NULL)
  5816. return posix_error();
  5817. f = PyFile_FromFile(fp, "<fdopen>", orgmode, fclose);
  5818. if (f != NULL)
  5819. PyFile_SetBufSize(f, bufsize);
  5820. return f;
  5821. }
  5822. PyDoc_STRVAR(posix_isatty__doc__,
  5823. "isatty(fd) -> bool\n\n\
  5824. Return True if the file descriptor 'fd' is an open file descriptor\n\
  5825. connected to the slave end of a terminal.");
  5826. static PyObject *
  5827. posix_isatty(PyObject *self, PyObject *args)
  5828. {
  5829. int fd;
  5830. if (!PyArg_ParseTuple(args, "i:isatty", &fd))
  5831. return NULL;
  5832. return PyBool_FromLong(isatty(fd));
  5833. }
  5834. #ifdef HAVE_PIPE
  5835. PyDoc_STRVAR(posix_pipe__doc__,
  5836. "pipe() -> (read_end, write_end)\n\n\
  5837. Create a pipe.");
  5838. static PyObject *
  5839. posix_pipe(PyObject *self, PyObject *noargs)
  5840. {
  5841. #if defined(PYOS_OS2)
  5842. HFILE read, write;
  5843. APIRET rc;
  5844. Py_BEGIN_ALLOW_THREADS
  5845. rc = DosCreatePipe( &read, &write, 4096);
  5846. Py_END_ALLOW_THREADS
  5847. if (rc != NO_ERROR)
  5848. return os2_error(rc);
  5849. return Py_BuildValue("(ii)", read, write);
  5850. #else
  5851. #if !defined(MS_WINDOWS)
  5852. int fds[2];
  5853. int res;
  5854. Py_BEGIN_ALLOW_THREADS
  5855. res = pipe(fds);
  5856. Py_END_ALLOW_THREADS
  5857. if (res != 0)
  5858. return posix_error();
  5859. return Py_BuildValue("(ii)", fds[0], fds[1]);
  5860. #else /* MS_WINDOWS */
  5861. HANDLE read, write;
  5862. int read_fd, write_fd;
  5863. BOOL ok;
  5864. Py_BEGIN_ALLOW_THREADS
  5865. ok = CreatePipe(&read, &write, NULL, 0);
  5866. Py_END_ALLOW_THREADS
  5867. if (!ok)
  5868. return win32_error("CreatePipe", NULL);
  5869. read_fd = _open_osfhandle((Py_intptr_t)read, 0);
  5870. write_fd = _open_osfhandle((Py_intptr_t)write, 1);
  5871. return Py_BuildValue("(ii)", read_fd, write_fd);
  5872. #endif /* MS_WINDOWS */
  5873. #endif
  5874. }
  5875. #endif /* HAVE_PIPE */
  5876. #ifdef HAVE_MKFIFO
  5877. PyDoc_STRVAR(posix_mkfifo__doc__,
  5878. "mkfifo(filename [, mode=0666])\n\n\
  5879. Create a FIFO (a POSIX named pipe).");
  5880. static PyObject *
  5881. posix_mkfifo(PyObject *self, PyObject *args)
  5882. {
  5883. char *filename;
  5884. int mode = 0666;
  5885. int res;
  5886. if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode))
  5887. return NULL;
  5888. Py_BEGIN_ALLOW_THREADS
  5889. res = mkfifo(filename, mode);
  5890. Py_END_ALLOW_THREADS
  5891. if (res < 0)
  5892. return posix_error();
  5893. Py_INCREF(Py_None);
  5894. return Py_None;
  5895. }
  5896. #endif
  5897. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  5898. PyDoc_STRVAR(posix_mknod__doc__,
  5899. "mknod(filename [, mode=0600, device])\n\n\
  5900. Create a filesystem node (file, device special file or named pipe)\n\
  5901. named filename. mode specifies both the permissions to use and the\n\
  5902. type of node to be created, being combined (bitwise OR) with one of\n\
  5903. S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. For S_IFCHR and S_IFBLK,\n\
  5904. device defines the newly created device special file (probably using\n\
  5905. os.makedev()), otherwise it is ignored.");
  5906. static PyObject *
  5907. posix_mknod(PyObject *self, PyObject *args)
  5908. {
  5909. char *filename;
  5910. int mode = 0600;
  5911. int device = 0;
  5912. int res;
  5913. if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device))
  5914. return NULL;
  5915. Py_BEGIN_ALLOW_THREADS
  5916. res = mknod(filename, mode, device);
  5917. Py_END_ALLOW_THREADS
  5918. if (res < 0)
  5919. return posix_error();
  5920. Py_INCREF(Py_None);
  5921. return Py_None;
  5922. }
  5923. #endif
  5924. #ifdef HAVE_DEVICE_MACROS
  5925. PyDoc_STRVAR(posix_major__doc__,
  5926. "major(device) -> major number\n\
  5927. Extracts a device major number from a raw device number.");
  5928. static PyObject *
  5929. posix_major(PyObject *self, PyObject *args)
  5930. {
  5931. int device;
  5932. if (!PyArg_ParseTuple(args, "i:major", &device))
  5933. return NULL;
  5934. return PyInt_FromLong((long)major(device));
  5935. }
  5936. PyDoc_STRVAR(posix_minor__doc__,
  5937. "minor(device) -> minor number\n\
  5938. Extracts a device minor number from a raw device number.");
  5939. static PyObject *
  5940. posix_minor(PyObject *self, PyObject *args)
  5941. {
  5942. int device;
  5943. if (!PyArg_ParseTuple(args, "i:minor", &device))
  5944. return NULL;
  5945. return PyInt_FromLong((long)minor(device));
  5946. }
  5947. PyDoc_STRVAR(posix_makedev__doc__,
  5948. "makedev(major, minor) -> device number\n\
  5949. Composes a raw device number from the major and minor device numbers.");
  5950. static PyObject *
  5951. posix_makedev(PyObject *self, PyObject *args)
  5952. {
  5953. int major, minor;
  5954. if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor))
  5955. return NULL;
  5956. return PyInt_FromLong((long)makedev(major, minor));
  5957. }
  5958. #endif /* device macros */
  5959. #ifdef HAVE_FTRUNCATE
  5960. PyDoc_STRVAR(posix_ftruncate__doc__,
  5961. "ftruncate(fd, length)\n\n\
  5962. Truncate a file to a specified length.");
  5963. static PyObject *
  5964. posix_ftruncate(PyObject *self, PyObject *args)
  5965. {
  5966. int fd;
  5967. off_t length;
  5968. int res;
  5969. PyObject *lenobj;
  5970. if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj))
  5971. return NULL;
  5972. #if !defined(HAVE_LARGEFILE_SUPPORT)
  5973. length = PyInt_AsLong(lenobj);
  5974. #else
  5975. length = PyLong_Check(lenobj) ?
  5976. PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj);
  5977. #endif
  5978. if (PyErr_Occurred())
  5979. return NULL;
  5980. Py_BEGIN_ALLOW_THREADS
  5981. res = ftruncate(fd, length);
  5982. Py_END_ALLOW_THREADS
  5983. if (res < 0) {
  5984. PyErr_SetFromErrno(PyExc_IOError);
  5985. return NULL;
  5986. }
  5987. Py_INCREF(Py_None);
  5988. return Py_None;
  5989. }
  5990. #endif
  5991. #ifdef HAVE_PUTENV
  5992. PyDoc_STRVAR(posix_putenv__doc__,
  5993. "putenv(key, value)\n\n\
  5994. Change or add an environment variable.");
  5995. /* Save putenv() parameters as values here, so we can collect them when they
  5996. * get re-set with another call for the same key. */
  5997. static PyObject *posix_putenv_garbage;
  5998. static PyObject *
  5999. posix_putenv(PyObject *self, PyObject *args)
  6000. {
  6001. char *s1, *s2;
  6002. char *newenv;
  6003. PyObject *newstr;
  6004. size_t len;
  6005. if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2))
  6006. return NULL;
  6007. #if defined(PYOS_OS2)
  6008. if (stricmp(s1, "BEGINLIBPATH") == 0) {
  6009. APIRET rc;
  6010. rc = DosSetExtLIBPATH(s2, BEGIN_LIBPATH);
  6011. if (rc != NO_ERROR)
  6012. return os2_error(rc);
  6013. } else if (stricmp(s1, "ENDLIBPATH") == 0) {
  6014. APIRET rc;
  6015. rc = DosSetExtLIBPATH(s2, END_LIBPATH);
  6016. if (rc != NO_ERROR)
  6017. return os2_error(rc);
  6018. } else {
  6019. #endif
  6020. /* XXX This can leak memory -- not easy to fix :-( */
  6021. len = strlen(s1) + strlen(s2) + 2;
  6022. /* len includes space for a trailing \0; the size arg to
  6023. PyString_FromStringAndSize does not count that */
  6024. newstr = PyString_FromStringAndSize(NULL, (int)len - 1);
  6025. if (newstr == NULL)
  6026. return PyErr_NoMemory();
  6027. newenv = PyString_AS_STRING(newstr);
  6028. PyOS_snprintf(newenv, len, "%s=%s", s1, s2);
  6029. if (putenv(newenv)) {
  6030. Py_DECREF(newstr);
  6031. posix_error();
  6032. return NULL;
  6033. }
  6034. /* Install the first arg and newstr in posix_putenv_garbage;
  6035. * this will cause previous value to be collected. This has to
  6036. * happen after the real putenv() call because the old value
  6037. * was still accessible until then. */
  6038. if (PyDict_SetItem(posix_putenv_garbage,
  6039. PyTuple_GET_ITEM(args, 0), newstr)) {
  6040. /* really not much we can do; just leak */
  6041. PyErr_Clear();
  6042. }
  6043. else {
  6044. Py_DECREF(newstr);
  6045. }
  6046. #if defined(PYOS_OS2)
  6047. }
  6048. #endif
  6049. Py_INCREF(Py_None);
  6050. return Py_None;
  6051. }
  6052. #endif /* putenv */
  6053. #ifdef HAVE_UNSETENV
  6054. PyDoc_STRVAR(posix_unsetenv__doc__,
  6055. "unsetenv(key)\n\n\
  6056. Delete an environment variable.");
  6057. static PyObject *
  6058. posix_unsetenv(PyObject *self, PyObject *args)
  6059. {
  6060. char *s1;
  6061. if (!PyArg_ParseTuple(args, "s:unsetenv", &s1))
  6062. return NULL;
  6063. unsetenv(s1);
  6064. /* Remove the key from posix_putenv_garbage;
  6065. * this will cause it to be collected. This has to
  6066. * happen after the real unsetenv() call because the
  6067. * old value was still accessible until then.
  6068. */
  6069. if (PyDict_DelItem(posix_putenv_garbage,
  6070. PyTuple_GET_ITEM(args, 0))) {
  6071. /* really not much we can do; just leak */
  6072. PyErr_Clear();
  6073. }
  6074. Py_INCREF(Py_None);
  6075. return Py_None;
  6076. }
  6077. #endif /* unsetenv */
  6078. PyDoc_STRVAR(posix_strerror__doc__,
  6079. "strerror(code) -> string\n\n\
  6080. Translate an error code to a message string.");
  6081. static PyObject *
  6082. posix_strerror(PyObject *self, PyObject *args)
  6083. {
  6084. int code;
  6085. char *message;
  6086. if (!PyArg_ParseTuple(args, "i:strerror", &code))
  6087. return NULL;
  6088. message = strerror(code);
  6089. if (message == NULL) {
  6090. PyErr_SetString(PyExc_ValueError,
  6091. "strerror() argument out of range");
  6092. return NULL;
  6093. }
  6094. return PyString_FromString(message);
  6095. }
  6096. #ifdef HAVE_SYS_WAIT_H
  6097. #ifdef WCOREDUMP
  6098. PyDoc_STRVAR(posix_WCOREDUMP__doc__,
  6099. "WCOREDUMP(status) -> bool\n\n\
  6100. Return True if the process returning 'status' was dumped to a core file.");
  6101. static PyObject *
  6102. posix_WCOREDUMP(PyObject *self, PyObject *args)
  6103. {
  6104. WAIT_TYPE status;
  6105. WAIT_STATUS_INT(status) = 0;
  6106. if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status)))
  6107. return NULL;
  6108. return PyBool_FromLong(WCOREDUMP(status));
  6109. }
  6110. #endif /* WCOREDUMP */
  6111. #ifdef WIFCONTINUED
  6112. PyDoc_STRVAR(posix_WIFCONTINUED__doc__,
  6113. "WIFCONTINUED(status) -> bool\n\n\
  6114. Return True if the process returning 'status' was continued from a\n\
  6115. job control stop.");
  6116. static PyObject *
  6117. posix_WIFCONTINUED(PyObject *self, PyObject *args)
  6118. {
  6119. WAIT_TYPE status;
  6120. WAIT_STATUS_INT(status) = 0;
  6121. if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status)))
  6122. return NULL;
  6123. return PyBool_FromLong(WIFCONTINUED(status));
  6124. }
  6125. #endif /* WIFCONTINUED */
  6126. #ifdef WIFSTOPPED
  6127. PyDoc_STRVAR(posix_WIFSTOPPED__doc__,
  6128. "WIFSTOPPED(status) -> bool\n\n\
  6129. Return True if the process returning 'status' was stopped.");
  6130. static PyObject *
  6131. posix_WIFSTOPPED(PyObject *self, PyObject *args)
  6132. {
  6133. WAIT_TYPE status;
  6134. WAIT_STATUS_INT(status) = 0;
  6135. if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status)))
  6136. return NULL;
  6137. return PyBool_FromLong(WIFSTOPPED(status));
  6138. }
  6139. #endif /* WIFSTOPPED */
  6140. #ifdef WIFSIGNALED
  6141. PyDoc_STRVAR(posix_WIFSIGNALED__doc__,
  6142. "WIFSIGNALED(status) -> bool\n\n\
  6143. Return True if the process returning 'status' was terminated by a signal.");
  6144. static PyObject *
  6145. posix_WIFSIGNALED(PyObject *self, PyObject *args)
  6146. {
  6147. WAIT_TYPE status;
  6148. WAIT_STATUS_INT(status) = 0;
  6149. if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status)))
  6150. return NULL;
  6151. return PyBool_FromLong(WIFSIGNALED(status));
  6152. }
  6153. #endif /* WIFSIGNALED */
  6154. #ifdef WIFEXITED
  6155. PyDoc_STRVAR(posix_WIFEXITED__doc__,
  6156. "WIFEXITED(status) -> bool\n\n\
  6157. Return true if the process returning 'status' exited using the exit()\n\
  6158. system call.");
  6159. static PyObject *
  6160. posix_WIFEXITED(PyObject *self, PyObject *args)
  6161. {
  6162. WAIT_TYPE status;
  6163. WAIT_STATUS_INT(status) = 0;
  6164. if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status)))
  6165. return NULL;
  6166. return PyBool_FromLong(WIFEXITED(status));
  6167. }
  6168. #endif /* WIFEXITED */
  6169. #ifdef WEXITSTATUS
  6170. PyDoc_STRVAR(posix_WEXITSTATUS__doc__,
  6171. "WEXITSTATUS(status) -> integer\n\n\
  6172. Return the process return code from 'status'.");
  6173. static PyObject *
  6174. posix_WEXITSTATUS(PyObject *self, PyObject *args)
  6175. {
  6176. WAIT_TYPE status;
  6177. WAIT_STATUS_INT(status) = 0;
  6178. if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status)))
  6179. return NULL;
  6180. return Py_BuildValue("i", WEXITSTATUS(status));
  6181. }
  6182. #endif /* WEXITSTATUS */
  6183. #ifdef WTERMSIG
  6184. PyDoc_STRVAR(posix_WTERMSIG__doc__,
  6185. "WTERMSIG(status) -> integer\n\n\
  6186. Return the signal that terminated the process that provided the 'status'\n\
  6187. value.");
  6188. static PyObject *
  6189. posix_WTERMSIG(PyObject *self, PyObject *args)
  6190. {
  6191. WAIT_TYPE status;
  6192. WAIT_STATUS_INT(status) = 0;
  6193. if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status)))
  6194. return NULL;
  6195. return Py_BuildValue("i", WTERMSIG(status));
  6196. }
  6197. #endif /* WTERMSIG */
  6198. #ifdef WSTOPSIG
  6199. PyDoc_STRVAR(posix_WSTOPSIG__doc__,
  6200. "WSTOPSIG(status) -> integer\n\n\
  6201. Return the signal that stopped the process that provided\n\
  6202. the 'status' value.");
  6203. static PyObject *
  6204. posix_WSTOPSIG(PyObject *self, PyObject *args)
  6205. {
  6206. WAIT_TYPE status;
  6207. WAIT_STATUS_INT(status) = 0;
  6208. if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status)))
  6209. return NULL;
  6210. return Py_BuildValue("i", WSTOPSIG(status));
  6211. }
  6212. #endif /* WSTOPSIG */
  6213. #endif /* HAVE_SYS_WAIT_H */
  6214. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  6215. #ifdef _SCO_DS
  6216. /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
  6217. needed definitions in sys/statvfs.h */
  6218. #define _SVID3
  6219. #endif
  6220. #include <sys/statvfs.h>
  6221. static PyObject*
  6222. _pystatvfs_fromstructstatvfs(struct statvfs st) {
  6223. PyObject *v = PyStructSequence_New(&StatVFSResultType);
  6224. if (v == NULL)
  6225. return NULL;
  6226. #if !defined(HAVE_LARGEFILE_SUPPORT)
  6227. PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));
  6228. PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));
  6229. PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks));
  6230. PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree));
  6231. PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail));
  6232. PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files));
  6233. PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree));
  6234. PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail));
  6235. PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));
  6236. PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));
  6237. #else
  6238. PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize));
  6239. PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize));
  6240. PyStructSequence_SET_ITEM(v, 2,
  6241. PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks));
  6242. PyStructSequence_SET_ITEM(v, 3,
  6243. PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree));
  6244. PyStructSequence_SET_ITEM(v, 4,
  6245. PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail));
  6246. PyStructSequence_SET_ITEM(v, 5,
  6247. PyLong_FromLongLong((PY_LONG_LONG) st.f_files));
  6248. PyStructSequence_SET_ITEM(v, 6,
  6249. PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree));
  6250. PyStructSequence_SET_ITEM(v, 7,
  6251. PyLong_FromLongLong((PY_LONG_LONG) st.f_favail));
  6252. PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag));
  6253. PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax));
  6254. #endif
  6255. return v;
  6256. }
  6257. PyDoc_STRVAR(posix_fstatvfs__doc__,
  6258. "fstatvfs(fd) -> statvfs result\n\n\
  6259. Perform an fstatvfs system call on the given fd.");
  6260. static PyObject *
  6261. posix_fstatvfs(PyObject *self, PyObject *args)
  6262. {
  6263. int fd, res;
  6264. struct statvfs st;
  6265. if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd))
  6266. return NULL;
  6267. Py_BEGIN_ALLOW_THREADS
  6268. res = fstatvfs(fd, &st);
  6269. Py_END_ALLOW_THREADS
  6270. if (res != 0)
  6271. return posix_error();
  6272. return _pystatvfs_fromstructstatvfs(st);
  6273. }
  6274. #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */
  6275. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  6276. #include <sys/statvfs.h>
  6277. PyDoc_STRVAR(posix_statvfs__doc__,
  6278. "statvfs(path) -> statvfs result\n\n\
  6279. Perform a statvfs system call on the given path.");
  6280. static PyObject *
  6281. posix_statvfs(PyObject *self, PyObject *args)
  6282. {
  6283. char *path;
  6284. int res;
  6285. struct statvfs st;
  6286. if (!PyArg_ParseTuple(args, "s:statvfs", &path))
  6287. return NULL;
  6288. Py_BEGIN_ALLOW_THREADS
  6289. res = statvfs(path, &st);
  6290. Py_END_ALLOW_THREADS
  6291. if (res != 0)
  6292. return posix_error_with_filename(path);
  6293. return _pystatvfs_fromstructstatvfs(st);
  6294. }
  6295. #endif /* HAVE_STATVFS */
  6296. #ifdef HAVE_TEMPNAM
  6297. PyDoc_STRVAR(posix_tempnam__doc__,
  6298. "tempnam([dir[, prefix]]) -> string\n\n\
  6299. Return a unique name for a temporary file.\n\
  6300. The directory and a prefix may be specified as strings; they may be omitted\n\
  6301. or None if not needed.");
  6302. static PyObject *
  6303. posix_tempnam(PyObject *self, PyObject *args)
  6304. {
  6305. PyObject *result = NULL;
  6306. char *dir = NULL;
  6307. char *pfx = NULL;
  6308. char *name;
  6309. if (!PyArg_ParseTuple(args, "|zz:tempnam", &dir, &pfx))
  6310. return NULL;
  6311. if (PyErr_Warn(PyExc_RuntimeWarning,
  6312. "tempnam is a potential security risk to your program") < 0)
  6313. return NULL;
  6314. #ifdef MS_WINDOWS
  6315. name = _tempnam(dir, pfx);
  6316. #else
  6317. name = tempnam(dir, pfx);
  6318. #endif
  6319. if (name == NULL)
  6320. return PyErr_NoMemory();
  6321. result = PyString_FromString(name);
  6322. free(name);
  6323. return result;
  6324. }
  6325. #endif
  6326. #ifdef HAVE_TMPFILE
  6327. PyDoc_STRVAR(posix_tmpfile__doc__,
  6328. "tmpfile() -> file object\n\n\
  6329. Create a temporary file with no directory entries.");
  6330. static PyObject *
  6331. posix_tmpfile(PyObject *self, PyObject *noargs)
  6332. {
  6333. FILE *fp;
  6334. fp = tmpfile();
  6335. if (fp == NULL)
  6336. return posix_error();
  6337. return PyFile_FromFile(fp, "<tmpfile>", "w+b", fclose);
  6338. }
  6339. #endif
  6340. #ifdef HAVE_TMPNAM
  6341. PyDoc_STRVAR(posix_tmpnam__doc__,
  6342. "tmpnam() -> string\n\n\
  6343. Return a unique name for a temporary file.");
  6344. static PyObject *
  6345. posix_tmpnam(PyObject *self, PyObject *noargs)
  6346. {
  6347. char buffer[L_tmpnam];
  6348. char *name;
  6349. if (PyErr_Warn(PyExc_RuntimeWarning,
  6350. "tmpnam is a potential security risk to your program") < 0)
  6351. return NULL;
  6352. #ifdef USE_TMPNAM_R
  6353. name = tmpnam_r(buffer);
  6354. #else
  6355. name = tmpnam(buffer);
  6356. #endif
  6357. if (name == NULL) {
  6358. PyObject *err = Py_BuildValue("is", 0,
  6359. #ifdef USE_TMPNAM_R
  6360. "unexpected NULL from tmpnam_r"
  6361. #else
  6362. "unexpected NULL from tmpnam"
  6363. #endif
  6364. );
  6365. PyErr_SetObject(PyExc_OSError, err);
  6366. Py_XDECREF(err);
  6367. return NULL;
  6368. }
  6369. return PyString_FromString(buffer);
  6370. }
  6371. #endif
  6372. /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
  6373. * It maps strings representing configuration variable names to
  6374. * integer values, allowing those functions to be called with the
  6375. * magic names instead of polluting the module's namespace with tons of
  6376. * rarely-used constants. There are three separate tables that use
  6377. * these definitions.
  6378. *
  6379. * This code is always included, even if none of the interfaces that
  6380. * need it are included. The #if hackery needed to avoid it would be
  6381. * sufficiently pervasive that it's not worth the loss of readability.
  6382. */
  6383. struct constdef {
  6384. char *name;
  6385. long value;
  6386. };
  6387. static int
  6388. conv_confname(PyObject *arg, int *valuep, struct constdef *table,
  6389. size_t tablesize)
  6390. {
  6391. if (PyInt_Check(arg)) {
  6392. *valuep = PyInt_AS_LONG(arg);
  6393. return 1;
  6394. }
  6395. if (PyString_Check(arg)) {
  6396. /* look up the value in the table using a binary search */
  6397. size_t lo = 0;
  6398. size_t mid;
  6399. size_t hi = tablesize;
  6400. int cmp;
  6401. char *confname = PyString_AS_STRING(arg);
  6402. while (lo < hi) {
  6403. mid = (lo + hi) / 2;
  6404. cmp = strcmp(confname, table[mid].name);
  6405. if (cmp < 0)
  6406. hi = mid;
  6407. else if (cmp > 0)
  6408. lo = mid + 1;
  6409. else {
  6410. *valuep = table[mid].value;
  6411. return 1;
  6412. }
  6413. }
  6414. PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
  6415. }
  6416. else
  6417. PyErr_SetString(PyExc_TypeError,
  6418. "configuration names must be strings or integers");
  6419. return 0;
  6420. }
  6421. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  6422. static struct constdef posix_constants_pathconf[] = {
  6423. #ifdef _PC_ABI_AIO_XFER_MAX
  6424. {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
  6425. #endif
  6426. #ifdef _PC_ABI_ASYNC_IO
  6427. {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
  6428. #endif
  6429. #ifdef _PC_ASYNC_IO
  6430. {"PC_ASYNC_IO", _PC_ASYNC_IO},
  6431. #endif
  6432. #ifdef _PC_CHOWN_RESTRICTED
  6433. {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
  6434. #endif
  6435. #ifdef _PC_FILESIZEBITS
  6436. {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
  6437. #endif
  6438. #ifdef _PC_LAST
  6439. {"PC_LAST", _PC_LAST},
  6440. #endif
  6441. #ifdef _PC_LINK_MAX
  6442. {"PC_LINK_MAX", _PC_LINK_MAX},
  6443. #endif
  6444. #ifdef _PC_MAX_CANON
  6445. {"PC_MAX_CANON", _PC_MAX_CANON},
  6446. #endif
  6447. #ifdef _PC_MAX_INPUT
  6448. {"PC_MAX_INPUT", _PC_MAX_INPUT},
  6449. #endif
  6450. #ifdef _PC_NAME_MAX
  6451. {"PC_NAME_MAX", _PC_NAME_MAX},
  6452. #endif
  6453. #ifdef _PC_NO_TRUNC
  6454. {"PC_NO_TRUNC", _PC_NO_TRUNC},
  6455. #endif
  6456. #ifdef _PC_PATH_MAX
  6457. {"PC_PATH_MAX", _PC_PATH_MAX},
  6458. #endif
  6459. #ifdef _PC_PIPE_BUF
  6460. {"PC_PIPE_BUF", _PC_PIPE_BUF},
  6461. #endif
  6462. #ifdef _PC_PRIO_IO
  6463. {"PC_PRIO_IO", _PC_PRIO_IO},
  6464. #endif
  6465. #ifdef _PC_SOCK_MAXBUF
  6466. {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
  6467. #endif
  6468. #ifdef _PC_SYNC_IO
  6469. {"PC_SYNC_IO", _PC_SYNC_IO},
  6470. #endif
  6471. #ifdef _PC_VDISABLE
  6472. {"PC_VDISABLE", _PC_VDISABLE},
  6473. #endif
  6474. };
  6475. static int
  6476. conv_path_confname(PyObject *arg, int *valuep)
  6477. {
  6478. return conv_confname(arg, valuep, posix_constants_pathconf,
  6479. sizeof(posix_constants_pathconf)
  6480. / sizeof(struct constdef));
  6481. }
  6482. #endif
  6483. #ifdef HAVE_FPATHCONF
  6484. PyDoc_STRVAR(posix_fpathconf__doc__,
  6485. "fpathconf(fd, name) -> integer\n\n\
  6486. Return the configuration limit name for the file descriptor fd.\n\
  6487. If there is no limit, return -1.");
  6488. static PyObject *
  6489. posix_fpathconf(PyObject *self, PyObject *args)
  6490. {
  6491. PyObject *result = NULL;
  6492. int name, fd;
  6493. if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd,
  6494. conv_path_confname, &name)) {
  6495. long limit;
  6496. errno = 0;
  6497. limit = fpathconf(fd, name);
  6498. if (limit == -1 && errno != 0)
  6499. posix_error();
  6500. else
  6501. result = PyInt_FromLong(limit);
  6502. }
  6503. return result;
  6504. }
  6505. #endif
  6506. #ifdef HAVE_PATHCONF
  6507. PyDoc_STRVAR(posix_pathconf__doc__,
  6508. "pathconf(path, name) -> integer\n\n\
  6509. Return the configuration limit name for the file or directory path.\n\
  6510. If there is no limit, return -1.");
  6511. static PyObject *
  6512. posix_pathconf(PyObject *self, PyObject *args)
  6513. {
  6514. PyObject *result = NULL;
  6515. int name;
  6516. char *path;
  6517. if (PyArg_ParseTuple(args, "sO&:pathconf", &path,
  6518. conv_path_confname, &name)) {
  6519. long limit;
  6520. errno = 0;
  6521. limit = pathconf(path, name);
  6522. if (limit == -1 && errno != 0) {
  6523. if (errno == EINVAL)
  6524. /* could be a path or name problem */
  6525. posix_error();
  6526. else
  6527. posix_error_with_filename(path);
  6528. }
  6529. else
  6530. result = PyInt_FromLong(limit);
  6531. }
  6532. return result;
  6533. }
  6534. #endif
  6535. #ifdef HAVE_CONFSTR
  6536. static struct constdef posix_constants_confstr[] = {
  6537. #ifdef _CS_ARCHITECTURE
  6538. {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
  6539. #endif
  6540. #ifdef _CS_HOSTNAME
  6541. {"CS_HOSTNAME", _CS_HOSTNAME},
  6542. #endif
  6543. #ifdef _CS_HW_PROVIDER
  6544. {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
  6545. #endif
  6546. #ifdef _CS_HW_SERIAL
  6547. {"CS_HW_SERIAL", _CS_HW_SERIAL},
  6548. #endif
  6549. #ifdef _CS_INITTAB_NAME
  6550. {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
  6551. #endif
  6552. #ifdef _CS_LFS64_CFLAGS
  6553. {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
  6554. #endif
  6555. #ifdef _CS_LFS64_LDFLAGS
  6556. {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
  6557. #endif
  6558. #ifdef _CS_LFS64_LIBS
  6559. {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
  6560. #endif
  6561. #ifdef _CS_LFS64_LINTFLAGS
  6562. {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
  6563. #endif
  6564. #ifdef _CS_LFS_CFLAGS
  6565. {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
  6566. #endif
  6567. #ifdef _CS_LFS_LDFLAGS
  6568. {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
  6569. #endif
  6570. #ifdef _CS_LFS_LIBS
  6571. {"CS_LFS_LIBS", _CS_LFS_LIBS},
  6572. #endif
  6573. #ifdef _CS_LFS_LINTFLAGS
  6574. {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
  6575. #endif
  6576. #ifdef _CS_MACHINE
  6577. {"CS_MACHINE", _CS_MACHINE},
  6578. #endif
  6579. #ifdef _CS_PATH
  6580. {"CS_PATH", _CS_PATH},
  6581. #endif
  6582. #ifdef _CS_RELEASE
  6583. {"CS_RELEASE", _CS_RELEASE},
  6584. #endif
  6585. #ifdef _CS_SRPC_DOMAIN
  6586. {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
  6587. #endif
  6588. #ifdef _CS_SYSNAME
  6589. {"CS_SYSNAME", _CS_SYSNAME},
  6590. #endif
  6591. #ifdef _CS_VERSION
  6592. {"CS_VERSION", _CS_VERSION},
  6593. #endif
  6594. #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
  6595. {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
  6596. #endif
  6597. #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
  6598. {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
  6599. #endif
  6600. #ifdef _CS_XBS5_ILP32_OFF32_LIBS
  6601. {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
  6602. #endif
  6603. #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
  6604. {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
  6605. #endif
  6606. #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
  6607. {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
  6608. #endif
  6609. #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
  6610. {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
  6611. #endif
  6612. #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
  6613. {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
  6614. #endif
  6615. #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
  6616. {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
  6617. #endif
  6618. #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
  6619. {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
  6620. #endif
  6621. #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
  6622. {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
  6623. #endif
  6624. #ifdef _CS_XBS5_LP64_OFF64_LIBS
  6625. {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
  6626. #endif
  6627. #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
  6628. {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
  6629. #endif
  6630. #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
  6631. {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
  6632. #endif
  6633. #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
  6634. {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
  6635. #endif
  6636. #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
  6637. {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
  6638. #endif
  6639. #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
  6640. {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
  6641. #endif
  6642. #ifdef _MIPS_CS_AVAIL_PROCESSORS
  6643. {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
  6644. #endif
  6645. #ifdef _MIPS_CS_BASE
  6646. {"MIPS_CS_BASE", _MIPS_CS_BASE},
  6647. #endif
  6648. #ifdef _MIPS_CS_HOSTID
  6649. {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
  6650. #endif
  6651. #ifdef _MIPS_CS_HW_NAME
  6652. {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
  6653. #endif
  6654. #ifdef _MIPS_CS_NUM_PROCESSORS
  6655. {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
  6656. #endif
  6657. #ifdef _MIPS_CS_OSREL_MAJ
  6658. {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
  6659. #endif
  6660. #ifdef _MIPS_CS_OSREL_MIN
  6661. {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
  6662. #endif
  6663. #ifdef _MIPS_CS_OSREL_PATCH
  6664. {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
  6665. #endif
  6666. #ifdef _MIPS_CS_OS_NAME
  6667. {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
  6668. #endif
  6669. #ifdef _MIPS_CS_OS_PROVIDER
  6670. {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
  6671. #endif
  6672. #ifdef _MIPS_CS_PROCESSORS
  6673. {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
  6674. #endif
  6675. #ifdef _MIPS_CS_SERIAL
  6676. {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
  6677. #endif
  6678. #ifdef _MIPS_CS_VENDOR
  6679. {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
  6680. #endif
  6681. };
  6682. static int
  6683. conv_confstr_confname(PyObject *arg, int *valuep)
  6684. {
  6685. return conv_confname(arg, valuep, posix_constants_confstr,
  6686. sizeof(posix_constants_confstr)
  6687. / sizeof(struct constdef));
  6688. }
  6689. PyDoc_STRVAR(posix_confstr__doc__,
  6690. "confstr(name) -> string\n\n\
  6691. Return a string-valued system configuration variable.");
  6692. static PyObject *
  6693. posix_confstr(PyObject *self, PyObject *args)
  6694. {
  6695. PyObject *result = NULL;
  6696. int name;
  6697. char buffer[256];
  6698. if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) {
  6699. int len;
  6700. errno = 0;
  6701. len = confstr(name, buffer, sizeof(buffer));
  6702. if (len == 0) {
  6703. if (errno) {
  6704. posix_error();
  6705. }
  6706. else {
  6707. result = Py_None;
  6708. Py_INCREF(Py_None);
  6709. }
  6710. }
  6711. else {
  6712. if ((unsigned int)len >= sizeof(buffer)) {
  6713. result = PyString_FromStringAndSize(NULL, len-1);
  6714. if (result != NULL)
  6715. confstr(name, PyString_AS_STRING(result), len);
  6716. }
  6717. else
  6718. result = PyString_FromStringAndSize(buffer, len-1);
  6719. }
  6720. }
  6721. return result;
  6722. }
  6723. #endif
  6724. #ifdef HAVE_SYSCONF
  6725. static struct constdef posix_constants_sysconf[] = {
  6726. #ifdef _SC_2_CHAR_TERM
  6727. {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
  6728. #endif
  6729. #ifdef _SC_2_C_BIND
  6730. {"SC_2_C_BIND", _SC_2_C_BIND},
  6731. #endif
  6732. #ifdef _SC_2_C_DEV
  6733. {"SC_2_C_DEV", _SC_2_C_DEV},
  6734. #endif
  6735. #ifdef _SC_2_C_VERSION
  6736. {"SC_2_C_VERSION", _SC_2_C_VERSION},
  6737. #endif
  6738. #ifdef _SC_2_FORT_DEV
  6739. {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
  6740. #endif
  6741. #ifdef _SC_2_FORT_RUN
  6742. {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
  6743. #endif
  6744. #ifdef _SC_2_LOCALEDEF
  6745. {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
  6746. #endif
  6747. #ifdef _SC_2_SW_DEV
  6748. {"SC_2_SW_DEV", _SC_2_SW_DEV},
  6749. #endif
  6750. #ifdef _SC_2_UPE
  6751. {"SC_2_UPE", _SC_2_UPE},
  6752. #endif
  6753. #ifdef _SC_2_VERSION
  6754. {"SC_2_VERSION", _SC_2_VERSION},
  6755. #endif
  6756. #ifdef _SC_ABI_ASYNCHRONOUS_IO
  6757. {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
  6758. #endif
  6759. #ifdef _SC_ACL
  6760. {"SC_ACL", _SC_ACL},
  6761. #endif
  6762. #ifdef _SC_AIO_LISTIO_MAX
  6763. {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
  6764. #endif
  6765. #ifdef _SC_AIO_MAX
  6766. {"SC_AIO_MAX", _SC_AIO_MAX},
  6767. #endif
  6768. #ifdef _SC_AIO_PRIO_DELTA_MAX
  6769. {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
  6770. #endif
  6771. #ifdef _SC_ARG_MAX
  6772. {"SC_ARG_MAX", _SC_ARG_MAX},
  6773. #endif
  6774. #ifdef _SC_ASYNCHRONOUS_IO
  6775. {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
  6776. #endif
  6777. #ifdef _SC_ATEXIT_MAX
  6778. {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
  6779. #endif
  6780. #ifdef _SC_AUDIT
  6781. {"SC_AUDIT", _SC_AUDIT},
  6782. #endif
  6783. #ifdef _SC_AVPHYS_PAGES
  6784. {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
  6785. #endif
  6786. #ifdef _SC_BC_BASE_MAX
  6787. {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
  6788. #endif
  6789. #ifdef _SC_BC_DIM_MAX
  6790. {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
  6791. #endif
  6792. #ifdef _SC_BC_SCALE_MAX
  6793. {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
  6794. #endif
  6795. #ifdef _SC_BC_STRING_MAX
  6796. {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
  6797. #endif
  6798. #ifdef _SC_CAP
  6799. {"SC_CAP", _SC_CAP},
  6800. #endif
  6801. #ifdef _SC_CHARCLASS_NAME_MAX
  6802. {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
  6803. #endif
  6804. #ifdef _SC_CHAR_BIT
  6805. {"SC_CHAR_BIT", _SC_CHAR_BIT},
  6806. #endif
  6807. #ifdef _SC_CHAR_MAX
  6808. {"SC_CHAR_MAX", _SC_CHAR_MAX},
  6809. #endif
  6810. #ifdef _SC_CHAR_MIN
  6811. {"SC_CHAR_MIN", _SC_CHAR_MIN},
  6812. #endif
  6813. #ifdef _SC_CHILD_MAX
  6814. {"SC_CHILD_MAX", _SC_CHILD_MAX},
  6815. #endif
  6816. #ifdef _SC_CLK_TCK
  6817. {"SC_CLK_TCK", _SC_CLK_TCK},
  6818. #endif
  6819. #ifdef _SC_COHER_BLKSZ
  6820. {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
  6821. #endif
  6822. #ifdef _SC_COLL_WEIGHTS_MAX
  6823. {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
  6824. #endif
  6825. #ifdef _SC_DCACHE_ASSOC
  6826. {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
  6827. #endif
  6828. #ifdef _SC_DCACHE_BLKSZ
  6829. {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
  6830. #endif
  6831. #ifdef _SC_DCACHE_LINESZ
  6832. {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
  6833. #endif
  6834. #ifdef _SC_DCACHE_SZ
  6835. {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
  6836. #endif
  6837. #ifdef _SC_DCACHE_TBLKSZ
  6838. {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
  6839. #endif
  6840. #ifdef _SC_DELAYTIMER_MAX
  6841. {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
  6842. #endif
  6843. #ifdef _SC_EQUIV_CLASS_MAX
  6844. {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
  6845. #endif
  6846. #ifdef _SC_EXPR_NEST_MAX
  6847. {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
  6848. #endif
  6849. #ifdef _SC_FSYNC
  6850. {"SC_FSYNC", _SC_FSYNC},
  6851. #endif
  6852. #ifdef _SC_GETGR_R_SIZE_MAX
  6853. {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
  6854. #endif
  6855. #ifdef _SC_GETPW_R_SIZE_MAX
  6856. {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
  6857. #endif
  6858. #ifdef _SC_ICACHE_ASSOC
  6859. {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
  6860. #endif
  6861. #ifdef _SC_ICACHE_BLKSZ
  6862. {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
  6863. #endif
  6864. #ifdef _SC_ICACHE_LINESZ
  6865. {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
  6866. #endif
  6867. #ifdef _SC_ICACHE_SZ
  6868. {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
  6869. #endif
  6870. #ifdef _SC_INF
  6871. {"SC_INF", _SC_INF},
  6872. #endif
  6873. #ifdef _SC_INT_MAX
  6874. {"SC_INT_MAX", _SC_INT_MAX},
  6875. #endif
  6876. #ifdef _SC_INT_MIN
  6877. {"SC_INT_MIN", _SC_INT_MIN},
  6878. #endif
  6879. #ifdef _SC_IOV_MAX
  6880. {"SC_IOV_MAX", _SC_IOV_MAX},
  6881. #endif
  6882. #ifdef _SC_IP_SECOPTS
  6883. {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
  6884. #endif
  6885. #ifdef _SC_JOB_CONTROL
  6886. {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
  6887. #endif
  6888. #ifdef _SC_KERN_POINTERS
  6889. {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
  6890. #endif
  6891. #ifdef _SC_KERN_SIM
  6892. {"SC_KERN_SIM", _SC_KERN_SIM},
  6893. #endif
  6894. #ifdef _SC_LINE_MAX
  6895. {"SC_LINE_MAX", _SC_LINE_MAX},
  6896. #endif
  6897. #ifdef _SC_LOGIN_NAME_MAX
  6898. {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
  6899. #endif
  6900. #ifdef _SC_LOGNAME_MAX
  6901. {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
  6902. #endif
  6903. #ifdef _SC_LONG_BIT
  6904. {"SC_LONG_BIT", _SC_LONG_BIT},
  6905. #endif
  6906. #ifdef _SC_MAC
  6907. {"SC_MAC", _SC_MAC},
  6908. #endif
  6909. #ifdef _SC_MAPPED_FILES
  6910. {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
  6911. #endif
  6912. #ifdef _SC_MAXPID
  6913. {"SC_MAXPID", _SC_MAXPID},
  6914. #endif
  6915. #ifdef _SC_MB_LEN_MAX
  6916. {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
  6917. #endif
  6918. #ifdef _SC_MEMLOCK
  6919. {"SC_MEMLOCK", _SC_MEMLOCK},
  6920. #endif
  6921. #ifdef _SC_MEMLOCK_RANGE
  6922. {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
  6923. #endif
  6924. #ifdef _SC_MEMORY_PROTECTION
  6925. {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
  6926. #endif
  6927. #ifdef _SC_MESSAGE_PASSING
  6928. {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
  6929. #endif
  6930. #ifdef _SC_MMAP_FIXED_ALIGNMENT
  6931. {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
  6932. #endif
  6933. #ifdef _SC_MQ_OPEN_MAX
  6934. {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
  6935. #endif
  6936. #ifdef _SC_MQ_PRIO_MAX
  6937. {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
  6938. #endif
  6939. #ifdef _SC_NACLS_MAX
  6940. {"SC_NACLS_MAX", _SC_NACLS_MAX},
  6941. #endif
  6942. #ifdef _SC_NGROUPS_MAX
  6943. {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
  6944. #endif
  6945. #ifdef _SC_NL_ARGMAX
  6946. {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
  6947. #endif
  6948. #ifdef _SC_NL_LANGMAX
  6949. {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
  6950. #endif
  6951. #ifdef _SC_NL_MSGMAX
  6952. {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
  6953. #endif
  6954. #ifdef _SC_NL_NMAX
  6955. {"SC_NL_NMAX", _SC_NL_NMAX},
  6956. #endif
  6957. #ifdef _SC_NL_SETMAX
  6958. {"SC_NL_SETMAX", _SC_NL_SETMAX},
  6959. #endif
  6960. #ifdef _SC_NL_TEXTMAX
  6961. {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
  6962. #endif
  6963. #ifdef _SC_NPROCESSORS_CONF
  6964. {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
  6965. #endif
  6966. #ifdef _SC_NPROCESSORS_ONLN
  6967. {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
  6968. #endif
  6969. #ifdef _SC_NPROC_CONF
  6970. {"SC_NPROC_CONF", _SC_NPROC_CONF},
  6971. #endif
  6972. #ifdef _SC_NPROC_ONLN
  6973. {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
  6974. #endif
  6975. #ifdef _SC_NZERO
  6976. {"SC_NZERO", _SC_NZERO},
  6977. #endif
  6978. #ifdef _SC_OPEN_MAX
  6979. {"SC_OPEN_MAX", _SC_OPEN_MAX},
  6980. #endif
  6981. #ifdef _SC_PAGESIZE
  6982. {"SC_PAGESIZE", _SC_PAGESIZE},
  6983. #endif
  6984. #ifdef _SC_PAGE_SIZE
  6985. {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
  6986. #endif
  6987. #ifdef _SC_PASS_MAX
  6988. {"SC_PASS_MAX", _SC_PASS_MAX},
  6989. #endif
  6990. #ifdef _SC_PHYS_PAGES
  6991. {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
  6992. #endif
  6993. #ifdef _SC_PII
  6994. {"SC_PII", _SC_PII},
  6995. #endif
  6996. #ifdef _SC_PII_INTERNET
  6997. {"SC_PII_INTERNET", _SC_PII_INTERNET},
  6998. #endif
  6999. #ifdef _SC_PII_INTERNET_DGRAM
  7000. {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
  7001. #endif
  7002. #ifdef _SC_PII_INTERNET_STREAM
  7003. {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
  7004. #endif
  7005. #ifdef _SC_PII_OSI
  7006. {"SC_PII_OSI", _SC_PII_OSI},
  7007. #endif
  7008. #ifdef _SC_PII_OSI_CLTS
  7009. {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
  7010. #endif
  7011. #ifdef _SC_PII_OSI_COTS
  7012. {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
  7013. #endif
  7014. #ifdef _SC_PII_OSI_M
  7015. {"SC_PII_OSI_M", _SC_PII_OSI_M},
  7016. #endif
  7017. #ifdef _SC_PII_SOCKET
  7018. {"SC_PII_SOCKET", _SC_PII_SOCKET},
  7019. #endif
  7020. #ifdef _SC_PII_XTI
  7021. {"SC_PII_XTI", _SC_PII_XTI},
  7022. #endif
  7023. #ifdef _SC_POLL
  7024. {"SC_POLL", _SC_POLL},
  7025. #endif
  7026. #ifdef _SC_PRIORITIZED_IO
  7027. {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
  7028. #endif
  7029. #ifdef _SC_PRIORITY_SCHEDULING
  7030. {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
  7031. #endif
  7032. #ifdef _SC_REALTIME_SIGNALS
  7033. {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
  7034. #endif
  7035. #ifdef _SC_RE_DUP_MAX
  7036. {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
  7037. #endif
  7038. #ifdef _SC_RTSIG_MAX
  7039. {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
  7040. #endif
  7041. #ifdef _SC_SAVED_IDS
  7042. {"SC_SAVED_IDS", _SC_SAVED_IDS},
  7043. #endif
  7044. #ifdef _SC_SCHAR_MAX
  7045. {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
  7046. #endif
  7047. #ifdef _SC_SCHAR_MIN
  7048. {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
  7049. #endif
  7050. #ifdef _SC_SELECT
  7051. {"SC_SELECT", _SC_SELECT},
  7052. #endif
  7053. #ifdef _SC_SEMAPHORES
  7054. {"SC_SEMAPHORES", _SC_SEMAPHORES},
  7055. #endif
  7056. #ifdef _SC_SEM_NSEMS_MAX
  7057. {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
  7058. #endif
  7059. #ifdef _SC_SEM_VALUE_MAX
  7060. {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
  7061. #endif
  7062. #ifdef _SC_SHARED_MEMORY_OBJECTS
  7063. {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
  7064. #endif
  7065. #ifdef _SC_SHRT_MAX
  7066. {"SC_SHRT_MAX", _SC_SHRT_MAX},
  7067. #endif
  7068. #ifdef _SC_SHRT_MIN
  7069. {"SC_SHRT_MIN", _SC_SHRT_MIN},
  7070. #endif
  7071. #ifdef _SC_SIGQUEUE_MAX
  7072. {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
  7073. #endif
  7074. #ifdef _SC_SIGRT_MAX
  7075. {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
  7076. #endif
  7077. #ifdef _SC_SIGRT_MIN
  7078. {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
  7079. #endif
  7080. #ifdef _SC_SOFTPOWER
  7081. {"SC_SOFTPOWER", _SC_SOFTPOWER},
  7082. #endif
  7083. #ifdef _SC_SPLIT_CACHE
  7084. {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
  7085. #endif
  7086. #ifdef _SC_SSIZE_MAX
  7087. {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
  7088. #endif
  7089. #ifdef _SC_STACK_PROT
  7090. {"SC_STACK_PROT", _SC_STACK_PROT},
  7091. #endif
  7092. #ifdef _SC_STREAM_MAX
  7093. {"SC_STREAM_MAX", _SC_STREAM_MAX},
  7094. #endif
  7095. #ifdef _SC_SYNCHRONIZED_IO
  7096. {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
  7097. #endif
  7098. #ifdef _SC_THREADS
  7099. {"SC_THREADS", _SC_THREADS},
  7100. #endif
  7101. #ifdef _SC_THREAD_ATTR_STACKADDR
  7102. {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
  7103. #endif
  7104. #ifdef _SC_THREAD_ATTR_STACKSIZE
  7105. {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
  7106. #endif
  7107. #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
  7108. {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
  7109. #endif
  7110. #ifdef _SC_THREAD_KEYS_MAX
  7111. {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
  7112. #endif
  7113. #ifdef _SC_THREAD_PRIORITY_SCHEDULING
  7114. {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
  7115. #endif
  7116. #ifdef _SC_THREAD_PRIO_INHERIT
  7117. {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
  7118. #endif
  7119. #ifdef _SC_THREAD_PRIO_PROTECT
  7120. {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
  7121. #endif
  7122. #ifdef _SC_THREAD_PROCESS_SHARED
  7123. {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
  7124. #endif
  7125. #ifdef _SC_THREAD_SAFE_FUNCTIONS
  7126. {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
  7127. #endif
  7128. #ifdef _SC_THREAD_STACK_MIN
  7129. {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
  7130. #endif
  7131. #ifdef _SC_THREAD_THREADS_MAX
  7132. {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
  7133. #endif
  7134. #ifdef _SC_TIMERS
  7135. {"SC_TIMERS", _SC_TIMERS},
  7136. #endif
  7137. #ifdef _SC_TIMER_MAX
  7138. {"SC_TIMER_MAX", _SC_TIMER_MAX},
  7139. #endif
  7140. #ifdef _SC_TTY_NAME_MAX
  7141. {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
  7142. #endif
  7143. #ifdef _SC_TZNAME_MAX
  7144. {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
  7145. #endif
  7146. #ifdef _SC_T_IOV_MAX
  7147. {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
  7148. #endif
  7149. #ifdef _SC_UCHAR_MAX
  7150. {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
  7151. #endif
  7152. #ifdef _SC_UINT_MAX
  7153. {"SC_UINT_MAX", _SC_UINT_MAX},
  7154. #endif
  7155. #ifdef _SC_UIO_MAXIOV
  7156. {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
  7157. #endif
  7158. #ifdef _SC_ULONG_MAX
  7159. {"SC_ULONG_MAX", _SC_ULONG_MAX},
  7160. #endif
  7161. #ifdef _SC_USHRT_MAX
  7162. {"SC_USHRT_MAX", _SC_USHRT_MAX},
  7163. #endif
  7164. #ifdef _SC_VERSION
  7165. {"SC_VERSION", _SC_VERSION},
  7166. #endif
  7167. #ifdef _SC_WORD_BIT
  7168. {"SC_WORD_BIT", _SC_WORD_BIT},
  7169. #endif
  7170. #ifdef _SC_XBS5_ILP32_OFF32
  7171. {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
  7172. #endif
  7173. #ifdef _SC_XBS5_ILP32_OFFBIG
  7174. {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
  7175. #endif
  7176. #ifdef _SC_XBS5_LP64_OFF64
  7177. {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
  7178. #endif
  7179. #ifdef _SC_XBS5_LPBIG_OFFBIG
  7180. {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
  7181. #endif
  7182. #ifdef _SC_XOPEN_CRYPT
  7183. {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
  7184. #endif
  7185. #ifdef _SC_XOPEN_ENH_I18N
  7186. {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
  7187. #endif
  7188. #ifdef _SC_XOPEN_LEGACY
  7189. {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
  7190. #endif
  7191. #ifdef _SC_XOPEN_REALTIME
  7192. {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
  7193. #endif
  7194. #ifdef _SC_XOPEN_REALTIME_THREADS
  7195. {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
  7196. #endif
  7197. #ifdef _SC_XOPEN_SHM
  7198. {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
  7199. #endif
  7200. #ifdef _SC_XOPEN_UNIX
  7201. {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
  7202. #endif
  7203. #ifdef _SC_XOPEN_VERSION
  7204. {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
  7205. #endif
  7206. #ifdef _SC_XOPEN_XCU_VERSION
  7207. {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
  7208. #endif
  7209. #ifdef _SC_XOPEN_XPG2
  7210. {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
  7211. #endif
  7212. #ifdef _SC_XOPEN_XPG3
  7213. {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
  7214. #endif
  7215. #ifdef _SC_XOPEN_XPG4
  7216. {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
  7217. #endif
  7218. };
  7219. static int
  7220. conv_sysconf_confname(PyObject *arg, int *valuep)
  7221. {
  7222. return conv_confname(arg, valuep, posix_constants_sysconf,
  7223. sizeof(posix_constants_sysconf)
  7224. / sizeof(struct constdef));
  7225. }
  7226. PyDoc_STRVAR(posix_sysconf__doc__,
  7227. "sysconf(name) -> integer\n\n\
  7228. Return an integer-valued system configuration variable.");
  7229. static PyObject *
  7230. posix_sysconf(PyObject *self, PyObject *args)
  7231. {
  7232. PyObject *result = NULL;
  7233. int name;
  7234. if (PyArg_ParseTuple(args, "O&:sysconf", conv_sysconf_confname, &name)) {
  7235. int value;
  7236. errno = 0;
  7237. value = sysconf(name);
  7238. if (value == -1 && errno != 0)
  7239. posix_error();
  7240. else
  7241. result = PyInt_FromLong(value);
  7242. }
  7243. return result;
  7244. }
  7245. #endif
  7246. /* This code is used to ensure that the tables of configuration value names
  7247. * are in sorted order as required by conv_confname(), and also to build the
  7248. * the exported dictionaries that are used to publish information about the
  7249. * names available on the host platform.
  7250. *
  7251. * Sorting the table at runtime ensures that the table is properly ordered
  7252. * when used, even for platforms we're not able to test on. It also makes
  7253. * it easier to add additional entries to the tables.
  7254. */
  7255. static int
  7256. cmp_constdefs(const void *v1, const void *v2)
  7257. {
  7258. const struct constdef *c1 =
  7259. (const struct constdef *) v1;
  7260. const struct constdef *c2 =
  7261. (const struct constdef *) v2;
  7262. return strcmp(c1->name, c2->name);
  7263. }
  7264. static int
  7265. setup_confname_table(struct constdef *table, size_t tablesize,
  7266. char *tablename, PyObject *module)
  7267. {
  7268. PyObject *d = NULL;
  7269. size_t i;
  7270. qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
  7271. d = PyDict_New();
  7272. if (d == NULL)
  7273. return -1;
  7274. for (i=0; i < tablesize; ++i) {
  7275. PyObject *o = PyInt_FromLong(table[i].value);
  7276. if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
  7277. Py_XDECREF(o);
  7278. Py_DECREF(d);
  7279. return -1;
  7280. }
  7281. Py_DECREF(o);
  7282. }
  7283. return PyModule_AddObject(module, tablename, d);
  7284. }
  7285. /* Return -1 on failure, 0 on success. */
  7286. static int
  7287. setup_confname_tables(PyObject *module)
  7288. {
  7289. #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
  7290. if (setup_confname_table(posix_constants_pathconf,
  7291. sizeof(posix_constants_pathconf)
  7292. / sizeof(struct constdef),
  7293. "pathconf_names", module))
  7294. return -1;
  7295. #endif
  7296. #ifdef HAVE_CONFSTR
  7297. if (setup_confname_table(posix_constants_confstr,
  7298. sizeof(posix_constants_confstr)
  7299. / sizeof(struct constdef),
  7300. "confstr_names", module))
  7301. return -1;
  7302. #endif
  7303. #ifdef HAVE_SYSCONF
  7304. if (setup_confname_table(posix_constants_sysconf,
  7305. sizeof(posix_constants_sysconf)
  7306. / sizeof(struct constdef),
  7307. "sysconf_names", module))
  7308. return -1;
  7309. #endif
  7310. return 0;
  7311. }
  7312. PyDoc_STRVAR(posix_abort__doc__,
  7313. "abort() -> does not return!\n\n\
  7314. Abort the interpreter immediately. This 'dumps core' or otherwise fails\n\
  7315. in the hardest way possible on the hosting operating system.");
  7316. static PyObject *
  7317. posix_abort(PyObject *self, PyObject *noargs)
  7318. {
  7319. abort();
  7320. /*NOTREACHED*/
  7321. Py_FatalError("abort() called from Python code didn't abort!");
  7322. return NULL;
  7323. }
  7324. #ifdef MS_WINDOWS
  7325. PyDoc_STRVAR(win32_startfile__doc__,
  7326. "startfile(filepath [, operation]) - Start a file with its associated\n\
  7327. application.\n\
  7328. \n\
  7329. When \"operation\" is not specified or \"open\", this acts like\n\
  7330. double-clicking the file in Explorer, or giving the file name as an\n\
  7331. argument to the DOS \"start\" command: the file is opened with whatever\n\
  7332. application (if any) its extension is associated.\n\
  7333. When another \"operation\" is given, it specifies what should be done with\n\
  7334. the file. A typical operation is \"print\".\n\
  7335. \n\
  7336. startfile returns as soon as the associated application is launched.\n\
  7337. There is no option to wait for the application to close, and no way\n\
  7338. to retrieve the application's exit status.\n\
  7339. \n\
  7340. The filepath is relative to the current directory. If you want to use\n\
  7341. an absolute path, make sure the first character is not a slash (\"/\");\n\
  7342. the underlying Win32 ShellExecute function doesn't work if it is.");
  7343. static PyObject *
  7344. win32_startfile(PyObject *self, PyObject *args)
  7345. {
  7346. char *filepath;
  7347. char *operation = NULL;
  7348. HINSTANCE rc;
  7349. #ifdef Py_WIN_WIDE_FILENAMES
  7350. if (unicode_file_names()) {
  7351. PyObject *unipath, *woperation = NULL;
  7352. if (!PyArg_ParseTuple(args, "U|s:startfile",
  7353. &unipath, &operation)) {
  7354. PyErr_Clear();
  7355. goto normal;
  7356. }
  7357. if (operation) {
  7358. woperation = PyUnicode_DecodeASCII(operation,
  7359. strlen(operation), NULL);
  7360. if (!woperation) {
  7361. PyErr_Clear();
  7362. operation = NULL;
  7363. goto normal;
  7364. }
  7365. }
  7366. Py_BEGIN_ALLOW_THREADS
  7367. rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0,
  7368. PyUnicode_AS_UNICODE(unipath),
  7369. NULL, NULL, SW_SHOWNORMAL);
  7370. Py_END_ALLOW_THREADS
  7371. Py_XDECREF(woperation);
  7372. if (rc <= (HINSTANCE)32) {
  7373. PyObject *errval = win32_error_unicode("startfile",
  7374. PyUnicode_AS_UNICODE(unipath));
  7375. return errval;
  7376. }
  7377. Py_INCREF(Py_None);
  7378. return Py_None;
  7379. }
  7380. #endif
  7381. normal:
  7382. if (!PyArg_ParseTuple(args, "et|s:startfile",
  7383. Py_FileSystemDefaultEncoding, &filepath,
  7384. &operation))
  7385. return NULL;
  7386. Py_BEGIN_ALLOW_THREADS
  7387. rc = ShellExecute((HWND)0, operation, filepath,
  7388. NULL, NULL, SW_SHOWNORMAL);
  7389. Py_END_ALLOW_THREADS
  7390. if (rc <= (HINSTANCE)32) {
  7391. PyObject *errval = win32_error("startfile", filepath);
  7392. PyMem_Free(filepath);
  7393. return errval;
  7394. }
  7395. PyMem_Free(filepath);
  7396. Py_INCREF(Py_None);
  7397. return Py_None;
  7398. }
  7399. #endif
  7400. #ifdef HAVE_GETLOADAVG
  7401. PyDoc_STRVAR(posix_getloadavg__doc__,
  7402. "getloadavg() -> (float, float, float)\n\n\
  7403. Return the number of processes in the system run queue averaged over\n\
  7404. the last 1, 5, and 15 minutes or raises OSError if the load average\n\
  7405. was unobtainable");
  7406. static PyObject *
  7407. posix_getloadavg(PyObject *self, PyObject *noargs)
  7408. {
  7409. double loadavg[3];
  7410. if (getloadavg(loadavg, 3)!=3) {
  7411. PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
  7412. return NULL;
  7413. } else
  7414. return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
  7415. }
  7416. #endif
  7417. #ifdef MS_WINDOWS
  7418. PyDoc_STRVAR(win32_urandom__doc__,
  7419. "urandom(n) -> str\n\n\
  7420. Return a string of n random bytes suitable for cryptographic use.");
  7421. typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\
  7422. LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\
  7423. DWORD dwFlags );
  7424. typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\
  7425. BYTE *pbBuffer );
  7426. static CRYPTGENRANDOM pCryptGenRandom = NULL;
  7427. /* This handle is never explicitly released. Instead, the operating
  7428. system will release it when the process terminates. */
  7429. static HCRYPTPROV hCryptProv = 0;
  7430. static PyObject*
  7431. win32_urandom(PyObject *self, PyObject *args)
  7432. {
  7433. int howMany;
  7434. PyObject* result;
  7435. /* Read arguments */
  7436. if (! PyArg_ParseTuple(args, "i:urandom", &howMany))
  7437. return NULL;
  7438. if (howMany < 0)
  7439. return PyErr_Format(PyExc_ValueError,
  7440. "negative argument not allowed");
  7441. if (hCryptProv == 0) {
  7442. HINSTANCE hAdvAPI32 = NULL;
  7443. CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL;
  7444. /* Obtain handle to the DLL containing CryptoAPI
  7445. This should not fail */
  7446. hAdvAPI32 = GetModuleHandle("advapi32.dll");
  7447. if(hAdvAPI32 == NULL)
  7448. return win32_error("GetModuleHandle", NULL);
  7449. /* Obtain pointers to the CryptoAPI functions
  7450. This will fail on some early versions of Win95 */
  7451. pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress(
  7452. hAdvAPI32,
  7453. "CryptAcquireContextA");
  7454. if (pCryptAcquireContext == NULL)
  7455. return PyErr_Format(PyExc_NotImplementedError,
  7456. "CryptAcquireContextA not found");
  7457. pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress(
  7458. hAdvAPI32, "CryptGenRandom");
  7459. if (pCryptGenRandom == NULL)
  7460. return PyErr_Format(PyExc_NotImplementedError,
  7461. "CryptGenRandom not found");
  7462. /* Acquire context */
  7463. if (! pCryptAcquireContext(&hCryptProv, NULL, NULL,
  7464. PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
  7465. return win32_error("CryptAcquireContext", NULL);
  7466. }
  7467. /* Allocate bytes */
  7468. result = PyString_FromStringAndSize(NULL, howMany);
  7469. if (result != NULL) {
  7470. /* Get random data */
  7471. memset(PyString_AS_STRING(result), 0, howMany); /* zero seed */
  7472. if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*)
  7473. PyString_AS_STRING(result))) {
  7474. Py_DECREF(result);
  7475. return win32_error("CryptGenRandom", NULL);
  7476. }
  7477. }
  7478. return result;
  7479. }
  7480. #endif
  7481. #ifdef __VMS
  7482. /* Use openssl random routine */
  7483. #include <openssl/rand.h>
  7484. PyDoc_STRVAR(vms_urandom__doc__,
  7485. "urandom(n) -> str\n\n\
  7486. Return a string of n random bytes suitable for cryptographic use.");
  7487. static PyObject*
  7488. vms_urandom(PyObject *self, PyObject *args)
  7489. {
  7490. int howMany;
  7491. PyObject* result;
  7492. /* Read arguments */
  7493. if (! PyArg_ParseTuple(args, "i:urandom", &howMany))
  7494. return NULL;
  7495. if (howMany < 0)
  7496. return PyErr_Format(PyExc_ValueError,
  7497. "negative argument not allowed");
  7498. /* Allocate bytes */
  7499. result = PyString_FromStringAndSize(NULL, howMany);
  7500. if (result != NULL) {
  7501. /* Get random data */
  7502. if (RAND_pseudo_bytes((unsigned char*)
  7503. PyString_AS_STRING(result),
  7504. howMany) < 0) {
  7505. Py_DECREF(result);
  7506. return PyErr_Format(PyExc_ValueError,
  7507. "RAND_pseudo_bytes");
  7508. }
  7509. }
  7510. return result;
  7511. }
  7512. #endif
  7513. static PyMethodDef posix_methods[] = {
  7514. {"access", posix_access, METH_VARARGS, posix_access__doc__},
  7515. #ifdef HAVE_TTYNAME
  7516. {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__},
  7517. #endif
  7518. {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__},
  7519. #ifdef HAVE_CHFLAGS
  7520. {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__},
  7521. #endif /* HAVE_CHFLAGS */
  7522. {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__},
  7523. #ifdef HAVE_FCHMOD
  7524. {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__},
  7525. #endif /* HAVE_FCHMOD */
  7526. #ifdef HAVE_CHOWN
  7527. {"chown", posix_chown, METH_VARARGS, posix_chown__doc__},
  7528. #endif /* HAVE_CHOWN */
  7529. #ifdef HAVE_LCHMOD
  7530. {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__},
  7531. #endif /* HAVE_LCHMOD */
  7532. #ifdef HAVE_FCHOWN
  7533. {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__},
  7534. #endif /* HAVE_FCHOWN */
  7535. #ifdef HAVE_LCHFLAGS
  7536. {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__},
  7537. #endif /* HAVE_LCHFLAGS */
  7538. #ifdef HAVE_LCHOWN
  7539. {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__},
  7540. #endif /* HAVE_LCHOWN */
  7541. #ifdef HAVE_CHROOT
  7542. {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__},
  7543. #endif
  7544. #ifdef HAVE_CTERMID
  7545. {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__},
  7546. #endif
  7547. #ifdef HAVE_GETCWD
  7548. {"getcwd", posix_getcwd, METH_NOARGS, posix_getcwd__doc__},
  7549. #ifdef Py_USING_UNICODE
  7550. {"getcwdu", posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__},
  7551. #endif
  7552. #endif
  7553. #ifdef HAVE_LINK
  7554. {"link", posix_link, METH_VARARGS, posix_link__doc__},
  7555. #endif /* HAVE_LINK */
  7556. {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__},
  7557. {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__},
  7558. {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__},
  7559. #ifdef HAVE_NICE
  7560. {"nice", posix_nice, METH_VARARGS, posix_nice__doc__},
  7561. #endif /* HAVE_NICE */
  7562. #ifdef HAVE_READLINK
  7563. {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__},
  7564. #endif /* HAVE_READLINK */
  7565. {"rename", posix_rename, METH_VARARGS, posix_rename__doc__},
  7566. {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
  7567. {"stat", posix_stat, METH_VARARGS, posix_stat__doc__},
  7568. {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
  7569. #ifdef HAVE_SYMLINK
  7570. {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__},
  7571. #endif /* HAVE_SYMLINK */
  7572. #ifdef HAVE_SYSTEM
  7573. {"system", posix_system, METH_VARARGS, posix_system__doc__},
  7574. #endif
  7575. {"umask", posix_umask, METH_VARARGS, posix_umask__doc__},
  7576. #ifdef HAVE_UNAME
  7577. {"uname", posix_uname, METH_NOARGS, posix_uname__doc__},
  7578. #endif /* HAVE_UNAME */
  7579. {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__},
  7580. {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__},
  7581. {"utime", posix_utime, METH_VARARGS, posix_utime__doc__},
  7582. #ifdef HAVE_TIMES
  7583. {"times", posix_times, METH_NOARGS, posix_times__doc__},
  7584. #endif /* HAVE_TIMES */
  7585. {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__},
  7586. #ifdef HAVE_EXECV
  7587. {"execv", posix_execv, METH_VARARGS, posix_execv__doc__},
  7588. {"execve", posix_execve, METH_VARARGS, posix_execve__doc__},
  7589. #endif /* HAVE_EXECV */
  7590. #ifdef HAVE_SPAWNV
  7591. {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__},
  7592. {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__},
  7593. #if defined(PYOS_OS2)
  7594. {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__},
  7595. {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__},
  7596. #endif /* PYOS_OS2 */
  7597. #endif /* HAVE_SPAWNV */
  7598. #ifdef HAVE_FORK1
  7599. {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__},
  7600. #endif /* HAVE_FORK1 */
  7601. #ifdef HAVE_FORK
  7602. {"fork", posix_fork, METH_NOARGS, posix_fork__doc__},
  7603. #endif /* HAVE_FORK */
  7604. #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
  7605. {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__},
  7606. #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */
  7607. #ifdef HAVE_FORKPTY
  7608. {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__},
  7609. #endif /* HAVE_FORKPTY */
  7610. #ifdef HAVE_GETEGID
  7611. {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__},
  7612. #endif /* HAVE_GETEGID */
  7613. #ifdef HAVE_GETEUID
  7614. {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__},
  7615. #endif /* HAVE_GETEUID */
  7616. #ifdef HAVE_GETGID
  7617. {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__},
  7618. #endif /* HAVE_GETGID */
  7619. #ifdef HAVE_GETGROUPS
  7620. {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__},
  7621. #endif
  7622. {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__},
  7623. #ifdef HAVE_GETPGRP
  7624. {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__},
  7625. #endif /* HAVE_GETPGRP */
  7626. #ifdef HAVE_GETPPID
  7627. {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__},
  7628. #endif /* HAVE_GETPPID */
  7629. #ifdef HAVE_GETUID
  7630. {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__},
  7631. #endif /* HAVE_GETUID */
  7632. #ifdef HAVE_GETLOGIN
  7633. {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__},
  7634. #endif
  7635. #ifdef HAVE_KILL
  7636. {"kill", posix_kill, METH_VARARGS, posix_kill__doc__},
  7637. #endif /* HAVE_KILL */
  7638. #ifdef HAVE_KILLPG
  7639. {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__},
  7640. #endif /* HAVE_KILLPG */
  7641. #ifdef HAVE_PLOCK
  7642. {"plock", posix_plock, METH_VARARGS, posix_plock__doc__},
  7643. #endif /* HAVE_PLOCK */
  7644. #ifdef HAVE_POPEN
  7645. {"popen", posix_popen, METH_VARARGS, posix_popen__doc__},
  7646. #ifdef MS_WINDOWS
  7647. {"popen2", win32_popen2, METH_VARARGS},
  7648. {"popen3", win32_popen3, METH_VARARGS},
  7649. {"popen4", win32_popen4, METH_VARARGS},
  7650. {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__},
  7651. #else
  7652. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  7653. {"popen2", os2emx_popen2, METH_VARARGS},
  7654. {"popen3", os2emx_popen3, METH_VARARGS},
  7655. {"popen4", os2emx_popen4, METH_VARARGS},
  7656. #endif
  7657. #endif
  7658. #endif /* HAVE_POPEN */
  7659. #ifdef HAVE_SETUID
  7660. {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__},
  7661. #endif /* HAVE_SETUID */
  7662. #ifdef HAVE_SETEUID
  7663. {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__},
  7664. #endif /* HAVE_SETEUID */
  7665. #ifdef HAVE_SETEGID
  7666. {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__},
  7667. #endif /* HAVE_SETEGID */
  7668. #ifdef HAVE_SETREUID
  7669. {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__},
  7670. #endif /* HAVE_SETREUID */
  7671. #ifdef HAVE_SETREGID
  7672. {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__},
  7673. #endif /* HAVE_SETREGID */
  7674. #ifdef HAVE_SETGID
  7675. {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__},
  7676. #endif /* HAVE_SETGID */
  7677. #ifdef HAVE_SETGROUPS
  7678. {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__},
  7679. #endif /* HAVE_SETGROUPS */
  7680. #ifdef HAVE_GETPGID
  7681. {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__},
  7682. #endif /* HAVE_GETPGID */
  7683. #ifdef HAVE_SETPGRP
  7684. {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__},
  7685. #endif /* HAVE_SETPGRP */
  7686. #ifdef HAVE_WAIT
  7687. {"wait", posix_wait, METH_NOARGS, posix_wait__doc__},
  7688. #endif /* HAVE_WAIT */
  7689. #ifdef HAVE_WAIT3
  7690. {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__},
  7691. #endif /* HAVE_WAIT3 */
  7692. #ifdef HAVE_WAIT4
  7693. {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__},
  7694. #endif /* HAVE_WAIT4 */
  7695. #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT)
  7696. {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__},
  7697. #endif /* HAVE_WAITPID */
  7698. #ifdef HAVE_GETSID
  7699. {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__},
  7700. #endif /* HAVE_GETSID */
  7701. #ifdef HAVE_SETSID
  7702. {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__},
  7703. #endif /* HAVE_SETSID */
  7704. #ifdef HAVE_SETPGID
  7705. {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__},
  7706. #endif /* HAVE_SETPGID */
  7707. #ifdef HAVE_TCGETPGRP
  7708. {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__},
  7709. #endif /* HAVE_TCGETPGRP */
  7710. #ifdef HAVE_TCSETPGRP
  7711. {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__},
  7712. #endif /* HAVE_TCSETPGRP */
  7713. {"open", posix_open, METH_VARARGS, posix_open__doc__},
  7714. {"close", posix_close, METH_VARARGS, posix_close__doc__},
  7715. {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__},
  7716. {"dup", posix_dup, METH_VARARGS, posix_dup__doc__},
  7717. {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__},
  7718. {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__},
  7719. {"read", posix_read, METH_VARARGS, posix_read__doc__},
  7720. {"write", posix_write, METH_VARARGS, posix_write__doc__},
  7721. {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__},
  7722. {"fdopen", posix_fdopen, METH_VARARGS, posix_fdopen__doc__},
  7723. {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__},
  7724. #ifdef HAVE_PIPE
  7725. {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__},
  7726. #endif
  7727. #ifdef HAVE_MKFIFO
  7728. {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__},
  7729. #endif
  7730. #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
  7731. {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__},
  7732. #endif
  7733. #ifdef HAVE_DEVICE_MACROS
  7734. {"major", posix_major, METH_VARARGS, posix_major__doc__},
  7735. {"minor", posix_minor, METH_VARARGS, posix_minor__doc__},
  7736. {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__},
  7737. #endif
  7738. #ifdef HAVE_FTRUNCATE
  7739. {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__},
  7740. #endif
  7741. #ifdef HAVE_PUTENV
  7742. {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__},
  7743. #endif
  7744. #ifdef HAVE_UNSETENV
  7745. {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__},
  7746. #endif
  7747. {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__},
  7748. #ifdef HAVE_FCHDIR
  7749. {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__},
  7750. #endif
  7751. #ifdef HAVE_FSYNC
  7752. {"fsync", posix_fsync, METH_O, posix_fsync__doc__},
  7753. #endif
  7754. #ifdef HAVE_FDATASYNC
  7755. {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__},
  7756. #endif
  7757. #ifdef HAVE_SYS_WAIT_H
  7758. #ifdef WCOREDUMP
  7759. {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__},
  7760. #endif /* WCOREDUMP */
  7761. #ifdef WIFCONTINUED
  7762. {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__},
  7763. #endif /* WIFCONTINUED */
  7764. #ifdef WIFSTOPPED
  7765. {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__},
  7766. #endif /* WIFSTOPPED */
  7767. #ifdef WIFSIGNALED
  7768. {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__},
  7769. #endif /* WIFSIGNALED */
  7770. #ifdef WIFEXITED
  7771. {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__},
  7772. #endif /* WIFEXITED */
  7773. #ifdef WEXITSTATUS
  7774. {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__},
  7775. #endif /* WEXITSTATUS */
  7776. #ifdef WTERMSIG
  7777. {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__},
  7778. #endif /* WTERMSIG */
  7779. #ifdef WSTOPSIG
  7780. {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__},
  7781. #endif /* WSTOPSIG */
  7782. #endif /* HAVE_SYS_WAIT_H */
  7783. #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
  7784. {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__},
  7785. #endif
  7786. #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
  7787. {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__},
  7788. #endif
  7789. #ifdef HAVE_TMPFILE
  7790. {"tmpfile", posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__},
  7791. #endif
  7792. #ifdef HAVE_TEMPNAM
  7793. {"tempnam", posix_tempnam, METH_VARARGS, posix_tempnam__doc__},
  7794. #endif
  7795. #ifdef HAVE_TMPNAM
  7796. {"tmpnam", posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__},
  7797. #endif
  7798. #ifdef HAVE_CONFSTR
  7799. {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__},
  7800. #endif
  7801. #ifdef HAVE_SYSCONF
  7802. {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__},
  7803. #endif
  7804. #ifdef HAVE_FPATHCONF
  7805. {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__},
  7806. #endif
  7807. #ifdef HAVE_PATHCONF
  7808. {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__},
  7809. #endif
  7810. {"abort", posix_abort, METH_NOARGS, posix_abort__doc__},
  7811. #ifdef MS_WINDOWS
  7812. {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL},
  7813. #endif
  7814. #ifdef HAVE_GETLOADAVG
  7815. {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__},
  7816. #endif
  7817. #ifdef MS_WINDOWS
  7818. {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__},
  7819. #endif
  7820. #ifdef __VMS
  7821. {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__},
  7822. #endif
  7823. {NULL, NULL} /* Sentinel */
  7824. };
  7825. static int
  7826. ins(PyObject *module, char *symbol, long value)
  7827. {
  7828. return PyModule_AddIntConstant(module, symbol, value);
  7829. }
  7830. #if defined(PYOS_OS2)
  7831. /* Insert Platform-Specific Constant Values (Strings & Numbers) of Common Use */
  7832. static int insertvalues(PyObject *module)
  7833. {
  7834. APIRET rc;
  7835. ULONG values[QSV_MAX+1];
  7836. PyObject *v;
  7837. char *ver, tmp[50];
  7838. Py_BEGIN_ALLOW_THREADS
  7839. rc = DosQuerySysInfo(1L, QSV_MAX, &values[1], sizeof(ULONG) * QSV_MAX);
  7840. Py_END_ALLOW_THREADS
  7841. if (rc != NO_ERROR) {
  7842. os2_error(rc);
  7843. return -1;
  7844. }
  7845. if (ins(module, "meminstalled", values[QSV_TOTPHYSMEM])) return -1;
  7846. if (ins(module, "memkernel", values[QSV_TOTRESMEM])) return -1;
  7847. if (ins(module, "memvirtual", values[QSV_TOTAVAILMEM])) return -1;
  7848. if (ins(module, "maxpathlen", values[QSV_MAX_PATH_LENGTH])) return -1;
  7849. if (ins(module, "maxnamelen", values[QSV_MAX_COMP_LENGTH])) return -1;
  7850. if (ins(module, "revision", values[QSV_VERSION_REVISION])) return -1;
  7851. if (ins(module, "timeslice", values[QSV_MIN_SLICE])) return -1;
  7852. switch (values[QSV_VERSION_MINOR]) {
  7853. case 0: ver = "2.00"; break;
  7854. case 10: ver = "2.10"; break;
  7855. case 11: ver = "2.11"; break;
  7856. case 30: ver = "3.00"; break;
  7857. case 40: ver = "4.00"; break;
  7858. case 50: ver = "5.00"; break;
  7859. default:
  7860. PyOS_snprintf(tmp, sizeof(tmp),
  7861. "%d-%d", values[QSV_VERSION_MAJOR],
  7862. values[QSV_VERSION_MINOR]);
  7863. ver = &tmp[0];
  7864. }
  7865. /* Add Indicator of the Version of the Operating System */
  7866. if (PyModule_AddStringConstant(module, "version", tmp) < 0)
  7867. return -1;
  7868. /* Add Indicator of Which Drive was Used to Boot the System */
  7869. tmp[0] = 'A' + values[QSV_BOOT_DRIVE] - 1;
  7870. tmp[1] = ':';
  7871. tmp[2] = '\0';
  7872. return PyModule_AddStringConstant(module, "bootdrive", tmp);
  7873. }
  7874. #endif
  7875. static int
  7876. all_ins(PyObject *d)
  7877. {
  7878. #ifdef F_OK
  7879. if (ins(d, "F_OK", (long)F_OK)) return -1;
  7880. #endif
  7881. #ifdef R_OK
  7882. if (ins(d, "R_OK", (long)R_OK)) return -1;
  7883. #endif
  7884. #ifdef W_OK
  7885. if (ins(d, "W_OK", (long)W_OK)) return -1;
  7886. #endif
  7887. #ifdef X_OK
  7888. if (ins(d, "X_OK", (long)X_OK)) return -1;
  7889. #endif
  7890. #ifdef NGROUPS_MAX
  7891. if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1;
  7892. #endif
  7893. #ifdef TMP_MAX
  7894. if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1;
  7895. #endif
  7896. #ifdef WCONTINUED
  7897. if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1;
  7898. #endif
  7899. #ifdef WNOHANG
  7900. if (ins(d, "WNOHANG", (long)WNOHANG)) return -1;
  7901. #endif
  7902. #ifdef WUNTRACED
  7903. if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1;
  7904. #endif
  7905. #ifdef O_RDONLY
  7906. if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1;
  7907. #endif
  7908. #ifdef O_WRONLY
  7909. if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1;
  7910. #endif
  7911. #ifdef O_RDWR
  7912. if (ins(d, "O_RDWR", (long)O_RDWR)) return -1;
  7913. #endif
  7914. #ifdef O_NDELAY
  7915. if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1;
  7916. #endif
  7917. #ifdef O_NONBLOCK
  7918. if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1;
  7919. #endif
  7920. #ifdef O_APPEND
  7921. if (ins(d, "O_APPEND", (long)O_APPEND)) return -1;
  7922. #endif
  7923. #ifdef O_DSYNC
  7924. if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1;
  7925. #endif
  7926. #ifdef O_RSYNC
  7927. if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1;
  7928. #endif
  7929. #ifdef O_SYNC
  7930. if (ins(d, "O_SYNC", (long)O_SYNC)) return -1;
  7931. #endif
  7932. #ifdef O_NOCTTY
  7933. if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1;
  7934. #endif
  7935. #ifdef O_CREAT
  7936. if (ins(d, "O_CREAT", (long)O_CREAT)) return -1;
  7937. #endif
  7938. #ifdef O_EXCL
  7939. if (ins(d, "O_EXCL", (long)O_EXCL)) return -1;
  7940. #endif
  7941. #ifdef O_TRUNC
  7942. if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1;
  7943. #endif
  7944. #ifdef O_BINARY
  7945. if (ins(d, "O_BINARY", (long)O_BINARY)) return -1;
  7946. #endif
  7947. #ifdef O_TEXT
  7948. if (ins(d, "O_TEXT", (long)O_TEXT)) return -1;
  7949. #endif
  7950. #ifdef O_LARGEFILE
  7951. if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1;
  7952. #endif
  7953. #ifdef O_SHLOCK
  7954. if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1;
  7955. #endif
  7956. #ifdef O_EXLOCK
  7957. if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1;
  7958. #endif
  7959. /* MS Windows */
  7960. #ifdef O_NOINHERIT
  7961. /* Don't inherit in child processes. */
  7962. if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1;
  7963. #endif
  7964. #ifdef _O_SHORT_LIVED
  7965. /* Optimize for short life (keep in memory). */
  7966. /* MS forgot to define this one with a non-underscore form too. */
  7967. if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1;
  7968. #endif
  7969. #ifdef O_TEMPORARY
  7970. /* Automatically delete when last handle is closed. */
  7971. if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1;
  7972. #endif
  7973. #ifdef O_RANDOM
  7974. /* Optimize for random access. */
  7975. if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1;
  7976. #endif
  7977. #ifdef O_SEQUENTIAL
  7978. /* Optimize for sequential access. */
  7979. if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1;
  7980. #endif
  7981. /* GNU extensions. */
  7982. #ifdef O_ASYNC
  7983. /* Send a SIGIO signal whenever input or output
  7984. becomes available on file descriptor */
  7985. if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1;
  7986. #endif
  7987. #ifdef O_DIRECT
  7988. /* Direct disk access. */
  7989. if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1;
  7990. #endif
  7991. #ifdef O_DIRECTORY
  7992. /* Must be a directory. */
  7993. if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1;
  7994. #endif
  7995. #ifdef O_NOFOLLOW
  7996. /* Do not follow links. */
  7997. if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1;
  7998. #endif
  7999. #ifdef O_NOATIME
  8000. /* Do not update the access time. */
  8001. if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1;
  8002. #endif
  8003. /* These come from sysexits.h */
  8004. #ifdef EX_OK
  8005. if (ins(d, "EX_OK", (long)EX_OK)) return -1;
  8006. #endif /* EX_OK */
  8007. #ifdef EX_USAGE
  8008. if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1;
  8009. #endif /* EX_USAGE */
  8010. #ifdef EX_DATAERR
  8011. if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1;
  8012. #endif /* EX_DATAERR */
  8013. #ifdef EX_NOINPUT
  8014. if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1;
  8015. #endif /* EX_NOINPUT */
  8016. #ifdef EX_NOUSER
  8017. if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1;
  8018. #endif /* EX_NOUSER */
  8019. #ifdef EX_NOHOST
  8020. if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1;
  8021. #endif /* EX_NOHOST */
  8022. #ifdef EX_UNAVAILABLE
  8023. if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1;
  8024. #endif /* EX_UNAVAILABLE */
  8025. #ifdef EX_SOFTWARE
  8026. if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1;
  8027. #endif /* EX_SOFTWARE */
  8028. #ifdef EX_OSERR
  8029. if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1;
  8030. #endif /* EX_OSERR */
  8031. #ifdef EX_OSFILE
  8032. if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1;
  8033. #endif /* EX_OSFILE */
  8034. #ifdef EX_CANTCREAT
  8035. if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1;
  8036. #endif /* EX_CANTCREAT */
  8037. #ifdef EX_IOERR
  8038. if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1;
  8039. #endif /* EX_IOERR */
  8040. #ifdef EX_TEMPFAIL
  8041. if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1;
  8042. #endif /* EX_TEMPFAIL */
  8043. #ifdef EX_PROTOCOL
  8044. if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1;
  8045. #endif /* EX_PROTOCOL */
  8046. #ifdef EX_NOPERM
  8047. if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1;
  8048. #endif /* EX_NOPERM */
  8049. #ifdef EX_CONFIG
  8050. if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1;
  8051. #endif /* EX_CONFIG */
  8052. #ifdef EX_NOTFOUND
  8053. if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1;
  8054. #endif /* EX_NOTFOUND */
  8055. #ifdef HAVE_SPAWNV
  8056. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  8057. if (ins(d, "P_WAIT", (long)P_WAIT)) return -1;
  8058. if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1;
  8059. if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1;
  8060. if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1;
  8061. if (ins(d, "P_SESSION", (long)P_SESSION)) return -1;
  8062. if (ins(d, "P_DETACH", (long)P_DETACH)) return -1;
  8063. if (ins(d, "P_PM", (long)P_PM)) return -1;
  8064. if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1;
  8065. if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1;
  8066. if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1;
  8067. if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1;
  8068. if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1;
  8069. if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1;
  8070. if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1;
  8071. if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1;
  8072. if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1;
  8073. if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1;
  8074. if (ins(d, "P_TILDE", (long)P_TILDE)) return -1;
  8075. if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1;
  8076. if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1;
  8077. #else
  8078. if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1;
  8079. if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1;
  8080. if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1;
  8081. if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1;
  8082. if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1;
  8083. #endif
  8084. #endif
  8085. #if defined(PYOS_OS2)
  8086. if (insertvalues(d)) return -1;
  8087. #endif
  8088. return 0;
  8089. }
  8090. #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__)) && !defined(__QNX__)
  8091. #define INITFUNC initnt
  8092. #define MODNAME "nt"
  8093. #elif defined(PYOS_OS2)
  8094. #define INITFUNC initos2
  8095. #define MODNAME "os2"
  8096. #else
  8097. #define INITFUNC initposix
  8098. #define MODNAME "posix"
  8099. #endif
  8100. PyMODINIT_FUNC
  8101. INITFUNC(void)
  8102. {
  8103. PyObject *m, *v;
  8104. m = Py_InitModule3(MODNAME,
  8105. posix_methods,
  8106. posix__doc__);
  8107. if (m == NULL)
  8108. return;
  8109. /* Initialize environ dictionary */
  8110. v = convertenviron();
  8111. Py_XINCREF(v);
  8112. if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
  8113. return;
  8114. Py_DECREF(v);
  8115. if (all_ins(m))
  8116. return;
  8117. if (setup_confname_tables(m))
  8118. return;
  8119. Py_INCREF(PyExc_OSError);
  8120. PyModule_AddObject(m, "error", PyExc_OSError);
  8121. #ifdef HAVE_PUTENV
  8122. if (posix_putenv_garbage == NULL)
  8123. posix_putenv_garbage = PyDict_New();
  8124. #endif
  8125. if (!initialized) {
  8126. stat_result_desc.name = MODNAME ".stat_result";
  8127. stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
  8128. stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
  8129. stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
  8130. PyStructSequence_InitType(&StatResultType, &stat_result_desc);
  8131. structseq_new = StatResultType.tp_new;
  8132. StatResultType.tp_new = statresult_new;
  8133. statvfs_result_desc.name = MODNAME ".statvfs_result";
  8134. PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc);
  8135. #ifdef NEED_TICKS_PER_SECOND
  8136. # if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
  8137. ticks_per_second = sysconf(_SC_CLK_TCK);
  8138. # elif defined(HZ)
  8139. ticks_per_second = HZ;
  8140. # else
  8141. ticks_per_second = 60; /* magic fallback value; may be bogus */
  8142. # endif
  8143. #endif
  8144. }
  8145. Py_INCREF((PyObject*) &StatResultType);
  8146. PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);
  8147. Py_INCREF((PyObject*) &StatVFSResultType);
  8148. PyModule_AddObject(m, "statvfs_result",
  8149. (PyObject*) &StatVFSResultType);
  8150. initialized = 1;
  8151. #ifdef __APPLE__
  8152. /*
  8153. * Step 2 of weak-linking support on Mac OS X.
  8154. *
  8155. * The code below removes functions that are not available on the
  8156. * currently active platform.
  8157. *
  8158. * This block allow one to use a python binary that was build on
  8159. * OSX 10.4 on OSX 10.3, without loosing access to new APIs on
  8160. * OSX 10.4.
  8161. */
  8162. #ifdef HAVE_FSTATVFS
  8163. if (fstatvfs == NULL) {
  8164. if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
  8165. return;
  8166. }
  8167. }
  8168. #endif /* HAVE_FSTATVFS */
  8169. #ifdef HAVE_STATVFS
  8170. if (statvfs == NULL) {
  8171. if (PyObject_DelAttrString(m, "statvfs") == -1) {
  8172. return;
  8173. }
  8174. }
  8175. #endif /* HAVE_STATVFS */
  8176. # ifdef HAVE_LCHOWN
  8177. if (lchown == NULL) {
  8178. if (PyObject_DelAttrString(m, "lchown") == -1) {
  8179. return;
  8180. }
  8181. }
  8182. #endif /* HAVE_LCHOWN */
  8183. #endif /* __APPLE__ */
  8184. }
  8185. #ifdef __cplusplus
  8186. }
  8187. #endif