blob: e5c2a9cfc1eccbe5f6f22c69849f8ae96eabf50e [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* POSIX module implementation */
3
Jesus Ceaab70e2a2012-10-05 01:48:08 +02004/* This file is also used for Windows NT/MS-Win. In that case the
5 module actually calls itself 'nt', not 'posix', and a few
Andrew MacIntyre6c73af22002-03-03 03:07:07 +00006 functions are either unimplemented or implemented differently. The source
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00007 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
Guido van Rossumad0ee831995-03-01 10:34:45 +00008 of the compiler used. Different compilers define their own feature
Victor Stinnerf427a142014-10-22 12:33:23 +02009 test macro, e.g. '_MSC_VER'. */
Guido van Rossumad0ee831995-03-01 10:34:45 +000010
Larry Hastings31826802013-10-19 00:09:25 -070011
12
Thomas Wouters477c8d52006-05-27 19:21:47 +000013#ifdef __APPLE__
14 /*
Victor Stinner8c62be82010-05-06 00:08:46 +000015 * Step 1 of support for weak-linking a number of symbols existing on
Thomas Wouters477c8d52006-05-27 19:21:47 +000016 * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
17 * at the end of this file for more information.
18 */
19# pragma weak lchown
20# pragma weak statvfs
21# pragma weak fstatvfs
22
23#endif /* __APPLE__ */
24
Thomas Wouters68bc4f92006-03-01 01:05:10 +000025#define PY_SSIZE_T_CLEAN
26
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000027#include "Python.h"
Antoine Pitrou346cbd32017-05-27 17:50:54 +020028#include "pythread.h"
Victor Stinner6036e442015-03-08 01:58:04 +010029#include "structmember.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020030#ifndef MS_WINDOWS
31#include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010032#else
33#include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020034#endif
Victor Stinner621cebe2018-11-12 16:53:38 +010035#include "pycore_pystate.h"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000036
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020037/* On android API level 21, 'AT_EACCESS' is not declared although
38 * HAVE_FACCESSAT is defined. */
39#ifdef __ANDROID__
40#undef HAVE_FACCESSAT
41#endif
42
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000043#include <stdio.h> /* needed for ctermid() */
44
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000045#ifdef __cplusplus
46extern "C" {
47#endif
48
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000049PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000050"This module provides access to operating system functionality that is\n\
51standardized by the C Standard and the POSIX standard (a thinly\n\
52disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000053corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000055
Ross Lagerwall4d076da2011-03-18 06:56:53 +020056#ifdef HAVE_SYS_UIO_H
57#include <sys/uio.h>
58#endif
59
Christian Heimes75b96182017-09-05 15:53:09 +020060#ifdef HAVE_SYS_SYSMACROS_H
61/* GNU C Library: major(), minor(), makedev() */
62#include <sys/sysmacros.h>
63#endif
64
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000066#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067#endif /* HAVE_SYS_TYPES_H */
68
69#ifdef HAVE_SYS_STAT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000070#include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000072
Guido van Rossum36bc6801995-06-14 22:54:23 +000073#ifdef HAVE_SYS_WAIT_H
Victor Stinner8c62be82010-05-06 00:08:46 +000074#include <sys/wait.h> /* For WNOHANG */
Guido van Rossum36bc6801995-06-14 22:54:23 +000075#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000076
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077#ifdef HAVE_SIGNAL_H
Guido van Rossuma376cc51996-12-05 23:43:35 +000078#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000080
Guido van Rossumb6775db1994-08-01 11:34:53 +000081#ifdef HAVE_FCNTL_H
82#include <fcntl.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +000083#endif /* HAVE_FCNTL_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +000084
Guido van Rossuma6535fd2001-10-18 19:44:10 +000085#ifdef HAVE_GRP_H
86#include <grp.h>
87#endif
88
Barry Warsaw5676bd12003-01-07 20:57:09 +000089#ifdef HAVE_SYSEXITS_H
90#include <sysexits.h>
91#endif /* HAVE_SYSEXITS_H */
92
Anthony Baxter8a560de2004-10-13 15:30:56 +000093#ifdef HAVE_SYS_LOADAVG_H
94#include <sys/loadavg.h>
95#endif
96
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000097#ifdef HAVE_SYS_SENDFILE_H
98#include <sys/sendfile.h>
99#endif
100
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200101#if defined(__APPLE__)
102#include <copyfile.h>
103#endif
104
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500105#ifdef HAVE_SCHED_H
106#include <sched.h>
107#endif
108
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500109#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500110#undef HAVE_SCHED_SETAFFINITY
111#endif
112
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200113#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Benjamin Peterson9428d532011-09-14 11:45:52 -0400114#define USE_XATTRS
115#endif
116
117#ifdef USE_XATTRS
Benjamin Petersonb77fe172011-09-13 17:20:47 -0400118#include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400119#endif
120
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000121#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
122#ifdef HAVE_SYS_SOCKET_H
123#include <sys/socket.h>
124#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000125#endif
126
Victor Stinner8b905bd2011-10-25 13:34:04 +0200127#ifdef HAVE_DLFCN_H
128#include <dlfcn.h>
129#endif
130
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200131#ifdef __hpux
132#include <sys/mpctl.h>
133#endif
134
135#if defined(__DragonFly__) || \
136 defined(__OpenBSD__) || \
137 defined(__FreeBSD__) || \
138 defined(__NetBSD__) || \
139 defined(__APPLE__)
140#include <sys/sysctl.h>
141#endif
142
Victor Stinner9b1f4742016-09-06 16:18:52 -0700143#ifdef HAVE_LINUX_RANDOM_H
144# include <linux/random.h>
145#endif
146#ifdef HAVE_GETRANDOM_SYSCALL
147# include <sys/syscall.h>
148#endif
149
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100150#if defined(MS_WINDOWS)
151# define TERMSIZE_USE_CONIO
152#elif defined(HAVE_SYS_IOCTL_H)
153# include <sys/ioctl.h>
154# if defined(HAVE_TERMIOS_H)
155# include <termios.h>
156# endif
157# if defined(TIOCGWINSZ)
158# define TERMSIZE_USE_IOCTL
159# endif
160#endif /* MS_WINDOWS */
161
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000162/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000163/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000164#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000165#define HAVE_OPENDIR 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000166#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000167#include <process.h>
168#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000169#ifdef _MSC_VER /* Microsoft compiler */
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000170#define HAVE_GETPPID 1
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000171#define HAVE_GETLOGIN 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000172#define HAVE_SPAWNV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000173#define HAVE_EXECV 1
Steve Dowercc16be82016-09-08 10:35:16 -0700174#define HAVE_WSPAWNV 1
175#define HAVE_WEXECV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000176#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000177#define HAVE_SYSTEM 1
178#define HAVE_CWAIT 1
179#define HAVE_FSYNC 1
Tim Peters11b23062003-04-23 02:39:17 +0000180#define fsync _commit
Andrew MacIntyre6c73af22002-03-03 03:07:07 +0000181#else
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000182/* Unix functions that the configure script doesn't check for */
183#define HAVE_EXECV 1
184#define HAVE_FORK 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000185#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
Guido van Rossum2242f2f2001-04-11 20:58:20 +0000186#define HAVE_FORK1 1
187#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000188#define HAVE_GETEGID 1
189#define HAVE_GETEUID 1
190#define HAVE_GETGID 1
191#define HAVE_GETPPID 1
192#define HAVE_GETUID 1
193#define HAVE_KILL 1
194#define HAVE_OPENDIR 1
195#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000196#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000197#define HAVE_WAIT 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000198#define HAVE_TTYNAME 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000199#endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000200#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000201
Victor Stinnera2f7c002012-02-08 03:36:25 +0100202
Larry Hastings61272b72014-01-07 12:41:53 -0800203/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000204# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800205module os
Larry Hastings61272b72014-01-07 12:41:53 -0800206[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000207/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100208
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000209#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000210
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000211#if defined(__sgi)&&_COMPILER_VERSION>=700
212/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
213 (default) */
214extern char *ctermid_r(char *);
215#endif
216
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000217#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000219#ifdef HAVE_POSIX_SPAWN
220#include <spawn.h>
221#endif
222
Guido van Rossumb6775db1994-08-01 11:34:53 +0000223#ifdef HAVE_UTIME_H
224#include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000225#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000226
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000227#ifdef HAVE_SYS_UTIME_H
228#include <sys/utime.h>
229#define HAVE_UTIME_H /* pretend we do for the rest of this file */
230#endif /* HAVE_SYS_UTIME_H */
231
Guido van Rossumb6775db1994-08-01 11:34:53 +0000232#ifdef HAVE_SYS_TIMES_H
233#include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000234#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000235
236#ifdef HAVE_SYS_PARAM_H
237#include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000238#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000239
240#ifdef HAVE_SYS_UTSNAME_H
241#include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000242#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000243
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000244#ifdef HAVE_DIRENT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000245#include <dirent.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000246#define NAMLEN(dirent) strlen((dirent)->d_name)
247#else
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000248#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000249#include <direct.h>
250#define NAMLEN(dirent) strlen((dirent)->d_name)
251#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000252#define dirent direct
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000253#define NAMLEN(dirent) (dirent)->d_namlen
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000254#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000255#ifdef HAVE_SYS_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000256#include <sys/ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000257#endif
258#ifdef HAVE_SYS_DIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000259#include <sys/dir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000260#endif
261#ifdef HAVE_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000262#include <ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000263#endif
264#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000265
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000266#ifdef _MSC_VER
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000267#ifdef HAVE_DIRECT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000268#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000269#endif
270#ifdef HAVE_IO_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000271#include <io.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000272#endif
273#ifdef HAVE_PROCESS_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000274#include <process.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000275#endif
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000276#ifndef IO_REPARSE_TAG_SYMLINK
Amaury Forgeot d'Arc844807e2010-08-16 22:16:51 +0000277#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000278#endif
Tim Golden0321cf22014-05-05 19:46:17 +0100279#ifndef IO_REPARSE_TAG_MOUNT_POINT
280#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
281#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000282#include "osdefs.h"
Kristján Valur Jónssonf64e6512009-04-13 10:16:14 +0000283#include <malloc.h>
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284#include <windows.h>
Victor Stinner8c62be82010-05-06 00:08:46 +0000285#include <shellapi.h> /* for ShellExecute() */
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000286#include <lmcons.h> /* for UNLEN */
Brian Curtin52173d42010-12-02 18:29:18 +0000287#ifdef SE_CREATE_SYMBOLIC_LINK_NAME /* Available starting with Vista */
288#define HAVE_SYMLINK
Brian Curtin3b4499c2010-12-28 14:31:47 +0000289static int win32_can_symlink = 0;
Brian Curtin52173d42010-12-02 18:29:18 +0000290#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000291#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000292
Tim Petersbc2e10e2002-03-03 23:17:02 +0000293#ifndef MAXPATHLEN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000294#if defined(PATH_MAX) && PATH_MAX > 1024
295#define MAXPATHLEN PATH_MAX
296#else
Tim Petersbc2e10e2002-03-03 23:17:02 +0000297#define MAXPATHLEN 1024
Thomas Wouters477c8d52006-05-27 19:21:47 +0000298#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000299#endif /* MAXPATHLEN */
300
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000301#ifdef UNION_WAIT
302/* Emulate some macros on systems that have a union instead of macros */
303
304#ifndef WIFEXITED
305#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
306#endif
307
308#ifndef WEXITSTATUS
309#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
310#endif
311
312#ifndef WTERMSIG
313#define WTERMSIG(u_wait) ((u_wait).w_termsig)
314#endif
315
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000316#define WAIT_TYPE union wait
317#define WAIT_STATUS_INT(s) (s.w_status)
318
319#else /* !UNION_WAIT */
320#define WAIT_TYPE int
321#define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000322#endif /* UNION_WAIT */
323
Greg Wardb48bc172000-03-01 21:51:56 +0000324/* Don't use the "_r" form if we don't need it (also, won't have a
325 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200326#if defined(HAVE_CTERMID_R)
Greg Wardb48bc172000-03-01 21:51:56 +0000327#define USE_CTERMID_R
328#endif
329
Fred Drake699f3522000-06-29 21:12:41 +0000330/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000331#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000332#undef FSTAT
333#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200334#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +0000335# define STAT win32_stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700336# define LSTAT win32_lstat
Victor Stinnere134a7f2015-03-30 10:09:31 +0200337# define FSTAT _Py_fstat_noraise
Steve Dowerf2f373f2015-02-21 08:44:05 -0800338# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000339#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000340# define STAT stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700341# define LSTAT lstat
Victor Stinner8c62be82010-05-06 00:08:46 +0000342# define FSTAT fstat
343# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000344#endif
345
Tim Peters11b23062003-04-23 02:39:17 +0000346#if defined(MAJOR_IN_MKDEV)
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000347#include <sys/mkdev.h>
348#else
349#if defined(MAJOR_IN_SYSMACROS)
350#include <sys/sysmacros.h>
351#endif
Neal Norwitz3d949422002-04-20 13:46:43 +0000352#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
353#include <sys/mkdev.h>
354#endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000355#endif
Fred Drake699f3522000-06-29 21:12:41 +0000356
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200357#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +0100358#define INITFUNC PyInit_nt
359#define MODNAME "nt"
360#else
361#define INITFUNC PyInit_posix
362#define MODNAME "posix"
363#endif
364
jcea6c51d512018-01-28 14:00:08 +0100365#if defined(__sun)
366/* Something to implement in autoconf, not present in autoconf 2.69 */
367#define HAVE_STRUCT_STAT_ST_FSTYPE 1
368#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200369
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800370#ifdef _Py_MEMORY_SANITIZER
371# include <sanitizer/msan_interface.h>
372#endif
373
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200374#ifdef HAVE_FORK
375static void
376run_at_forkers(PyObject *lst, int reverse)
377{
378 Py_ssize_t i;
379 PyObject *cpy;
380
381 if (lst != NULL) {
382 assert(PyList_CheckExact(lst));
383
384 /* Use a list copy in case register_at_fork() is called from
385 * one of the callbacks.
386 */
387 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
388 if (cpy == NULL)
389 PyErr_WriteUnraisable(lst);
390 else {
391 if (reverse)
392 PyList_Reverse(cpy);
393 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
394 PyObject *func, *res;
395 func = PyList_GET_ITEM(cpy, i);
396 res = PyObject_CallObject(func, NULL);
397 if (res == NULL)
398 PyErr_WriteUnraisable(func);
399 else
400 Py_DECREF(res);
401 }
402 Py_DECREF(cpy);
403 }
404 }
405}
406
407void
408PyOS_BeforeFork(void)
409{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200410 run_at_forkers(_PyInterpreterState_Get()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200411
412 _PyImport_AcquireLock();
413}
414
415void
416PyOS_AfterFork_Parent(void)
417{
418 if (_PyImport_ReleaseLock() <= 0)
419 Py_FatalError("failed releasing import lock after fork");
420
Victor Stinnercaba55b2018-08-03 15:33:52 +0200421 run_at_forkers(_PyInterpreterState_Get()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200422}
423
424void
425PyOS_AfterFork_Child(void)
426{
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200427 _PyGILState_Reinit();
Eric Snow59032962018-09-14 14:17:20 -0700428 _PyInterpreterState_DeleteExceptMain();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200429 PyEval_ReInitThreads();
430 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200431 _PySignal_AfterFork();
432
Victor Stinnercaba55b2018-08-03 15:33:52 +0200433 run_at_forkers(_PyInterpreterState_Get()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200434}
435
436static int
437register_at_forker(PyObject **lst, PyObject *func)
438{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700439 if (func == NULL) /* nothing to register? do nothing. */
440 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200441 if (*lst == NULL) {
442 *lst = PyList_New(0);
443 if (*lst == NULL)
444 return -1;
445 }
446 return PyList_Append(*lst, func);
447}
448#endif
449
450/* Legacy wrapper */
451void
452PyOS_AfterFork(void)
453{
454#ifdef HAVE_FORK
455 PyOS_AfterFork_Child();
456#endif
457}
458
459
Victor Stinner6036e442015-03-08 01:58:04 +0100460#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200461/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700462void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
463void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200464 ULONG, struct _Py_stat_struct *);
465#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700466
467#ifdef MS_WINDOWS
468static int
469win32_warn_bytes_api()
470{
471 return PyErr_WarnEx(PyExc_DeprecationWarning,
472 "The Windows bytes API has been deprecated, "
473 "use Unicode filenames instead",
474 1);
475}
476#endif
477
478
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200479#ifndef MS_WINDOWS
480PyObject *
481_PyLong_FromUid(uid_t uid)
482{
483 if (uid == (uid_t)-1)
484 return PyLong_FromLong(-1);
485 return PyLong_FromUnsignedLong(uid);
486}
487
488PyObject *
489_PyLong_FromGid(gid_t gid)
490{
491 if (gid == (gid_t)-1)
492 return PyLong_FromLong(-1);
493 return PyLong_FromUnsignedLong(gid);
494}
495
496int
497_Py_Uid_Converter(PyObject *obj, void *p)
498{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700499 uid_t uid;
500 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200501 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200502 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700503 unsigned long uresult;
504
505 index = PyNumber_Index(obj);
506 if (index == NULL) {
507 PyErr_Format(PyExc_TypeError,
508 "uid should be integer, not %.200s",
509 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200510 return 0;
511 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700512
513 /*
514 * Handling uid_t is complicated for two reasons:
515 * * Although uid_t is (always?) unsigned, it still
516 * accepts -1.
517 * * We don't know its size in advance--it may be
518 * bigger than an int, or it may be smaller than
519 * a long.
520 *
521 * So a bit of defensive programming is in order.
522 * Start with interpreting the value passed
523 * in as a signed long and see if it works.
524 */
525
526 result = PyLong_AsLongAndOverflow(index, &overflow);
527
528 if (!overflow) {
529 uid = (uid_t)result;
530
531 if (result == -1) {
532 if (PyErr_Occurred())
533 goto fail;
534 /* It's a legitimate -1, we're done. */
535 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200536 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700537
538 /* Any other negative number is disallowed. */
539 if (result < 0)
540 goto underflow;
541
542 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200543 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700544 (long)uid != result)
545 goto underflow;
546 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200547 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700548
549 if (overflow < 0)
550 goto underflow;
551
552 /*
553 * Okay, the value overflowed a signed long. If it
554 * fits in an *unsigned* long, it may still be okay,
555 * as uid_t may be unsigned long on this platform.
556 */
557 uresult = PyLong_AsUnsignedLong(index);
558 if (PyErr_Occurred()) {
559 if (PyErr_ExceptionMatches(PyExc_OverflowError))
560 goto overflow;
561 goto fail;
562 }
563
564 uid = (uid_t)uresult;
565
566 /*
567 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
568 * but this value would get interpreted as (uid_t)-1 by chown
569 * and its siblings. That's not what the user meant! So we
570 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100571 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700572 */
573 if (uid == (uid_t)-1)
574 goto overflow;
575
576 /* Ensure the value wasn't truncated. */
577 if (sizeof(uid_t) < sizeof(long) &&
578 (unsigned long)uid != uresult)
579 goto overflow;
580 /* fallthrough */
581
582success:
583 Py_DECREF(index);
584 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200585 return 1;
586
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700587underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200588 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700589 "uid is less than minimum");
590 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200591
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700592overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200593 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700594 "uid is greater than maximum");
595 /* fallthrough */
596
597fail:
598 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200599 return 0;
600}
601
602int
603_Py_Gid_Converter(PyObject *obj, void *p)
604{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700605 gid_t gid;
606 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200607 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200608 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700609 unsigned long uresult;
610
611 index = PyNumber_Index(obj);
612 if (index == NULL) {
613 PyErr_Format(PyExc_TypeError,
614 "gid should be integer, not %.200s",
615 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200616 return 0;
617 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700618
619 /*
620 * Handling gid_t is complicated for two reasons:
621 * * Although gid_t is (always?) unsigned, it still
622 * accepts -1.
623 * * We don't know its size in advance--it may be
624 * bigger than an int, or it may be smaller than
625 * a long.
626 *
627 * So a bit of defensive programming is in order.
628 * Start with interpreting the value passed
629 * in as a signed long and see if it works.
630 */
631
632 result = PyLong_AsLongAndOverflow(index, &overflow);
633
634 if (!overflow) {
635 gid = (gid_t)result;
636
637 if (result == -1) {
638 if (PyErr_Occurred())
639 goto fail;
640 /* It's a legitimate -1, we're done. */
641 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200642 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700643
644 /* Any other negative number is disallowed. */
645 if (result < 0) {
646 goto underflow;
647 }
648
649 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200650 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700651 (long)gid != result)
652 goto underflow;
653 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200654 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700655
656 if (overflow < 0)
657 goto underflow;
658
659 /*
660 * Okay, the value overflowed a signed long. If it
661 * fits in an *unsigned* long, it may still be okay,
662 * as gid_t may be unsigned long on this platform.
663 */
664 uresult = PyLong_AsUnsignedLong(index);
665 if (PyErr_Occurred()) {
666 if (PyErr_ExceptionMatches(PyExc_OverflowError))
667 goto overflow;
668 goto fail;
669 }
670
671 gid = (gid_t)uresult;
672
673 /*
674 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
675 * but this value would get interpreted as (gid_t)-1 by chown
676 * and its siblings. That's not what the user meant! So we
677 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100678 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700679 */
680 if (gid == (gid_t)-1)
681 goto overflow;
682
683 /* Ensure the value wasn't truncated. */
684 if (sizeof(gid_t) < sizeof(long) &&
685 (unsigned long)gid != uresult)
686 goto overflow;
687 /* fallthrough */
688
689success:
690 Py_DECREF(index);
691 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200692 return 1;
693
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700694underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200695 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700696 "gid is less than minimum");
697 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200698
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700699overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200700 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700701 "gid is greater than maximum");
702 /* fallthrough */
703
704fail:
705 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200706 return 0;
707}
708#endif /* MS_WINDOWS */
709
710
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700711#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800712
713
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200714#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
715static int
716_Py_Dev_Converter(PyObject *obj, void *p)
717{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200718 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200719 if (PyErr_Occurred())
720 return 0;
721 return 1;
722}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800723#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200724
725
Larry Hastings9cf065c2012-06-22 16:30:09 -0700726#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400727/*
728 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
729 * without the int cast, the value gets interpreted as uint (4291925331),
730 * which doesn't play nicely with all the initializer lines in this file that
731 * look like this:
732 * int dir_fd = DEFAULT_DIR_FD;
733 */
734#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700735#else
736#define DEFAULT_DIR_FD (-100)
737#endif
738
739static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300740_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200741{
742 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700743 long long_value;
744
745 PyObject *index = PyNumber_Index(o);
746 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700747 return 0;
748 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700749
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300750 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700751 long_value = PyLong_AsLongAndOverflow(index, &overflow);
752 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300753 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200754 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700755 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700756 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700757 return 0;
758 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200759 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700760 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700761 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700762 return 0;
763 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700764
Larry Hastings9cf065c2012-06-22 16:30:09 -0700765 *p = (int)long_value;
766 return 1;
767}
768
769static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200770dir_fd_converter(PyObject *o, void *p)
771{
772 if (o == Py_None) {
773 *(int *)p = DEFAULT_DIR_FD;
774 return 1;
775 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300776 else if (PyIndex_Check(o)) {
777 return _fd_converter(o, (int *)p);
778 }
779 else {
780 PyErr_Format(PyExc_TypeError,
781 "argument should be integer or None, not %.200s",
782 Py_TYPE(o)->tp_name);
783 return 0;
784 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700785}
786
787
Larry Hastings9cf065c2012-06-22 16:30:09 -0700788/*
789 * A PyArg_ParseTuple "converter" function
790 * that handles filesystem paths in the manner
791 * preferred by the os module.
792 *
793 * path_converter accepts (Unicode) strings and their
794 * subclasses, and bytes and their subclasses. What
795 * it does with the argument depends on the platform:
796 *
797 * * On Windows, if we get a (Unicode) string we
798 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700799 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700800 *
801 * * On all other platforms, strings are encoded
802 * to bytes using PyUnicode_FSConverter, then we
803 * extract the char * from the bytes object and
804 * return that.
805 *
806 * path_converter also optionally accepts signed
807 * integers (representing open file descriptors) instead
808 * of path strings.
809 *
810 * Input fields:
811 * path.nullable
812 * If nonzero, the path is permitted to be None.
813 * path.allow_fd
814 * If nonzero, the path is permitted to be a file handle
815 * (a signed int) instead of a string.
816 * path.function_name
817 * If non-NULL, path_converter will use that as the name
818 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700819 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700820 * path.argument_name
821 * If non-NULL, path_converter will use that as the name
822 * of the parameter in error messages.
823 * (If path.argument_name is NULL it uses "path".)
824 *
825 * Output fields:
826 * path.wide
827 * Points to the path if it was expressed as Unicode
828 * and was not encoded. (Only used on Windows.)
829 * path.narrow
830 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700831 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000832 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700833 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700834 * path.fd
835 * Contains a file descriptor if path.accept_fd was true
836 * and the caller provided a signed integer instead of any
837 * sort of string.
838 *
839 * WARNING: if your "path" parameter is optional, and is
840 * unspecified, path_converter will never get called.
841 * So if you set allow_fd, you *MUST* initialize path.fd = -1
842 * yourself!
843 * path.length
844 * The length of the path in characters, if specified as
845 * a string.
846 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800847 * The original object passed in (if get a PathLike object,
848 * the result of PyOS_FSPath() is treated as the original object).
849 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700850 * path.cleanup
851 * For internal use only. May point to a temporary object.
852 * (Pay no attention to the man behind the curtain.)
853 *
854 * At most one of path.wide or path.narrow will be non-NULL.
855 * If path was None and path.nullable was set,
856 * or if path was an integer and path.allow_fd was set,
857 * both path.wide and path.narrow will be NULL
858 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200859 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700860 * path_converter takes care to not write to the path_t
861 * unless it's successful. However it must reset the
862 * "cleanup" field each time it's called.
863 *
864 * Use as follows:
865 * path_t path;
866 * memset(&path, 0, sizeof(path));
867 * PyArg_ParseTuple(args, "O&", path_converter, &path);
868 * // ... use values from path ...
869 * path_cleanup(&path);
870 *
871 * (Note that if PyArg_Parse fails you don't need to call
872 * path_cleanup(). However it is safe to do so.)
873 */
874typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100875 const char *function_name;
876 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700877 int nullable;
878 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300879 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700880#ifdef MS_WINDOWS
881 BOOL narrow;
882#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300883 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700884#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700885 int fd;
886 Py_ssize_t length;
887 PyObject *object;
888 PyObject *cleanup;
889} path_t;
890
Steve Dowercc16be82016-09-08 10:35:16 -0700891#ifdef MS_WINDOWS
892#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
893 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
894#else
Larry Hastings2f936352014-08-05 14:04:04 +1000895#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
896 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700897#endif
Larry Hastings31826802013-10-19 00:09:25 -0700898
Larry Hastings9cf065c2012-06-22 16:30:09 -0700899static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800900path_cleanup(path_t *path)
901{
902 Py_CLEAR(path->object);
903 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700904}
905
906static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300907path_converter(PyObject *o, void *p)
908{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700909 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800910 PyObject *bytes = NULL;
911 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700912 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300913 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700914#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800915 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700916 const wchar_t *wide;
917#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700918
919#define FORMAT_EXCEPTION(exc, fmt) \
920 PyErr_Format(exc, "%s%s" fmt, \
921 path->function_name ? path->function_name : "", \
922 path->function_name ? ": " : "", \
923 path->argument_name ? path->argument_name : "path")
924
925 /* Py_CLEANUP_SUPPORTED support */
926 if (o == NULL) {
927 path_cleanup(path);
928 return 1;
929 }
930
Brett Cannon3f9183b2016-08-26 14:44:48 -0700931 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800932 path->object = path->cleanup = NULL;
933 /* path->object owns a reference to the original object */
934 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700935
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300936 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700937 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700938#ifdef MS_WINDOWS
939 path->narrow = FALSE;
940#else
Larry Hastings9cf065c2012-06-22 16:30:09 -0700941 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700942#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700943 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +0800944 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700945 }
946
Brett Cannon3f9183b2016-08-26 14:44:48 -0700947 /* Only call this here so that we don't treat the return value of
948 os.fspath() as an fd or buffer. */
949 is_index = path->allow_fd && PyIndex_Check(o);
950 is_buffer = PyObject_CheckBuffer(o);
951 is_bytes = PyBytes_Check(o);
952 is_unicode = PyUnicode_Check(o);
953
954 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
955 /* Inline PyOS_FSPath() for better error messages. */
956 _Py_IDENTIFIER(__fspath__);
957 PyObject *func = NULL;
958
959 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
960 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +0800961 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700962 }
Xiang Zhang04316c42017-01-08 23:26:57 +0800963 /* still owns a reference to the original object */
964 Py_DECREF(o);
965 o = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -0700966 Py_DECREF(func);
967 if (NULL == o) {
968 goto error_exit;
969 }
970 else if (PyUnicode_Check(o)) {
971 is_unicode = 1;
972 }
973 else if (PyBytes_Check(o)) {
974 is_bytes = 1;
975 }
976 else {
Xiang Zhang04316c42017-01-08 23:26:57 +0800977 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700978 }
979 }
980
981 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700982#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +0200983 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +0100984 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +0800985 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700986 }
Victor Stinner59799a82013-11-13 14:17:30 +0100987 if (length > 32767) {
988 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +0800989 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700990 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +0300991 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300992 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +0800993 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +0300994 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700995
996 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +0800997 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700998 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +0800999 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001000#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001001 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001002 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001003 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001004#endif
1005 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001006 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001007 bytes = o;
1008 Py_INCREF(bytes);
1009 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001010 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001011 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001012 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001013 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1014 "%s%s%s should be %s, not %.200s",
1015 path->function_name ? path->function_name : "",
1016 path->function_name ? ": " : "",
1017 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001018 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1019 "integer or None" :
1020 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1021 path->nullable ? "string, bytes, os.PathLike or None" :
1022 "string, bytes or os.PathLike",
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001023 Py_TYPE(o)->tp_name)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001024 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001025 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001026 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001027 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001028 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001029 }
1030 }
Steve Dowercc16be82016-09-08 10:35:16 -07001031 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001032 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001033 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001034 }
1035 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001036#ifdef MS_WINDOWS
1037 path->narrow = FALSE;
1038#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001039 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001040#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001041 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001042 }
1043 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001044 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001045 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1046 path->function_name ? path->function_name : "",
1047 path->function_name ? ": " : "",
1048 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001049 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1050 "integer or None" :
1051 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1052 path->nullable ? "string, bytes, os.PathLike or None" :
1053 "string, bytes or os.PathLike",
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001054 Py_TYPE(o)->tp_name);
Xiang Zhang04316c42017-01-08 23:26:57 +08001055 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001056 }
1057
Larry Hastings9cf065c2012-06-22 16:30:09 -07001058 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001059 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001060 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001061 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001062 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001063 }
1064
Steve Dowercc16be82016-09-08 10:35:16 -07001065#ifdef MS_WINDOWS
1066 wo = PyUnicode_DecodeFSDefaultAndSize(
1067 narrow,
1068 length
1069 );
1070 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001071 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001072 }
1073
Xiang Zhang04316c42017-01-08 23:26:57 +08001074 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001075 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001076 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001077 }
1078 if (length > 32767) {
1079 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001080 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001081 }
1082 if (wcslen(wide) != length) {
1083 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001084 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001085 }
1086 path->wide = wide;
1087 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001088 path->cleanup = wo;
1089 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001090#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001091 path->wide = NULL;
1092 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001093 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001094 /* Still a reference owned by path->object, don't have to
1095 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001096 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001097 }
1098 else {
1099 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001100 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001101#endif
1102 path->fd = -1;
1103
1104 success_exit:
1105 path->length = length;
1106 path->object = o;
1107 return Py_CLEANUP_SUPPORTED;
1108
1109 error_exit:
1110 Py_XDECREF(o);
1111 Py_XDECREF(bytes);
1112#ifdef MS_WINDOWS
1113 Py_XDECREF(wo);
1114#endif
1115 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001116}
1117
1118static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001119argument_unavailable_error(const char *function_name, const char *argument_name)
1120{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001121 PyErr_Format(PyExc_NotImplementedError,
1122 "%s%s%s unavailable on this platform",
1123 (function_name != NULL) ? function_name : "",
1124 (function_name != NULL) ? ": ": "",
1125 argument_name);
1126}
1127
1128static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001129dir_fd_unavailable(PyObject *o, void *p)
1130{
1131 int dir_fd;
1132 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001133 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001134 if (dir_fd != DEFAULT_DIR_FD) {
1135 argument_unavailable_error(NULL, "dir_fd");
1136 return 0;
1137 }
1138 *(int *)p = dir_fd;
1139 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001140}
1141
1142static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001143fd_specified(const char *function_name, int fd)
1144{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001145 if (fd == -1)
1146 return 0;
1147
1148 argument_unavailable_error(function_name, "fd");
1149 return 1;
1150}
1151
1152static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001153follow_symlinks_specified(const char *function_name, int follow_symlinks)
1154{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001155 if (follow_symlinks)
1156 return 0;
1157
1158 argument_unavailable_error(function_name, "follow_symlinks");
1159 return 1;
1160}
1161
1162static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001163path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1164{
Steve Dowercc16be82016-09-08 10:35:16 -07001165 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1166#ifndef MS_WINDOWS
1167 && !path->narrow
1168#endif
1169 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001170 PyErr_Format(PyExc_ValueError,
1171 "%s: can't specify dir_fd without matching path",
1172 function_name);
1173 return 1;
1174 }
1175 return 0;
1176}
1177
1178static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001179dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1180{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001181 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1182 PyErr_Format(PyExc_ValueError,
1183 "%s: can't specify both dir_fd and fd",
1184 function_name);
1185 return 1;
1186 }
1187 return 0;
1188}
1189
1190static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001191fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1192 int follow_symlinks)
1193{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001194 if ((fd > 0) && (!follow_symlinks)) {
1195 PyErr_Format(PyExc_ValueError,
1196 "%s: cannot use fd and follow_symlinks together",
1197 function_name);
1198 return 1;
1199 }
1200 return 0;
1201}
1202
1203static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001204dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1205 int follow_symlinks)
1206{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001207 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1208 PyErr_Format(PyExc_ValueError,
1209 "%s: cannot use dir_fd and follow_symlinks together",
1210 function_name);
1211 return 1;
1212 }
1213 return 0;
1214}
1215
Larry Hastings2f936352014-08-05 14:04:04 +10001216#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001217 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001218#else
Larry Hastings2f936352014-08-05 14:04:04 +10001219 typedef off_t Py_off_t;
1220#endif
1221
1222static int
1223Py_off_t_converter(PyObject *arg, void *addr)
1224{
1225#ifdef HAVE_LARGEFILE_SUPPORT
1226 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1227#else
1228 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001229#endif
1230 if (PyErr_Occurred())
1231 return 0;
1232 return 1;
1233}
Larry Hastings2f936352014-08-05 14:04:04 +10001234
1235static PyObject *
1236PyLong_FromPy_off_t(Py_off_t offset)
1237{
1238#ifdef HAVE_LARGEFILE_SUPPORT
1239 return PyLong_FromLongLong(offset);
1240#else
1241 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001242#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001243}
1244
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001245#ifdef HAVE_SIGSET_T
1246/* Convert an iterable of integers to a sigset.
1247 Return 1 on success, return 0 and raise an exception on error. */
1248int
1249_Py_Sigset_Converter(PyObject *obj, void *addr)
1250{
1251 sigset_t *mask = (sigset_t *)addr;
1252 PyObject *iterator, *item;
1253 long signum;
1254 int overflow;
1255
1256 if (sigemptyset(mask)) {
1257 /* Probably only if mask == NULL. */
1258 PyErr_SetFromErrno(PyExc_OSError);
1259 return 0;
1260 }
1261
1262 iterator = PyObject_GetIter(obj);
1263 if (iterator == NULL) {
1264 return 0;
1265 }
1266
1267 while ((item = PyIter_Next(iterator)) != NULL) {
1268 signum = PyLong_AsLongAndOverflow(item, &overflow);
1269 Py_DECREF(item);
1270 if (signum <= 0 || signum >= NSIG) {
1271 if (overflow || signum != -1 || !PyErr_Occurred()) {
1272 PyErr_Format(PyExc_ValueError,
1273 "signal number %ld out of range", signum);
1274 }
1275 goto error;
1276 }
1277 if (sigaddset(mask, (int)signum)) {
1278 if (errno != EINVAL) {
1279 /* Probably impossible */
1280 PyErr_SetFromErrno(PyExc_OSError);
1281 goto error;
1282 }
1283 /* For backwards compatibility, allow idioms such as
1284 * `range(1, NSIG)` but warn about invalid signal numbers
1285 */
1286 const char msg[] =
1287 "invalid signal number %ld, please use valid_signals()";
1288 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1289 goto error;
1290 }
1291 }
1292 }
1293 if (!PyErr_Occurred()) {
1294 Py_DECREF(iterator);
1295 return 1;
1296 }
1297
1298error:
1299 Py_DECREF(iterator);
1300 return 0;
1301}
1302#endif /* HAVE_SIGSET_T */
1303
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001304#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001305
1306static int
Brian Curtind25aef52011-06-13 15:16:04 -05001307win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001308{
Martin Panter70214ad2016-08-04 02:38:59 +00001309 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1310 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001311 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001312
1313 if (0 == DeviceIoControl(
1314 reparse_point_handle,
1315 FSCTL_GET_REPARSE_POINT,
1316 NULL, 0, /* in buffer */
1317 target_buffer, sizeof(target_buffer),
1318 &n_bytes_returned,
1319 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001320 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001321
1322 if (reparse_tag)
1323 *reparse_tag = rdb->ReparseTag;
1324
Brian Curtind25aef52011-06-13 15:16:04 -05001325 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001326}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001327
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001328#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001329
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001330/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001331#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001332/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001333** environ directly, we must obtain it with _NSGetEnviron(). See also
1334** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001335*/
1336#include <crt_externs.h>
1337static char **environ;
1338#elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001339extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001340#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001341
Barry Warsaw53699e91996-12-10 23:23:01 +00001342static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001343convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001344{
Victor Stinner8c62be82010-05-06 00:08:46 +00001345 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001346#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001347 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001348#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001349 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001350#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001351
Victor Stinner8c62be82010-05-06 00:08:46 +00001352 d = PyDict_New();
1353 if (d == NULL)
1354 return NULL;
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001355#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Victor Stinner8c62be82010-05-06 00:08:46 +00001356 if (environ == NULL)
1357 environ = *_NSGetEnviron();
1358#endif
1359#ifdef MS_WINDOWS
1360 /* _wenviron must be initialized in this way if the program is started
1361 through main() instead of wmain(). */
1362 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001363 e = _wenviron;
Victor Stinner8c62be82010-05-06 00:08:46 +00001364#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001365 e = environ;
1366#endif
1367 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001368 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001369 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001370 PyObject *k;
1371 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001372#ifdef MS_WINDOWS
1373 const wchar_t *p = wcschr(*e, L'=');
1374#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001375 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001376#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001377 if (p == NULL)
1378 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001379#ifdef MS_WINDOWS
1380 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1381#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001382 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001383#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001384 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001385 Py_DECREF(d);
1386 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001387 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001388#ifdef MS_WINDOWS
1389 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1390#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001391 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001392#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001393 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001394 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001395 Py_DECREF(d);
1396 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001397 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001398 if (PyDict_GetItemWithError(d, k) == NULL) {
1399 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1400 Py_DECREF(v);
1401 Py_DECREF(k);
1402 Py_DECREF(d);
1403 return NULL;
1404 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001405 }
1406 Py_DECREF(k);
1407 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001408 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001409 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001410}
1411
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001412/* Set a POSIX-specific error from errno, and return NULL */
1413
Barry Warsawd58d7641998-07-23 16:14:40 +00001414static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001415posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001416{
Victor Stinner8c62be82010-05-06 00:08:46 +00001417 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001418}
Mark Hammondef8b6542001-05-13 08:04:26 +00001419
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001420#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001421static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001422win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001423{
Victor Stinner8c62be82010-05-06 00:08:46 +00001424 /* XXX We should pass the function name along in the future.
1425 (winreg.c also wants to pass the function name.)
1426 This would however require an additional param to the
1427 Windows error object, which is non-trivial.
1428 */
1429 errno = GetLastError();
1430 if (filename)
1431 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1432 else
1433 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001434}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001435
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001436static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001437win32_error_object(const char* function, PyObject* filename)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001438{
1439 /* XXX - see win32_error for comments on 'function' */
1440 errno = GetLastError();
1441 if (filename)
1442 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001443 PyExc_OSError,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001444 errno,
1445 filename);
1446 else
1447 return PyErr_SetFromWindowsErr(errno);
1448}
1449
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001450#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001451
Larry Hastings9cf065c2012-06-22 16:30:09 -07001452static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001453posix_path_object_error(PyObject *path)
1454{
1455 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1456}
1457
1458static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001459path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001460{
1461#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001462 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1463 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001464#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001465 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001466#endif
1467}
1468
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001469static PyObject *
1470path_object_error2(PyObject *path, PyObject *path2)
1471{
1472#ifdef MS_WINDOWS
1473 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1474 PyExc_OSError, 0, path, path2);
1475#else
1476 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1477#endif
1478}
1479
1480static PyObject *
1481path_error(path_t *path)
1482{
1483 return path_object_error(path->object);
1484}
Larry Hastings31826802013-10-19 00:09:25 -07001485
Larry Hastingsb0827312014-02-09 22:05:19 -08001486static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001487posix_path_error(path_t *path)
1488{
1489 return posix_path_object_error(path->object);
1490}
1491
1492static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001493path_error2(path_t *path, path_t *path2)
1494{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001495 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001496}
1497
1498
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001499/* POSIX generic methods */
1500
Larry Hastings2f936352014-08-05 14:04:04 +10001501static int
1502fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001503{
Victor Stinner8c62be82010-05-06 00:08:46 +00001504 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001505 int *pointer = (int *)p;
1506 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001507 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001508 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001509 *pointer = fd;
1510 return 1;
1511}
1512
1513static PyObject *
1514posix_fildes_fd(int fd, int (*func)(int))
1515{
1516 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001517 int async_err = 0;
1518
1519 do {
1520 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001521 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001522 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001523 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001524 Py_END_ALLOW_THREADS
1525 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1526 if (res != 0)
1527 return (!async_err) ? posix_error() : NULL;
1528 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001529}
Guido van Rossum21142a01999-01-08 21:05:37 +00001530
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001531
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001532#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001533/* This is a reimplementation of the C library's chdir function,
1534 but one that produces Win32 errors instead of DOS error codes.
1535 chdir is essentially a wrapper around SetCurrentDirectory; however,
1536 it also needs to set "magic" environment variables indicating
1537 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001538static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001539win32_wchdir(LPCWSTR path)
1540{
Victor Stinnered537822015-12-13 21:40:26 +01001541 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001542 int result;
1543 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001544
Victor Stinner8c62be82010-05-06 00:08:46 +00001545 if(!SetCurrentDirectoryW(path))
1546 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001547 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001548 if (!result)
1549 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001550 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001551 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001552 if (!new_path) {
1553 SetLastError(ERROR_OUTOFMEMORY);
1554 return FALSE;
1555 }
1556 result = GetCurrentDirectoryW(result, new_path);
1557 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001558 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001559 return FALSE;
1560 }
1561 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001562 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1563 wcsncmp(new_path, L"//", 2) == 0);
1564 if (!is_unc_like_path) {
1565 env[1] = new_path[0];
1566 result = SetEnvironmentVariableW(env, new_path);
1567 }
Victor Stinnered537822015-12-13 21:40:26 +01001568 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001569 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001570 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001571}
1572#endif
1573
Martin v. Löwis14694662006-02-03 12:54:16 +00001574#ifdef MS_WINDOWS
1575/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1576 - time stamps are restricted to second resolution
1577 - file modification times suffer from forth-and-back conversions between
1578 UTC and local time
1579 Therefore, we implement our own stat, based on the Win32 API directly.
1580*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001581#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001582#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001583
Victor Stinner6036e442015-03-08 01:58:04 +01001584static void
Steve Dowercc16be82016-09-08 10:35:16 -07001585find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1586 BY_HANDLE_FILE_INFORMATION *info,
1587 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001588{
1589 memset(info, 0, sizeof(*info));
1590 info->dwFileAttributes = pFileData->dwFileAttributes;
1591 info->ftCreationTime = pFileData->ftCreationTime;
1592 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1593 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1594 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1595 info->nFileSizeLow = pFileData->nFileSizeLow;
1596/* info->nNumberOfLinks = 1; */
1597 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1598 *reparse_tag = pFileData->dwReserved0;
1599 else
1600 *reparse_tag = 0;
1601}
1602
Guido van Rossumd8faa362007-04-27 19:54:29 +00001603static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001604attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001605{
Victor Stinner8c62be82010-05-06 00:08:46 +00001606 HANDLE hFindFile;
1607 WIN32_FIND_DATAW FileData;
1608 hFindFile = FindFirstFileW(pszFile, &FileData);
1609 if (hFindFile == INVALID_HANDLE_VALUE)
1610 return FALSE;
1611 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001612 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001613 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001614}
1615
Brian Curtind25aef52011-06-13 15:16:04 -05001616static BOOL
1617get_target_path(HANDLE hdl, wchar_t **target_path)
1618{
1619 int buf_size, result_length;
1620 wchar_t *buf;
1621
1622 /* We have a good handle to the target, use it to determine
1623 the target path name (then we'll call lstat on it). */
Steve Dower2ea51c92015-03-20 21:49:12 -07001624 buf_size = GetFinalPathNameByHandleW(hdl, 0, 0,
1625 VOLUME_NAME_DOS);
Brian Curtind25aef52011-06-13 15:16:04 -05001626 if(!buf_size)
1627 return FALSE;
1628
Victor Stinnerc36674a2016-03-16 14:30:16 +01001629 buf = (wchar_t *)PyMem_RawMalloc((buf_size + 1) * sizeof(wchar_t));
Brian Curtinc8be8402011-06-14 09:52:50 -05001630 if (!buf) {
1631 SetLastError(ERROR_OUTOFMEMORY);
1632 return FALSE;
1633 }
1634
Steve Dower2ea51c92015-03-20 21:49:12 -07001635 result_length = GetFinalPathNameByHandleW(hdl,
Brian Curtind25aef52011-06-13 15:16:04 -05001636 buf, buf_size, VOLUME_NAME_DOS);
1637
1638 if(!result_length) {
Victor Stinnerc36674a2016-03-16 14:30:16 +01001639 PyMem_RawFree(buf);
Brian Curtind25aef52011-06-13 15:16:04 -05001640 return FALSE;
1641 }
1642
1643 if(!CloseHandle(hdl)) {
Victor Stinnerc36674a2016-03-16 14:30:16 +01001644 PyMem_RawFree(buf);
Brian Curtind25aef52011-06-13 15:16:04 -05001645 return FALSE;
1646 }
1647
1648 buf[result_length] = 0;
1649
1650 *target_path = buf;
1651 return TRUE;
1652}
1653
1654static int
Steve Dowercc16be82016-09-08 10:35:16 -07001655win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001656 BOOL traverse)
1657{
Victor Stinner26de69d2011-06-17 15:15:38 +02001658 int code;
Brian Curtind25aef52011-06-13 15:16:04 -05001659 HANDLE hFile, hFile2;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001660 BY_HANDLE_FILE_INFORMATION info;
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001661 ULONG reparse_tag = 0;
Victor Stinner26de69d2011-06-17 15:15:38 +02001662 wchar_t *target_path;
Steve Dowercc16be82016-09-08 10:35:16 -07001663 const wchar_t *dot;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001664
Steve Dowercc16be82016-09-08 10:35:16 -07001665 hFile = CreateFileW(
Brian Curtinf5e76d02010-11-24 13:14:05 +00001666 path,
Brian Curtind25aef52011-06-13 15:16:04 -05001667 FILE_READ_ATTRIBUTES, /* desired access */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001668 0, /* share mode */
1669 NULL, /* security attributes */
1670 OPEN_EXISTING,
1671 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
Brian Curtind25aef52011-06-13 15:16:04 -05001672 /* FILE_FLAG_OPEN_REPARSE_POINT does not follow the symlink.
1673 Because of this, calls like GetFinalPathNameByHandle will return
R David Murrayfc069992013-12-13 20:52:19 -05001674 the symlink path again and not the actual final path. */
Brian Curtind25aef52011-06-13 15:16:04 -05001675 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|
1676 FILE_FLAG_OPEN_REPARSE_POINT,
Brian Curtinf5e76d02010-11-24 13:14:05 +00001677 NULL);
1678
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001679 if (hFile == INVALID_HANDLE_VALUE) {
Brian Curtinf5e76d02010-11-24 13:14:05 +00001680 /* Either the target doesn't exist, or we don't have access to
1681 get a handle to it. If the former, we need to return an error.
1682 If the latter, we can use attributes_from_dir. */
Berker Peksag0b4dc482016-09-17 15:49:59 +03001683 DWORD lastError = GetLastError();
1684 if (lastError != ERROR_ACCESS_DENIED &&
1685 lastError != ERROR_SHARING_VIOLATION)
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001686 return -1;
1687 /* Could not get attributes on open file. Fall back to
1688 reading the directory. */
1689 if (!attributes_from_dir(path, &info, &reparse_tag))
1690 /* Very strange. This should not fail now */
1691 return -1;
1692 if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1693 if (traverse) {
1694 /* Should traverse, but could not open reparse point handle */
Berker Peksag0b4dc482016-09-17 15:49:59 +03001695 SetLastError(lastError);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001696 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001697 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001698 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001699 } else {
1700 if (!GetFileInformationByHandle(hFile, &info)) {
1701 CloseHandle(hFile);
Brian Curtind25aef52011-06-13 15:16:04 -05001702 return -1;
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001703 }
1704 if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
Brian Curtind25aef52011-06-13 15:16:04 -05001705 if (!win32_get_reparse_tag(hFile, &reparse_tag))
1706 return -1;
1707
1708 /* Close the outer open file handle now that we're about to
1709 reopen it with different flags. */
1710 if (!CloseHandle(hFile))
1711 return -1;
1712
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001713 if (traverse) {
Brian Curtind25aef52011-06-13 15:16:04 -05001714 /* In order to call GetFinalPathNameByHandle we need to open
1715 the file without the reparse handling flag set. */
Brian Curtind25aef52011-06-13 15:16:04 -05001716 hFile2 = CreateFileW(
1717 path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ,
1718 NULL, OPEN_EXISTING,
1719 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
1720 NULL);
1721 if (hFile2 == INVALID_HANDLE_VALUE)
1722 return -1;
1723
1724 if (!get_target_path(hFile2, &target_path))
1725 return -1;
1726
Steve Dowercc16be82016-09-08 10:35:16 -07001727 code = win32_xstat_impl(target_path, result, FALSE);
Victor Stinnerc36674a2016-03-16 14:30:16 +01001728 PyMem_RawFree(target_path);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001729 return code;
1730 }
Hirokazu Yamamoto7ed117a2010-12-07 10:24:37 +00001731 } else
1732 CloseHandle(hFile);
Brian Curtinf5e76d02010-11-24 13:14:05 +00001733 }
Steve Dowera2af1a52015-02-21 10:04:10 -08001734 _Py_attribute_data_to_stat(&info, reparse_tag, result);
Brian Curtinf5e76d02010-11-24 13:14:05 +00001735
1736 /* Set S_IEXEC if it is an .exe, .bat, ... */
1737 dot = wcsrchr(path, '.');
1738 if (dot) {
1739 if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
1740 _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
1741 result->st_mode |= 0111;
1742 }
1743 return 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001744}
1745
1746static int
Steve Dowercc16be82016-09-08 10:35:16 -07001747win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001748{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001749 /* Protocol violation: we explicitly clear errno, instead of
1750 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001751 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001752 errno = 0;
1753 return code;
1754}
Brian Curtind25aef52011-06-13 15:16:04 -05001755/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001756
1757 In Posix, stat automatically traverses symlinks and returns the stat
1758 structure for the target. In Windows, the equivalent GetFileAttributes by
1759 default does not traverse symlinks and instead returns attributes for
1760 the symlink.
1761
1762 Therefore, win32_lstat will get the attributes traditionally, and
1763 win32_stat will first explicitly resolve the symlink target and then will
Steve Dowercc16be82016-09-08 10:35:16 -07001764 call win32_lstat on that result. */
Brian Curtind40e6f72010-07-08 21:39:08 +00001765
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001766static int
Steve Dowercc16be82016-09-08 10:35:16 -07001767win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001768{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001769 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001770}
1771
Victor Stinner8c62be82010-05-06 00:08:46 +00001772static int
Steve Dowercc16be82016-09-08 10:35:16 -07001773win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001774{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001775 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001776}
1777
Martin v. Löwis14694662006-02-03 12:54:16 +00001778#endif /* MS_WINDOWS */
1779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001780PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001781"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001782This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001783 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001784or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1785\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001786Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1787or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001788\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001789See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001790
1791static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001792 {"st_mode", "protection bits"},
1793 {"st_ino", "inode"},
1794 {"st_dev", "device"},
1795 {"st_nlink", "number of hard links"},
1796 {"st_uid", "user ID of owner"},
1797 {"st_gid", "group ID of owner"},
1798 {"st_size", "total size, in bytes"},
1799 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1800 {NULL, "integer time of last access"},
1801 {NULL, "integer time of last modification"},
1802 {NULL, "integer time of last change"},
1803 {"st_atime", "time of last access"},
1804 {"st_mtime", "time of last modification"},
1805 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001806 {"st_atime_ns", "time of last access in nanoseconds"},
1807 {"st_mtime_ns", "time of last modification in nanoseconds"},
1808 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001809#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001810 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001811#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001812#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001813 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001814#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001815#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001816 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001817#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001818#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001819 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001820#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001821#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001822 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001823#endif
1824#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001825 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001826#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001827#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1828 {"st_file_attributes", "Windows file attribute bits"},
1829#endif
jcea6c51d512018-01-28 14:00:08 +01001830#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1831 {"st_fstype", "Type of filesystem"},
1832#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001833 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001834};
1835
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001836#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001837#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001838#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001839#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001840#endif
1841
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001842#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001843#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1844#else
1845#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1846#endif
1847
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001848#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001849#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1850#else
1851#define ST_RDEV_IDX ST_BLOCKS_IDX
1852#endif
1853
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001854#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1855#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1856#else
1857#define ST_FLAGS_IDX ST_RDEV_IDX
1858#endif
1859
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001860#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001861#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001862#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001863#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001864#endif
1865
1866#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1867#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1868#else
1869#define ST_BIRTHTIME_IDX ST_GEN_IDX
1870#endif
1871
Zachary Ware63f277b2014-06-19 09:46:37 -05001872#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1873#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
1874#else
1875#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
1876#endif
1877
jcea6c51d512018-01-28 14:00:08 +01001878#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1879#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
1880#else
1881#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
1882#endif
1883
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001884static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001885 "stat_result", /* name */
1886 stat_result__doc__, /* doc */
1887 stat_result_fields,
1888 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001889};
1890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001892"statvfs_result: Result from statvfs or fstatvfs.\n\n\
1893This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001894 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00001895or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001896\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001897See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001898
1899static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001900 {"f_bsize", },
1901 {"f_frsize", },
1902 {"f_blocks", },
1903 {"f_bfree", },
1904 {"f_bavail", },
1905 {"f_files", },
1906 {"f_ffree", },
1907 {"f_favail", },
1908 {"f_flag", },
1909 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01001910 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00001911 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001912};
1913
1914static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001915 "statvfs_result", /* name */
1916 statvfs_result__doc__, /* doc */
1917 statvfs_result_fields,
1918 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001919};
1920
Ross Lagerwall7807c352011-03-17 20:20:30 +02001921#if defined(HAVE_WAITID) && !defined(__APPLE__)
1922PyDoc_STRVAR(waitid_result__doc__,
1923"waitid_result: Result from waitid.\n\n\
1924This object may be accessed either as a tuple of\n\
1925 (si_pid, si_uid, si_signo, si_status, si_code),\n\
1926or via the attributes si_pid, si_uid, and so on.\n\
1927\n\
1928See os.waitid for more information.");
1929
1930static PyStructSequence_Field waitid_result_fields[] = {
1931 {"si_pid", },
1932 {"si_uid", },
1933 {"si_signo", },
1934 {"si_status", },
1935 {"si_code", },
1936 {0}
1937};
1938
1939static PyStructSequence_Desc waitid_result_desc = {
1940 "waitid_result", /* name */
1941 waitid_result__doc__, /* doc */
1942 waitid_result_fields,
1943 5
1944};
Eddie Elizondo474eedf2018-11-13 04:09:31 -08001945static PyTypeObject* WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +02001946#endif
1947
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001948static int initialized;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08001949static PyTypeObject* StatResultType;
1950static PyTypeObject* StatVFSResultType;
William Orr81574b82018-10-01 22:19:56 -07001951#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08001952static PyTypeObject* SchedParamType;
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05001953#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001954static newfunc structseq_new;
1955
1956static PyObject *
1957statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1958{
Victor Stinner8c62be82010-05-06 00:08:46 +00001959 PyStructSequence *result;
1960 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001961
Victor Stinner8c62be82010-05-06 00:08:46 +00001962 result = (PyStructSequence*)structseq_new(type, args, kwds);
1963 if (!result)
1964 return NULL;
1965 /* If we have been initialized from a tuple,
1966 st_?time might be set to None. Initialize it
1967 from the int slots. */
1968 for (i = 7; i <= 9; i++) {
1969 if (result->ob_item[i+3] == Py_None) {
1970 Py_DECREF(Py_None);
1971 Py_INCREF(result->ob_item[i]);
1972 result->ob_item[i+3] = result->ob_item[i];
1973 }
1974 }
1975 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001976}
1977
1978
Larry Hastings6fe20b32012-04-19 15:07:49 -07001979static PyObject *billion = NULL;
1980
Martin v. Löwis94717ed2002-09-09 14:24:16 +00001981static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01001982fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00001983{
Larry Hastings6fe20b32012-04-19 15:07:49 -07001984 PyObject *s = _PyLong_FromTime_t(sec);
1985 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
1986 PyObject *s_in_ns = NULL;
1987 PyObject *ns_total = NULL;
1988 PyObject *float_s = NULL;
1989
1990 if (!(s && ns_fractional))
1991 goto exit;
1992
1993 s_in_ns = PyNumber_Multiply(s, billion);
1994 if (!s_in_ns)
1995 goto exit;
1996
1997 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
1998 if (!ns_total)
1999 goto exit;
2000
Victor Stinner01b5aab2017-10-24 02:02:00 -07002001 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2002 if (!float_s) {
2003 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002004 }
2005
2006 PyStructSequence_SET_ITEM(v, index, s);
2007 PyStructSequence_SET_ITEM(v, index+3, float_s);
2008 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2009 s = NULL;
2010 float_s = NULL;
2011 ns_total = NULL;
2012exit:
2013 Py_XDECREF(s);
2014 Py_XDECREF(ns_fractional);
2015 Py_XDECREF(s_in_ns);
2016 Py_XDECREF(ns_total);
2017 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002018}
2019
Tim Peters5aa91602002-01-30 05:46:57 +00002020/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002021 (used by posix_stat() and posix_fstat()) */
2022static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002023_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002024{
Victor Stinner8c62be82010-05-06 00:08:46 +00002025 unsigned long ansec, mnsec, cnsec;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002026 PyObject *v = PyStructSequence_New(StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002027 if (v == NULL)
2028 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002029
Victor Stinner8c62be82010-05-06 00:08:46 +00002030 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002031 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002032 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002033#ifdef MS_WINDOWS
2034 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002035#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002036 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002037#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002038 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002039#if defined(MS_WINDOWS)
2040 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2041 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2042#else
2043 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2044 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2045#endif
xdegaye50e86032017-05-22 11:15:08 +02002046 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2047 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002048
Martin v. Löwis14694662006-02-03 12:54:16 +00002049#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002050 ansec = st->st_atim.tv_nsec;
2051 mnsec = st->st_mtim.tv_nsec;
2052 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002053#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002054 ansec = st->st_atimespec.tv_nsec;
2055 mnsec = st->st_mtimespec.tv_nsec;
2056 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002057#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002058 ansec = st->st_atime_nsec;
2059 mnsec = st->st_mtime_nsec;
2060 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002061#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002062 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002063#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002064 fill_time(v, 7, st->st_atime, ansec);
2065 fill_time(v, 8, st->st_mtime, mnsec);
2066 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002067
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002068#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002069 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2070 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002071#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002072#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002073 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2074 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002075#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002076#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002077 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2078 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002079#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002080#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002081 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2082 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002083#endif
2084#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002085 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002086 PyObject *val;
2087 unsigned long bsec,bnsec;
2088 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002089#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002090 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002091#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002092 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002093#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002094 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002095 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2096 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002097 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002098#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002099#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002100 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2101 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002102#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002103#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2104 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2105 PyLong_FromUnsignedLong(st->st_file_attributes));
2106#endif
jcea6c51d512018-01-28 14:00:08 +01002107#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2108 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2109 PyUnicode_FromString(st->st_fstype));
2110#endif
Fred Drake699f3522000-06-29 21:12:41 +00002111
Victor Stinner8c62be82010-05-06 00:08:46 +00002112 if (PyErr_Occurred()) {
2113 Py_DECREF(v);
2114 return NULL;
2115 }
Fred Drake699f3522000-06-29 21:12:41 +00002116
Victor Stinner8c62be82010-05-06 00:08:46 +00002117 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002118}
2119
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002120/* POSIX methods */
2121
Guido van Rossum94f6f721999-01-06 18:42:14 +00002122
2123static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002124posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002125 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002126{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002127 STRUCT_STAT st;
2128 int result;
2129
2130#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2131 if (follow_symlinks_specified(function_name, follow_symlinks))
2132 return NULL;
2133#endif
2134
2135 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2136 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2137 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2138 return NULL;
2139
2140 Py_BEGIN_ALLOW_THREADS
2141 if (path->fd != -1)
2142 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002143#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002144 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002145 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002146 else
Steve Dowercc16be82016-09-08 10:35:16 -07002147 result = win32_lstat(path->wide, &st);
2148#else
2149 else
2150#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002151 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2152 result = LSTAT(path->narrow, &st);
2153 else
Steve Dowercc16be82016-09-08 10:35:16 -07002154#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002155#ifdef HAVE_FSTATAT
2156 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2157 result = fstatat(dir_fd, path->narrow, &st,
2158 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2159 else
Steve Dowercc16be82016-09-08 10:35:16 -07002160#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002161 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002162#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002163 Py_END_ALLOW_THREADS
2164
Victor Stinner292c8352012-10-30 02:17:38 +01002165 if (result != 0) {
2166 return path_error(path);
2167 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002168
2169 return _pystat_fromstructstat(&st);
2170}
2171
Larry Hastings2f936352014-08-05 14:04:04 +10002172/*[python input]
2173
2174for s in """
2175
2176FACCESSAT
2177FCHMODAT
2178FCHOWNAT
2179FSTATAT
2180LINKAT
2181MKDIRAT
2182MKFIFOAT
2183MKNODAT
2184OPENAT
2185READLINKAT
2186SYMLINKAT
2187UNLINKAT
2188
2189""".strip().split():
2190 s = s.strip()
2191 print("""
2192#ifdef HAVE_{s}
2193 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002194#else
Larry Hastings2f936352014-08-05 14:04:04 +10002195 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002196#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002197""".rstrip().format(s=s))
2198
2199for s in """
2200
2201FCHDIR
2202FCHMOD
2203FCHOWN
2204FDOPENDIR
2205FEXECVE
2206FPATHCONF
2207FSTATVFS
2208FTRUNCATE
2209
2210""".strip().split():
2211 s = s.strip()
2212 print("""
2213#ifdef HAVE_{s}
2214 #define PATH_HAVE_{s} 1
2215#else
2216 #define PATH_HAVE_{s} 0
2217#endif
2218
2219""".rstrip().format(s=s))
2220[python start generated code]*/
2221
2222#ifdef HAVE_FACCESSAT
2223 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2224#else
2225 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2226#endif
2227
2228#ifdef HAVE_FCHMODAT
2229 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2230#else
2231 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2232#endif
2233
2234#ifdef HAVE_FCHOWNAT
2235 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2236#else
2237 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2238#endif
2239
2240#ifdef HAVE_FSTATAT
2241 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2242#else
2243 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2244#endif
2245
2246#ifdef HAVE_LINKAT
2247 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2248#else
2249 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2250#endif
2251
2252#ifdef HAVE_MKDIRAT
2253 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2254#else
2255 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2256#endif
2257
2258#ifdef HAVE_MKFIFOAT
2259 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2260#else
2261 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2262#endif
2263
2264#ifdef HAVE_MKNODAT
2265 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2266#else
2267 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2268#endif
2269
2270#ifdef HAVE_OPENAT
2271 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2272#else
2273 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2274#endif
2275
2276#ifdef HAVE_READLINKAT
2277 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2278#else
2279 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2280#endif
2281
2282#ifdef HAVE_SYMLINKAT
2283 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2284#else
2285 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2286#endif
2287
2288#ifdef HAVE_UNLINKAT
2289 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2290#else
2291 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2292#endif
2293
2294#ifdef HAVE_FCHDIR
2295 #define PATH_HAVE_FCHDIR 1
2296#else
2297 #define PATH_HAVE_FCHDIR 0
2298#endif
2299
2300#ifdef HAVE_FCHMOD
2301 #define PATH_HAVE_FCHMOD 1
2302#else
2303 #define PATH_HAVE_FCHMOD 0
2304#endif
2305
2306#ifdef HAVE_FCHOWN
2307 #define PATH_HAVE_FCHOWN 1
2308#else
2309 #define PATH_HAVE_FCHOWN 0
2310#endif
2311
2312#ifdef HAVE_FDOPENDIR
2313 #define PATH_HAVE_FDOPENDIR 1
2314#else
2315 #define PATH_HAVE_FDOPENDIR 0
2316#endif
2317
2318#ifdef HAVE_FEXECVE
2319 #define PATH_HAVE_FEXECVE 1
2320#else
2321 #define PATH_HAVE_FEXECVE 0
2322#endif
2323
2324#ifdef HAVE_FPATHCONF
2325 #define PATH_HAVE_FPATHCONF 1
2326#else
2327 #define PATH_HAVE_FPATHCONF 0
2328#endif
2329
2330#ifdef HAVE_FSTATVFS
2331 #define PATH_HAVE_FSTATVFS 1
2332#else
2333 #define PATH_HAVE_FSTATVFS 0
2334#endif
2335
2336#ifdef HAVE_FTRUNCATE
2337 #define PATH_HAVE_FTRUNCATE 1
2338#else
2339 #define PATH_HAVE_FTRUNCATE 0
2340#endif
2341/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002342
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002343#ifdef MS_WINDOWS
2344 #undef PATH_HAVE_FTRUNCATE
2345 #define PATH_HAVE_FTRUNCATE 1
2346#endif
Larry Hastings31826802013-10-19 00:09:25 -07002347
Larry Hastings61272b72014-01-07 12:41:53 -08002348/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002349
2350class path_t_converter(CConverter):
2351
2352 type = "path_t"
2353 impl_by_reference = True
2354 parse_by_reference = True
2355
2356 converter = 'path_converter'
2357
2358 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002359 # right now path_t doesn't support default values.
2360 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002361 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002362 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002363
Larry Hastings2f936352014-08-05 14:04:04 +10002364 if self.c_default not in (None, 'Py_None'):
2365 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002366
2367 self.nullable = nullable
2368 self.allow_fd = allow_fd
2369
Larry Hastings7726ac92014-01-31 22:03:12 -08002370 def pre_render(self):
2371 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002372 if isinstance(value, str):
2373 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002374 return str(int(bool(value)))
2375
2376 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002377 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002378 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002379 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002380 strify(self.nullable),
2381 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002382 )
2383
2384 def cleanup(self):
2385 return "path_cleanup(&" + self.name + ");\n"
2386
2387
2388class dir_fd_converter(CConverter):
2389 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002390
Larry Hastings2f936352014-08-05 14:04:04 +10002391 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002392 if self.default in (unspecified, None):
2393 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002394 if isinstance(requires, str):
2395 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2396 else:
2397 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002398
Larry Hastings2f936352014-08-05 14:04:04 +10002399class fildes_converter(CConverter):
2400 type = 'int'
2401 converter = 'fildes_converter'
2402
2403class uid_t_converter(CConverter):
2404 type = "uid_t"
2405 converter = '_Py_Uid_Converter'
2406
2407class gid_t_converter(CConverter):
2408 type = "gid_t"
2409 converter = '_Py_Gid_Converter'
2410
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002411class dev_t_converter(CConverter):
2412 type = 'dev_t'
2413 converter = '_Py_Dev_Converter'
2414
2415class dev_t_return_converter(unsigned_long_return_converter):
2416 type = 'dev_t'
2417 conversion_fn = '_PyLong_FromDev'
2418 unsigned_cast = '(dev_t)'
2419
Larry Hastings2f936352014-08-05 14:04:04 +10002420class FSConverter_converter(CConverter):
2421 type = 'PyObject *'
2422 converter = 'PyUnicode_FSConverter'
2423 def converter_init(self):
2424 if self.default is not unspecified:
2425 fail("FSConverter_converter does not support default values")
2426 self.c_default = 'NULL'
2427
2428 def cleanup(self):
2429 return "Py_XDECREF(" + self.name + ");\n"
2430
2431class pid_t_converter(CConverter):
2432 type = 'pid_t'
2433 format_unit = '" _Py_PARSE_PID "'
2434
2435class idtype_t_converter(int_converter):
2436 type = 'idtype_t'
2437
2438class id_t_converter(CConverter):
2439 type = 'id_t'
2440 format_unit = '" _Py_PARSE_PID "'
2441
Benjamin Petersonca470632016-09-06 13:47:26 -07002442class intptr_t_converter(CConverter):
2443 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002444 format_unit = '" _Py_PARSE_INTPTR "'
2445
2446class Py_off_t_converter(CConverter):
2447 type = 'Py_off_t'
2448 converter = 'Py_off_t_converter'
2449
2450class Py_off_t_return_converter(long_return_converter):
2451 type = 'Py_off_t'
2452 conversion_fn = 'PyLong_FromPy_off_t'
2453
2454class path_confname_converter(CConverter):
2455 type="int"
2456 converter="conv_path_confname"
2457
2458class confstr_confname_converter(path_confname_converter):
2459 converter='conv_confstr_confname'
2460
2461class sysconf_confname_converter(path_confname_converter):
2462 converter="conv_sysconf_confname"
2463
2464class sched_param_converter(CConverter):
2465 type = 'struct sched_param'
2466 converter = 'convert_sched_param'
2467 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002468
Larry Hastings61272b72014-01-07 12:41:53 -08002469[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002470/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002471
Larry Hastings61272b72014-01-07 12:41:53 -08002472/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002473
Larry Hastings2a727912014-01-16 11:32:01 -08002474os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002475
2476 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002477 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002478 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002479
2480 *
2481
Larry Hastings2f936352014-08-05 14:04:04 +10002482 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002483 If not None, it should be a file descriptor open to a directory,
2484 and path should be a relative string; path will then be relative to
2485 that directory.
2486
2487 follow_symlinks: bool = True
2488 If False, and the last element of the path is a symbolic link,
2489 stat will examine the symbolic link itself instead of the file
2490 the link points to.
2491
2492Perform a stat system call on the given path.
2493
2494dir_fd and follow_symlinks may not be implemented
2495 on your platform. If they are unavailable, using them will raise a
2496 NotImplementedError.
2497
2498It's an error to use dir_fd or follow_symlinks when specifying path as
2499 an open file descriptor.
2500
Larry Hastings61272b72014-01-07 12:41:53 -08002501[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002502
Larry Hastings31826802013-10-19 00:09:25 -07002503static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002504os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002505/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002506{
2507 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2508}
2509
Larry Hastings2f936352014-08-05 14:04:04 +10002510
2511/*[clinic input]
2512os.lstat
2513
2514 path : path_t
2515
2516 *
2517
2518 dir_fd : dir_fd(requires='fstatat') = None
2519
2520Perform a stat system call on the given path, without following symbolic links.
2521
2522Like stat(), but do not follow symbolic links.
2523Equivalent to stat(path, follow_symlinks=False).
2524[clinic start generated code]*/
2525
Larry Hastings2f936352014-08-05 14:04:04 +10002526static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002527os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2528/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002529{
2530 int follow_symlinks = 0;
2531 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2532}
Larry Hastings31826802013-10-19 00:09:25 -07002533
Larry Hastings2f936352014-08-05 14:04:04 +10002534
Larry Hastings61272b72014-01-07 12:41:53 -08002535/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002536os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002537
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002538 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002539 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002540
2541 mode: int
2542 Operating-system mode bitfield. Can be F_OK to test existence,
2543 or the inclusive-OR of R_OK, W_OK, and X_OK.
2544
2545 *
2546
Larry Hastings2f936352014-08-05 14:04:04 +10002547 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002548 If not None, it should be a file descriptor open to a directory,
2549 and path should be relative; path will then be relative to that
2550 directory.
2551
2552 effective_ids: bool = False
2553 If True, access will use the effective uid/gid instead of
2554 the real uid/gid.
2555
2556 follow_symlinks: bool = True
2557 If False, and the last element of the path is a symbolic link,
2558 access will examine the symbolic link itself instead of the file
2559 the link points to.
2560
2561Use the real uid/gid to test for access to a path.
2562
2563{parameters}
2564dir_fd, effective_ids, and follow_symlinks may not be implemented
2565 on your platform. If they are unavailable, using them will raise a
2566 NotImplementedError.
2567
2568Note that most operations will use the effective uid/gid, therefore this
2569 routine can be used in a suid/sgid environment to test if the invoking user
2570 has the specified access to the path.
2571
Larry Hastings61272b72014-01-07 12:41:53 -08002572[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002573
Larry Hastings2f936352014-08-05 14:04:04 +10002574static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002575os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002576 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002577/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002578{
Larry Hastings2f936352014-08-05 14:04:04 +10002579 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002580
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002581#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002582 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002583#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002584 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002585#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002586
Larry Hastings9cf065c2012-06-22 16:30:09 -07002587#ifndef HAVE_FACCESSAT
2588 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002589 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002590
2591 if (effective_ids) {
2592 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002593 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002594 }
2595#endif
2596
2597#ifdef MS_WINDOWS
2598 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002599 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002600 Py_END_ALLOW_THREADS
2601
2602 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002603 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002604 * * we didn't get a -1, and
2605 * * write access wasn't requested,
2606 * * or the file isn't read-only,
2607 * * or it's a directory.
2608 * (Directories cannot be read-only on Windows.)
2609 */
Larry Hastings2f936352014-08-05 14:04:04 +10002610 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002611 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002612 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002613 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002614#else
2615
2616 Py_BEGIN_ALLOW_THREADS
2617#ifdef HAVE_FACCESSAT
2618 if ((dir_fd != DEFAULT_DIR_FD) ||
2619 effective_ids ||
2620 !follow_symlinks) {
2621 int flags = 0;
2622 if (!follow_symlinks)
2623 flags |= AT_SYMLINK_NOFOLLOW;
2624 if (effective_ids)
2625 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002626 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002627 }
2628 else
2629#endif
Larry Hastings31826802013-10-19 00:09:25 -07002630 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002631 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002632 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002633#endif
2634
Larry Hastings9cf065c2012-06-22 16:30:09 -07002635 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002636}
2637
Guido van Rossumd371ff11999-01-25 16:12:23 +00002638#ifndef F_OK
2639#define F_OK 0
2640#endif
2641#ifndef R_OK
2642#define R_OK 4
2643#endif
2644#ifndef W_OK
2645#define W_OK 2
2646#endif
2647#ifndef X_OK
2648#define X_OK 1
2649#endif
2650
Larry Hastings31826802013-10-19 00:09:25 -07002651
Guido van Rossumd371ff11999-01-25 16:12:23 +00002652#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002653/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002654os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002655
2656 fd: int
2657 Integer file descriptor handle.
2658
2659 /
2660
2661Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002662[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002663
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002664static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002665os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002666/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002667{
2668 char *ret;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002669
Larry Hastings31826802013-10-19 00:09:25 -07002670 ret = ttyname(fd);
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002671 if (ret == NULL) {
2672 return posix_error();
2673 }
2674 return PyUnicode_DecodeFSDefault(ret);
Guido van Rossum94f6f721999-01-06 18:42:14 +00002675}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002676#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002677
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002678#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002679/*[clinic input]
2680os.ctermid
2681
2682Return the name of the controlling terminal for this process.
2683[clinic start generated code]*/
2684
Larry Hastings2f936352014-08-05 14:04:04 +10002685static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002686os_ctermid_impl(PyObject *module)
2687/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002688{
Victor Stinner8c62be82010-05-06 00:08:46 +00002689 char *ret;
2690 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002691
Greg Wardb48bc172000-03-01 21:51:56 +00002692#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002693 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002694#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002695 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002696#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002697 if (ret == NULL)
2698 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002699 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002700}
Larry Hastings2f936352014-08-05 14:04:04 +10002701#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002702
Larry Hastings2f936352014-08-05 14:04:04 +10002703
2704/*[clinic input]
2705os.chdir
2706
2707 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2708
2709Change the current working directory to the specified path.
2710
2711path may always be specified as a string.
2712On some platforms, path may also be specified as an open file descriptor.
2713 If this functionality is unavailable, using it raises an exception.
2714[clinic start generated code]*/
2715
Larry Hastings2f936352014-08-05 14:04:04 +10002716static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002717os_chdir_impl(PyObject *module, path_t *path)
2718/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002719{
2720 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002721
2722 Py_BEGIN_ALLOW_THREADS
2723#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002724 /* on unix, success = 0, on windows, success = !0 */
2725 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002726#else
2727#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002728 if (path->fd != -1)
2729 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002730 else
2731#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002732 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002733#endif
2734 Py_END_ALLOW_THREADS
2735
2736 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002737 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002738 }
2739
Larry Hastings2f936352014-08-05 14:04:04 +10002740 Py_RETURN_NONE;
2741}
2742
2743
2744#ifdef HAVE_FCHDIR
2745/*[clinic input]
2746os.fchdir
2747
2748 fd: fildes
2749
2750Change to the directory of the given file descriptor.
2751
2752fd must be opened on a directory, not a file.
2753Equivalent to os.chdir(fd).
2754
2755[clinic start generated code]*/
2756
Fred Drake4d1e64b2002-04-15 19:40:07 +00002757static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002758os_fchdir_impl(PyObject *module, int fd)
2759/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002760{
Larry Hastings2f936352014-08-05 14:04:04 +10002761 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002762}
2763#endif /* HAVE_FCHDIR */
2764
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002765
Larry Hastings2f936352014-08-05 14:04:04 +10002766/*[clinic input]
2767os.chmod
2768
2769 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002770 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002771 On some platforms, path may also be specified as an open file descriptor.
2772 If this functionality is unavailable, using it raises an exception.
2773
2774 mode: int
2775 Operating-system mode bitfield.
2776
2777 *
2778
2779 dir_fd : dir_fd(requires='fchmodat') = None
2780 If not None, it should be a file descriptor open to a directory,
2781 and path should be relative; path will then be relative to that
2782 directory.
2783
2784 follow_symlinks: bool = True
2785 If False, and the last element of the path is a symbolic link,
2786 chmod will modify the symbolic link itself instead of the file
2787 the link points to.
2788
2789Change the access permissions of a file.
2790
2791It is an error to use dir_fd or follow_symlinks when specifying path as
2792 an open file descriptor.
2793dir_fd and follow_symlinks may not be implemented on your platform.
2794 If they are unavailable, using them will raise a NotImplementedError.
2795
2796[clinic start generated code]*/
2797
Larry Hastings2f936352014-08-05 14:04:04 +10002798static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002799os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002800 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002801/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002802{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002803 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002804
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002805#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002806 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002807#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00002808
Larry Hastings9cf065c2012-06-22 16:30:09 -07002809#ifdef HAVE_FCHMODAT
2810 int fchmodat_nofollow_unsupported = 0;
2811#endif
2812
Larry Hastings9cf065c2012-06-22 16:30:09 -07002813#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
2814 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002815 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002816#endif
2817
2818#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002819 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002820 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01002821 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002822 result = 0;
2823 else {
2824 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00002825 attr &= ~FILE_ATTRIBUTE_READONLY;
2826 else
2827 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07002828 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002829 }
2830 Py_END_ALLOW_THREADS
2831
2832 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002833 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002834 }
2835#else /* MS_WINDOWS */
2836 Py_BEGIN_ALLOW_THREADS
2837#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002838 if (path->fd != -1)
2839 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002840 else
2841#endif
2842#ifdef HAVE_LCHMOD
2843 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10002844 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002845 else
2846#endif
2847#ifdef HAVE_FCHMODAT
2848 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
2849 /*
2850 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
2851 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002852 * and then says it isn't implemented yet.
2853 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002854 *
2855 * Once it is supported, os.chmod will automatically
2856 * support dir_fd and follow_symlinks=False. (Hopefully.)
2857 * Until then, we need to be careful what exception we raise.
2858 */
Larry Hastings2f936352014-08-05 14:04:04 +10002859 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002860 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2861 /*
2862 * But wait! We can't throw the exception without allowing threads,
2863 * and we can't do that in this nested scope. (Macro trickery, sigh.)
2864 */
2865 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002866 result &&
2867 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
2868 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00002869 }
2870 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00002871#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002872 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002873 Py_END_ALLOW_THREADS
2874
2875 if (result) {
2876#ifdef HAVE_FCHMODAT
2877 if (fchmodat_nofollow_unsupported) {
2878 if (dir_fd != DEFAULT_DIR_FD)
2879 dir_fd_and_follow_symlinks_invalid("chmod",
2880 dir_fd, follow_symlinks);
2881 else
2882 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08002883 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002884 }
2885 else
2886#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002887 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002888 }
2889#endif
2890
Larry Hastings2f936352014-08-05 14:04:04 +10002891 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002892}
2893
Larry Hastings9cf065c2012-06-22 16:30:09 -07002894
Christian Heimes4e30a842007-11-30 22:12:06 +00002895#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002896/*[clinic input]
2897os.fchmod
2898
2899 fd: int
2900 mode: int
2901
2902Change the access permissions of the file given by file descriptor fd.
2903
2904Equivalent to os.chmod(fd, mode).
2905[clinic start generated code]*/
2906
Larry Hastings2f936352014-08-05 14:04:04 +10002907static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002908os_fchmod_impl(PyObject *module, int fd, int mode)
2909/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002910{
2911 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00002912 int async_err = 0;
2913
2914 do {
2915 Py_BEGIN_ALLOW_THREADS
2916 res = fchmod(fd, mode);
2917 Py_END_ALLOW_THREADS
2918 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
2919 if (res != 0)
2920 return (!async_err) ? posix_error() : NULL;
2921
Victor Stinner8c62be82010-05-06 00:08:46 +00002922 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00002923}
2924#endif /* HAVE_FCHMOD */
2925
Larry Hastings2f936352014-08-05 14:04:04 +10002926
Christian Heimes4e30a842007-11-30 22:12:06 +00002927#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002928/*[clinic input]
2929os.lchmod
2930
2931 path: path_t
2932 mode: int
2933
2934Change the access permissions of a file, without following symbolic links.
2935
2936If path is a symlink, this affects the link itself rather than the target.
2937Equivalent to chmod(path, mode, follow_symlinks=False)."
2938[clinic start generated code]*/
2939
Larry Hastings2f936352014-08-05 14:04:04 +10002940static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002941os_lchmod_impl(PyObject *module, path_t *path, int mode)
2942/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002943{
Victor Stinner8c62be82010-05-06 00:08:46 +00002944 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00002945 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10002946 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00002947 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01002948 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10002949 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01002950 return NULL;
2951 }
Victor Stinner8c62be82010-05-06 00:08:46 +00002952 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00002953}
2954#endif /* HAVE_LCHMOD */
2955
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002956
Thomas Wouterscf297e42007-02-23 15:07:44 +00002957#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10002958/*[clinic input]
2959os.chflags
2960
2961 path: path_t
2962 flags: unsigned_long(bitwise=True)
2963 follow_symlinks: bool=True
2964
2965Set file flags.
2966
2967If follow_symlinks is False, and the last element of the path is a symbolic
2968 link, chflags will change flags on the symbolic link itself instead of the
2969 file the link points to.
2970follow_symlinks may not be implemented on your platform. If it is
2971unavailable, using it will raise a NotImplementedError.
2972
2973[clinic start generated code]*/
2974
Larry Hastings2f936352014-08-05 14:04:04 +10002975static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002976os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04002977 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002978/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002979{
2980 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002981
2982#ifndef HAVE_LCHFLAGS
2983 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002984 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002985#endif
2986
Victor Stinner8c62be82010-05-06 00:08:46 +00002987 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07002988#ifdef HAVE_LCHFLAGS
2989 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10002990 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002991 else
2992#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002993 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00002994 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07002995
Larry Hastings2f936352014-08-05 14:04:04 +10002996 if (result)
2997 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002998
Larry Hastings2f936352014-08-05 14:04:04 +10002999 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003000}
3001#endif /* HAVE_CHFLAGS */
3002
Larry Hastings2f936352014-08-05 14:04:04 +10003003
Thomas Wouterscf297e42007-02-23 15:07:44 +00003004#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003005/*[clinic input]
3006os.lchflags
3007
3008 path: path_t
3009 flags: unsigned_long(bitwise=True)
3010
3011Set file flags.
3012
3013This function will not follow symbolic links.
3014Equivalent to chflags(path, flags, follow_symlinks=False).
3015[clinic start generated code]*/
3016
Larry Hastings2f936352014-08-05 14:04:04 +10003017static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003018os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3019/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003020{
Victor Stinner8c62be82010-05-06 00:08:46 +00003021 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003022 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003023 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003024 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003025 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003026 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003027 }
Victor Stinner292c8352012-10-30 02:17:38 +01003028 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003029}
3030#endif /* HAVE_LCHFLAGS */
3031
Larry Hastings2f936352014-08-05 14:04:04 +10003032
Martin v. Löwis244edc82001-10-04 22:44:26 +00003033#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003034/*[clinic input]
3035os.chroot
3036 path: path_t
3037
3038Change root directory to path.
3039
3040[clinic start generated code]*/
3041
Larry Hastings2f936352014-08-05 14:04:04 +10003042static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003043os_chroot_impl(PyObject *module, path_t *path)
3044/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003045{
3046 int res;
3047 Py_BEGIN_ALLOW_THREADS
3048 res = chroot(path->narrow);
3049 Py_END_ALLOW_THREADS
3050 if (res < 0)
3051 return path_error(path);
3052 Py_RETURN_NONE;
3053}
3054#endif /* HAVE_CHROOT */
3055
Martin v. Löwis244edc82001-10-04 22:44:26 +00003056
Guido van Rossum21142a01999-01-08 21:05:37 +00003057#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003058/*[clinic input]
3059os.fsync
3060
3061 fd: fildes
3062
3063Force write of fd to disk.
3064[clinic start generated code]*/
3065
Larry Hastings2f936352014-08-05 14:04:04 +10003066static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003067os_fsync_impl(PyObject *module, int fd)
3068/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003069{
3070 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003071}
3072#endif /* HAVE_FSYNC */
3073
Larry Hastings2f936352014-08-05 14:04:04 +10003074
Ross Lagerwall7807c352011-03-17 20:20:30 +02003075#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003076/*[clinic input]
3077os.sync
3078
3079Force write of everything to disk.
3080[clinic start generated code]*/
3081
Larry Hastings2f936352014-08-05 14:04:04 +10003082static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003083os_sync_impl(PyObject *module)
3084/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003085{
3086 Py_BEGIN_ALLOW_THREADS
3087 sync();
3088 Py_END_ALLOW_THREADS
3089 Py_RETURN_NONE;
3090}
Larry Hastings2f936352014-08-05 14:04:04 +10003091#endif /* HAVE_SYNC */
3092
Ross Lagerwall7807c352011-03-17 20:20:30 +02003093
Guido van Rossum21142a01999-01-08 21:05:37 +00003094#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003095#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003096extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3097#endif
3098
Larry Hastings2f936352014-08-05 14:04:04 +10003099/*[clinic input]
3100os.fdatasync
3101
3102 fd: fildes
3103
3104Force write of fd to disk without forcing update of metadata.
3105[clinic start generated code]*/
3106
Larry Hastings2f936352014-08-05 14:04:04 +10003107static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003108os_fdatasync_impl(PyObject *module, int fd)
3109/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003110{
3111 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003112}
3113#endif /* HAVE_FDATASYNC */
3114
3115
Fredrik Lundh10723342000-07-10 16:38:09 +00003116#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003117/*[clinic input]
3118os.chown
3119
3120 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003121 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003122
3123 uid: uid_t
3124
3125 gid: gid_t
3126
3127 *
3128
3129 dir_fd : dir_fd(requires='fchownat') = None
3130 If not None, it should be a file descriptor open to a directory,
3131 and path should be relative; path will then be relative to that
3132 directory.
3133
3134 follow_symlinks: bool = True
3135 If False, and the last element of the path is a symbolic link,
3136 stat will examine the symbolic link itself instead of the file
3137 the link points to.
3138
3139Change the owner and group id of path to the numeric uid and gid.\
3140
3141path may always be specified as a string.
3142On some platforms, path may also be specified as an open file descriptor.
3143 If this functionality is unavailable, using it raises an exception.
3144If dir_fd is not None, it should be a file descriptor open to a directory,
3145 and path should be relative; path will then be relative to that directory.
3146If follow_symlinks is False, and the last element of the path is a symbolic
3147 link, chown will modify the symbolic link itself instead of the file the
3148 link points to.
3149It is an error to use dir_fd or follow_symlinks when specifying path as
3150 an open file descriptor.
3151dir_fd and follow_symlinks may not be implemented on your platform.
3152 If they are unavailable, using them will raise a NotImplementedError.
3153
3154[clinic start generated code]*/
3155
Larry Hastings2f936352014-08-05 14:04:04 +10003156static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003157os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003158 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003159/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003160{
3161 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003162
3163#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3164 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003165 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003166#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003167 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3168 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3169 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003170
3171#ifdef __APPLE__
3172 /*
3173 * This is for Mac OS X 10.3, which doesn't have lchown.
3174 * (But we still have an lchown symbol because of weak-linking.)
3175 * It doesn't have fchownat either. So there's no possibility
3176 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003177 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003178 if ((!follow_symlinks) && (lchown == NULL)) {
3179 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003180 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003181 }
3182#endif
3183
Victor Stinner8c62be82010-05-06 00:08:46 +00003184 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003185#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003186 if (path->fd != -1)
3187 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003188 else
3189#endif
3190#ifdef HAVE_LCHOWN
3191 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003192 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003193 else
3194#endif
3195#ifdef HAVE_FCHOWNAT
3196 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003197 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003198 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3199 else
3200#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003201 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003202 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003203
Larry Hastings2f936352014-08-05 14:04:04 +10003204 if (result)
3205 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003206
Larry Hastings2f936352014-08-05 14:04:04 +10003207 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003208}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003209#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003210
Larry Hastings2f936352014-08-05 14:04:04 +10003211
Christian Heimes4e30a842007-11-30 22:12:06 +00003212#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003213/*[clinic input]
3214os.fchown
3215
3216 fd: int
3217 uid: uid_t
3218 gid: gid_t
3219
3220Change the owner and group id of the file specified by file descriptor.
3221
3222Equivalent to os.chown(fd, uid, gid).
3223
3224[clinic start generated code]*/
3225
Larry Hastings2f936352014-08-05 14:04:04 +10003226static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003227os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3228/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003229{
Victor Stinner8c62be82010-05-06 00:08:46 +00003230 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003231 int async_err = 0;
3232
3233 do {
3234 Py_BEGIN_ALLOW_THREADS
3235 res = fchown(fd, uid, gid);
3236 Py_END_ALLOW_THREADS
3237 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3238 if (res != 0)
3239 return (!async_err) ? posix_error() : NULL;
3240
Victor Stinner8c62be82010-05-06 00:08:46 +00003241 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003242}
3243#endif /* HAVE_FCHOWN */
3244
Larry Hastings2f936352014-08-05 14:04:04 +10003245
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003246#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003247/*[clinic input]
3248os.lchown
3249
3250 path : path_t
3251 uid: uid_t
3252 gid: gid_t
3253
3254Change the owner and group id of path to the numeric uid and gid.
3255
3256This function will not follow symbolic links.
3257Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3258[clinic start generated code]*/
3259
Larry Hastings2f936352014-08-05 14:04:04 +10003260static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003261os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3262/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003263{
Victor Stinner8c62be82010-05-06 00:08:46 +00003264 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003265 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003266 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003267 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003268 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003269 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003270 }
Larry Hastings2f936352014-08-05 14:04:04 +10003271 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003272}
3273#endif /* HAVE_LCHOWN */
3274
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003275
Barry Warsaw53699e91996-12-10 23:23:01 +00003276static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003277posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003278{
Victor Stinner4403d7d2015-04-25 00:16:10 +02003279 char *buf, *tmpbuf;
3280 char *cwd;
3281 const size_t chunk = 1024;
3282 size_t buflen = 0;
3283 PyObject *obj;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003284
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003285#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003286 if (!use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003287 wchar_t wbuf[MAXPATHLEN];
Victor Stinner8c62be82010-05-06 00:08:46 +00003288 wchar_t *wbuf2 = wbuf;
3289 PyObject *resobj;
3290 DWORD len;
3291 Py_BEGIN_ALLOW_THREADS
Victor Stinner75875072013-11-24 19:23:25 +01003292 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003293 /* If the buffer is large enough, len does not include the
3294 terminating \0. If the buffer is too small, len includes
3295 the space needed for the terminator. */
Victor Stinner75875072013-11-24 19:23:25 +01003296 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003297 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003298 if (wbuf2)
3299 len = GetCurrentDirectoryW(len, wbuf2);
3300 }
3301 Py_END_ALLOW_THREADS
3302 if (!wbuf2) {
3303 PyErr_NoMemory();
3304 return NULL;
3305 }
3306 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003307 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003308 PyMem_RawFree(wbuf2);
Victor Stinnerb024e842012-10-31 22:24:06 +01003309 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003310 }
3311 resobj = PyUnicode_FromWideChar(wbuf2, len);
Victor Stinnerb024e842012-10-31 22:24:06 +01003312 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003313 PyMem_RawFree(wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003314 return resobj;
3315 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003316
3317 if (win32_warn_bytes_api())
3318 return NULL;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003319#endif
3320
Victor Stinner4403d7d2015-04-25 00:16:10 +02003321 buf = cwd = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003322 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003323 do {
3324 buflen += chunk;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003325#ifdef MS_WINDOWS
3326 if (buflen > INT_MAX) {
3327 PyErr_NoMemory();
3328 break;
3329 }
3330#endif
Victor Stinner4403d7d2015-04-25 00:16:10 +02003331 tmpbuf = PyMem_RawRealloc(buf, buflen);
3332 if (tmpbuf == NULL)
3333 break;
3334
3335 buf = tmpbuf;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003336#ifdef MS_WINDOWS
3337 cwd = getcwd(buf, (int)buflen);
3338#else
Victor Stinner4403d7d2015-04-25 00:16:10 +02003339 cwd = getcwd(buf, buflen);
Victor Stinnerc44f7072016-03-14 18:07:53 +01003340#endif
Victor Stinner4403d7d2015-04-25 00:16:10 +02003341 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003342 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003343
3344 if (cwd == NULL) {
3345 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003346 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003347 }
3348
Victor Stinner8c62be82010-05-06 00:08:46 +00003349 if (use_bytes)
Victor Stinner4403d7d2015-04-25 00:16:10 +02003350 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
3351 else
3352 obj = PyUnicode_DecodeFSDefault(buf);
3353 PyMem_RawFree(buf);
3354
3355 return obj;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003356}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003357
Larry Hastings2f936352014-08-05 14:04:04 +10003358
3359/*[clinic input]
3360os.getcwd
3361
3362Return a unicode string representing the current working directory.
3363[clinic start generated code]*/
3364
Larry Hastings2f936352014-08-05 14:04:04 +10003365static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003366os_getcwd_impl(PyObject *module)
3367/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003368{
3369 return posix_getcwd(0);
3370}
3371
Larry Hastings2f936352014-08-05 14:04:04 +10003372
3373/*[clinic input]
3374os.getcwdb
3375
3376Return a bytes string representing the current working directory.
3377[clinic start generated code]*/
3378
Larry Hastings2f936352014-08-05 14:04:04 +10003379static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003380os_getcwdb_impl(PyObject *module)
3381/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003382{
3383 return posix_getcwd(1);
3384}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003385
Larry Hastings2f936352014-08-05 14:04:04 +10003386
Larry Hastings9cf065c2012-06-22 16:30:09 -07003387#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3388#define HAVE_LINK 1
3389#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003390
Guido van Rossumb6775db1994-08-01 11:34:53 +00003391#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003392/*[clinic input]
3393
3394os.link
3395
3396 src : path_t
3397 dst : path_t
3398 *
3399 src_dir_fd : dir_fd = None
3400 dst_dir_fd : dir_fd = None
3401 follow_symlinks: bool = True
3402
3403Create a hard link to a file.
3404
3405If either src_dir_fd or dst_dir_fd is not None, it should be a file
3406 descriptor open to a directory, and the respective path string (src or dst)
3407 should be relative; the path will then be relative to that directory.
3408If follow_symlinks is False, and the last element of src is a symbolic
3409 link, link will create a link to the symbolic link itself instead of the
3410 file the link points to.
3411src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3412 platform. If they are unavailable, using them will raise a
3413 NotImplementedError.
3414[clinic start generated code]*/
3415
Larry Hastings2f936352014-08-05 14:04:04 +10003416static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003417os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003418 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003419/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003420{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003421#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003422 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003423#else
3424 int result;
3425#endif
3426
Larry Hastings9cf065c2012-06-22 16:30:09 -07003427#ifndef HAVE_LINKAT
3428 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3429 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003430 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003431 }
3432#endif
3433
Steve Dowercc16be82016-09-08 10:35:16 -07003434#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003435 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003436 PyErr_SetString(PyExc_NotImplementedError,
3437 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003438 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003439 }
Steve Dowercc16be82016-09-08 10:35:16 -07003440#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003441
Brian Curtin1b9df392010-11-24 20:24:31 +00003442#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003443 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003444 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003445 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003446
Larry Hastings2f936352014-08-05 14:04:04 +10003447 if (!result)
3448 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003449#else
3450 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003451#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003452 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3453 (dst_dir_fd != DEFAULT_DIR_FD) ||
3454 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003455 result = linkat(src_dir_fd, src->narrow,
3456 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003457 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3458 else
Steve Dowercc16be82016-09-08 10:35:16 -07003459#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003460 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003461 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003462
Larry Hastings2f936352014-08-05 14:04:04 +10003463 if (result)
3464 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003465#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003466
Larry Hastings2f936352014-08-05 14:04:04 +10003467 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003468}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003469#endif
3470
Brian Curtin1b9df392010-11-24 20:24:31 +00003471
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003472#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003473static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003474_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003475{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003476 PyObject *v;
3477 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3478 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003479 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003480 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003481 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003482 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003483
Steve Dowercc16be82016-09-08 10:35:16 -07003484 WIN32_FIND_DATAW wFileData;
3485 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003486
Steve Dowercc16be82016-09-08 10:35:16 -07003487 if (!path->wide) { /* Default arg: "." */
3488 po_wchars = L".";
3489 len = 1;
3490 } else {
3491 po_wchars = path->wide;
3492 len = wcslen(path->wide);
3493 }
3494 /* The +5 is so we can append "\\*.*\0" */
3495 wnamebuf = PyMem_New(wchar_t, len + 5);
3496 if (!wnamebuf) {
3497 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003498 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003499 }
Steve Dowercc16be82016-09-08 10:35:16 -07003500 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003501 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003502 wchar_t wch = wnamebuf[len-1];
3503 if (wch != SEP && wch != ALTSEP && wch != L':')
3504 wnamebuf[len++] = SEP;
3505 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003506 }
Steve Dowercc16be82016-09-08 10:35:16 -07003507 if ((list = PyList_New(0)) == NULL) {
3508 goto exit;
3509 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003510 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003511 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003512 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003513 if (hFindFile == INVALID_HANDLE_VALUE) {
3514 int error = GetLastError();
3515 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003516 goto exit;
3517 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003518 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003519 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003520 }
3521 do {
3522 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003523 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3524 wcscmp(wFileData.cFileName, L"..") != 0) {
3525 v = PyUnicode_FromWideChar(wFileData.cFileName,
3526 wcslen(wFileData.cFileName));
3527 if (path->narrow && v) {
3528 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3529 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003530 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003531 Py_DECREF(list);
3532 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003533 break;
3534 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003535 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003536 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003537 Py_DECREF(list);
3538 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003539 break;
3540 }
3541 Py_DECREF(v);
3542 }
3543 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003544 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003545 Py_END_ALLOW_THREADS
3546 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3547 it got to the end of the directory. */
3548 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003549 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003550 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003551 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003552 }
3553 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003554
Larry Hastings9cf065c2012-06-22 16:30:09 -07003555exit:
3556 if (hFindFile != INVALID_HANDLE_VALUE) {
3557 if (FindClose(hFindFile) == FALSE) {
3558 if (list != NULL) {
3559 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003560 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003561 }
3562 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003563 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003564 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003565
Larry Hastings9cf065c2012-06-22 16:30:09 -07003566 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003567} /* end of _listdir_windows_no_opendir */
3568
3569#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3570
3571static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003572_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003573{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003574 PyObject *v;
3575 DIR *dirp = NULL;
3576 struct dirent *ep;
3577 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003578#ifdef HAVE_FDOPENDIR
3579 int fd = -1;
3580#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003581
Victor Stinner8c62be82010-05-06 00:08:46 +00003582 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003583#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003584 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003585 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003586 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003587 if (fd == -1)
3588 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003589
Larry Hastingsfdaea062012-06-25 04:42:23 -07003590 return_str = 1;
3591
Larry Hastings9cf065c2012-06-22 16:30:09 -07003592 Py_BEGIN_ALLOW_THREADS
3593 dirp = fdopendir(fd);
3594 Py_END_ALLOW_THREADS
3595 }
3596 else
3597#endif
3598 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003599 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003600 if (path->narrow) {
3601 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003602 /* only return bytes if they specified a bytes-like object */
3603 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003604 }
3605 else {
3606 name = ".";
3607 return_str = 1;
3608 }
3609
Larry Hastings9cf065c2012-06-22 16:30:09 -07003610 Py_BEGIN_ALLOW_THREADS
3611 dirp = opendir(name);
3612 Py_END_ALLOW_THREADS
3613 }
3614
3615 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003616 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003617#ifdef HAVE_FDOPENDIR
3618 if (fd != -1) {
3619 Py_BEGIN_ALLOW_THREADS
3620 close(fd);
3621 Py_END_ALLOW_THREADS
3622 }
3623#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003624 goto exit;
3625 }
3626 if ((list = PyList_New(0)) == NULL) {
3627 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003628 }
3629 for (;;) {
3630 errno = 0;
3631 Py_BEGIN_ALLOW_THREADS
3632 ep = readdir(dirp);
3633 Py_END_ALLOW_THREADS
3634 if (ep == NULL) {
3635 if (errno == 0) {
3636 break;
3637 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003638 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003639 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003640 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003641 }
3642 }
3643 if (ep->d_name[0] == '.' &&
3644 (NAMLEN(ep) == 1 ||
3645 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3646 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003647 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003648 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3649 else
3650 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003651 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003652 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003653 break;
3654 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003655 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003656 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003657 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003658 break;
3659 }
3660 Py_DECREF(v);
3661 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003662
Larry Hastings9cf065c2012-06-22 16:30:09 -07003663exit:
3664 if (dirp != NULL) {
3665 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003666#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003667 if (fd > -1)
3668 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003669#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003670 closedir(dirp);
3671 Py_END_ALLOW_THREADS
3672 }
3673
Larry Hastings9cf065c2012-06-22 16:30:09 -07003674 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003675} /* end of _posix_listdir */
3676#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003677
Larry Hastings2f936352014-08-05 14:04:04 +10003678
3679/*[clinic input]
3680os.listdir
3681
3682 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3683
3684Return a list containing the names of the files in the directory.
3685
BNMetricsb9427072018-11-02 15:20:19 +00003686path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003687 the filenames returned will also be bytes; in all other circumstances
3688 the filenames returned will be str.
3689If path is None, uses the path='.'.
3690On some platforms, path may also be specified as an open file descriptor;\
3691 the file descriptor must refer to a directory.
3692 If this functionality is unavailable, using it raises NotImplementedError.
3693
3694The list is in arbitrary order. It does not include the special
3695entries '.' and '..' even if they are present in the directory.
3696
3697
3698[clinic start generated code]*/
3699
Larry Hastings2f936352014-08-05 14:04:04 +10003700static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003701os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003702/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003703{
3704#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3705 return _listdir_windows_no_opendir(path, NULL);
3706#else
3707 return _posix_listdir(path, NULL);
3708#endif
3709}
3710
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003711#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003712/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003713/*[clinic input]
3714os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003715
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003716 path: path_t
3717 /
3718
3719[clinic start generated code]*/
3720
3721static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003722os__getfullpathname_impl(PyObject *module, path_t *path)
3723/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003724{
Steve Dowercc16be82016-09-08 10:35:16 -07003725 wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
3726 wchar_t *wtemp;
3727 DWORD result;
3728 PyObject *v;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003729
Steve Dowercc16be82016-09-08 10:35:16 -07003730 result = GetFullPathNameW(path->wide,
3731 Py_ARRAY_LENGTH(woutbuf),
3732 woutbuf, &wtemp);
3733 if (result > Py_ARRAY_LENGTH(woutbuf)) {
3734 woutbufp = PyMem_New(wchar_t, result);
3735 if (!woutbufp)
3736 return PyErr_NoMemory();
3737 result = GetFullPathNameW(path->wide, result, woutbufp, &wtemp);
Victor Stinner8c62be82010-05-06 00:08:46 +00003738 }
Steve Dowercc16be82016-09-08 10:35:16 -07003739 if (result) {
3740 v = PyUnicode_FromWideChar(woutbufp, wcslen(woutbufp));
3741 if (path->narrow)
3742 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3743 } else
3744 v = win32_error_object("GetFullPathNameW", path->object);
3745 if (woutbufp != woutbuf)
3746 PyMem_Free(woutbufp);
3747 return v;
Larry Hastings2f936352014-08-05 14:04:04 +10003748}
Brian Curtind40e6f72010-07-08 21:39:08 +00003749
Brian Curtind25aef52011-06-13 15:16:04 -05003750
Larry Hastings2f936352014-08-05 14:04:04 +10003751/*[clinic input]
3752os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003753
Steve Dower23ad6d02018-02-22 10:39:10 -08003754 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003755 /
3756
3757A helper function for samepath on windows.
3758[clinic start generated code]*/
3759
Larry Hastings2f936352014-08-05 14:04:04 +10003760static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003761os__getfinalpathname_impl(PyObject *module, path_t *path)
3762/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003763{
3764 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003765 wchar_t buf[MAXPATHLEN], *target_path = buf;
3766 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003767 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003768 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003769
Steve Dower23ad6d02018-02-22 10:39:10 -08003770 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003771 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003772 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003773 0, /* desired access */
3774 0, /* share mode */
3775 NULL, /* security attributes */
3776 OPEN_EXISTING,
3777 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3778 FILE_FLAG_BACKUP_SEMANTICS,
3779 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003780 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003781
Steve Dower23ad6d02018-02-22 10:39:10 -08003782 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003783 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08003784 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003785
3786 /* We have a good handle to the target, use it to determine the
3787 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003788 while (1) {
3789 Py_BEGIN_ALLOW_THREADS
3790 result_length = GetFinalPathNameByHandleW(hFile, target_path,
3791 buf_size, VOLUME_NAME_DOS);
3792 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003793
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003794 if (!result_length) {
3795 result = win32_error_object("GetFinalPathNameByHandleW",
3796 path->object);
3797 goto cleanup;
3798 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003799
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003800 if (result_length < buf_size) {
3801 break;
3802 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003803
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003804 wchar_t *tmp;
3805 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
3806 result_length * sizeof(*tmp));
3807 if (!tmp) {
3808 result = PyErr_NoMemory();
3809 goto cleanup;
3810 }
3811
3812 buf_size = result_length;
3813 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08003814 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003815
Victor Stinner9d3b93b2011-11-22 02:27:30 +01003816 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dower23ad6d02018-02-22 10:39:10 -08003817 if (path->narrow)
3818 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dower23ad6d02018-02-22 10:39:10 -08003819
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003820cleanup:
3821 if (target_path != buf) {
3822 PyMem_Free(target_path);
3823 }
3824 CloseHandle(hFile);
3825 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10003826}
Brian Curtin62857742010-09-06 17:07:27 +00003827
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003828/*[clinic input]
3829os._isdir
3830
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003831 path as arg: object
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003832 /
3833
Serhiy Storchaka579f0382016-11-08 20:21:22 +02003834Return true if the pathname refers to an existing directory.
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003835[clinic start generated code]*/
3836
Brian Curtin9c669cc2011-06-08 18:17:18 -05003837static PyObject *
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003838os__isdir(PyObject *module, PyObject *arg)
3839/*[clinic end generated code: output=404f334d85d4bf25 input=36cb6785874d479e]*/
Brian Curtin9c669cc2011-06-08 18:17:18 -05003840{
Brian Curtin9c669cc2011-06-08 18:17:18 -05003841 DWORD attributes;
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003842 path_t path = PATH_T_INITIALIZE("_isdir", "path", 0, 0);
3843
3844 if (!path_converter(arg, &path)) {
3845 if (PyErr_ExceptionMatches(PyExc_ValueError)) {
3846 PyErr_Clear();
3847 Py_RETURN_FALSE;
3848 }
3849 return NULL;
3850 }
Brian Curtin9c669cc2011-06-08 18:17:18 -05003851
Steve Dowerb22a6772016-07-17 20:49:38 -07003852 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003853 attributes = GetFileAttributesW(path.wide);
Steve Dowerb22a6772016-07-17 20:49:38 -07003854 Py_END_ALLOW_THREADS
Brian Curtin9c669cc2011-06-08 18:17:18 -05003855
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003856 path_cleanup(&path);
Brian Curtin9c669cc2011-06-08 18:17:18 -05003857 if (attributes == INVALID_FILE_ATTRIBUTES)
3858 Py_RETURN_FALSE;
3859
Brian Curtin9c669cc2011-06-08 18:17:18 -05003860 if (attributes & FILE_ATTRIBUTE_DIRECTORY)
3861 Py_RETURN_TRUE;
3862 else
3863 Py_RETURN_FALSE;
3864}
Tim Golden6b528062013-08-01 12:44:00 +01003865
Tim Golden6b528062013-08-01 12:44:00 +01003866
Larry Hastings2f936352014-08-05 14:04:04 +10003867/*[clinic input]
3868os._getvolumepathname
3869
Steve Dower23ad6d02018-02-22 10:39:10 -08003870 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003871
3872A helper function for ismount on Win32.
3873[clinic start generated code]*/
3874
Larry Hastings2f936352014-08-05 14:04:04 +10003875static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003876os__getvolumepathname_impl(PyObject *module, path_t *path)
3877/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003878{
3879 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003880 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01003881 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01003882 BOOL ret;
3883
Tim Golden6b528062013-08-01 12:44:00 +01003884 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08003885 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01003886
Victor Stinner850a18e2017-10-24 16:53:32 -07003887 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01003888 PyErr_SetString(PyExc_OverflowError, "path too long");
3889 return NULL;
3890 }
3891
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003892 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01003893 if (mountpath == NULL)
3894 return PyErr_NoMemory();
3895
3896 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08003897 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01003898 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01003899 Py_END_ALLOW_THREADS
3900
3901 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08003902 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01003903 goto exit;
3904 }
3905 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08003906 if (path->narrow)
3907 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01003908
3909exit:
3910 PyMem_Free(mountpath);
3911 return result;
3912}
Tim Golden6b528062013-08-01 12:44:00 +01003913
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003914#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00003915
Larry Hastings2f936352014-08-05 14:04:04 +10003916
3917/*[clinic input]
3918os.mkdir
3919
3920 path : path_t
3921
3922 mode: int = 0o777
3923
3924 *
3925
3926 dir_fd : dir_fd(requires='mkdirat') = None
3927
3928# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
3929
3930Create a directory.
3931
3932If dir_fd is not None, it should be a file descriptor open to a directory,
3933 and path should be relative; path will then be relative to that directory.
3934dir_fd may not be implemented on your platform.
3935 If it is unavailable, using it will raise a NotImplementedError.
3936
3937The mode argument is ignored on Windows.
3938[clinic start generated code]*/
3939
Larry Hastings2f936352014-08-05 14:04:04 +10003940static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003941os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
3942/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003943{
3944 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003945
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003946#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003947 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003948 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00003949 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003950
Larry Hastings2f936352014-08-05 14:04:04 +10003951 if (!result)
3952 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003953#else
Victor Stinner8c62be82010-05-06 00:08:46 +00003954 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003955#if HAVE_MKDIRAT
3956 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10003957 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003958 else
3959#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02003960#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10003961 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00003962#else
Larry Hastings2f936352014-08-05 14:04:04 +10003963 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00003964#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00003965 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003966 if (result < 0)
3967 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07003968#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10003969 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003970}
3971
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003972
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003973/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
3974#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00003975#include <sys/resource.h>
3976#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00003977
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003978
3979#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10003980/*[clinic input]
3981os.nice
3982
3983 increment: int
3984 /
3985
3986Add increment to the priority of process and return the new priority.
3987[clinic start generated code]*/
3988
Larry Hastings2f936352014-08-05 14:04:04 +10003989static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003990os_nice_impl(PyObject *module, int increment)
3991/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003992{
3993 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00003994
Victor Stinner8c62be82010-05-06 00:08:46 +00003995 /* There are two flavours of 'nice': one that returns the new
3996 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07003997 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00003998 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00003999
Victor Stinner8c62be82010-05-06 00:08:46 +00004000 If we are of the nice family that returns the new priority, we
4001 need to clear errno before the call, and check if errno is filled
4002 before calling posix_error() on a returnvalue of -1, because the
4003 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004004
Victor Stinner8c62be82010-05-06 00:08:46 +00004005 errno = 0;
4006 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004007#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004008 if (value == 0)
4009 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004010#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004011 if (value == -1 && errno != 0)
4012 /* either nice() or getpriority() returned an error */
4013 return posix_error();
4014 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004015}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004016#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004017
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004018
4019#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004020/*[clinic input]
4021os.getpriority
4022
4023 which: int
4024 who: int
4025
4026Return program scheduling priority.
4027[clinic start generated code]*/
4028
Larry Hastings2f936352014-08-05 14:04:04 +10004029static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004030os_getpriority_impl(PyObject *module, int which, int who)
4031/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004032{
4033 int retval;
4034
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004035 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004036 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004037 if (errno != 0)
4038 return posix_error();
4039 return PyLong_FromLong((long)retval);
4040}
4041#endif /* HAVE_GETPRIORITY */
4042
4043
4044#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004045/*[clinic input]
4046os.setpriority
4047
4048 which: int
4049 who: int
4050 priority: int
4051
4052Set program scheduling priority.
4053[clinic start generated code]*/
4054
Larry Hastings2f936352014-08-05 14:04:04 +10004055static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004056os_setpriority_impl(PyObject *module, int which, int who, int priority)
4057/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004058{
4059 int retval;
4060
4061 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004062 if (retval == -1)
4063 return posix_error();
4064 Py_RETURN_NONE;
4065}
4066#endif /* HAVE_SETPRIORITY */
4067
4068
Barry Warsaw53699e91996-12-10 23:23:01 +00004069static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004070internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004071{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004072 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004073 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004074
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004075#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004076 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004077 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004078#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004079 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004080#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004081
Larry Hastings9cf065c2012-06-22 16:30:09 -07004082 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4083 (dst_dir_fd != DEFAULT_DIR_FD);
4084#ifndef HAVE_RENAMEAT
4085 if (dir_fd_specified) {
4086 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004087 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004088 }
4089#endif
4090
Larry Hastings9cf065c2012-06-22 16:30:09 -07004091#ifdef MS_WINDOWS
4092 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004093 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004094 Py_END_ALLOW_THREADS
4095
Larry Hastings2f936352014-08-05 14:04:04 +10004096 if (!result)
4097 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004098
4099#else
Steve Dowercc16be82016-09-08 10:35:16 -07004100 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4101 PyErr_Format(PyExc_ValueError,
4102 "%s: src and dst must be the same type", function_name);
4103 return NULL;
4104 }
4105
Larry Hastings9cf065c2012-06-22 16:30:09 -07004106 Py_BEGIN_ALLOW_THREADS
4107#ifdef HAVE_RENAMEAT
4108 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004109 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004110 else
4111#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004112 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004113 Py_END_ALLOW_THREADS
4114
Larry Hastings2f936352014-08-05 14:04:04 +10004115 if (result)
4116 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004117#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004118 Py_RETURN_NONE;
4119}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004120
Larry Hastings2f936352014-08-05 14:04:04 +10004121
4122/*[clinic input]
4123os.rename
4124
4125 src : path_t
4126 dst : path_t
4127 *
4128 src_dir_fd : dir_fd = None
4129 dst_dir_fd : dir_fd = None
4130
4131Rename a file or directory.
4132
4133If either src_dir_fd or dst_dir_fd is not None, it should be a file
4134 descriptor open to a directory, and the respective path string (src or dst)
4135 should be relative; the path will then be relative to that directory.
4136src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4137 If they are unavailable, using them will raise a NotImplementedError.
4138[clinic start generated code]*/
4139
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004140static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004141os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004142 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004143/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004144{
Larry Hastings2f936352014-08-05 14:04:04 +10004145 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004146}
4147
Larry Hastings2f936352014-08-05 14:04:04 +10004148
4149/*[clinic input]
4150os.replace = os.rename
4151
4152Rename a file or directory, overwriting the destination.
4153
4154If either src_dir_fd or dst_dir_fd is not None, it should be a file
4155 descriptor open to a directory, and the respective path string (src or dst)
4156 should be relative; the path will then be relative to that directory.
4157src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4158 If they are unavailable, using them will raise a NotImplementedError."
4159[clinic start generated code]*/
4160
Larry Hastings2f936352014-08-05 14:04:04 +10004161static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004162os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4163 int dst_dir_fd)
4164/*[clinic end generated code: output=1968c02e7857422b input=25515dfb107c8421]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004165{
4166 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4167}
4168
4169
4170/*[clinic input]
4171os.rmdir
4172
4173 path: path_t
4174 *
4175 dir_fd: dir_fd(requires='unlinkat') = None
4176
4177Remove a directory.
4178
4179If dir_fd is not None, it should be a file descriptor open to a directory,
4180 and path should be relative; path will then be relative to that directory.
4181dir_fd may not be implemented on your platform.
4182 If it is unavailable, using it will raise a NotImplementedError.
4183[clinic start generated code]*/
4184
Larry Hastings2f936352014-08-05 14:04:04 +10004185static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004186os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4187/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004188{
4189 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004190
4191 Py_BEGIN_ALLOW_THREADS
4192#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004193 /* Windows, success=1, UNIX, success=0 */
4194 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004195#else
4196#ifdef HAVE_UNLINKAT
4197 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004198 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004199 else
4200#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004201 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004202#endif
4203 Py_END_ALLOW_THREADS
4204
Larry Hastings2f936352014-08-05 14:04:04 +10004205 if (result)
4206 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004207
Larry Hastings2f936352014-08-05 14:04:04 +10004208 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004209}
4210
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004211
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004212#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004213#ifdef MS_WINDOWS
4214/*[clinic input]
4215os.system -> long
4216
4217 command: Py_UNICODE
4218
4219Execute the command in a subshell.
4220[clinic start generated code]*/
4221
Larry Hastings2f936352014-08-05 14:04:04 +10004222static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004223os_system_impl(PyObject *module, const Py_UNICODE *command)
4224/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004225{
4226 long result;
Victor Stinner8c62be82010-05-06 00:08:46 +00004227 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004228 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004229 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004230 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004231 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004232 return result;
4233}
4234#else /* MS_WINDOWS */
4235/*[clinic input]
4236os.system -> long
4237
4238 command: FSConverter
4239
4240Execute the command in a subshell.
4241[clinic start generated code]*/
4242
Larry Hastings2f936352014-08-05 14:04:04 +10004243static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004244os_system_impl(PyObject *module, PyObject *command)
4245/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004246{
4247 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004248 const char *bytes = PyBytes_AsString(command);
Larry Hastings2f936352014-08-05 14:04:04 +10004249 Py_BEGIN_ALLOW_THREADS
4250 result = system(bytes);
4251 Py_END_ALLOW_THREADS
4252 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004253}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004254#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004255#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004256
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004257
Larry Hastings2f936352014-08-05 14:04:04 +10004258/*[clinic input]
4259os.umask
4260
4261 mask: int
4262 /
4263
4264Set the current numeric umask and return the previous umask.
4265[clinic start generated code]*/
4266
Larry Hastings2f936352014-08-05 14:04:04 +10004267static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004268os_umask_impl(PyObject *module, int mask)
4269/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004270{
4271 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004272 if (i < 0)
4273 return posix_error();
4274 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004275}
4276
Brian Curtind40e6f72010-07-08 21:39:08 +00004277#ifdef MS_WINDOWS
4278
4279/* override the default DeleteFileW behavior so that directory
4280symlinks can be removed with this function, the same as with
4281Unix symlinks */
4282BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4283{
4284 WIN32_FILE_ATTRIBUTE_DATA info;
4285 WIN32_FIND_DATAW find_data;
4286 HANDLE find_data_handle;
4287 int is_directory = 0;
4288 int is_link = 0;
4289
4290 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4291 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004292
Brian Curtind40e6f72010-07-08 21:39:08 +00004293 /* Get WIN32_FIND_DATA structure for the path to determine if
4294 it is a symlink */
4295 if(is_directory &&
4296 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4297 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4298
4299 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004300 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4301 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4302 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4303 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004304 FindClose(find_data_handle);
4305 }
4306 }
4307 }
4308
4309 if (is_directory && is_link)
4310 return RemoveDirectoryW(lpFileName);
4311
4312 return DeleteFileW(lpFileName);
4313}
4314#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004315
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004316
Larry Hastings2f936352014-08-05 14:04:04 +10004317/*[clinic input]
4318os.unlink
4319
4320 path: path_t
4321 *
4322 dir_fd: dir_fd(requires='unlinkat')=None
4323
4324Remove a file (same as remove()).
4325
4326If dir_fd is not None, it should be a file descriptor open to a directory,
4327 and path should be relative; path will then be relative to that directory.
4328dir_fd may not be implemented on your platform.
4329 If it is unavailable, using it will raise a NotImplementedError.
4330
4331[clinic start generated code]*/
4332
Larry Hastings2f936352014-08-05 14:04:04 +10004333static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004334os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4335/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004336{
4337 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004338
4339 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004340 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004341#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004342 /* Windows, success=1, UNIX, success=0 */
4343 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004344#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004345#ifdef HAVE_UNLINKAT
4346 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004347 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004348 else
4349#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004350 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004351#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004352 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004353 Py_END_ALLOW_THREADS
4354
Larry Hastings2f936352014-08-05 14:04:04 +10004355 if (result)
4356 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004357
Larry Hastings2f936352014-08-05 14:04:04 +10004358 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004359}
4360
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004361
Larry Hastings2f936352014-08-05 14:04:04 +10004362/*[clinic input]
4363os.remove = os.unlink
4364
4365Remove a file (same as unlink()).
4366
4367If dir_fd is not None, it should be a file descriptor open to a directory,
4368 and path should be relative; path will then be relative to that directory.
4369dir_fd may not be implemented on your platform.
4370 If it is unavailable, using it will raise a NotImplementedError.
4371[clinic start generated code]*/
4372
Larry Hastings2f936352014-08-05 14:04:04 +10004373static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004374os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4375/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004376{
4377 return os_unlink_impl(module, path, dir_fd);
4378}
4379
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004380
Larry Hastings605a62d2012-06-24 04:33:36 -07004381static PyStructSequence_Field uname_result_fields[] = {
4382 {"sysname", "operating system name"},
4383 {"nodename", "name of machine on network (implementation-defined)"},
4384 {"release", "operating system release"},
4385 {"version", "operating system version"},
4386 {"machine", "hardware identifier"},
4387 {NULL}
4388};
4389
4390PyDoc_STRVAR(uname_result__doc__,
4391"uname_result: Result from os.uname().\n\n\
4392This object may be accessed either as a tuple of\n\
4393 (sysname, nodename, release, version, machine),\n\
4394or via the attributes sysname, nodename, release, version, and machine.\n\
4395\n\
4396See os.uname for more information.");
4397
4398static PyStructSequence_Desc uname_result_desc = {
4399 "uname_result", /* name */
4400 uname_result__doc__, /* doc */
4401 uname_result_fields,
4402 5
4403};
4404
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004405static PyTypeObject* UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07004406
4407
4408#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004409/*[clinic input]
4410os.uname
4411
4412Return an object identifying the current operating system.
4413
4414The object behaves like a named tuple with the following fields:
4415 (sysname, nodename, release, version, machine)
4416
4417[clinic start generated code]*/
4418
Larry Hastings2f936352014-08-05 14:04:04 +10004419static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004420os_uname_impl(PyObject *module)
4421/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004422{
Victor Stinner8c62be82010-05-06 00:08:46 +00004423 struct utsname u;
4424 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004425 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004426
Victor Stinner8c62be82010-05-06 00:08:46 +00004427 Py_BEGIN_ALLOW_THREADS
4428 res = uname(&u);
4429 Py_END_ALLOW_THREADS
4430 if (res < 0)
4431 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004432
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004433 value = PyStructSequence_New(UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004434 if (value == NULL)
4435 return NULL;
4436
4437#define SET(i, field) \
4438 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004439 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004440 if (!o) { \
4441 Py_DECREF(value); \
4442 return NULL; \
4443 } \
4444 PyStructSequence_SET_ITEM(value, i, o); \
4445 } \
4446
4447 SET(0, u.sysname);
4448 SET(1, u.nodename);
4449 SET(2, u.release);
4450 SET(3, u.version);
4451 SET(4, u.machine);
4452
4453#undef SET
4454
4455 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004456}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004457#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004458
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004459
Larry Hastings9cf065c2012-06-22 16:30:09 -07004460
4461typedef struct {
4462 int now;
4463 time_t atime_s;
4464 long atime_ns;
4465 time_t mtime_s;
4466 long mtime_ns;
4467} utime_t;
4468
4469/*
Victor Stinner484df002014-10-09 13:52:31 +02004470 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004471 * they also intentionally leak the declaration of a pointer named "time"
4472 */
4473#define UTIME_TO_TIMESPEC \
4474 struct timespec ts[2]; \
4475 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004476 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004477 time = NULL; \
4478 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004479 ts[0].tv_sec = ut->atime_s; \
4480 ts[0].tv_nsec = ut->atime_ns; \
4481 ts[1].tv_sec = ut->mtime_s; \
4482 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004483 time = ts; \
4484 } \
4485
4486#define UTIME_TO_TIMEVAL \
4487 struct timeval tv[2]; \
4488 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004489 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004490 time = NULL; \
4491 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004492 tv[0].tv_sec = ut->atime_s; \
4493 tv[0].tv_usec = ut->atime_ns / 1000; \
4494 tv[1].tv_sec = ut->mtime_s; \
4495 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004496 time = tv; \
4497 } \
4498
4499#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004500 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004501 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004502 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004503 time = NULL; \
4504 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004505 u.actime = ut->atime_s; \
4506 u.modtime = ut->mtime_s; \
4507 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004508 }
4509
4510#define UTIME_TO_TIME_T \
4511 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004512 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004513 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004514 time = NULL; \
4515 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004516 timet[0] = ut->atime_s; \
4517 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004518 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004519 } \
4520
4521
Victor Stinner528a9ab2015-09-03 21:30:26 +02004522#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004523
4524static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004525utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004526{
4527#ifdef HAVE_UTIMENSAT
4528 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4529 UTIME_TO_TIMESPEC;
4530 return utimensat(dir_fd, path, time, flags);
4531#elif defined(HAVE_FUTIMESAT)
4532 UTIME_TO_TIMEVAL;
4533 /*
4534 * follow_symlinks will never be false here;
4535 * we only allow !follow_symlinks and dir_fd together
4536 * if we have utimensat()
4537 */
4538 assert(follow_symlinks);
4539 return futimesat(dir_fd, path, time);
4540#endif
4541}
4542
Larry Hastings2f936352014-08-05 14:04:04 +10004543 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4544#else
4545 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004546#endif
4547
Victor Stinner528a9ab2015-09-03 21:30:26 +02004548#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004549
4550static int
Victor Stinner484df002014-10-09 13:52:31 +02004551utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004552{
4553#ifdef HAVE_FUTIMENS
4554 UTIME_TO_TIMESPEC;
4555 return futimens(fd, time);
4556#else
4557 UTIME_TO_TIMEVAL;
4558 return futimes(fd, time);
4559#endif
4560}
4561
Larry Hastings2f936352014-08-05 14:04:04 +10004562 #define PATH_UTIME_HAVE_FD 1
4563#else
4564 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004565#endif
4566
Victor Stinner5ebae872015-09-22 01:29:33 +02004567#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4568# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4569#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004570
Victor Stinner4552ced2015-09-21 22:37:15 +02004571#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004572
4573static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004574utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004575{
4576#ifdef HAVE_UTIMENSAT
4577 UTIME_TO_TIMESPEC;
4578 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4579#else
4580 UTIME_TO_TIMEVAL;
4581 return lutimes(path, time);
4582#endif
4583}
4584
4585#endif
4586
4587#ifndef MS_WINDOWS
4588
4589static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004590utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004591{
4592#ifdef HAVE_UTIMENSAT
4593 UTIME_TO_TIMESPEC;
4594 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4595#elif defined(HAVE_UTIMES)
4596 UTIME_TO_TIMEVAL;
4597 return utimes(path, time);
4598#elif defined(HAVE_UTIME_H)
4599 UTIME_TO_UTIMBUF;
4600 return utime(path, time);
4601#else
4602 UTIME_TO_TIME_T;
4603 return utime(path, time);
4604#endif
4605}
4606
4607#endif
4608
Larry Hastings76ad59b2012-05-03 00:30:07 -07004609static int
4610split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4611{
4612 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004613 PyObject *divmod;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004614 divmod = PyNumber_Divmod(py_long, billion);
4615 if (!divmod)
4616 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004617 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4618 PyErr_Format(PyExc_TypeError,
4619 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
4620 Py_TYPE(py_long)->tp_name, Py_TYPE(divmod)->tp_name);
4621 goto exit;
4622 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004623 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4624 if ((*s == -1) && PyErr_Occurred())
4625 goto exit;
4626 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004627 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004628 goto exit;
4629
4630 result = 1;
4631exit:
4632 Py_XDECREF(divmod);
4633 return result;
4634}
4635
Larry Hastings2f936352014-08-05 14:04:04 +10004636
4637/*[clinic input]
4638os.utime
4639
4640 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
4641 times: object = NULL
4642 *
4643 ns: object = NULL
4644 dir_fd: dir_fd(requires='futimensat') = None
4645 follow_symlinks: bool=True
4646
Martin Panter0ff89092015-09-09 01:56:53 +00004647# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004648
4649Set the access and modified time of path.
4650
4651path may always be specified as a string.
4652On some platforms, path may also be specified as an open file descriptor.
4653 If this functionality is unavailable, using it raises an exception.
4654
4655If times is not None, it must be a tuple (atime, mtime);
4656 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004657If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004658 atime_ns and mtime_ns should be expressed as integer nanoseconds
4659 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004660If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004661Specifying tuples for both times and ns is an error.
4662
4663If dir_fd is not None, it should be a file descriptor open to a directory,
4664 and path should be relative; path will then be relative to that directory.
4665If follow_symlinks is False, and the last element of the path is a symbolic
4666 link, utime will modify the symbolic link itself instead of the file the
4667 link points to.
4668It is an error to use dir_fd or follow_symlinks when specifying path
4669 as an open file descriptor.
4670dir_fd and follow_symlinks may not be available on your platform.
4671 If they are unavailable, using them will raise a NotImplementedError.
4672
4673[clinic start generated code]*/
4674
Larry Hastings2f936352014-08-05 14:04:04 +10004675static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004676os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4677 int dir_fd, int follow_symlinks)
4678/*[clinic end generated code: output=cfcac69d027b82cf input=081cdc54ca685385]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004679{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004680#ifdef MS_WINDOWS
4681 HANDLE hFile;
4682 FILETIME atime, mtime;
4683#else
4684 int result;
4685#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004686
Larry Hastings2f936352014-08-05 14:04:04 +10004687 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004688
Christian Heimesb3c87242013-08-01 00:08:16 +02004689 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004690
Larry Hastings9cf065c2012-06-22 16:30:09 -07004691 if (times && (times != Py_None) && ns) {
4692 PyErr_SetString(PyExc_ValueError,
4693 "utime: you may specify either 'times'"
4694 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004695 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004696 }
4697
4698 if (times && (times != Py_None)) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004699 time_t a_sec, m_sec;
4700 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004701 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004702 PyErr_SetString(PyExc_TypeError,
4703 "utime: 'times' must be either"
4704 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004705 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004706 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004707 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004708 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004709 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004710 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004711 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004712 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004713 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004714 utime.atime_s = a_sec;
4715 utime.atime_ns = a_nsec;
4716 utime.mtime_s = m_sec;
4717 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004718 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004719 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004720 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004721 PyErr_SetString(PyExc_TypeError,
4722 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004723 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004724 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004725 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004726 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004727 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004728 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004729 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004730 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004731 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004732 }
4733 else {
4734 /* times and ns are both None/unspecified. use "now". */
4735 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004736 }
4737
Victor Stinner4552ced2015-09-21 22:37:15 +02004738#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004739 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004740 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004741#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004742
Larry Hastings2f936352014-08-05 14:04:04 +10004743 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4744 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4745 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004746 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004747
Larry Hastings9cf065c2012-06-22 16:30:09 -07004748#if !defined(HAVE_UTIMENSAT)
4749 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004750 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004751 "utime: cannot use dir_fd and follow_symlinks "
4752 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004753 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004754 }
4755#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004756
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004757#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004758 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004759 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4760 NULL, OPEN_EXISTING,
4761 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004762 Py_END_ALLOW_THREADS
4763 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004764 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004765 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004766 }
4767
Larry Hastings9cf065c2012-06-22 16:30:09 -07004768 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004769 GetSystemTimeAsFileTime(&mtime);
4770 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004771 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004772 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004773 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4774 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004775 }
4776 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4777 /* Avoid putting the file name into the error here,
4778 as that may confuse the user into believing that
4779 something is wrong with the file, when it also
4780 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004781 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004782 CloseHandle(hFile);
4783 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004784 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004785 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004786#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004787 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004788
Victor Stinner4552ced2015-09-21 22:37:15 +02004789#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004790 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004791 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004792 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004793#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004794
Victor Stinner528a9ab2015-09-03 21:30:26 +02004795#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004796 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004797 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004798 else
4799#endif
4800
Victor Stinner528a9ab2015-09-03 21:30:26 +02004801#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004802 if (path->fd != -1)
4803 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004804 else
4805#endif
4806
Larry Hastings2f936352014-08-05 14:04:04 +10004807 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004808
4809 Py_END_ALLOW_THREADS
4810
4811 if (result < 0) {
4812 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004813 posix_error();
4814 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004815 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004816
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004817#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004818
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004819 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004820}
4821
Guido van Rossum3b066191991-06-04 19:40:25 +00004822/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004823
Larry Hastings2f936352014-08-05 14:04:04 +10004824
4825/*[clinic input]
4826os._exit
4827
4828 status: int
4829
4830Exit to the system with specified status, without normal exit processing.
4831[clinic start generated code]*/
4832
Larry Hastings2f936352014-08-05 14:04:04 +10004833static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004834os__exit_impl(PyObject *module, int status)
4835/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004836{
4837 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00004838 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004839}
4840
Steve Dowercc16be82016-09-08 10:35:16 -07004841#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4842#define EXECV_CHAR wchar_t
4843#else
4844#define EXECV_CHAR char
4845#endif
4846
Martin v. Löwis114619e2002-10-07 06:44:21 +00004847#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
4848static void
Steve Dowercc16be82016-09-08 10:35:16 -07004849free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00004850{
Victor Stinner8c62be82010-05-06 00:08:46 +00004851 Py_ssize_t i;
4852 for (i = 0; i < count; i++)
4853 PyMem_Free(array[i]);
4854 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00004855}
Martin v. Löwis011e8422009-05-05 04:43:17 +00004856
Berker Peksag81816462016-09-15 20:19:47 +03004857static int
4858fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00004859{
Victor Stinner8c62be82010-05-06 00:08:46 +00004860 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03004861 PyObject *ub;
4862 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07004863#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03004864 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07004865 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03004866 *out = PyUnicode_AsWideCharString(ub, &size);
4867 if (*out)
4868 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07004869#else
Berker Peksag81816462016-09-15 20:19:47 +03004870 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00004871 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03004872 size = PyBytes_GET_SIZE(ub);
4873 *out = PyMem_Malloc(size + 1);
4874 if (*out) {
4875 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
4876 result = 1;
4877 } else
Victor Stinner50abf222013-11-07 23:56:10 +01004878 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07004879#endif
Berker Peksag81816462016-09-15 20:19:47 +03004880 Py_DECREF(ub);
4881 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004882}
Martin v. Löwis114619e2002-10-07 06:44:21 +00004883#endif
4884
Ross Lagerwall7807c352011-03-17 20:20:30 +02004885#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE)
Steve Dowercc16be82016-09-08 10:35:16 -07004886static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00004887parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
4888{
Victor Stinner8c62be82010-05-06 00:08:46 +00004889 Py_ssize_t i, pos, envc;
4890 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03004891 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07004892 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004893
Victor Stinner8c62be82010-05-06 00:08:46 +00004894 i = PyMapping_Size(env);
4895 if (i < 0)
4896 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07004897 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00004898 if (envlist == NULL) {
4899 PyErr_NoMemory();
4900 return NULL;
4901 }
4902 envc = 0;
4903 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01004904 if (!keys)
4905 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00004906 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01004907 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00004908 goto error;
4909 if (!PyList_Check(keys) || !PyList_Check(vals)) {
4910 PyErr_Format(PyExc_TypeError,
4911 "env.keys() or env.values() is not a list");
4912 goto error;
4913 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00004914
Victor Stinner8c62be82010-05-06 00:08:46 +00004915 for (pos = 0; pos < i; pos++) {
4916 key = PyList_GetItem(keys, pos);
4917 val = PyList_GetItem(vals, pos);
4918 if (!key || !val)
4919 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004920
Berker Peksag81816462016-09-15 20:19:47 +03004921#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4922 if (!PyUnicode_FSDecoder(key, &key2))
4923 goto error;
4924 if (!PyUnicode_FSDecoder(val, &val2)) {
4925 Py_DECREF(key2);
4926 goto error;
4927 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03004928 /* Search from index 1 because on Windows starting '=' is allowed for
4929 defining hidden environment variables. */
4930 if (PyUnicode_GET_LENGTH(key2) == 0 ||
4931 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
4932 {
4933 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04004934 Py_DECREF(key2);
4935 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03004936 goto error;
4937 }
Berker Peksag81816462016-09-15 20:19:47 +03004938 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
4939#else
4940 if (!PyUnicode_FSConverter(key, &key2))
4941 goto error;
4942 if (!PyUnicode_FSConverter(val, &val2)) {
4943 Py_DECREF(key2);
4944 goto error;
4945 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03004946 if (PyBytes_GET_SIZE(key2) == 0 ||
4947 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
4948 {
4949 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04004950 Py_DECREF(key2);
4951 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03004952 goto error;
4953 }
Berker Peksag81816462016-09-15 20:19:47 +03004954 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
4955 PyBytes_AS_STRING(val2));
4956#endif
4957 Py_DECREF(key2);
4958 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07004959 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00004960 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07004961
4962 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
4963 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00004964 goto error;
4965 }
Berker Peksag81816462016-09-15 20:19:47 +03004966
Steve Dowercc16be82016-09-08 10:35:16 -07004967 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00004968 }
4969 Py_DECREF(vals);
4970 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00004971
Victor Stinner8c62be82010-05-06 00:08:46 +00004972 envlist[envc] = 0;
4973 *envc_ptr = envc;
4974 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004975
4976error:
Victor Stinner8c62be82010-05-06 00:08:46 +00004977 Py_XDECREF(keys);
4978 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07004979 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00004980 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004981}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004982
Steve Dowercc16be82016-09-08 10:35:16 -07004983static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02004984parse_arglist(PyObject* argv, Py_ssize_t *argc)
4985{
4986 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07004987 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02004988 if (argvlist == NULL) {
4989 PyErr_NoMemory();
4990 return NULL;
4991 }
4992 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02004993 PyObject* item = PySequence_ITEM(argv, i);
4994 if (item == NULL)
4995 goto fail;
4996 if (!fsconvert_strdup(item, &argvlist[i])) {
4997 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02004998 goto fail;
4999 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005000 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005001 }
5002 argvlist[*argc] = NULL;
5003 return argvlist;
5004fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005005 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005006 free_string_array(argvlist, *argc);
5007 return NULL;
5008}
Steve Dowercc16be82016-09-08 10:35:16 -07005009
Ross Lagerwall7807c352011-03-17 20:20:30 +02005010#endif
5011
Larry Hastings2f936352014-08-05 14:04:04 +10005012
Ross Lagerwall7807c352011-03-17 20:20:30 +02005013#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005014/*[clinic input]
5015os.execv
5016
Steve Dowercc16be82016-09-08 10:35:16 -07005017 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005018 Path of executable file.
5019 argv: object
5020 Tuple or list of strings.
5021 /
5022
5023Execute an executable path with arguments, replacing current process.
5024[clinic start generated code]*/
5025
Larry Hastings2f936352014-08-05 14:04:04 +10005026static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005027os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5028/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005029{
Steve Dowercc16be82016-09-08 10:35:16 -07005030 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005031 Py_ssize_t argc;
5032
5033 /* execv has two arguments: (path, argv), where
5034 argv is a list or tuple of strings. */
5035
Ross Lagerwall7807c352011-03-17 20:20:30 +02005036 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5037 PyErr_SetString(PyExc_TypeError,
5038 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005039 return NULL;
5040 }
5041 argc = PySequence_Size(argv);
5042 if (argc < 1) {
5043 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005044 return NULL;
5045 }
5046
5047 argvlist = parse_arglist(argv, &argc);
5048 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005049 return NULL;
5050 }
Steve Dowerbce26262016-11-19 19:17:26 -08005051 if (!argvlist[0][0]) {
5052 PyErr_SetString(PyExc_ValueError,
5053 "execv() arg 2 first element cannot be empty");
5054 free_string_array(argvlist, argc);
5055 return NULL;
5056 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005057
Steve Dowerbce26262016-11-19 19:17:26 -08005058 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005059#ifdef HAVE_WEXECV
5060 _wexecv(path->wide, argvlist);
5061#else
5062 execv(path->narrow, argvlist);
5063#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005064 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005065
5066 /* If we get here it's definitely an error */
5067
5068 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005069 return posix_error();
5070}
5071
Larry Hastings2f936352014-08-05 14:04:04 +10005072
5073/*[clinic input]
5074os.execve
5075
5076 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5077 Path of executable file.
5078 argv: object
5079 Tuple or list of strings.
5080 env: object
5081 Dictionary of strings mapping to strings.
5082
5083Execute an executable path with arguments, replacing current process.
5084[clinic start generated code]*/
5085
Larry Hastings2f936352014-08-05 14:04:04 +10005086static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005087os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5088/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005089{
Steve Dowercc16be82016-09-08 10:35:16 -07005090 EXECV_CHAR **argvlist = NULL;
5091 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005092 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005093
Victor Stinner8c62be82010-05-06 00:08:46 +00005094 /* execve has three arguments: (path, argv, env), where
5095 argv is a list or tuple of strings and env is a dictionary
5096 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005097
Ross Lagerwall7807c352011-03-17 20:20:30 +02005098 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005099 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005100 "execve: argv must be a tuple or list");
5101 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005102 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005103 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005104 if (argc < 1) {
5105 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5106 return NULL;
5107 }
5108
Victor Stinner8c62be82010-05-06 00:08:46 +00005109 if (!PyMapping_Check(env)) {
5110 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005111 "execve: environment must be a mapping object");
5112 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005113 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005114
Ross Lagerwall7807c352011-03-17 20:20:30 +02005115 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005116 if (argvlist == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005117 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005118 }
Steve Dowerbce26262016-11-19 19:17:26 -08005119 if (!argvlist[0][0]) {
5120 PyErr_SetString(PyExc_ValueError,
5121 "execve: argv first element cannot be empty");
5122 goto fail;
5123 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005124
Victor Stinner8c62be82010-05-06 00:08:46 +00005125 envlist = parse_envlist(env, &envc);
5126 if (envlist == NULL)
Ross Lagerwall7807c352011-03-17 20:20:30 +02005127 goto fail;
5128
Steve Dowerbce26262016-11-19 19:17:26 -08005129 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005130#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005131 if (path->fd > -1)
5132 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005133 else
5134#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005135#ifdef HAVE_WEXECV
5136 _wexecve(path->wide, argvlist, envlist);
5137#else
Larry Hastings2f936352014-08-05 14:04:04 +10005138 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005139#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005140 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005141
5142 /* If we get here it's definitely an error */
5143
Alexey Izbyshev83460312018-10-20 03:28:22 +03005144 posix_path_error(path);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005145
Steve Dowercc16be82016-09-08 10:35:16 -07005146 free_string_array(envlist, envc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005147 fail:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005148 if (argvlist)
5149 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005150 return NULL;
5151}
Steve Dowercc16be82016-09-08 10:35:16 -07005152
Larry Hastings9cf065c2012-06-22 16:30:09 -07005153#endif /* HAVE_EXECV */
5154
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005155#ifdef HAVE_POSIX_SPAWN
5156
5157enum posix_spawn_file_actions_identifier {
5158 POSIX_SPAWN_OPEN,
5159 POSIX_SPAWN_CLOSE,
5160 POSIX_SPAWN_DUP2
5161};
5162
William Orr81574b82018-10-01 22:19:56 -07005163#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005164static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005165convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005166#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005167
5168static int
5169parse_posix_spawn_flags(PyObject *setpgroup, int resetids, PyObject *setsigmask,
5170 PyObject *setsigdef, PyObject *scheduler,
5171 posix_spawnattr_t *attrp)
5172{
5173 long all_flags = 0;
5174
5175 errno = posix_spawnattr_init(attrp);
5176 if (errno) {
5177 posix_error();
5178 return -1;
5179 }
5180
5181 if (setpgroup) {
5182 pid_t pgid = PyLong_AsPid(setpgroup);
5183 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5184 goto fail;
5185 }
5186 errno = posix_spawnattr_setpgroup(attrp, pgid);
5187 if (errno) {
5188 posix_error();
5189 goto fail;
5190 }
5191 all_flags |= POSIX_SPAWN_SETPGROUP;
5192 }
5193
5194 if (resetids) {
5195 all_flags |= POSIX_SPAWN_RESETIDS;
5196 }
5197
5198 if (setsigmask) {
5199 sigset_t set;
5200 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5201 goto fail;
5202 }
5203 errno = posix_spawnattr_setsigmask(attrp, &set);
5204 if (errno) {
5205 posix_error();
5206 goto fail;
5207 }
5208 all_flags |= POSIX_SPAWN_SETSIGMASK;
5209 }
5210
5211 if (setsigdef) {
5212 sigset_t set;
5213 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5214 goto fail;
5215 }
5216 errno = posix_spawnattr_setsigdefault(attrp, &set);
5217 if (errno) {
5218 posix_error();
5219 goto fail;
5220 }
5221 all_flags |= POSIX_SPAWN_SETSIGDEF;
5222 }
5223
5224 if (scheduler) {
5225#ifdef POSIX_SPAWN_SETSCHEDULER
5226 PyObject *py_schedpolicy;
5227 struct sched_param schedparam;
5228
5229 if (!PyArg_ParseTuple(scheduler, "OO&"
5230 ";A scheduler tuple must have two elements",
5231 &py_schedpolicy, convert_sched_param, &schedparam)) {
5232 goto fail;
5233 }
5234 if (py_schedpolicy != Py_None) {
5235 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5236
5237 if (schedpolicy == -1 && PyErr_Occurred()) {
5238 goto fail;
5239 }
5240 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5241 if (errno) {
5242 posix_error();
5243 goto fail;
5244 }
5245 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5246 }
5247 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5248 if (errno) {
5249 posix_error();
5250 goto fail;
5251 }
5252 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5253#else
5254 PyErr_SetString(PyExc_NotImplementedError,
5255 "The scheduler option is not supported in this system.");
5256 goto fail;
5257#endif
5258 }
5259
5260 errno = posix_spawnattr_setflags(attrp, all_flags);
5261 if (errno) {
5262 posix_error();
5263 goto fail;
5264 }
5265
5266 return 0;
5267
5268fail:
5269 (void)posix_spawnattr_destroy(attrp);
5270 return -1;
5271}
5272
5273static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005274parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005275 posix_spawn_file_actions_t *file_actionsp,
5276 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005277{
5278 PyObject *seq;
5279 PyObject *file_action = NULL;
5280 PyObject *tag_obj;
5281
5282 seq = PySequence_Fast(file_actions,
5283 "file_actions must be a sequence or None");
5284 if (seq == NULL) {
5285 return -1;
5286 }
5287
5288 errno = posix_spawn_file_actions_init(file_actionsp);
5289 if (errno) {
5290 posix_error();
5291 Py_DECREF(seq);
5292 return -1;
5293 }
5294
5295 for (int i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
5296 file_action = PySequence_Fast_GET_ITEM(seq, i);
5297 Py_INCREF(file_action);
5298 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5299 PyErr_SetString(PyExc_TypeError,
5300 "Each file_actions element must be a non-empty tuple");
5301 goto fail;
5302 }
5303 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5304 if (tag == -1 && PyErr_Occurred()) {
5305 goto fail;
5306 }
5307
5308 /* Populate the file_actions object */
5309 switch (tag) {
5310 case POSIX_SPAWN_OPEN: {
5311 int fd, oflag;
5312 PyObject *path;
5313 unsigned long mode;
5314 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5315 ";A open file_action tuple must have 5 elements",
5316 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5317 &oflag, &mode))
5318 {
5319 goto fail;
5320 }
Pablo Galindocb970732018-06-19 09:19:50 +01005321 if (PyList_Append(temp_buffer, path)) {
5322 Py_DECREF(path);
5323 goto fail;
5324 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005325 errno = posix_spawn_file_actions_addopen(file_actionsp,
5326 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005327 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005328 if (errno) {
5329 posix_error();
5330 goto fail;
5331 }
5332 break;
5333 }
5334 case POSIX_SPAWN_CLOSE: {
5335 int fd;
5336 if (!PyArg_ParseTuple(file_action, "Oi"
5337 ";A close file_action tuple must have 2 elements",
5338 &tag_obj, &fd))
5339 {
5340 goto fail;
5341 }
5342 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5343 if (errno) {
5344 posix_error();
5345 goto fail;
5346 }
5347 break;
5348 }
5349 case POSIX_SPAWN_DUP2: {
5350 int fd1, fd2;
5351 if (!PyArg_ParseTuple(file_action, "Oii"
5352 ";A dup2 file_action tuple must have 3 elements",
5353 &tag_obj, &fd1, &fd2))
5354 {
5355 goto fail;
5356 }
5357 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5358 fd1, fd2);
5359 if (errno) {
5360 posix_error();
5361 goto fail;
5362 }
5363 break;
5364 }
5365 default: {
5366 PyErr_SetString(PyExc_TypeError,
5367 "Unknown file_actions identifier");
5368 goto fail;
5369 }
5370 }
5371 Py_DECREF(file_action);
5372 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005373
Serhiy Storchakaef347532018-05-01 16:45:04 +03005374 Py_DECREF(seq);
5375 return 0;
5376
5377fail:
5378 Py_DECREF(seq);
5379 Py_DECREF(file_action);
5380 (void)posix_spawn_file_actions_destroy(file_actionsp);
5381 return -1;
5382}
5383
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005384/*[clinic input]
5385
5386os.posix_spawn
5387 path: path_t
5388 Path of executable file.
5389 argv: object
5390 Tuple or list of strings.
5391 env: object
5392 Dictionary of strings mapping to strings.
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005393 /
Pablo Galindo254a4662018-09-07 16:44:24 +01005394 *
Serhiy Storchakad700f972018-09-08 14:48:18 +03005395 file_actions: object(c_default='NULL') = ()
5396 A sequence of file action tuples.
Pablo Galindo254a4662018-09-07 16:44:24 +01005397 setpgroup: object = NULL
5398 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5399 resetids: bool(accept={int}) = False
5400 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
5401 setsigmask: object(c_default='NULL') = ()
5402 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5403 setsigdef: object(c_default='NULL') = ()
5404 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5405 scheduler: object = NULL
5406 A tuple with the scheduler policy (optional) and parameters.
Serhiy Storchakad700f972018-09-08 14:48:18 +03005407
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005408Execute the program specified by path in a new process.
5409[clinic start generated code]*/
5410
5411static PyObject *
5412os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
Pablo Galindo254a4662018-09-07 16:44:24 +01005413 PyObject *env, PyObject *file_actions,
5414 PyObject *setpgroup, int resetids, PyObject *setsigmask,
5415 PyObject *setsigdef, PyObject *scheduler)
Serhiy Storchakad700f972018-09-08 14:48:18 +03005416/*[clinic end generated code: output=45dfa4c515d09f2c input=2891c2f1d457e39b]*/
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005417{
5418 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005419 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005420 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005421 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005422 posix_spawnattr_t attr;
5423 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005424 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005425 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005426 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005427 pid_t pid;
5428 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005429
5430 /* posix_spawn has three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005431 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005432 like posix.environ. */
5433
Serhiy Storchakaef347532018-05-01 16:45:04 +03005434 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005435 PyErr_SetString(PyExc_TypeError,
5436 "posix_spawn: argv must be a tuple or list");
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005437 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005438 }
5439 argc = PySequence_Size(argv);
5440 if (argc < 1) {
5441 PyErr_SetString(PyExc_ValueError, "posix_spawn: argv must not be empty");
5442 return NULL;
5443 }
5444
5445 if (!PyMapping_Check(env)) {
5446 PyErr_SetString(PyExc_TypeError,
5447 "posix_spawn: environment must be a mapping object");
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005448 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005449 }
5450
5451 argvlist = parse_arglist(argv, &argc);
5452 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005453 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005454 }
5455 if (!argvlist[0][0]) {
5456 PyErr_SetString(PyExc_ValueError,
5457 "posix_spawn: argv first element cannot be empty");
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005458 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005459 }
5460
5461 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005462 if (envlist == NULL) {
5463 goto exit;
5464 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005465
Serhiy Storchakad700f972018-09-08 14:48:18 +03005466 if (file_actions != NULL) {
Pablo Galindocb970732018-06-19 09:19:50 +01005467 /* There is a bug in old versions of glibc that makes some of the
5468 * helper functions for manipulating file actions not copy the provided
5469 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5470 * copy the value of path for some old versions of glibc (<2.20).
5471 * The use of temp_buffer here is a workaround that keeps the
5472 * python objects that own the buffers alive until posix_spawn gets called.
5473 * Check https://bugs.python.org/issue33630 and
5474 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5475 temp_buffer = PyList_New(0);
5476 if (!temp_buffer) {
5477 goto exit;
5478 }
5479 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005480 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005481 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005482 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005483 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005484
Pablo Galindo254a4662018-09-07 16:44:24 +01005485 if (parse_posix_spawn_flags(setpgroup, resetids, setsigmask,
5486 setsigdef, scheduler, &attr)) {
5487 goto exit;
5488 }
5489 attrp = &attr;
5490
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005491 _Py_BEGIN_SUPPRESS_IPH
Serhiy Storchakaef347532018-05-01 16:45:04 +03005492 err_code = posix_spawn(&pid, path->narrow,
Pablo Galindo254a4662018-09-07 16:44:24 +01005493 file_actionsp, attrp, argvlist, envlist);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005494 _Py_END_SUPPRESS_IPH
Serhiy Storchakaef347532018-05-01 16:45:04 +03005495 if (err_code) {
5496 errno = err_code;
5497 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005498 goto exit;
5499 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005500#ifdef _Py_MEMORY_SANITIZER
5501 __msan_unpoison(&pid, sizeof(pid));
5502#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005503 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005504
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005505exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005506 if (file_actionsp) {
5507 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005508 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005509 if (attrp) {
5510 (void)posix_spawnattr_destroy(attrp);
5511 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005512 if (envlist) {
5513 free_string_array(envlist, envc);
5514 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005515 if (argvlist) {
5516 free_string_array(argvlist, argc);
5517 }
Pablo Galindocb970732018-06-19 09:19:50 +01005518 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005519 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005520}
5521#endif /* HAVE_POSIX_SPAWN */
5522
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005523
Steve Dowercc16be82016-09-08 10:35:16 -07005524#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV)
Larry Hastings2f936352014-08-05 14:04:04 +10005525/*[clinic input]
5526os.spawnv
5527
5528 mode: int
5529 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005530 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005531 Path of executable file.
5532 argv: object
5533 Tuple or list of strings.
5534 /
5535
5536Execute the program specified by path in a new process.
5537[clinic start generated code]*/
5538
Larry Hastings2f936352014-08-05 14:04:04 +10005539static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005540os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5541/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005542{
Steve Dowercc16be82016-09-08 10:35:16 -07005543 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005544 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005545 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005546 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005547 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005548
Victor Stinner8c62be82010-05-06 00:08:46 +00005549 /* spawnv has three arguments: (mode, path, argv), where
5550 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005551
Victor Stinner8c62be82010-05-06 00:08:46 +00005552 if (PyList_Check(argv)) {
5553 argc = PyList_Size(argv);
5554 getitem = PyList_GetItem;
5555 }
5556 else if (PyTuple_Check(argv)) {
5557 argc = PyTuple_Size(argv);
5558 getitem = PyTuple_GetItem;
5559 }
5560 else {
5561 PyErr_SetString(PyExc_TypeError,
5562 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005563 return NULL;
5564 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005565 if (argc == 0) {
5566 PyErr_SetString(PyExc_ValueError,
5567 "spawnv() arg 2 cannot be empty");
5568 return NULL;
5569 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005570
Steve Dowercc16be82016-09-08 10:35:16 -07005571 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005572 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005573 return PyErr_NoMemory();
5574 }
5575 for (i = 0; i < argc; i++) {
5576 if (!fsconvert_strdup((*getitem)(argv, i),
5577 &argvlist[i])) {
5578 free_string_array(argvlist, i);
5579 PyErr_SetString(
5580 PyExc_TypeError,
5581 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005582 return NULL;
5583 }
Steve Dower93ff8722016-11-19 19:03:54 -08005584 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005585 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005586 PyErr_SetString(
5587 PyExc_ValueError,
5588 "spawnv() arg 2 first element cannot be empty");
5589 return NULL;
5590 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005591 }
5592 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005593
Victor Stinner8c62be82010-05-06 00:08:46 +00005594 if (mode == _OLD_P_OVERLAY)
5595 mode = _P_OVERLAY;
Tim Peters5aa91602002-01-30 05:46:57 +00005596
Victor Stinner8c62be82010-05-06 00:08:46 +00005597 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005598 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005599#ifdef HAVE_WSPAWNV
5600 spawnval = _wspawnv(mode, path->wide, argvlist);
5601#else
5602 spawnval = _spawnv(mode, path->narrow, argvlist);
5603#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005604 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005605 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005606
Victor Stinner8c62be82010-05-06 00:08:46 +00005607 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005608
Victor Stinner8c62be82010-05-06 00:08:46 +00005609 if (spawnval == -1)
5610 return posix_error();
5611 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005612 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005613}
5614
Larry Hastings2f936352014-08-05 14:04:04 +10005615/*[clinic input]
5616os.spawnve
5617
5618 mode: int
5619 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005620 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005621 Path of executable file.
5622 argv: object
5623 Tuple or list of strings.
5624 env: object
5625 Dictionary of strings mapping to strings.
5626 /
5627
5628Execute the program specified by path in a new process.
5629[clinic start generated code]*/
5630
Larry Hastings2f936352014-08-05 14:04:04 +10005631static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005632os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005633 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005634/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005635{
Steve Dowercc16be82016-09-08 10:35:16 -07005636 EXECV_CHAR **argvlist;
5637 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005638 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005639 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005640 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005641 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005642 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005643
Victor Stinner8c62be82010-05-06 00:08:46 +00005644 /* spawnve has four arguments: (mode, path, argv, env), where
5645 argv is a list or tuple of strings and env is a dictionary
5646 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005647
Victor Stinner8c62be82010-05-06 00:08:46 +00005648 if (PyList_Check(argv)) {
5649 argc = PyList_Size(argv);
5650 getitem = PyList_GetItem;
5651 }
5652 else if (PyTuple_Check(argv)) {
5653 argc = PyTuple_Size(argv);
5654 getitem = PyTuple_GetItem;
5655 }
5656 else {
5657 PyErr_SetString(PyExc_TypeError,
5658 "spawnve() arg 2 must be a tuple or list");
5659 goto fail_0;
5660 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005661 if (argc == 0) {
5662 PyErr_SetString(PyExc_ValueError,
5663 "spawnve() arg 2 cannot be empty");
5664 goto fail_0;
5665 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005666 if (!PyMapping_Check(env)) {
5667 PyErr_SetString(PyExc_TypeError,
5668 "spawnve() arg 3 must be a mapping object");
5669 goto fail_0;
5670 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005671
Steve Dowercc16be82016-09-08 10:35:16 -07005672 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005673 if (argvlist == NULL) {
5674 PyErr_NoMemory();
5675 goto fail_0;
5676 }
5677 for (i = 0; i < argc; i++) {
5678 if (!fsconvert_strdup((*getitem)(argv, i),
5679 &argvlist[i]))
5680 {
5681 lastarg = i;
5682 goto fail_1;
5683 }
Steve Dowerbce26262016-11-19 19:17:26 -08005684 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005685 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08005686 PyErr_SetString(
5687 PyExc_ValueError,
5688 "spawnv() arg 2 first element cannot be empty");
5689 goto fail_1;
5690 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005691 }
5692 lastarg = argc;
5693 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005694
Victor Stinner8c62be82010-05-06 00:08:46 +00005695 envlist = parse_envlist(env, &envc);
5696 if (envlist == NULL)
5697 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00005698
Victor Stinner8c62be82010-05-06 00:08:46 +00005699 if (mode == _OLD_P_OVERLAY)
5700 mode = _P_OVERLAY;
Tim Peters25059d32001-12-07 20:35:43 +00005701
Victor Stinner8c62be82010-05-06 00:08:46 +00005702 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005703 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005704#ifdef HAVE_WSPAWNV
5705 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
5706#else
5707 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
5708#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005709 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005710 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00005711
Victor Stinner8c62be82010-05-06 00:08:46 +00005712 if (spawnval == -1)
5713 (void) posix_error();
5714 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005715 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005716
Victor Stinner8c62be82010-05-06 00:08:46 +00005717 while (--envc >= 0)
5718 PyMem_DEL(envlist[envc]);
5719 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00005720 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005721 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005722 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00005723 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00005724}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00005725
Guido van Rossuma1065681999-01-25 23:20:23 +00005726#endif /* HAVE_SPAWNV */
5727
5728
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005729#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07005730
5731/* Helper function to validate arguments.
5732 Returns 0 on success. non-zero on failure with a TypeError raised.
5733 If obj is non-NULL it must be callable. */
5734static int
5735check_null_or_callable(PyObject *obj, const char* obj_name)
5736{
5737 if (obj && !PyCallable_Check(obj)) {
5738 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
5739 obj_name, Py_TYPE(obj)->tp_name);
5740 return -1;
5741 }
5742 return 0;
5743}
5744
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005745/*[clinic input]
5746os.register_at_fork
5747
Gregory P. Smith163468a2017-05-29 10:03:41 -07005748 *
5749 before: object=NULL
5750 A callable to be called in the parent before the fork() syscall.
5751 after_in_child: object=NULL
5752 A callable to be called in the child after fork().
5753 after_in_parent: object=NULL
5754 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005755
Gregory P. Smith163468a2017-05-29 10:03:41 -07005756Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005757
Gregory P. Smith163468a2017-05-29 10:03:41 -07005758'before' callbacks are called in reverse order.
5759'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005760
5761[clinic start generated code]*/
5762
5763static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07005764os_register_at_fork_impl(PyObject *module, PyObject *before,
5765 PyObject *after_in_child, PyObject *after_in_parent)
5766/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005767{
5768 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005769
Gregory P. Smith163468a2017-05-29 10:03:41 -07005770 if (!before && !after_in_child && !after_in_parent) {
5771 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
5772 return NULL;
5773 }
5774 if (check_null_or_callable(before, "before") ||
5775 check_null_or_callable(after_in_child, "after_in_child") ||
5776 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005777 return NULL;
5778 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02005779 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005780
Gregory P. Smith163468a2017-05-29 10:03:41 -07005781 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005782 return NULL;
5783 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07005784 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005785 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07005786 }
5787 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
5788 return NULL;
5789 }
5790 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005791}
5792#endif /* HAVE_FORK */
5793
5794
Guido van Rossum2242f2f2001-04-11 20:58:20 +00005795#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10005796/*[clinic input]
5797os.fork1
5798
5799Fork a child process with a single multiplexed (i.e., not bound) thread.
5800
5801Return 0 to child process and PID of child to parent process.
5802[clinic start generated code]*/
5803
Larry Hastings2f936352014-08-05 14:04:04 +10005804static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005805os_fork1_impl(PyObject *module)
5806/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00005807{
Victor Stinner8c62be82010-05-06 00:08:46 +00005808 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005809
Eric Snow59032962018-09-14 14:17:20 -07005810 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
5811 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
5812 return NULL;
5813 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005814 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00005815 pid = fork1();
5816 if (pid == 0) {
5817 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005818 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00005819 } else {
5820 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005821 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00005822 }
5823 if (pid == -1)
5824 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00005825 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00005826}
Larry Hastings2f936352014-08-05 14:04:04 +10005827#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00005828
5829
Guido van Rossumad0ee831995-03-01 10:34:45 +00005830#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10005831/*[clinic input]
5832os.fork
5833
5834Fork a child process.
5835
5836Return 0 to child process and PID of child to parent process.
5837[clinic start generated code]*/
5838
Larry Hastings2f936352014-08-05 14:04:04 +10005839static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005840os_fork_impl(PyObject *module)
5841/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00005842{
Victor Stinner8c62be82010-05-06 00:08:46 +00005843 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005844
Eric Snow59032962018-09-14 14:17:20 -07005845 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
5846 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
5847 return NULL;
5848 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005849 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00005850 pid = fork();
5851 if (pid == 0) {
5852 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005853 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00005854 } else {
5855 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005856 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00005857 }
5858 if (pid == -1)
5859 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00005860 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00005861}
Larry Hastings2f936352014-08-05 14:04:04 +10005862#endif /* HAVE_FORK */
5863
Guido van Rossum85e3b011991-06-03 12:42:10 +00005864
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005865#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02005866#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10005867/*[clinic input]
5868os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02005869
Larry Hastings2f936352014-08-05 14:04:04 +10005870 policy: int
5871
5872Get the maximum scheduling priority for policy.
5873[clinic start generated code]*/
5874
Larry Hastings2f936352014-08-05 14:04:04 +10005875static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005876os_sched_get_priority_max_impl(PyObject *module, int policy)
5877/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005878{
5879 int max;
5880
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005881 max = sched_get_priority_max(policy);
5882 if (max < 0)
5883 return posix_error();
5884 return PyLong_FromLong(max);
5885}
5886
Larry Hastings2f936352014-08-05 14:04:04 +10005887
5888/*[clinic input]
5889os.sched_get_priority_min
5890
5891 policy: int
5892
5893Get the minimum scheduling priority for policy.
5894[clinic start generated code]*/
5895
Larry Hastings2f936352014-08-05 14:04:04 +10005896static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005897os_sched_get_priority_min_impl(PyObject *module, int policy)
5898/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005899{
5900 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005901 if (min < 0)
5902 return posix_error();
5903 return PyLong_FromLong(min);
5904}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02005905#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
5906
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05005907
Larry Hastings2f936352014-08-05 14:04:04 +10005908#ifdef HAVE_SCHED_SETSCHEDULER
5909/*[clinic input]
5910os.sched_getscheduler
5911 pid: pid_t
5912 /
5913
5914Get the scheduling policy for the process identifiedy by pid.
5915
5916Passing 0 for pid returns the scheduling policy for the calling process.
5917[clinic start generated code]*/
5918
Larry Hastings2f936352014-08-05 14:04:04 +10005919static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005920os_sched_getscheduler_impl(PyObject *module, pid_t pid)
5921/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=5f14cfd1f189e1a0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005922{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005923 int policy;
5924
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005925 policy = sched_getscheduler(pid);
5926 if (policy < 0)
5927 return posix_error();
5928 return PyLong_FromLong(policy);
5929}
Larry Hastings2f936352014-08-05 14:04:04 +10005930#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005931
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05005932
William Orr81574b82018-10-01 22:19:56 -07005933#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10005934/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08005935class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10005936
5937@classmethod
5938os.sched_param.__new__
5939
5940 sched_priority: object
5941 A scheduling parameter.
5942
5943Current has only one field: sched_priority");
5944[clinic start generated code]*/
5945
Larry Hastings2f936352014-08-05 14:04:04 +10005946static PyObject *
5947os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08005948/*[clinic end generated code: output=48f4067d60f48c13 input=ab4de35a9a7811f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005949{
5950 PyObject *res;
5951
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005952 res = PyStructSequence_New(type);
5953 if (!res)
5954 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10005955 Py_INCREF(sched_priority);
5956 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005957 return res;
5958}
5959
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005960
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03005961PyDoc_VAR(os_sched_param__doc__);
5962
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005963static PyStructSequence_Field sched_param_fields[] = {
5964 {"sched_priority", "the scheduling priority"},
5965 {0}
5966};
5967
5968static PyStructSequence_Desc sched_param_desc = {
5969 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10005970 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005971 sched_param_fields,
5972 1
5973};
5974
5975static int
5976convert_sched_param(PyObject *param, struct sched_param *res)
5977{
5978 long priority;
5979
Eddie Elizondo474eedf2018-11-13 04:09:31 -08005980 if (Py_TYPE(param) != SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005981 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
5982 return 0;
5983 }
5984 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
5985 if (priority == -1 && PyErr_Occurred())
5986 return 0;
5987 if (priority > INT_MAX || priority < INT_MIN) {
5988 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
5989 return 0;
5990 }
5991 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
5992 return 1;
5993}
William Orr81574b82018-10-01 22:19:56 -07005994#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05005995
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05005996
5997#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10005998/*[clinic input]
5999os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006000
Larry Hastings2f936352014-08-05 14:04:04 +10006001 pid: pid_t
6002 policy: int
6003 param: sched_param
6004 /
6005
6006Set the scheduling policy for the process identified by pid.
6007
6008If pid is 0, the calling process is changed.
6009param is an instance of sched_param.
6010[clinic start generated code]*/
6011
Larry Hastings2f936352014-08-05 14:04:04 +10006012static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006013os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006014 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006015/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006016{
Jesus Cea9c822272011-09-10 01:40:52 +02006017 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006018 ** sched_setscheduler() returns 0 in Linux, but the previous
6019 ** scheduling policy under Solaris/Illumos, and others.
6020 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006021 */
Larry Hastings2f936352014-08-05 14:04:04 +10006022 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006023 return posix_error();
6024 Py_RETURN_NONE;
6025}
Larry Hastings2f936352014-08-05 14:04:04 +10006026#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006027
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006028
6029#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006030/*[clinic input]
6031os.sched_getparam
6032 pid: pid_t
6033 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006034
Larry Hastings2f936352014-08-05 14:04:04 +10006035Returns scheduling parameters for the process identified by pid.
6036
6037If pid is 0, returns parameters for the calling process.
6038Return value is an instance of sched_param.
6039[clinic start generated code]*/
6040
Larry Hastings2f936352014-08-05 14:04:04 +10006041static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006042os_sched_getparam_impl(PyObject *module, pid_t pid)
6043/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006044{
6045 struct sched_param param;
6046 PyObject *result;
6047 PyObject *priority;
6048
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006049 if (sched_getparam(pid, &param))
6050 return posix_error();
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006051 result = PyStructSequence_New(SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006052 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006053 return NULL;
6054 priority = PyLong_FromLong(param.sched_priority);
6055 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006056 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006057 return NULL;
6058 }
Larry Hastings2f936352014-08-05 14:04:04 +10006059 PyStructSequence_SET_ITEM(result, 0, priority);
6060 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006061}
6062
Larry Hastings2f936352014-08-05 14:04:04 +10006063
6064/*[clinic input]
6065os.sched_setparam
6066 pid: pid_t
6067 param: sched_param
6068 /
6069
6070Set scheduling parameters for the process identified by pid.
6071
6072If pid is 0, sets parameters for the calling process.
6073param should be an instance of sched_param.
6074[clinic start generated code]*/
6075
Larry Hastings2f936352014-08-05 14:04:04 +10006076static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006077os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006078 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006079/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006080{
6081 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006082 return posix_error();
6083 Py_RETURN_NONE;
6084}
Larry Hastings2f936352014-08-05 14:04:04 +10006085#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006086
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006087
6088#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006089/*[clinic input]
6090os.sched_rr_get_interval -> double
6091 pid: pid_t
6092 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006093
Larry Hastings2f936352014-08-05 14:04:04 +10006094Return the round-robin quantum for the process identified by pid, in seconds.
6095
6096Value returned is a float.
6097[clinic start generated code]*/
6098
Larry Hastings2f936352014-08-05 14:04:04 +10006099static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006100os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6101/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006102{
6103 struct timespec interval;
6104 if (sched_rr_get_interval(pid, &interval)) {
6105 posix_error();
6106 return -1.0;
6107 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006108#ifdef _Py_MEMORY_SANITIZER
6109 __msan_unpoison(&interval, sizeof(interval));
6110#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006111 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6112}
6113#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006114
Larry Hastings2f936352014-08-05 14:04:04 +10006115
6116/*[clinic input]
6117os.sched_yield
6118
6119Voluntarily relinquish the CPU.
6120[clinic start generated code]*/
6121
Larry Hastings2f936352014-08-05 14:04:04 +10006122static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006123os_sched_yield_impl(PyObject *module)
6124/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006125{
6126 if (sched_yield())
6127 return posix_error();
6128 Py_RETURN_NONE;
6129}
6130
Benjamin Peterson2740af82011-08-02 17:41:34 -05006131#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006132/* The minimum number of CPUs allocated in a cpu_set_t */
6133static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006134
Larry Hastings2f936352014-08-05 14:04:04 +10006135/*[clinic input]
6136os.sched_setaffinity
6137 pid: pid_t
6138 mask : object
6139 /
6140
6141Set the CPU affinity of the process identified by pid to mask.
6142
6143mask should be an iterable of integers identifying CPUs.
6144[clinic start generated code]*/
6145
Larry Hastings2f936352014-08-05 14:04:04 +10006146static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006147os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6148/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006149{
Antoine Pitrou84869872012-08-04 16:16:35 +02006150 int ncpus;
6151 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006152 cpu_set_t *cpu_set = NULL;
6153 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006154
Larry Hastings2f936352014-08-05 14:04:04 +10006155 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006156 if (iterator == NULL)
6157 return NULL;
6158
6159 ncpus = NCPUS_START;
6160 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006161 cpu_set = CPU_ALLOC(ncpus);
6162 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006163 PyErr_NoMemory();
6164 goto error;
6165 }
Larry Hastings2f936352014-08-05 14:04:04 +10006166 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006167
6168 while ((item = PyIter_Next(iterator))) {
6169 long cpu;
6170 if (!PyLong_Check(item)) {
6171 PyErr_Format(PyExc_TypeError,
6172 "expected an iterator of ints, "
6173 "but iterator yielded %R",
6174 Py_TYPE(item));
6175 Py_DECREF(item);
6176 goto error;
6177 }
6178 cpu = PyLong_AsLong(item);
6179 Py_DECREF(item);
6180 if (cpu < 0) {
6181 if (!PyErr_Occurred())
6182 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6183 goto error;
6184 }
6185 if (cpu > INT_MAX - 1) {
6186 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6187 goto error;
6188 }
6189 if (cpu >= ncpus) {
6190 /* Grow CPU mask to fit the CPU number */
6191 int newncpus = ncpus;
6192 cpu_set_t *newmask;
6193 size_t newsetsize;
6194 while (newncpus <= cpu) {
6195 if (newncpus > INT_MAX / 2)
6196 newncpus = cpu + 1;
6197 else
6198 newncpus = newncpus * 2;
6199 }
6200 newmask = CPU_ALLOC(newncpus);
6201 if (newmask == NULL) {
6202 PyErr_NoMemory();
6203 goto error;
6204 }
6205 newsetsize = CPU_ALLOC_SIZE(newncpus);
6206 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006207 memcpy(newmask, cpu_set, setsize);
6208 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006209 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006210 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006211 ncpus = newncpus;
6212 }
Larry Hastings2f936352014-08-05 14:04:04 +10006213 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006214 }
6215 Py_CLEAR(iterator);
6216
Larry Hastings2f936352014-08-05 14:04:04 +10006217 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006218 posix_error();
6219 goto error;
6220 }
Larry Hastings2f936352014-08-05 14:04:04 +10006221 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006222 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006223
6224error:
Larry Hastings2f936352014-08-05 14:04:04 +10006225 if (cpu_set)
6226 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006227 Py_XDECREF(iterator);
6228 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006229}
6230
Larry Hastings2f936352014-08-05 14:04:04 +10006231
6232/*[clinic input]
6233os.sched_getaffinity
6234 pid: pid_t
6235 /
6236
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006237Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006238
6239The affinity is returned as a set of CPU identifiers.
6240[clinic start generated code]*/
6241
Larry Hastings2f936352014-08-05 14:04:04 +10006242static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006243os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006244/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006245{
Antoine Pitrou84869872012-08-04 16:16:35 +02006246 int cpu, ncpus, count;
6247 size_t setsize;
6248 cpu_set_t *mask = NULL;
6249 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006250
Antoine Pitrou84869872012-08-04 16:16:35 +02006251 ncpus = NCPUS_START;
6252 while (1) {
6253 setsize = CPU_ALLOC_SIZE(ncpus);
6254 mask = CPU_ALLOC(ncpus);
6255 if (mask == NULL)
6256 return PyErr_NoMemory();
6257 if (sched_getaffinity(pid, setsize, mask) == 0)
6258 break;
6259 CPU_FREE(mask);
6260 if (errno != EINVAL)
6261 return posix_error();
6262 if (ncpus > INT_MAX / 2) {
6263 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6264 "a large enough CPU set");
6265 return NULL;
6266 }
6267 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006268 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006269
6270 res = PySet_New(NULL);
6271 if (res == NULL)
6272 goto error;
6273 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6274 if (CPU_ISSET_S(cpu, setsize, mask)) {
6275 PyObject *cpu_num = PyLong_FromLong(cpu);
6276 --count;
6277 if (cpu_num == NULL)
6278 goto error;
6279 if (PySet_Add(res, cpu_num)) {
6280 Py_DECREF(cpu_num);
6281 goto error;
6282 }
6283 Py_DECREF(cpu_num);
6284 }
6285 }
6286 CPU_FREE(mask);
6287 return res;
6288
6289error:
6290 if (mask)
6291 CPU_FREE(mask);
6292 Py_XDECREF(res);
6293 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006294}
6295
Benjamin Peterson2740af82011-08-02 17:41:34 -05006296#endif /* HAVE_SCHED_SETAFFINITY */
6297
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006298#endif /* HAVE_SCHED_H */
6299
Larry Hastings2f936352014-08-05 14:04:04 +10006300
Neal Norwitzb59798b2003-03-21 01:43:31 +00006301/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006302/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6303#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006304#define DEV_PTY_FILE "/dev/ptc"
6305#define HAVE_DEV_PTMX
6306#else
6307#define DEV_PTY_FILE "/dev/ptmx"
6308#endif
6309
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006310#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006311#ifdef HAVE_PTY_H
6312#include <pty.h>
6313#else
6314#ifdef HAVE_LIBUTIL_H
6315#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006316#else
6317#ifdef HAVE_UTIL_H
6318#include <util.h>
6319#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006320#endif /* HAVE_LIBUTIL_H */
6321#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006322#ifdef HAVE_STROPTS_H
6323#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006324#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006325#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006326
Larry Hastings2f936352014-08-05 14:04:04 +10006327
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006328#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006329/*[clinic input]
6330os.openpty
6331
6332Open a pseudo-terminal.
6333
6334Return a tuple of (master_fd, slave_fd) containing open file descriptors
6335for both the master and slave ends.
6336[clinic start generated code]*/
6337
Larry Hastings2f936352014-08-05 14:04:04 +10006338static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006339os_openpty_impl(PyObject *module)
6340/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006341{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006342 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006343#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006344 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006345#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006346#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006347 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006348#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006349 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006350#endif
6351#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006352
Thomas Wouters70c21a12000-07-14 14:28:33 +00006353#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006354 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006355 goto posix_error;
6356
6357 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6358 goto error;
6359 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6360 goto error;
6361
Neal Norwitzb59798b2003-03-21 01:43:31 +00006362#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006363 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6364 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006365 goto posix_error;
6366 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6367 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006368
Victor Stinnerdaf45552013-08-28 00:53:59 +02006369 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006370 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006371 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006372
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006373#else
Victor Stinner000de532013-11-25 23:19:58 +01006374 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006375 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006376 goto posix_error;
6377
Victor Stinner8c62be82010-05-06 00:08:46 +00006378 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006379
Victor Stinner8c62be82010-05-06 00:08:46 +00006380 /* change permission of slave */
6381 if (grantpt(master_fd) < 0) {
6382 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006383 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006384 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006385
Victor Stinner8c62be82010-05-06 00:08:46 +00006386 /* unlock slave */
6387 if (unlockpt(master_fd) < 0) {
6388 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006389 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006390 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006391
Victor Stinner8c62be82010-05-06 00:08:46 +00006392 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006393
Victor Stinner8c62be82010-05-06 00:08:46 +00006394 slave_name = ptsname(master_fd); /* get name of slave */
6395 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006396 goto posix_error;
6397
6398 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006399 if (slave_fd == -1)
6400 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006401
6402 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6403 goto posix_error;
6404
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006405#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006406 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6407 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006408#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006409 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006410#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006411#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006412#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006413
Victor Stinner8c62be82010-05-06 00:08:46 +00006414 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006415
Victor Stinnerdaf45552013-08-28 00:53:59 +02006416posix_error:
6417 posix_error();
6418error:
6419 if (master_fd != -1)
6420 close(master_fd);
6421 if (slave_fd != -1)
6422 close(slave_fd);
6423 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006424}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006425#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006426
Larry Hastings2f936352014-08-05 14:04:04 +10006427
Fred Drake8cef4cf2000-06-28 16:40:38 +00006428#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006429/*[clinic input]
6430os.forkpty
6431
6432Fork a new process with a new pseudo-terminal as controlling tty.
6433
6434Returns a tuple of (pid, master_fd).
6435Like fork(), return pid of 0 to the child process,
6436and pid of child to the parent process.
6437To both, return fd of newly opened pseudo-terminal.
6438[clinic start generated code]*/
6439
Larry Hastings2f936352014-08-05 14:04:04 +10006440static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006441os_forkpty_impl(PyObject *module)
6442/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006443{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006444 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006445 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006446
Eric Snow59032962018-09-14 14:17:20 -07006447 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6448 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6449 return NULL;
6450 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006451 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006452 pid = forkpty(&master_fd, NULL, NULL, NULL);
6453 if (pid == 0) {
6454 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006455 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006456 } else {
6457 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006458 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006459 }
6460 if (pid == -1)
6461 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006462 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006463}
Larry Hastings2f936352014-08-05 14:04:04 +10006464#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006465
Ross Lagerwall7807c352011-03-17 20:20:30 +02006466
Guido van Rossumad0ee831995-03-01 10:34:45 +00006467#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006468/*[clinic input]
6469os.getegid
6470
6471Return the current process's effective group id.
6472[clinic start generated code]*/
6473
Larry Hastings2f936352014-08-05 14:04:04 +10006474static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006475os_getegid_impl(PyObject *module)
6476/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006477{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006478 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006479}
Larry Hastings2f936352014-08-05 14:04:04 +10006480#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006481
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006482
Guido van Rossumad0ee831995-03-01 10:34:45 +00006483#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006484/*[clinic input]
6485os.geteuid
6486
6487Return the current process's effective user id.
6488[clinic start generated code]*/
6489
Larry Hastings2f936352014-08-05 14:04:04 +10006490static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006491os_geteuid_impl(PyObject *module)
6492/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006493{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006494 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006495}
Larry Hastings2f936352014-08-05 14:04:04 +10006496#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006497
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006498
Guido van Rossumad0ee831995-03-01 10:34:45 +00006499#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006500/*[clinic input]
6501os.getgid
6502
6503Return the current process's group id.
6504[clinic start generated code]*/
6505
Larry Hastings2f936352014-08-05 14:04:04 +10006506static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006507os_getgid_impl(PyObject *module)
6508/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006509{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006510 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006511}
Larry Hastings2f936352014-08-05 14:04:04 +10006512#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006513
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006514
Berker Peksag39404992016-09-15 20:45:16 +03006515#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006516/*[clinic input]
6517os.getpid
6518
6519Return the current process id.
6520[clinic start generated code]*/
6521
Larry Hastings2f936352014-08-05 14:04:04 +10006522static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006523os_getpid_impl(PyObject *module)
6524/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006525{
Victor Stinner8c62be82010-05-06 00:08:46 +00006526 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006527}
Berker Peksag39404992016-09-15 20:45:16 +03006528#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006529
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006530#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006531
6532/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006533PyDoc_STRVAR(posix_getgrouplist__doc__,
6534"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6535Returns a list of groups to which a user belongs.\n\n\
6536 user: username to lookup\n\
6537 group: base group id of the user");
6538
6539static PyObject *
6540posix_getgrouplist(PyObject *self, PyObject *args)
6541{
6542#ifdef NGROUPS_MAX
6543#define MAX_GROUPS NGROUPS_MAX
6544#else
6545 /* defined to be 16 on Solaris7, so this should be a small number */
6546#define MAX_GROUPS 64
6547#endif
6548
6549 const char *user;
6550 int i, ngroups;
6551 PyObject *list;
6552#ifdef __APPLE__
6553 int *groups, basegid;
6554#else
6555 gid_t *groups, basegid;
6556#endif
6557 ngroups = MAX_GROUPS;
6558
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006559#ifdef __APPLE__
6560 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006561 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006562#else
6563 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6564 _Py_Gid_Converter, &basegid))
6565 return NULL;
6566#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006567
6568#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006569 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006570#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006571 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006572#endif
6573 if (groups == NULL)
6574 return PyErr_NoMemory();
6575
6576 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6577 PyMem_Del(groups);
6578 return posix_error();
6579 }
6580
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006581#ifdef _Py_MEMORY_SANITIZER
6582 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6583 __msan_unpoison(&ngroups, sizeof(ngroups));
6584 __msan_unpoison(groups, ngroups*sizeof(*groups));
6585#endif
6586
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006587 list = PyList_New(ngroups);
6588 if (list == NULL) {
6589 PyMem_Del(groups);
6590 return NULL;
6591 }
6592
6593 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006594#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006595 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006596#else
6597 PyObject *o = _PyLong_FromGid(groups[i]);
6598#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006599 if (o == NULL) {
6600 Py_DECREF(list);
6601 PyMem_Del(groups);
6602 return NULL;
6603 }
6604 PyList_SET_ITEM(list, i, o);
6605 }
6606
6607 PyMem_Del(groups);
6608
6609 return list;
6610}
Larry Hastings2f936352014-08-05 14:04:04 +10006611#endif /* HAVE_GETGROUPLIST */
6612
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006613
Fred Drakec9680921999-12-13 16:37:25 +00006614#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006615/*[clinic input]
6616os.getgroups
6617
6618Return list of supplemental group IDs for the process.
6619[clinic start generated code]*/
6620
Larry Hastings2f936352014-08-05 14:04:04 +10006621static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006622os_getgroups_impl(PyObject *module)
6623/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006624{
6625 PyObject *result = NULL;
6626
Fred Drakec9680921999-12-13 16:37:25 +00006627#ifdef NGROUPS_MAX
6628#define MAX_GROUPS NGROUPS_MAX
6629#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006630 /* defined to be 16 on Solaris7, so this should be a small number */
Fred Drakec9680921999-12-13 16:37:25 +00006631#define MAX_GROUPS 64
6632#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00006633 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006634
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006635 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006636 * This is a helper variable to store the intermediate result when
6637 * that happens.
6638 *
6639 * To keep the code readable the OSX behaviour is unconditional,
6640 * according to the POSIX spec this should be safe on all unix-y
6641 * systems.
6642 */
6643 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006644 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006645
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006646#ifdef __APPLE__
6647 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6648 * there are more groups than can fit in grouplist. Therefore, on OS X
6649 * always first call getgroups with length 0 to get the actual number
6650 * of groups.
6651 */
6652 n = getgroups(0, NULL);
6653 if (n < 0) {
6654 return posix_error();
6655 } else if (n <= MAX_GROUPS) {
6656 /* groups will fit in existing array */
6657 alt_grouplist = grouplist;
6658 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006659 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006660 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006661 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006662 }
6663 }
6664
6665 n = getgroups(n, alt_grouplist);
6666 if (n == -1) {
6667 if (alt_grouplist != grouplist) {
6668 PyMem_Free(alt_grouplist);
6669 }
6670 return posix_error();
6671 }
6672#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006673 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006674 if (n < 0) {
6675 if (errno == EINVAL) {
6676 n = getgroups(0, NULL);
6677 if (n == -1) {
6678 return posix_error();
6679 }
6680 if (n == 0) {
6681 /* Avoid malloc(0) */
6682 alt_grouplist = grouplist;
6683 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006684 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006685 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006686 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006687 }
6688 n = getgroups(n, alt_grouplist);
6689 if (n == -1) {
6690 PyMem_Free(alt_grouplist);
6691 return posix_error();
6692 }
6693 }
6694 } else {
6695 return posix_error();
6696 }
6697 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006698#endif
6699
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006700 result = PyList_New(n);
6701 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00006702 int i;
6703 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006704 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00006705 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00006706 Py_DECREF(result);
6707 result = NULL;
6708 break;
Fred Drakec9680921999-12-13 16:37:25 +00006709 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006710 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00006711 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006712 }
6713
6714 if (alt_grouplist != grouplist) {
6715 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00006716 }
Neal Norwitze241ce82003-02-17 18:17:05 +00006717
Fred Drakec9680921999-12-13 16:37:25 +00006718 return result;
6719}
Larry Hastings2f936352014-08-05 14:04:04 +10006720#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00006721
Antoine Pitroub7572f02009-12-02 20:46:48 +00006722#ifdef HAVE_INITGROUPS
6723PyDoc_STRVAR(posix_initgroups__doc__,
6724"initgroups(username, gid) -> None\n\n\
6725Call the system initgroups() to initialize the group access list with all of\n\
6726the groups of which the specified username is a member, plus the specified\n\
6727group id.");
6728
Larry Hastings2f936352014-08-05 14:04:04 +10006729/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00006730static PyObject *
6731posix_initgroups(PyObject *self, PyObject *args)
6732{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006733 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03006734 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006735 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006736#ifdef __APPLE__
6737 int gid;
6738#else
6739 gid_t gid;
6740#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00006741
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006742#ifdef __APPLE__
6743 if (!PyArg_ParseTuple(args, "O&i:initgroups",
6744 PyUnicode_FSConverter, &oname,
6745 &gid))
6746#else
6747 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
6748 PyUnicode_FSConverter, &oname,
6749 _Py_Gid_Converter, &gid))
6750#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00006751 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006752 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00006753
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006754 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006755 Py_DECREF(oname);
6756 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00006757 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00006758
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02006759 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00006760}
Larry Hastings2f936352014-08-05 14:04:04 +10006761#endif /* HAVE_INITGROUPS */
6762
Antoine Pitroub7572f02009-12-02 20:46:48 +00006763
Martin v. Löwis606edc12002-06-13 21:09:11 +00006764#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10006765/*[clinic input]
6766os.getpgid
6767
6768 pid: pid_t
6769
6770Call the system call getpgid(), and return the result.
6771[clinic start generated code]*/
6772
Larry Hastings2f936352014-08-05 14:04:04 +10006773static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006774os_getpgid_impl(PyObject *module, pid_t pid)
6775/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006776{
6777 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00006778 if (pgid < 0)
6779 return posix_error();
6780 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00006781}
6782#endif /* HAVE_GETPGID */
6783
6784
Guido van Rossumb6775db1994-08-01 11:34:53 +00006785#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10006786/*[clinic input]
6787os.getpgrp
6788
6789Return the current process group id.
6790[clinic start generated code]*/
6791
Larry Hastings2f936352014-08-05 14:04:04 +10006792static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006793os_getpgrp_impl(PyObject *module)
6794/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00006795{
Guido van Rossumb6775db1994-08-01 11:34:53 +00006796#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00006797 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00006798#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00006799 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00006800#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00006801}
Guido van Rossumb6775db1994-08-01 11:34:53 +00006802#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00006803
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006804
Guido van Rossumb6775db1994-08-01 11:34:53 +00006805#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10006806/*[clinic input]
6807os.setpgrp
6808
6809Make the current process the leader of its process group.
6810[clinic start generated code]*/
6811
Larry Hastings2f936352014-08-05 14:04:04 +10006812static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006813os_setpgrp_impl(PyObject *module)
6814/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00006815{
Guido van Rossum64933891994-10-20 21:56:42 +00006816#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00006817 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00006818#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00006819 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00006820#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00006821 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02006822 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00006823}
Guido van Rossumb6775db1994-08-01 11:34:53 +00006824#endif /* HAVE_SETPGRP */
6825
Guido van Rossumad0ee831995-03-01 10:34:45 +00006826#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00006827
6828#ifdef MS_WINDOWS
6829#include <tlhelp32.h>
6830
6831static PyObject*
6832win32_getppid()
6833{
6834 HANDLE snapshot;
6835 pid_t mypid;
6836 PyObject* result = NULL;
6837 BOOL have_record;
6838 PROCESSENTRY32 pe;
6839
6840 mypid = getpid(); /* This function never fails */
6841
6842 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6843 if (snapshot == INVALID_HANDLE_VALUE)
6844 return PyErr_SetFromWindowsErr(GetLastError());
6845
6846 pe.dwSize = sizeof(pe);
6847 have_record = Process32First(snapshot, &pe);
6848 while (have_record) {
6849 if (mypid == (pid_t)pe.th32ProcessID) {
6850 /* We could cache the ulong value in a static variable. */
6851 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
6852 break;
6853 }
6854
6855 have_record = Process32Next(snapshot, &pe);
6856 }
6857
6858 /* If our loop exits and our pid was not found (result will be NULL)
6859 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
6860 * error anyway, so let's raise it. */
6861 if (!result)
6862 result = PyErr_SetFromWindowsErr(GetLastError());
6863
6864 CloseHandle(snapshot);
6865
6866 return result;
6867}
6868#endif /*MS_WINDOWS*/
6869
Larry Hastings2f936352014-08-05 14:04:04 +10006870
6871/*[clinic input]
6872os.getppid
6873
6874Return the parent's process id.
6875
6876If the parent process has already exited, Windows machines will still
6877return its id; others systems will return the id of the 'init' process (1).
6878[clinic start generated code]*/
6879
Larry Hastings2f936352014-08-05 14:04:04 +10006880static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006881os_getppid_impl(PyObject *module)
6882/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006883{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00006884#ifdef MS_WINDOWS
6885 return win32_getppid();
6886#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006887 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00006888#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00006889}
6890#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006891
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006892
Fred Drake12c6e2d1999-12-14 21:25:03 +00006893#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10006894/*[clinic input]
6895os.getlogin
6896
6897Return the actual login name.
6898[clinic start generated code]*/
6899
Larry Hastings2f936352014-08-05 14:04:04 +10006900static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006901os_getlogin_impl(PyObject *module)
6902/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00006903{
Victor Stinner8c62be82010-05-06 00:08:46 +00006904 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006905#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00006906 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02006907 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00006908
6909 if (GetUserNameW(user_name, &num_chars)) {
6910 /* num_chars is the number of unicode chars plus null terminator */
6911 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006912 }
6913 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00006914 result = PyErr_SetFromWindowsErr(GetLastError());
6915#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006916 char *name;
6917 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00006918
Victor Stinner8c62be82010-05-06 00:08:46 +00006919 errno = 0;
6920 name = getlogin();
6921 if (name == NULL) {
6922 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00006923 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00006924 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00006925 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00006926 }
6927 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00006928 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00006929 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00006930#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00006931 return result;
6932}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00006933#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00006934
Larry Hastings2f936352014-08-05 14:04:04 +10006935
Guido van Rossumad0ee831995-03-01 10:34:45 +00006936#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10006937/*[clinic input]
6938os.getuid
6939
6940Return the current process's user id.
6941[clinic start generated code]*/
6942
Larry Hastings2f936352014-08-05 14:04:04 +10006943static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006944os_getuid_impl(PyObject *module)
6945/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006946{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006947 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006948}
Larry Hastings2f936352014-08-05 14:04:04 +10006949#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006950
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006951
Brian Curtineb24d742010-04-12 17:16:38 +00006952#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10006953#define HAVE_KILL
6954#endif /* MS_WINDOWS */
6955
6956#ifdef HAVE_KILL
6957/*[clinic input]
6958os.kill
6959
6960 pid: pid_t
6961 signal: Py_ssize_t
6962 /
6963
6964Kill a process with a signal.
6965[clinic start generated code]*/
6966
Larry Hastings2f936352014-08-05 14:04:04 +10006967static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006968os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
6969/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006970#ifndef MS_WINDOWS
6971{
6972 if (kill(pid, (int)signal) == -1)
6973 return posix_error();
6974 Py_RETURN_NONE;
6975}
6976#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00006977{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00006978 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10006979 DWORD sig = (DWORD)signal;
6980 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00006981 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00006982
Victor Stinner8c62be82010-05-06 00:08:46 +00006983 /* Console processes which share a common console can be sent CTRL+C or
6984 CTRL+BREAK events, provided they handle said events. */
6985 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006986 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00006987 err = GetLastError();
6988 PyErr_SetFromWindowsErr(err);
6989 }
6990 else
6991 Py_RETURN_NONE;
6992 }
Brian Curtineb24d742010-04-12 17:16:38 +00006993
Victor Stinner8c62be82010-05-06 00:08:46 +00006994 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
6995 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006996 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00006997 if (handle == NULL) {
6998 err = GetLastError();
6999 return PyErr_SetFromWindowsErr(err);
7000 }
Brian Curtineb24d742010-04-12 17:16:38 +00007001
Victor Stinner8c62be82010-05-06 00:08:46 +00007002 if (TerminateProcess(handle, sig) == 0) {
7003 err = GetLastError();
7004 result = PyErr_SetFromWindowsErr(err);
7005 } else {
7006 Py_INCREF(Py_None);
7007 result = Py_None;
7008 }
Brian Curtineb24d742010-04-12 17:16:38 +00007009
Victor Stinner8c62be82010-05-06 00:08:46 +00007010 CloseHandle(handle);
7011 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007012}
Larry Hastings2f936352014-08-05 14:04:04 +10007013#endif /* !MS_WINDOWS */
7014#endif /* HAVE_KILL */
7015
7016
7017#ifdef HAVE_KILLPG
7018/*[clinic input]
7019os.killpg
7020
7021 pgid: pid_t
7022 signal: int
7023 /
7024
7025Kill a process group with a signal.
7026[clinic start generated code]*/
7027
Larry Hastings2f936352014-08-05 14:04:04 +10007028static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007029os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7030/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007031{
7032 /* XXX some man pages make the `pgid` parameter an int, others
7033 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7034 take the same type. Moreover, pid_t is always at least as wide as
7035 int (else compilation of this module fails), which is safe. */
7036 if (killpg(pgid, signal) == -1)
7037 return posix_error();
7038 Py_RETURN_NONE;
7039}
7040#endif /* HAVE_KILLPG */
7041
Brian Curtineb24d742010-04-12 17:16:38 +00007042
Guido van Rossumc0125471996-06-28 18:55:32 +00007043#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007044#ifdef HAVE_SYS_LOCK_H
7045#include <sys/lock.h>
7046#endif
7047
Larry Hastings2f936352014-08-05 14:04:04 +10007048/*[clinic input]
7049os.plock
7050 op: int
7051 /
7052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007053Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007054[clinic start generated code]*/
7055
Larry Hastings2f936352014-08-05 14:04:04 +10007056static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007057os_plock_impl(PyObject *module, int op)
7058/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007059{
Victor Stinner8c62be82010-05-06 00:08:46 +00007060 if (plock(op) == -1)
7061 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007062 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007063}
Larry Hastings2f936352014-08-05 14:04:04 +10007064#endif /* HAVE_PLOCK */
7065
Guido van Rossumc0125471996-06-28 18:55:32 +00007066
Guido van Rossumb6775db1994-08-01 11:34:53 +00007067#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007068/*[clinic input]
7069os.setuid
7070
7071 uid: uid_t
7072 /
7073
7074Set the current process's user id.
7075[clinic start generated code]*/
7076
Larry Hastings2f936352014-08-05 14:04:04 +10007077static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007078os_setuid_impl(PyObject *module, uid_t uid)
7079/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007080{
Victor Stinner8c62be82010-05-06 00:08:46 +00007081 if (setuid(uid) < 0)
7082 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007083 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007084}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007085#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007086
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007087
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007088#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007089/*[clinic input]
7090os.seteuid
7091
7092 euid: uid_t
7093 /
7094
7095Set the current process's effective user id.
7096[clinic start generated code]*/
7097
Larry Hastings2f936352014-08-05 14:04:04 +10007098static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007099os_seteuid_impl(PyObject *module, uid_t euid)
7100/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007101{
7102 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007103 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007104 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007105}
7106#endif /* HAVE_SETEUID */
7107
Larry Hastings2f936352014-08-05 14:04:04 +10007108
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007109#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007110/*[clinic input]
7111os.setegid
7112
7113 egid: gid_t
7114 /
7115
7116Set the current process's effective group id.
7117[clinic start generated code]*/
7118
Larry Hastings2f936352014-08-05 14:04:04 +10007119static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007120os_setegid_impl(PyObject *module, gid_t egid)
7121/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007122{
7123 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007124 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007125 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007126}
7127#endif /* HAVE_SETEGID */
7128
Larry Hastings2f936352014-08-05 14:04:04 +10007129
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007130#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007131/*[clinic input]
7132os.setreuid
7133
7134 ruid: uid_t
7135 euid: uid_t
7136 /
7137
7138Set the current process's real and effective user ids.
7139[clinic start generated code]*/
7140
Larry Hastings2f936352014-08-05 14:04:04 +10007141static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007142os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7143/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007144{
Victor Stinner8c62be82010-05-06 00:08:46 +00007145 if (setreuid(ruid, euid) < 0) {
7146 return posix_error();
7147 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007148 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007149 }
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007150}
7151#endif /* HAVE_SETREUID */
7152
Larry Hastings2f936352014-08-05 14:04:04 +10007153
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007154#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007155/*[clinic input]
7156os.setregid
7157
7158 rgid: gid_t
7159 egid: gid_t
7160 /
7161
7162Set the current process's real and effective group ids.
7163[clinic start generated code]*/
7164
Larry Hastings2f936352014-08-05 14:04:04 +10007165static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007166os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7167/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007168{
7169 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007170 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007171 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007172}
7173#endif /* HAVE_SETREGID */
7174
Larry Hastings2f936352014-08-05 14:04:04 +10007175
Guido van Rossumb6775db1994-08-01 11:34:53 +00007176#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007177/*[clinic input]
7178os.setgid
7179 gid: gid_t
7180 /
7181
7182Set the current process's group id.
7183[clinic start generated code]*/
7184
Larry Hastings2f936352014-08-05 14:04:04 +10007185static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007186os_setgid_impl(PyObject *module, gid_t gid)
7187/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007188{
Victor Stinner8c62be82010-05-06 00:08:46 +00007189 if (setgid(gid) < 0)
7190 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007191 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007192}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007193#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007194
Larry Hastings2f936352014-08-05 14:04:04 +10007195
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007196#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007197/*[clinic input]
7198os.setgroups
7199
7200 groups: object
7201 /
7202
7203Set the groups of the current process to list.
7204[clinic start generated code]*/
7205
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007206static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007207os_setgroups(PyObject *module, PyObject *groups)
7208/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007209{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007210 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007211 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007212
Victor Stinner8c62be82010-05-06 00:08:46 +00007213 if (!PySequence_Check(groups)) {
7214 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7215 return NULL;
7216 }
7217 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007218 if (len < 0) {
7219 return NULL;
7220 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007221 if (len > MAX_GROUPS) {
7222 PyErr_SetString(PyExc_ValueError, "too many groups");
7223 return NULL;
7224 }
7225 for(i = 0; i < len; i++) {
7226 PyObject *elem;
7227 elem = PySequence_GetItem(groups, i);
7228 if (!elem)
7229 return NULL;
7230 if (!PyLong_Check(elem)) {
7231 PyErr_SetString(PyExc_TypeError,
7232 "groups must be integers");
7233 Py_DECREF(elem);
7234 return NULL;
7235 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007236 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007237 Py_DECREF(elem);
7238 return NULL;
7239 }
7240 }
7241 Py_DECREF(elem);
7242 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007243
Victor Stinner8c62be82010-05-06 00:08:46 +00007244 if (setgroups(len, grouplist) < 0)
7245 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007246 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007247}
7248#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007249
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007250#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7251static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007252wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007253{
Victor Stinner8c62be82010-05-06 00:08:46 +00007254 PyObject *result;
7255 static PyObject *struct_rusage;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02007256 _Py_IDENTIFIER(struct_rusage);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007257
Victor Stinner8c62be82010-05-06 00:08:46 +00007258 if (pid == -1)
7259 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007260
Victor Stinner8c62be82010-05-06 00:08:46 +00007261 if (struct_rusage == NULL) {
7262 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7263 if (m == NULL)
7264 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02007265 struct_rusage = _PyObject_GetAttrId(m, &PyId_struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007266 Py_DECREF(m);
7267 if (struct_rusage == NULL)
7268 return NULL;
7269 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007270
Victor Stinner8c62be82010-05-06 00:08:46 +00007271 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7272 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
7273 if (!result)
7274 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007275
7276#ifndef doubletime
7277#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7278#endif
7279
Victor Stinner8c62be82010-05-06 00:08:46 +00007280 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007281 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007282 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007283 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007284#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007285 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7286 SET_INT(result, 2, ru->ru_maxrss);
7287 SET_INT(result, 3, ru->ru_ixrss);
7288 SET_INT(result, 4, ru->ru_idrss);
7289 SET_INT(result, 5, ru->ru_isrss);
7290 SET_INT(result, 6, ru->ru_minflt);
7291 SET_INT(result, 7, ru->ru_majflt);
7292 SET_INT(result, 8, ru->ru_nswap);
7293 SET_INT(result, 9, ru->ru_inblock);
7294 SET_INT(result, 10, ru->ru_oublock);
7295 SET_INT(result, 11, ru->ru_msgsnd);
7296 SET_INT(result, 12, ru->ru_msgrcv);
7297 SET_INT(result, 13, ru->ru_nsignals);
7298 SET_INT(result, 14, ru->ru_nvcsw);
7299 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007300#undef SET_INT
7301
Victor Stinner8c62be82010-05-06 00:08:46 +00007302 if (PyErr_Occurred()) {
7303 Py_DECREF(result);
7304 return NULL;
7305 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007306
Victor Stinner8c62be82010-05-06 00:08:46 +00007307 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007308}
7309#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7310
Larry Hastings2f936352014-08-05 14:04:04 +10007311
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007312#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007313/*[clinic input]
7314os.wait3
7315
7316 options: int
7317Wait for completion of a child process.
7318
7319Returns a tuple of information about the child process:
7320 (pid, status, rusage)
7321[clinic start generated code]*/
7322
Larry Hastings2f936352014-08-05 14:04:04 +10007323static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007324os_wait3_impl(PyObject *module, int options)
7325/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007326{
Victor Stinner8c62be82010-05-06 00:08:46 +00007327 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007328 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007329 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007330 WAIT_TYPE status;
7331 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007332
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007333 do {
7334 Py_BEGIN_ALLOW_THREADS
7335 pid = wait3(&status, options, &ru);
7336 Py_END_ALLOW_THREADS
7337 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7338 if (pid < 0)
7339 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007340
Victor Stinner4195b5c2012-02-08 23:03:19 +01007341 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007342}
7343#endif /* HAVE_WAIT3 */
7344
Larry Hastings2f936352014-08-05 14:04:04 +10007345
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007346#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007347/*[clinic input]
7348
7349os.wait4
7350
7351 pid: pid_t
7352 options: int
7353
7354Wait for completion of a specific child process.
7355
7356Returns a tuple of information about the child process:
7357 (pid, status, rusage)
7358[clinic start generated code]*/
7359
Larry Hastings2f936352014-08-05 14:04:04 +10007360static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007361os_wait4_impl(PyObject *module, pid_t pid, int options)
7362/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007363{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007364 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007365 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007366 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007367 WAIT_TYPE status;
7368 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007369
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007370 do {
7371 Py_BEGIN_ALLOW_THREADS
7372 res = wait4(pid, &status, options, &ru);
7373 Py_END_ALLOW_THREADS
7374 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7375 if (res < 0)
7376 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007377
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007378 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007379}
7380#endif /* HAVE_WAIT4 */
7381
Larry Hastings2f936352014-08-05 14:04:04 +10007382
Ross Lagerwall7807c352011-03-17 20:20:30 +02007383#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007384/*[clinic input]
7385os.waitid
7386
7387 idtype: idtype_t
7388 Must be one of be P_PID, P_PGID or P_ALL.
7389 id: id_t
7390 The id to wait on.
7391 options: int
7392 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7393 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7394 /
7395
7396Returns the result of waiting for a process or processes.
7397
7398Returns either waitid_result or None if WNOHANG is specified and there are
7399no children in a waitable state.
7400[clinic start generated code]*/
7401
Larry Hastings2f936352014-08-05 14:04:04 +10007402static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007403os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7404/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007405{
7406 PyObject *result;
7407 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007408 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007409 siginfo_t si;
7410 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007411
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007412 do {
7413 Py_BEGIN_ALLOW_THREADS
7414 res = waitid(idtype, id, &si, options);
7415 Py_END_ALLOW_THREADS
7416 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7417 if (res < 0)
7418 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007419
7420 if (si.si_pid == 0)
7421 Py_RETURN_NONE;
7422
Eddie Elizondo474eedf2018-11-13 04:09:31 -08007423 result = PyStructSequence_New(WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007424 if (!result)
7425 return NULL;
7426
7427 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007428 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007429 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7430 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7431 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7432 if (PyErr_Occurred()) {
7433 Py_DECREF(result);
7434 return NULL;
7435 }
7436
7437 return result;
7438}
Larry Hastings2f936352014-08-05 14:04:04 +10007439#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007440
Larry Hastings2f936352014-08-05 14:04:04 +10007441
7442#if defined(HAVE_WAITPID)
7443/*[clinic input]
7444os.waitpid
7445 pid: pid_t
7446 options: int
7447 /
7448
7449Wait for completion of a given child process.
7450
7451Returns a tuple of information regarding the child process:
7452 (pid, status)
7453
7454The options argument is ignored on Windows.
7455[clinic start generated code]*/
7456
Larry Hastings2f936352014-08-05 14:04:04 +10007457static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007458os_waitpid_impl(PyObject *module, pid_t pid, int options)
7459/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007460{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007461 pid_t res;
7462 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007463 WAIT_TYPE status;
7464 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007465
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007466 do {
7467 Py_BEGIN_ALLOW_THREADS
7468 res = waitpid(pid, &status, options);
7469 Py_END_ALLOW_THREADS
7470 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7471 if (res < 0)
7472 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007473
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007474 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007475}
Tim Petersab034fa2002-02-01 11:27:43 +00007476#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007477/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007478/*[clinic input]
7479os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007480 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007481 options: int
7482 /
7483
7484Wait for completion of a given process.
7485
7486Returns a tuple of information regarding the process:
7487 (pid, status << 8)
7488
7489The options argument is ignored on Windows.
7490[clinic start generated code]*/
7491
Larry Hastings2f936352014-08-05 14:04:04 +10007492static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007493os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007494/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007495{
7496 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007497 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007498 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007499
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007500 do {
7501 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007502 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007503 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007504 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007505 Py_END_ALLOW_THREADS
7506 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007507 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007508 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007509
Victor Stinner8c62be82010-05-06 00:08:46 +00007510 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007511 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007512}
Larry Hastings2f936352014-08-05 14:04:04 +10007513#endif
7514
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007515
Guido van Rossumad0ee831995-03-01 10:34:45 +00007516#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007517/*[clinic input]
7518os.wait
7519
7520Wait for completion of a child process.
7521
7522Returns a tuple of information about the child process:
7523 (pid, status)
7524[clinic start generated code]*/
7525
Larry Hastings2f936352014-08-05 14:04:04 +10007526static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007527os_wait_impl(PyObject *module)
7528/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007529{
Victor Stinner8c62be82010-05-06 00:08:46 +00007530 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007531 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007532 WAIT_TYPE status;
7533 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007534
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007535 do {
7536 Py_BEGIN_ALLOW_THREADS
7537 pid = wait(&status);
7538 Py_END_ALLOW_THREADS
7539 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7540 if (pid < 0)
7541 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007542
Victor Stinner8c62be82010-05-06 00:08:46 +00007543 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007544}
Larry Hastings2f936352014-08-05 14:04:04 +10007545#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007546
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007547
Larry Hastings9cf065c2012-06-22 16:30:09 -07007548#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007549/*[clinic input]
7550os.readlink
7551
7552 path: path_t
7553 *
7554 dir_fd: dir_fd(requires='readlinkat') = None
7555
7556Return a string representing the path to which the symbolic link points.
7557
7558If dir_fd is not None, it should be a file descriptor open to a directory,
7559and path should be relative; path will then be relative to that directory.
7560
7561dir_fd may not be implemented on your platform. If it is unavailable,
7562using it will raise a NotImplementedError.
7563[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007564
Barry Warsaw53699e91996-12-10 23:23:01 +00007565static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007566os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7567/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007568{
Berker Peksage0b5b202018-08-15 13:03:41 +03007569#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007570 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007571 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007572
7573 Py_BEGIN_ALLOW_THREADS
7574#ifdef HAVE_READLINKAT
7575 if (dir_fd != DEFAULT_DIR_FD)
7576 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7577 else
7578#endif
7579 length = readlink(path->narrow, buffer, MAXPATHLEN);
7580 Py_END_ALLOW_THREADS
7581
7582 if (length < 0) {
7583 return path_error(path);
7584 }
7585 buffer[length] = '\0';
7586
7587 if (PyUnicode_Check(path->object))
7588 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7589 else
7590 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007591#elif defined(MS_WINDOWS)
7592 DWORD n_bytes_returned;
7593 DWORD io_result;
7594 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007595 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7596 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
7597 const wchar_t *print_name;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007598 PyObject *result;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007599
Larry Hastings2f936352014-08-05 14:04:04 +10007600 /* First get a handle to the reparse point */
7601 Py_BEGIN_ALLOW_THREADS
7602 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007603 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007604 0,
7605 0,
7606 0,
7607 OPEN_EXISTING,
7608 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7609 0);
7610 Py_END_ALLOW_THREADS
7611
Berker Peksage0b5b202018-08-15 13:03:41 +03007612 if (reparse_point_handle == INVALID_HANDLE_VALUE) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007613 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007614 }
Larry Hastings2f936352014-08-05 14:04:04 +10007615
7616 Py_BEGIN_ALLOW_THREADS
7617 /* New call DeviceIoControl to read the reparse point */
7618 io_result = DeviceIoControl(
7619 reparse_point_handle,
7620 FSCTL_GET_REPARSE_POINT,
7621 0, 0, /* in buffer */
7622 target_buffer, sizeof(target_buffer),
7623 &n_bytes_returned,
7624 0 /* we're not using OVERLAPPED_IO */
7625 );
7626 CloseHandle(reparse_point_handle);
7627 Py_END_ALLOW_THREADS
7628
Berker Peksage0b5b202018-08-15 13:03:41 +03007629 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007630 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007631 }
Larry Hastings2f936352014-08-05 14:04:04 +10007632
7633 if (rdb->ReparseTag != IO_REPARSE_TAG_SYMLINK)
7634 {
7635 PyErr_SetString(PyExc_ValueError,
7636 "not a symbolic link");
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007637 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10007638 }
SSE43c34aad2018-02-13 00:10:35 +07007639 print_name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7640 rdb->SymbolicLinkReparseBuffer.PrintNameOffset);
Larry Hastings2f936352014-08-05 14:04:04 +10007641
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007642 result = PyUnicode_FromWideChar(print_name,
7643 rdb->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(wchar_t));
7644 if (path->narrow) {
7645 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Berker Peksage0b5b202018-08-15 13:03:41 +03007646 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007647 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03007648#endif
Larry Hastings2f936352014-08-05 14:04:04 +10007649}
Berker Peksage0b5b202018-08-15 13:03:41 +03007650#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007651
Larry Hastings9cf065c2012-06-22 16:30:09 -07007652#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07007653
7654#if defined(MS_WINDOWS)
7655
7656/* Grab CreateSymbolicLinkW dynamically from kernel32 */
Steve Dower6921e732018-03-05 14:26:08 -08007657static BOOLEAN (CALLBACK *Py_CreateSymbolicLinkW)(LPCWSTR, LPCWSTR, DWORD) = NULL;
Victor Stinner31b3b922013-06-05 01:49:17 +02007658
Larry Hastings9cf065c2012-06-22 16:30:09 -07007659static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007660check_CreateSymbolicLink(void)
Larry Hastings9cf065c2012-06-22 16:30:09 -07007661{
7662 HINSTANCE hKernel32;
7663 /* only recheck */
Steve Dowercc16be82016-09-08 10:35:16 -07007664 if (Py_CreateSymbolicLinkW)
Larry Hastings9cf065c2012-06-22 16:30:09 -07007665 return 1;
7666 hKernel32 = GetModuleHandleW(L"KERNEL32");
7667 *(FARPROC*)&Py_CreateSymbolicLinkW = GetProcAddress(hKernel32,
7668 "CreateSymbolicLinkW");
Steve Dowercc16be82016-09-08 10:35:16 -07007669 return Py_CreateSymbolicLinkW != NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07007670}
7671
Steve Dower6921e732018-03-05 14:26:08 -08007672/* Remove the last portion of the path - return 0 on success */
7673static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007674_dirnameW(WCHAR *path)
7675{
Jason R. Coombs3a092862013-05-27 23:21:28 -04007676 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08007677 size_t length = wcsnlen_s(path, MAX_PATH);
7678 if (length == MAX_PATH) {
7679 return -1;
7680 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007681
7682 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08007683 for(ptr = path + length; ptr != path; ptr--) {
7684 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04007685 break;
Steve Dower6921e732018-03-05 14:26:08 -08007686 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007687 }
7688 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08007689 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04007690}
7691
Victor Stinner31b3b922013-06-05 01:49:17 +02007692/* Is this path absolute? */
7693static int
7694_is_absW(const WCHAR *path)
7695{
Steve Dower6921e732018-03-05 14:26:08 -08007696 return path[0] == L'\\' || path[0] == L'/' ||
7697 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04007698}
7699
Steve Dower6921e732018-03-05 14:26:08 -08007700/* join root and rest with a backslash - return 0 on success */
7701static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007702_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
7703{
Victor Stinner31b3b922013-06-05 01:49:17 +02007704 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08007705 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04007706 }
7707
Steve Dower6921e732018-03-05 14:26:08 -08007708 if (wcscpy_s(dest_path, MAX_PATH, root)) {
7709 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04007710 }
Steve Dower6921e732018-03-05 14:26:08 -08007711
7712 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
7713 return -1;
7714 }
7715
7716 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04007717}
7718
Victor Stinner31b3b922013-06-05 01:49:17 +02007719/* Return True if the path at src relative to dest is a directory */
7720static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007721_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04007722{
Jason R. Coombs3a092862013-05-27 23:21:28 -04007723 WIN32_FILE_ATTRIBUTE_DATA src_info;
7724 WCHAR dest_parent[MAX_PATH];
7725 WCHAR src_resolved[MAX_PATH] = L"";
7726
7727 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08007728 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
7729 _dirnameW(dest_parent)) {
7730 return 0;
7731 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007732 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08007733 if (_joinW(src_resolved, dest_parent, src)) {
7734 return 0;
7735 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007736 return (
7737 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
7738 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
7739 );
7740}
Larry Hastings9cf065c2012-06-22 16:30:09 -07007741#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007742
Larry Hastings2f936352014-08-05 14:04:04 +10007743
7744/*[clinic input]
7745os.symlink
7746 src: path_t
7747 dst: path_t
7748 target_is_directory: bool = False
7749 *
7750 dir_fd: dir_fd(requires='symlinkat')=None
7751
7752# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
7753
7754Create a symbolic link pointing to src named dst.
7755
7756target_is_directory is required on Windows if the target is to be
7757 interpreted as a directory. (On Windows, symlink requires
7758 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
7759 target_is_directory is ignored on non-Windows platforms.
7760
7761If dir_fd is not None, it should be a file descriptor open to a directory,
7762 and path should be relative; path will then be relative to that directory.
7763dir_fd may not be implemented on your platform.
7764 If it is unavailable, using it will raise a NotImplementedError.
7765
7766[clinic start generated code]*/
7767
Larry Hastings2f936352014-08-05 14:04:04 +10007768static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007769os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04007770 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007771/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007772{
Larry Hastings9cf065c2012-06-22 16:30:09 -07007773#ifdef MS_WINDOWS
7774 DWORD result;
7775#else
7776 int result;
7777#endif
7778
Larry Hastings9cf065c2012-06-22 16:30:09 -07007779#ifdef MS_WINDOWS
7780 if (!check_CreateSymbolicLink()) {
7781 PyErr_SetString(PyExc_NotImplementedError,
7782 "CreateSymbolicLink functions not found");
Larry Hastings2f936352014-08-05 14:04:04 +10007783 return NULL;
Petri Lehtinen5445a8c2012-10-23 16:12:14 +03007784 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07007785 if (!win32_can_symlink) {
7786 PyErr_SetString(PyExc_OSError, "symbolic link privilege not held");
Larry Hastings2f936352014-08-05 14:04:04 +10007787 return NULL;
Petri Lehtinen5445a8c2012-10-23 16:12:14 +03007788 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07007789#endif
7790
Larry Hastings9cf065c2012-06-22 16:30:09 -07007791#ifdef MS_WINDOWS
Jason R. Coombs3a092862013-05-27 23:21:28 -04007792
Larry Hastings9cf065c2012-06-22 16:30:09 -07007793 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08007794 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07007795 /* if src is a directory, ensure target_is_directory==1 */
7796 target_is_directory |= _check_dirW(src->wide, dst->wide);
7797 result = Py_CreateSymbolicLinkW(dst->wide, src->wide,
7798 target_is_directory);
Steve Dower6921e732018-03-05 14:26:08 -08007799 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07007800 Py_END_ALLOW_THREADS
7801
Larry Hastings2f936352014-08-05 14:04:04 +10007802 if (!result)
7803 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07007804
7805#else
7806
Steve Dower6921e732018-03-05 14:26:08 -08007807 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
7808 PyErr_SetString(PyExc_ValueError,
7809 "symlink: src and dst must be the same type");
7810 return NULL;
7811 }
7812
Larry Hastings9cf065c2012-06-22 16:30:09 -07007813 Py_BEGIN_ALLOW_THREADS
7814#if HAVE_SYMLINKAT
7815 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10007816 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07007817 else
7818#endif
Larry Hastings2f936352014-08-05 14:04:04 +10007819 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07007820 Py_END_ALLOW_THREADS
7821
Larry Hastings2f936352014-08-05 14:04:04 +10007822 if (result)
7823 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07007824#endif
7825
Larry Hastings2f936352014-08-05 14:04:04 +10007826 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00007827}
7828#endif /* HAVE_SYMLINK */
7829
Larry Hastings9cf065c2012-06-22 16:30:09 -07007830
Brian Curtind40e6f72010-07-08 21:39:08 +00007831
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00007832
Larry Hastings605a62d2012-06-24 04:33:36 -07007833static PyStructSequence_Field times_result_fields[] = {
7834 {"user", "user time"},
7835 {"system", "system time"},
7836 {"children_user", "user time of children"},
7837 {"children_system", "system time of children"},
7838 {"elapsed", "elapsed time since an arbitrary point in the past"},
7839 {NULL}
7840};
7841
7842PyDoc_STRVAR(times_result__doc__,
7843"times_result: Result from os.times().\n\n\
7844This object may be accessed either as a tuple of\n\
7845 (user, system, children_user, children_system, elapsed),\n\
7846or via the attributes user, system, children_user, children_system,\n\
7847and elapsed.\n\
7848\n\
7849See os.times for more information.");
7850
7851static PyStructSequence_Desc times_result_desc = {
7852 "times_result", /* name */
7853 times_result__doc__, /* doc */
7854 times_result_fields,
7855 5
7856};
7857
Eddie Elizondo474eedf2018-11-13 04:09:31 -08007858static PyTypeObject* TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07007859
Antoine Pitrouf3923e92012-07-24 21:23:53 +02007860#ifdef MS_WINDOWS
7861#define HAVE_TIMES /* mandatory, for the method table */
7862#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07007863
Antoine Pitrouf3923e92012-07-24 21:23:53 +02007864#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07007865
7866static PyObject *
7867build_times_result(double user, double system,
7868 double children_user, double children_system,
7869 double elapsed)
7870{
Eddie Elizondo474eedf2018-11-13 04:09:31 -08007871 PyObject *value = PyStructSequence_New(TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07007872 if (value == NULL)
7873 return NULL;
7874
7875#define SET(i, field) \
7876 { \
7877 PyObject *o = PyFloat_FromDouble(field); \
7878 if (!o) { \
7879 Py_DECREF(value); \
7880 return NULL; \
7881 } \
7882 PyStructSequence_SET_ITEM(value, i, o); \
7883 } \
7884
7885 SET(0, user);
7886 SET(1, system);
7887 SET(2, children_user);
7888 SET(3, children_system);
7889 SET(4, elapsed);
7890
7891#undef SET
7892
7893 return value;
7894}
7895
Larry Hastings605a62d2012-06-24 04:33:36 -07007896
Larry Hastings2f936352014-08-05 14:04:04 +10007897#ifndef MS_WINDOWS
7898#define NEED_TICKS_PER_SECOND
7899static long ticks_per_second = -1;
7900#endif /* MS_WINDOWS */
7901
7902/*[clinic input]
7903os.times
7904
7905Return a collection containing process timing information.
7906
7907The object returned behaves like a named tuple with these fields:
7908 (utime, stime, cutime, cstime, elapsed_time)
7909All fields are floating point numbers.
7910[clinic start generated code]*/
7911
Larry Hastings2f936352014-08-05 14:04:04 +10007912static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007913os_times_impl(PyObject *module)
7914/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007915#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00007916{
Victor Stinner8c62be82010-05-06 00:08:46 +00007917 FILETIME create, exit, kernel, user;
7918 HANDLE hProc;
7919 hProc = GetCurrentProcess();
7920 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
7921 /* The fields of a FILETIME structure are the hi and lo part
7922 of a 64-bit value expressed in 100 nanosecond units.
7923 1e7 is one second in such units; 1e-7 the inverse.
7924 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
7925 */
Larry Hastings605a62d2012-06-24 04:33:36 -07007926 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00007927 (double)(user.dwHighDateTime*429.4967296 +
7928 user.dwLowDateTime*1e-7),
7929 (double)(kernel.dwHighDateTime*429.4967296 +
7930 kernel.dwLowDateTime*1e-7),
7931 (double)0,
7932 (double)0,
7933 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00007934}
Larry Hastings2f936352014-08-05 14:04:04 +10007935#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02007936{
Larry Hastings2f936352014-08-05 14:04:04 +10007937
7938
Antoine Pitrouf3923e92012-07-24 21:23:53 +02007939 struct tms t;
7940 clock_t c;
7941 errno = 0;
7942 c = times(&t);
7943 if (c == (clock_t) -1)
7944 return posix_error();
7945 return build_times_result(
7946 (double)t.tms_utime / ticks_per_second,
7947 (double)t.tms_stime / ticks_per_second,
7948 (double)t.tms_cutime / ticks_per_second,
7949 (double)t.tms_cstime / ticks_per_second,
7950 (double)c / ticks_per_second);
7951}
Larry Hastings2f936352014-08-05 14:04:04 +10007952#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02007953#endif /* HAVE_TIMES */
7954
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007955
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00007956#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10007957/*[clinic input]
7958os.getsid
7959
7960 pid: pid_t
7961 /
7962
7963Call the system call getsid(pid) and return the result.
7964[clinic start generated code]*/
7965
Larry Hastings2f936352014-08-05 14:04:04 +10007966static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007967os_getsid_impl(PyObject *module, pid_t pid)
7968/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007969{
Victor Stinner8c62be82010-05-06 00:08:46 +00007970 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007971 sid = getsid(pid);
7972 if (sid < 0)
7973 return posix_error();
7974 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00007975}
7976#endif /* HAVE_GETSID */
7977
7978
Guido van Rossumb6775db1994-08-01 11:34:53 +00007979#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10007980/*[clinic input]
7981os.setsid
7982
7983Call the system call setsid().
7984[clinic start generated code]*/
7985
Larry Hastings2f936352014-08-05 14:04:04 +10007986static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007987os_setsid_impl(PyObject *module)
7988/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007989{
Victor Stinner8c62be82010-05-06 00:08:46 +00007990 if (setsid() < 0)
7991 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007992 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007993}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007994#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00007995
Larry Hastings2f936352014-08-05 14:04:04 +10007996
Guido van Rossumb6775db1994-08-01 11:34:53 +00007997#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007998/*[clinic input]
7999os.setpgid
8000
8001 pid: pid_t
8002 pgrp: pid_t
8003 /
8004
8005Call the system call setpgid(pid, pgrp).
8006[clinic start generated code]*/
8007
Larry Hastings2f936352014-08-05 14:04:04 +10008008static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008009os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8010/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008011{
Victor Stinner8c62be82010-05-06 00:08:46 +00008012 if (setpgid(pid, pgrp) < 0)
8013 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008014 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008015}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008016#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008017
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008018
Guido van Rossumb6775db1994-08-01 11:34:53 +00008019#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008020/*[clinic input]
8021os.tcgetpgrp
8022
8023 fd: int
8024 /
8025
8026Return the process group associated with the terminal specified by fd.
8027[clinic start generated code]*/
8028
Larry Hastings2f936352014-08-05 14:04:04 +10008029static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008030os_tcgetpgrp_impl(PyObject *module, int fd)
8031/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008032{
8033 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008034 if (pgid < 0)
8035 return posix_error();
8036 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008037}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008038#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008039
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008040
Guido van Rossumb6775db1994-08-01 11:34:53 +00008041#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008042/*[clinic input]
8043os.tcsetpgrp
8044
8045 fd: int
8046 pgid: pid_t
8047 /
8048
8049Set the process group associated with the terminal specified by fd.
8050[clinic start generated code]*/
8051
Larry Hastings2f936352014-08-05 14:04:04 +10008052static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008053os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8054/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008055{
Victor Stinner8c62be82010-05-06 00:08:46 +00008056 if (tcsetpgrp(fd, pgid) < 0)
8057 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008058 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008059}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008060#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008061
Guido van Rossum687dd131993-05-17 08:34:16 +00008062/* Functions acting on file descriptors */
8063
Victor Stinnerdaf45552013-08-28 00:53:59 +02008064#ifdef O_CLOEXEC
8065extern int _Py_open_cloexec_works;
8066#endif
8067
Larry Hastings2f936352014-08-05 14:04:04 +10008068
8069/*[clinic input]
8070os.open -> int
8071 path: path_t
8072 flags: int
8073 mode: int = 0o777
8074 *
8075 dir_fd: dir_fd(requires='openat') = None
8076
8077# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8078
8079Open a file for low level IO. Returns a file descriptor (integer).
8080
8081If dir_fd is not None, it should be a file descriptor open to a directory,
8082 and path should be relative; path will then be relative to that directory.
8083dir_fd may not be implemented on your platform.
8084 If it is unavailable, using it will raise a NotImplementedError.
8085[clinic start generated code]*/
8086
Larry Hastings2f936352014-08-05 14:04:04 +10008087static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008088os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8089/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008090{
8091 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008092 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008093
Victor Stinnerdaf45552013-08-28 00:53:59 +02008094#ifdef O_CLOEXEC
8095 int *atomic_flag_works = &_Py_open_cloexec_works;
8096#elif !defined(MS_WINDOWS)
8097 int *atomic_flag_works = NULL;
8098#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008099
Victor Stinnerdaf45552013-08-28 00:53:59 +02008100#ifdef MS_WINDOWS
8101 flags |= O_NOINHERIT;
8102#elif defined(O_CLOEXEC)
8103 flags |= O_CLOEXEC;
8104#endif
8105
Steve Dower8fc89802015-04-12 00:26:27 -04008106 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008107 do {
8108 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008109#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008110 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008111#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008112#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008113 if (dir_fd != DEFAULT_DIR_FD)
8114 fd = openat(dir_fd, path->narrow, flags, mode);
8115 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008116#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008117 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008118#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008119 Py_END_ALLOW_THREADS
8120 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008121 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008122
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008123 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008124 if (!async_err)
8125 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008126 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008127 }
8128
Victor Stinnerdaf45552013-08-28 00:53:59 +02008129#ifndef MS_WINDOWS
8130 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8131 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008132 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008133 }
8134#endif
8135
Larry Hastings2f936352014-08-05 14:04:04 +10008136 return fd;
8137}
8138
8139
8140/*[clinic input]
8141os.close
8142
8143 fd: int
8144
8145Close a file descriptor.
8146[clinic start generated code]*/
8147
Barry Warsaw53699e91996-12-10 23:23:01 +00008148static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008149os_close_impl(PyObject *module, int fd)
8150/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008151{
Larry Hastings2f936352014-08-05 14:04:04 +10008152 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008153 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8154 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8155 * for more details.
8156 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008157 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008158 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008159 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008160 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008161 Py_END_ALLOW_THREADS
8162 if (res < 0)
8163 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008164 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008165}
8166
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008167
Larry Hastings2f936352014-08-05 14:04:04 +10008168/*[clinic input]
8169os.closerange
8170
8171 fd_low: int
8172 fd_high: int
8173 /
8174
8175Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8176[clinic start generated code]*/
8177
Larry Hastings2f936352014-08-05 14:04:04 +10008178static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008179os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8180/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008181{
8182 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00008183 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008184 _Py_BEGIN_SUPPRESS_IPH
Benjamin Peterson207116b2016-09-08 11:28:06 -07008185 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008186 close(i);
Steve Dower8fc89802015-04-12 00:26:27 -04008187 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008188 Py_END_ALLOW_THREADS
8189 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008190}
8191
8192
Larry Hastings2f936352014-08-05 14:04:04 +10008193/*[clinic input]
8194os.dup -> int
8195
8196 fd: int
8197 /
8198
8199Return a duplicate of a file descriptor.
8200[clinic start generated code]*/
8201
Larry Hastings2f936352014-08-05 14:04:04 +10008202static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008203os_dup_impl(PyObject *module, int fd)
8204/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008205{
8206 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008207}
8208
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008209
Larry Hastings2f936352014-08-05 14:04:04 +10008210/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008211os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008212 fd: int
8213 fd2: int
8214 inheritable: bool=True
8215
8216Duplicate file descriptor.
8217[clinic start generated code]*/
8218
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008219static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008220os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008221/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008222{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008223 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008224#if defined(HAVE_DUP3) && \
8225 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8226 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008227 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008228#endif
8229
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008230 if (fd < 0 || fd2 < 0) {
8231 posix_error();
8232 return -1;
8233 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008234
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008235 /* dup2() can fail with EINTR if the target FD is already open, because it
8236 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8237 * upon close(), and therefore below.
8238 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008239#ifdef MS_WINDOWS
8240 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008241 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008242 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008243 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008244 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008245 if (res < 0) {
8246 posix_error();
8247 return -1;
8248 }
8249 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008250
8251 /* Character files like console cannot be make non-inheritable */
8252 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8253 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008254 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008255 }
8256
8257#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8258 Py_BEGIN_ALLOW_THREADS
8259 if (!inheritable)
8260 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8261 else
8262 res = dup2(fd, fd2);
8263 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008264 if (res < 0) {
8265 posix_error();
8266 return -1;
8267 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008268
8269#else
8270
8271#ifdef HAVE_DUP3
8272 if (!inheritable && dup3_works != 0) {
8273 Py_BEGIN_ALLOW_THREADS
8274 res = dup3(fd, fd2, O_CLOEXEC);
8275 Py_END_ALLOW_THREADS
8276 if (res < 0) {
8277 if (dup3_works == -1)
8278 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008279 if (dup3_works) {
8280 posix_error();
8281 return -1;
8282 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008283 }
8284 }
8285
8286 if (inheritable || dup3_works == 0)
8287 {
8288#endif
8289 Py_BEGIN_ALLOW_THREADS
8290 res = dup2(fd, fd2);
8291 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008292 if (res < 0) {
8293 posix_error();
8294 return -1;
8295 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008296
8297 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8298 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008299 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008300 }
8301#ifdef HAVE_DUP3
8302 }
8303#endif
8304
8305#endif
8306
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008307 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008308}
8309
Larry Hastings2f936352014-08-05 14:04:04 +10008310
Ross Lagerwall7807c352011-03-17 20:20:30 +02008311#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008312/*[clinic input]
8313os.lockf
8314
8315 fd: int
8316 An open file descriptor.
8317 command: int
8318 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8319 length: Py_off_t
8320 The number of bytes to lock, starting at the current position.
8321 /
8322
8323Apply, test or remove a POSIX lock on an open file descriptor.
8324
8325[clinic start generated code]*/
8326
Larry Hastings2f936352014-08-05 14:04:04 +10008327static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008328os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8329/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008330{
8331 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008332
8333 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008334 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008335 Py_END_ALLOW_THREADS
8336
8337 if (res < 0)
8338 return posix_error();
8339
8340 Py_RETURN_NONE;
8341}
Larry Hastings2f936352014-08-05 14:04:04 +10008342#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008343
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008344
Larry Hastings2f936352014-08-05 14:04:04 +10008345/*[clinic input]
8346os.lseek -> Py_off_t
8347
8348 fd: int
8349 position: Py_off_t
8350 how: int
8351 /
8352
8353Set the position of a file descriptor. Return the new position.
8354
8355Return the new cursor position in number of bytes
8356relative to the beginning of the file.
8357[clinic start generated code]*/
8358
Larry Hastings2f936352014-08-05 14:04:04 +10008359static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008360os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8361/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008362{
8363 Py_off_t result;
8364
Guido van Rossum687dd131993-05-17 08:34:16 +00008365#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008366 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8367 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008368 case 0: how = SEEK_SET; break;
8369 case 1: how = SEEK_CUR; break;
8370 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008371 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008372#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008373
Victor Stinner8c62be82010-05-06 00:08:46 +00008374 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008375 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008376#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008377 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008378#else
Larry Hastings2f936352014-08-05 14:04:04 +10008379 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008380#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008381 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008382 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008383 if (result < 0)
8384 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008385
Larry Hastings2f936352014-08-05 14:04:04 +10008386 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008387}
8388
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008389
Larry Hastings2f936352014-08-05 14:04:04 +10008390/*[clinic input]
8391os.read
8392 fd: int
8393 length: Py_ssize_t
8394 /
8395
8396Read from a file descriptor. Returns a bytes object.
8397[clinic start generated code]*/
8398
Larry Hastings2f936352014-08-05 14:04:04 +10008399static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008400os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8401/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008402{
Victor Stinner8c62be82010-05-06 00:08:46 +00008403 Py_ssize_t n;
8404 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008405
8406 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008407 errno = EINVAL;
8408 return posix_error();
8409 }
Larry Hastings2f936352014-08-05 14:04:04 +10008410
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008411 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008412
8413 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008414 if (buffer == NULL)
8415 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008416
Victor Stinner66aab0c2015-03-19 22:53:20 +01008417 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8418 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008419 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008420 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008421 }
Larry Hastings2f936352014-08-05 14:04:04 +10008422
8423 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008424 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008425
Victor Stinner8c62be82010-05-06 00:08:46 +00008426 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008427}
8428
Ross Lagerwall7807c352011-03-17 20:20:30 +02008429#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008430 || defined(__APPLE__))) \
8431 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8432 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8433static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008434iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008435{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008436 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008437
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008438 *iov = PyMem_New(struct iovec, cnt);
8439 if (*iov == NULL) {
8440 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008441 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008442 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008443
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008444 *buf = PyMem_New(Py_buffer, cnt);
8445 if (*buf == NULL) {
8446 PyMem_Del(*iov);
8447 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008448 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008449 }
8450
8451 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008452 PyObject *item = PySequence_GetItem(seq, i);
8453 if (item == NULL)
8454 goto fail;
8455 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8456 Py_DECREF(item);
8457 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008458 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008459 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008460 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008461 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008462 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008463 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008464
8465fail:
8466 PyMem_Del(*iov);
8467 for (j = 0; j < i; j++) {
8468 PyBuffer_Release(&(*buf)[j]);
8469 }
8470 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008471 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008472}
8473
8474static void
8475iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8476{
8477 int i;
8478 PyMem_Del(iov);
8479 for (i = 0; i < cnt; i++) {
8480 PyBuffer_Release(&buf[i]);
8481 }
8482 PyMem_Del(buf);
8483}
8484#endif
8485
Larry Hastings2f936352014-08-05 14:04:04 +10008486
Ross Lagerwall7807c352011-03-17 20:20:30 +02008487#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008488/*[clinic input]
8489os.readv -> Py_ssize_t
8490
8491 fd: int
8492 buffers: object
8493 /
8494
8495Read from a file descriptor fd into an iterable of buffers.
8496
8497The buffers should be mutable buffers accepting bytes.
8498readv will transfer data into each buffer until it is full
8499and then move on to the next buffer in the sequence to hold
8500the rest of the data.
8501
8502readv returns the total number of bytes read,
8503which may be less than the total capacity of all the buffers.
8504[clinic start generated code]*/
8505
Larry Hastings2f936352014-08-05 14:04:04 +10008506static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008507os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8508/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008509{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008510 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008511 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008512 struct iovec *iov;
8513 Py_buffer *buf;
8514
Larry Hastings2f936352014-08-05 14:04:04 +10008515 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008516 PyErr_SetString(PyExc_TypeError,
8517 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008518 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008519 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008520
Larry Hastings2f936352014-08-05 14:04:04 +10008521 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008522 if (cnt < 0)
8523 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008524
8525 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8526 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008527
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008528 do {
8529 Py_BEGIN_ALLOW_THREADS
8530 n = readv(fd, iov, cnt);
8531 Py_END_ALLOW_THREADS
8532 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008533
8534 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008535 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008536 if (!async_err)
8537 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008538 return -1;
8539 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008540
Larry Hastings2f936352014-08-05 14:04:04 +10008541 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008542}
Larry Hastings2f936352014-08-05 14:04:04 +10008543#endif /* HAVE_READV */
8544
Ross Lagerwall7807c352011-03-17 20:20:30 +02008545
8546#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008547/*[clinic input]
8548# TODO length should be size_t! but Python doesn't support parsing size_t yet.
8549os.pread
8550
8551 fd: int
8552 length: int
8553 offset: Py_off_t
8554 /
8555
8556Read a number of bytes from a file descriptor starting at a particular offset.
8557
8558Read length bytes from file descriptor fd, starting at offset bytes from
8559the beginning of the file. The file offset remains unchanged.
8560[clinic start generated code]*/
8561
Larry Hastings2f936352014-08-05 14:04:04 +10008562static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008563os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset)
8564/*[clinic end generated code: output=435b29ee32b54a78 input=084948dcbaa35d4c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008565{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008566 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008567 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008568 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008569
Larry Hastings2f936352014-08-05 14:04:04 +10008570 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008571 errno = EINVAL;
8572 return posix_error();
8573 }
Larry Hastings2f936352014-08-05 14:04:04 +10008574 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008575 if (buffer == NULL)
8576 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008577
8578 do {
8579 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008580 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008581 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008582 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008583 Py_END_ALLOW_THREADS
8584 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8585
Ross Lagerwall7807c352011-03-17 20:20:30 +02008586 if (n < 0) {
8587 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008588 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008589 }
Larry Hastings2f936352014-08-05 14:04:04 +10008590 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008591 _PyBytes_Resize(&buffer, n);
8592 return buffer;
8593}
Larry Hastings2f936352014-08-05 14:04:04 +10008594#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008595
Pablo Galindo4defba32018-01-27 16:16:37 +00008596#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8597/*[clinic input]
8598os.preadv -> Py_ssize_t
8599
8600 fd: int
8601 buffers: object
8602 offset: Py_off_t
8603 flags: int = 0
8604 /
8605
8606Reads from a file descriptor into a number of mutable bytes-like objects.
8607
8608Combines the functionality of readv() and pread(). As readv(), it will
8609transfer data into each buffer until it is full and then move on to the next
8610buffer in the sequence to hold the rest of the data. Its fourth argument,
8611specifies the file offset at which the input operation is to be performed. It
8612will return the total number of bytes read (which can be less than the total
8613capacity of all the objects).
8614
8615The flags argument contains a bitwise OR of zero or more of the following flags:
8616
8617- RWF_HIPRI
8618- RWF_NOWAIT
8619
8620Using non-zero flags requires Linux 4.6 or newer.
8621[clinic start generated code]*/
8622
8623static Py_ssize_t
8624os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
8625 int flags)
8626/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
8627{
8628 Py_ssize_t cnt, n;
8629 int async_err = 0;
8630 struct iovec *iov;
8631 Py_buffer *buf;
8632
8633 if (!PySequence_Check(buffers)) {
8634 PyErr_SetString(PyExc_TypeError,
8635 "preadv2() arg 2 must be a sequence");
8636 return -1;
8637 }
8638
8639 cnt = PySequence_Size(buffers);
8640 if (cnt < 0) {
8641 return -1;
8642 }
8643
8644#ifndef HAVE_PREADV2
8645 if(flags != 0) {
8646 argument_unavailable_error("preadv2", "flags");
8647 return -1;
8648 }
8649#endif
8650
8651 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
8652 return -1;
8653 }
8654#ifdef HAVE_PREADV2
8655 do {
8656 Py_BEGIN_ALLOW_THREADS
8657 _Py_BEGIN_SUPPRESS_IPH
8658 n = preadv2(fd, iov, cnt, offset, flags);
8659 _Py_END_SUPPRESS_IPH
8660 Py_END_ALLOW_THREADS
8661 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8662#else
8663 do {
8664 Py_BEGIN_ALLOW_THREADS
8665 _Py_BEGIN_SUPPRESS_IPH
8666 n = preadv(fd, iov, cnt, offset);
8667 _Py_END_SUPPRESS_IPH
8668 Py_END_ALLOW_THREADS
8669 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8670#endif
8671
8672 iov_cleanup(iov, buf, cnt);
8673 if (n < 0) {
8674 if (!async_err) {
8675 posix_error();
8676 }
8677 return -1;
8678 }
8679
8680 return n;
8681}
8682#endif /* HAVE_PREADV */
8683
Larry Hastings2f936352014-08-05 14:04:04 +10008684
8685/*[clinic input]
8686os.write -> Py_ssize_t
8687
8688 fd: int
8689 data: Py_buffer
8690 /
8691
8692Write a bytes object to a file descriptor.
8693[clinic start generated code]*/
8694
Larry Hastings2f936352014-08-05 14:04:04 +10008695static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008696os_write_impl(PyObject *module, int fd, Py_buffer *data)
8697/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008698{
Victor Stinner66aab0c2015-03-19 22:53:20 +01008699 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008700}
8701
8702#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008703PyDoc_STRVAR(posix_sendfile__doc__,
Martin Panterbf19d162015-09-09 01:01:13 +00008704"sendfile(out, in, offset, count) -> byteswritten\n\
Martin Panter94994132015-09-09 05:29:24 +00008705sendfile(out, in, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008706 -> byteswritten\n\
Martin Panterbf19d162015-09-09 01:01:13 +00008707Copy count bytes from file descriptor in to file descriptor out.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008708
Larry Hastings2f936352014-08-05 14:04:04 +10008709/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008710static PyObject *
8711posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
8712{
8713 int in, out;
8714 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008715 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008716 off_t offset;
8717
8718#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
8719#ifndef __APPLE__
8720 Py_ssize_t len;
8721#endif
8722 PyObject *headers = NULL, *trailers = NULL;
8723 Py_buffer *hbuf, *tbuf;
8724 off_t sbytes;
8725 struct sf_hdtr sf;
8726 int flags = 0;
Martin Panterbf19d162015-09-09 01:01:13 +00008727 /* Beware that "in" clashes with Python's own "in" operator keyword */
Benjamin Petersond8a43b42011-02-26 21:35:16 +00008728 static char *keywords[] = {"out", "in",
8729 "offset", "count",
8730 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008731
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02008732 sf.headers = NULL;
8733 sf.trailers = NULL;
8734
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008735#ifdef __APPLE__
8736 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10008737 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008738#else
8739 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10008740 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008741#endif
8742 &headers, &trailers, &flags))
8743 return NULL;
8744 if (headers != NULL) {
8745 if (!PySequence_Check(headers)) {
8746 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00008747 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008748 return NULL;
8749 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008750 Py_ssize_t i = PySequence_Size(headers);
8751 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008752 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008753 if (i > INT_MAX) {
8754 PyErr_SetString(PyExc_OverflowError,
8755 "sendfile() header is too large");
8756 return NULL;
8757 }
8758 if (i > 0) {
8759 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008760 if (iov_setup(&(sf.headers), &hbuf,
8761 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008762 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008763#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008764 for (i = 0; i < sf.hdr_cnt; i++) {
8765 Py_ssize_t blen = sf.headers[i].iov_len;
8766# define OFF_T_MAX 0x7fffffffffffffff
8767 if (sbytes >= OFF_T_MAX - blen) {
8768 PyErr_SetString(PyExc_OverflowError,
8769 "sendfile() header is too large");
8770 return NULL;
8771 }
8772 sbytes += blen;
8773 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008774#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008775 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008776 }
8777 }
8778 if (trailers != NULL) {
8779 if (!PySequence_Check(trailers)) {
8780 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00008781 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008782 return NULL;
8783 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008784 Py_ssize_t i = PySequence_Size(trailers);
8785 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008786 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008787 if (i > INT_MAX) {
8788 PyErr_SetString(PyExc_OverflowError,
8789 "sendfile() trailer is too large");
8790 return NULL;
8791 }
8792 if (i > 0) {
8793 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008794 if (iov_setup(&(sf.trailers), &tbuf,
8795 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008796 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008797 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008798 }
8799 }
8800
Steve Dower8fc89802015-04-12 00:26:27 -04008801 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008802 do {
8803 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008804#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008805 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008806#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008807 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008808#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008809 Py_END_ALLOW_THREADS
8810 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008811 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008812
8813 if (sf.headers != NULL)
8814 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
8815 if (sf.trailers != NULL)
8816 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
8817
8818 if (ret < 0) {
8819 if ((errno == EAGAIN) || (errno == EBUSY)) {
8820 if (sbytes != 0) {
8821 // some data has been sent
8822 goto done;
8823 }
8824 else {
8825 // no data has been sent; upper application is supposed
8826 // to retry on EAGAIN or EBUSY
8827 return posix_error();
8828 }
8829 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008830 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008831 }
8832 goto done;
8833
8834done:
8835 #if !defined(HAVE_LARGEFILE_SUPPORT)
8836 return Py_BuildValue("l", sbytes);
8837 #else
8838 return Py_BuildValue("L", sbytes);
8839 #endif
8840
8841#else
8842 Py_ssize_t count;
8843 PyObject *offobj;
8844 static char *keywords[] = {"out", "in",
8845 "offset", "count", NULL};
8846 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
8847 keywords, &out, &in, &offobj, &count))
8848 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07008849#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008850 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008851 do {
8852 Py_BEGIN_ALLOW_THREADS
8853 ret = sendfile(out, in, NULL, count);
8854 Py_END_ALLOW_THREADS
8855 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008856 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008857 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02008858 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008859 }
8860#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008861 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00008862 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008863
8864 do {
8865 Py_BEGIN_ALLOW_THREADS
8866 ret = sendfile(out, in, &offset, count);
8867 Py_END_ALLOW_THREADS
8868 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008869 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008870 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008871 return Py_BuildValue("n", ret);
8872#endif
8873}
Larry Hastings2f936352014-08-05 14:04:04 +10008874#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008875
Larry Hastings2f936352014-08-05 14:04:04 +10008876
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02008877#if defined(__APPLE__)
8878/*[clinic input]
8879os._fcopyfile
8880
8881 infd: int
8882 outfd: int
8883 flags: int
8884 /
8885
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07008886Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02008887[clinic start generated code]*/
8888
8889static PyObject *
8890os__fcopyfile_impl(PyObject *module, int infd, int outfd, int flags)
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07008891/*[clinic end generated code: output=8e8885c721ec38e3 input=69e0770e600cb44f]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02008892{
8893 int ret;
8894
8895 Py_BEGIN_ALLOW_THREADS
8896 ret = fcopyfile(infd, outfd, NULL, flags);
8897 Py_END_ALLOW_THREADS
8898 if (ret < 0)
8899 return posix_error();
8900 Py_RETURN_NONE;
8901}
8902#endif
8903
8904
Larry Hastings2f936352014-08-05 14:04:04 +10008905/*[clinic input]
8906os.fstat
8907
8908 fd : int
8909
8910Perform a stat system call on the given file descriptor.
8911
8912Like stat(), but for an open file descriptor.
8913Equivalent to os.stat(fd).
8914[clinic start generated code]*/
8915
Larry Hastings2f936352014-08-05 14:04:04 +10008916static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008917os_fstat_impl(PyObject *module, int fd)
8918/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008919{
Victor Stinner8c62be82010-05-06 00:08:46 +00008920 STRUCT_STAT st;
8921 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008922 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008923
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008924 do {
8925 Py_BEGIN_ALLOW_THREADS
8926 res = FSTAT(fd, &st);
8927 Py_END_ALLOW_THREADS
8928 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00008929 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00008930#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01008931 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00008932#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008933 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00008934#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008935 }
Tim Peters5aa91602002-01-30 05:46:57 +00008936
Victor Stinner4195b5c2012-02-08 23:03:19 +01008937 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00008938}
8939
Larry Hastings2f936352014-08-05 14:04:04 +10008940
8941/*[clinic input]
8942os.isatty -> bool
8943 fd: int
8944 /
8945
8946Return True if the fd is connected to a terminal.
8947
8948Return True if the file descriptor is an open file descriptor
8949connected to the slave end of a terminal.
8950[clinic start generated code]*/
8951
Larry Hastings2f936352014-08-05 14:04:04 +10008952static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008953os_isatty_impl(PyObject *module, int fd)
8954/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008955{
Steve Dower8fc89802015-04-12 00:26:27 -04008956 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04008957 _Py_BEGIN_SUPPRESS_IPH
8958 return_value = isatty(fd);
8959 _Py_END_SUPPRESS_IPH
8960 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10008961}
8962
8963
Guido van Rossuma4916fa1996-05-23 22:58:55 +00008964#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10008965/*[clinic input]
8966os.pipe
8967
8968Create a pipe.
8969
8970Returns a tuple of two file descriptors:
8971 (read_fd, write_fd)
8972[clinic start generated code]*/
8973
Larry Hastings2f936352014-08-05 14:04:04 +10008974static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008975os_pipe_impl(PyObject *module)
8976/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008977{
Victor Stinner8c62be82010-05-06 00:08:46 +00008978 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02008979#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00008980 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008981 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00008982 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008983#else
8984 int res;
8985#endif
8986
8987#ifdef MS_WINDOWS
8988 attr.nLength = sizeof(attr);
8989 attr.lpSecurityDescriptor = NULL;
8990 attr.bInheritHandle = FALSE;
8991
8992 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08008993 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008994 ok = CreatePipe(&read, &write, &attr, 0);
8995 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07008996 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
8997 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02008998 if (fds[0] == -1 || fds[1] == -1) {
8999 CloseHandle(read);
9000 CloseHandle(write);
9001 ok = 0;
9002 }
9003 }
Steve Dowerc3630612016-11-19 18:41:16 -08009004 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009005 Py_END_ALLOW_THREADS
9006
Victor Stinner8c62be82010-05-06 00:08:46 +00009007 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009008 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009009#else
9010
9011#ifdef HAVE_PIPE2
9012 Py_BEGIN_ALLOW_THREADS
9013 res = pipe2(fds, O_CLOEXEC);
9014 Py_END_ALLOW_THREADS
9015
9016 if (res != 0 && errno == ENOSYS)
9017 {
9018#endif
9019 Py_BEGIN_ALLOW_THREADS
9020 res = pipe(fds);
9021 Py_END_ALLOW_THREADS
9022
9023 if (res == 0) {
9024 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9025 close(fds[0]);
9026 close(fds[1]);
9027 return NULL;
9028 }
9029 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9030 close(fds[0]);
9031 close(fds[1]);
9032 return NULL;
9033 }
9034 }
9035#ifdef HAVE_PIPE2
9036 }
9037#endif
9038
9039 if (res != 0)
9040 return PyErr_SetFromErrno(PyExc_OSError);
9041#endif /* !MS_WINDOWS */
9042 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009043}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009044#endif /* HAVE_PIPE */
9045
Larry Hastings2f936352014-08-05 14:04:04 +10009046
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009047#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009048/*[clinic input]
9049os.pipe2
9050
9051 flags: int
9052 /
9053
9054Create a pipe with flags set atomically.
9055
9056Returns a tuple of two file descriptors:
9057 (read_fd, write_fd)
9058
9059flags can be constructed by ORing together one or more of these values:
9060O_NONBLOCK, O_CLOEXEC.
9061[clinic start generated code]*/
9062
Larry Hastings2f936352014-08-05 14:04:04 +10009063static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009064os_pipe2_impl(PyObject *module, int flags)
9065/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009066{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009067 int fds[2];
9068 int res;
9069
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009070 res = pipe2(fds, flags);
9071 if (res != 0)
9072 return posix_error();
9073 return Py_BuildValue("(ii)", fds[0], fds[1]);
9074}
9075#endif /* HAVE_PIPE2 */
9076
Larry Hastings2f936352014-08-05 14:04:04 +10009077
Ross Lagerwall7807c352011-03-17 20:20:30 +02009078#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009079/*[clinic input]
9080os.writev -> Py_ssize_t
9081 fd: int
9082 buffers: object
9083 /
9084
9085Iterate over buffers, and write the contents of each to a file descriptor.
9086
9087Returns the total number of bytes written.
9088buffers must be a sequence of bytes-like objects.
9089[clinic start generated code]*/
9090
Larry Hastings2f936352014-08-05 14:04:04 +10009091static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009092os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9093/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009094{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009095 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009096 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009097 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009098 struct iovec *iov;
9099 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009100
9101 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009102 PyErr_SetString(PyExc_TypeError,
9103 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009104 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009105 }
Larry Hastings2f936352014-08-05 14:04:04 +10009106 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009107 if (cnt < 0)
9108 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009109
Larry Hastings2f936352014-08-05 14:04:04 +10009110 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9111 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009112 }
9113
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009114 do {
9115 Py_BEGIN_ALLOW_THREADS
9116 result = writev(fd, iov, cnt);
9117 Py_END_ALLOW_THREADS
9118 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009119
9120 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009121 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009122 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009123
Georg Brandl306336b2012-06-24 12:55:33 +02009124 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009125}
Larry Hastings2f936352014-08-05 14:04:04 +10009126#endif /* HAVE_WRITEV */
9127
9128
9129#ifdef HAVE_PWRITE
9130/*[clinic input]
9131os.pwrite -> Py_ssize_t
9132
9133 fd: int
9134 buffer: Py_buffer
9135 offset: Py_off_t
9136 /
9137
9138Write bytes to a file descriptor starting at a particular offset.
9139
9140Write buffer to fd, starting at offset bytes from the beginning of
9141the file. Returns the number of bytes writte. Does not change the
9142current file offset.
9143[clinic start generated code]*/
9144
Larry Hastings2f936352014-08-05 14:04:04 +10009145static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009146os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9147/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009148{
9149 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009150 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009151
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009152 do {
9153 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009154 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009155 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009156 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009157 Py_END_ALLOW_THREADS
9158 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009159
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009160 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009161 posix_error();
9162 return size;
9163}
9164#endif /* HAVE_PWRITE */
9165
Pablo Galindo4defba32018-01-27 16:16:37 +00009166#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9167/*[clinic input]
9168os.pwritev -> Py_ssize_t
9169
9170 fd: int
9171 buffers: object
9172 offset: Py_off_t
9173 flags: int = 0
9174 /
9175
9176Writes the contents of bytes-like objects to a file descriptor at a given offset.
9177
9178Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9179of bytes-like objects. Buffers are processed in array order. Entire contents of first
9180buffer is written before proceeding to second, and so on. The operating system may
9181set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9182This function writes the contents of each object to the file descriptor and returns
9183the total number of bytes written.
9184
9185The flags argument contains a bitwise OR of zero or more of the following flags:
9186
9187- RWF_DSYNC
9188- RWF_SYNC
9189
9190Using non-zero flags requires Linux 4.7 or newer.
9191[clinic start generated code]*/
9192
9193static Py_ssize_t
9194os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9195 int flags)
9196/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9197{
9198 Py_ssize_t cnt;
9199 Py_ssize_t result;
9200 int async_err = 0;
9201 struct iovec *iov;
9202 Py_buffer *buf;
9203
9204 if (!PySequence_Check(buffers)) {
9205 PyErr_SetString(PyExc_TypeError,
9206 "pwritev() arg 2 must be a sequence");
9207 return -1;
9208 }
9209
9210 cnt = PySequence_Size(buffers);
9211 if (cnt < 0) {
9212 return -1;
9213 }
9214
9215#ifndef HAVE_PWRITEV2
9216 if(flags != 0) {
9217 argument_unavailable_error("pwritev2", "flags");
9218 return -1;
9219 }
9220#endif
9221
9222 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9223 return -1;
9224 }
9225#ifdef HAVE_PWRITEV2
9226 do {
9227 Py_BEGIN_ALLOW_THREADS
9228 _Py_BEGIN_SUPPRESS_IPH
9229 result = pwritev2(fd, iov, cnt, offset, flags);
9230 _Py_END_SUPPRESS_IPH
9231 Py_END_ALLOW_THREADS
9232 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9233#else
9234 do {
9235 Py_BEGIN_ALLOW_THREADS
9236 _Py_BEGIN_SUPPRESS_IPH
9237 result = pwritev(fd, iov, cnt, offset);
9238 _Py_END_SUPPRESS_IPH
9239 Py_END_ALLOW_THREADS
9240 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9241#endif
9242
9243 iov_cleanup(iov, buf, cnt);
9244 if (result < 0) {
9245 if (!async_err) {
9246 posix_error();
9247 }
9248 return -1;
9249 }
9250
9251 return result;
9252}
9253#endif /* HAVE_PWRITEV */
9254
9255
9256
Larry Hastings2f936352014-08-05 14:04:04 +10009257
9258#ifdef HAVE_MKFIFO
9259/*[clinic input]
9260os.mkfifo
9261
9262 path: path_t
9263 mode: int=0o666
9264 *
9265 dir_fd: dir_fd(requires='mkfifoat')=None
9266
9267Create a "fifo" (a POSIX named pipe).
9268
9269If dir_fd is not None, it should be a file descriptor open to a directory,
9270 and path should be relative; path will then be relative to that directory.
9271dir_fd may not be implemented on your platform.
9272 If it is unavailable, using it will raise a NotImplementedError.
9273[clinic start generated code]*/
9274
Larry Hastings2f936352014-08-05 14:04:04 +10009275static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009276os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9277/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009278{
9279 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009280 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009281
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009282 do {
9283 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009284#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009285 if (dir_fd != DEFAULT_DIR_FD)
9286 result = mkfifoat(dir_fd, path->narrow, mode);
9287 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009288#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009289 result = mkfifo(path->narrow, mode);
9290 Py_END_ALLOW_THREADS
9291 } while (result != 0 && errno == EINTR &&
9292 !(async_err = PyErr_CheckSignals()));
9293 if (result != 0)
9294 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009295
9296 Py_RETURN_NONE;
9297}
9298#endif /* HAVE_MKFIFO */
9299
9300
9301#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9302/*[clinic input]
9303os.mknod
9304
9305 path: path_t
9306 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009307 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009308 *
9309 dir_fd: dir_fd(requires='mknodat')=None
9310
9311Create a node in the file system.
9312
9313Create a node in the file system (file, device special file or named pipe)
9314at path. mode specifies both the permissions to use and the
9315type of node to be created, being combined (bitwise OR) with one of
9316S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9317device defines the newly created device special file (probably using
9318os.makedev()). Otherwise device is ignored.
9319
9320If dir_fd is not None, it should be a file descriptor open to a directory,
9321 and path should be relative; path will then be relative to that directory.
9322dir_fd may not be implemented on your platform.
9323 If it is unavailable, using it will raise a NotImplementedError.
9324[clinic start generated code]*/
9325
Larry Hastings2f936352014-08-05 14:04:04 +10009326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009327os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009328 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009329/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009330{
9331 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009332 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009333
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009334 do {
9335 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009336#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009337 if (dir_fd != DEFAULT_DIR_FD)
9338 result = mknodat(dir_fd, path->narrow, mode, device);
9339 else
Larry Hastings2f936352014-08-05 14:04:04 +10009340#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009341 result = mknod(path->narrow, mode, device);
9342 Py_END_ALLOW_THREADS
9343 } while (result != 0 && errno == EINTR &&
9344 !(async_err = PyErr_CheckSignals()));
9345 if (result != 0)
9346 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009347
9348 Py_RETURN_NONE;
9349}
9350#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9351
9352
9353#ifdef HAVE_DEVICE_MACROS
9354/*[clinic input]
9355os.major -> unsigned_int
9356
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009357 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009358 /
9359
9360Extracts a device major number from a raw device number.
9361[clinic start generated code]*/
9362
Larry Hastings2f936352014-08-05 14:04:04 +10009363static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009364os_major_impl(PyObject *module, dev_t device)
9365/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009366{
9367 return major(device);
9368}
9369
9370
9371/*[clinic input]
9372os.minor -> unsigned_int
9373
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009374 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009375 /
9376
9377Extracts a device minor number from a raw device number.
9378[clinic start generated code]*/
9379
Larry Hastings2f936352014-08-05 14:04:04 +10009380static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009381os_minor_impl(PyObject *module, dev_t device)
9382/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009383{
9384 return minor(device);
9385}
9386
9387
9388/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009389os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009390
9391 major: int
9392 minor: int
9393 /
9394
9395Composes a raw device number from the major and minor device numbers.
9396[clinic start generated code]*/
9397
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009398static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009399os_makedev_impl(PyObject *module, int major, int minor)
9400/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009401{
9402 return makedev(major, minor);
9403}
9404#endif /* HAVE_DEVICE_MACROS */
9405
9406
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009407#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009408/*[clinic input]
9409os.ftruncate
9410
9411 fd: int
9412 length: Py_off_t
9413 /
9414
9415Truncate a file, specified by file descriptor, to a specific length.
9416[clinic start generated code]*/
9417
Larry Hastings2f936352014-08-05 14:04:04 +10009418static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009419os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9420/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009421{
9422 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009423 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009424
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009425 do {
9426 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009427 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009428#ifdef MS_WINDOWS
9429 result = _chsize_s(fd, length);
9430#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009431 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009432#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009433 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009434 Py_END_ALLOW_THREADS
9435 } while (result != 0 && errno == EINTR &&
9436 !(async_err = PyErr_CheckSignals()));
9437 if (result != 0)
9438 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009439 Py_RETURN_NONE;
9440}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009441#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009442
9443
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009444#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009445/*[clinic input]
9446os.truncate
9447 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9448 length: Py_off_t
9449
9450Truncate a file, specified by path, to a specific length.
9451
9452On some platforms, path may also be specified as an open file descriptor.
9453 If this functionality is unavailable, using it raises an exception.
9454[clinic start generated code]*/
9455
Larry Hastings2f936352014-08-05 14:04:04 +10009456static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009457os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9458/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009459{
9460 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009461#ifdef MS_WINDOWS
9462 int fd;
9463#endif
9464
9465 if (path->fd != -1)
9466 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009467
9468 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009469 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009470#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009471 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009472 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009473 result = -1;
9474 else {
9475 result = _chsize_s(fd, length);
9476 close(fd);
9477 if (result < 0)
9478 errno = result;
9479 }
9480#else
9481 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009482#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009483 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009484 Py_END_ALLOW_THREADS
9485 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009486 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009487
9488 Py_RETURN_NONE;
9489}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009490#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009491
Ross Lagerwall7807c352011-03-17 20:20:30 +02009492
Victor Stinnerd6b17692014-09-30 12:20:05 +02009493/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9494 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9495 defined, which is the case in Python on AIX. AIX bug report:
9496 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9497#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9498# define POSIX_FADVISE_AIX_BUG
9499#endif
9500
Victor Stinnerec39e262014-09-30 12:35:58 +02009501
Victor Stinnerd6b17692014-09-30 12:20:05 +02009502#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009503/*[clinic input]
9504os.posix_fallocate
9505
9506 fd: int
9507 offset: Py_off_t
9508 length: Py_off_t
9509 /
9510
9511Ensure a file has allocated at least a particular number of bytes on disk.
9512
9513Ensure that the file specified by fd encompasses a range of bytes
9514starting at offset bytes from the beginning and continuing for length bytes.
9515[clinic start generated code]*/
9516
Larry Hastings2f936352014-08-05 14:04:04 +10009517static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009518os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009519 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009520/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009521{
9522 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009523 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009524
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009525 do {
9526 Py_BEGIN_ALLOW_THREADS
9527 result = posix_fallocate(fd, offset, length);
9528 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009529 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9530
9531 if (result == 0)
9532 Py_RETURN_NONE;
9533
9534 if (async_err)
9535 return NULL;
9536
9537 errno = result;
9538 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009539}
Victor Stinnerec39e262014-09-30 12:35:58 +02009540#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +10009541
Ross Lagerwall7807c352011-03-17 20:20:30 +02009542
Victor Stinnerd6b17692014-09-30 12:20:05 +02009543#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009544/*[clinic input]
9545os.posix_fadvise
9546
9547 fd: int
9548 offset: Py_off_t
9549 length: Py_off_t
9550 advice: int
9551 /
9552
9553Announce an intention to access data in a specific pattern.
9554
9555Announce an intention to access data in a specific pattern, thus allowing
9556the kernel to make optimizations.
9557The advice applies to the region of the file specified by fd starting at
9558offset and continuing for length bytes.
9559advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
9560POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
9561POSIX_FADV_DONTNEED.
9562[clinic start generated code]*/
9563
Larry Hastings2f936352014-08-05 14:04:04 +10009564static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009565os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009566 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009567/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009568{
9569 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009570 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009571
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009572 do {
9573 Py_BEGIN_ALLOW_THREADS
9574 result = posix_fadvise(fd, offset, length, advice);
9575 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009576 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9577
9578 if (result == 0)
9579 Py_RETURN_NONE;
9580
9581 if (async_err)
9582 return NULL;
9583
9584 errno = result;
9585 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009586}
Victor Stinnerec39e262014-09-30 12:35:58 +02009587#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009588
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009589#ifdef HAVE_PUTENV
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009590
Fred Drake762e2061999-08-26 17:23:54 +00009591/* Save putenv() parameters as values here, so we can collect them when they
9592 * get re-set with another call for the same key. */
9593static PyObject *posix_putenv_garbage;
9594
Larry Hastings2f936352014-08-05 14:04:04 +10009595static void
9596posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009597{
Larry Hastings2f936352014-08-05 14:04:04 +10009598 /* Install the first arg and newstr in posix_putenv_garbage;
9599 * this will cause previous value to be collected. This has to
9600 * happen after the real putenv() call because the old value
9601 * was still accessible until then. */
9602 if (PyDict_SetItem(posix_putenv_garbage, name, value))
9603 /* really not much we can do; just leak */
9604 PyErr_Clear();
9605 else
9606 Py_DECREF(value);
9607}
9608
9609
Thomas Hellerf78f12a2007-11-08 19:33:05 +00009610#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009611/*[clinic input]
9612os.putenv
9613
9614 name: unicode
9615 value: unicode
9616 /
9617
9618Change or add an environment variable.
9619[clinic start generated code]*/
9620
Larry Hastings2f936352014-08-05 14:04:04 +10009621static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009622os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9623/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009624{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03009625 const wchar_t *env;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009626 Py_ssize_t size;
Larry Hastings2f936352014-08-05 14:04:04 +10009627
Serhiy Storchaka77703942017-06-25 07:33:01 +03009628 /* Search from index 1 because on Windows starting '=' is allowed for
9629 defining hidden environment variables. */
9630 if (PyUnicode_GET_LENGTH(name) == 0 ||
9631 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
9632 {
9633 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9634 return NULL;
9635 }
Larry Hastings2f936352014-08-05 14:04:04 +10009636 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
9637 if (unicode == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +10009638 return NULL;
Victor Stinner84ae1182010-05-06 22:05:07 +00009639 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009640
9641 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
9642 if (env == NULL)
9643 goto error;
9644 if (size > _MAX_ENV) {
Victor Stinner65170952011-11-22 22:16:17 +01009645 PyErr_Format(PyExc_ValueError,
9646 "the environment variable is longer than %u characters",
9647 _MAX_ENV);
9648 goto error;
9649 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009650 if (wcslen(env) != (size_t)size) {
9651 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnereb5657a2011-09-30 01:44:27 +02009652 goto error;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009653 }
9654
Larry Hastings2f936352014-08-05 14:04:04 +10009655 if (_wputenv(env)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009656 posix_error();
Victor Stinner84ae1182010-05-06 22:05:07 +00009657 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00009658 }
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009659
Larry Hastings2f936352014-08-05 14:04:04 +10009660 posix_putenv_garbage_setitem(name, unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +00009661 Py_RETURN_NONE;
9662
9663error:
Larry Hastings2f936352014-08-05 14:04:04 +10009664 Py_DECREF(unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +00009665 return NULL;
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009666}
Larry Hastings2f936352014-08-05 14:04:04 +10009667#else /* MS_WINDOWS */
9668/*[clinic input]
9669os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +00009670
Larry Hastings2f936352014-08-05 14:04:04 +10009671 name: FSConverter
9672 value: FSConverter
9673 /
9674
9675Change or add an environment variable.
9676[clinic start generated code]*/
9677
Larry Hastings2f936352014-08-05 14:04:04 +10009678static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009679os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9680/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009681{
9682 PyObject *bytes = NULL;
9683 char *env;
Serhiy Storchaka77703942017-06-25 07:33:01 +03009684 const char *name_string = PyBytes_AS_STRING(name);
9685 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +10009686
Serhiy Storchaka77703942017-06-25 07:33:01 +03009687 if (strchr(name_string, '=') != NULL) {
9688 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9689 return NULL;
9690 }
Larry Hastings2f936352014-08-05 14:04:04 +10009691 bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
9692 if (bytes == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +10009693 return NULL;
9694 }
9695
9696 env = PyBytes_AS_STRING(bytes);
9697 if (putenv(env)) {
9698 Py_DECREF(bytes);
9699 return posix_error();
9700 }
9701
9702 posix_putenv_garbage_setitem(name, bytes);
9703 Py_RETURN_NONE;
9704}
9705#endif /* MS_WINDOWS */
9706#endif /* HAVE_PUTENV */
9707
9708
9709#ifdef HAVE_UNSETENV
9710/*[clinic input]
9711os.unsetenv
9712 name: FSConverter
9713 /
9714
9715Delete an environment variable.
9716[clinic start generated code]*/
9717
Larry Hastings2f936352014-08-05 14:04:04 +10009718static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009719os_unsetenv_impl(PyObject *module, PyObject *name)
9720/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009721{
Victor Stinner984890f2011-11-24 13:53:38 +01009722#ifndef HAVE_BROKEN_UNSETENV
Victor Stinner60b385e2011-11-22 22:01:28 +01009723 int err;
Victor Stinner984890f2011-11-24 13:53:38 +01009724#endif
Victor Stinner84ae1182010-05-06 22:05:07 +00009725
Victor Stinner984890f2011-11-24 13:53:38 +01009726#ifdef HAVE_BROKEN_UNSETENV
9727 unsetenv(PyBytes_AS_STRING(name));
9728#else
Victor Stinner65170952011-11-22 22:16:17 +01009729 err = unsetenv(PyBytes_AS_STRING(name));
Larry Hastings2f936352014-08-05 14:04:04 +10009730 if (err)
Victor Stinner60b385e2011-11-22 22:01:28 +01009731 return posix_error();
Victor Stinner984890f2011-11-24 13:53:38 +01009732#endif
Guido van Rossumc524d952001-10-19 01:31:59 +00009733
Victor Stinner8c62be82010-05-06 00:08:46 +00009734 /* Remove the key from posix_putenv_garbage;
9735 * this will cause it to be collected. This has to
9736 * happen after the real unsetenv() call because the
9737 * old value was still accessible until then.
9738 */
Victor Stinner65170952011-11-22 22:16:17 +01009739 if (PyDict_DelItem(posix_putenv_garbage, name)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009740 /* really not much we can do; just leak */
9741 PyErr_Clear();
9742 }
Victor Stinner84ae1182010-05-06 22:05:07 +00009743 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +00009744}
Larry Hastings2f936352014-08-05 14:04:04 +10009745#endif /* HAVE_UNSETENV */
Guido van Rossumc524d952001-10-19 01:31:59 +00009746
Larry Hastings2f936352014-08-05 14:04:04 +10009747
9748/*[clinic input]
9749os.strerror
9750
9751 code: int
9752 /
9753
9754Translate an error code to a message string.
9755[clinic start generated code]*/
9756
Larry Hastings2f936352014-08-05 14:04:04 +10009757static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009758os_strerror_impl(PyObject *module, int code)
9759/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009760{
9761 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +00009762 if (message == NULL) {
9763 PyErr_SetString(PyExc_ValueError,
9764 "strerror() argument out of range");
9765 return NULL;
9766 }
Victor Stinner1b579672011-12-17 05:47:23 +01009767 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +00009768}
Guido van Rossumb6a47161997-09-15 22:54:34 +00009769
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009770
Guido van Rossumc9641791998-08-04 15:26:23 +00009771#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +00009772#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +10009773/*[clinic input]
9774os.WCOREDUMP -> bool
9775
9776 status: int
9777 /
9778
9779Return True if the process returning status was dumped to a core file.
9780[clinic start generated code]*/
9781
Larry Hastings2f936352014-08-05 14:04:04 +10009782static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009783os_WCOREDUMP_impl(PyObject *module, int status)
9784/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009785{
9786 WAIT_TYPE wait_status;
9787 WAIT_STATUS_INT(wait_status) = status;
9788 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +00009789}
9790#endif /* WCOREDUMP */
9791
Larry Hastings2f936352014-08-05 14:04:04 +10009792
Fred Drake106c1a02002-04-23 15:58:02 +00009793#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +10009794/*[clinic input]
9795os.WIFCONTINUED -> bool
9796
9797 status: int
9798
9799Return True if a particular process was continued from a job control stop.
9800
9801Return True if the process returning status was continued from a
9802job control stop.
9803[clinic start generated code]*/
9804
Larry Hastings2f936352014-08-05 14:04:04 +10009805static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009806os_WIFCONTINUED_impl(PyObject *module, int status)
9807/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009808{
9809 WAIT_TYPE wait_status;
9810 WAIT_STATUS_INT(wait_status) = status;
9811 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +00009812}
9813#endif /* WIFCONTINUED */
9814
Larry Hastings2f936352014-08-05 14:04:04 +10009815
Guido van Rossumc9641791998-08-04 15:26:23 +00009816#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +10009817/*[clinic input]
9818os.WIFSTOPPED -> bool
9819
9820 status: int
9821
9822Return True if the process returning status was stopped.
9823[clinic start generated code]*/
9824
Larry Hastings2f936352014-08-05 14:04:04 +10009825static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009826os_WIFSTOPPED_impl(PyObject *module, int status)
9827/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009828{
9829 WAIT_TYPE wait_status;
9830 WAIT_STATUS_INT(wait_status) = status;
9831 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +00009832}
9833#endif /* WIFSTOPPED */
9834
Larry Hastings2f936352014-08-05 14:04:04 +10009835
Guido van Rossumc9641791998-08-04 15:26:23 +00009836#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +10009837/*[clinic input]
9838os.WIFSIGNALED -> bool
9839
9840 status: int
9841
9842Return True if the process returning status was terminated by a signal.
9843[clinic start generated code]*/
9844
Larry Hastings2f936352014-08-05 14:04:04 +10009845static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009846os_WIFSIGNALED_impl(PyObject *module, int status)
9847/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009848{
9849 WAIT_TYPE wait_status;
9850 WAIT_STATUS_INT(wait_status) = status;
9851 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +00009852}
9853#endif /* WIFSIGNALED */
9854
Larry Hastings2f936352014-08-05 14:04:04 +10009855
Guido van Rossumc9641791998-08-04 15:26:23 +00009856#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +10009857/*[clinic input]
9858os.WIFEXITED -> bool
9859
9860 status: int
9861
9862Return True if the process returning status exited via the exit() system call.
9863[clinic start generated code]*/
9864
Larry Hastings2f936352014-08-05 14:04:04 +10009865static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009866os_WIFEXITED_impl(PyObject *module, int status)
9867/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009868{
9869 WAIT_TYPE wait_status;
9870 WAIT_STATUS_INT(wait_status) = status;
9871 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +00009872}
9873#endif /* WIFEXITED */
9874
Larry Hastings2f936352014-08-05 14:04:04 +10009875
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00009876#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +10009877/*[clinic input]
9878os.WEXITSTATUS -> int
9879
9880 status: int
9881
9882Return the process return code from status.
9883[clinic start generated code]*/
9884
Larry Hastings2f936352014-08-05 14:04:04 +10009885static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009886os_WEXITSTATUS_impl(PyObject *module, int status)
9887/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009888{
9889 WAIT_TYPE wait_status;
9890 WAIT_STATUS_INT(wait_status) = status;
9891 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +00009892}
9893#endif /* WEXITSTATUS */
9894
Larry Hastings2f936352014-08-05 14:04:04 +10009895
Guido van Rossumc9641791998-08-04 15:26:23 +00009896#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +10009897/*[clinic input]
9898os.WTERMSIG -> int
9899
9900 status: int
9901
9902Return the signal that terminated the process that provided the status value.
9903[clinic start generated code]*/
9904
Larry Hastings2f936352014-08-05 14:04:04 +10009905static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009906os_WTERMSIG_impl(PyObject *module, int status)
9907/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009908{
9909 WAIT_TYPE wait_status;
9910 WAIT_STATUS_INT(wait_status) = status;
9911 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +00009912}
9913#endif /* WTERMSIG */
9914
Larry Hastings2f936352014-08-05 14:04:04 +10009915
Guido van Rossumc9641791998-08-04 15:26:23 +00009916#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +10009917/*[clinic input]
9918os.WSTOPSIG -> int
9919
9920 status: int
9921
9922Return the signal that stopped the process that provided the status value.
9923[clinic start generated code]*/
9924
Larry Hastings2f936352014-08-05 14:04:04 +10009925static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009926os_WSTOPSIG_impl(PyObject *module, int status)
9927/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009928{
9929 WAIT_TYPE wait_status;
9930 WAIT_STATUS_INT(wait_status) = status;
9931 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +00009932}
9933#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +00009934#endif /* HAVE_SYS_WAIT_H */
9935
9936
Thomas Wouters477c8d52006-05-27 19:21:47 +00009937#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +00009938#ifdef _SCO_DS
9939/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
9940 needed definitions in sys/statvfs.h */
9941#define _SVID3
9942#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00009943#include <sys/statvfs.h>
9944
Guido van Rossum98bf58f2001-10-18 20:34:25 +00009945static PyObject*
9946_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondo474eedf2018-11-13 04:09:31 -08009947 PyObject *v = PyStructSequence_New(StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00009948 if (v == NULL)
9949 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00009950
9951#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +00009952 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
9953 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
9954 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
9955 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
9956 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
9957 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
9958 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
9959 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
9960 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
9961 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00009962#else
Victor Stinner8c62be82010-05-06 00:08:46 +00009963 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
9964 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
9965 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -07009966 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +00009967 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -07009968 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +00009969 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -07009970 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +00009971 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -07009972 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +00009973 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -07009974 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +00009975 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -07009976 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +00009977 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
9978 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00009979#endif
Michael Felt502d5512018-01-05 13:01:58 +01009980/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
9981 * (issue #32390). */
9982#if defined(_AIX) && defined(_ALL_SOURCE)
9983 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
9984#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01009985 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +01009986#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +01009987 if (PyErr_Occurred()) {
9988 Py_DECREF(v);
9989 return NULL;
9990 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +00009991
Victor Stinner8c62be82010-05-06 00:08:46 +00009992 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00009993}
9994
Larry Hastings2f936352014-08-05 14:04:04 +10009995
9996/*[clinic input]
9997os.fstatvfs
9998 fd: int
9999 /
10000
10001Perform an fstatvfs system call on the given fd.
10002
10003Equivalent to statvfs(fd).
10004[clinic start generated code]*/
10005
Larry Hastings2f936352014-08-05 14:04:04 +100010006static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010007os_fstatvfs_impl(PyObject *module, int fd)
10008/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010009{
10010 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010011 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010012 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010013
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010014 do {
10015 Py_BEGIN_ALLOW_THREADS
10016 result = fstatvfs(fd, &st);
10017 Py_END_ALLOW_THREADS
10018 } while (result != 0 && errno == EINTR &&
10019 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010020 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010021 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010022
Victor Stinner8c62be82010-05-06 00:08:46 +000010023 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010024}
Larry Hastings2f936352014-08-05 14:04:04 +100010025#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010026
10027
Thomas Wouters477c8d52006-05-27 19:21:47 +000010028#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010029#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010030/*[clinic input]
10031os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010032
Larry Hastings2f936352014-08-05 14:04:04 +100010033 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10034
10035Perform a statvfs system call on the given path.
10036
10037path may always be specified as a string.
10038On some platforms, path may also be specified as an open file descriptor.
10039 If this functionality is unavailable, using it raises an exception.
10040[clinic start generated code]*/
10041
Larry Hastings2f936352014-08-05 14:04:04 +100010042static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010043os_statvfs_impl(PyObject *module, path_t *path)
10044/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010045{
10046 int result;
10047 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010048
10049 Py_BEGIN_ALLOW_THREADS
10050#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010051 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010052#ifdef __APPLE__
10053 /* handle weak-linking on Mac OS X 10.3 */
10054 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010055 fd_specified("statvfs", path->fd);
10056 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010057 }
10058#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010059 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010060 }
10061 else
10062#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010063 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010064 Py_END_ALLOW_THREADS
10065
10066 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010067 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010068 }
10069
Larry Hastings2f936352014-08-05 14:04:04 +100010070 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010071}
Larry Hastings2f936352014-08-05 14:04:04 +100010072#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10073
Guido van Rossum94f6f721999-01-06 18:42:14 +000010074
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010075#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010076/*[clinic input]
10077os._getdiskusage
10078
Steve Dower23ad6d02018-02-22 10:39:10 -080010079 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010080
10081Return disk usage statistics about the given path as a (total, free) tuple.
10082[clinic start generated code]*/
10083
Larry Hastings2f936352014-08-05 14:04:04 +100010084static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010085os__getdiskusage_impl(PyObject *module, path_t *path)
10086/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010087{
10088 BOOL retval;
10089 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010090 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010091
10092 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010093 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010094 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010095 if (retval == 0) {
10096 if (GetLastError() == ERROR_DIRECTORY) {
10097 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010098
Joe Pamerc8c02492018-09-25 10:57:36 -040010099 dir_path = PyMem_New(wchar_t, path->length + 1);
10100 if (dir_path == NULL) {
10101 return PyErr_NoMemory();
10102 }
10103
10104 wcscpy_s(dir_path, path->length + 1, path->wide);
10105
10106 if (_dirnameW(dir_path) != -1) {
10107 Py_BEGIN_ALLOW_THREADS
10108 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10109 Py_END_ALLOW_THREADS
10110 }
10111 /* Record the last error in case it's modified by PyMem_Free. */
10112 err = GetLastError();
10113 PyMem_Free(dir_path);
10114 if (retval) {
10115 goto success;
10116 }
10117 }
10118 return PyErr_SetFromWindowsErr(err);
10119 }
10120
10121success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010122 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10123}
Larry Hastings2f936352014-08-05 14:04:04 +100010124#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010125
10126
Fred Drakec9680921999-12-13 16:37:25 +000010127/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10128 * It maps strings representing configuration variable names to
10129 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010130 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010131 * rarely-used constants. There are three separate tables that use
10132 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010133 *
10134 * This code is always included, even if none of the interfaces that
10135 * need it are included. The #if hackery needed to avoid it would be
10136 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010137 */
10138struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010139 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010140 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010141};
10142
Fred Drake12c6e2d1999-12-14 21:25:03 +000010143static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010144conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010145 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010146{
Christian Heimes217cfd12007-12-02 14:31:20 +000010147 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010148 int value = _PyLong_AsInt(arg);
10149 if (value == -1 && PyErr_Occurred())
10150 return 0;
10151 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010152 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010153 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010154 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010155 /* look up the value in the table using a binary search */
10156 size_t lo = 0;
10157 size_t mid;
10158 size_t hi = tablesize;
10159 int cmp;
10160 const char *confname;
10161 if (!PyUnicode_Check(arg)) {
10162 PyErr_SetString(PyExc_TypeError,
10163 "configuration names must be strings or integers");
10164 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010165 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010166 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010167 if (confname == NULL)
10168 return 0;
10169 while (lo < hi) {
10170 mid = (lo + hi) / 2;
10171 cmp = strcmp(confname, table[mid].name);
10172 if (cmp < 0)
10173 hi = mid;
10174 else if (cmp > 0)
10175 lo = mid + 1;
10176 else {
10177 *valuep = table[mid].value;
10178 return 1;
10179 }
10180 }
10181 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10182 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010183 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010184}
10185
10186
10187#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10188static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010189#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010190 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010191#endif
10192#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010193 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010194#endif
Fred Drakec9680921999-12-13 16:37:25 +000010195#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010196 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010197#endif
10198#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010199 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010200#endif
10201#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010202 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010203#endif
10204#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010205 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010206#endif
10207#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010208 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010209#endif
10210#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010211 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010212#endif
10213#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010214 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010215#endif
10216#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010217 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010218#endif
10219#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010220 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010221#endif
10222#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010223 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010224#endif
10225#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010226 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010227#endif
10228#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010229 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010230#endif
10231#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010232 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010233#endif
10234#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010235 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010236#endif
10237#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010238 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010239#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010240#ifdef _PC_ACL_ENABLED
10241 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10242#endif
10243#ifdef _PC_MIN_HOLE_SIZE
10244 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10245#endif
10246#ifdef _PC_ALLOC_SIZE_MIN
10247 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10248#endif
10249#ifdef _PC_REC_INCR_XFER_SIZE
10250 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10251#endif
10252#ifdef _PC_REC_MAX_XFER_SIZE
10253 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10254#endif
10255#ifdef _PC_REC_MIN_XFER_SIZE
10256 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10257#endif
10258#ifdef _PC_REC_XFER_ALIGN
10259 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10260#endif
10261#ifdef _PC_SYMLINK_MAX
10262 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10263#endif
10264#ifdef _PC_XATTR_ENABLED
10265 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10266#endif
10267#ifdef _PC_XATTR_EXISTS
10268 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10269#endif
10270#ifdef _PC_TIMESTAMP_RESOLUTION
10271 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10272#endif
Fred Drakec9680921999-12-13 16:37:25 +000010273};
10274
Fred Drakec9680921999-12-13 16:37:25 +000010275static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010276conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010277{
10278 return conv_confname(arg, valuep, posix_constants_pathconf,
10279 sizeof(posix_constants_pathconf)
10280 / sizeof(struct constdef));
10281}
10282#endif
10283
Larry Hastings2f936352014-08-05 14:04:04 +100010284
Fred Drakec9680921999-12-13 16:37:25 +000010285#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010286/*[clinic input]
10287os.fpathconf -> long
10288
10289 fd: int
10290 name: path_confname
10291 /
10292
10293Return the configuration limit name for the file descriptor fd.
10294
10295If there is no limit, return -1.
10296[clinic start generated code]*/
10297
Larry Hastings2f936352014-08-05 14:04:04 +100010298static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010299os_fpathconf_impl(PyObject *module, int fd, int name)
10300/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010301{
10302 long limit;
10303
10304 errno = 0;
10305 limit = fpathconf(fd, name);
10306 if (limit == -1 && errno != 0)
10307 posix_error();
10308
10309 return limit;
10310}
10311#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010312
10313
10314#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010315/*[clinic input]
10316os.pathconf -> long
10317 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10318 name: path_confname
10319
10320Return the configuration limit name for the file or directory path.
10321
10322If there is no limit, return -1.
10323On some platforms, path may also be specified as an open file descriptor.
10324 If this functionality is unavailable, using it raises an exception.
10325[clinic start generated code]*/
10326
Larry Hastings2f936352014-08-05 14:04:04 +100010327static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010328os_pathconf_impl(PyObject *module, path_t *path, int name)
10329/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010330{
Victor Stinner8c62be82010-05-06 00:08:46 +000010331 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010332
Victor Stinner8c62be82010-05-06 00:08:46 +000010333 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010334#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010335 if (path->fd != -1)
10336 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010337 else
10338#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010339 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010340 if (limit == -1 && errno != 0) {
10341 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010342 /* could be a path or name problem */
10343 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010344 else
Larry Hastings2f936352014-08-05 14:04:04 +100010345 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010346 }
Larry Hastings2f936352014-08-05 14:04:04 +100010347
10348 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010349}
Larry Hastings2f936352014-08-05 14:04:04 +100010350#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010351
10352#ifdef HAVE_CONFSTR
10353static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010354#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010355 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010356#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010357#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010358 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010359#endif
10360#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010361 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010362#endif
Fred Draked86ed291999-12-15 15:34:33 +000010363#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010364 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010365#endif
10366#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010367 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010368#endif
10369#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010370 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010371#endif
10372#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010373 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010374#endif
Fred Drakec9680921999-12-13 16:37:25 +000010375#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010376 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010377#endif
10378#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010379 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010380#endif
10381#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010382 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010383#endif
10384#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010385 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010386#endif
10387#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010388 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010389#endif
10390#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010391 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010392#endif
10393#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010394 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010395#endif
10396#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010397 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010398#endif
Fred Draked86ed291999-12-15 15:34:33 +000010399#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010400 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010401#endif
Fred Drakec9680921999-12-13 16:37:25 +000010402#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010403 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010404#endif
Fred Draked86ed291999-12-15 15:34:33 +000010405#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010406 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010407#endif
10408#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010409 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010410#endif
10411#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010412 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010413#endif
10414#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010415 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010416#endif
Fred Drakec9680921999-12-13 16:37:25 +000010417#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010418 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010419#endif
10420#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010421 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010422#endif
10423#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010424 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010425#endif
10426#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010427 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010428#endif
10429#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010430 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010431#endif
10432#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010433 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010434#endif
10435#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010436 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010437#endif
10438#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010439 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010440#endif
10441#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010442 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010443#endif
10444#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010445 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010446#endif
10447#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010448 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010449#endif
10450#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010451 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010452#endif
10453#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010454 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010455#endif
10456#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010457 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010458#endif
10459#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010460 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010461#endif
10462#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010463 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010464#endif
Fred Draked86ed291999-12-15 15:34:33 +000010465#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010466 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010467#endif
10468#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010469 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010470#endif
10471#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010472 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010473#endif
10474#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010475 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010476#endif
10477#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010478 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010479#endif
10480#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010481 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010482#endif
10483#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010484 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010485#endif
10486#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010487 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010488#endif
10489#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010490 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010491#endif
10492#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010493 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010494#endif
10495#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010496 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010497#endif
10498#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010499 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010500#endif
10501#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010502 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010503#endif
Fred Drakec9680921999-12-13 16:37:25 +000010504};
10505
10506static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010507conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010508{
10509 return conv_confname(arg, valuep, posix_constants_confstr,
10510 sizeof(posix_constants_confstr)
10511 / sizeof(struct constdef));
10512}
10513
Larry Hastings2f936352014-08-05 14:04:04 +100010514
10515/*[clinic input]
10516os.confstr
10517
10518 name: confstr_confname
10519 /
10520
10521Return a string-valued system configuration variable.
10522[clinic start generated code]*/
10523
Larry Hastings2f936352014-08-05 14:04:04 +100010524static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010525os_confstr_impl(PyObject *module, int name)
10526/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000010527{
10528 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000010529 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010530 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000010531
Victor Stinnercb043522010-09-10 23:49:04 +000010532 errno = 0;
10533 len = confstr(name, buffer, sizeof(buffer));
10534 if (len == 0) {
10535 if (errno) {
10536 posix_error();
10537 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000010538 }
10539 else {
Victor Stinnercb043522010-09-10 23:49:04 +000010540 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000010541 }
10542 }
Victor Stinnercb043522010-09-10 23:49:04 +000010543
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010544 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010010545 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000010546 char *buf = PyMem_Malloc(len);
10547 if (buf == NULL)
10548 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010010549 len2 = confstr(name, buf, len);
10550 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020010551 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000010552 PyMem_Free(buf);
10553 }
10554 else
10555 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000010556 return result;
10557}
Larry Hastings2f936352014-08-05 14:04:04 +100010558#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000010559
10560
10561#ifdef HAVE_SYSCONF
10562static struct constdef posix_constants_sysconf[] = {
10563#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000010564 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000010565#endif
10566#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000010567 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000010568#endif
10569#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010570 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010571#endif
10572#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010573 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000010574#endif
10575#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010576 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010577#endif
10578#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000010579 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000010580#endif
10581#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000010582 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000010583#endif
10584#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010585 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010586#endif
10587#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000010588 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000010589#endif
10590#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010591 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000010592#endif
Fred Draked86ed291999-12-15 15:34:33 +000010593#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010594 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010595#endif
10596#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000010597 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000010598#endif
Fred Drakec9680921999-12-13 16:37:25 +000010599#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010600 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010601#endif
Fred Drakec9680921999-12-13 16:37:25 +000010602#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010603 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010604#endif
10605#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010606 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010607#endif
10608#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010609 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010610#endif
10611#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010612 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010613#endif
10614#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010615 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010616#endif
Fred Draked86ed291999-12-15 15:34:33 +000010617#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010618 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000010619#endif
Fred Drakec9680921999-12-13 16:37:25 +000010620#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000010621 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000010622#endif
10623#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010624 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010625#endif
10626#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010627 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010628#endif
10629#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010630 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010631#endif
10632#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010633 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010634#endif
Fred Draked86ed291999-12-15 15:34:33 +000010635#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000010636 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000010637#endif
Fred Drakec9680921999-12-13 16:37:25 +000010638#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010639 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010640#endif
10641#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010642 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000010643#endif
10644#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010645 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010646#endif
10647#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010648 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010649#endif
10650#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010651 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010652#endif
10653#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000010654 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000010655#endif
10656#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010657 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010658#endif
10659#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010660 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010661#endif
10662#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000010663 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000010664#endif
10665#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010666 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010667#endif
10668#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010669 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000010670#endif
10671#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010672 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000010673#endif
10674#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010675 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010676#endif
10677#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010678 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010679#endif
10680#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010681 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010682#endif
10683#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010684 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010685#endif
10686#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010687 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000010688#endif
10689#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010690 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010691#endif
10692#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010693 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010694#endif
10695#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000010696 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000010697#endif
10698#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010699 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010700#endif
10701#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010702 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000010703#endif
10704#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010705 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000010706#endif
Fred Draked86ed291999-12-15 15:34:33 +000010707#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000010708 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000010709#endif
Fred Drakec9680921999-12-13 16:37:25 +000010710#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010711 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010712#endif
10713#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010714 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010715#endif
10716#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010717 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010718#endif
Fred Draked86ed291999-12-15 15:34:33 +000010719#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000010720 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000010721#endif
Fred Drakec9680921999-12-13 16:37:25 +000010722#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000010723 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000010724#endif
Fred Draked86ed291999-12-15 15:34:33 +000010725#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000010726 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000010727#endif
10728#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000010729 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000010730#endif
Fred Drakec9680921999-12-13 16:37:25 +000010731#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010732 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010733#endif
10734#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010735 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010736#endif
10737#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010738 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010739#endif
10740#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010741 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000010742#endif
Fred Draked86ed291999-12-15 15:34:33 +000010743#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000010744 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000010745#endif
Fred Drakec9680921999-12-13 16:37:25 +000010746#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000010747 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000010748#endif
10749#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000010750 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000010751#endif
10752#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010753 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010754#endif
10755#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000010756 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000010757#endif
10758#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000010759 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000010760#endif
10761#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000010762 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000010763#endif
10764#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000010765 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000010766#endif
Fred Draked86ed291999-12-15 15:34:33 +000010767#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000010768 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000010769#endif
Fred Drakec9680921999-12-13 16:37:25 +000010770#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010771 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010772#endif
10773#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010774 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010775#endif
Fred Draked86ed291999-12-15 15:34:33 +000010776#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010777 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010778#endif
Fred Drakec9680921999-12-13 16:37:25 +000010779#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010780 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010781#endif
10782#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010783 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000010784#endif
10785#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010786 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000010787#endif
10788#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010789 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000010790#endif
10791#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010792 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000010793#endif
10794#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010795 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000010796#endif
10797#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010798 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000010799#endif
10800#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000010801 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000010802#endif
10803#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000010804 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000010805#endif
Fred Draked86ed291999-12-15 15:34:33 +000010806#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000010807 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000010808#endif
10809#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000010810 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000010811#endif
Fred Drakec9680921999-12-13 16:37:25 +000010812#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000010813 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000010814#endif
10815#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010816 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010817#endif
10818#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000010819 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000010820#endif
10821#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000010822 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000010823#endif
10824#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010825 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010826#endif
10827#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000010828 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000010829#endif
10830#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000010831 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000010832#endif
10833#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000010834 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000010835#endif
10836#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000010837 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000010838#endif
10839#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000010840 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000010841#endif
10842#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000010843 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000010844#endif
10845#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000010846 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000010847#endif
10848#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000010849 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000010850#endif
10851#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000010852 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000010853#endif
10854#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000010855 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000010856#endif
10857#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000010858 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000010859#endif
10860#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000010861 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000010862#endif
10863#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010864 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010865#endif
10866#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000010867 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000010868#endif
10869#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000010870 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000010871#endif
10872#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010873 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010874#endif
10875#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010876 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010877#endif
10878#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000010879 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000010880#endif
10881#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010882 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010883#endif
10884#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010885 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010886#endif
10887#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000010888 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000010889#endif
10890#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000010891 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000010892#endif
10893#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010894 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010895#endif
10896#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010897 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010898#endif
10899#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000010900 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000010901#endif
10902#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010903 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010904#endif
10905#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010906 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010907#endif
10908#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010909 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010910#endif
10911#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010912 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010913#endif
10914#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010915 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010916#endif
Fred Draked86ed291999-12-15 15:34:33 +000010917#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000010918 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000010919#endif
Fred Drakec9680921999-12-13 16:37:25 +000010920#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000010921 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000010922#endif
10923#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010924 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010925#endif
10926#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000010927 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000010928#endif
10929#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010930 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010931#endif
10932#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010933 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010934#endif
10935#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000010936 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000010937#endif
10938#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000010939 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000010940#endif
10941#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000010942 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000010943#endif
10944#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000010945 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000010946#endif
10947#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010948 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010949#endif
10950#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000010951 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000010952#endif
10953#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010954 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000010955#endif
10956#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000010957 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000010958#endif
10959#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000010960 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000010961#endif
10962#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000010963 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000010964#endif
10965#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010966 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010967#endif
10968#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010969 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010970#endif
10971#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000010972 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000010973#endif
10974#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010975 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010976#endif
10977#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010978 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010979#endif
10980#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010981 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010982#endif
10983#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010984 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010985#endif
10986#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010987 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010988#endif
10989#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010990 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010991#endif
10992#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000010993 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000010994#endif
10995#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010996 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010997#endif
10998#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010999 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011000#endif
11001#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011002 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011003#endif
11004#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011005 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011006#endif
11007#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011008 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011009#endif
11010#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011011 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011012#endif
11013#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011014 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011015#endif
11016#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011017 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011018#endif
11019#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011020 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011021#endif
11022#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011023 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011024#endif
11025#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011026 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011027#endif
11028#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011029 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011030#endif
11031#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011032 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011033#endif
11034#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011035 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011036#endif
11037#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011038 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011039#endif
11040#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011041 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011042#endif
11043#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011044 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011045#endif
11046#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011047 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011048#endif
11049#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011050 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011051#endif
11052#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011053 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011054#endif
11055};
11056
11057static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011058conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011059{
11060 return conv_confname(arg, valuep, posix_constants_sysconf,
11061 sizeof(posix_constants_sysconf)
11062 / sizeof(struct constdef));
11063}
11064
Larry Hastings2f936352014-08-05 14:04:04 +100011065
11066/*[clinic input]
11067os.sysconf -> long
11068 name: sysconf_confname
11069 /
11070
11071Return an integer-valued system configuration variable.
11072[clinic start generated code]*/
11073
Larry Hastings2f936352014-08-05 14:04:04 +100011074static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011075os_sysconf_impl(PyObject *module, int name)
11076/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011077{
11078 long value;
11079
11080 errno = 0;
11081 value = sysconf(name);
11082 if (value == -1 && errno != 0)
11083 posix_error();
11084 return value;
11085}
11086#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011087
11088
Fred Drakebec628d1999-12-15 18:31:10 +000011089/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011090 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011091 * the exported dictionaries that are used to publish information about the
11092 * names available on the host platform.
11093 *
11094 * Sorting the table at runtime ensures that the table is properly ordered
11095 * when used, even for platforms we're not able to test on. It also makes
11096 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011097 */
Fred Drakebec628d1999-12-15 18:31:10 +000011098
11099static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011100cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011101{
11102 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011103 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011104 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011105 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011106
11107 return strcmp(c1->name, c2->name);
11108}
11109
11110static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011111setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011112 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011113{
Fred Drakebec628d1999-12-15 18:31:10 +000011114 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011115 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011116
11117 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11118 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011119 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011120 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011121
Barry Warsaw3155db32000-04-13 15:20:40 +000011122 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011123 PyObject *o = PyLong_FromLong(table[i].value);
11124 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11125 Py_XDECREF(o);
11126 Py_DECREF(d);
11127 return -1;
11128 }
11129 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011130 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011131 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011132}
11133
Fred Drakebec628d1999-12-15 18:31:10 +000011134/* Return -1 on failure, 0 on success. */
11135static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011136setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011137{
11138#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011139 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011140 sizeof(posix_constants_pathconf)
11141 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011142 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011143 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011144#endif
11145#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011146 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011147 sizeof(posix_constants_confstr)
11148 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011149 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011150 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011151#endif
11152#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011153 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011154 sizeof(posix_constants_sysconf)
11155 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011156 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011157 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011158#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011159 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011160}
Fred Draked86ed291999-12-15 15:34:33 +000011161
11162
Larry Hastings2f936352014-08-05 14:04:04 +100011163/*[clinic input]
11164os.abort
11165
11166Abort the interpreter immediately.
11167
11168This function 'dumps core' or otherwise fails in the hardest way possible
11169on the hosting operating system. This function never returns.
11170[clinic start generated code]*/
11171
Larry Hastings2f936352014-08-05 14:04:04 +100011172static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011173os_abort_impl(PyObject *module)
11174/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011175{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011176 abort();
11177 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011178#ifndef __clang__
11179 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11180 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11181 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011182 Py_FatalError("abort() called from Python code didn't abort!");
11183 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011184#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011185}
Fred Drakebec628d1999-12-15 18:31:10 +000011186
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011187#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011188/* Grab ShellExecute dynamically from shell32 */
11189static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011190static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11191 LPCWSTR, INT);
11192static int
11193check_ShellExecute()
11194{
11195 HINSTANCE hShell32;
11196
11197 /* only recheck */
11198 if (-1 == has_ShellExecute) {
11199 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011200 /* Security note: this call is not vulnerable to "DLL hijacking".
11201 SHELL32 is part of "KnownDLLs" and so Windows always load
11202 the system SHELL32.DLL, even if there is another SHELL32.DLL
11203 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011204 hShell32 = LoadLibraryW(L"SHELL32");
11205 Py_END_ALLOW_THREADS
11206 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011207 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11208 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011209 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011210 } else {
11211 has_ShellExecute = 0;
11212 }
11213 }
11214 return has_ShellExecute;
11215}
11216
11217
Steve Dowercc16be82016-09-08 10:35:16 -070011218/*[clinic input]
11219os.startfile
11220 filepath: path_t
11221 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011222
Steve Dowercc16be82016-09-08 10:35:16 -070011223startfile(filepath [, operation])
11224
11225Start a file with its associated application.
11226
11227When "operation" is not specified or "open", this acts like
11228double-clicking the file in Explorer, or giving the file name as an
11229argument to the DOS "start" command: the file is opened with whatever
11230application (if any) its extension is associated.
11231When another "operation" is given, it specifies what should be done with
11232the file. A typical operation is "print".
11233
11234startfile returns as soon as the associated application is launched.
11235There is no option to wait for the application to close, and no way
11236to retrieve the application's exit status.
11237
11238The filepath is relative to the current directory. If you want to use
11239an absolute path, make sure the first character is not a slash ("/");
11240the underlying Win32 ShellExecute function doesn't work if it is.
11241[clinic start generated code]*/
11242
11243static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011244os_startfile_impl(PyObject *module, path_t *filepath,
11245 const Py_UNICODE *operation)
11246/*[clinic end generated code: output=66dc311c94d50797 input=63950bf2986380d0]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011247{
11248 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011249
11250 if(!check_ShellExecute()) {
11251 /* If the OS doesn't have ShellExecute, return a
11252 NotImplementedError. */
11253 return PyErr_Format(PyExc_NotImplementedError,
11254 "startfile not available on this platform");
11255 }
11256
Victor Stinner8c62be82010-05-06 00:08:46 +000011257 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011258 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011259 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011260 Py_END_ALLOW_THREADS
11261
Victor Stinner8c62be82010-05-06 00:08:46 +000011262 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011263 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011264 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011265 }
Steve Dowercc16be82016-09-08 10:35:16 -070011266 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011267}
Larry Hastings2f936352014-08-05 14:04:04 +100011268#endif /* MS_WINDOWS */
11269
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011270
Martin v. Löwis438b5342002-12-27 10:16:42 +000011271#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011272/*[clinic input]
11273os.getloadavg
11274
11275Return average recent system load information.
11276
11277Return the number of processes in the system run queue averaged over
11278the last 1, 5, and 15 minutes as a tuple of three floats.
11279Raises OSError if the load average was unobtainable.
11280[clinic start generated code]*/
11281
Larry Hastings2f936352014-08-05 14:04:04 +100011282static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011283os_getloadavg_impl(PyObject *module)
11284/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011285{
11286 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011287 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011288 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11289 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011290 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011291 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011292}
Larry Hastings2f936352014-08-05 14:04:04 +100011293#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011294
Larry Hastings2f936352014-08-05 14:04:04 +100011295
11296/*[clinic input]
11297os.device_encoding
11298 fd: int
11299
11300Return a string describing the encoding of a terminal's file descriptor.
11301
11302The file descriptor must be attached to a terminal.
11303If the device is not a terminal, return None.
11304[clinic start generated code]*/
11305
Larry Hastings2f936352014-08-05 14:04:04 +100011306static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011307os_device_encoding_impl(PyObject *module, int fd)
11308/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011309{
Brett Cannonefb00c02012-02-29 18:31:31 -050011310 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011311}
11312
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011313
Larry Hastings2f936352014-08-05 14:04:04 +100011314#ifdef HAVE_SETRESUID
11315/*[clinic input]
11316os.setresuid
11317
11318 ruid: uid_t
11319 euid: uid_t
11320 suid: uid_t
11321 /
11322
11323Set the current process's real, effective, and saved user ids.
11324[clinic start generated code]*/
11325
Larry Hastings2f936352014-08-05 14:04:04 +100011326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011327os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11328/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011329{
Victor Stinner8c62be82010-05-06 00:08:46 +000011330 if (setresuid(ruid, euid, suid) < 0)
11331 return posix_error();
11332 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011333}
Larry Hastings2f936352014-08-05 14:04:04 +100011334#endif /* HAVE_SETRESUID */
11335
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011336
11337#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011338/*[clinic input]
11339os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011340
Larry Hastings2f936352014-08-05 14:04:04 +100011341 rgid: gid_t
11342 egid: gid_t
11343 sgid: gid_t
11344 /
11345
11346Set the current process's real, effective, and saved group ids.
11347[clinic start generated code]*/
11348
Larry Hastings2f936352014-08-05 14:04:04 +100011349static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011350os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11351/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011352{
Victor Stinner8c62be82010-05-06 00:08:46 +000011353 if (setresgid(rgid, egid, sgid) < 0)
11354 return posix_error();
11355 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011356}
Larry Hastings2f936352014-08-05 14:04:04 +100011357#endif /* HAVE_SETRESGID */
11358
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011359
11360#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011361/*[clinic input]
11362os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011363
Larry Hastings2f936352014-08-05 14:04:04 +100011364Return a tuple of the current process's real, effective, and saved user ids.
11365[clinic start generated code]*/
11366
Larry Hastings2f936352014-08-05 14:04:04 +100011367static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011368os_getresuid_impl(PyObject *module)
11369/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011370{
Victor Stinner8c62be82010-05-06 00:08:46 +000011371 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011372 if (getresuid(&ruid, &euid, &suid) < 0)
11373 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011374 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11375 _PyLong_FromUid(euid),
11376 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011377}
Larry Hastings2f936352014-08-05 14:04:04 +100011378#endif /* HAVE_GETRESUID */
11379
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011380
11381#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011382/*[clinic input]
11383os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011384
Larry Hastings2f936352014-08-05 14:04:04 +100011385Return a tuple of the current process's real, effective, and saved group ids.
11386[clinic start generated code]*/
11387
Larry Hastings2f936352014-08-05 14:04:04 +100011388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011389os_getresgid_impl(PyObject *module)
11390/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011391{
11392 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011393 if (getresgid(&rgid, &egid, &sgid) < 0)
11394 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011395 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11396 _PyLong_FromGid(egid),
11397 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011398}
Larry Hastings2f936352014-08-05 14:04:04 +100011399#endif /* HAVE_GETRESGID */
11400
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011401
Benjamin Peterson9428d532011-09-14 11:45:52 -040011402#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011403/*[clinic input]
11404os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011405
Larry Hastings2f936352014-08-05 14:04:04 +100011406 path: path_t(allow_fd=True)
11407 attribute: path_t
11408 *
11409 follow_symlinks: bool = True
11410
11411Return the value of extended attribute attribute on path.
11412
BNMetricsb9427072018-11-02 15:20:19 +000011413path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011414If follow_symlinks is False, and the last element of the path is a symbolic
11415 link, getxattr will examine the symbolic link itself instead of the file
11416 the link points to.
11417
11418[clinic start generated code]*/
11419
Larry Hastings2f936352014-08-05 14:04:04 +100011420static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011421os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011422 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011423/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011424{
11425 Py_ssize_t i;
11426 PyObject *buffer = NULL;
11427
11428 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11429 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011430
Larry Hastings9cf065c2012-06-22 16:30:09 -070011431 for (i = 0; ; i++) {
11432 void *ptr;
11433 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011434 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011435 Py_ssize_t buffer_size = buffer_sizes[i];
11436 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011437 path_error(path);
11438 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011439 }
11440 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11441 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011442 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011443 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011444
Larry Hastings9cf065c2012-06-22 16:30:09 -070011445 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011446 if (path->fd >= 0)
11447 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011448 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011449 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011450 else
Larry Hastings2f936352014-08-05 14:04:04 +100011451 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011452 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011453
Larry Hastings9cf065c2012-06-22 16:30:09 -070011454 if (result < 0) {
11455 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011456 if (errno == ERANGE)
11457 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011458 path_error(path);
11459 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011460 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011461
Larry Hastings9cf065c2012-06-22 16:30:09 -070011462 if (result != buffer_size) {
11463 /* Can only shrink. */
11464 _PyBytes_Resize(&buffer, result);
11465 }
11466 break;
11467 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011468
Larry Hastings9cf065c2012-06-22 16:30:09 -070011469 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011470}
11471
Larry Hastings2f936352014-08-05 14:04:04 +100011472
11473/*[clinic input]
11474os.setxattr
11475
11476 path: path_t(allow_fd=True)
11477 attribute: path_t
11478 value: Py_buffer
11479 flags: int = 0
11480 *
11481 follow_symlinks: bool = True
11482
11483Set extended attribute attribute on path to value.
11484
BNMetricsb9427072018-11-02 15:20:19 +000011485path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011486If follow_symlinks is False, and the last element of the path is a symbolic
11487 link, setxattr will modify the symbolic link itself instead of the file
11488 the link points to.
11489
11490[clinic start generated code]*/
11491
Benjamin Peterson799bd802011-08-31 22:15:17 -040011492static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011493os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011494 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011495/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011496{
Larry Hastings2f936352014-08-05 14:04:04 +100011497 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011498
Larry Hastings2f936352014-08-05 14:04:04 +100011499 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011500 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011501
Benjamin Peterson799bd802011-08-31 22:15:17 -040011502 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011503 if (path->fd > -1)
11504 result = fsetxattr(path->fd, attribute->narrow,
11505 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011506 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011507 result = setxattr(path->narrow, attribute->narrow,
11508 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011509 else
Larry Hastings2f936352014-08-05 14:04:04 +100011510 result = lsetxattr(path->narrow, attribute->narrow,
11511 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011512 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011513
Larry Hastings9cf065c2012-06-22 16:30:09 -070011514 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100011515 path_error(path);
11516 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011517 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011518
Larry Hastings2f936352014-08-05 14:04:04 +100011519 Py_RETURN_NONE;
11520}
11521
11522
11523/*[clinic input]
11524os.removexattr
11525
11526 path: path_t(allow_fd=True)
11527 attribute: path_t
11528 *
11529 follow_symlinks: bool = True
11530
11531Remove extended attribute attribute on path.
11532
BNMetricsb9427072018-11-02 15:20:19 +000011533path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011534If follow_symlinks is False, and the last element of the path is a symbolic
11535 link, removexattr will modify the symbolic link itself instead of the file
11536 the link points to.
11537
11538[clinic start generated code]*/
11539
Larry Hastings2f936352014-08-05 14:04:04 +100011540static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011541os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011542 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011543/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011544{
11545 ssize_t result;
11546
11547 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
11548 return NULL;
11549
11550 Py_BEGIN_ALLOW_THREADS;
11551 if (path->fd > -1)
11552 result = fremovexattr(path->fd, attribute->narrow);
11553 else if (follow_symlinks)
11554 result = removexattr(path->narrow, attribute->narrow);
11555 else
11556 result = lremovexattr(path->narrow, attribute->narrow);
11557 Py_END_ALLOW_THREADS;
11558
11559 if (result) {
11560 return path_error(path);
11561 }
11562
11563 Py_RETURN_NONE;
11564}
11565
11566
11567/*[clinic input]
11568os.listxattr
11569
11570 path: path_t(allow_fd=True, nullable=True) = None
11571 *
11572 follow_symlinks: bool = True
11573
11574Return a list of extended attributes on path.
11575
BNMetricsb9427072018-11-02 15:20:19 +000011576path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011577if path is None, listxattr will examine the current directory.
11578If follow_symlinks is False, and the last element of the path is a symbolic
11579 link, listxattr will examine the symbolic link itself instead of the file
11580 the link points to.
11581[clinic start generated code]*/
11582
Larry Hastings2f936352014-08-05 14:04:04 +100011583static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011584os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011585/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011586{
Larry Hastings9cf065c2012-06-22 16:30:09 -070011587 Py_ssize_t i;
11588 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100011589 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011590 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011591
Larry Hastings2f936352014-08-05 14:04:04 +100011592 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070011593 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011594
Larry Hastings2f936352014-08-05 14:04:04 +100011595 name = path->narrow ? path->narrow : ".";
11596
Larry Hastings9cf065c2012-06-22 16:30:09 -070011597 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011598 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011599 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011600 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070011601 Py_ssize_t buffer_size = buffer_sizes[i];
11602 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020011603 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100011604 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011605 break;
11606 }
11607 buffer = PyMem_MALLOC(buffer_size);
11608 if (!buffer) {
11609 PyErr_NoMemory();
11610 break;
11611 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011612
Larry Hastings9cf065c2012-06-22 16:30:09 -070011613 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011614 if (path->fd > -1)
11615 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011616 else if (follow_symlinks)
11617 length = listxattr(name, buffer, buffer_size);
11618 else
11619 length = llistxattr(name, buffer, buffer_size);
11620 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011621
Larry Hastings9cf065c2012-06-22 16:30:09 -070011622 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020011623 if (errno == ERANGE) {
11624 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050011625 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011626 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020011627 }
Larry Hastings2f936352014-08-05 14:04:04 +100011628 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011629 break;
11630 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011631
Larry Hastings9cf065c2012-06-22 16:30:09 -070011632 result = PyList_New(0);
11633 if (!result) {
11634 goto exit;
11635 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011636
Larry Hastings9cf065c2012-06-22 16:30:09 -070011637 end = buffer + length;
11638 for (trace = start = buffer; trace != end; trace++) {
11639 if (!*trace) {
11640 int error;
11641 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
11642 trace - start);
11643 if (!attribute) {
11644 Py_DECREF(result);
11645 result = NULL;
11646 goto exit;
11647 }
11648 error = PyList_Append(result, attribute);
11649 Py_DECREF(attribute);
11650 if (error) {
11651 Py_DECREF(result);
11652 result = NULL;
11653 goto exit;
11654 }
11655 start = trace + 1;
11656 }
11657 }
11658 break;
11659 }
11660exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070011661 if (buffer)
11662 PyMem_FREE(buffer);
11663 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011664}
Benjamin Peterson9428d532011-09-14 11:45:52 -040011665#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040011666
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011667
Larry Hastings2f936352014-08-05 14:04:04 +100011668/*[clinic input]
11669os.urandom
11670
11671 size: Py_ssize_t
11672 /
11673
11674Return a bytes object containing random bytes suitable for cryptographic use.
11675[clinic start generated code]*/
11676
Larry Hastings2f936352014-08-05 14:04:04 +100011677static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011678os_urandom_impl(PyObject *module, Py_ssize_t size)
11679/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011680{
11681 PyObject *bytes;
11682 int result;
11683
Georg Brandl2fb477c2012-02-21 00:33:36 +010011684 if (size < 0)
11685 return PyErr_Format(PyExc_ValueError,
11686 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100011687 bytes = PyBytes_FromStringAndSize(NULL, size);
11688 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010011689 return NULL;
11690
Victor Stinnere66987e2016-09-06 16:33:52 -070011691 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100011692 if (result == -1) {
11693 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010011694 return NULL;
11695 }
Larry Hastings2f936352014-08-05 14:04:04 +100011696 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010011697}
11698
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011699/* Terminal size querying */
11700
Eddie Elizondo474eedf2018-11-13 04:09:31 -080011701static PyTypeObject* TerminalSizeType;
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011702
11703PyDoc_STRVAR(TerminalSize_docstring,
11704 "A tuple of (columns, lines) for holding terminal window size");
11705
11706static PyStructSequence_Field TerminalSize_fields[] = {
11707 {"columns", "width of the terminal window in characters"},
11708 {"lines", "height of the terminal window in characters"},
11709 {NULL, NULL}
11710};
11711
11712static PyStructSequence_Desc TerminalSize_desc = {
11713 "os.terminal_size",
11714 TerminalSize_docstring,
11715 TerminalSize_fields,
11716 2,
11717};
11718
11719#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100011720/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011721PyDoc_STRVAR(termsize__doc__,
11722 "Return the size of the terminal window as (columns, lines).\n" \
11723 "\n" \
11724 "The optional argument fd (default standard output) specifies\n" \
11725 "which file descriptor should be queried.\n" \
11726 "\n" \
11727 "If the file descriptor is not connected to a terminal, an OSError\n" \
11728 "is thrown.\n" \
11729 "\n" \
11730 "This function will only be defined if an implementation is\n" \
11731 "available for this system.\n" \
11732 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080011733 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011734 "normally be used, os.get_terminal_size is the low-level implementation.");
11735
11736static PyObject*
11737get_terminal_size(PyObject *self, PyObject *args)
11738{
11739 int columns, lines;
11740 PyObject *termsize;
11741
11742 int fd = fileno(stdout);
11743 /* Under some conditions stdout may not be connected and
11744 * fileno(stdout) may point to an invalid file descriptor. For example
11745 * GUI apps don't have valid standard streams by default.
11746 *
11747 * If this happens, and the optional fd argument is not present,
11748 * the ioctl below will fail returning EBADF. This is what we want.
11749 */
11750
11751 if (!PyArg_ParseTuple(args, "|i", &fd))
11752 return NULL;
11753
11754#ifdef TERMSIZE_USE_IOCTL
11755 {
11756 struct winsize w;
11757 if (ioctl(fd, TIOCGWINSZ, &w))
11758 return PyErr_SetFromErrno(PyExc_OSError);
11759 columns = w.ws_col;
11760 lines = w.ws_row;
11761 }
11762#endif /* TERMSIZE_USE_IOCTL */
11763
11764#ifdef TERMSIZE_USE_CONIO
11765 {
11766 DWORD nhandle;
11767 HANDLE handle;
11768 CONSOLE_SCREEN_BUFFER_INFO csbi;
11769 switch (fd) {
11770 case 0: nhandle = STD_INPUT_HANDLE;
11771 break;
11772 case 1: nhandle = STD_OUTPUT_HANDLE;
11773 break;
11774 case 2: nhandle = STD_ERROR_HANDLE;
11775 break;
11776 default:
11777 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
11778 }
11779 handle = GetStdHandle(nhandle);
11780 if (handle == NULL)
11781 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
11782 if (handle == INVALID_HANDLE_VALUE)
11783 return PyErr_SetFromWindowsErr(0);
11784
11785 if (!GetConsoleScreenBufferInfo(handle, &csbi))
11786 return PyErr_SetFromWindowsErr(0);
11787
11788 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
11789 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
11790 }
11791#endif /* TERMSIZE_USE_CONIO */
11792
Eddie Elizondo474eedf2018-11-13 04:09:31 -080011793 termsize = PyStructSequence_New(TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011794 if (termsize == NULL)
11795 return NULL;
11796 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
11797 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
11798 if (PyErr_Occurred()) {
11799 Py_DECREF(termsize);
11800 return NULL;
11801 }
11802 return termsize;
11803}
11804#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
11805
Larry Hastings2f936352014-08-05 14:04:04 +100011806
11807/*[clinic input]
11808os.cpu_count
11809
Charles-François Natali80d62e62015-08-13 20:37:08 +010011810Return the number of CPUs in the system; return None if indeterminable.
11811
11812This number is not equivalent to the number of CPUs the current process can
11813use. The number of usable CPUs can be obtained with
11814``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100011815[clinic start generated code]*/
11816
Larry Hastings2f936352014-08-05 14:04:04 +100011817static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011818os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030011819/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020011820{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020011821 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020011822#ifdef MS_WINDOWS
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040011823 /* Vista is supported and the GetMaximumProcessorCount API is Win7+
11824 Need to fallback to Vista behavior if this call isn't present */
11825 HINSTANCE hKernel32;
11826 hKernel32 = GetModuleHandleW(L"KERNEL32");
11827
11828 static DWORD(CALLBACK *_GetMaximumProcessorCount)(WORD) = NULL;
11829 *(FARPROC*)&_GetMaximumProcessorCount = GetProcAddress(hKernel32,
11830 "GetMaximumProcessorCount");
11831 if (_GetMaximumProcessorCount != NULL) {
11832 ncpu = _GetMaximumProcessorCount(ALL_PROCESSOR_GROUPS);
11833 }
11834 else {
11835 SYSTEM_INFO sysinfo;
11836 GetSystemInfo(&sysinfo);
11837 ncpu = sysinfo.dwNumberOfProcessors;
11838 }
Charles-Francois Natali44feda32013-05-20 14:40:46 +020011839#elif defined(__hpux)
11840 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
11841#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
11842 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020011843#elif defined(__DragonFly__) || \
11844 defined(__OpenBSD__) || \
11845 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020011846 defined(__NetBSD__) || \
11847 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020011848 int mib[2];
11849 size_t len = sizeof(ncpu);
11850 mib[0] = CTL_HW;
11851 mib[1] = HW_NCPU;
11852 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
11853 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020011854#endif
11855 if (ncpu >= 1)
11856 return PyLong_FromLong(ncpu);
11857 else
11858 Py_RETURN_NONE;
11859}
11860
Victor Stinnerdaf45552013-08-28 00:53:59 +020011861
Larry Hastings2f936352014-08-05 14:04:04 +100011862/*[clinic input]
11863os.get_inheritable -> bool
11864
11865 fd: int
11866 /
11867
11868Get the close-on-exe flag of the specified file descriptor.
11869[clinic start generated code]*/
11870
Larry Hastings2f936352014-08-05 14:04:04 +100011871static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011872os_get_inheritable_impl(PyObject *module, int fd)
11873/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011874{
Steve Dower8fc89802015-04-12 00:26:27 -040011875 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040011876 _Py_BEGIN_SUPPRESS_IPH
11877 return_value = _Py_get_inheritable(fd);
11878 _Py_END_SUPPRESS_IPH
11879 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100011880}
11881
11882
11883/*[clinic input]
11884os.set_inheritable
11885 fd: int
11886 inheritable: int
11887 /
11888
11889Set the inheritable flag of the specified file descriptor.
11890[clinic start generated code]*/
11891
Larry Hastings2f936352014-08-05 14:04:04 +100011892static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011893os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
11894/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020011895{
Steve Dower8fc89802015-04-12 00:26:27 -040011896 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020011897
Steve Dower8fc89802015-04-12 00:26:27 -040011898 _Py_BEGIN_SUPPRESS_IPH
11899 result = _Py_set_inheritable(fd, inheritable, NULL);
11900 _Py_END_SUPPRESS_IPH
11901 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020011902 return NULL;
11903 Py_RETURN_NONE;
11904}
11905
11906
11907#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100011908/*[clinic input]
11909os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070011910 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100011911 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020011912
Larry Hastings2f936352014-08-05 14:04:04 +100011913Get the close-on-exe flag of the specified file descriptor.
11914[clinic start generated code]*/
11915
Larry Hastings2f936352014-08-05 14:04:04 +100011916static int
Benjamin Petersonca470632016-09-06 13:47:26 -070011917os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070011918/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011919{
11920 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020011921
11922 if (!GetHandleInformation((HANDLE)handle, &flags)) {
11923 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100011924 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020011925 }
11926
Larry Hastings2f936352014-08-05 14:04:04 +100011927 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020011928}
11929
Victor Stinnerdaf45552013-08-28 00:53:59 +020011930
Larry Hastings2f936352014-08-05 14:04:04 +100011931/*[clinic input]
11932os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070011933 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100011934 inheritable: bool
11935 /
11936
11937Set the inheritable flag of the specified handle.
11938[clinic start generated code]*/
11939
Larry Hastings2f936352014-08-05 14:04:04 +100011940static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070011941os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040011942 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070011943/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011944{
11945 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020011946 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
11947 PyErr_SetFromWindowsErr(0);
11948 return NULL;
11949 }
11950 Py_RETURN_NONE;
11951}
Larry Hastings2f936352014-08-05 14:04:04 +100011952#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011953
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011954#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030011955/*[clinic input]
11956os.get_blocking -> bool
11957 fd: int
11958 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011959
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030011960Get the blocking mode of the file descriptor.
11961
11962Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
11963[clinic start generated code]*/
11964
11965static int
11966os_get_blocking_impl(PyObject *module, int fd)
11967/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011968{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011969 int blocking;
11970
Steve Dower8fc89802015-04-12 00:26:27 -040011971 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011972 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040011973 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030011974 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011975}
11976
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030011977/*[clinic input]
11978os.set_blocking
11979 fd: int
11980 blocking: bool(accept={int})
11981 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011982
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030011983Set the blocking mode of the specified file descriptor.
11984
11985Set the O_NONBLOCK flag if blocking is False,
11986clear the O_NONBLOCK flag otherwise.
11987[clinic start generated code]*/
11988
11989static PyObject *
11990os_set_blocking_impl(PyObject *module, int fd, int blocking)
11991/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011992{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030011993 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011994
Steve Dower8fc89802015-04-12 00:26:27 -040011995 _Py_BEGIN_SUPPRESS_IPH
11996 result = _Py_set_blocking(fd, blocking);
11997 _Py_END_SUPPRESS_IPH
11998 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020011999 return NULL;
12000 Py_RETURN_NONE;
12001}
12002#endif /* !MS_WINDOWS */
12003
12004
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012005/*[clinic input]
12006class os.DirEntry "DirEntry *" "&DirEntryType"
12007[clinic start generated code]*/
12008/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3138f09f7c683f1d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012009
12010typedef struct {
12011 PyObject_HEAD
12012 PyObject *name;
12013 PyObject *path;
12014 PyObject *stat;
12015 PyObject *lstat;
12016#ifdef MS_WINDOWS
12017 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012018 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012019 int got_file_index;
12020#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012021#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012022 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012023#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012024 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012025 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012026#endif
12027} DirEntry;
12028
12029static void
12030DirEntry_dealloc(DirEntry *entry)
12031{
12032 Py_XDECREF(entry->name);
12033 Py_XDECREF(entry->path);
12034 Py_XDECREF(entry->stat);
12035 Py_XDECREF(entry->lstat);
12036 Py_TYPE(entry)->tp_free((PyObject *)entry);
12037}
12038
12039/* Forward reference */
12040static int
12041DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12042
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012043/*[clinic input]
12044os.DirEntry.is_symlink -> bool
12045
12046Return True if the entry is a symbolic link; cached per entry.
12047[clinic start generated code]*/
12048
Victor Stinner6036e442015-03-08 01:58:04 +010012049static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012050os_DirEntry_is_symlink_impl(DirEntry *self)
12051/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012052{
12053#ifdef MS_WINDOWS
12054 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012055#elif defined(HAVE_DIRENT_D_TYPE)
12056 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012057 if (self->d_type != DT_UNKNOWN)
12058 return self->d_type == DT_LNK;
12059 else
12060 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012061#else
12062 /* POSIX without d_type */
12063 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012064#endif
12065}
12066
12067static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012068DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12069{
12070 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012071 STRUCT_STAT st;
12072 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012073
12074#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012075 if (!PyUnicode_FSDecoder(self->path, &ub))
12076 return NULL;
12077 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012078#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012079 if (!PyUnicode_FSConverter(self->path, &ub))
12080 return NULL;
12081 const char *path = PyBytes_AS_STRING(ub);
12082 if (self->dir_fd != DEFAULT_DIR_FD) {
12083#ifdef HAVE_FSTATAT
12084 result = fstatat(self->dir_fd, path, &st,
12085 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12086#else
12087 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12088 return NULL;
12089#endif /* HAVE_FSTATAT */
12090 }
12091 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012092#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012093 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012094 if (follow_symlinks)
12095 result = STAT(path, &st);
12096 else
12097 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012098 }
12099 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012100
12101 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012102 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012103
12104 return _pystat_fromstructstat(&st);
12105}
12106
12107static PyObject *
12108DirEntry_get_lstat(DirEntry *self)
12109{
12110 if (!self->lstat) {
12111#ifdef MS_WINDOWS
12112 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12113#else /* POSIX */
12114 self->lstat = DirEntry_fetch_stat(self, 0);
12115#endif
12116 }
12117 Py_XINCREF(self->lstat);
12118 return self->lstat;
12119}
12120
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012121/*[clinic input]
12122os.DirEntry.stat
12123 *
12124 follow_symlinks: bool = True
12125
12126Return stat_result object for the entry; cached per entry.
12127[clinic start generated code]*/
12128
Victor Stinner6036e442015-03-08 01:58:04 +010012129static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012130os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12131/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012132{
12133 if (!follow_symlinks)
12134 return DirEntry_get_lstat(self);
12135
12136 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012137 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012138 if (result == -1)
12139 return NULL;
12140 else if (result)
12141 self->stat = DirEntry_fetch_stat(self, 1);
12142 else
12143 self->stat = DirEntry_get_lstat(self);
12144 }
12145
12146 Py_XINCREF(self->stat);
12147 return self->stat;
12148}
12149
Victor Stinner6036e442015-03-08 01:58:04 +010012150/* Set exception and return -1 on error, 0 for False, 1 for True */
12151static int
12152DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12153{
12154 PyObject *stat = NULL;
12155 PyObject *st_mode = NULL;
12156 long mode;
12157 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012158#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012159 int is_symlink;
12160 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012161#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012162#ifdef MS_WINDOWS
12163 unsigned long dir_bits;
12164#endif
Victor Stinner35a97c02015-03-08 02:59:09 +010012165 _Py_IDENTIFIER(st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012166
12167#ifdef MS_WINDOWS
12168 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12169 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012170#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012171 is_symlink = self->d_type == DT_LNK;
12172 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12173#endif
12174
Victor Stinner35a97c02015-03-08 02:59:09 +010012175#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012176 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012177#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012178 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012179 if (!stat) {
12180 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12181 /* If file doesn't exist (anymore), then return False
12182 (i.e., say it's not a file/directory) */
12183 PyErr_Clear();
12184 return 0;
12185 }
12186 goto error;
12187 }
12188 st_mode = _PyObject_GetAttrId(stat, &PyId_st_mode);
12189 if (!st_mode)
12190 goto error;
12191
12192 mode = PyLong_AsLong(st_mode);
12193 if (mode == -1 && PyErr_Occurred())
12194 goto error;
12195 Py_CLEAR(st_mode);
12196 Py_CLEAR(stat);
12197 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012198#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012199 }
12200 else if (is_symlink) {
12201 assert(mode_bits != S_IFLNK);
12202 result = 0;
12203 }
12204 else {
12205 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12206#ifdef MS_WINDOWS
12207 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12208 if (mode_bits == S_IFDIR)
12209 result = dir_bits != 0;
12210 else
12211 result = dir_bits == 0;
12212#else /* POSIX */
12213 if (mode_bits == S_IFDIR)
12214 result = self->d_type == DT_DIR;
12215 else
12216 result = self->d_type == DT_REG;
12217#endif
12218 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012219#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012220
12221 return result;
12222
12223error:
12224 Py_XDECREF(st_mode);
12225 Py_XDECREF(stat);
12226 return -1;
12227}
12228
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012229/*[clinic input]
12230os.DirEntry.is_dir -> bool
12231 *
12232 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012233
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012234Return True if the entry is a directory; cached per entry.
12235[clinic start generated code]*/
12236
12237static int
12238os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12239/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12240{
12241 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012242}
12243
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012244/*[clinic input]
12245os.DirEntry.is_file -> bool
12246 *
12247 follow_symlinks: bool = True
12248
12249Return True if the entry is a file; cached per entry.
12250[clinic start generated code]*/
12251
12252static int
12253os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12254/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012255{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012256 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012257}
12258
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012259/*[clinic input]
12260os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012261
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012262Return inode of the entry; cached per entry.
12263[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012264
12265static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012266os_DirEntry_inode_impl(DirEntry *self)
12267/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012268{
12269#ifdef MS_WINDOWS
12270 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012271 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012272 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012273 STRUCT_STAT stat;
12274 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012275
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012276 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012277 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012278 path = PyUnicode_AsUnicode(unicode);
12279 result = LSTAT(path, &stat);
12280 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012281
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012282 if (result != 0)
12283 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012284
12285 self->win32_file_index = stat.st_ino;
12286 self->got_file_index = 1;
12287 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012288 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12289 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012290#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012291 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12292 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012293#endif
12294}
12295
12296static PyObject *
12297DirEntry_repr(DirEntry *self)
12298{
12299 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12300}
12301
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012302/*[clinic input]
12303os.DirEntry.__fspath__
12304
12305Returns the path for the entry.
12306[clinic start generated code]*/
12307
Brett Cannon96881cd2016-06-10 14:37:21 -070012308static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012309os_DirEntry___fspath___impl(DirEntry *self)
12310/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012311{
12312 Py_INCREF(self->path);
12313 return self->path;
12314}
12315
Victor Stinner6036e442015-03-08 01:58:04 +010012316static PyMemberDef DirEntry_members[] = {
12317 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12318 "the entry's base filename, relative to scandir() \"path\" argument"},
12319 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12320 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12321 {NULL}
12322};
12323
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012324#include "clinic/posixmodule.c.h"
12325
Victor Stinner6036e442015-03-08 01:58:04 +010012326static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012327 OS_DIRENTRY_IS_DIR_METHODDEF
12328 OS_DIRENTRY_IS_FILE_METHODDEF
12329 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12330 OS_DIRENTRY_STAT_METHODDEF
12331 OS_DIRENTRY_INODE_METHODDEF
12332 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012333 {NULL}
12334};
12335
Benjamin Peterson5646de42015-04-12 17:56:34 -040012336static PyTypeObject DirEntryType = {
Victor Stinner6036e442015-03-08 01:58:04 +010012337 PyVarObject_HEAD_INIT(NULL, 0)
12338 MODNAME ".DirEntry", /* tp_name */
12339 sizeof(DirEntry), /* tp_basicsize */
12340 0, /* tp_itemsize */
12341 /* methods */
12342 (destructor)DirEntry_dealloc, /* tp_dealloc */
12343 0, /* tp_print */
12344 0, /* tp_getattr */
12345 0, /* tp_setattr */
12346 0, /* tp_compare */
12347 (reprfunc)DirEntry_repr, /* tp_repr */
12348 0, /* tp_as_number */
12349 0, /* tp_as_sequence */
12350 0, /* tp_as_mapping */
12351 0, /* tp_hash */
12352 0, /* tp_call */
12353 0, /* tp_str */
12354 0, /* tp_getattro */
12355 0, /* tp_setattro */
12356 0, /* tp_as_buffer */
12357 Py_TPFLAGS_DEFAULT, /* tp_flags */
12358 0, /* tp_doc */
12359 0, /* tp_traverse */
12360 0, /* tp_clear */
12361 0, /* tp_richcompare */
12362 0, /* tp_weaklistoffset */
12363 0, /* tp_iter */
12364 0, /* tp_iternext */
12365 DirEntry_methods, /* tp_methods */
12366 DirEntry_members, /* tp_members */
12367};
12368
12369#ifdef MS_WINDOWS
12370
12371static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012372join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012373{
12374 Py_ssize_t path_len;
12375 Py_ssize_t size;
12376 wchar_t *result;
12377 wchar_t ch;
12378
12379 if (!path_wide) { /* Default arg: "." */
12380 path_wide = L".";
12381 path_len = 1;
12382 }
12383 else {
12384 path_len = wcslen(path_wide);
12385 }
12386
12387 /* The +1's are for the path separator and the NUL */
12388 size = path_len + 1 + wcslen(filename) + 1;
12389 result = PyMem_New(wchar_t, size);
12390 if (!result) {
12391 PyErr_NoMemory();
12392 return NULL;
12393 }
12394 wcscpy(result, path_wide);
12395 if (path_len > 0) {
12396 ch = result[path_len - 1];
12397 if (ch != SEP && ch != ALTSEP && ch != L':')
12398 result[path_len++] = SEP;
12399 wcscpy(result + path_len, filename);
12400 }
12401 return result;
12402}
12403
12404static PyObject *
12405DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12406{
12407 DirEntry *entry;
12408 BY_HANDLE_FILE_INFORMATION file_info;
12409 ULONG reparse_tag;
12410 wchar_t *joined_path;
12411
12412 entry = PyObject_New(DirEntry, &DirEntryType);
12413 if (!entry)
12414 return NULL;
12415 entry->name = NULL;
12416 entry->path = NULL;
12417 entry->stat = NULL;
12418 entry->lstat = NULL;
12419 entry->got_file_index = 0;
12420
12421 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12422 if (!entry->name)
12423 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012424 if (path->narrow) {
12425 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12426 if (!entry->name)
12427 goto error;
12428 }
Victor Stinner6036e442015-03-08 01:58:04 +010012429
12430 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12431 if (!joined_path)
12432 goto error;
12433
12434 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12435 PyMem_Free(joined_path);
12436 if (!entry->path)
12437 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012438 if (path->narrow) {
12439 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12440 if (!entry->path)
12441 goto error;
12442 }
Victor Stinner6036e442015-03-08 01:58:04 +010012443
Steve Dowercc16be82016-09-08 10:35:16 -070012444 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012445 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12446
12447 return (PyObject *)entry;
12448
12449error:
12450 Py_DECREF(entry);
12451 return NULL;
12452}
12453
12454#else /* POSIX */
12455
12456static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012457join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012458{
12459 Py_ssize_t path_len;
12460 Py_ssize_t size;
12461 char *result;
12462
12463 if (!path_narrow) { /* Default arg: "." */
12464 path_narrow = ".";
12465 path_len = 1;
12466 }
12467 else {
12468 path_len = strlen(path_narrow);
12469 }
12470
12471 if (filename_len == -1)
12472 filename_len = strlen(filename);
12473
12474 /* The +1's are for the path separator and the NUL */
12475 size = path_len + 1 + filename_len + 1;
12476 result = PyMem_New(char, size);
12477 if (!result) {
12478 PyErr_NoMemory();
12479 return NULL;
12480 }
12481 strcpy(result, path_narrow);
12482 if (path_len > 0 && result[path_len - 1] != '/')
12483 result[path_len++] = '/';
12484 strcpy(result + path_len, filename);
12485 return result;
12486}
12487
12488static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012489DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012490 ino_t d_ino
12491#ifdef HAVE_DIRENT_D_TYPE
12492 , unsigned char d_type
12493#endif
12494 )
Victor Stinner6036e442015-03-08 01:58:04 +010012495{
12496 DirEntry *entry;
12497 char *joined_path;
12498
12499 entry = PyObject_New(DirEntry, &DirEntryType);
12500 if (!entry)
12501 return NULL;
12502 entry->name = NULL;
12503 entry->path = NULL;
12504 entry->stat = NULL;
12505 entry->lstat = NULL;
12506
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012507 if (path->fd != -1) {
12508 entry->dir_fd = path->fd;
12509 joined_path = NULL;
12510 }
12511 else {
12512 entry->dir_fd = DEFAULT_DIR_FD;
12513 joined_path = join_path_filename(path->narrow, name, name_len);
12514 if (!joined_path)
12515 goto error;
12516 }
Victor Stinner6036e442015-03-08 01:58:04 +010012517
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030012518 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010012519 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012520 if (joined_path)
12521 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012522 }
12523 else {
12524 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012525 if (joined_path)
12526 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012527 }
12528 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012529 if (!entry->name)
12530 goto error;
12531
12532 if (path->fd != -1) {
12533 entry->path = entry->name;
12534 Py_INCREF(entry->path);
12535 }
12536 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010012537 goto error;
12538
Victor Stinner35a97c02015-03-08 02:59:09 +010012539#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012540 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012541#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012542 entry->d_ino = d_ino;
12543
12544 return (PyObject *)entry;
12545
12546error:
12547 Py_XDECREF(entry);
12548 return NULL;
12549}
12550
12551#endif
12552
12553
12554typedef struct {
12555 PyObject_HEAD
12556 path_t path;
12557#ifdef MS_WINDOWS
12558 HANDLE handle;
12559 WIN32_FIND_DATAW file_data;
12560 int first_time;
12561#else /* POSIX */
12562 DIR *dirp;
12563#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012564#ifdef HAVE_FDOPENDIR
12565 int fd;
12566#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012567} ScandirIterator;
12568
12569#ifdef MS_WINDOWS
12570
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012571static int
12572ScandirIterator_is_closed(ScandirIterator *iterator)
12573{
12574 return iterator->handle == INVALID_HANDLE_VALUE;
12575}
12576
Victor Stinner6036e442015-03-08 01:58:04 +010012577static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012578ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010012579{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012580 HANDLE handle = iterator->handle;
12581
12582 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010012583 return;
12584
Victor Stinner6036e442015-03-08 01:58:04 +010012585 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012586 Py_BEGIN_ALLOW_THREADS
12587 FindClose(handle);
12588 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010012589}
12590
12591static PyObject *
12592ScandirIterator_iternext(ScandirIterator *iterator)
12593{
12594 WIN32_FIND_DATAW *file_data = &iterator->file_data;
12595 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012596 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012597
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012598 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012599 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010012600 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012601
12602 while (1) {
12603 if (!iterator->first_time) {
12604 Py_BEGIN_ALLOW_THREADS
12605 success = FindNextFileW(iterator->handle, file_data);
12606 Py_END_ALLOW_THREADS
12607 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012608 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010012609 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012610 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012611 break;
12612 }
12613 }
12614 iterator->first_time = 0;
12615
12616 /* Skip over . and .. */
12617 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012618 wcscmp(file_data->cFileName, L"..") != 0) {
12619 entry = DirEntry_from_find_data(&iterator->path, file_data);
12620 if (!entry)
12621 break;
12622 return entry;
12623 }
Victor Stinner6036e442015-03-08 01:58:04 +010012624
12625 /* Loop till we get a non-dot directory or finish iterating */
12626 }
12627
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012628 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012629 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010012630 return NULL;
12631}
12632
12633#else /* POSIX */
12634
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012635static int
12636ScandirIterator_is_closed(ScandirIterator *iterator)
12637{
12638 return !iterator->dirp;
12639}
12640
Victor Stinner6036e442015-03-08 01:58:04 +010012641static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012642ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010012643{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012644 DIR *dirp = iterator->dirp;
12645
12646 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010012647 return;
12648
Victor Stinner6036e442015-03-08 01:58:04 +010012649 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012650 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012651#ifdef HAVE_FDOPENDIR
12652 if (iterator->path.fd != -1)
12653 rewinddir(dirp);
12654#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012655 closedir(dirp);
12656 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010012657 return;
12658}
12659
12660static PyObject *
12661ScandirIterator_iternext(ScandirIterator *iterator)
12662{
12663 struct dirent *direntp;
12664 Py_ssize_t name_len;
12665 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012666 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012667
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012668 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012669 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010012670 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012671
12672 while (1) {
12673 errno = 0;
12674 Py_BEGIN_ALLOW_THREADS
12675 direntp = readdir(iterator->dirp);
12676 Py_END_ALLOW_THREADS
12677
12678 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012679 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010012680 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012681 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012682 break;
12683 }
12684
12685 /* Skip over . and .. */
12686 name_len = NAMLEN(direntp);
12687 is_dot = direntp->d_name[0] == '.' &&
12688 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
12689 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012690 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010012691 name_len, direntp->d_ino
12692#ifdef HAVE_DIRENT_D_TYPE
12693 , direntp->d_type
12694#endif
12695 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012696 if (!entry)
12697 break;
12698 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012699 }
12700
12701 /* Loop till we get a non-dot directory or finish iterating */
12702 }
12703
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012704 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012705 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010012706 return NULL;
12707}
12708
12709#endif
12710
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012711static PyObject *
12712ScandirIterator_close(ScandirIterator *self, PyObject *args)
12713{
12714 ScandirIterator_closedir(self);
12715 Py_RETURN_NONE;
12716}
12717
12718static PyObject *
12719ScandirIterator_enter(PyObject *self, PyObject *args)
12720{
12721 Py_INCREF(self);
12722 return self;
12723}
12724
12725static PyObject *
12726ScandirIterator_exit(ScandirIterator *self, PyObject *args)
12727{
12728 ScandirIterator_closedir(self);
12729 Py_RETURN_NONE;
12730}
12731
Victor Stinner6036e442015-03-08 01:58:04 +010012732static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010012733ScandirIterator_finalize(ScandirIterator *iterator)
12734{
12735 PyObject *error_type, *error_value, *error_traceback;
12736
12737 /* Save the current exception, if any. */
12738 PyErr_Fetch(&error_type, &error_value, &error_traceback);
12739
12740 if (!ScandirIterator_is_closed(iterator)) {
12741 ScandirIterator_closedir(iterator);
12742
12743 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
12744 "unclosed scandir iterator %R", iterator)) {
12745 /* Spurious errors can appear at shutdown */
12746 if (PyErr_ExceptionMatches(PyExc_Warning)) {
12747 PyErr_WriteUnraisable((PyObject *) iterator);
12748 }
12749 }
12750 }
12751
Victor Stinner7bfa4092016-03-23 00:43:54 +010012752 path_cleanup(&iterator->path);
12753
12754 /* Restore the saved exception. */
12755 PyErr_Restore(error_type, error_value, error_traceback);
12756}
12757
12758static void
Victor Stinner6036e442015-03-08 01:58:04 +010012759ScandirIterator_dealloc(ScandirIterator *iterator)
12760{
Victor Stinner7bfa4092016-03-23 00:43:54 +010012761 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
12762 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012763
Victor Stinner6036e442015-03-08 01:58:04 +010012764 Py_TYPE(iterator)->tp_free((PyObject *)iterator);
12765}
12766
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012767static PyMethodDef ScandirIterator_methods[] = {
12768 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
12769 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
12770 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
12771 {NULL}
12772};
12773
Benjamin Peterson5646de42015-04-12 17:56:34 -040012774static PyTypeObject ScandirIteratorType = {
Victor Stinner6036e442015-03-08 01:58:04 +010012775 PyVarObject_HEAD_INIT(NULL, 0)
12776 MODNAME ".ScandirIterator", /* tp_name */
12777 sizeof(ScandirIterator), /* tp_basicsize */
12778 0, /* tp_itemsize */
12779 /* methods */
12780 (destructor)ScandirIterator_dealloc, /* tp_dealloc */
12781 0, /* tp_print */
12782 0, /* tp_getattr */
12783 0, /* tp_setattr */
12784 0, /* tp_compare */
12785 0, /* tp_repr */
12786 0, /* tp_as_number */
12787 0, /* tp_as_sequence */
12788 0, /* tp_as_mapping */
12789 0, /* tp_hash */
12790 0, /* tp_call */
12791 0, /* tp_str */
12792 0, /* tp_getattro */
12793 0, /* tp_setattro */
12794 0, /* tp_as_buffer */
Victor Stinner7bfa4092016-03-23 00:43:54 +010012795 Py_TPFLAGS_DEFAULT
12796 | Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Victor Stinner6036e442015-03-08 01:58:04 +010012797 0, /* tp_doc */
12798 0, /* tp_traverse */
12799 0, /* tp_clear */
12800 0, /* tp_richcompare */
12801 0, /* tp_weaklistoffset */
12802 PyObject_SelfIter, /* tp_iter */
12803 (iternextfunc)ScandirIterator_iternext, /* tp_iternext */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012804 ScandirIterator_methods, /* tp_methods */
Victor Stinner7bfa4092016-03-23 00:43:54 +010012805 0, /* tp_members */
12806 0, /* tp_getset */
12807 0, /* tp_base */
12808 0, /* tp_dict */
12809 0, /* tp_descr_get */
12810 0, /* tp_descr_set */
12811 0, /* tp_dictoffset */
12812 0, /* tp_init */
12813 0, /* tp_alloc */
12814 0, /* tp_new */
12815 0, /* tp_free */
12816 0, /* tp_is_gc */
12817 0, /* tp_bases */
12818 0, /* tp_mro */
12819 0, /* tp_cache */
12820 0, /* tp_subclasses */
12821 0, /* tp_weaklist */
12822 0, /* tp_del */
12823 0, /* tp_version_tag */
12824 (destructor)ScandirIterator_finalize, /* tp_finalize */
Victor Stinner6036e442015-03-08 01:58:04 +010012825};
12826
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012827/*[clinic input]
12828os.scandir
12829
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012830 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012831
12832Return an iterator of DirEntry objects for given path.
12833
BNMetricsb9427072018-11-02 15:20:19 +000012834path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012835is bytes, the names of yielded DirEntry objects will also be bytes; in
12836all other circumstances they will be str.
12837
12838If path is None, uses the path='.'.
12839[clinic start generated code]*/
12840
Victor Stinner6036e442015-03-08 01:58:04 +010012841static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012842os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000012843/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012844{
12845 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010012846#ifdef MS_WINDOWS
12847 wchar_t *path_strW;
12848#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012849 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012850#ifdef HAVE_FDOPENDIR
12851 int fd = -1;
12852#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012853#endif
12854
12855 iterator = PyObject_New(ScandirIterator, &ScandirIteratorType);
12856 if (!iterator)
12857 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012858
12859#ifdef MS_WINDOWS
12860 iterator->handle = INVALID_HANDLE_VALUE;
12861#else
12862 iterator->dirp = NULL;
12863#endif
12864
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012865 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020012866 /* Move the ownership to iterator->path */
12867 path->object = NULL;
12868 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012869
12870#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010012871 iterator->first_time = 1;
12872
12873 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
12874 if (!path_strW)
12875 goto error;
12876
12877 Py_BEGIN_ALLOW_THREADS
12878 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
12879 Py_END_ALLOW_THREADS
12880
12881 PyMem_Free(path_strW);
12882
12883 if (iterator->handle == INVALID_HANDLE_VALUE) {
12884 path_error(&iterator->path);
12885 goto error;
12886 }
12887#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012888 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012889#ifdef HAVE_FDOPENDIR
12890 if (path->fd != -1) {
12891 /* closedir() closes the FD, so we duplicate it */
12892 fd = _Py_dup(path->fd);
12893 if (fd == -1)
12894 goto error;
12895
12896 Py_BEGIN_ALLOW_THREADS
12897 iterator->dirp = fdopendir(fd);
12898 Py_END_ALLOW_THREADS
12899 }
12900 else
12901#endif
12902 {
12903 if (iterator->path.narrow)
12904 path_str = iterator->path.narrow;
12905 else
12906 path_str = ".";
12907
12908 Py_BEGIN_ALLOW_THREADS
12909 iterator->dirp = opendir(path_str);
12910 Py_END_ALLOW_THREADS
12911 }
Victor Stinner6036e442015-03-08 01:58:04 +010012912
12913 if (!iterator->dirp) {
12914 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012915#ifdef HAVE_FDOPENDIR
12916 if (fd != -1) {
12917 Py_BEGIN_ALLOW_THREADS
12918 close(fd);
12919 Py_END_ALLOW_THREADS
12920 }
12921#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012922 goto error;
12923 }
12924#endif
12925
12926 return (PyObject *)iterator;
12927
12928error:
12929 Py_DECREF(iterator);
12930 return NULL;
12931}
12932
Ethan Furman410ef8e2016-06-04 12:06:26 -070012933/*
12934 Return the file system path representation of the object.
12935
12936 If the object is str or bytes, then allow it to pass through with
12937 an incremented refcount. If the object defines __fspath__(), then
12938 return the result of that method. All other types raise a TypeError.
12939*/
12940PyObject *
12941PyOS_FSPath(PyObject *path)
12942{
Brett Cannon3f9183b2016-08-26 14:44:48 -070012943 /* For error message reasons, this function is manually inlined in
12944 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070012945 _Py_IDENTIFIER(__fspath__);
12946 PyObject *func = NULL;
12947 PyObject *path_repr = NULL;
12948
12949 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
12950 Py_INCREF(path);
12951 return path;
12952 }
12953
12954 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
12955 if (NULL == func) {
12956 return PyErr_Format(PyExc_TypeError,
12957 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070012958 "not %.200s",
12959 Py_TYPE(path)->tp_name);
Ethan Furman410ef8e2016-06-04 12:06:26 -070012960 }
12961
Victor Stinnerf17c3de2016-12-06 18:46:19 +010012962 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070012963 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070012964 if (NULL == path_repr) {
12965 return NULL;
12966 }
12967
Brett Cannonc78ca1e2016-06-24 12:03:43 -070012968 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
12969 PyErr_Format(PyExc_TypeError,
12970 "expected %.200s.__fspath__() to return str or bytes, "
12971 "not %.200s", Py_TYPE(path)->tp_name,
12972 Py_TYPE(path_repr)->tp_name);
12973 Py_DECREF(path_repr);
12974 return NULL;
12975 }
12976
Ethan Furman410ef8e2016-06-04 12:06:26 -070012977 return path_repr;
12978}
12979
12980/*[clinic input]
12981os.fspath
12982
12983 path: object
12984
12985Return the file system path representation of the object.
12986
Brett Cannonb4f43e92016-06-09 14:32:08 -070012987If the object is str or bytes, then allow it to pass through as-is. If the
12988object defines __fspath__(), then return the result of that method. All other
12989types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070012990[clinic start generated code]*/
12991
12992static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012993os_fspath_impl(PyObject *module, PyObject *path)
12994/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070012995{
12996 return PyOS_FSPath(path);
12997}
Victor Stinner6036e442015-03-08 01:58:04 +010012998
Victor Stinner9b1f4742016-09-06 16:18:52 -070012999#ifdef HAVE_GETRANDOM_SYSCALL
13000/*[clinic input]
13001os.getrandom
13002
13003 size: Py_ssize_t
13004 flags: int=0
13005
13006Obtain a series of random bytes.
13007[clinic start generated code]*/
13008
13009static PyObject *
13010os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13011/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13012{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013013 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013014 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013015
13016 if (size < 0) {
13017 errno = EINVAL;
13018 return posix_error();
13019 }
13020
Victor Stinnerec2319c2016-09-20 23:00:59 +020013021 bytes = PyBytes_FromStringAndSize(NULL, size);
13022 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013023 PyErr_NoMemory();
13024 return NULL;
13025 }
13026
13027 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013028 n = syscall(SYS_getrandom,
13029 PyBytes_AS_STRING(bytes),
13030 PyBytes_GET_SIZE(bytes),
13031 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013032 if (n < 0 && errno == EINTR) {
13033 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013034 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013035 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013036
13037 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013038 continue;
13039 }
13040 break;
13041 }
13042
13043 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013044 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013045 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013046 }
13047
Victor Stinnerec2319c2016-09-20 23:00:59 +020013048 if (n != size) {
13049 _PyBytes_Resize(&bytes, n);
13050 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013051
13052 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013053
13054error:
13055 Py_DECREF(bytes);
13056 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013057}
13058#endif /* HAVE_GETRANDOM_SYSCALL */
13059
Larry Hastings31826802013-10-19 00:09:25 -070013060
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013061static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013062
13063 OS_STAT_METHODDEF
13064 OS_ACCESS_METHODDEF
13065 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013066 OS_CHDIR_METHODDEF
13067 OS_CHFLAGS_METHODDEF
13068 OS_CHMOD_METHODDEF
13069 OS_FCHMOD_METHODDEF
13070 OS_LCHMOD_METHODDEF
13071 OS_CHOWN_METHODDEF
13072 OS_FCHOWN_METHODDEF
13073 OS_LCHOWN_METHODDEF
13074 OS_LCHFLAGS_METHODDEF
13075 OS_CHROOT_METHODDEF
13076 OS_CTERMID_METHODDEF
13077 OS_GETCWD_METHODDEF
13078 OS_GETCWDB_METHODDEF
13079 OS_LINK_METHODDEF
13080 OS_LISTDIR_METHODDEF
13081 OS_LSTAT_METHODDEF
13082 OS_MKDIR_METHODDEF
13083 OS_NICE_METHODDEF
13084 OS_GETPRIORITY_METHODDEF
13085 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013086 OS_POSIX_SPAWN_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013087 OS_READLINK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013088 OS_RENAME_METHODDEF
13089 OS_REPLACE_METHODDEF
13090 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013091 OS_SYMLINK_METHODDEF
13092 OS_SYSTEM_METHODDEF
13093 OS_UMASK_METHODDEF
13094 OS_UNAME_METHODDEF
13095 OS_UNLINK_METHODDEF
13096 OS_REMOVE_METHODDEF
13097 OS_UTIME_METHODDEF
13098 OS_TIMES_METHODDEF
13099 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013100 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013101 OS_EXECV_METHODDEF
13102 OS_EXECVE_METHODDEF
13103 OS_SPAWNV_METHODDEF
13104 OS_SPAWNVE_METHODDEF
13105 OS_FORK1_METHODDEF
13106 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013107 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013108 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13109 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13110 OS_SCHED_GETPARAM_METHODDEF
13111 OS_SCHED_GETSCHEDULER_METHODDEF
13112 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13113 OS_SCHED_SETPARAM_METHODDEF
13114 OS_SCHED_SETSCHEDULER_METHODDEF
13115 OS_SCHED_YIELD_METHODDEF
13116 OS_SCHED_SETAFFINITY_METHODDEF
13117 OS_SCHED_GETAFFINITY_METHODDEF
13118 OS_OPENPTY_METHODDEF
13119 OS_FORKPTY_METHODDEF
13120 OS_GETEGID_METHODDEF
13121 OS_GETEUID_METHODDEF
13122 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013123#ifdef HAVE_GETGROUPLIST
13124 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13125#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013126 OS_GETGROUPS_METHODDEF
13127 OS_GETPID_METHODDEF
13128 OS_GETPGRP_METHODDEF
13129 OS_GETPPID_METHODDEF
13130 OS_GETUID_METHODDEF
13131 OS_GETLOGIN_METHODDEF
13132 OS_KILL_METHODDEF
13133 OS_KILLPG_METHODDEF
13134 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013135#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013136 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013137#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013138 OS_SETUID_METHODDEF
13139 OS_SETEUID_METHODDEF
13140 OS_SETREUID_METHODDEF
13141 OS_SETGID_METHODDEF
13142 OS_SETEGID_METHODDEF
13143 OS_SETREGID_METHODDEF
13144 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013145#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013146 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013147#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013148 OS_GETPGID_METHODDEF
13149 OS_SETPGRP_METHODDEF
13150 OS_WAIT_METHODDEF
13151 OS_WAIT3_METHODDEF
13152 OS_WAIT4_METHODDEF
13153 OS_WAITID_METHODDEF
13154 OS_WAITPID_METHODDEF
13155 OS_GETSID_METHODDEF
13156 OS_SETSID_METHODDEF
13157 OS_SETPGID_METHODDEF
13158 OS_TCGETPGRP_METHODDEF
13159 OS_TCSETPGRP_METHODDEF
13160 OS_OPEN_METHODDEF
13161 OS_CLOSE_METHODDEF
13162 OS_CLOSERANGE_METHODDEF
13163 OS_DEVICE_ENCODING_METHODDEF
13164 OS_DUP_METHODDEF
13165 OS_DUP2_METHODDEF
13166 OS_LOCKF_METHODDEF
13167 OS_LSEEK_METHODDEF
13168 OS_READ_METHODDEF
13169 OS_READV_METHODDEF
13170 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013171 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013172 OS_WRITE_METHODDEF
13173 OS_WRITEV_METHODDEF
13174 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013175 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013176#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013177 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013178 posix_sendfile__doc__},
13179#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013180 OS_FSTAT_METHODDEF
13181 OS_ISATTY_METHODDEF
13182 OS_PIPE_METHODDEF
13183 OS_PIPE2_METHODDEF
13184 OS_MKFIFO_METHODDEF
13185 OS_MKNOD_METHODDEF
13186 OS_MAJOR_METHODDEF
13187 OS_MINOR_METHODDEF
13188 OS_MAKEDEV_METHODDEF
13189 OS_FTRUNCATE_METHODDEF
13190 OS_TRUNCATE_METHODDEF
13191 OS_POSIX_FALLOCATE_METHODDEF
13192 OS_POSIX_FADVISE_METHODDEF
13193 OS_PUTENV_METHODDEF
13194 OS_UNSETENV_METHODDEF
13195 OS_STRERROR_METHODDEF
13196 OS_FCHDIR_METHODDEF
13197 OS_FSYNC_METHODDEF
13198 OS_SYNC_METHODDEF
13199 OS_FDATASYNC_METHODDEF
13200 OS_WCOREDUMP_METHODDEF
13201 OS_WIFCONTINUED_METHODDEF
13202 OS_WIFSTOPPED_METHODDEF
13203 OS_WIFSIGNALED_METHODDEF
13204 OS_WIFEXITED_METHODDEF
13205 OS_WEXITSTATUS_METHODDEF
13206 OS_WTERMSIG_METHODDEF
13207 OS_WSTOPSIG_METHODDEF
13208 OS_FSTATVFS_METHODDEF
13209 OS_STATVFS_METHODDEF
13210 OS_CONFSTR_METHODDEF
13211 OS_SYSCONF_METHODDEF
13212 OS_FPATHCONF_METHODDEF
13213 OS_PATHCONF_METHODDEF
13214 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013215 OS__GETFULLPATHNAME_METHODDEF
13216 OS__ISDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013217 OS__GETDISKUSAGE_METHODDEF
13218 OS__GETFINALPATHNAME_METHODDEF
13219 OS__GETVOLUMEPATHNAME_METHODDEF
13220 OS_GETLOADAVG_METHODDEF
13221 OS_URANDOM_METHODDEF
13222 OS_SETRESUID_METHODDEF
13223 OS_SETRESGID_METHODDEF
13224 OS_GETRESUID_METHODDEF
13225 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013226
Larry Hastings2f936352014-08-05 14:04:04 +100013227 OS_GETXATTR_METHODDEF
13228 OS_SETXATTR_METHODDEF
13229 OS_REMOVEXATTR_METHODDEF
13230 OS_LISTXATTR_METHODDEF
13231
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013232#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13233 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13234#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013235 OS_CPU_COUNT_METHODDEF
13236 OS_GET_INHERITABLE_METHODDEF
13237 OS_SET_INHERITABLE_METHODDEF
13238 OS_GET_HANDLE_INHERITABLE_METHODDEF
13239 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013240#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013241 OS_GET_BLOCKING_METHODDEF
13242 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013243#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013244 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013245 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013246 OS_GETRANDOM_METHODDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000013247 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013248};
13249
13250
Brian Curtin52173d42010-12-02 18:29:18 +000013251#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
Brian Curtin3b4499c2010-12-28 14:31:47 +000013252static int
Brian Curtin52173d42010-12-02 18:29:18 +000013253enable_symlink()
13254{
13255 HANDLE tok;
13256 TOKEN_PRIVILEGES tok_priv;
13257 LUID luid;
Brian Curtin52173d42010-12-02 18:29:18 +000013258
13259 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &tok))
Brian Curtin3b4499c2010-12-28 14:31:47 +000013260 return 0;
Brian Curtin52173d42010-12-02 18:29:18 +000013261
13262 if (!LookupPrivilegeValue(NULL, SE_CREATE_SYMBOLIC_LINK_NAME, &luid))
Brian Curtin3b4499c2010-12-28 14:31:47 +000013263 return 0;
Brian Curtin52173d42010-12-02 18:29:18 +000013264
13265 tok_priv.PrivilegeCount = 1;
13266 tok_priv.Privileges[0].Luid = luid;
13267 tok_priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
13268
13269 if (!AdjustTokenPrivileges(tok, FALSE, &tok_priv,
13270 sizeof(TOKEN_PRIVILEGES),
13271 (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL))
Brian Curtin3b4499c2010-12-28 14:31:47 +000013272 return 0;
Brian Curtin52173d42010-12-02 18:29:18 +000013273
Brian Curtin3b4499c2010-12-28 14:31:47 +000013274 /* ERROR_NOT_ALL_ASSIGNED returned when the privilege can't be assigned. */
13275 return GetLastError() == ERROR_NOT_ALL_ASSIGNED ? 0 : 1;
Brian Curtin52173d42010-12-02 18:29:18 +000013276}
13277#endif /* defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
13278
Barry Warsaw4a342091996-12-19 23:50:02 +000013279static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013280all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013281{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013282#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013283 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013284#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013285#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013286 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013287#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013288#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013289 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013290#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013291#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013292 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013293#endif
Fred Drakec9680921999-12-13 16:37:25 +000013294#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013295 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013296#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013297#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013298 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013299#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013300#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013301 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013302#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013303#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013304 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013305#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013306#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013307 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013308#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013309#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013310 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013311#endif
13312#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013313 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013314#endif
13315#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013316 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013317#endif
13318#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013319 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013320#endif
13321#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013322 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013323#endif
13324#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013325 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013326#endif
13327#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013328 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013329#endif
13330#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013331 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013332#endif
13333#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013334 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013335#endif
13336#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013337 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013338#endif
13339#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013340 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013341#endif
13342#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013343 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013344#endif
13345#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013346 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013347#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013348#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013349 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013350#endif
13351#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013352 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013353#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013354#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013355 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013356#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013357#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013358 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013359#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013360#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013361#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013362 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013363#endif
13364#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013365 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013366#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013367#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013368#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013369 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013370#endif
13371#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013372 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013373#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013374#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013375 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013376#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013377#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013378 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013379#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013380#ifdef O_TMPFILE
13381 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13382#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013383#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013384 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013385#endif
13386#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013387 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013388#endif
13389#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013390 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013391#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013392#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013393 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013394#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013395#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013396 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013397#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013398
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013399
Jesus Cea94363612012-06-22 18:32:07 +020013400#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013401 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013402#endif
13403#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013404 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013405#endif
13406
Tim Peters5aa91602002-01-30 05:46:57 +000013407/* MS Windows */
13408#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013409 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013410 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013411#endif
13412#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013413 /* Optimize for short life (keep in memory). */
13414 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013415 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013416#endif
13417#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013418 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013419 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013420#endif
13421#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013422 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013423 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013424#endif
13425#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013426 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013427 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013428#endif
13429
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013430/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013431#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013432 /* Send a SIGIO signal whenever input or output
13433 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013434 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013435#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013436#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013437 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013438 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013439#endif
13440#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013441 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013442 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013443#endif
13444#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013445 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013446 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013447#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013448#ifdef O_NOLINKS
13449 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013450 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013451#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013452#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000013453 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013454 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013455#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000013456
Victor Stinner8c62be82010-05-06 00:08:46 +000013457 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013458#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013459 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013460#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013461#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013462 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013463#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013464#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013465 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013466#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013467#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013468 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013469#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013470#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013471 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013472#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013473#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013474 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013475#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013476#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013477 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013478#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013479#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013480 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013481#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013482#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013483 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013484#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013485#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013486 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013487#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013488#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013489 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013490#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013491#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013492 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013493#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013494#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013495 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013496#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013497#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013498 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013499#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013500#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013501 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013502#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013503#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013504 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013505#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013506#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013507 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013508#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013509
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000013510 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013511#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013512 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013513#endif /* ST_RDONLY */
13514#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013515 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013516#endif /* ST_NOSUID */
13517
doko@ubuntu.comca616a22013-12-08 15:23:07 +010013518 /* GNU extensions */
13519#ifdef ST_NODEV
13520 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
13521#endif /* ST_NODEV */
13522#ifdef ST_NOEXEC
13523 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
13524#endif /* ST_NOEXEC */
13525#ifdef ST_SYNCHRONOUS
13526 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
13527#endif /* ST_SYNCHRONOUS */
13528#ifdef ST_MANDLOCK
13529 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
13530#endif /* ST_MANDLOCK */
13531#ifdef ST_WRITE
13532 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
13533#endif /* ST_WRITE */
13534#ifdef ST_APPEND
13535 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
13536#endif /* ST_APPEND */
13537#ifdef ST_NOATIME
13538 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
13539#endif /* ST_NOATIME */
13540#ifdef ST_NODIRATIME
13541 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
13542#endif /* ST_NODIRATIME */
13543#ifdef ST_RELATIME
13544 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
13545#endif /* ST_RELATIME */
13546
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013547 /* FreeBSD sendfile() constants */
13548#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013549 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013550#endif
13551#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013552 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013553#endif
13554#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013555 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013556#endif
13557
Ross Lagerwall7807c352011-03-17 20:20:30 +020013558 /* constants for posix_fadvise */
13559#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013560 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013561#endif
13562#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013563 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013564#endif
13565#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013566 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013567#endif
13568#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013569 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013570#endif
13571#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013572 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013573#endif
13574#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013575 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013576#endif
13577
13578 /* constants for waitid */
13579#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013580 if (PyModule_AddIntMacro(m, P_PID)) return -1;
13581 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
13582 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013583#endif
13584#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013585 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013586#endif
13587#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013588 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013589#endif
13590#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013591 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013592#endif
13593#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013594 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013595#endif
13596#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013597 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013598#endif
13599#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013600 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013601#endif
13602#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013603 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013604#endif
13605
13606 /* constants for lockf */
13607#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013608 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013609#endif
13610#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013611 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013612#endif
13613#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013614 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013615#endif
13616#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013617 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013618#endif
13619
Pablo Galindo4defba32018-01-27 16:16:37 +000013620#ifdef RWF_DSYNC
13621 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
13622#endif
13623#ifdef RWF_HIPRI
13624 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
13625#endif
13626#ifdef RWF_SYNC
13627 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
13628#endif
13629#ifdef RWF_NOWAIT
13630 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
13631#endif
13632
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013633/* constants for posix_spawn */
13634#ifdef HAVE_POSIX_SPAWN
13635 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
13636 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
13637 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
13638#endif
13639
Guido van Rossum246bc171999-02-01 23:54:31 +000013640#ifdef HAVE_SPAWNV
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013641 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
13642 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
13643 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
13644 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
13645 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000013646#endif
13647
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013648#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070013649#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013650 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070013651#endif
13652#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013653 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070013654#endif
13655#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013656 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070013657#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013658#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080013659 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013660#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013661#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013662 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013663#endif
13664#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013665 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013666#endif
13667#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013668 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013669#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020013670#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013671 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020013672#endif
13673#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013674 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020013675#endif
13676#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013677 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020013678#endif
13679#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013680 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020013681#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013682#endif
13683
Benjamin Peterson9428d532011-09-14 11:45:52 -040013684#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013685 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
13686 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
13687 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040013688#endif
13689
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030013690#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013691 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020013692#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030013693#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013694 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020013695#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030013696#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013697 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020013698#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030013699#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013700 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020013701#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030013702#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013703 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020013704#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030013705#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013706 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020013707#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030013708#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013709 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020013710#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010013711#if HAVE_DECL_RTLD_MEMBER
13712 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
13713#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020013714
Victor Stinner9b1f4742016-09-06 16:18:52 -070013715#ifdef HAVE_GETRANDOM_SYSCALL
13716 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
13717 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
13718#endif
13719
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013720#if defined(__APPLE__)
13721 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
13722#endif
13723
Victor Stinner8c62be82010-05-06 00:08:46 +000013724 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000013725}
13726
13727
Martin v. Löwis1a214512008-06-11 05:26:20 +000013728static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000013729 PyModuleDef_HEAD_INIT,
13730 MODNAME,
13731 posix__doc__,
13732 -1,
13733 posix_methods,
13734 NULL,
13735 NULL,
13736 NULL,
13737 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +000013738};
13739
13740
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020013741static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070013742
13743#ifdef HAVE_FACCESSAT
13744 "HAVE_FACCESSAT",
13745#endif
13746
13747#ifdef HAVE_FCHDIR
13748 "HAVE_FCHDIR",
13749#endif
13750
13751#ifdef HAVE_FCHMOD
13752 "HAVE_FCHMOD",
13753#endif
13754
13755#ifdef HAVE_FCHMODAT
13756 "HAVE_FCHMODAT",
13757#endif
13758
13759#ifdef HAVE_FCHOWN
13760 "HAVE_FCHOWN",
13761#endif
13762
Larry Hastings00964ed2013-08-12 13:49:30 -040013763#ifdef HAVE_FCHOWNAT
13764 "HAVE_FCHOWNAT",
13765#endif
13766
Larry Hastings9cf065c2012-06-22 16:30:09 -070013767#ifdef HAVE_FEXECVE
13768 "HAVE_FEXECVE",
13769#endif
13770
13771#ifdef HAVE_FDOPENDIR
13772 "HAVE_FDOPENDIR",
13773#endif
13774
Georg Brandl306336b2012-06-24 12:55:33 +020013775#ifdef HAVE_FPATHCONF
13776 "HAVE_FPATHCONF",
13777#endif
13778
Larry Hastings9cf065c2012-06-22 16:30:09 -070013779#ifdef HAVE_FSTATAT
13780 "HAVE_FSTATAT",
13781#endif
13782
13783#ifdef HAVE_FSTATVFS
13784 "HAVE_FSTATVFS",
13785#endif
13786
Steve Dowerfe0a41a2015-03-20 19:50:46 -070013787#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020013788 "HAVE_FTRUNCATE",
13789#endif
13790
Larry Hastings9cf065c2012-06-22 16:30:09 -070013791#ifdef HAVE_FUTIMENS
13792 "HAVE_FUTIMENS",
13793#endif
13794
13795#ifdef HAVE_FUTIMES
13796 "HAVE_FUTIMES",
13797#endif
13798
13799#ifdef HAVE_FUTIMESAT
13800 "HAVE_FUTIMESAT",
13801#endif
13802
13803#ifdef HAVE_LINKAT
13804 "HAVE_LINKAT",
13805#endif
13806
13807#ifdef HAVE_LCHFLAGS
13808 "HAVE_LCHFLAGS",
13809#endif
13810
13811#ifdef HAVE_LCHMOD
13812 "HAVE_LCHMOD",
13813#endif
13814
13815#ifdef HAVE_LCHOWN
13816 "HAVE_LCHOWN",
13817#endif
13818
13819#ifdef HAVE_LSTAT
13820 "HAVE_LSTAT",
13821#endif
13822
13823#ifdef HAVE_LUTIMES
13824 "HAVE_LUTIMES",
13825#endif
13826
13827#ifdef HAVE_MKDIRAT
13828 "HAVE_MKDIRAT",
13829#endif
13830
13831#ifdef HAVE_MKFIFOAT
13832 "HAVE_MKFIFOAT",
13833#endif
13834
13835#ifdef HAVE_MKNODAT
13836 "HAVE_MKNODAT",
13837#endif
13838
13839#ifdef HAVE_OPENAT
13840 "HAVE_OPENAT",
13841#endif
13842
13843#ifdef HAVE_READLINKAT
13844 "HAVE_READLINKAT",
13845#endif
13846
13847#ifdef HAVE_RENAMEAT
13848 "HAVE_RENAMEAT",
13849#endif
13850
13851#ifdef HAVE_SYMLINKAT
13852 "HAVE_SYMLINKAT",
13853#endif
13854
13855#ifdef HAVE_UNLINKAT
13856 "HAVE_UNLINKAT",
13857#endif
13858
13859#ifdef HAVE_UTIMENSAT
13860 "HAVE_UTIMENSAT",
13861#endif
13862
13863#ifdef MS_WINDOWS
13864 "MS_WINDOWS",
13865#endif
13866
13867 NULL
13868};
13869
13870
Mark Hammondfe51c6d2002-08-02 02:27:13 +000013871PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000013872INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000013873{
Victor Stinner8c62be82010-05-06 00:08:46 +000013874 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070013875 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020013876 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000013877
Brian Curtin52173d42010-12-02 18:29:18 +000013878#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
Brian Curtin3b4499c2010-12-28 14:31:47 +000013879 win32_can_symlink = enable_symlink();
Brian Curtin52173d42010-12-02 18:29:18 +000013880#endif
13881
Victor Stinner8c62be82010-05-06 00:08:46 +000013882 m = PyModule_Create(&posixmodule);
13883 if (m == NULL)
13884 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000013885
Victor Stinner8c62be82010-05-06 00:08:46 +000013886 /* Initialize environ dictionary */
13887 v = convertenviron();
13888 Py_XINCREF(v);
13889 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
13890 return NULL;
13891 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000013892
Victor Stinner8c62be82010-05-06 00:08:46 +000013893 if (all_ins(m))
13894 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000013895
Victor Stinner8c62be82010-05-06 00:08:46 +000013896 if (setup_confname_tables(m))
13897 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000013898
Victor Stinner8c62be82010-05-06 00:08:46 +000013899 Py_INCREF(PyExc_OSError);
13900 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000013901
Guido van Rossumb3d39562000-01-31 18:41:26 +000013902#ifdef HAVE_PUTENV
Victor Stinner8c62be82010-05-06 00:08:46 +000013903 if (posix_putenv_garbage == NULL)
13904 posix_putenv_garbage = PyDict_New();
Guido van Rossumb3d39562000-01-31 18:41:26 +000013905#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +000013906
Victor Stinner8c62be82010-05-06 00:08:46 +000013907 if (!initialized) {
Ross Lagerwall7807c352011-03-17 20:20:30 +020013908#if defined(HAVE_WAITID) && !defined(__APPLE__)
13909 waitid_result_desc.name = MODNAME ".waitid_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013910 WaitidResultType = PyStructSequence_NewType(&waitid_result_desc);
13911 if (WaitidResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020013912 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013913 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020013914#endif
13915
Christian Heimes25827622013-10-12 01:27:08 +020013916 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
Victor Stinner8c62be82010-05-06 00:08:46 +000013917 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
13918 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
13919 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013920 StatResultType = PyStructSequence_NewType(&stat_result_desc);
13921 if (StatResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020013922 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013923 }
13924 structseq_new = StatResultType->tp_new;
13925 StatResultType->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013926
Christian Heimes25827622013-10-12 01:27:08 +020013927 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013928 StatVFSResultType = PyStructSequence_NewType(&statvfs_result_desc);
13929 if (StatVFSResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020013930 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013931 }
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000013932#ifdef NEED_TICKS_PER_SECOND
13933# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinner8c62be82010-05-06 00:08:46 +000013934 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000013935# elif defined(HZ)
Victor Stinner8c62be82010-05-06 00:08:46 +000013936 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000013937# else
Victor Stinner8c62be82010-05-06 00:08:46 +000013938 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000013939# endif
13940#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013941
William Orr81574b82018-10-01 22:19:56 -070013942#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013943 sched_param_desc.name = MODNAME ".sched_param";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013944 SchedParamType = PyStructSequence_NewType(&sched_param_desc);
13945 if (SchedParamType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020013946 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013947 }
13948 SchedParamType->tp_new = os_sched_param;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013949#endif
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013950
13951 /* initialize TerminalSize_info */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013952 TerminalSizeType = PyStructSequence_NewType(&TerminalSize_desc);
13953 if (TerminalSizeType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020013954 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013955 }
Victor Stinner6036e442015-03-08 01:58:04 +010013956
13957 /* initialize scandir types */
13958 if (PyType_Ready(&ScandirIteratorType) < 0)
13959 return NULL;
13960 if (PyType_Ready(&DirEntryType) < 0)
13961 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000013962 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020013963#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013964 Py_INCREF((PyObject*) WaitidResultType);
13965 PyModule_AddObject(m, "waitid_result", (PyObject*) WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +020013966#endif
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013967 Py_INCREF((PyObject*) StatResultType);
13968 PyModule_AddObject(m, "stat_result", (PyObject*) StatResultType);
13969 Py_INCREF((PyObject*) StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000013970 PyModule_AddObject(m, "statvfs_result",
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013971 (PyObject*) StatVFSResultType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050013972
13973#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013974 Py_INCREF(SchedParamType);
13975 PyModule_AddObject(m, "sched_param", (PyObject *)SchedParamType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050013976#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000013977
Larry Hastings605a62d2012-06-24 04:33:36 -070013978 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013979 TimesResultType = PyStructSequence_NewType(&times_result_desc);
13980 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020013981 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013982 }
13983 PyModule_AddObject(m, "times_result", (PyObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070013984
13985 uname_result_desc.name = MODNAME ".uname_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013986 UnameResultType = PyStructSequence_NewType(&uname_result_desc);
13987 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020013988 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080013989 }
13990 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070013991
Thomas Wouters477c8d52006-05-27 19:21:47 +000013992#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000013993 /*
13994 * Step 2 of weak-linking support on Mac OS X.
13995 *
13996 * The code below removes functions that are not available on the
13997 * currently active platform.
13998 *
13999 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014000 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014001 * OSX 10.4.
14002 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014003#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014004 if (fstatvfs == NULL) {
14005 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14006 return NULL;
14007 }
14008 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014009#endif /* HAVE_FSTATVFS */
14010
14011#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014012 if (statvfs == NULL) {
14013 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14014 return NULL;
14015 }
14016 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014017#endif /* HAVE_STATVFS */
14018
14019# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014020 if (lchown == NULL) {
14021 if (PyObject_DelAttrString(m, "lchown") == -1) {
14022 return NULL;
14023 }
14024 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014025#endif /* HAVE_LCHOWN */
14026
14027
14028#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014029
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014030 Py_INCREF(TerminalSizeType);
14031 PyModule_AddObject(m, "terminal_size", (PyObject*)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014032
Larry Hastings6fe20b32012-04-19 15:07:49 -070014033 billion = PyLong_FromLong(1000000000);
14034 if (!billion)
14035 return NULL;
14036
Larry Hastings9cf065c2012-06-22 16:30:09 -070014037 /* suppress "function not used" warnings */
14038 {
14039 int ignored;
14040 fd_specified("", -1);
14041 follow_symlinks_specified("", 1);
14042 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14043 dir_fd_converter(Py_None, &ignored);
14044 dir_fd_unavailable(Py_None, &ignored);
14045 }
14046
14047 /*
14048 * provide list of locally available functions
14049 * so os.py can populate support_* lists
14050 */
14051 list = PyList_New(0);
14052 if (!list)
14053 return NULL;
14054 for (trace = have_functions; *trace; trace++) {
14055 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14056 if (!unicode)
14057 return NULL;
14058 if (PyList_Append(list, unicode))
14059 return NULL;
14060 Py_DECREF(unicode);
14061 }
14062 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014063
14064 Py_INCREF((PyObject *) &DirEntryType);
Brett Cannona32c4d02016-06-24 14:14:44 -070014065 PyModule_AddObject(m, "DirEntry", (PyObject *)&DirEntryType);
Larry Hastings9cf065c2012-06-22 16:30:09 -070014066
14067 initialized = 1;
14068
Victor Stinner8c62be82010-05-06 00:08:46 +000014069 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014070}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014071
14072#ifdef __cplusplus
14073}
14074#endif