blob: 7588d3cde7166637fb6e2ac80354c3b32a842d37 [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"
Victor Stinnerd5d9e812019-05-13 12:35:37 +020028#ifdef MS_WINDOWS
29 /* include <windows.h> early to avoid conflict with pycore_condvar.h:
30
31 #define WIN32_LEAN_AND_MEAN
32 #include <windows.h>
33
34 FSCTL_GET_REPARSE_POINT is not exported with WIN32_LEAN_AND_MEAN. */
35# include <windows.h>
36#endif
37
38#include "pycore_ceval.h" /* _PyEval_ReInitThreads() */
39#include "pycore_pystate.h" /* _PyRuntime */
Antoine Pitrou346cbd32017-05-27 17:50:54 +020040#include "pythread.h"
Victor Stinner6036e442015-03-08 01:58:04 +010041#include "structmember.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020042#ifndef MS_WINDOWS
Victor Stinnerd5d9e812019-05-13 12:35:37 +020043# include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010044#else
Victor Stinnerd5d9e812019-05-13 12:35:37 +020045# include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020046#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000047
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020048/* On android API level 21, 'AT_EACCESS' is not declared although
49 * HAVE_FACCESSAT is defined. */
50#ifdef __ANDROID__
51#undef HAVE_FACCESSAT
52#endif
53
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000054#include <stdio.h> /* needed for ctermid() */
55
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056#ifdef __cplusplus
57extern "C" {
58#endif
59
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000060PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000061"This module provides access to operating system functionality that is\n\
62standardized by the C Standard and the POSIX standard (a thinly\n\
63disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000064corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000066
Ross Lagerwall4d076da2011-03-18 06:56:53 +020067#ifdef HAVE_SYS_UIO_H
68#include <sys/uio.h>
69#endif
70
Christian Heimes75b96182017-09-05 15:53:09 +020071#ifdef HAVE_SYS_SYSMACROS_H
72/* GNU C Library: major(), minor(), makedev() */
73#include <sys/sysmacros.h>
74#endif
75
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000077#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#endif /* HAVE_SYS_TYPES_H */
79
80#ifdef HAVE_SYS_STAT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000081#include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000083
Guido van Rossum36bc6801995-06-14 22:54:23 +000084#ifdef HAVE_SYS_WAIT_H
Victor Stinner8c62be82010-05-06 00:08:46 +000085#include <sys/wait.h> /* For WNOHANG */
Guido van Rossum36bc6801995-06-14 22:54:23 +000086#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000087
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088#ifdef HAVE_SIGNAL_H
Guido van Rossuma376cc51996-12-05 23:43:35 +000089#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000091
Guido van Rossumb6775db1994-08-01 11:34:53 +000092#ifdef HAVE_FCNTL_H
93#include <fcntl.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +000094#endif /* HAVE_FCNTL_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +000095
Guido van Rossuma6535fd2001-10-18 19:44:10 +000096#ifdef HAVE_GRP_H
97#include <grp.h>
98#endif
99
Barry Warsaw5676bd12003-01-07 20:57:09 +0000100#ifdef HAVE_SYSEXITS_H
101#include <sysexits.h>
102#endif /* HAVE_SYSEXITS_H */
103
Anthony Baxter8a560de2004-10-13 15:30:56 +0000104#ifdef HAVE_SYS_LOADAVG_H
105#include <sys/loadavg.h>
106#endif
107
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000108#ifdef HAVE_SYS_SENDFILE_H
109#include <sys/sendfile.h>
110#endif
111
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200112#if defined(__APPLE__)
113#include <copyfile.h>
114#endif
115
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500116#ifdef HAVE_SCHED_H
117#include <sched.h>
118#endif
119
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500120#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500121#undef HAVE_SCHED_SETAFFINITY
122#endif
123
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200124#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Benjamin Peterson9428d532011-09-14 11:45:52 -0400125#define USE_XATTRS
126#endif
127
128#ifdef USE_XATTRS
Benjamin Petersonb77fe172011-09-13 17:20:47 -0400129#include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400130#endif
131
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000132#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
133#ifdef HAVE_SYS_SOCKET_H
134#include <sys/socket.h>
135#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000136#endif
137
Victor Stinner8b905bd2011-10-25 13:34:04 +0200138#ifdef HAVE_DLFCN_H
139#include <dlfcn.h>
140#endif
141
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200142#ifdef __hpux
143#include <sys/mpctl.h>
144#endif
145
146#if defined(__DragonFly__) || \
147 defined(__OpenBSD__) || \
148 defined(__FreeBSD__) || \
149 defined(__NetBSD__) || \
150 defined(__APPLE__)
151#include <sys/sysctl.h>
152#endif
153
Victor Stinner9b1f4742016-09-06 16:18:52 -0700154#ifdef HAVE_LINUX_RANDOM_H
155# include <linux/random.h>
156#endif
157#ifdef HAVE_GETRANDOM_SYSCALL
158# include <sys/syscall.h>
159#endif
160
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100161#if defined(MS_WINDOWS)
162# define TERMSIZE_USE_CONIO
163#elif defined(HAVE_SYS_IOCTL_H)
164# include <sys/ioctl.h>
165# if defined(HAVE_TERMIOS_H)
166# include <termios.h>
167# endif
168# if defined(TIOCGWINSZ)
169# define TERMSIZE_USE_IOCTL
170# endif
171#endif /* MS_WINDOWS */
172
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000173/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000174/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000175#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000176#define HAVE_OPENDIR 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000177#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000178#include <process.h>
179#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000180#ifdef _MSC_VER /* Microsoft compiler */
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000181#define HAVE_GETPPID 1
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000182#define HAVE_GETLOGIN 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000183#define HAVE_SPAWNV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000184#define HAVE_EXECV 1
Steve Dowercc16be82016-09-08 10:35:16 -0700185#define HAVE_WSPAWNV 1
186#define HAVE_WEXECV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000187#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000188#define HAVE_SYSTEM 1
189#define HAVE_CWAIT 1
190#define HAVE_FSYNC 1
Tim Peters11b23062003-04-23 02:39:17 +0000191#define fsync _commit
Andrew MacIntyre6c73af22002-03-03 03:07:07 +0000192#else
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000193/* Unix functions that the configure script doesn't check for */
pxinwrf2d7ac72019-05-21 18:46:37 +0800194#ifndef __VXWORKS__
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000195#define HAVE_EXECV 1
196#define HAVE_FORK 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000197#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
Guido van Rossum2242f2f2001-04-11 20:58:20 +0000198#define HAVE_FORK1 1
199#endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800200#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000201#define HAVE_GETEGID 1
202#define HAVE_GETEUID 1
203#define HAVE_GETGID 1
204#define HAVE_GETPPID 1
205#define HAVE_GETUID 1
206#define HAVE_KILL 1
207#define HAVE_OPENDIR 1
208#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000209#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000210#define HAVE_WAIT 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000211#define HAVE_TTYNAME 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000212#endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000213#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000214
Victor Stinnera2f7c002012-02-08 03:36:25 +0100215
Larry Hastings61272b72014-01-07 12:41:53 -0800216/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000217# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800218module os
Larry Hastings61272b72014-01-07 12:41:53 -0800219[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000220/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100221
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000222#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000223
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000224#if defined(__sgi)&&_COMPILER_VERSION>=700
225/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
226 (default) */
227extern char *ctermid_r(char *);
228#endif
229
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000230#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000231
pxinwrf2d7ac72019-05-21 18:46:37 +0800232#if defined(__VXWORKS__)
233#include <vxCpuLib.h>
234#include <rtpLib.h>
235#include <wait.h>
236#include <taskLib.h>
237#ifndef _P_WAIT
238#define _P_WAIT 0
239#define _P_NOWAIT 1
240#define _P_NOWAITO 1
241#endif
242#endif /* __VXWORKS__ */
243
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000244#ifdef HAVE_POSIX_SPAWN
245#include <spawn.h>
246#endif
247
Guido van Rossumb6775db1994-08-01 11:34:53 +0000248#ifdef HAVE_UTIME_H
249#include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000250#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000251
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000252#ifdef HAVE_SYS_UTIME_H
253#include <sys/utime.h>
254#define HAVE_UTIME_H /* pretend we do for the rest of this file */
255#endif /* HAVE_SYS_UTIME_H */
256
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257#ifdef HAVE_SYS_TIMES_H
258#include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000259#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260
261#ifdef HAVE_SYS_PARAM_H
262#include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000263#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000264
265#ifdef HAVE_SYS_UTSNAME_H
266#include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000267#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000268
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000269#ifdef HAVE_DIRENT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270#include <dirent.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000271#define NAMLEN(dirent) strlen((dirent)->d_name)
272#else
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000273#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000274#include <direct.h>
275#define NAMLEN(dirent) strlen((dirent)->d_name)
276#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000277#define dirent direct
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000278#define NAMLEN(dirent) (dirent)->d_namlen
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000279#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000280#ifdef HAVE_SYS_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000281#include <sys/ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000282#endif
283#ifdef HAVE_SYS_DIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284#include <sys/dir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000285#endif
286#ifdef HAVE_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000287#include <ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000288#endif
289#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000290
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000291#ifdef _MSC_VER
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000292#ifdef HAVE_DIRECT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000293#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000294#endif
295#ifdef HAVE_IO_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000296#include <io.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000297#endif
298#ifdef HAVE_PROCESS_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000299#include <process.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000300#endif
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000301#ifndef IO_REPARSE_TAG_SYMLINK
Amaury Forgeot d'Arc844807e2010-08-16 22:16:51 +0000302#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000303#endif
Tim Golden0321cf22014-05-05 19:46:17 +0100304#ifndef IO_REPARSE_TAG_MOUNT_POINT
305#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
306#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000307#include "osdefs.h"
Kristján Valur Jónssonf64e6512009-04-13 10:16:14 +0000308#include <malloc.h>
Guido van Rossumb6775db1994-08-01 11:34:53 +0000309#include <windows.h>
Victor Stinner8c62be82010-05-06 00:08:46 +0000310#include <shellapi.h> /* for ShellExecute() */
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000311#include <lmcons.h> /* for UNLEN */
Brian Curtin52173d42010-12-02 18:29:18 +0000312#define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000313#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314
Tim Petersbc2e10e2002-03-03 23:17:02 +0000315#ifndef MAXPATHLEN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000316#if defined(PATH_MAX) && PATH_MAX > 1024
317#define MAXPATHLEN PATH_MAX
318#else
Tim Petersbc2e10e2002-03-03 23:17:02 +0000319#define MAXPATHLEN 1024
Thomas Wouters477c8d52006-05-27 19:21:47 +0000320#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000321#endif /* MAXPATHLEN */
322
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000323#ifdef UNION_WAIT
324/* Emulate some macros on systems that have a union instead of macros */
325
326#ifndef WIFEXITED
327#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
328#endif
329
330#ifndef WEXITSTATUS
331#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
332#endif
333
334#ifndef WTERMSIG
335#define WTERMSIG(u_wait) ((u_wait).w_termsig)
336#endif
337
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338#define WAIT_TYPE union wait
339#define WAIT_STATUS_INT(s) (s.w_status)
340
341#else /* !UNION_WAIT */
342#define WAIT_TYPE int
343#define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000344#endif /* UNION_WAIT */
345
Greg Wardb48bc172000-03-01 21:51:56 +0000346/* Don't use the "_r" form if we don't need it (also, won't have a
347 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200348#if defined(HAVE_CTERMID_R)
Greg Wardb48bc172000-03-01 21:51:56 +0000349#define USE_CTERMID_R
350#endif
351
Fred Drake699f3522000-06-29 21:12:41 +0000352/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000353#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000354#undef FSTAT
355#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200356#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +0000357# define STAT win32_stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700358# define LSTAT win32_lstat
Victor Stinnere134a7f2015-03-30 10:09:31 +0200359# define FSTAT _Py_fstat_noraise
Steve Dowerf2f373f2015-02-21 08:44:05 -0800360# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000361#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000362# define STAT stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700363# define LSTAT lstat
Victor Stinner8c62be82010-05-06 00:08:46 +0000364# define FSTAT fstat
365# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000366#endif
367
Tim Peters11b23062003-04-23 02:39:17 +0000368#if defined(MAJOR_IN_MKDEV)
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000369#include <sys/mkdev.h>
370#else
371#if defined(MAJOR_IN_SYSMACROS)
372#include <sys/sysmacros.h>
373#endif
Neal Norwitz3d949422002-04-20 13:46:43 +0000374#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
375#include <sys/mkdev.h>
376#endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000377#endif
Fred Drake699f3522000-06-29 21:12:41 +0000378
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200379#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +0100380#define INITFUNC PyInit_nt
381#define MODNAME "nt"
382#else
383#define INITFUNC PyInit_posix
384#define MODNAME "posix"
385#endif
386
jcea6c51d512018-01-28 14:00:08 +0100387#if defined(__sun)
388/* Something to implement in autoconf, not present in autoconf 2.69 */
389#define HAVE_STRUCT_STAT_ST_FSTYPE 1
390#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200391
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600392/* memfd_create is either defined in sys/mman.h or sys/memfd.h
393 * linux/memfd.h defines additional flags
394 */
395#ifdef HAVE_SYS_MMAN_H
396#include <sys/mman.h>
397#endif
398#ifdef HAVE_SYS_MEMFD_H
399#include <sys/memfd.h>
400#endif
401#ifdef HAVE_LINUX_MEMFD_H
402#include <linux/memfd.h>
403#endif
404
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800405#ifdef _Py_MEMORY_SANITIZER
406# include <sanitizer/msan_interface.h>
407#endif
408
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200409#ifdef HAVE_FORK
410static void
411run_at_forkers(PyObject *lst, int reverse)
412{
413 Py_ssize_t i;
414 PyObject *cpy;
415
416 if (lst != NULL) {
417 assert(PyList_CheckExact(lst));
418
419 /* Use a list copy in case register_at_fork() is called from
420 * one of the callbacks.
421 */
422 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
423 if (cpy == NULL)
424 PyErr_WriteUnraisable(lst);
425 else {
426 if (reverse)
427 PyList_Reverse(cpy);
428 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
429 PyObject *func, *res;
430 func = PyList_GET_ITEM(cpy, i);
431 res = PyObject_CallObject(func, NULL);
432 if (res == NULL)
433 PyErr_WriteUnraisable(func);
434 else
435 Py_DECREF(res);
436 }
437 Py_DECREF(cpy);
438 }
439 }
440}
441
442void
443PyOS_BeforeFork(void)
444{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200445 run_at_forkers(_PyInterpreterState_Get()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200446
447 _PyImport_AcquireLock();
448}
449
450void
451PyOS_AfterFork_Parent(void)
452{
453 if (_PyImport_ReleaseLock() <= 0)
454 Py_FatalError("failed releasing import lock after fork");
455
Victor Stinnercaba55b2018-08-03 15:33:52 +0200456 run_at_forkers(_PyInterpreterState_Get()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200457}
458
459void
460PyOS_AfterFork_Child(void)
461{
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200462 _PyRuntimeState *runtime = &_PyRuntime;
463 _PyGILState_Reinit(runtime);
Victor Stinnerd5d9e812019-05-13 12:35:37 +0200464 _PyEval_ReInitThreads(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200465 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200466 _PySignal_AfterFork();
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200467 _PyRuntimeState_ReInitThreads(runtime);
Victor Stinnerb49858b2019-05-24 15:20:23 +0200468 _PyInterpreterState_DeleteExceptMain(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200469
Victor Stinnercaba55b2018-08-03 15:33:52 +0200470 run_at_forkers(_PyInterpreterState_Get()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200471}
472
473static int
474register_at_forker(PyObject **lst, PyObject *func)
475{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700476 if (func == NULL) /* nothing to register? do nothing. */
477 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200478 if (*lst == NULL) {
479 *lst = PyList_New(0);
480 if (*lst == NULL)
481 return -1;
482 }
483 return PyList_Append(*lst, func);
484}
485#endif
486
487/* Legacy wrapper */
488void
489PyOS_AfterFork(void)
490{
491#ifdef HAVE_FORK
492 PyOS_AfterFork_Child();
493#endif
494}
495
496
Victor Stinner6036e442015-03-08 01:58:04 +0100497#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200498/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700499void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
500void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200501 ULONG, struct _Py_stat_struct *);
502#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700503
504#ifdef MS_WINDOWS
505static int
506win32_warn_bytes_api()
507{
508 return PyErr_WarnEx(PyExc_DeprecationWarning,
509 "The Windows bytes API has been deprecated, "
510 "use Unicode filenames instead",
511 1);
512}
513#endif
514
515
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200516#ifndef MS_WINDOWS
517PyObject *
518_PyLong_FromUid(uid_t uid)
519{
520 if (uid == (uid_t)-1)
521 return PyLong_FromLong(-1);
522 return PyLong_FromUnsignedLong(uid);
523}
524
525PyObject *
526_PyLong_FromGid(gid_t gid)
527{
528 if (gid == (gid_t)-1)
529 return PyLong_FromLong(-1);
530 return PyLong_FromUnsignedLong(gid);
531}
532
533int
534_Py_Uid_Converter(PyObject *obj, void *p)
535{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700536 uid_t uid;
537 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200538 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200539 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700540 unsigned long uresult;
541
542 index = PyNumber_Index(obj);
543 if (index == NULL) {
544 PyErr_Format(PyExc_TypeError,
545 "uid should be integer, not %.200s",
546 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200547 return 0;
548 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700549
550 /*
551 * Handling uid_t is complicated for two reasons:
552 * * Although uid_t is (always?) unsigned, it still
553 * accepts -1.
554 * * We don't know its size in advance--it may be
555 * bigger than an int, or it may be smaller than
556 * a long.
557 *
558 * So a bit of defensive programming is in order.
559 * Start with interpreting the value passed
560 * in as a signed long and see if it works.
561 */
562
563 result = PyLong_AsLongAndOverflow(index, &overflow);
564
565 if (!overflow) {
566 uid = (uid_t)result;
567
568 if (result == -1) {
569 if (PyErr_Occurred())
570 goto fail;
571 /* It's a legitimate -1, we're done. */
572 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200573 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700574
575 /* Any other negative number is disallowed. */
576 if (result < 0)
577 goto underflow;
578
579 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200580 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700581 (long)uid != result)
582 goto underflow;
583 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200584 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700585
586 if (overflow < 0)
587 goto underflow;
588
589 /*
590 * Okay, the value overflowed a signed long. If it
591 * fits in an *unsigned* long, it may still be okay,
592 * as uid_t may be unsigned long on this platform.
593 */
594 uresult = PyLong_AsUnsignedLong(index);
595 if (PyErr_Occurred()) {
596 if (PyErr_ExceptionMatches(PyExc_OverflowError))
597 goto overflow;
598 goto fail;
599 }
600
601 uid = (uid_t)uresult;
602
603 /*
604 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
605 * but this value would get interpreted as (uid_t)-1 by chown
606 * and its siblings. That's not what the user meant! So we
607 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100608 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700609 */
610 if (uid == (uid_t)-1)
611 goto overflow;
612
613 /* Ensure the value wasn't truncated. */
614 if (sizeof(uid_t) < sizeof(long) &&
615 (unsigned long)uid != uresult)
616 goto overflow;
617 /* fallthrough */
618
619success:
620 Py_DECREF(index);
621 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200622 return 1;
623
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700624underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200625 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700626 "uid is less than minimum");
627 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200628
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700629overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200630 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700631 "uid is greater than maximum");
632 /* fallthrough */
633
634fail:
635 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200636 return 0;
637}
638
639int
640_Py_Gid_Converter(PyObject *obj, void *p)
641{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700642 gid_t gid;
643 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200644 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200645 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700646 unsigned long uresult;
647
648 index = PyNumber_Index(obj);
649 if (index == NULL) {
650 PyErr_Format(PyExc_TypeError,
651 "gid should be integer, not %.200s",
652 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200653 return 0;
654 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700655
656 /*
657 * Handling gid_t is complicated for two reasons:
658 * * Although gid_t is (always?) unsigned, it still
659 * accepts -1.
660 * * We don't know its size in advance--it may be
661 * bigger than an int, or it may be smaller than
662 * a long.
663 *
664 * So a bit of defensive programming is in order.
665 * Start with interpreting the value passed
666 * in as a signed long and see if it works.
667 */
668
669 result = PyLong_AsLongAndOverflow(index, &overflow);
670
671 if (!overflow) {
672 gid = (gid_t)result;
673
674 if (result == -1) {
675 if (PyErr_Occurred())
676 goto fail;
677 /* It's a legitimate -1, we're done. */
678 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200679 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700680
681 /* Any other negative number is disallowed. */
682 if (result < 0) {
683 goto underflow;
684 }
685
686 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200687 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700688 (long)gid != result)
689 goto underflow;
690 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200691 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700692
693 if (overflow < 0)
694 goto underflow;
695
696 /*
697 * Okay, the value overflowed a signed long. If it
698 * fits in an *unsigned* long, it may still be okay,
699 * as gid_t may be unsigned long on this platform.
700 */
701 uresult = PyLong_AsUnsignedLong(index);
702 if (PyErr_Occurred()) {
703 if (PyErr_ExceptionMatches(PyExc_OverflowError))
704 goto overflow;
705 goto fail;
706 }
707
708 gid = (gid_t)uresult;
709
710 /*
711 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
712 * but this value would get interpreted as (gid_t)-1 by chown
713 * and its siblings. That's not what the user meant! So we
714 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100715 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700716 */
717 if (gid == (gid_t)-1)
718 goto overflow;
719
720 /* Ensure the value wasn't truncated. */
721 if (sizeof(gid_t) < sizeof(long) &&
722 (unsigned long)gid != uresult)
723 goto overflow;
724 /* fallthrough */
725
726success:
727 Py_DECREF(index);
728 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200729 return 1;
730
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700731underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200732 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700733 "gid is less than minimum");
734 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200735
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700736overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200737 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700738 "gid is greater than maximum");
739 /* fallthrough */
740
741fail:
742 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200743 return 0;
744}
745#endif /* MS_WINDOWS */
746
747
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700748#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800749
750
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200751#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
752static int
753_Py_Dev_Converter(PyObject *obj, void *p)
754{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200755 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200756 if (PyErr_Occurred())
757 return 0;
758 return 1;
759}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800760#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200761
762
Larry Hastings9cf065c2012-06-22 16:30:09 -0700763#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400764/*
765 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
766 * without the int cast, the value gets interpreted as uint (4291925331),
767 * which doesn't play nicely with all the initializer lines in this file that
768 * look like this:
769 * int dir_fd = DEFAULT_DIR_FD;
770 */
771#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700772#else
773#define DEFAULT_DIR_FD (-100)
774#endif
775
776static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300777_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200778{
779 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700780 long long_value;
781
782 PyObject *index = PyNumber_Index(o);
783 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700784 return 0;
785 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700786
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300787 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700788 long_value = PyLong_AsLongAndOverflow(index, &overflow);
789 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300790 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200791 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700792 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700793 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700794 return 0;
795 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200796 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700797 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700798 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700799 return 0;
800 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700801
Larry Hastings9cf065c2012-06-22 16:30:09 -0700802 *p = (int)long_value;
803 return 1;
804}
805
806static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200807dir_fd_converter(PyObject *o, void *p)
808{
809 if (o == Py_None) {
810 *(int *)p = DEFAULT_DIR_FD;
811 return 1;
812 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300813 else if (PyIndex_Check(o)) {
814 return _fd_converter(o, (int *)p);
815 }
816 else {
817 PyErr_Format(PyExc_TypeError,
818 "argument should be integer or None, not %.200s",
819 Py_TYPE(o)->tp_name);
820 return 0;
821 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700822}
823
824
Larry Hastings9cf065c2012-06-22 16:30:09 -0700825/*
826 * A PyArg_ParseTuple "converter" function
827 * that handles filesystem paths in the manner
828 * preferred by the os module.
829 *
830 * path_converter accepts (Unicode) strings and their
831 * subclasses, and bytes and their subclasses. What
832 * it does with the argument depends on the platform:
833 *
834 * * On Windows, if we get a (Unicode) string we
835 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700836 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700837 *
838 * * On all other platforms, strings are encoded
839 * to bytes using PyUnicode_FSConverter, then we
840 * extract the char * from the bytes object and
841 * return that.
842 *
843 * path_converter also optionally accepts signed
844 * integers (representing open file descriptors) instead
845 * of path strings.
846 *
847 * Input fields:
848 * path.nullable
849 * If nonzero, the path is permitted to be None.
850 * path.allow_fd
851 * If nonzero, the path is permitted to be a file handle
852 * (a signed int) instead of a string.
853 * path.function_name
854 * If non-NULL, path_converter will use that as the name
855 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700856 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700857 * path.argument_name
858 * If non-NULL, path_converter will use that as the name
859 * of the parameter in error messages.
860 * (If path.argument_name is NULL it uses "path".)
861 *
862 * Output fields:
863 * path.wide
864 * Points to the path if it was expressed as Unicode
865 * and was not encoded. (Only used on Windows.)
866 * path.narrow
867 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700868 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000869 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700870 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700871 * path.fd
872 * Contains a file descriptor if path.accept_fd was true
873 * and the caller provided a signed integer instead of any
874 * sort of string.
875 *
876 * WARNING: if your "path" parameter is optional, and is
877 * unspecified, path_converter will never get called.
878 * So if you set allow_fd, you *MUST* initialize path.fd = -1
879 * yourself!
880 * path.length
881 * The length of the path in characters, if specified as
882 * a string.
883 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800884 * The original object passed in (if get a PathLike object,
885 * the result of PyOS_FSPath() is treated as the original object).
886 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700887 * path.cleanup
888 * For internal use only. May point to a temporary object.
889 * (Pay no attention to the man behind the curtain.)
890 *
891 * At most one of path.wide or path.narrow will be non-NULL.
892 * If path was None and path.nullable was set,
893 * or if path was an integer and path.allow_fd was set,
894 * both path.wide and path.narrow will be NULL
895 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200896 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700897 * path_converter takes care to not write to the path_t
898 * unless it's successful. However it must reset the
899 * "cleanup" field each time it's called.
900 *
901 * Use as follows:
902 * path_t path;
903 * memset(&path, 0, sizeof(path));
904 * PyArg_ParseTuple(args, "O&", path_converter, &path);
905 * // ... use values from path ...
906 * path_cleanup(&path);
907 *
908 * (Note that if PyArg_Parse fails you don't need to call
909 * path_cleanup(). However it is safe to do so.)
910 */
911typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100912 const char *function_name;
913 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700914 int nullable;
915 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300916 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700917#ifdef MS_WINDOWS
918 BOOL narrow;
919#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300920 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700921#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700922 int fd;
923 Py_ssize_t length;
924 PyObject *object;
925 PyObject *cleanup;
926} path_t;
927
Steve Dowercc16be82016-09-08 10:35:16 -0700928#ifdef MS_WINDOWS
929#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
930 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
931#else
Larry Hastings2f936352014-08-05 14:04:04 +1000932#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
933 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700934#endif
Larry Hastings31826802013-10-19 00:09:25 -0700935
Larry Hastings9cf065c2012-06-22 16:30:09 -0700936static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800937path_cleanup(path_t *path)
938{
939 Py_CLEAR(path->object);
940 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700941}
942
943static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300944path_converter(PyObject *o, void *p)
945{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700946 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800947 PyObject *bytes = NULL;
948 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700949 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300950 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700951#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800952 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700953 const wchar_t *wide;
954#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700955
956#define FORMAT_EXCEPTION(exc, fmt) \
957 PyErr_Format(exc, "%s%s" fmt, \
958 path->function_name ? path->function_name : "", \
959 path->function_name ? ": " : "", \
960 path->argument_name ? path->argument_name : "path")
961
962 /* Py_CLEANUP_SUPPORTED support */
963 if (o == NULL) {
964 path_cleanup(path);
965 return 1;
966 }
967
Brett Cannon3f9183b2016-08-26 14:44:48 -0700968 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800969 path->object = path->cleanup = NULL;
970 /* path->object owns a reference to the original object */
971 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700972
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300973 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700974 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700975#ifdef MS_WINDOWS
976 path->narrow = FALSE;
977#else
Larry Hastings9cf065c2012-06-22 16:30:09 -0700978 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700979#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700980 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +0800981 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700982 }
983
Brett Cannon3f9183b2016-08-26 14:44:48 -0700984 /* Only call this here so that we don't treat the return value of
985 os.fspath() as an fd or buffer. */
986 is_index = path->allow_fd && PyIndex_Check(o);
987 is_buffer = PyObject_CheckBuffer(o);
988 is_bytes = PyBytes_Check(o);
989 is_unicode = PyUnicode_Check(o);
990
991 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
992 /* Inline PyOS_FSPath() for better error messages. */
993 _Py_IDENTIFIER(__fspath__);
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000994 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700995
996 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
997 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +0800998 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700999 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001000 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001001 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001002 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001003 goto error_exit;
1004 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001005 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001006 is_unicode = 1;
1007 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001008 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001009 is_bytes = 1;
1010 }
1011 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001012 PyErr_Format(PyExc_TypeError,
1013 "expected %.200s.__fspath__() to return str or bytes, "
1014 "not %.200s", Py_TYPE(o)->tp_name,
1015 Py_TYPE(res)->tp_name);
1016 Py_DECREF(res);
1017 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001018 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001019
1020 /* still owns a reference to the original object */
1021 Py_DECREF(o);
1022 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001023 }
1024
1025 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001026#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001027 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001028 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001029 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001030 }
Victor Stinner59799a82013-11-13 14:17:30 +01001031 if (length > 32767) {
1032 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001033 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001034 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001035 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001036 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001037 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001038 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001039
1040 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001041 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001042 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001043 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001044#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001045 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001046 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001047 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001048#endif
1049 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001050 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001051 bytes = o;
1052 Py_INCREF(bytes);
1053 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001054 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001055 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001056 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001057 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1058 "%s%s%s should be %s, not %.200s",
1059 path->function_name ? path->function_name : "",
1060 path->function_name ? ": " : "",
1061 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001062 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1063 "integer or None" :
1064 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1065 path->nullable ? "string, bytes, os.PathLike or None" :
1066 "string, bytes or os.PathLike",
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001067 Py_TYPE(o)->tp_name)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001068 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001069 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001070 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001071 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001072 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001073 }
1074 }
Steve Dowercc16be82016-09-08 10:35:16 -07001075 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001076 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001077 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001078 }
1079 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001080#ifdef MS_WINDOWS
1081 path->narrow = FALSE;
1082#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001083 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001084#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001085 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001086 }
1087 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001088 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001089 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1090 path->function_name ? path->function_name : "",
1091 path->function_name ? ": " : "",
1092 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001093 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1094 "integer or None" :
1095 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1096 path->nullable ? "string, bytes, os.PathLike or None" :
1097 "string, bytes or os.PathLike",
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001098 Py_TYPE(o)->tp_name);
Xiang Zhang04316c42017-01-08 23:26:57 +08001099 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001100 }
1101
Larry Hastings9cf065c2012-06-22 16:30:09 -07001102 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001103 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001104 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001105 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001106 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001107 }
1108
Steve Dowercc16be82016-09-08 10:35:16 -07001109#ifdef MS_WINDOWS
1110 wo = PyUnicode_DecodeFSDefaultAndSize(
1111 narrow,
1112 length
1113 );
1114 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001115 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001116 }
1117
Xiang Zhang04316c42017-01-08 23:26:57 +08001118 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001119 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001120 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001121 }
1122 if (length > 32767) {
1123 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001124 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001125 }
1126 if (wcslen(wide) != length) {
1127 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001128 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001129 }
1130 path->wide = wide;
1131 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001132 path->cleanup = wo;
1133 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001134#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001135 path->wide = NULL;
1136 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001137 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001138 /* Still a reference owned by path->object, don't have to
1139 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001140 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001141 }
1142 else {
1143 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001144 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001145#endif
1146 path->fd = -1;
1147
1148 success_exit:
1149 path->length = length;
1150 path->object = o;
1151 return Py_CLEANUP_SUPPORTED;
1152
1153 error_exit:
1154 Py_XDECREF(o);
1155 Py_XDECREF(bytes);
1156#ifdef MS_WINDOWS
1157 Py_XDECREF(wo);
1158#endif
1159 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001160}
1161
1162static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001163argument_unavailable_error(const char *function_name, const char *argument_name)
1164{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001165 PyErr_Format(PyExc_NotImplementedError,
1166 "%s%s%s unavailable on this platform",
1167 (function_name != NULL) ? function_name : "",
1168 (function_name != NULL) ? ": ": "",
1169 argument_name);
1170}
1171
1172static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001173dir_fd_unavailable(PyObject *o, void *p)
1174{
1175 int dir_fd;
1176 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001177 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001178 if (dir_fd != DEFAULT_DIR_FD) {
1179 argument_unavailable_error(NULL, "dir_fd");
1180 return 0;
1181 }
1182 *(int *)p = dir_fd;
1183 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001184}
1185
1186static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001187fd_specified(const char *function_name, int fd)
1188{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001189 if (fd == -1)
1190 return 0;
1191
1192 argument_unavailable_error(function_name, "fd");
1193 return 1;
1194}
1195
1196static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001197follow_symlinks_specified(const char *function_name, int follow_symlinks)
1198{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001199 if (follow_symlinks)
1200 return 0;
1201
1202 argument_unavailable_error(function_name, "follow_symlinks");
1203 return 1;
1204}
1205
1206static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001207path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1208{
Steve Dowercc16be82016-09-08 10:35:16 -07001209 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1210#ifndef MS_WINDOWS
1211 && !path->narrow
1212#endif
1213 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001214 PyErr_Format(PyExc_ValueError,
1215 "%s: can't specify dir_fd without matching path",
1216 function_name);
1217 return 1;
1218 }
1219 return 0;
1220}
1221
1222static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001223dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1224{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001225 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1226 PyErr_Format(PyExc_ValueError,
1227 "%s: can't specify both dir_fd and fd",
1228 function_name);
1229 return 1;
1230 }
1231 return 0;
1232}
1233
1234static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001235fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1236 int follow_symlinks)
1237{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001238 if ((fd > 0) && (!follow_symlinks)) {
1239 PyErr_Format(PyExc_ValueError,
1240 "%s: cannot use fd and follow_symlinks together",
1241 function_name);
1242 return 1;
1243 }
1244 return 0;
1245}
1246
1247static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001248dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1249 int follow_symlinks)
1250{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001251 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1252 PyErr_Format(PyExc_ValueError,
1253 "%s: cannot use dir_fd and follow_symlinks together",
1254 function_name);
1255 return 1;
1256 }
1257 return 0;
1258}
1259
Larry Hastings2f936352014-08-05 14:04:04 +10001260#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001261 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001262#else
Larry Hastings2f936352014-08-05 14:04:04 +10001263 typedef off_t Py_off_t;
1264#endif
1265
1266static int
1267Py_off_t_converter(PyObject *arg, void *addr)
1268{
1269#ifdef HAVE_LARGEFILE_SUPPORT
1270 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1271#else
1272 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001273#endif
1274 if (PyErr_Occurred())
1275 return 0;
1276 return 1;
1277}
Larry Hastings2f936352014-08-05 14:04:04 +10001278
1279static PyObject *
1280PyLong_FromPy_off_t(Py_off_t offset)
1281{
1282#ifdef HAVE_LARGEFILE_SUPPORT
1283 return PyLong_FromLongLong(offset);
1284#else
1285 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001286#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001287}
1288
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001289#ifdef HAVE_SIGSET_T
1290/* Convert an iterable of integers to a sigset.
1291 Return 1 on success, return 0 and raise an exception on error. */
1292int
1293_Py_Sigset_Converter(PyObject *obj, void *addr)
1294{
1295 sigset_t *mask = (sigset_t *)addr;
1296 PyObject *iterator, *item;
1297 long signum;
1298 int overflow;
1299
Rémi Lapeyref0900192019-05-04 01:30:53 +02001300 // The extra parens suppress the unreachable-code warning with clang on MacOS
1301 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001302 /* Probably only if mask == NULL. */
1303 PyErr_SetFromErrno(PyExc_OSError);
1304 return 0;
1305 }
1306
1307 iterator = PyObject_GetIter(obj);
1308 if (iterator == NULL) {
1309 return 0;
1310 }
1311
1312 while ((item = PyIter_Next(iterator)) != NULL) {
1313 signum = PyLong_AsLongAndOverflow(item, &overflow);
1314 Py_DECREF(item);
1315 if (signum <= 0 || signum >= NSIG) {
1316 if (overflow || signum != -1 || !PyErr_Occurred()) {
1317 PyErr_Format(PyExc_ValueError,
1318 "signal number %ld out of range", signum);
1319 }
1320 goto error;
1321 }
1322 if (sigaddset(mask, (int)signum)) {
1323 if (errno != EINVAL) {
1324 /* Probably impossible */
1325 PyErr_SetFromErrno(PyExc_OSError);
1326 goto error;
1327 }
1328 /* For backwards compatibility, allow idioms such as
1329 * `range(1, NSIG)` but warn about invalid signal numbers
1330 */
1331 const char msg[] =
1332 "invalid signal number %ld, please use valid_signals()";
1333 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1334 goto error;
1335 }
1336 }
1337 }
1338 if (!PyErr_Occurred()) {
1339 Py_DECREF(iterator);
1340 return 1;
1341 }
1342
1343error:
1344 Py_DECREF(iterator);
1345 return 0;
1346}
1347#endif /* HAVE_SIGSET_T */
1348
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001349#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001350
1351static int
Brian Curtind25aef52011-06-13 15:16:04 -05001352win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001353{
Martin Panter70214ad2016-08-04 02:38:59 +00001354 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1355 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001356 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001357
1358 if (0 == DeviceIoControl(
1359 reparse_point_handle,
1360 FSCTL_GET_REPARSE_POINT,
1361 NULL, 0, /* in buffer */
1362 target_buffer, sizeof(target_buffer),
1363 &n_bytes_returned,
1364 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001365 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001366
1367 if (reparse_tag)
1368 *reparse_tag = rdb->ReparseTag;
1369
Brian Curtind25aef52011-06-13 15:16:04 -05001370 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001371}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001372
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001373#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001374
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001375/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001376#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001377/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001378** environ directly, we must obtain it with _NSGetEnviron(). See also
1379** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001380*/
1381#include <crt_externs.h>
1382static char **environ;
pxinwrf2d7ac72019-05-21 18:46:37 +08001383#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001384extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001385#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001386
Barry Warsaw53699e91996-12-10 23:23:01 +00001387static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001388convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001389{
Victor Stinner8c62be82010-05-06 00:08:46 +00001390 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001391#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001392 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001393#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001394 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001395#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001396
Victor Stinner8c62be82010-05-06 00:08:46 +00001397 d = PyDict_New();
1398 if (d == NULL)
1399 return NULL;
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001400#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Victor Stinner8c62be82010-05-06 00:08:46 +00001401 if (environ == NULL)
1402 environ = *_NSGetEnviron();
1403#endif
1404#ifdef MS_WINDOWS
1405 /* _wenviron must be initialized in this way if the program is started
1406 through main() instead of wmain(). */
1407 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001408 e = _wenviron;
Victor Stinner8c62be82010-05-06 00:08:46 +00001409#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001410 e = environ;
1411#endif
1412 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001413 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001414 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001415 PyObject *k;
1416 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001417#ifdef MS_WINDOWS
1418 const wchar_t *p = wcschr(*e, L'=');
1419#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001420 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001421#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001422 if (p == NULL)
1423 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001424#ifdef MS_WINDOWS
1425 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1426#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001427 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001428#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001429 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001430 Py_DECREF(d);
1431 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001432 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001433#ifdef MS_WINDOWS
1434 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1435#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001436 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001437#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001438 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001439 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001440 Py_DECREF(d);
1441 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001442 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001443 if (PyDict_GetItemWithError(d, k) == NULL) {
1444 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1445 Py_DECREF(v);
1446 Py_DECREF(k);
1447 Py_DECREF(d);
1448 return NULL;
1449 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001450 }
1451 Py_DECREF(k);
1452 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001453 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001454 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001455}
1456
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001457/* Set a POSIX-specific error from errno, and return NULL */
1458
Barry Warsawd58d7641998-07-23 16:14:40 +00001459static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001460posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001461{
Victor Stinner8c62be82010-05-06 00:08:46 +00001462 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001463}
Mark Hammondef8b6542001-05-13 08:04:26 +00001464
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001465#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001466static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001467win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001468{
Victor Stinner8c62be82010-05-06 00:08:46 +00001469 /* XXX We should pass the function name along in the future.
1470 (winreg.c also wants to pass the function name.)
1471 This would however require an additional param to the
1472 Windows error object, which is non-trivial.
1473 */
1474 errno = GetLastError();
1475 if (filename)
1476 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1477 else
1478 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001479}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001480
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001481static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001482win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001483{
1484 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001485 if (filename)
1486 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001487 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001488 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001489 filename);
1490 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001491 return PyErr_SetFromWindowsErr(err);
1492}
1493
1494static PyObject *
1495win32_error_object(const char* function, PyObject* filename)
1496{
1497 errno = GetLastError();
1498 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001499}
1500
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001501#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001502
Larry Hastings9cf065c2012-06-22 16:30:09 -07001503static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001504posix_path_object_error(PyObject *path)
1505{
1506 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1507}
1508
1509static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001510path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001511{
1512#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001513 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1514 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001515#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001516 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001517#endif
1518}
1519
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001520static PyObject *
1521path_object_error2(PyObject *path, PyObject *path2)
1522{
1523#ifdef MS_WINDOWS
1524 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1525 PyExc_OSError, 0, path, path2);
1526#else
1527 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1528#endif
1529}
1530
1531static PyObject *
1532path_error(path_t *path)
1533{
1534 return path_object_error(path->object);
1535}
Larry Hastings31826802013-10-19 00:09:25 -07001536
Larry Hastingsb0827312014-02-09 22:05:19 -08001537static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001538posix_path_error(path_t *path)
1539{
1540 return posix_path_object_error(path->object);
1541}
1542
1543static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001544path_error2(path_t *path, path_t *path2)
1545{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001546 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001547}
1548
1549
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001550/* POSIX generic methods */
1551
Larry Hastings2f936352014-08-05 14:04:04 +10001552static int
1553fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001554{
Victor Stinner8c62be82010-05-06 00:08:46 +00001555 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001556 int *pointer = (int *)p;
1557 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001558 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001559 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001560 *pointer = fd;
1561 return 1;
1562}
1563
1564static PyObject *
1565posix_fildes_fd(int fd, int (*func)(int))
1566{
1567 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001568 int async_err = 0;
1569
1570 do {
1571 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001572 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001573 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001574 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001575 Py_END_ALLOW_THREADS
1576 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1577 if (res != 0)
1578 return (!async_err) ? posix_error() : NULL;
1579 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001580}
Guido van Rossum21142a01999-01-08 21:05:37 +00001581
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001582
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001583#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584/* This is a reimplementation of the C library's chdir function,
1585 but one that produces Win32 errors instead of DOS error codes.
1586 chdir is essentially a wrapper around SetCurrentDirectory; however,
1587 it also needs to set "magic" environment variables indicating
1588 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001589static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001590win32_wchdir(LPCWSTR path)
1591{
Victor Stinnered537822015-12-13 21:40:26 +01001592 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001593 int result;
1594 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001595
Victor Stinner8c62be82010-05-06 00:08:46 +00001596 if(!SetCurrentDirectoryW(path))
1597 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001598 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001599 if (!result)
1600 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001601 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001602 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001603 if (!new_path) {
1604 SetLastError(ERROR_OUTOFMEMORY);
1605 return FALSE;
1606 }
1607 result = GetCurrentDirectoryW(result, new_path);
1608 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001609 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001610 return FALSE;
1611 }
1612 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001613 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1614 wcsncmp(new_path, L"//", 2) == 0);
1615 if (!is_unc_like_path) {
1616 env[1] = new_path[0];
1617 result = SetEnvironmentVariableW(env, new_path);
1618 }
Victor Stinnered537822015-12-13 21:40:26 +01001619 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001620 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001621 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001622}
1623#endif
1624
Martin v. Löwis14694662006-02-03 12:54:16 +00001625#ifdef MS_WINDOWS
1626/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1627 - time stamps are restricted to second resolution
1628 - file modification times suffer from forth-and-back conversions between
1629 UTC and local time
1630 Therefore, we implement our own stat, based on the Win32 API directly.
1631*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001632#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001633#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001634
Victor Stinner6036e442015-03-08 01:58:04 +01001635static void
Steve Dowercc16be82016-09-08 10:35:16 -07001636find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1637 BY_HANDLE_FILE_INFORMATION *info,
1638 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001639{
1640 memset(info, 0, sizeof(*info));
1641 info->dwFileAttributes = pFileData->dwFileAttributes;
1642 info->ftCreationTime = pFileData->ftCreationTime;
1643 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1644 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1645 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1646 info->nFileSizeLow = pFileData->nFileSizeLow;
1647/* info->nNumberOfLinks = 1; */
1648 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1649 *reparse_tag = pFileData->dwReserved0;
1650 else
1651 *reparse_tag = 0;
1652}
1653
Guido van Rossumd8faa362007-04-27 19:54:29 +00001654static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001655attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001656{
Victor Stinner8c62be82010-05-06 00:08:46 +00001657 HANDLE hFindFile;
1658 WIN32_FIND_DATAW FileData;
1659 hFindFile = FindFirstFileW(pszFile, &FileData);
1660 if (hFindFile == INVALID_HANDLE_VALUE)
1661 return FALSE;
1662 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001663 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001664 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001665}
1666
Brian Curtind25aef52011-06-13 15:16:04 -05001667static BOOL
1668get_target_path(HANDLE hdl, wchar_t **target_path)
1669{
1670 int buf_size, result_length;
1671 wchar_t *buf;
1672
1673 /* We have a good handle to the target, use it to determine
1674 the target path name (then we'll call lstat on it). */
Steve Dower2ea51c92015-03-20 21:49:12 -07001675 buf_size = GetFinalPathNameByHandleW(hdl, 0, 0,
1676 VOLUME_NAME_DOS);
Brian Curtind25aef52011-06-13 15:16:04 -05001677 if(!buf_size)
1678 return FALSE;
1679
Victor Stinnerc36674a2016-03-16 14:30:16 +01001680 buf = (wchar_t *)PyMem_RawMalloc((buf_size + 1) * sizeof(wchar_t));
Brian Curtinc8be8402011-06-14 09:52:50 -05001681 if (!buf) {
1682 SetLastError(ERROR_OUTOFMEMORY);
1683 return FALSE;
1684 }
1685
Steve Dower2ea51c92015-03-20 21:49:12 -07001686 result_length = GetFinalPathNameByHandleW(hdl,
Brian Curtind25aef52011-06-13 15:16:04 -05001687 buf, buf_size, VOLUME_NAME_DOS);
1688
1689 if(!result_length) {
Victor Stinnerc36674a2016-03-16 14:30:16 +01001690 PyMem_RawFree(buf);
Brian Curtind25aef52011-06-13 15:16:04 -05001691 return FALSE;
1692 }
1693
Brian Curtind25aef52011-06-13 15:16:04 -05001694 buf[result_length] = 0;
1695
1696 *target_path = buf;
1697 return TRUE;
1698}
1699
1700static int
Steve Dowercc16be82016-09-08 10:35:16 -07001701win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001702 BOOL traverse)
1703{
Victor Stinner26de69d2011-06-17 15:15:38 +02001704 int code;
Brian Curtind25aef52011-06-13 15:16:04 -05001705 HANDLE hFile, hFile2;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001706 BY_HANDLE_FILE_INFORMATION info;
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001707 ULONG reparse_tag = 0;
Victor Stinner26de69d2011-06-17 15:15:38 +02001708 wchar_t *target_path;
Steve Dowercc16be82016-09-08 10:35:16 -07001709 const wchar_t *dot;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001710
Steve Dowercc16be82016-09-08 10:35:16 -07001711 hFile = CreateFileW(
Brian Curtinf5e76d02010-11-24 13:14:05 +00001712 path,
Brian Curtind25aef52011-06-13 15:16:04 -05001713 FILE_READ_ATTRIBUTES, /* desired access */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001714 0, /* share mode */
1715 NULL, /* security attributes */
1716 OPEN_EXISTING,
1717 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
Brian Curtind25aef52011-06-13 15:16:04 -05001718 /* FILE_FLAG_OPEN_REPARSE_POINT does not follow the symlink.
1719 Because of this, calls like GetFinalPathNameByHandle will return
R David Murrayfc069992013-12-13 20:52:19 -05001720 the symlink path again and not the actual final path. */
Brian Curtind25aef52011-06-13 15:16:04 -05001721 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|
1722 FILE_FLAG_OPEN_REPARSE_POINT,
Brian Curtinf5e76d02010-11-24 13:14:05 +00001723 NULL);
1724
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001725 if (hFile == INVALID_HANDLE_VALUE) {
Brian Curtinf5e76d02010-11-24 13:14:05 +00001726 /* Either the target doesn't exist, or we don't have access to
1727 get a handle to it. If the former, we need to return an error.
1728 If the latter, we can use attributes_from_dir. */
Berker Peksag0b4dc482016-09-17 15:49:59 +03001729 DWORD lastError = GetLastError();
1730 if (lastError != ERROR_ACCESS_DENIED &&
1731 lastError != ERROR_SHARING_VIOLATION)
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001732 return -1;
1733 /* Could not get attributes on open file. Fall back to
1734 reading the directory. */
1735 if (!attributes_from_dir(path, &info, &reparse_tag))
1736 /* Very strange. This should not fail now */
1737 return -1;
1738 if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1739 if (traverse) {
1740 /* Should traverse, but could not open reparse point handle */
Berker Peksag0b4dc482016-09-17 15:49:59 +03001741 SetLastError(lastError);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001742 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001743 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001744 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001745 } else {
1746 if (!GetFileInformationByHandle(hFile, &info)) {
1747 CloseHandle(hFile);
Brian Curtind25aef52011-06-13 15:16:04 -05001748 return -1;
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001749 }
1750 if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
Mark Becwarb82bfac2019-02-02 16:08:23 -05001751 if (!win32_get_reparse_tag(hFile, &reparse_tag)) {
1752 CloseHandle(hFile);
Brian Curtind25aef52011-06-13 15:16:04 -05001753 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001754 }
Brian Curtind25aef52011-06-13 15:16:04 -05001755 /* Close the outer open file handle now that we're about to
1756 reopen it with different flags. */
1757 if (!CloseHandle(hFile))
1758 return -1;
1759
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001760 if (traverse) {
Brian Curtind25aef52011-06-13 15:16:04 -05001761 /* In order to call GetFinalPathNameByHandle we need to open
1762 the file without the reparse handling flag set. */
Brian Curtind25aef52011-06-13 15:16:04 -05001763 hFile2 = CreateFileW(
1764 path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ,
1765 NULL, OPEN_EXISTING,
1766 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
1767 NULL);
1768 if (hFile2 == INVALID_HANDLE_VALUE)
1769 return -1;
1770
Mark Becwarb82bfac2019-02-02 16:08:23 -05001771 if (!get_target_path(hFile2, &target_path)) {
1772 CloseHandle(hFile2);
Brian Curtind25aef52011-06-13 15:16:04 -05001773 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001774 }
1775
1776 if (!CloseHandle(hFile2)) {
1777 return -1;
1778 }
Brian Curtind25aef52011-06-13 15:16:04 -05001779
Steve Dowercc16be82016-09-08 10:35:16 -07001780 code = win32_xstat_impl(target_path, result, FALSE);
Victor Stinnerc36674a2016-03-16 14:30:16 +01001781 PyMem_RawFree(target_path);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001782 return code;
1783 }
Hirokazu Yamamoto7ed117a2010-12-07 10:24:37 +00001784 } else
1785 CloseHandle(hFile);
Brian Curtinf5e76d02010-11-24 13:14:05 +00001786 }
Steve Dowera2af1a52015-02-21 10:04:10 -08001787 _Py_attribute_data_to_stat(&info, reparse_tag, result);
Brian Curtinf5e76d02010-11-24 13:14:05 +00001788
1789 /* Set S_IEXEC if it is an .exe, .bat, ... */
1790 dot = wcsrchr(path, '.');
1791 if (dot) {
1792 if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
1793 _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
1794 result->st_mode |= 0111;
1795 }
1796 return 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001797}
1798
1799static int
Steve Dowercc16be82016-09-08 10:35:16 -07001800win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001801{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001802 /* Protocol violation: we explicitly clear errno, instead of
1803 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001804 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001805 errno = 0;
1806 return code;
1807}
Brian Curtind25aef52011-06-13 15:16:04 -05001808/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001809
1810 In Posix, stat automatically traverses symlinks and returns the stat
1811 structure for the target. In Windows, the equivalent GetFileAttributes by
1812 default does not traverse symlinks and instead returns attributes for
1813 the symlink.
1814
1815 Therefore, win32_lstat will get the attributes traditionally, and
1816 win32_stat will first explicitly resolve the symlink target and then will
Steve Dowercc16be82016-09-08 10:35:16 -07001817 call win32_lstat on that result. */
Brian Curtind40e6f72010-07-08 21:39:08 +00001818
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001819static int
Steve Dowercc16be82016-09-08 10:35:16 -07001820win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001821{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001822 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001823}
1824
Victor Stinner8c62be82010-05-06 00:08:46 +00001825static int
Steve Dowercc16be82016-09-08 10:35:16 -07001826win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001827{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001828 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001829}
1830
Martin v. Löwis14694662006-02-03 12:54:16 +00001831#endif /* MS_WINDOWS */
1832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001833PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001834"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001835This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001836 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001837or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1838\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001839Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1840or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001841\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001842See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001843
1844static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001845 {"st_mode", "protection bits"},
1846 {"st_ino", "inode"},
1847 {"st_dev", "device"},
1848 {"st_nlink", "number of hard links"},
1849 {"st_uid", "user ID of owner"},
1850 {"st_gid", "group ID of owner"},
1851 {"st_size", "total size, in bytes"},
1852 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1853 {NULL, "integer time of last access"},
1854 {NULL, "integer time of last modification"},
1855 {NULL, "integer time of last change"},
1856 {"st_atime", "time of last access"},
1857 {"st_mtime", "time of last modification"},
1858 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001859 {"st_atime_ns", "time of last access in nanoseconds"},
1860 {"st_mtime_ns", "time of last modification in nanoseconds"},
1861 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001862#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001863 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001864#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001865#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001866 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001867#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001868#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001869 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001870#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001871#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001872 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001873#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001874#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001875 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001876#endif
1877#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001878 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001879#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001880#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1881 {"st_file_attributes", "Windows file attribute bits"},
1882#endif
jcea6c51d512018-01-28 14:00:08 +01001883#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1884 {"st_fstype", "Type of filesystem"},
1885#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001886 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001887};
1888
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001889#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001890#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001891#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001892#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001893#endif
1894
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001895#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001896#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1897#else
1898#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1899#endif
1900
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001901#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001902#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1903#else
1904#define ST_RDEV_IDX ST_BLOCKS_IDX
1905#endif
1906
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001907#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1908#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1909#else
1910#define ST_FLAGS_IDX ST_RDEV_IDX
1911#endif
1912
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001913#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001914#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001915#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001916#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001917#endif
1918
1919#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1920#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1921#else
1922#define ST_BIRTHTIME_IDX ST_GEN_IDX
1923#endif
1924
Zachary Ware63f277b2014-06-19 09:46:37 -05001925#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1926#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
1927#else
1928#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
1929#endif
1930
jcea6c51d512018-01-28 14:00:08 +01001931#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1932#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
1933#else
1934#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
1935#endif
1936
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001937static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001938 "stat_result", /* name */
1939 stat_result__doc__, /* doc */
1940 stat_result_fields,
1941 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001942};
1943
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001944PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001945"statvfs_result: Result from statvfs or fstatvfs.\n\n\
1946This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001947 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00001948or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001949\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001950See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001951
1952static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001953 {"f_bsize", },
1954 {"f_frsize", },
1955 {"f_blocks", },
1956 {"f_bfree", },
1957 {"f_bavail", },
1958 {"f_files", },
1959 {"f_ffree", },
1960 {"f_favail", },
1961 {"f_flag", },
1962 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01001963 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00001964 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001965};
1966
1967static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001968 "statvfs_result", /* name */
1969 statvfs_result__doc__, /* doc */
1970 statvfs_result_fields,
1971 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001972};
1973
Ross Lagerwall7807c352011-03-17 20:20:30 +02001974#if defined(HAVE_WAITID) && !defined(__APPLE__)
1975PyDoc_STRVAR(waitid_result__doc__,
1976"waitid_result: Result from waitid.\n\n\
1977This object may be accessed either as a tuple of\n\
1978 (si_pid, si_uid, si_signo, si_status, si_code),\n\
1979or via the attributes si_pid, si_uid, and so on.\n\
1980\n\
1981See os.waitid for more information.");
1982
1983static PyStructSequence_Field waitid_result_fields[] = {
1984 {"si_pid", },
1985 {"si_uid", },
1986 {"si_signo", },
1987 {"si_status", },
1988 {"si_code", },
1989 {0}
1990};
1991
1992static PyStructSequence_Desc waitid_result_desc = {
1993 "waitid_result", /* name */
1994 waitid_result__doc__, /* doc */
1995 waitid_result_fields,
1996 5
1997};
Eddie Elizondo474eedf2018-11-13 04:09:31 -08001998static PyTypeObject* WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +02001999#endif
2000
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002001static int initialized;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002002static PyTypeObject* StatResultType;
2003static PyTypeObject* StatVFSResultType;
William Orr81574b82018-10-01 22:19:56 -07002004#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002005static PyTypeObject* SchedParamType;
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002006#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002007static newfunc structseq_new;
2008
2009static PyObject *
2010statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2011{
Victor Stinner8c62be82010-05-06 00:08:46 +00002012 PyStructSequence *result;
2013 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002014
Victor Stinner8c62be82010-05-06 00:08:46 +00002015 result = (PyStructSequence*)structseq_new(type, args, kwds);
2016 if (!result)
2017 return NULL;
2018 /* If we have been initialized from a tuple,
2019 st_?time might be set to None. Initialize it
2020 from the int slots. */
2021 for (i = 7; i <= 9; i++) {
2022 if (result->ob_item[i+3] == Py_None) {
2023 Py_DECREF(Py_None);
2024 Py_INCREF(result->ob_item[i]);
2025 result->ob_item[i+3] = result->ob_item[i];
2026 }
2027 }
2028 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002029}
2030
2031
Larry Hastings6fe20b32012-04-19 15:07:49 -07002032static PyObject *billion = NULL;
2033
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002034static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002035fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002036{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002037 PyObject *s = _PyLong_FromTime_t(sec);
2038 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2039 PyObject *s_in_ns = NULL;
2040 PyObject *ns_total = NULL;
2041 PyObject *float_s = NULL;
2042
2043 if (!(s && ns_fractional))
2044 goto exit;
2045
2046 s_in_ns = PyNumber_Multiply(s, billion);
2047 if (!s_in_ns)
2048 goto exit;
2049
2050 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2051 if (!ns_total)
2052 goto exit;
2053
Victor Stinner01b5aab2017-10-24 02:02:00 -07002054 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2055 if (!float_s) {
2056 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002057 }
2058
2059 PyStructSequence_SET_ITEM(v, index, s);
2060 PyStructSequence_SET_ITEM(v, index+3, float_s);
2061 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2062 s = NULL;
2063 float_s = NULL;
2064 ns_total = NULL;
2065exit:
2066 Py_XDECREF(s);
2067 Py_XDECREF(ns_fractional);
2068 Py_XDECREF(s_in_ns);
2069 Py_XDECREF(ns_total);
2070 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002071}
2072
Tim Peters5aa91602002-01-30 05:46:57 +00002073/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002074 (used by posix_stat() and posix_fstat()) */
2075static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002076_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002077{
Victor Stinner8c62be82010-05-06 00:08:46 +00002078 unsigned long ansec, mnsec, cnsec;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002079 PyObject *v = PyStructSequence_New(StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002080 if (v == NULL)
2081 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002082
Victor Stinner8c62be82010-05-06 00:08:46 +00002083 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002084 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002085 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002086#ifdef MS_WINDOWS
2087 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002088#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002089 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002090#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002091 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002092#if defined(MS_WINDOWS)
2093 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2094 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2095#else
2096 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2097 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2098#endif
xdegaye50e86032017-05-22 11:15:08 +02002099 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2100 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002101
Martin v. Löwis14694662006-02-03 12:54:16 +00002102#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002103 ansec = st->st_atim.tv_nsec;
2104 mnsec = st->st_mtim.tv_nsec;
2105 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002106#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002107 ansec = st->st_atimespec.tv_nsec;
2108 mnsec = st->st_mtimespec.tv_nsec;
2109 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002110#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002111 ansec = st->st_atime_nsec;
2112 mnsec = st->st_mtime_nsec;
2113 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002114#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002115 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002116#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002117 fill_time(v, 7, st->st_atime, ansec);
2118 fill_time(v, 8, st->st_mtime, mnsec);
2119 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002120
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002121#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002122 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2123 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002124#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002125#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002126 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2127 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002128#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002129#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002130 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2131 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002132#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002133#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002134 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2135 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002136#endif
2137#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002138 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002139 PyObject *val;
2140 unsigned long bsec,bnsec;
2141 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002142#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002143 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002144#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002145 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002146#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002147 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002148 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2149 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002150 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002151#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002152#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002153 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2154 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002155#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002156#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2157 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2158 PyLong_FromUnsignedLong(st->st_file_attributes));
2159#endif
jcea6c51d512018-01-28 14:00:08 +01002160#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2161 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2162 PyUnicode_FromString(st->st_fstype));
2163#endif
Fred Drake699f3522000-06-29 21:12:41 +00002164
Victor Stinner8c62be82010-05-06 00:08:46 +00002165 if (PyErr_Occurred()) {
2166 Py_DECREF(v);
2167 return NULL;
2168 }
Fred Drake699f3522000-06-29 21:12:41 +00002169
Victor Stinner8c62be82010-05-06 00:08:46 +00002170 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002171}
2172
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002173/* POSIX methods */
2174
Guido van Rossum94f6f721999-01-06 18:42:14 +00002175
2176static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002177posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002178 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002179{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002180 STRUCT_STAT st;
2181 int result;
2182
2183#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2184 if (follow_symlinks_specified(function_name, follow_symlinks))
2185 return NULL;
2186#endif
2187
2188 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2189 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2190 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2191 return NULL;
2192
2193 Py_BEGIN_ALLOW_THREADS
2194 if (path->fd != -1)
2195 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002196#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002197 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002198 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002199 else
Steve Dowercc16be82016-09-08 10:35:16 -07002200 result = win32_lstat(path->wide, &st);
2201#else
2202 else
2203#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002204 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2205 result = LSTAT(path->narrow, &st);
2206 else
Steve Dowercc16be82016-09-08 10:35:16 -07002207#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002208#ifdef HAVE_FSTATAT
2209 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2210 result = fstatat(dir_fd, path->narrow, &st,
2211 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2212 else
Steve Dowercc16be82016-09-08 10:35:16 -07002213#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002214 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002215#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002216 Py_END_ALLOW_THREADS
2217
Victor Stinner292c8352012-10-30 02:17:38 +01002218 if (result != 0) {
2219 return path_error(path);
2220 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002221
2222 return _pystat_fromstructstat(&st);
2223}
2224
Larry Hastings2f936352014-08-05 14:04:04 +10002225/*[python input]
2226
2227for s in """
2228
2229FACCESSAT
2230FCHMODAT
2231FCHOWNAT
2232FSTATAT
2233LINKAT
2234MKDIRAT
2235MKFIFOAT
2236MKNODAT
2237OPENAT
2238READLINKAT
2239SYMLINKAT
2240UNLINKAT
2241
2242""".strip().split():
2243 s = s.strip()
2244 print("""
2245#ifdef HAVE_{s}
2246 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002247#else
Larry Hastings2f936352014-08-05 14:04:04 +10002248 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002249#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002250""".rstrip().format(s=s))
2251
2252for s in """
2253
2254FCHDIR
2255FCHMOD
2256FCHOWN
2257FDOPENDIR
2258FEXECVE
2259FPATHCONF
2260FSTATVFS
2261FTRUNCATE
2262
2263""".strip().split():
2264 s = s.strip()
2265 print("""
2266#ifdef HAVE_{s}
2267 #define PATH_HAVE_{s} 1
2268#else
2269 #define PATH_HAVE_{s} 0
2270#endif
2271
2272""".rstrip().format(s=s))
2273[python start generated code]*/
2274
2275#ifdef HAVE_FACCESSAT
2276 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2277#else
2278 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2279#endif
2280
2281#ifdef HAVE_FCHMODAT
2282 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2283#else
2284 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2285#endif
2286
2287#ifdef HAVE_FCHOWNAT
2288 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2289#else
2290 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2291#endif
2292
2293#ifdef HAVE_FSTATAT
2294 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2295#else
2296 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2297#endif
2298
2299#ifdef HAVE_LINKAT
2300 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2301#else
2302 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2303#endif
2304
2305#ifdef HAVE_MKDIRAT
2306 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2307#else
2308 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2309#endif
2310
2311#ifdef HAVE_MKFIFOAT
2312 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2313#else
2314 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2315#endif
2316
2317#ifdef HAVE_MKNODAT
2318 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2319#else
2320 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2321#endif
2322
2323#ifdef HAVE_OPENAT
2324 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2325#else
2326 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2327#endif
2328
2329#ifdef HAVE_READLINKAT
2330 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2331#else
2332 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2333#endif
2334
2335#ifdef HAVE_SYMLINKAT
2336 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2337#else
2338 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2339#endif
2340
2341#ifdef HAVE_UNLINKAT
2342 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2343#else
2344 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2345#endif
2346
2347#ifdef HAVE_FCHDIR
2348 #define PATH_HAVE_FCHDIR 1
2349#else
2350 #define PATH_HAVE_FCHDIR 0
2351#endif
2352
2353#ifdef HAVE_FCHMOD
2354 #define PATH_HAVE_FCHMOD 1
2355#else
2356 #define PATH_HAVE_FCHMOD 0
2357#endif
2358
2359#ifdef HAVE_FCHOWN
2360 #define PATH_HAVE_FCHOWN 1
2361#else
2362 #define PATH_HAVE_FCHOWN 0
2363#endif
2364
2365#ifdef HAVE_FDOPENDIR
2366 #define PATH_HAVE_FDOPENDIR 1
2367#else
2368 #define PATH_HAVE_FDOPENDIR 0
2369#endif
2370
2371#ifdef HAVE_FEXECVE
2372 #define PATH_HAVE_FEXECVE 1
2373#else
2374 #define PATH_HAVE_FEXECVE 0
2375#endif
2376
2377#ifdef HAVE_FPATHCONF
2378 #define PATH_HAVE_FPATHCONF 1
2379#else
2380 #define PATH_HAVE_FPATHCONF 0
2381#endif
2382
2383#ifdef HAVE_FSTATVFS
2384 #define PATH_HAVE_FSTATVFS 1
2385#else
2386 #define PATH_HAVE_FSTATVFS 0
2387#endif
2388
2389#ifdef HAVE_FTRUNCATE
2390 #define PATH_HAVE_FTRUNCATE 1
2391#else
2392 #define PATH_HAVE_FTRUNCATE 0
2393#endif
2394/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002395
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002396#ifdef MS_WINDOWS
2397 #undef PATH_HAVE_FTRUNCATE
2398 #define PATH_HAVE_FTRUNCATE 1
2399#endif
Larry Hastings31826802013-10-19 00:09:25 -07002400
Larry Hastings61272b72014-01-07 12:41:53 -08002401/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002402
2403class path_t_converter(CConverter):
2404
2405 type = "path_t"
2406 impl_by_reference = True
2407 parse_by_reference = True
2408
2409 converter = 'path_converter'
2410
2411 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002412 # right now path_t doesn't support default values.
2413 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002414 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002415 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002416
Larry Hastings2f936352014-08-05 14:04:04 +10002417 if self.c_default not in (None, 'Py_None'):
2418 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002419
2420 self.nullable = nullable
2421 self.allow_fd = allow_fd
2422
Larry Hastings7726ac92014-01-31 22:03:12 -08002423 def pre_render(self):
2424 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002425 if isinstance(value, str):
2426 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002427 return str(int(bool(value)))
2428
2429 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002430 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002431 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002432 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002433 strify(self.nullable),
2434 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002435 )
2436
2437 def cleanup(self):
2438 return "path_cleanup(&" + self.name + ");\n"
2439
2440
2441class dir_fd_converter(CConverter):
2442 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002443
Larry Hastings2f936352014-08-05 14:04:04 +10002444 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002445 if self.default in (unspecified, None):
2446 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002447 if isinstance(requires, str):
2448 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2449 else:
2450 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002451
Larry Hastings2f936352014-08-05 14:04:04 +10002452class fildes_converter(CConverter):
2453 type = 'int'
2454 converter = 'fildes_converter'
2455
2456class uid_t_converter(CConverter):
2457 type = "uid_t"
2458 converter = '_Py_Uid_Converter'
2459
2460class gid_t_converter(CConverter):
2461 type = "gid_t"
2462 converter = '_Py_Gid_Converter'
2463
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002464class dev_t_converter(CConverter):
2465 type = 'dev_t'
2466 converter = '_Py_Dev_Converter'
2467
2468class dev_t_return_converter(unsigned_long_return_converter):
2469 type = 'dev_t'
2470 conversion_fn = '_PyLong_FromDev'
2471 unsigned_cast = '(dev_t)'
2472
Larry Hastings2f936352014-08-05 14:04:04 +10002473class FSConverter_converter(CConverter):
2474 type = 'PyObject *'
2475 converter = 'PyUnicode_FSConverter'
2476 def converter_init(self):
2477 if self.default is not unspecified:
2478 fail("FSConverter_converter does not support default values")
2479 self.c_default = 'NULL'
2480
2481 def cleanup(self):
2482 return "Py_XDECREF(" + self.name + ");\n"
2483
2484class pid_t_converter(CConverter):
2485 type = 'pid_t'
2486 format_unit = '" _Py_PARSE_PID "'
2487
2488class idtype_t_converter(int_converter):
2489 type = 'idtype_t'
2490
2491class id_t_converter(CConverter):
2492 type = 'id_t'
2493 format_unit = '" _Py_PARSE_PID "'
2494
Benjamin Petersonca470632016-09-06 13:47:26 -07002495class intptr_t_converter(CConverter):
2496 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002497 format_unit = '" _Py_PARSE_INTPTR "'
2498
2499class Py_off_t_converter(CConverter):
2500 type = 'Py_off_t'
2501 converter = 'Py_off_t_converter'
2502
2503class Py_off_t_return_converter(long_return_converter):
2504 type = 'Py_off_t'
2505 conversion_fn = 'PyLong_FromPy_off_t'
2506
2507class path_confname_converter(CConverter):
2508 type="int"
2509 converter="conv_path_confname"
2510
2511class confstr_confname_converter(path_confname_converter):
2512 converter='conv_confstr_confname'
2513
2514class sysconf_confname_converter(path_confname_converter):
2515 converter="conv_sysconf_confname"
2516
2517class sched_param_converter(CConverter):
2518 type = 'struct sched_param'
2519 converter = 'convert_sched_param'
2520 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002521
Larry Hastings61272b72014-01-07 12:41:53 -08002522[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002523/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002524
Larry Hastings61272b72014-01-07 12:41:53 -08002525/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002526
Larry Hastings2a727912014-01-16 11:32:01 -08002527os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002528
2529 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002530 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002531 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002532
2533 *
2534
Larry Hastings2f936352014-08-05 14:04:04 +10002535 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002536 If not None, it should be a file descriptor open to a directory,
2537 and path should be a relative string; path will then be relative to
2538 that directory.
2539
2540 follow_symlinks: bool = True
2541 If False, and the last element of the path is a symbolic link,
2542 stat will examine the symbolic link itself instead of the file
2543 the link points to.
2544
2545Perform a stat system call on the given path.
2546
2547dir_fd and follow_symlinks may not be implemented
2548 on your platform. If they are unavailable, using them will raise a
2549 NotImplementedError.
2550
2551It's an error to use dir_fd or follow_symlinks when specifying path as
2552 an open file descriptor.
2553
Larry Hastings61272b72014-01-07 12:41:53 -08002554[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002555
Larry Hastings31826802013-10-19 00:09:25 -07002556static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002557os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002558/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002559{
2560 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2561}
2562
Larry Hastings2f936352014-08-05 14:04:04 +10002563
2564/*[clinic input]
2565os.lstat
2566
2567 path : path_t
2568
2569 *
2570
2571 dir_fd : dir_fd(requires='fstatat') = None
2572
2573Perform a stat system call on the given path, without following symbolic links.
2574
2575Like stat(), but do not follow symbolic links.
2576Equivalent to stat(path, follow_symlinks=False).
2577[clinic start generated code]*/
2578
Larry Hastings2f936352014-08-05 14:04:04 +10002579static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002580os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2581/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002582{
2583 int follow_symlinks = 0;
2584 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2585}
Larry Hastings31826802013-10-19 00:09:25 -07002586
Larry Hastings2f936352014-08-05 14:04:04 +10002587
Larry Hastings61272b72014-01-07 12:41:53 -08002588/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002589os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002590
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002591 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002592 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002593
2594 mode: int
2595 Operating-system mode bitfield. Can be F_OK to test existence,
2596 or the inclusive-OR of R_OK, W_OK, and X_OK.
2597
2598 *
2599
Larry Hastings2f936352014-08-05 14:04:04 +10002600 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002601 If not None, it should be a file descriptor open to a directory,
2602 and path should be relative; path will then be relative to that
2603 directory.
2604
2605 effective_ids: bool = False
2606 If True, access will use the effective uid/gid instead of
2607 the real uid/gid.
2608
2609 follow_symlinks: bool = True
2610 If False, and the last element of the path is a symbolic link,
2611 access will examine the symbolic link itself instead of the file
2612 the link points to.
2613
2614Use the real uid/gid to test for access to a path.
2615
2616{parameters}
2617dir_fd, effective_ids, and follow_symlinks may not be implemented
2618 on your platform. If they are unavailable, using them will raise a
2619 NotImplementedError.
2620
2621Note that most operations will use the effective uid/gid, therefore this
2622 routine can be used in a suid/sgid environment to test if the invoking user
2623 has the specified access to the path.
2624
Larry Hastings61272b72014-01-07 12:41:53 -08002625[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002626
Larry Hastings2f936352014-08-05 14:04:04 +10002627static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002628os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002629 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002630/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002631{
Larry Hastings2f936352014-08-05 14:04:04 +10002632 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002633
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002634#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002635 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002636#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002637 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002638#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002639
Larry Hastings9cf065c2012-06-22 16:30:09 -07002640#ifndef HAVE_FACCESSAT
2641 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002642 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002643
2644 if (effective_ids) {
2645 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002646 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002647 }
2648#endif
2649
2650#ifdef MS_WINDOWS
2651 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002652 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002653 Py_END_ALLOW_THREADS
2654
2655 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002656 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002657 * * we didn't get a -1, and
2658 * * write access wasn't requested,
2659 * * or the file isn't read-only,
2660 * * or it's a directory.
2661 * (Directories cannot be read-only on Windows.)
2662 */
Larry Hastings2f936352014-08-05 14:04:04 +10002663 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002664 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002665 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002666 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002667#else
2668
2669 Py_BEGIN_ALLOW_THREADS
2670#ifdef HAVE_FACCESSAT
2671 if ((dir_fd != DEFAULT_DIR_FD) ||
2672 effective_ids ||
2673 !follow_symlinks) {
2674 int flags = 0;
2675 if (!follow_symlinks)
2676 flags |= AT_SYMLINK_NOFOLLOW;
2677 if (effective_ids)
2678 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002679 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002680 }
2681 else
2682#endif
Larry Hastings31826802013-10-19 00:09:25 -07002683 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002684 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002685 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002686#endif
2687
Larry Hastings9cf065c2012-06-22 16:30:09 -07002688 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002689}
2690
Guido van Rossumd371ff11999-01-25 16:12:23 +00002691#ifndef F_OK
2692#define F_OK 0
2693#endif
2694#ifndef R_OK
2695#define R_OK 4
2696#endif
2697#ifndef W_OK
2698#define W_OK 2
2699#endif
2700#ifndef X_OK
2701#define X_OK 1
2702#endif
2703
Larry Hastings31826802013-10-19 00:09:25 -07002704
Guido van Rossumd371ff11999-01-25 16:12:23 +00002705#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002706/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002707os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002708
2709 fd: int
2710 Integer file descriptor handle.
2711
2712 /
2713
2714Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002715[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002716
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002717static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002718os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002719/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002720{
2721 char *ret;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002722
Larry Hastings31826802013-10-19 00:09:25 -07002723 ret = ttyname(fd);
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002724 if (ret == NULL) {
2725 return posix_error();
2726 }
2727 return PyUnicode_DecodeFSDefault(ret);
Guido van Rossum94f6f721999-01-06 18:42:14 +00002728}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002729#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002730
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002731#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002732/*[clinic input]
2733os.ctermid
2734
2735Return the name of the controlling terminal for this process.
2736[clinic start generated code]*/
2737
Larry Hastings2f936352014-08-05 14:04:04 +10002738static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002739os_ctermid_impl(PyObject *module)
2740/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002741{
Victor Stinner8c62be82010-05-06 00:08:46 +00002742 char *ret;
2743 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002744
Greg Wardb48bc172000-03-01 21:51:56 +00002745#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002746 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002747#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002748 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002749#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002750 if (ret == NULL)
2751 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002752 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002753}
Larry Hastings2f936352014-08-05 14:04:04 +10002754#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002755
Larry Hastings2f936352014-08-05 14:04:04 +10002756
2757/*[clinic input]
2758os.chdir
2759
2760 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2761
2762Change the current working directory to the specified path.
2763
2764path may always be specified as a string.
2765On some platforms, path may also be specified as an open file descriptor.
2766 If this functionality is unavailable, using it raises an exception.
2767[clinic start generated code]*/
2768
Larry Hastings2f936352014-08-05 14:04:04 +10002769static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002770os_chdir_impl(PyObject *module, path_t *path)
2771/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002772{
2773 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002774
2775 Py_BEGIN_ALLOW_THREADS
2776#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002777 /* on unix, success = 0, on windows, success = !0 */
2778 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002779#else
2780#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002781 if (path->fd != -1)
2782 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002783 else
2784#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002785 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002786#endif
2787 Py_END_ALLOW_THREADS
2788
2789 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002790 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002791 }
2792
Larry Hastings2f936352014-08-05 14:04:04 +10002793 Py_RETURN_NONE;
2794}
2795
2796
2797#ifdef HAVE_FCHDIR
2798/*[clinic input]
2799os.fchdir
2800
2801 fd: fildes
2802
2803Change to the directory of the given file descriptor.
2804
2805fd must be opened on a directory, not a file.
2806Equivalent to os.chdir(fd).
2807
2808[clinic start generated code]*/
2809
Fred Drake4d1e64b2002-04-15 19:40:07 +00002810static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002811os_fchdir_impl(PyObject *module, int fd)
2812/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002813{
Larry Hastings2f936352014-08-05 14:04:04 +10002814 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002815}
2816#endif /* HAVE_FCHDIR */
2817
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002818
Larry Hastings2f936352014-08-05 14:04:04 +10002819/*[clinic input]
2820os.chmod
2821
2822 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002823 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002824 On some platforms, path may also be specified as an open file descriptor.
2825 If this functionality is unavailable, using it raises an exception.
2826
2827 mode: int
2828 Operating-system mode bitfield.
2829
2830 *
2831
2832 dir_fd : dir_fd(requires='fchmodat') = None
2833 If not None, it should be a file descriptor open to a directory,
2834 and path should be relative; path will then be relative to that
2835 directory.
2836
2837 follow_symlinks: bool = True
2838 If False, and the last element of the path is a symbolic link,
2839 chmod will modify the symbolic link itself instead of the file
2840 the link points to.
2841
2842Change the access permissions of a file.
2843
2844It is an error to use dir_fd or follow_symlinks when specifying path as
2845 an open file descriptor.
2846dir_fd and follow_symlinks may not be implemented on your platform.
2847 If they are unavailable, using them will raise a NotImplementedError.
2848
2849[clinic start generated code]*/
2850
Larry Hastings2f936352014-08-05 14:04:04 +10002851static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002852os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002853 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002854/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002855{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002856 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002857
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002858#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002859 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002860#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00002861
Larry Hastings9cf065c2012-06-22 16:30:09 -07002862#ifdef HAVE_FCHMODAT
2863 int fchmodat_nofollow_unsupported = 0;
2864#endif
2865
Larry Hastings9cf065c2012-06-22 16:30:09 -07002866#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
2867 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002868 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002869#endif
2870
2871#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002872 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002873 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01002874 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002875 result = 0;
2876 else {
2877 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00002878 attr &= ~FILE_ATTRIBUTE_READONLY;
2879 else
2880 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07002881 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002882 }
2883 Py_END_ALLOW_THREADS
2884
2885 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002886 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002887 }
2888#else /* MS_WINDOWS */
2889 Py_BEGIN_ALLOW_THREADS
2890#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002891 if (path->fd != -1)
2892 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002893 else
2894#endif
2895#ifdef HAVE_LCHMOD
2896 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10002897 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002898 else
2899#endif
2900#ifdef HAVE_FCHMODAT
2901 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
2902 /*
2903 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
2904 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002905 * and then says it isn't implemented yet.
2906 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002907 *
2908 * Once it is supported, os.chmod will automatically
2909 * support dir_fd and follow_symlinks=False. (Hopefully.)
2910 * Until then, we need to be careful what exception we raise.
2911 */
Larry Hastings2f936352014-08-05 14:04:04 +10002912 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002913 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2914 /*
2915 * But wait! We can't throw the exception without allowing threads,
2916 * and we can't do that in this nested scope. (Macro trickery, sigh.)
2917 */
2918 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002919 result &&
2920 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
2921 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00002922 }
2923 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00002924#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002925 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002926 Py_END_ALLOW_THREADS
2927
2928 if (result) {
2929#ifdef HAVE_FCHMODAT
2930 if (fchmodat_nofollow_unsupported) {
2931 if (dir_fd != DEFAULT_DIR_FD)
2932 dir_fd_and_follow_symlinks_invalid("chmod",
2933 dir_fd, follow_symlinks);
2934 else
2935 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08002936 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002937 }
2938 else
2939#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002940 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002941 }
2942#endif
2943
Larry Hastings2f936352014-08-05 14:04:04 +10002944 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002945}
2946
Larry Hastings9cf065c2012-06-22 16:30:09 -07002947
Christian Heimes4e30a842007-11-30 22:12:06 +00002948#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002949/*[clinic input]
2950os.fchmod
2951
2952 fd: int
2953 mode: int
2954
2955Change the access permissions of the file given by file descriptor fd.
2956
2957Equivalent to os.chmod(fd, mode).
2958[clinic start generated code]*/
2959
Larry Hastings2f936352014-08-05 14:04:04 +10002960static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002961os_fchmod_impl(PyObject *module, int fd, int mode)
2962/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002963{
2964 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00002965 int async_err = 0;
2966
2967 do {
2968 Py_BEGIN_ALLOW_THREADS
2969 res = fchmod(fd, mode);
2970 Py_END_ALLOW_THREADS
2971 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
2972 if (res != 0)
2973 return (!async_err) ? posix_error() : NULL;
2974
Victor Stinner8c62be82010-05-06 00:08:46 +00002975 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00002976}
2977#endif /* HAVE_FCHMOD */
2978
Larry Hastings2f936352014-08-05 14:04:04 +10002979
Christian Heimes4e30a842007-11-30 22:12:06 +00002980#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002981/*[clinic input]
2982os.lchmod
2983
2984 path: path_t
2985 mode: int
2986
2987Change the access permissions of a file, without following symbolic links.
2988
2989If path is a symlink, this affects the link itself rather than the target.
2990Equivalent to chmod(path, mode, follow_symlinks=False)."
2991[clinic start generated code]*/
2992
Larry Hastings2f936352014-08-05 14:04:04 +10002993static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002994os_lchmod_impl(PyObject *module, path_t *path, int mode)
2995/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002996{
Victor Stinner8c62be82010-05-06 00:08:46 +00002997 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00002998 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10002999 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003000 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003001 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003002 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003003 return NULL;
3004 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003005 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003006}
3007#endif /* HAVE_LCHMOD */
3008
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003009
Thomas Wouterscf297e42007-02-23 15:07:44 +00003010#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003011/*[clinic input]
3012os.chflags
3013
3014 path: path_t
3015 flags: unsigned_long(bitwise=True)
3016 follow_symlinks: bool=True
3017
3018Set file flags.
3019
3020If follow_symlinks is False, and the last element of the path is a symbolic
3021 link, chflags will change flags on the symbolic link itself instead of the
3022 file the link points to.
3023follow_symlinks may not be implemented on your platform. If it is
3024unavailable, using it will raise a NotImplementedError.
3025
3026[clinic start generated code]*/
3027
Larry Hastings2f936352014-08-05 14:04:04 +10003028static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003029os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003030 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003031/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003032{
3033 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003034
3035#ifndef HAVE_LCHFLAGS
3036 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003037 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003038#endif
3039
Victor Stinner8c62be82010-05-06 00:08:46 +00003040 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003041#ifdef HAVE_LCHFLAGS
3042 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003043 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003044 else
3045#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003046 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003047 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003048
Larry Hastings2f936352014-08-05 14:04:04 +10003049 if (result)
3050 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003051
Larry Hastings2f936352014-08-05 14:04:04 +10003052 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003053}
3054#endif /* HAVE_CHFLAGS */
3055
Larry Hastings2f936352014-08-05 14:04:04 +10003056
Thomas Wouterscf297e42007-02-23 15:07:44 +00003057#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003058/*[clinic input]
3059os.lchflags
3060
3061 path: path_t
3062 flags: unsigned_long(bitwise=True)
3063
3064Set file flags.
3065
3066This function will not follow symbolic links.
3067Equivalent to chflags(path, flags, follow_symlinks=False).
3068[clinic start generated code]*/
3069
Larry Hastings2f936352014-08-05 14:04:04 +10003070static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003071os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3072/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003073{
Victor Stinner8c62be82010-05-06 00:08:46 +00003074 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003075 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003076 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003077 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003078 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003079 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003080 }
Victor Stinner292c8352012-10-30 02:17:38 +01003081 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003082}
3083#endif /* HAVE_LCHFLAGS */
3084
Larry Hastings2f936352014-08-05 14:04:04 +10003085
Martin v. Löwis244edc82001-10-04 22:44:26 +00003086#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003087/*[clinic input]
3088os.chroot
3089 path: path_t
3090
3091Change root directory to path.
3092
3093[clinic start generated code]*/
3094
Larry Hastings2f936352014-08-05 14:04:04 +10003095static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003096os_chroot_impl(PyObject *module, path_t *path)
3097/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003098{
3099 int res;
3100 Py_BEGIN_ALLOW_THREADS
3101 res = chroot(path->narrow);
3102 Py_END_ALLOW_THREADS
3103 if (res < 0)
3104 return path_error(path);
3105 Py_RETURN_NONE;
3106}
3107#endif /* HAVE_CHROOT */
3108
Martin v. Löwis244edc82001-10-04 22:44:26 +00003109
Guido van Rossum21142a01999-01-08 21:05:37 +00003110#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003111/*[clinic input]
3112os.fsync
3113
3114 fd: fildes
3115
3116Force write of fd to disk.
3117[clinic start generated code]*/
3118
Larry Hastings2f936352014-08-05 14:04:04 +10003119static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003120os_fsync_impl(PyObject *module, int fd)
3121/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003122{
3123 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003124}
3125#endif /* HAVE_FSYNC */
3126
Larry Hastings2f936352014-08-05 14:04:04 +10003127
Ross Lagerwall7807c352011-03-17 20:20:30 +02003128#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003129/*[clinic input]
3130os.sync
3131
3132Force write of everything to disk.
3133[clinic start generated code]*/
3134
Larry Hastings2f936352014-08-05 14:04:04 +10003135static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003136os_sync_impl(PyObject *module)
3137/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003138{
3139 Py_BEGIN_ALLOW_THREADS
3140 sync();
3141 Py_END_ALLOW_THREADS
3142 Py_RETURN_NONE;
3143}
Larry Hastings2f936352014-08-05 14:04:04 +10003144#endif /* HAVE_SYNC */
3145
Ross Lagerwall7807c352011-03-17 20:20:30 +02003146
Guido van Rossum21142a01999-01-08 21:05:37 +00003147#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003148#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003149extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3150#endif
3151
Larry Hastings2f936352014-08-05 14:04:04 +10003152/*[clinic input]
3153os.fdatasync
3154
3155 fd: fildes
3156
3157Force write of fd to disk without forcing update of metadata.
3158[clinic start generated code]*/
3159
Larry Hastings2f936352014-08-05 14:04:04 +10003160static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003161os_fdatasync_impl(PyObject *module, int fd)
3162/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003163{
3164 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003165}
3166#endif /* HAVE_FDATASYNC */
3167
3168
Fredrik Lundh10723342000-07-10 16:38:09 +00003169#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003170/*[clinic input]
3171os.chown
3172
3173 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003174 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003175
3176 uid: uid_t
3177
3178 gid: gid_t
3179
3180 *
3181
3182 dir_fd : dir_fd(requires='fchownat') = None
3183 If not None, it should be a file descriptor open to a directory,
3184 and path should be relative; path will then be relative to that
3185 directory.
3186
3187 follow_symlinks: bool = True
3188 If False, and the last element of the path is a symbolic link,
3189 stat will examine the symbolic link itself instead of the file
3190 the link points to.
3191
3192Change the owner and group id of path to the numeric uid and gid.\
3193
3194path may always be specified as a string.
3195On some platforms, path may also be specified as an open file descriptor.
3196 If this functionality is unavailable, using it raises an exception.
3197If dir_fd is not None, it should be a file descriptor open to a directory,
3198 and path should be relative; path will then be relative to that directory.
3199If follow_symlinks is False, and the last element of the path is a symbolic
3200 link, chown will modify the symbolic link itself instead of the file the
3201 link points to.
3202It is an error to use dir_fd or follow_symlinks when specifying path as
3203 an open file descriptor.
3204dir_fd and follow_symlinks may not be implemented on your platform.
3205 If they are unavailable, using them will raise a NotImplementedError.
3206
3207[clinic start generated code]*/
3208
Larry Hastings2f936352014-08-05 14:04:04 +10003209static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003210os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003211 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003212/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003213{
3214 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003215
3216#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3217 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003218 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003219#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003220 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3221 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3222 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003223
3224#ifdef __APPLE__
3225 /*
3226 * This is for Mac OS X 10.3, which doesn't have lchown.
3227 * (But we still have an lchown symbol because of weak-linking.)
3228 * It doesn't have fchownat either. So there's no possibility
3229 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003230 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003231 if ((!follow_symlinks) && (lchown == NULL)) {
3232 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003233 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003234 }
3235#endif
3236
Victor Stinner8c62be82010-05-06 00:08:46 +00003237 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003238#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003239 if (path->fd != -1)
3240 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003241 else
3242#endif
3243#ifdef HAVE_LCHOWN
3244 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003245 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003246 else
3247#endif
3248#ifdef HAVE_FCHOWNAT
3249 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003250 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003251 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3252 else
3253#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003254 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003255 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003256
Larry Hastings2f936352014-08-05 14:04:04 +10003257 if (result)
3258 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003259
Larry Hastings2f936352014-08-05 14:04:04 +10003260 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003261}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003262#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003263
Larry Hastings2f936352014-08-05 14:04:04 +10003264
Christian Heimes4e30a842007-11-30 22:12:06 +00003265#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003266/*[clinic input]
3267os.fchown
3268
3269 fd: int
3270 uid: uid_t
3271 gid: gid_t
3272
3273Change the owner and group id of the file specified by file descriptor.
3274
3275Equivalent to os.chown(fd, uid, gid).
3276
3277[clinic start generated code]*/
3278
Larry Hastings2f936352014-08-05 14:04:04 +10003279static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003280os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3281/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003282{
Victor Stinner8c62be82010-05-06 00:08:46 +00003283 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003284 int async_err = 0;
3285
3286 do {
3287 Py_BEGIN_ALLOW_THREADS
3288 res = fchown(fd, uid, gid);
3289 Py_END_ALLOW_THREADS
3290 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3291 if (res != 0)
3292 return (!async_err) ? posix_error() : NULL;
3293
Victor Stinner8c62be82010-05-06 00:08:46 +00003294 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003295}
3296#endif /* HAVE_FCHOWN */
3297
Larry Hastings2f936352014-08-05 14:04:04 +10003298
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003299#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003300/*[clinic input]
3301os.lchown
3302
3303 path : path_t
3304 uid: uid_t
3305 gid: gid_t
3306
3307Change the owner and group id of path to the numeric uid and gid.
3308
3309This function will not follow symbolic links.
3310Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3311[clinic start generated code]*/
3312
Larry Hastings2f936352014-08-05 14:04:04 +10003313static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003314os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3315/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003316{
Victor Stinner8c62be82010-05-06 00:08:46 +00003317 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003318 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003319 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003320 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003321 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003322 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003323 }
Larry Hastings2f936352014-08-05 14:04:04 +10003324 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003325}
3326#endif /* HAVE_LCHOWN */
3327
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003328
Barry Warsaw53699e91996-12-10 23:23:01 +00003329static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003330posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003331{
Victor Stinner4403d7d2015-04-25 00:16:10 +02003332 char *buf, *tmpbuf;
3333 char *cwd;
3334 const size_t chunk = 1024;
3335 size_t buflen = 0;
3336 PyObject *obj;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003337
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003338#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003339 if (!use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003340 wchar_t wbuf[MAXPATHLEN];
Victor Stinner8c62be82010-05-06 00:08:46 +00003341 wchar_t *wbuf2 = wbuf;
3342 PyObject *resobj;
3343 DWORD len;
3344 Py_BEGIN_ALLOW_THREADS
Victor Stinner75875072013-11-24 19:23:25 +01003345 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003346 /* If the buffer is large enough, len does not include the
3347 terminating \0. If the buffer is too small, len includes
3348 the space needed for the terminator. */
Victor Stinner75875072013-11-24 19:23:25 +01003349 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003350 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003351 if (wbuf2)
3352 len = GetCurrentDirectoryW(len, wbuf2);
3353 }
3354 Py_END_ALLOW_THREADS
3355 if (!wbuf2) {
3356 PyErr_NoMemory();
3357 return NULL;
3358 }
3359 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003360 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003361 PyMem_RawFree(wbuf2);
Victor Stinnerb024e842012-10-31 22:24:06 +01003362 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003363 }
3364 resobj = PyUnicode_FromWideChar(wbuf2, len);
Victor Stinnerb024e842012-10-31 22:24:06 +01003365 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003366 PyMem_RawFree(wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003367 return resobj;
3368 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003369
3370 if (win32_warn_bytes_api())
3371 return NULL;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003372#endif
3373
Victor Stinner4403d7d2015-04-25 00:16:10 +02003374 buf = cwd = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003375 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003376 do {
3377 buflen += chunk;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003378#ifdef MS_WINDOWS
3379 if (buflen > INT_MAX) {
3380 PyErr_NoMemory();
3381 break;
3382 }
3383#endif
Victor Stinner4403d7d2015-04-25 00:16:10 +02003384 tmpbuf = PyMem_RawRealloc(buf, buflen);
3385 if (tmpbuf == NULL)
3386 break;
3387
3388 buf = tmpbuf;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003389#ifdef MS_WINDOWS
3390 cwd = getcwd(buf, (int)buflen);
3391#else
Victor Stinner4403d7d2015-04-25 00:16:10 +02003392 cwd = getcwd(buf, buflen);
Victor Stinnerc44f7072016-03-14 18:07:53 +01003393#endif
Victor Stinner4403d7d2015-04-25 00:16:10 +02003394 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003395 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003396
3397 if (cwd == NULL) {
3398 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003399 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003400 }
3401
Victor Stinner8c62be82010-05-06 00:08:46 +00003402 if (use_bytes)
Victor Stinner4403d7d2015-04-25 00:16:10 +02003403 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
3404 else
3405 obj = PyUnicode_DecodeFSDefault(buf);
3406 PyMem_RawFree(buf);
3407
3408 return obj;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003409}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003410
Larry Hastings2f936352014-08-05 14:04:04 +10003411
3412/*[clinic input]
3413os.getcwd
3414
3415Return a unicode string representing the current working directory.
3416[clinic start generated code]*/
3417
Larry Hastings2f936352014-08-05 14:04:04 +10003418static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003419os_getcwd_impl(PyObject *module)
3420/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003421{
3422 return posix_getcwd(0);
3423}
3424
Larry Hastings2f936352014-08-05 14:04:04 +10003425
3426/*[clinic input]
3427os.getcwdb
3428
3429Return a bytes string representing the current working directory.
3430[clinic start generated code]*/
3431
Larry Hastings2f936352014-08-05 14:04:04 +10003432static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003433os_getcwdb_impl(PyObject *module)
3434/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003435{
3436 return posix_getcwd(1);
3437}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003438
Larry Hastings2f936352014-08-05 14:04:04 +10003439
Larry Hastings9cf065c2012-06-22 16:30:09 -07003440#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3441#define HAVE_LINK 1
3442#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003443
Guido van Rossumb6775db1994-08-01 11:34:53 +00003444#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003445/*[clinic input]
3446
3447os.link
3448
3449 src : path_t
3450 dst : path_t
3451 *
3452 src_dir_fd : dir_fd = None
3453 dst_dir_fd : dir_fd = None
3454 follow_symlinks: bool = True
3455
3456Create a hard link to a file.
3457
3458If either src_dir_fd or dst_dir_fd is not None, it should be a file
3459 descriptor open to a directory, and the respective path string (src or dst)
3460 should be relative; the path will then be relative to that directory.
3461If follow_symlinks is False, and the last element of src is a symbolic
3462 link, link will create a link to the symbolic link itself instead of the
3463 file the link points to.
3464src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3465 platform. If they are unavailable, using them will raise a
3466 NotImplementedError.
3467[clinic start generated code]*/
3468
Larry Hastings2f936352014-08-05 14:04:04 +10003469static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003470os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003471 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003472/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003473{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003474#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003475 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003476#else
3477 int result;
3478#endif
3479
Larry Hastings9cf065c2012-06-22 16:30:09 -07003480#ifndef HAVE_LINKAT
3481 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3482 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003483 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003484 }
3485#endif
3486
Steve Dowercc16be82016-09-08 10:35:16 -07003487#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003488 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003489 PyErr_SetString(PyExc_NotImplementedError,
3490 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003491 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003492 }
Steve Dowercc16be82016-09-08 10:35:16 -07003493#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003494
Brian Curtin1b9df392010-11-24 20:24:31 +00003495#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003496 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003497 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003498 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003499
Larry Hastings2f936352014-08-05 14:04:04 +10003500 if (!result)
3501 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003502#else
3503 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003504#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003505 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3506 (dst_dir_fd != DEFAULT_DIR_FD) ||
3507 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003508 result = linkat(src_dir_fd, src->narrow,
3509 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003510 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3511 else
Steve Dowercc16be82016-09-08 10:35:16 -07003512#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003513 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003514 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003515
Larry Hastings2f936352014-08-05 14:04:04 +10003516 if (result)
3517 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003518#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003519
Larry Hastings2f936352014-08-05 14:04:04 +10003520 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003521}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003522#endif
3523
Brian Curtin1b9df392010-11-24 20:24:31 +00003524
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003525#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003526static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003527_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003528{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003529 PyObject *v;
3530 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3531 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003532 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003533 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003534 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003535 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003536
Steve Dowercc16be82016-09-08 10:35:16 -07003537 WIN32_FIND_DATAW wFileData;
3538 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003539
Steve Dowercc16be82016-09-08 10:35:16 -07003540 if (!path->wide) { /* Default arg: "." */
3541 po_wchars = L".";
3542 len = 1;
3543 } else {
3544 po_wchars = path->wide;
3545 len = wcslen(path->wide);
3546 }
3547 /* The +5 is so we can append "\\*.*\0" */
3548 wnamebuf = PyMem_New(wchar_t, len + 5);
3549 if (!wnamebuf) {
3550 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003551 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003552 }
Steve Dowercc16be82016-09-08 10:35:16 -07003553 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003554 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003555 wchar_t wch = wnamebuf[len-1];
3556 if (wch != SEP && wch != ALTSEP && wch != L':')
3557 wnamebuf[len++] = SEP;
3558 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003559 }
Steve Dowercc16be82016-09-08 10:35:16 -07003560 if ((list = PyList_New(0)) == NULL) {
3561 goto exit;
3562 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003563 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003564 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003565 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003566 if (hFindFile == INVALID_HANDLE_VALUE) {
3567 int error = GetLastError();
3568 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003569 goto exit;
3570 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003571 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003572 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003573 }
3574 do {
3575 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003576 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3577 wcscmp(wFileData.cFileName, L"..") != 0) {
3578 v = PyUnicode_FromWideChar(wFileData.cFileName,
3579 wcslen(wFileData.cFileName));
3580 if (path->narrow && v) {
3581 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3582 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003583 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003584 Py_DECREF(list);
3585 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003586 break;
3587 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003588 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003589 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003590 Py_DECREF(list);
3591 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003592 break;
3593 }
3594 Py_DECREF(v);
3595 }
3596 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003597 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003598 Py_END_ALLOW_THREADS
3599 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3600 it got to the end of the directory. */
3601 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003602 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003603 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003604 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003605 }
3606 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003607
Larry Hastings9cf065c2012-06-22 16:30:09 -07003608exit:
3609 if (hFindFile != INVALID_HANDLE_VALUE) {
3610 if (FindClose(hFindFile) == FALSE) {
3611 if (list != NULL) {
3612 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003613 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003614 }
3615 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003616 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003617 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003618
Larry Hastings9cf065c2012-06-22 16:30:09 -07003619 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003620} /* end of _listdir_windows_no_opendir */
3621
3622#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3623
3624static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003625_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003626{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003627 PyObject *v;
3628 DIR *dirp = NULL;
3629 struct dirent *ep;
3630 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003631#ifdef HAVE_FDOPENDIR
3632 int fd = -1;
3633#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003634
Victor Stinner8c62be82010-05-06 00:08:46 +00003635 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003636#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003637 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003638 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003639 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003640 if (fd == -1)
3641 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003642
Larry Hastingsfdaea062012-06-25 04:42:23 -07003643 return_str = 1;
3644
Larry Hastings9cf065c2012-06-22 16:30:09 -07003645 Py_BEGIN_ALLOW_THREADS
3646 dirp = fdopendir(fd);
3647 Py_END_ALLOW_THREADS
3648 }
3649 else
3650#endif
3651 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003652 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003653 if (path->narrow) {
3654 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003655 /* only return bytes if they specified a bytes-like object */
3656 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003657 }
3658 else {
3659 name = ".";
3660 return_str = 1;
3661 }
3662
Larry Hastings9cf065c2012-06-22 16:30:09 -07003663 Py_BEGIN_ALLOW_THREADS
3664 dirp = opendir(name);
3665 Py_END_ALLOW_THREADS
3666 }
3667
3668 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003669 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003670#ifdef HAVE_FDOPENDIR
3671 if (fd != -1) {
3672 Py_BEGIN_ALLOW_THREADS
3673 close(fd);
3674 Py_END_ALLOW_THREADS
3675 }
3676#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003677 goto exit;
3678 }
3679 if ((list = PyList_New(0)) == NULL) {
3680 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003681 }
3682 for (;;) {
3683 errno = 0;
3684 Py_BEGIN_ALLOW_THREADS
3685 ep = readdir(dirp);
3686 Py_END_ALLOW_THREADS
3687 if (ep == NULL) {
3688 if (errno == 0) {
3689 break;
3690 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003691 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003692 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003693 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003694 }
3695 }
3696 if (ep->d_name[0] == '.' &&
3697 (NAMLEN(ep) == 1 ||
3698 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3699 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003700 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003701 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3702 else
3703 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003704 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003705 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003706 break;
3707 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003708 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003709 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003710 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003711 break;
3712 }
3713 Py_DECREF(v);
3714 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003715
Larry Hastings9cf065c2012-06-22 16:30:09 -07003716exit:
3717 if (dirp != NULL) {
3718 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003719#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003720 if (fd > -1)
3721 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003722#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003723 closedir(dirp);
3724 Py_END_ALLOW_THREADS
3725 }
3726
Larry Hastings9cf065c2012-06-22 16:30:09 -07003727 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003728} /* end of _posix_listdir */
3729#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003730
Larry Hastings2f936352014-08-05 14:04:04 +10003731
3732/*[clinic input]
3733os.listdir
3734
3735 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3736
3737Return a list containing the names of the files in the directory.
3738
BNMetricsb9427072018-11-02 15:20:19 +00003739path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003740 the filenames returned will also be bytes; in all other circumstances
3741 the filenames returned will be str.
3742If path is None, uses the path='.'.
3743On some platforms, path may also be specified as an open file descriptor;\
3744 the file descriptor must refer to a directory.
3745 If this functionality is unavailable, using it raises NotImplementedError.
3746
3747The list is in arbitrary order. It does not include the special
3748entries '.' and '..' even if they are present in the directory.
3749
3750
3751[clinic start generated code]*/
3752
Larry Hastings2f936352014-08-05 14:04:04 +10003753static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003754os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003755/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003756{
3757#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3758 return _listdir_windows_no_opendir(path, NULL);
3759#else
3760 return _posix_listdir(path, NULL);
3761#endif
3762}
3763
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003764#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003765/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003766/*[clinic input]
3767os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003768
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003769 path: path_t
3770 /
3771
3772[clinic start generated code]*/
3773
3774static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003775os__getfullpathname_impl(PyObject *module, path_t *path)
3776/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003777{
Steve Dowercc16be82016-09-08 10:35:16 -07003778 wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
3779 wchar_t *wtemp;
3780 DWORD result;
3781 PyObject *v;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003782
Steve Dowercc16be82016-09-08 10:35:16 -07003783 result = GetFullPathNameW(path->wide,
3784 Py_ARRAY_LENGTH(woutbuf),
3785 woutbuf, &wtemp);
3786 if (result > Py_ARRAY_LENGTH(woutbuf)) {
3787 woutbufp = PyMem_New(wchar_t, result);
3788 if (!woutbufp)
3789 return PyErr_NoMemory();
3790 result = GetFullPathNameW(path->wide, result, woutbufp, &wtemp);
Victor Stinner8c62be82010-05-06 00:08:46 +00003791 }
Steve Dowercc16be82016-09-08 10:35:16 -07003792 if (result) {
3793 v = PyUnicode_FromWideChar(woutbufp, wcslen(woutbufp));
3794 if (path->narrow)
3795 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3796 } else
3797 v = win32_error_object("GetFullPathNameW", path->object);
3798 if (woutbufp != woutbuf)
3799 PyMem_Free(woutbufp);
3800 return v;
Larry Hastings2f936352014-08-05 14:04:04 +10003801}
Brian Curtind40e6f72010-07-08 21:39:08 +00003802
Brian Curtind25aef52011-06-13 15:16:04 -05003803
Larry Hastings2f936352014-08-05 14:04:04 +10003804/*[clinic input]
3805os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003806
Steve Dower23ad6d02018-02-22 10:39:10 -08003807 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003808 /
3809
3810A helper function for samepath on windows.
3811[clinic start generated code]*/
3812
Larry Hastings2f936352014-08-05 14:04:04 +10003813static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003814os__getfinalpathname_impl(PyObject *module, path_t *path)
3815/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003816{
3817 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003818 wchar_t buf[MAXPATHLEN], *target_path = buf;
3819 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003820 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003821 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003822
Steve Dower23ad6d02018-02-22 10:39:10 -08003823 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003824 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003825 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003826 0, /* desired access */
3827 0, /* share mode */
3828 NULL, /* security attributes */
3829 OPEN_EXISTING,
3830 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3831 FILE_FLAG_BACKUP_SEMANTICS,
3832 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003833 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003834
Steve Dower23ad6d02018-02-22 10:39:10 -08003835 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003836 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08003837 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003838
3839 /* We have a good handle to the target, use it to determine the
3840 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003841 while (1) {
3842 Py_BEGIN_ALLOW_THREADS
3843 result_length = GetFinalPathNameByHandleW(hFile, target_path,
3844 buf_size, VOLUME_NAME_DOS);
3845 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003846
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003847 if (!result_length) {
3848 result = win32_error_object("GetFinalPathNameByHandleW",
3849 path->object);
3850 goto cleanup;
3851 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003852
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003853 if (result_length < buf_size) {
3854 break;
3855 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003856
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003857 wchar_t *tmp;
3858 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
3859 result_length * sizeof(*tmp));
3860 if (!tmp) {
3861 result = PyErr_NoMemory();
3862 goto cleanup;
3863 }
3864
3865 buf_size = result_length;
3866 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08003867 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003868
Victor Stinner9d3b93b2011-11-22 02:27:30 +01003869 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dower23ad6d02018-02-22 10:39:10 -08003870 if (path->narrow)
3871 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dower23ad6d02018-02-22 10:39:10 -08003872
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003873cleanup:
3874 if (target_path != buf) {
3875 PyMem_Free(target_path);
3876 }
3877 CloseHandle(hFile);
3878 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10003879}
Brian Curtin62857742010-09-06 17:07:27 +00003880
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003881/*[clinic input]
3882os._isdir
3883
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003884 path as arg: object
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003885 /
3886
Serhiy Storchaka579f0382016-11-08 20:21:22 +02003887Return true if the pathname refers to an existing directory.
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003888[clinic start generated code]*/
3889
Brian Curtin9c669cc2011-06-08 18:17:18 -05003890static PyObject *
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003891os__isdir(PyObject *module, PyObject *arg)
3892/*[clinic end generated code: output=404f334d85d4bf25 input=36cb6785874d479e]*/
Brian Curtin9c669cc2011-06-08 18:17:18 -05003893{
Brian Curtin9c669cc2011-06-08 18:17:18 -05003894 DWORD attributes;
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003895 path_t path = PATH_T_INITIALIZE("_isdir", "path", 0, 0);
3896
3897 if (!path_converter(arg, &path)) {
3898 if (PyErr_ExceptionMatches(PyExc_ValueError)) {
3899 PyErr_Clear();
3900 Py_RETURN_FALSE;
3901 }
3902 return NULL;
3903 }
Brian Curtin9c669cc2011-06-08 18:17:18 -05003904
Steve Dowerb22a6772016-07-17 20:49:38 -07003905 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003906 attributes = GetFileAttributesW(path.wide);
Steve Dowerb22a6772016-07-17 20:49:38 -07003907 Py_END_ALLOW_THREADS
Brian Curtin9c669cc2011-06-08 18:17:18 -05003908
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003909 path_cleanup(&path);
Brian Curtin9c669cc2011-06-08 18:17:18 -05003910 if (attributes == INVALID_FILE_ATTRIBUTES)
3911 Py_RETURN_FALSE;
3912
Brian Curtin9c669cc2011-06-08 18:17:18 -05003913 if (attributes & FILE_ATTRIBUTE_DIRECTORY)
3914 Py_RETURN_TRUE;
3915 else
3916 Py_RETURN_FALSE;
3917}
Tim Golden6b528062013-08-01 12:44:00 +01003918
Tim Golden6b528062013-08-01 12:44:00 +01003919
Larry Hastings2f936352014-08-05 14:04:04 +10003920/*[clinic input]
3921os._getvolumepathname
3922
Steve Dower23ad6d02018-02-22 10:39:10 -08003923 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003924
3925A helper function for ismount on Win32.
3926[clinic start generated code]*/
3927
Larry Hastings2f936352014-08-05 14:04:04 +10003928static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003929os__getvolumepathname_impl(PyObject *module, path_t *path)
3930/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003931{
3932 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003933 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01003934 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01003935 BOOL ret;
3936
Tim Golden6b528062013-08-01 12:44:00 +01003937 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08003938 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01003939
Victor Stinner850a18e2017-10-24 16:53:32 -07003940 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01003941 PyErr_SetString(PyExc_OverflowError, "path too long");
3942 return NULL;
3943 }
3944
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003945 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01003946 if (mountpath == NULL)
3947 return PyErr_NoMemory();
3948
3949 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08003950 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01003951 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01003952 Py_END_ALLOW_THREADS
3953
3954 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08003955 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01003956 goto exit;
3957 }
3958 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08003959 if (path->narrow)
3960 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01003961
3962exit:
3963 PyMem_Free(mountpath);
3964 return result;
3965}
Tim Golden6b528062013-08-01 12:44:00 +01003966
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003967#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00003968
Larry Hastings2f936352014-08-05 14:04:04 +10003969
3970/*[clinic input]
3971os.mkdir
3972
3973 path : path_t
3974
3975 mode: int = 0o777
3976
3977 *
3978
3979 dir_fd : dir_fd(requires='mkdirat') = None
3980
3981# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
3982
3983Create a directory.
3984
3985If dir_fd is not None, it should be a file descriptor open to a directory,
3986 and path should be relative; path will then be relative to that directory.
3987dir_fd may not be implemented on your platform.
3988 If it is unavailable, using it will raise a NotImplementedError.
3989
3990The mode argument is ignored on Windows.
3991[clinic start generated code]*/
3992
Larry Hastings2f936352014-08-05 14:04:04 +10003993static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003994os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
3995/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003996{
3997 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003998
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003999#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004000 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004001 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004002 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004003
Larry Hastings2f936352014-08-05 14:04:04 +10004004 if (!result)
4005 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004006#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004007 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004008#if HAVE_MKDIRAT
4009 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004010 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004011 else
4012#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004013#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004014 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004015#else
Larry Hastings2f936352014-08-05 14:04:04 +10004016 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004017#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004018 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004019 if (result < 0)
4020 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004021#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004022 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004023}
4024
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004025
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004026/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4027#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004028#include <sys/resource.h>
4029#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004030
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004031
4032#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004033/*[clinic input]
4034os.nice
4035
4036 increment: int
4037 /
4038
4039Add increment to the priority of process and return the new priority.
4040[clinic start generated code]*/
4041
Larry Hastings2f936352014-08-05 14:04:04 +10004042static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004043os_nice_impl(PyObject *module, int increment)
4044/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004045{
4046 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004047
Victor Stinner8c62be82010-05-06 00:08:46 +00004048 /* There are two flavours of 'nice': one that returns the new
4049 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004050 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004051 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004052
Victor Stinner8c62be82010-05-06 00:08:46 +00004053 If we are of the nice family that returns the new priority, we
4054 need to clear errno before the call, and check if errno is filled
4055 before calling posix_error() on a returnvalue of -1, because the
4056 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004057
Victor Stinner8c62be82010-05-06 00:08:46 +00004058 errno = 0;
4059 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004060#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004061 if (value == 0)
4062 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004063#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004064 if (value == -1 && errno != 0)
4065 /* either nice() or getpriority() returned an error */
4066 return posix_error();
4067 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004068}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004069#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004070
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004071
4072#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004073/*[clinic input]
4074os.getpriority
4075
4076 which: int
4077 who: int
4078
4079Return program scheduling priority.
4080[clinic start generated code]*/
4081
Larry Hastings2f936352014-08-05 14:04:04 +10004082static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004083os_getpriority_impl(PyObject *module, int which, int who)
4084/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004085{
4086 int retval;
4087
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004088 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004089 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004090 if (errno != 0)
4091 return posix_error();
4092 return PyLong_FromLong((long)retval);
4093}
4094#endif /* HAVE_GETPRIORITY */
4095
4096
4097#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004098/*[clinic input]
4099os.setpriority
4100
4101 which: int
4102 who: int
4103 priority: int
4104
4105Set program scheduling priority.
4106[clinic start generated code]*/
4107
Larry Hastings2f936352014-08-05 14:04:04 +10004108static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004109os_setpriority_impl(PyObject *module, int which, int who, int priority)
4110/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004111{
4112 int retval;
4113
4114 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004115 if (retval == -1)
4116 return posix_error();
4117 Py_RETURN_NONE;
4118}
4119#endif /* HAVE_SETPRIORITY */
4120
4121
Barry Warsaw53699e91996-12-10 23:23:01 +00004122static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004123internal_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 +00004124{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004125 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004126 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004127
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004128#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004129 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004130 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004131#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004132 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004133#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004134
Larry Hastings9cf065c2012-06-22 16:30:09 -07004135 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4136 (dst_dir_fd != DEFAULT_DIR_FD);
4137#ifndef HAVE_RENAMEAT
4138 if (dir_fd_specified) {
4139 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004140 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004141 }
4142#endif
4143
Larry Hastings9cf065c2012-06-22 16:30:09 -07004144#ifdef MS_WINDOWS
4145 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004146 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004147 Py_END_ALLOW_THREADS
4148
Larry Hastings2f936352014-08-05 14:04:04 +10004149 if (!result)
4150 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004151
4152#else
Steve Dowercc16be82016-09-08 10:35:16 -07004153 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4154 PyErr_Format(PyExc_ValueError,
4155 "%s: src and dst must be the same type", function_name);
4156 return NULL;
4157 }
4158
Larry Hastings9cf065c2012-06-22 16:30:09 -07004159 Py_BEGIN_ALLOW_THREADS
4160#ifdef HAVE_RENAMEAT
4161 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004162 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004163 else
4164#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004165 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004166 Py_END_ALLOW_THREADS
4167
Larry Hastings2f936352014-08-05 14:04:04 +10004168 if (result)
4169 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004170#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004171 Py_RETURN_NONE;
4172}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004173
Larry Hastings2f936352014-08-05 14:04:04 +10004174
4175/*[clinic input]
4176os.rename
4177
4178 src : path_t
4179 dst : path_t
4180 *
4181 src_dir_fd : dir_fd = None
4182 dst_dir_fd : dir_fd = None
4183
4184Rename a file or directory.
4185
4186If either src_dir_fd or dst_dir_fd is not None, it should be a file
4187 descriptor open to a directory, and the respective path string (src or dst)
4188 should be relative; the path will then be relative to that directory.
4189src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4190 If they are unavailable, using them will raise a NotImplementedError.
4191[clinic start generated code]*/
4192
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004193static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004194os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004195 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004196/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004197{
Larry Hastings2f936352014-08-05 14:04:04 +10004198 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004199}
4200
Larry Hastings2f936352014-08-05 14:04:04 +10004201
4202/*[clinic input]
4203os.replace = os.rename
4204
4205Rename a file or directory, overwriting the destination.
4206
4207If either src_dir_fd or dst_dir_fd is not None, it should be a file
4208 descriptor open to a directory, and the respective path string (src or dst)
4209 should be relative; the path will then be relative to that directory.
4210src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004211 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004212[clinic start generated code]*/
4213
Larry Hastings2f936352014-08-05 14:04:04 +10004214static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004215os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4216 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004217/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004218{
4219 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4220}
4221
4222
4223/*[clinic input]
4224os.rmdir
4225
4226 path: path_t
4227 *
4228 dir_fd: dir_fd(requires='unlinkat') = None
4229
4230Remove a directory.
4231
4232If dir_fd is not None, it should be a file descriptor open to a directory,
4233 and path should be relative; path will then be relative to that directory.
4234dir_fd may not be implemented on your platform.
4235 If it is unavailable, using it will raise a NotImplementedError.
4236[clinic start generated code]*/
4237
Larry Hastings2f936352014-08-05 14:04:04 +10004238static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004239os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4240/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004241{
4242 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004243
4244 Py_BEGIN_ALLOW_THREADS
4245#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004246 /* Windows, success=1, UNIX, success=0 */
4247 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004248#else
4249#ifdef HAVE_UNLINKAT
4250 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004251 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004252 else
4253#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004254 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004255#endif
4256 Py_END_ALLOW_THREADS
4257
Larry Hastings2f936352014-08-05 14:04:04 +10004258 if (result)
4259 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004260
Larry Hastings2f936352014-08-05 14:04:04 +10004261 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004262}
4263
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004264
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004265#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004266#ifdef MS_WINDOWS
4267/*[clinic input]
4268os.system -> long
4269
4270 command: Py_UNICODE
4271
4272Execute the command in a subshell.
4273[clinic start generated code]*/
4274
Larry Hastings2f936352014-08-05 14:04:04 +10004275static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004276os_system_impl(PyObject *module, const Py_UNICODE *command)
4277/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004278{
4279 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004280
4281 if (PySys_Audit("system", "(u)", command) < 0) {
4282 return -1;
4283 }
4284
Victor Stinner8c62be82010-05-06 00:08:46 +00004285 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004286 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004287 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004288 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004289 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004290 return result;
4291}
4292#else /* MS_WINDOWS */
4293/*[clinic input]
4294os.system -> long
4295
4296 command: FSConverter
4297
4298Execute the command in a subshell.
4299[clinic start generated code]*/
4300
Larry Hastings2f936352014-08-05 14:04:04 +10004301static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004302os_system_impl(PyObject *module, PyObject *command)
4303/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004304{
4305 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004306 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004307
4308 if (PySys_Audit("system", "(O)", command) < 0) {
4309 return -1;
4310 }
4311
Larry Hastings2f936352014-08-05 14:04:04 +10004312 Py_BEGIN_ALLOW_THREADS
4313 result = system(bytes);
4314 Py_END_ALLOW_THREADS
4315 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004316}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004317#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004318#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004319
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004320
Larry Hastings2f936352014-08-05 14:04:04 +10004321/*[clinic input]
4322os.umask
4323
4324 mask: int
4325 /
4326
4327Set the current numeric umask and return the previous umask.
4328[clinic start generated code]*/
4329
Larry Hastings2f936352014-08-05 14:04:04 +10004330static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004331os_umask_impl(PyObject *module, int mask)
4332/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004333{
4334 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004335 if (i < 0)
4336 return posix_error();
4337 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004338}
4339
Brian Curtind40e6f72010-07-08 21:39:08 +00004340#ifdef MS_WINDOWS
4341
4342/* override the default DeleteFileW behavior so that directory
4343symlinks can be removed with this function, the same as with
4344Unix symlinks */
4345BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4346{
4347 WIN32_FILE_ATTRIBUTE_DATA info;
4348 WIN32_FIND_DATAW find_data;
4349 HANDLE find_data_handle;
4350 int is_directory = 0;
4351 int is_link = 0;
4352
4353 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4354 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004355
Brian Curtind40e6f72010-07-08 21:39:08 +00004356 /* Get WIN32_FIND_DATA structure for the path to determine if
4357 it is a symlink */
4358 if(is_directory &&
4359 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4360 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4361
4362 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004363 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4364 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4365 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4366 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004367 FindClose(find_data_handle);
4368 }
4369 }
4370 }
4371
4372 if (is_directory && is_link)
4373 return RemoveDirectoryW(lpFileName);
4374
4375 return DeleteFileW(lpFileName);
4376}
4377#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004378
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004379
Larry Hastings2f936352014-08-05 14:04:04 +10004380/*[clinic input]
4381os.unlink
4382
4383 path: path_t
4384 *
4385 dir_fd: dir_fd(requires='unlinkat')=None
4386
4387Remove a file (same as remove()).
4388
4389If dir_fd is not None, it should be a file descriptor open to a directory,
4390 and path should be relative; path will then be relative to that directory.
4391dir_fd may not be implemented on your platform.
4392 If it is unavailable, using it will raise a NotImplementedError.
4393
4394[clinic start generated code]*/
4395
Larry Hastings2f936352014-08-05 14:04:04 +10004396static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004397os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4398/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004399{
4400 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004401
4402 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004403 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004404#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004405 /* Windows, success=1, UNIX, success=0 */
4406 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004407#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004408#ifdef HAVE_UNLINKAT
4409 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004410 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004411 else
4412#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004413 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004414#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004415 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004416 Py_END_ALLOW_THREADS
4417
Larry Hastings2f936352014-08-05 14:04:04 +10004418 if (result)
4419 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004420
Larry Hastings2f936352014-08-05 14:04:04 +10004421 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004422}
4423
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004424
Larry Hastings2f936352014-08-05 14:04:04 +10004425/*[clinic input]
4426os.remove = os.unlink
4427
4428Remove a file (same as unlink()).
4429
4430If dir_fd is not None, it should be a file descriptor open to a directory,
4431 and path should be relative; path will then be relative to that directory.
4432dir_fd may not be implemented on your platform.
4433 If it is unavailable, using it will raise a NotImplementedError.
4434[clinic start generated code]*/
4435
Larry Hastings2f936352014-08-05 14:04:04 +10004436static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004437os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4438/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004439{
4440 return os_unlink_impl(module, path, dir_fd);
4441}
4442
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004443
Larry Hastings605a62d2012-06-24 04:33:36 -07004444static PyStructSequence_Field uname_result_fields[] = {
4445 {"sysname", "operating system name"},
4446 {"nodename", "name of machine on network (implementation-defined)"},
4447 {"release", "operating system release"},
4448 {"version", "operating system version"},
4449 {"machine", "hardware identifier"},
4450 {NULL}
4451};
4452
4453PyDoc_STRVAR(uname_result__doc__,
4454"uname_result: Result from os.uname().\n\n\
4455This object may be accessed either as a tuple of\n\
4456 (sysname, nodename, release, version, machine),\n\
4457or via the attributes sysname, nodename, release, version, and machine.\n\
4458\n\
4459See os.uname for more information.");
4460
4461static PyStructSequence_Desc uname_result_desc = {
4462 "uname_result", /* name */
4463 uname_result__doc__, /* doc */
4464 uname_result_fields,
4465 5
4466};
4467
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004468static PyTypeObject* UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07004469
4470
4471#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004472/*[clinic input]
4473os.uname
4474
4475Return an object identifying the current operating system.
4476
4477The object behaves like a named tuple with the following fields:
4478 (sysname, nodename, release, version, machine)
4479
4480[clinic start generated code]*/
4481
Larry Hastings2f936352014-08-05 14:04:04 +10004482static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004483os_uname_impl(PyObject *module)
4484/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004485{
Victor Stinner8c62be82010-05-06 00:08:46 +00004486 struct utsname u;
4487 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004488 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004489
Victor Stinner8c62be82010-05-06 00:08:46 +00004490 Py_BEGIN_ALLOW_THREADS
4491 res = uname(&u);
4492 Py_END_ALLOW_THREADS
4493 if (res < 0)
4494 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004495
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004496 value = PyStructSequence_New(UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004497 if (value == NULL)
4498 return NULL;
4499
4500#define SET(i, field) \
4501 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004502 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004503 if (!o) { \
4504 Py_DECREF(value); \
4505 return NULL; \
4506 } \
4507 PyStructSequence_SET_ITEM(value, i, o); \
4508 } \
4509
4510 SET(0, u.sysname);
4511 SET(1, u.nodename);
4512 SET(2, u.release);
4513 SET(3, u.version);
4514 SET(4, u.machine);
4515
4516#undef SET
4517
4518 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004519}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004520#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004521
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004522
Larry Hastings9cf065c2012-06-22 16:30:09 -07004523
4524typedef struct {
4525 int now;
4526 time_t atime_s;
4527 long atime_ns;
4528 time_t mtime_s;
4529 long mtime_ns;
4530} utime_t;
4531
4532/*
Victor Stinner484df002014-10-09 13:52:31 +02004533 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004534 * they also intentionally leak the declaration of a pointer named "time"
4535 */
4536#define UTIME_TO_TIMESPEC \
4537 struct timespec ts[2]; \
4538 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004539 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004540 time = NULL; \
4541 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004542 ts[0].tv_sec = ut->atime_s; \
4543 ts[0].tv_nsec = ut->atime_ns; \
4544 ts[1].tv_sec = ut->mtime_s; \
4545 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004546 time = ts; \
4547 } \
4548
4549#define UTIME_TO_TIMEVAL \
4550 struct timeval tv[2]; \
4551 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004552 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004553 time = NULL; \
4554 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004555 tv[0].tv_sec = ut->atime_s; \
4556 tv[0].tv_usec = ut->atime_ns / 1000; \
4557 tv[1].tv_sec = ut->mtime_s; \
4558 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004559 time = tv; \
4560 } \
4561
4562#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004563 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004564 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004565 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004566 time = NULL; \
4567 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004568 u.actime = ut->atime_s; \
4569 u.modtime = ut->mtime_s; \
4570 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004571 }
4572
4573#define UTIME_TO_TIME_T \
4574 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004575 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004576 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004577 time = NULL; \
4578 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004579 timet[0] = ut->atime_s; \
4580 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004581 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004582 } \
4583
4584
Victor Stinner528a9ab2015-09-03 21:30:26 +02004585#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004586
4587static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004588utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004589{
4590#ifdef HAVE_UTIMENSAT
4591 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4592 UTIME_TO_TIMESPEC;
4593 return utimensat(dir_fd, path, time, flags);
4594#elif defined(HAVE_FUTIMESAT)
4595 UTIME_TO_TIMEVAL;
4596 /*
4597 * follow_symlinks will never be false here;
4598 * we only allow !follow_symlinks and dir_fd together
4599 * if we have utimensat()
4600 */
4601 assert(follow_symlinks);
4602 return futimesat(dir_fd, path, time);
4603#endif
4604}
4605
Larry Hastings2f936352014-08-05 14:04:04 +10004606 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4607#else
4608 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004609#endif
4610
Victor Stinner528a9ab2015-09-03 21:30:26 +02004611#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004612
4613static int
Victor Stinner484df002014-10-09 13:52:31 +02004614utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004615{
4616#ifdef HAVE_FUTIMENS
4617 UTIME_TO_TIMESPEC;
4618 return futimens(fd, time);
4619#else
4620 UTIME_TO_TIMEVAL;
4621 return futimes(fd, time);
4622#endif
4623}
4624
Larry Hastings2f936352014-08-05 14:04:04 +10004625 #define PATH_UTIME_HAVE_FD 1
4626#else
4627 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004628#endif
4629
Victor Stinner5ebae872015-09-22 01:29:33 +02004630#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4631# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4632#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004633
Victor Stinner4552ced2015-09-21 22:37:15 +02004634#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004635
4636static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004637utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004638{
4639#ifdef HAVE_UTIMENSAT
4640 UTIME_TO_TIMESPEC;
4641 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4642#else
4643 UTIME_TO_TIMEVAL;
4644 return lutimes(path, time);
4645#endif
4646}
4647
4648#endif
4649
4650#ifndef MS_WINDOWS
4651
4652static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004653utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004654{
4655#ifdef HAVE_UTIMENSAT
4656 UTIME_TO_TIMESPEC;
4657 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4658#elif defined(HAVE_UTIMES)
4659 UTIME_TO_TIMEVAL;
4660 return utimes(path, time);
4661#elif defined(HAVE_UTIME_H)
4662 UTIME_TO_UTIMBUF;
4663 return utime(path, time);
4664#else
4665 UTIME_TO_TIME_T;
4666 return utime(path, time);
4667#endif
4668}
4669
4670#endif
4671
Larry Hastings76ad59b2012-05-03 00:30:07 -07004672static int
4673split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4674{
4675 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004676 PyObject *divmod;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004677 divmod = PyNumber_Divmod(py_long, billion);
4678 if (!divmod)
4679 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004680 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4681 PyErr_Format(PyExc_TypeError,
4682 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
4683 Py_TYPE(py_long)->tp_name, Py_TYPE(divmod)->tp_name);
4684 goto exit;
4685 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004686 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4687 if ((*s == -1) && PyErr_Occurred())
4688 goto exit;
4689 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004690 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004691 goto exit;
4692
4693 result = 1;
4694exit:
4695 Py_XDECREF(divmod);
4696 return result;
4697}
4698
Larry Hastings2f936352014-08-05 14:04:04 +10004699
4700/*[clinic input]
4701os.utime
4702
4703 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
4704 times: object = NULL
4705 *
4706 ns: object = NULL
4707 dir_fd: dir_fd(requires='futimensat') = None
4708 follow_symlinks: bool=True
4709
Martin Panter0ff89092015-09-09 01:56:53 +00004710# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004711
4712Set the access and modified time of path.
4713
4714path may always be specified as a string.
4715On some platforms, path may also be specified as an open file descriptor.
4716 If this functionality is unavailable, using it raises an exception.
4717
4718If times is not None, it must be a tuple (atime, mtime);
4719 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004720If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004721 atime_ns and mtime_ns should be expressed as integer nanoseconds
4722 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004723If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004724Specifying tuples for both times and ns is an error.
4725
4726If dir_fd is not None, it should be a file descriptor open to a directory,
4727 and path should be relative; path will then be relative to that directory.
4728If follow_symlinks is False, and the last element of the path is a symbolic
4729 link, utime will modify the symbolic link itself instead of the file the
4730 link points to.
4731It is an error to use dir_fd or follow_symlinks when specifying path
4732 as an open file descriptor.
4733dir_fd and follow_symlinks may not be available on your platform.
4734 If they are unavailable, using them will raise a NotImplementedError.
4735
4736[clinic start generated code]*/
4737
Larry Hastings2f936352014-08-05 14:04:04 +10004738static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004739os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4740 int dir_fd, int follow_symlinks)
4741/*[clinic end generated code: output=cfcac69d027b82cf input=081cdc54ca685385]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004742{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004743#ifdef MS_WINDOWS
4744 HANDLE hFile;
4745 FILETIME atime, mtime;
4746#else
4747 int result;
4748#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004749
Larry Hastings2f936352014-08-05 14:04:04 +10004750 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004751
Christian Heimesb3c87242013-08-01 00:08:16 +02004752 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004753
Larry Hastings9cf065c2012-06-22 16:30:09 -07004754 if (times && (times != Py_None) && ns) {
4755 PyErr_SetString(PyExc_ValueError,
4756 "utime: you may specify either 'times'"
4757 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004758 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004759 }
4760
4761 if (times && (times != Py_None)) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004762 time_t a_sec, m_sec;
4763 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004764 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004765 PyErr_SetString(PyExc_TypeError,
4766 "utime: 'times' must be either"
4767 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004768 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004769 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004770 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004771 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004772 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004773 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004774 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004775 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004776 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004777 utime.atime_s = a_sec;
4778 utime.atime_ns = a_nsec;
4779 utime.mtime_s = m_sec;
4780 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004781 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004782 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004783 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004784 PyErr_SetString(PyExc_TypeError,
4785 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004786 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004787 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004788 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004789 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004790 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004791 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004792 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004793 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004794 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004795 }
4796 else {
4797 /* times and ns are both None/unspecified. use "now". */
4798 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004799 }
4800
Victor Stinner4552ced2015-09-21 22:37:15 +02004801#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004802 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004803 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004804#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004805
Larry Hastings2f936352014-08-05 14:04:04 +10004806 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4807 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4808 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004809 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004810
Larry Hastings9cf065c2012-06-22 16:30:09 -07004811#if !defined(HAVE_UTIMENSAT)
4812 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004813 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004814 "utime: cannot use dir_fd and follow_symlinks "
4815 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004816 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004817 }
4818#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004819
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004820#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004821 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004822 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4823 NULL, OPEN_EXISTING,
4824 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004825 Py_END_ALLOW_THREADS
4826 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004827 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004828 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004829 }
4830
Larry Hastings9cf065c2012-06-22 16:30:09 -07004831 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004832 GetSystemTimeAsFileTime(&mtime);
4833 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004834 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004835 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004836 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4837 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004838 }
4839 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4840 /* Avoid putting the file name into the error here,
4841 as that may confuse the user into believing that
4842 something is wrong with the file, when it also
4843 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004844 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004845 CloseHandle(hFile);
4846 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004847 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004848 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004849#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004850 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004851
Victor Stinner4552ced2015-09-21 22:37:15 +02004852#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004853 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004854 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004855 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004856#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004857
Victor Stinner528a9ab2015-09-03 21:30:26 +02004858#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004859 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004860 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004861 else
4862#endif
4863
Victor Stinner528a9ab2015-09-03 21:30:26 +02004864#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004865 if (path->fd != -1)
4866 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004867 else
4868#endif
4869
Larry Hastings2f936352014-08-05 14:04:04 +10004870 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004871
4872 Py_END_ALLOW_THREADS
4873
4874 if (result < 0) {
4875 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004876 posix_error();
4877 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004878 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004879
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004880#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004881
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004882 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004883}
4884
Guido van Rossum3b066191991-06-04 19:40:25 +00004885/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004886
Larry Hastings2f936352014-08-05 14:04:04 +10004887
4888/*[clinic input]
4889os._exit
4890
4891 status: int
4892
4893Exit to the system with specified status, without normal exit processing.
4894[clinic start generated code]*/
4895
Larry Hastings2f936352014-08-05 14:04:04 +10004896static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004897os__exit_impl(PyObject *module, int status)
4898/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004899{
4900 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00004901 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004902}
4903
Steve Dowercc16be82016-09-08 10:35:16 -07004904#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4905#define EXECV_CHAR wchar_t
4906#else
4907#define EXECV_CHAR char
4908#endif
4909
pxinwrf2d7ac72019-05-21 18:46:37 +08004910#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00004911static void
Steve Dowercc16be82016-09-08 10:35:16 -07004912free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00004913{
Victor Stinner8c62be82010-05-06 00:08:46 +00004914 Py_ssize_t i;
4915 for (i = 0; i < count; i++)
4916 PyMem_Free(array[i]);
4917 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00004918}
Martin v. Löwis011e8422009-05-05 04:43:17 +00004919
Berker Peksag81816462016-09-15 20:19:47 +03004920static int
4921fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00004922{
Victor Stinner8c62be82010-05-06 00:08:46 +00004923 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03004924 PyObject *ub;
4925 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07004926#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03004927 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07004928 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03004929 *out = PyUnicode_AsWideCharString(ub, &size);
4930 if (*out)
4931 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07004932#else
Berker Peksag81816462016-09-15 20:19:47 +03004933 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00004934 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03004935 size = PyBytes_GET_SIZE(ub);
4936 *out = PyMem_Malloc(size + 1);
4937 if (*out) {
4938 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
4939 result = 1;
4940 } else
Victor Stinner50abf222013-11-07 23:56:10 +01004941 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07004942#endif
Berker Peksag81816462016-09-15 20:19:47 +03004943 Py_DECREF(ub);
4944 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004945}
Martin v. Löwis114619e2002-10-07 06:44:21 +00004946#endif
4947
pxinwrf2d7ac72019-05-21 18:46:37 +08004948#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07004949static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00004950parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
4951{
Victor Stinner8c62be82010-05-06 00:08:46 +00004952 Py_ssize_t i, pos, envc;
4953 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03004954 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07004955 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004956
Victor Stinner8c62be82010-05-06 00:08:46 +00004957 i = PyMapping_Size(env);
4958 if (i < 0)
4959 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07004960 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00004961 if (envlist == NULL) {
4962 PyErr_NoMemory();
4963 return NULL;
4964 }
4965 envc = 0;
4966 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01004967 if (!keys)
4968 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00004969 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01004970 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00004971 goto error;
4972 if (!PyList_Check(keys) || !PyList_Check(vals)) {
4973 PyErr_Format(PyExc_TypeError,
4974 "env.keys() or env.values() is not a list");
4975 goto error;
4976 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00004977
Victor Stinner8c62be82010-05-06 00:08:46 +00004978 for (pos = 0; pos < i; pos++) {
4979 key = PyList_GetItem(keys, pos);
4980 val = PyList_GetItem(vals, pos);
4981 if (!key || !val)
4982 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004983
Berker Peksag81816462016-09-15 20:19:47 +03004984#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4985 if (!PyUnicode_FSDecoder(key, &key2))
4986 goto error;
4987 if (!PyUnicode_FSDecoder(val, &val2)) {
4988 Py_DECREF(key2);
4989 goto error;
4990 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03004991 /* Search from index 1 because on Windows starting '=' is allowed for
4992 defining hidden environment variables. */
4993 if (PyUnicode_GET_LENGTH(key2) == 0 ||
4994 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
4995 {
4996 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04004997 Py_DECREF(key2);
4998 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03004999 goto error;
5000 }
Berker Peksag81816462016-09-15 20:19:47 +03005001 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5002#else
5003 if (!PyUnicode_FSConverter(key, &key2))
5004 goto error;
5005 if (!PyUnicode_FSConverter(val, &val2)) {
5006 Py_DECREF(key2);
5007 goto error;
5008 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005009 if (PyBytes_GET_SIZE(key2) == 0 ||
5010 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5011 {
5012 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005013 Py_DECREF(key2);
5014 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005015 goto error;
5016 }
Berker Peksag81816462016-09-15 20:19:47 +03005017 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5018 PyBytes_AS_STRING(val2));
5019#endif
5020 Py_DECREF(key2);
5021 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005022 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005023 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005024
5025 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5026 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005027 goto error;
5028 }
Berker Peksag81816462016-09-15 20:19:47 +03005029
Steve Dowercc16be82016-09-08 10:35:16 -07005030 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005031 }
5032 Py_DECREF(vals);
5033 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005034
Victor Stinner8c62be82010-05-06 00:08:46 +00005035 envlist[envc] = 0;
5036 *envc_ptr = envc;
5037 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005038
5039error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005040 Py_XDECREF(keys);
5041 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005042 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005043 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005044}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005045
Steve Dowercc16be82016-09-08 10:35:16 -07005046static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005047parse_arglist(PyObject* argv, Py_ssize_t *argc)
5048{
5049 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005050 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005051 if (argvlist == NULL) {
5052 PyErr_NoMemory();
5053 return NULL;
5054 }
5055 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005056 PyObject* item = PySequence_ITEM(argv, i);
5057 if (item == NULL)
5058 goto fail;
5059 if (!fsconvert_strdup(item, &argvlist[i])) {
5060 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005061 goto fail;
5062 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005063 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005064 }
5065 argvlist[*argc] = NULL;
5066 return argvlist;
5067fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005068 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005069 free_string_array(argvlist, *argc);
5070 return NULL;
5071}
Steve Dowercc16be82016-09-08 10:35:16 -07005072
Ross Lagerwall7807c352011-03-17 20:20:30 +02005073#endif
5074
Larry Hastings2f936352014-08-05 14:04:04 +10005075
Ross Lagerwall7807c352011-03-17 20:20:30 +02005076#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005077/*[clinic input]
5078os.execv
5079
Steve Dowercc16be82016-09-08 10:35:16 -07005080 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005081 Path of executable file.
5082 argv: object
5083 Tuple or list of strings.
5084 /
5085
5086Execute an executable path with arguments, replacing current process.
5087[clinic start generated code]*/
5088
Larry Hastings2f936352014-08-05 14:04:04 +10005089static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005090os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5091/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005092{
Steve Dowercc16be82016-09-08 10:35:16 -07005093 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005094 Py_ssize_t argc;
5095
5096 /* execv has two arguments: (path, argv), where
5097 argv is a list or tuple of strings. */
5098
Ross Lagerwall7807c352011-03-17 20:20:30 +02005099 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5100 PyErr_SetString(PyExc_TypeError,
5101 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005102 return NULL;
5103 }
5104 argc = PySequence_Size(argv);
5105 if (argc < 1) {
5106 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005107 return NULL;
5108 }
5109
5110 argvlist = parse_arglist(argv, &argc);
5111 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005112 return NULL;
5113 }
Steve Dowerbce26262016-11-19 19:17:26 -08005114 if (!argvlist[0][0]) {
5115 PyErr_SetString(PyExc_ValueError,
5116 "execv() arg 2 first element cannot be empty");
5117 free_string_array(argvlist, argc);
5118 return NULL;
5119 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005120
Steve Dowerbce26262016-11-19 19:17:26 -08005121 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005122#ifdef HAVE_WEXECV
5123 _wexecv(path->wide, argvlist);
5124#else
5125 execv(path->narrow, argvlist);
5126#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005127 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005128
5129 /* If we get here it's definitely an error */
5130
5131 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005132 return posix_error();
5133}
5134
Larry Hastings2f936352014-08-05 14:04:04 +10005135
5136/*[clinic input]
5137os.execve
5138
5139 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5140 Path of executable file.
5141 argv: object
5142 Tuple or list of strings.
5143 env: object
5144 Dictionary of strings mapping to strings.
5145
5146Execute an executable path with arguments, replacing current process.
5147[clinic start generated code]*/
5148
Larry Hastings2f936352014-08-05 14:04:04 +10005149static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005150os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5151/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005152{
Steve Dowercc16be82016-09-08 10:35:16 -07005153 EXECV_CHAR **argvlist = NULL;
5154 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005155 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005156
Victor Stinner8c62be82010-05-06 00:08:46 +00005157 /* execve has three arguments: (path, argv, env), where
5158 argv is a list or tuple of strings and env is a dictionary
5159 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005160
Ross Lagerwall7807c352011-03-17 20:20:30 +02005161 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005162 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005163 "execve: argv must be a tuple or list");
5164 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005165 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005166 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005167 if (argc < 1) {
5168 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5169 return NULL;
5170 }
5171
Victor Stinner8c62be82010-05-06 00:08:46 +00005172 if (!PyMapping_Check(env)) {
5173 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005174 "execve: environment must be a mapping object");
5175 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005176 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005177
Ross Lagerwall7807c352011-03-17 20:20:30 +02005178 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005179 if (argvlist == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005180 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005181 }
Steve Dowerbce26262016-11-19 19:17:26 -08005182 if (!argvlist[0][0]) {
5183 PyErr_SetString(PyExc_ValueError,
5184 "execve: argv first element cannot be empty");
5185 goto fail;
5186 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005187
Victor Stinner8c62be82010-05-06 00:08:46 +00005188 envlist = parse_envlist(env, &envc);
5189 if (envlist == NULL)
Ross Lagerwall7807c352011-03-17 20:20:30 +02005190 goto fail;
5191
Steve Dowerbce26262016-11-19 19:17:26 -08005192 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005193#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005194 if (path->fd > -1)
5195 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005196 else
5197#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005198#ifdef HAVE_WEXECV
5199 _wexecve(path->wide, argvlist, envlist);
5200#else
Larry Hastings2f936352014-08-05 14:04:04 +10005201 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005202#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005203 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005204
5205 /* If we get here it's definitely an error */
5206
Alexey Izbyshev83460312018-10-20 03:28:22 +03005207 posix_path_error(path);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005208
Steve Dowercc16be82016-09-08 10:35:16 -07005209 free_string_array(envlist, envc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005210 fail:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005211 if (argvlist)
5212 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005213 return NULL;
5214}
Steve Dowercc16be82016-09-08 10:35:16 -07005215
Larry Hastings9cf065c2012-06-22 16:30:09 -07005216#endif /* HAVE_EXECV */
5217
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005218#ifdef HAVE_POSIX_SPAWN
5219
5220enum posix_spawn_file_actions_identifier {
5221 POSIX_SPAWN_OPEN,
5222 POSIX_SPAWN_CLOSE,
5223 POSIX_SPAWN_DUP2
5224};
5225
William Orr81574b82018-10-01 22:19:56 -07005226#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005227static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005228convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005229#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005230
5231static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005232parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5233 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005234 PyObject *setsigdef, PyObject *scheduler,
5235 posix_spawnattr_t *attrp)
5236{
5237 long all_flags = 0;
5238
5239 errno = posix_spawnattr_init(attrp);
5240 if (errno) {
5241 posix_error();
5242 return -1;
5243 }
5244
5245 if (setpgroup) {
5246 pid_t pgid = PyLong_AsPid(setpgroup);
5247 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5248 goto fail;
5249 }
5250 errno = posix_spawnattr_setpgroup(attrp, pgid);
5251 if (errno) {
5252 posix_error();
5253 goto fail;
5254 }
5255 all_flags |= POSIX_SPAWN_SETPGROUP;
5256 }
5257
5258 if (resetids) {
5259 all_flags |= POSIX_SPAWN_RESETIDS;
5260 }
5261
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005262 if (setsid) {
5263#ifdef POSIX_SPAWN_SETSID
5264 all_flags |= POSIX_SPAWN_SETSID;
5265#elif defined(POSIX_SPAWN_SETSID_NP)
5266 all_flags |= POSIX_SPAWN_SETSID_NP;
5267#else
5268 argument_unavailable_error(func_name, "setsid");
5269 return -1;
5270#endif
5271 }
5272
Pablo Galindo254a4662018-09-07 16:44:24 +01005273 if (setsigmask) {
5274 sigset_t set;
5275 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5276 goto fail;
5277 }
5278 errno = posix_spawnattr_setsigmask(attrp, &set);
5279 if (errno) {
5280 posix_error();
5281 goto fail;
5282 }
5283 all_flags |= POSIX_SPAWN_SETSIGMASK;
5284 }
5285
5286 if (setsigdef) {
5287 sigset_t set;
5288 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5289 goto fail;
5290 }
5291 errno = posix_spawnattr_setsigdefault(attrp, &set);
5292 if (errno) {
5293 posix_error();
5294 goto fail;
5295 }
5296 all_flags |= POSIX_SPAWN_SETSIGDEF;
5297 }
5298
5299 if (scheduler) {
5300#ifdef POSIX_SPAWN_SETSCHEDULER
5301 PyObject *py_schedpolicy;
5302 struct sched_param schedparam;
5303
5304 if (!PyArg_ParseTuple(scheduler, "OO&"
5305 ";A scheduler tuple must have two elements",
5306 &py_schedpolicy, convert_sched_param, &schedparam)) {
5307 goto fail;
5308 }
5309 if (py_schedpolicy != Py_None) {
5310 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5311
5312 if (schedpolicy == -1 && PyErr_Occurred()) {
5313 goto fail;
5314 }
5315 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5316 if (errno) {
5317 posix_error();
5318 goto fail;
5319 }
5320 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5321 }
5322 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5323 if (errno) {
5324 posix_error();
5325 goto fail;
5326 }
5327 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5328#else
5329 PyErr_SetString(PyExc_NotImplementedError,
5330 "The scheduler option is not supported in this system.");
5331 goto fail;
5332#endif
5333 }
5334
5335 errno = posix_spawnattr_setflags(attrp, all_flags);
5336 if (errno) {
5337 posix_error();
5338 goto fail;
5339 }
5340
5341 return 0;
5342
5343fail:
5344 (void)posix_spawnattr_destroy(attrp);
5345 return -1;
5346}
5347
5348static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005349parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005350 posix_spawn_file_actions_t *file_actionsp,
5351 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005352{
5353 PyObject *seq;
5354 PyObject *file_action = NULL;
5355 PyObject *tag_obj;
5356
5357 seq = PySequence_Fast(file_actions,
5358 "file_actions must be a sequence or None");
5359 if (seq == NULL) {
5360 return -1;
5361 }
5362
5363 errno = posix_spawn_file_actions_init(file_actionsp);
5364 if (errno) {
5365 posix_error();
5366 Py_DECREF(seq);
5367 return -1;
5368 }
5369
5370 for (int i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
5371 file_action = PySequence_Fast_GET_ITEM(seq, i);
5372 Py_INCREF(file_action);
5373 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5374 PyErr_SetString(PyExc_TypeError,
5375 "Each file_actions element must be a non-empty tuple");
5376 goto fail;
5377 }
5378 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5379 if (tag == -1 && PyErr_Occurred()) {
5380 goto fail;
5381 }
5382
5383 /* Populate the file_actions object */
5384 switch (tag) {
5385 case POSIX_SPAWN_OPEN: {
5386 int fd, oflag;
5387 PyObject *path;
5388 unsigned long mode;
5389 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5390 ";A open file_action tuple must have 5 elements",
5391 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5392 &oflag, &mode))
5393 {
5394 goto fail;
5395 }
Pablo Galindocb970732018-06-19 09:19:50 +01005396 if (PyList_Append(temp_buffer, path)) {
5397 Py_DECREF(path);
5398 goto fail;
5399 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005400 errno = posix_spawn_file_actions_addopen(file_actionsp,
5401 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005402 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005403 if (errno) {
5404 posix_error();
5405 goto fail;
5406 }
5407 break;
5408 }
5409 case POSIX_SPAWN_CLOSE: {
5410 int fd;
5411 if (!PyArg_ParseTuple(file_action, "Oi"
5412 ";A close file_action tuple must have 2 elements",
5413 &tag_obj, &fd))
5414 {
5415 goto fail;
5416 }
5417 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5418 if (errno) {
5419 posix_error();
5420 goto fail;
5421 }
5422 break;
5423 }
5424 case POSIX_SPAWN_DUP2: {
5425 int fd1, fd2;
5426 if (!PyArg_ParseTuple(file_action, "Oii"
5427 ";A dup2 file_action tuple must have 3 elements",
5428 &tag_obj, &fd1, &fd2))
5429 {
5430 goto fail;
5431 }
5432 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5433 fd1, fd2);
5434 if (errno) {
5435 posix_error();
5436 goto fail;
5437 }
5438 break;
5439 }
5440 default: {
5441 PyErr_SetString(PyExc_TypeError,
5442 "Unknown file_actions identifier");
5443 goto fail;
5444 }
5445 }
5446 Py_DECREF(file_action);
5447 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005448
Serhiy Storchakaef347532018-05-01 16:45:04 +03005449 Py_DECREF(seq);
5450 return 0;
5451
5452fail:
5453 Py_DECREF(seq);
5454 Py_DECREF(file_action);
5455 (void)posix_spawn_file_actions_destroy(file_actionsp);
5456 return -1;
5457}
5458
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005459
5460static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005461py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5462 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005463 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005464 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005465{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005466 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005467 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005468 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005469 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005470 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005471 posix_spawnattr_t attr;
5472 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005473 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005474 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005475 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005476 pid_t pid;
5477 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005478
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005479 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005480 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005481 like posix.environ. */
5482
Serhiy Storchakaef347532018-05-01 16:45:04 +03005483 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005484 PyErr_Format(PyExc_TypeError,
5485 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005486 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005487 }
5488 argc = PySequence_Size(argv);
5489 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005490 PyErr_Format(PyExc_ValueError,
5491 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005492 return NULL;
5493 }
5494
5495 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005496 PyErr_Format(PyExc_TypeError,
5497 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005498 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005499 }
5500
5501 argvlist = parse_arglist(argv, &argc);
5502 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005503 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005504 }
5505 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005506 PyErr_Format(PyExc_ValueError,
5507 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005508 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005509 }
5510
5511 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005512 if (envlist == NULL) {
5513 goto exit;
5514 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005515
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005516 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005517 /* There is a bug in old versions of glibc that makes some of the
5518 * helper functions for manipulating file actions not copy the provided
5519 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5520 * copy the value of path for some old versions of glibc (<2.20).
5521 * The use of temp_buffer here is a workaround that keeps the
5522 * python objects that own the buffers alive until posix_spawn gets called.
5523 * Check https://bugs.python.org/issue33630 and
5524 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5525 temp_buffer = PyList_New(0);
5526 if (!temp_buffer) {
5527 goto exit;
5528 }
5529 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005530 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005531 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005532 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005533 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005534
Victor Stinner325e4ba2019-02-01 15:47:24 +01005535 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5536 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005537 goto exit;
5538 }
5539 attrp = &attr;
5540
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005541 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005542#ifdef HAVE_POSIX_SPAWNP
5543 if (use_posix_spawnp) {
5544 err_code = posix_spawnp(&pid, path->narrow,
5545 file_actionsp, attrp, argvlist, envlist);
5546 }
5547 else
5548#endif /* HAVE_POSIX_SPAWNP */
5549 {
5550 err_code = posix_spawn(&pid, path->narrow,
5551 file_actionsp, attrp, argvlist, envlist);
5552 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005553 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005554
Serhiy Storchakaef347532018-05-01 16:45:04 +03005555 if (err_code) {
5556 errno = err_code;
5557 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005558 goto exit;
5559 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005560#ifdef _Py_MEMORY_SANITIZER
5561 __msan_unpoison(&pid, sizeof(pid));
5562#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005563 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005564
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005565exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005566 if (file_actionsp) {
5567 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005568 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005569 if (attrp) {
5570 (void)posix_spawnattr_destroy(attrp);
5571 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005572 if (envlist) {
5573 free_string_array(envlist, envc);
5574 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005575 if (argvlist) {
5576 free_string_array(argvlist, argc);
5577 }
Pablo Galindocb970732018-06-19 09:19:50 +01005578 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005579 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005580}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005581
5582
5583/*[clinic input]
5584
5585os.posix_spawn
5586 path: path_t
5587 Path of executable file.
5588 argv: object
5589 Tuple or list of strings.
5590 env: object
5591 Dictionary of strings mapping to strings.
5592 /
5593 *
5594 file_actions: object(c_default='NULL') = ()
5595 A sequence of file action tuples.
5596 setpgroup: object = NULL
5597 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5598 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005599 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5600 setsid: bool(accept={int}) = False
5601 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005602 setsigmask: object(c_default='NULL') = ()
5603 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5604 setsigdef: object(c_default='NULL') = ()
5605 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5606 scheduler: object = NULL
5607 A tuple with the scheduler policy (optional) and parameters.
5608
5609Execute the program specified by path in a new process.
5610[clinic start generated code]*/
5611
5612static PyObject *
5613os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5614 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005615 PyObject *setpgroup, int resetids, int setsid,
5616 PyObject *setsigmask, PyObject *setsigdef,
5617 PyObject *scheduler)
5618/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005619{
5620 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005621 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005622 scheduler);
5623}
5624 #endif /* HAVE_POSIX_SPAWN */
5625
5626
5627
5628#ifdef HAVE_POSIX_SPAWNP
5629/*[clinic input]
5630
5631os.posix_spawnp
5632 path: path_t
5633 Path of executable file.
5634 argv: object
5635 Tuple or list of strings.
5636 env: object
5637 Dictionary of strings mapping to strings.
5638 /
5639 *
5640 file_actions: object(c_default='NULL') = ()
5641 A sequence of file action tuples.
5642 setpgroup: object = NULL
5643 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5644 resetids: bool(accept={int}) = False
5645 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005646 setsid: bool(accept={int}) = False
5647 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005648 setsigmask: object(c_default='NULL') = ()
5649 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5650 setsigdef: object(c_default='NULL') = ()
5651 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5652 scheduler: object = NULL
5653 A tuple with the scheduler policy (optional) and parameters.
5654
5655Execute the program specified by path in a new process.
5656[clinic start generated code]*/
5657
5658static PyObject *
5659os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5660 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005661 PyObject *setpgroup, int resetids, int setsid,
5662 PyObject *setsigmask, PyObject *setsigdef,
5663 PyObject *scheduler)
5664/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005665{
5666 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005667 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005668 scheduler);
5669}
5670#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005671
pxinwrf2d7ac72019-05-21 18:46:37 +08005672#ifdef HAVE_RTPSPAWN
5673static intptr_t
5674_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5675 const char *envp[])
5676{
5677 RTP_ID rtpid;
5678 int status;
5679 pid_t res;
5680 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005681
pxinwrf2d7ac72019-05-21 18:46:37 +08005682 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5683 uStackSize=0 cannot be used, the default stack size is too small for
5684 Python. */
5685 if (envp) {
5686 rtpid = rtpSpawn(rtpFileName, argv, envp,
5687 100, 0x1000000, 0, VX_FP_TASK);
5688 }
5689 else {
5690 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5691 100, 0x1000000, 0, VX_FP_TASK);
5692 }
5693 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5694 do {
5695 res = waitpid((pid_t)rtpid, &status, 0);
5696 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5697
5698 if (res < 0)
5699 return RTP_ID_ERROR;
5700 return ((intptr_t)status);
5701 }
5702 return ((intptr_t)rtpid);
5703}
5704#endif
5705
5706#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005707/*[clinic input]
5708os.spawnv
5709
5710 mode: int
5711 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005712 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005713 Path of executable file.
5714 argv: object
5715 Tuple or list of strings.
5716 /
5717
5718Execute the program specified by path in a new process.
5719[clinic start generated code]*/
5720
Larry Hastings2f936352014-08-05 14:04:04 +10005721static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005722os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5723/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005724{
Steve Dowercc16be82016-09-08 10:35:16 -07005725 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005726 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005727 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005728 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005729 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005730
Victor Stinner8c62be82010-05-06 00:08:46 +00005731 /* spawnv has three arguments: (mode, path, argv), where
5732 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005733
Victor Stinner8c62be82010-05-06 00:08:46 +00005734 if (PyList_Check(argv)) {
5735 argc = PyList_Size(argv);
5736 getitem = PyList_GetItem;
5737 }
5738 else if (PyTuple_Check(argv)) {
5739 argc = PyTuple_Size(argv);
5740 getitem = PyTuple_GetItem;
5741 }
5742 else {
5743 PyErr_SetString(PyExc_TypeError,
5744 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005745 return NULL;
5746 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005747 if (argc == 0) {
5748 PyErr_SetString(PyExc_ValueError,
5749 "spawnv() arg 2 cannot be empty");
5750 return NULL;
5751 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005752
Steve Dowercc16be82016-09-08 10:35:16 -07005753 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005754 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005755 return PyErr_NoMemory();
5756 }
5757 for (i = 0; i < argc; i++) {
5758 if (!fsconvert_strdup((*getitem)(argv, i),
5759 &argvlist[i])) {
5760 free_string_array(argvlist, i);
5761 PyErr_SetString(
5762 PyExc_TypeError,
5763 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005764 return NULL;
5765 }
Steve Dower93ff8722016-11-19 19:03:54 -08005766 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005767 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005768 PyErr_SetString(
5769 PyExc_ValueError,
5770 "spawnv() arg 2 first element cannot be empty");
5771 return NULL;
5772 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005773 }
5774 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005775
pxinwrf2d7ac72019-05-21 18:46:37 +08005776#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005777 if (mode == _OLD_P_OVERLAY)
5778 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005779#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005780
Victor Stinner8c62be82010-05-06 00:08:46 +00005781 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005782 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005783#ifdef HAVE_WSPAWNV
5784 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005785#elif defined(HAVE_RTPSPAWN)
5786 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005787#else
5788 spawnval = _spawnv(mode, path->narrow, argvlist);
5789#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005790 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005791 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005792
Victor Stinner8c62be82010-05-06 00:08:46 +00005793 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005794
Victor Stinner8c62be82010-05-06 00:08:46 +00005795 if (spawnval == -1)
5796 return posix_error();
5797 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005798 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005799}
5800
Larry Hastings2f936352014-08-05 14:04:04 +10005801/*[clinic input]
5802os.spawnve
5803
5804 mode: int
5805 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005806 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005807 Path of executable file.
5808 argv: object
5809 Tuple or list of strings.
5810 env: object
5811 Dictionary of strings mapping to strings.
5812 /
5813
5814Execute the program specified by path in a new process.
5815[clinic start generated code]*/
5816
Larry Hastings2f936352014-08-05 14:04:04 +10005817static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005818os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005819 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005820/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005821{
Steve Dowercc16be82016-09-08 10:35:16 -07005822 EXECV_CHAR **argvlist;
5823 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005824 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005825 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005826 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005827 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005828 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005829
Victor Stinner8c62be82010-05-06 00:08:46 +00005830 /* spawnve has four arguments: (mode, path, argv, env), where
5831 argv is a list or tuple of strings and env is a dictionary
5832 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005833
Victor Stinner8c62be82010-05-06 00:08:46 +00005834 if (PyList_Check(argv)) {
5835 argc = PyList_Size(argv);
5836 getitem = PyList_GetItem;
5837 }
5838 else if (PyTuple_Check(argv)) {
5839 argc = PyTuple_Size(argv);
5840 getitem = PyTuple_GetItem;
5841 }
5842 else {
5843 PyErr_SetString(PyExc_TypeError,
5844 "spawnve() arg 2 must be a tuple or list");
5845 goto fail_0;
5846 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005847 if (argc == 0) {
5848 PyErr_SetString(PyExc_ValueError,
5849 "spawnve() arg 2 cannot be empty");
5850 goto fail_0;
5851 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005852 if (!PyMapping_Check(env)) {
5853 PyErr_SetString(PyExc_TypeError,
5854 "spawnve() arg 3 must be a mapping object");
5855 goto fail_0;
5856 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005857
Steve Dowercc16be82016-09-08 10:35:16 -07005858 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005859 if (argvlist == NULL) {
5860 PyErr_NoMemory();
5861 goto fail_0;
5862 }
5863 for (i = 0; i < argc; i++) {
5864 if (!fsconvert_strdup((*getitem)(argv, i),
5865 &argvlist[i]))
5866 {
5867 lastarg = i;
5868 goto fail_1;
5869 }
Steve Dowerbce26262016-11-19 19:17:26 -08005870 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005871 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08005872 PyErr_SetString(
5873 PyExc_ValueError,
5874 "spawnv() arg 2 first element cannot be empty");
5875 goto fail_1;
5876 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005877 }
5878 lastarg = argc;
5879 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005880
Victor Stinner8c62be82010-05-06 00:08:46 +00005881 envlist = parse_envlist(env, &envc);
5882 if (envlist == NULL)
5883 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00005884
pxinwrf2d7ac72019-05-21 18:46:37 +08005885#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005886 if (mode == _OLD_P_OVERLAY)
5887 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005888#endif
Tim Peters25059d32001-12-07 20:35:43 +00005889
Victor Stinner8c62be82010-05-06 00:08:46 +00005890 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005891 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005892#ifdef HAVE_WSPAWNV
5893 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005894#elif defined(HAVE_RTPSPAWN)
5895 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
5896 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005897#else
5898 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
5899#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005900 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005901 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00005902
Victor Stinner8c62be82010-05-06 00:08:46 +00005903 if (spawnval == -1)
5904 (void) posix_error();
5905 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005906 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005907
Victor Stinner8c62be82010-05-06 00:08:46 +00005908 while (--envc >= 0)
5909 PyMem_DEL(envlist[envc]);
5910 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00005911 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005912 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005913 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00005914 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00005915}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00005916
Guido van Rossuma1065681999-01-25 23:20:23 +00005917#endif /* HAVE_SPAWNV */
5918
5919
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005920#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07005921
5922/* Helper function to validate arguments.
5923 Returns 0 on success. non-zero on failure with a TypeError raised.
5924 If obj is non-NULL it must be callable. */
5925static int
5926check_null_or_callable(PyObject *obj, const char* obj_name)
5927{
5928 if (obj && !PyCallable_Check(obj)) {
5929 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
5930 obj_name, Py_TYPE(obj)->tp_name);
5931 return -1;
5932 }
5933 return 0;
5934}
5935
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005936/*[clinic input]
5937os.register_at_fork
5938
Gregory P. Smith163468a2017-05-29 10:03:41 -07005939 *
5940 before: object=NULL
5941 A callable to be called in the parent before the fork() syscall.
5942 after_in_child: object=NULL
5943 A callable to be called in the child after fork().
5944 after_in_parent: object=NULL
5945 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005946
Gregory P. Smith163468a2017-05-29 10:03:41 -07005947Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005948
Gregory P. Smith163468a2017-05-29 10:03:41 -07005949'before' callbacks are called in reverse order.
5950'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005951
5952[clinic start generated code]*/
5953
5954static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07005955os_register_at_fork_impl(PyObject *module, PyObject *before,
5956 PyObject *after_in_child, PyObject *after_in_parent)
5957/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005958{
5959 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005960
Gregory P. Smith163468a2017-05-29 10:03:41 -07005961 if (!before && !after_in_child && !after_in_parent) {
5962 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
5963 return NULL;
5964 }
5965 if (check_null_or_callable(before, "before") ||
5966 check_null_or_callable(after_in_child, "after_in_child") ||
5967 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005968 return NULL;
5969 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02005970 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005971
Gregory P. Smith163468a2017-05-29 10:03:41 -07005972 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005973 return NULL;
5974 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07005975 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005976 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07005977 }
5978 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
5979 return NULL;
5980 }
5981 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005982}
5983#endif /* HAVE_FORK */
5984
5985
Guido van Rossum2242f2f2001-04-11 20:58:20 +00005986#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10005987/*[clinic input]
5988os.fork1
5989
5990Fork a child process with a single multiplexed (i.e., not bound) thread.
5991
5992Return 0 to child process and PID of child to parent process.
5993[clinic start generated code]*/
5994
Larry Hastings2f936352014-08-05 14:04:04 +10005995static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005996os_fork1_impl(PyObject *module)
5997/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00005998{
Victor Stinner8c62be82010-05-06 00:08:46 +00005999 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006000
Eric Snow59032962018-09-14 14:17:20 -07006001 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6002 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6003 return NULL;
6004 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006005 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006006 pid = fork1();
6007 if (pid == 0) {
6008 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006009 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006010 } else {
6011 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006012 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006013 }
6014 if (pid == -1)
6015 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006016 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006017}
Larry Hastings2f936352014-08-05 14:04:04 +10006018#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006019
6020
Guido van Rossumad0ee831995-03-01 10:34:45 +00006021#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006022/*[clinic input]
6023os.fork
6024
6025Fork a child process.
6026
6027Return 0 to child process and PID of child to parent process.
6028[clinic start generated code]*/
6029
Larry Hastings2f936352014-08-05 14:04:04 +10006030static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006031os_fork_impl(PyObject *module)
6032/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006033{
Victor Stinner8c62be82010-05-06 00:08:46 +00006034 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006035
Eric Snow59032962018-09-14 14:17:20 -07006036 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6037 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6038 return NULL;
6039 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006040 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006041 pid = fork();
6042 if (pid == 0) {
6043 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006044 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006045 } else {
6046 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006047 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006048 }
6049 if (pid == -1)
6050 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006051 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006052}
Larry Hastings2f936352014-08-05 14:04:04 +10006053#endif /* HAVE_FORK */
6054
Guido van Rossum85e3b011991-06-03 12:42:10 +00006055
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006056#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006057#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006058/*[clinic input]
6059os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006060
Larry Hastings2f936352014-08-05 14:04:04 +10006061 policy: int
6062
6063Get the maximum scheduling priority for policy.
6064[clinic start generated code]*/
6065
Larry Hastings2f936352014-08-05 14:04:04 +10006066static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006067os_sched_get_priority_max_impl(PyObject *module, int policy)
6068/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006069{
6070 int max;
6071
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006072 max = sched_get_priority_max(policy);
6073 if (max < 0)
6074 return posix_error();
6075 return PyLong_FromLong(max);
6076}
6077
Larry Hastings2f936352014-08-05 14:04:04 +10006078
6079/*[clinic input]
6080os.sched_get_priority_min
6081
6082 policy: int
6083
6084Get the minimum scheduling priority for policy.
6085[clinic start generated code]*/
6086
Larry Hastings2f936352014-08-05 14:04:04 +10006087static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006088os_sched_get_priority_min_impl(PyObject *module, int policy)
6089/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006090{
6091 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006092 if (min < 0)
6093 return posix_error();
6094 return PyLong_FromLong(min);
6095}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006096#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6097
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006098
Larry Hastings2f936352014-08-05 14:04:04 +10006099#ifdef HAVE_SCHED_SETSCHEDULER
6100/*[clinic input]
6101os.sched_getscheduler
6102 pid: pid_t
6103 /
6104
6105Get the scheduling policy for the process identifiedy by pid.
6106
6107Passing 0 for pid returns the scheduling policy for the calling process.
6108[clinic start generated code]*/
6109
Larry Hastings2f936352014-08-05 14:04:04 +10006110static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006111os_sched_getscheduler_impl(PyObject *module, pid_t pid)
6112/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=5f14cfd1f189e1a0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006113{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006114 int policy;
6115
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006116 policy = sched_getscheduler(pid);
6117 if (policy < 0)
6118 return posix_error();
6119 return PyLong_FromLong(policy);
6120}
Larry Hastings2f936352014-08-05 14:04:04 +10006121#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006122
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006123
William Orr81574b82018-10-01 22:19:56 -07006124#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006125/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006126class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006127
6128@classmethod
6129os.sched_param.__new__
6130
6131 sched_priority: object
6132 A scheduling parameter.
6133
6134Current has only one field: sched_priority");
6135[clinic start generated code]*/
6136
Larry Hastings2f936352014-08-05 14:04:04 +10006137static PyObject *
6138os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006139/*[clinic end generated code: output=48f4067d60f48c13 input=ab4de35a9a7811f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006140{
6141 PyObject *res;
6142
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006143 res = PyStructSequence_New(type);
6144 if (!res)
6145 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006146 Py_INCREF(sched_priority);
6147 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006148 return res;
6149}
6150
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006151
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006152PyDoc_VAR(os_sched_param__doc__);
6153
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006154static PyStructSequence_Field sched_param_fields[] = {
6155 {"sched_priority", "the scheduling priority"},
6156 {0}
6157};
6158
6159static PyStructSequence_Desc sched_param_desc = {
6160 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006161 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006162 sched_param_fields,
6163 1
6164};
6165
6166static int
6167convert_sched_param(PyObject *param, struct sched_param *res)
6168{
6169 long priority;
6170
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006171 if (Py_TYPE(param) != SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006172 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6173 return 0;
6174 }
6175 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6176 if (priority == -1 && PyErr_Occurred())
6177 return 0;
6178 if (priority > INT_MAX || priority < INT_MIN) {
6179 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6180 return 0;
6181 }
6182 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6183 return 1;
6184}
William Orr81574b82018-10-01 22:19:56 -07006185#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006186
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006187
6188#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006189/*[clinic input]
6190os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006191
Larry Hastings2f936352014-08-05 14:04:04 +10006192 pid: pid_t
6193 policy: int
6194 param: sched_param
6195 /
6196
6197Set the scheduling policy for the process identified by pid.
6198
6199If pid is 0, the calling process is changed.
6200param is an instance of sched_param.
6201[clinic start generated code]*/
6202
Larry Hastings2f936352014-08-05 14:04:04 +10006203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006204os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006205 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006206/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006207{
Jesus Cea9c822272011-09-10 01:40:52 +02006208 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006209 ** sched_setscheduler() returns 0 in Linux, but the previous
6210 ** scheduling policy under Solaris/Illumos, and others.
6211 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006212 */
Larry Hastings2f936352014-08-05 14:04:04 +10006213 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006214 return posix_error();
6215 Py_RETURN_NONE;
6216}
Larry Hastings2f936352014-08-05 14:04:04 +10006217#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006218
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006219
6220#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006221/*[clinic input]
6222os.sched_getparam
6223 pid: pid_t
6224 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006225
Larry Hastings2f936352014-08-05 14:04:04 +10006226Returns scheduling parameters for the process identified by pid.
6227
6228If pid is 0, returns parameters for the calling process.
6229Return value is an instance of sched_param.
6230[clinic start generated code]*/
6231
Larry Hastings2f936352014-08-05 14:04:04 +10006232static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006233os_sched_getparam_impl(PyObject *module, pid_t pid)
6234/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006235{
6236 struct sched_param param;
6237 PyObject *result;
6238 PyObject *priority;
6239
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006240 if (sched_getparam(pid, &param))
6241 return posix_error();
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006242 result = PyStructSequence_New(SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006243 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006244 return NULL;
6245 priority = PyLong_FromLong(param.sched_priority);
6246 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006247 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006248 return NULL;
6249 }
Larry Hastings2f936352014-08-05 14:04:04 +10006250 PyStructSequence_SET_ITEM(result, 0, priority);
6251 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006252}
6253
Larry Hastings2f936352014-08-05 14:04:04 +10006254
6255/*[clinic input]
6256os.sched_setparam
6257 pid: pid_t
6258 param: sched_param
6259 /
6260
6261Set scheduling parameters for the process identified by pid.
6262
6263If pid is 0, sets parameters for the calling process.
6264param should be an instance of sched_param.
6265[clinic start generated code]*/
6266
Larry Hastings2f936352014-08-05 14:04:04 +10006267static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006268os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006269 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006270/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006271{
6272 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006273 return posix_error();
6274 Py_RETURN_NONE;
6275}
Larry Hastings2f936352014-08-05 14:04:04 +10006276#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006277
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006278
6279#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006280/*[clinic input]
6281os.sched_rr_get_interval -> double
6282 pid: pid_t
6283 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006284
Larry Hastings2f936352014-08-05 14:04:04 +10006285Return the round-robin quantum for the process identified by pid, in seconds.
6286
6287Value returned is a float.
6288[clinic start generated code]*/
6289
Larry Hastings2f936352014-08-05 14:04:04 +10006290static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006291os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6292/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006293{
6294 struct timespec interval;
6295 if (sched_rr_get_interval(pid, &interval)) {
6296 posix_error();
6297 return -1.0;
6298 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006299#ifdef _Py_MEMORY_SANITIZER
6300 __msan_unpoison(&interval, sizeof(interval));
6301#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006302 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6303}
6304#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006305
Larry Hastings2f936352014-08-05 14:04:04 +10006306
6307/*[clinic input]
6308os.sched_yield
6309
6310Voluntarily relinquish the CPU.
6311[clinic start generated code]*/
6312
Larry Hastings2f936352014-08-05 14:04:04 +10006313static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006314os_sched_yield_impl(PyObject *module)
6315/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006316{
6317 if (sched_yield())
6318 return posix_error();
6319 Py_RETURN_NONE;
6320}
6321
Benjamin Peterson2740af82011-08-02 17:41:34 -05006322#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006323/* The minimum number of CPUs allocated in a cpu_set_t */
6324static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006325
Larry Hastings2f936352014-08-05 14:04:04 +10006326/*[clinic input]
6327os.sched_setaffinity
6328 pid: pid_t
6329 mask : object
6330 /
6331
6332Set the CPU affinity of the process identified by pid to mask.
6333
6334mask should be an iterable of integers identifying CPUs.
6335[clinic start generated code]*/
6336
Larry Hastings2f936352014-08-05 14:04:04 +10006337static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006338os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6339/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006340{
Antoine Pitrou84869872012-08-04 16:16:35 +02006341 int ncpus;
6342 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006343 cpu_set_t *cpu_set = NULL;
6344 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006345
Larry Hastings2f936352014-08-05 14:04:04 +10006346 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006347 if (iterator == NULL)
6348 return NULL;
6349
6350 ncpus = NCPUS_START;
6351 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006352 cpu_set = CPU_ALLOC(ncpus);
6353 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006354 PyErr_NoMemory();
6355 goto error;
6356 }
Larry Hastings2f936352014-08-05 14:04:04 +10006357 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006358
6359 while ((item = PyIter_Next(iterator))) {
6360 long cpu;
6361 if (!PyLong_Check(item)) {
6362 PyErr_Format(PyExc_TypeError,
6363 "expected an iterator of ints, "
6364 "but iterator yielded %R",
6365 Py_TYPE(item));
6366 Py_DECREF(item);
6367 goto error;
6368 }
6369 cpu = PyLong_AsLong(item);
6370 Py_DECREF(item);
6371 if (cpu < 0) {
6372 if (!PyErr_Occurred())
6373 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6374 goto error;
6375 }
6376 if (cpu > INT_MAX - 1) {
6377 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6378 goto error;
6379 }
6380 if (cpu >= ncpus) {
6381 /* Grow CPU mask to fit the CPU number */
6382 int newncpus = ncpus;
6383 cpu_set_t *newmask;
6384 size_t newsetsize;
6385 while (newncpus <= cpu) {
6386 if (newncpus > INT_MAX / 2)
6387 newncpus = cpu + 1;
6388 else
6389 newncpus = newncpus * 2;
6390 }
6391 newmask = CPU_ALLOC(newncpus);
6392 if (newmask == NULL) {
6393 PyErr_NoMemory();
6394 goto error;
6395 }
6396 newsetsize = CPU_ALLOC_SIZE(newncpus);
6397 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006398 memcpy(newmask, cpu_set, setsize);
6399 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006400 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006401 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006402 ncpus = newncpus;
6403 }
Larry Hastings2f936352014-08-05 14:04:04 +10006404 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006405 }
6406 Py_CLEAR(iterator);
6407
Larry Hastings2f936352014-08-05 14:04:04 +10006408 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006409 posix_error();
6410 goto error;
6411 }
Larry Hastings2f936352014-08-05 14:04:04 +10006412 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006413 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006414
6415error:
Larry Hastings2f936352014-08-05 14:04:04 +10006416 if (cpu_set)
6417 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006418 Py_XDECREF(iterator);
6419 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006420}
6421
Larry Hastings2f936352014-08-05 14:04:04 +10006422
6423/*[clinic input]
6424os.sched_getaffinity
6425 pid: pid_t
6426 /
6427
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006428Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006429
6430The affinity is returned as a set of CPU identifiers.
6431[clinic start generated code]*/
6432
Larry Hastings2f936352014-08-05 14:04:04 +10006433static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006434os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006435/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006436{
Antoine Pitrou84869872012-08-04 16:16:35 +02006437 int cpu, ncpus, count;
6438 size_t setsize;
6439 cpu_set_t *mask = NULL;
6440 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006441
Antoine Pitrou84869872012-08-04 16:16:35 +02006442 ncpus = NCPUS_START;
6443 while (1) {
6444 setsize = CPU_ALLOC_SIZE(ncpus);
6445 mask = CPU_ALLOC(ncpus);
6446 if (mask == NULL)
6447 return PyErr_NoMemory();
6448 if (sched_getaffinity(pid, setsize, mask) == 0)
6449 break;
6450 CPU_FREE(mask);
6451 if (errno != EINVAL)
6452 return posix_error();
6453 if (ncpus > INT_MAX / 2) {
6454 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6455 "a large enough CPU set");
6456 return NULL;
6457 }
6458 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006459 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006460
6461 res = PySet_New(NULL);
6462 if (res == NULL)
6463 goto error;
6464 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6465 if (CPU_ISSET_S(cpu, setsize, mask)) {
6466 PyObject *cpu_num = PyLong_FromLong(cpu);
6467 --count;
6468 if (cpu_num == NULL)
6469 goto error;
6470 if (PySet_Add(res, cpu_num)) {
6471 Py_DECREF(cpu_num);
6472 goto error;
6473 }
6474 Py_DECREF(cpu_num);
6475 }
6476 }
6477 CPU_FREE(mask);
6478 return res;
6479
6480error:
6481 if (mask)
6482 CPU_FREE(mask);
6483 Py_XDECREF(res);
6484 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006485}
6486
Benjamin Peterson2740af82011-08-02 17:41:34 -05006487#endif /* HAVE_SCHED_SETAFFINITY */
6488
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006489#endif /* HAVE_SCHED_H */
6490
Larry Hastings2f936352014-08-05 14:04:04 +10006491
Neal Norwitzb59798b2003-03-21 01:43:31 +00006492/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006493/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6494#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006495#define DEV_PTY_FILE "/dev/ptc"
6496#define HAVE_DEV_PTMX
6497#else
6498#define DEV_PTY_FILE "/dev/ptmx"
6499#endif
6500
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006501#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006502#ifdef HAVE_PTY_H
6503#include <pty.h>
6504#else
6505#ifdef HAVE_LIBUTIL_H
6506#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006507#else
6508#ifdef HAVE_UTIL_H
6509#include <util.h>
6510#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006511#endif /* HAVE_LIBUTIL_H */
6512#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006513#ifdef HAVE_STROPTS_H
6514#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006515#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006516#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006517
Larry Hastings2f936352014-08-05 14:04:04 +10006518
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006519#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006520/*[clinic input]
6521os.openpty
6522
6523Open a pseudo-terminal.
6524
6525Return a tuple of (master_fd, slave_fd) containing open file descriptors
6526for both the master and slave ends.
6527[clinic start generated code]*/
6528
Larry Hastings2f936352014-08-05 14:04:04 +10006529static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006530os_openpty_impl(PyObject *module)
6531/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006532{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006533 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006534#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006535 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006536#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006537#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006538 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006539#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006540 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006541#endif
6542#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006543
Thomas Wouters70c21a12000-07-14 14:28:33 +00006544#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006545 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006546 goto posix_error;
6547
6548 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6549 goto error;
6550 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6551 goto error;
6552
Neal Norwitzb59798b2003-03-21 01:43:31 +00006553#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006554 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6555 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006556 goto posix_error;
6557 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6558 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006559
Victor Stinnerdaf45552013-08-28 00:53:59 +02006560 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006561 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006562 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006563
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006564#else
Victor Stinner000de532013-11-25 23:19:58 +01006565 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006566 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006567 goto posix_error;
6568
Victor Stinner8c62be82010-05-06 00:08:46 +00006569 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006570
Victor Stinner8c62be82010-05-06 00:08:46 +00006571 /* change permission of slave */
6572 if (grantpt(master_fd) < 0) {
6573 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006574 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006575 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006576
Victor Stinner8c62be82010-05-06 00:08:46 +00006577 /* unlock slave */
6578 if (unlockpt(master_fd) < 0) {
6579 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006580 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006581 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006582
Victor Stinner8c62be82010-05-06 00:08:46 +00006583 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006584
Victor Stinner8c62be82010-05-06 00:08:46 +00006585 slave_name = ptsname(master_fd); /* get name of slave */
6586 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006587 goto posix_error;
6588
6589 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006590 if (slave_fd == -1)
6591 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006592
6593 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6594 goto posix_error;
6595
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006596#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006597 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6598 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006599#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006600 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006601#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006602#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006603#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006604
Victor Stinner8c62be82010-05-06 00:08:46 +00006605 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006606
Victor Stinnerdaf45552013-08-28 00:53:59 +02006607posix_error:
6608 posix_error();
6609error:
6610 if (master_fd != -1)
6611 close(master_fd);
6612 if (slave_fd != -1)
6613 close(slave_fd);
6614 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006615}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006616#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006617
Larry Hastings2f936352014-08-05 14:04:04 +10006618
Fred Drake8cef4cf2000-06-28 16:40:38 +00006619#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006620/*[clinic input]
6621os.forkpty
6622
6623Fork a new process with a new pseudo-terminal as controlling tty.
6624
6625Returns a tuple of (pid, master_fd).
6626Like fork(), return pid of 0 to the child process,
6627and pid of child to the parent process.
6628To both, return fd of newly opened pseudo-terminal.
6629[clinic start generated code]*/
6630
Larry Hastings2f936352014-08-05 14:04:04 +10006631static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006632os_forkpty_impl(PyObject *module)
6633/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006634{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006635 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006636 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006637
Eric Snow59032962018-09-14 14:17:20 -07006638 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6639 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6640 return NULL;
6641 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006642 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006643 pid = forkpty(&master_fd, NULL, NULL, NULL);
6644 if (pid == 0) {
6645 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006646 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006647 } else {
6648 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006649 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006650 }
6651 if (pid == -1)
6652 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006653 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006654}
Larry Hastings2f936352014-08-05 14:04:04 +10006655#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006656
Ross Lagerwall7807c352011-03-17 20:20:30 +02006657
Guido van Rossumad0ee831995-03-01 10:34:45 +00006658#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006659/*[clinic input]
6660os.getegid
6661
6662Return the current process's effective group id.
6663[clinic start generated code]*/
6664
Larry Hastings2f936352014-08-05 14:04:04 +10006665static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006666os_getegid_impl(PyObject *module)
6667/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006668{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006669 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006670}
Larry Hastings2f936352014-08-05 14:04:04 +10006671#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006672
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006673
Guido van Rossumad0ee831995-03-01 10:34:45 +00006674#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006675/*[clinic input]
6676os.geteuid
6677
6678Return the current process's effective user id.
6679[clinic start generated code]*/
6680
Larry Hastings2f936352014-08-05 14:04:04 +10006681static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006682os_geteuid_impl(PyObject *module)
6683/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006684{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006685 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006686}
Larry Hastings2f936352014-08-05 14:04:04 +10006687#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006688
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006689
Guido van Rossumad0ee831995-03-01 10:34:45 +00006690#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006691/*[clinic input]
6692os.getgid
6693
6694Return the current process's group id.
6695[clinic start generated code]*/
6696
Larry Hastings2f936352014-08-05 14:04:04 +10006697static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006698os_getgid_impl(PyObject *module)
6699/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006700{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006701 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006702}
Larry Hastings2f936352014-08-05 14:04:04 +10006703#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006704
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006705
Berker Peksag39404992016-09-15 20:45:16 +03006706#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006707/*[clinic input]
6708os.getpid
6709
6710Return the current process id.
6711[clinic start generated code]*/
6712
Larry Hastings2f936352014-08-05 14:04:04 +10006713static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006714os_getpid_impl(PyObject *module)
6715/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006716{
Victor Stinner8c62be82010-05-06 00:08:46 +00006717 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006718}
Berker Peksag39404992016-09-15 20:45:16 +03006719#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006720
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006721#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006722
6723/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006724PyDoc_STRVAR(posix_getgrouplist__doc__,
6725"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6726Returns a list of groups to which a user belongs.\n\n\
6727 user: username to lookup\n\
6728 group: base group id of the user");
6729
6730static PyObject *
6731posix_getgrouplist(PyObject *self, PyObject *args)
6732{
6733#ifdef NGROUPS_MAX
6734#define MAX_GROUPS NGROUPS_MAX
6735#else
6736 /* defined to be 16 on Solaris7, so this should be a small number */
6737#define MAX_GROUPS 64
6738#endif
6739
6740 const char *user;
6741 int i, ngroups;
6742 PyObject *list;
6743#ifdef __APPLE__
6744 int *groups, basegid;
6745#else
6746 gid_t *groups, basegid;
6747#endif
6748 ngroups = MAX_GROUPS;
6749
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006750#ifdef __APPLE__
6751 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006752 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006753#else
6754 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6755 _Py_Gid_Converter, &basegid))
6756 return NULL;
6757#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006758
6759#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006760 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006761#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006762 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006763#endif
6764 if (groups == NULL)
6765 return PyErr_NoMemory();
6766
6767 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6768 PyMem_Del(groups);
6769 return posix_error();
6770 }
6771
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006772#ifdef _Py_MEMORY_SANITIZER
6773 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6774 __msan_unpoison(&ngroups, sizeof(ngroups));
6775 __msan_unpoison(groups, ngroups*sizeof(*groups));
6776#endif
6777
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006778 list = PyList_New(ngroups);
6779 if (list == NULL) {
6780 PyMem_Del(groups);
6781 return NULL;
6782 }
6783
6784 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006785#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006786 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006787#else
6788 PyObject *o = _PyLong_FromGid(groups[i]);
6789#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006790 if (o == NULL) {
6791 Py_DECREF(list);
6792 PyMem_Del(groups);
6793 return NULL;
6794 }
6795 PyList_SET_ITEM(list, i, o);
6796 }
6797
6798 PyMem_Del(groups);
6799
6800 return list;
6801}
Larry Hastings2f936352014-08-05 14:04:04 +10006802#endif /* HAVE_GETGROUPLIST */
6803
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006804
Fred Drakec9680921999-12-13 16:37:25 +00006805#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006806/*[clinic input]
6807os.getgroups
6808
6809Return list of supplemental group IDs for the process.
6810[clinic start generated code]*/
6811
Larry Hastings2f936352014-08-05 14:04:04 +10006812static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006813os_getgroups_impl(PyObject *module)
6814/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006815{
6816 PyObject *result = NULL;
6817
Fred Drakec9680921999-12-13 16:37:25 +00006818#ifdef NGROUPS_MAX
6819#define MAX_GROUPS NGROUPS_MAX
6820#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006821 /* defined to be 16 on Solaris7, so this should be a small number */
Fred Drakec9680921999-12-13 16:37:25 +00006822#define MAX_GROUPS 64
6823#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00006824 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006825
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006826 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006827 * This is a helper variable to store the intermediate result when
6828 * that happens.
6829 *
6830 * To keep the code readable the OSX behaviour is unconditional,
6831 * according to the POSIX spec this should be safe on all unix-y
6832 * systems.
6833 */
6834 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006835 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006836
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006837#ifdef __APPLE__
6838 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6839 * there are more groups than can fit in grouplist. Therefore, on OS X
6840 * always first call getgroups with length 0 to get the actual number
6841 * of groups.
6842 */
6843 n = getgroups(0, NULL);
6844 if (n < 0) {
6845 return posix_error();
6846 } else if (n <= MAX_GROUPS) {
6847 /* groups will fit in existing array */
6848 alt_grouplist = grouplist;
6849 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006850 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006851 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006852 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006853 }
6854 }
6855
6856 n = getgroups(n, alt_grouplist);
6857 if (n == -1) {
6858 if (alt_grouplist != grouplist) {
6859 PyMem_Free(alt_grouplist);
6860 }
6861 return posix_error();
6862 }
6863#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006864 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006865 if (n < 0) {
6866 if (errno == EINVAL) {
6867 n = getgroups(0, NULL);
6868 if (n == -1) {
6869 return posix_error();
6870 }
6871 if (n == 0) {
6872 /* Avoid malloc(0) */
6873 alt_grouplist = grouplist;
6874 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006875 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006876 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006877 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006878 }
6879 n = getgroups(n, alt_grouplist);
6880 if (n == -1) {
6881 PyMem_Free(alt_grouplist);
6882 return posix_error();
6883 }
6884 }
6885 } else {
6886 return posix_error();
6887 }
6888 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006889#endif
6890
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006891 result = PyList_New(n);
6892 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00006893 int i;
6894 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006895 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00006896 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00006897 Py_DECREF(result);
6898 result = NULL;
6899 break;
Fred Drakec9680921999-12-13 16:37:25 +00006900 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006901 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00006902 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006903 }
6904
6905 if (alt_grouplist != grouplist) {
6906 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00006907 }
Neal Norwitze241ce82003-02-17 18:17:05 +00006908
Fred Drakec9680921999-12-13 16:37:25 +00006909 return result;
6910}
Larry Hastings2f936352014-08-05 14:04:04 +10006911#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00006912
Antoine Pitroub7572f02009-12-02 20:46:48 +00006913#ifdef HAVE_INITGROUPS
6914PyDoc_STRVAR(posix_initgroups__doc__,
6915"initgroups(username, gid) -> None\n\n\
6916Call the system initgroups() to initialize the group access list with all of\n\
6917the groups of which the specified username is a member, plus the specified\n\
6918group id.");
6919
Larry Hastings2f936352014-08-05 14:04:04 +10006920/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00006921static PyObject *
6922posix_initgroups(PyObject *self, PyObject *args)
6923{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006924 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03006925 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006926 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006927#ifdef __APPLE__
6928 int gid;
6929#else
6930 gid_t gid;
6931#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00006932
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006933#ifdef __APPLE__
6934 if (!PyArg_ParseTuple(args, "O&i:initgroups",
6935 PyUnicode_FSConverter, &oname,
6936 &gid))
6937#else
6938 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
6939 PyUnicode_FSConverter, &oname,
6940 _Py_Gid_Converter, &gid))
6941#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00006942 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006943 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00006944
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006945 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006946 Py_DECREF(oname);
6947 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00006948 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00006949
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02006950 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00006951}
Larry Hastings2f936352014-08-05 14:04:04 +10006952#endif /* HAVE_INITGROUPS */
6953
Antoine Pitroub7572f02009-12-02 20:46:48 +00006954
Martin v. Löwis606edc12002-06-13 21:09:11 +00006955#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10006956/*[clinic input]
6957os.getpgid
6958
6959 pid: pid_t
6960
6961Call the system call getpgid(), and return the result.
6962[clinic start generated code]*/
6963
Larry Hastings2f936352014-08-05 14:04:04 +10006964static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006965os_getpgid_impl(PyObject *module, pid_t pid)
6966/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006967{
6968 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00006969 if (pgid < 0)
6970 return posix_error();
6971 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00006972}
6973#endif /* HAVE_GETPGID */
6974
6975
Guido van Rossumb6775db1994-08-01 11:34:53 +00006976#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10006977/*[clinic input]
6978os.getpgrp
6979
6980Return the current process group id.
6981[clinic start generated code]*/
6982
Larry Hastings2f936352014-08-05 14:04:04 +10006983static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006984os_getpgrp_impl(PyObject *module)
6985/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00006986{
Guido van Rossumb6775db1994-08-01 11:34:53 +00006987#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00006988 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00006989#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00006990 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00006991#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00006992}
Guido van Rossumb6775db1994-08-01 11:34:53 +00006993#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00006994
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006995
Guido van Rossumb6775db1994-08-01 11:34:53 +00006996#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10006997/*[clinic input]
6998os.setpgrp
6999
7000Make the current process the leader of its process group.
7001[clinic start generated code]*/
7002
Larry Hastings2f936352014-08-05 14:04:04 +10007003static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007004os_setpgrp_impl(PyObject *module)
7005/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007006{
Guido van Rossum64933891994-10-20 21:56:42 +00007007#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007008 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007009#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007010 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007011#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007012 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007013 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007014}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007015#endif /* HAVE_SETPGRP */
7016
Guido van Rossumad0ee831995-03-01 10:34:45 +00007017#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007018
7019#ifdef MS_WINDOWS
7020#include <tlhelp32.h>
7021
7022static PyObject*
7023win32_getppid()
7024{
7025 HANDLE snapshot;
7026 pid_t mypid;
7027 PyObject* result = NULL;
7028 BOOL have_record;
7029 PROCESSENTRY32 pe;
7030
7031 mypid = getpid(); /* This function never fails */
7032
7033 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7034 if (snapshot == INVALID_HANDLE_VALUE)
7035 return PyErr_SetFromWindowsErr(GetLastError());
7036
7037 pe.dwSize = sizeof(pe);
7038 have_record = Process32First(snapshot, &pe);
7039 while (have_record) {
7040 if (mypid == (pid_t)pe.th32ProcessID) {
7041 /* We could cache the ulong value in a static variable. */
7042 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7043 break;
7044 }
7045
7046 have_record = Process32Next(snapshot, &pe);
7047 }
7048
7049 /* If our loop exits and our pid was not found (result will be NULL)
7050 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7051 * error anyway, so let's raise it. */
7052 if (!result)
7053 result = PyErr_SetFromWindowsErr(GetLastError());
7054
7055 CloseHandle(snapshot);
7056
7057 return result;
7058}
7059#endif /*MS_WINDOWS*/
7060
Larry Hastings2f936352014-08-05 14:04:04 +10007061
7062/*[clinic input]
7063os.getppid
7064
7065Return the parent's process id.
7066
7067If the parent process has already exited, Windows machines will still
7068return its id; others systems will return the id of the 'init' process (1).
7069[clinic start generated code]*/
7070
Larry Hastings2f936352014-08-05 14:04:04 +10007071static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007072os_getppid_impl(PyObject *module)
7073/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007074{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007075#ifdef MS_WINDOWS
7076 return win32_getppid();
7077#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007078 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007079#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007080}
7081#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007082
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007083
Fred Drake12c6e2d1999-12-14 21:25:03 +00007084#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007085/*[clinic input]
7086os.getlogin
7087
7088Return the actual login name.
7089[clinic start generated code]*/
7090
Larry Hastings2f936352014-08-05 14:04:04 +10007091static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007092os_getlogin_impl(PyObject *module)
7093/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007094{
Victor Stinner8c62be82010-05-06 00:08:46 +00007095 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007096#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007097 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007098 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007099
7100 if (GetUserNameW(user_name, &num_chars)) {
7101 /* num_chars is the number of unicode chars plus null terminator */
7102 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007103 }
7104 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007105 result = PyErr_SetFromWindowsErr(GetLastError());
7106#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007107 char *name;
7108 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007109
Victor Stinner8c62be82010-05-06 00:08:46 +00007110 errno = 0;
7111 name = getlogin();
7112 if (name == NULL) {
7113 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007114 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007115 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007116 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007117 }
7118 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007119 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007120 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007121#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007122 return result;
7123}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007124#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007125
Larry Hastings2f936352014-08-05 14:04:04 +10007126
Guido van Rossumad0ee831995-03-01 10:34:45 +00007127#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007128/*[clinic input]
7129os.getuid
7130
7131Return the current process's user id.
7132[clinic start generated code]*/
7133
Larry Hastings2f936352014-08-05 14:04:04 +10007134static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007135os_getuid_impl(PyObject *module)
7136/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007137{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007138 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007139}
Larry Hastings2f936352014-08-05 14:04:04 +10007140#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007141
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007142
Brian Curtineb24d742010-04-12 17:16:38 +00007143#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007144#define HAVE_KILL
7145#endif /* MS_WINDOWS */
7146
7147#ifdef HAVE_KILL
7148/*[clinic input]
7149os.kill
7150
7151 pid: pid_t
7152 signal: Py_ssize_t
7153 /
7154
7155Kill a process with a signal.
7156[clinic start generated code]*/
7157
Larry Hastings2f936352014-08-05 14:04:04 +10007158static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007159os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7160/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007161#ifndef MS_WINDOWS
7162{
7163 if (kill(pid, (int)signal) == -1)
7164 return posix_error();
7165 Py_RETURN_NONE;
7166}
7167#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00007168{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007169 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007170 DWORD sig = (DWORD)signal;
7171 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007172 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007173
Victor Stinner8c62be82010-05-06 00:08:46 +00007174 /* Console processes which share a common console can be sent CTRL+C or
7175 CTRL+BREAK events, provided they handle said events. */
7176 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007177 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007178 err = GetLastError();
7179 PyErr_SetFromWindowsErr(err);
7180 }
7181 else
7182 Py_RETURN_NONE;
7183 }
Brian Curtineb24d742010-04-12 17:16:38 +00007184
Victor Stinner8c62be82010-05-06 00:08:46 +00007185 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7186 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007187 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007188 if (handle == NULL) {
7189 err = GetLastError();
7190 return PyErr_SetFromWindowsErr(err);
7191 }
Brian Curtineb24d742010-04-12 17:16:38 +00007192
Victor Stinner8c62be82010-05-06 00:08:46 +00007193 if (TerminateProcess(handle, sig) == 0) {
7194 err = GetLastError();
7195 result = PyErr_SetFromWindowsErr(err);
7196 } else {
7197 Py_INCREF(Py_None);
7198 result = Py_None;
7199 }
Brian Curtineb24d742010-04-12 17:16:38 +00007200
Victor Stinner8c62be82010-05-06 00:08:46 +00007201 CloseHandle(handle);
7202 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007203}
Larry Hastings2f936352014-08-05 14:04:04 +10007204#endif /* !MS_WINDOWS */
7205#endif /* HAVE_KILL */
7206
7207
7208#ifdef HAVE_KILLPG
7209/*[clinic input]
7210os.killpg
7211
7212 pgid: pid_t
7213 signal: int
7214 /
7215
7216Kill a process group with a signal.
7217[clinic start generated code]*/
7218
Larry Hastings2f936352014-08-05 14:04:04 +10007219static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007220os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7221/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007222{
7223 /* XXX some man pages make the `pgid` parameter an int, others
7224 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7225 take the same type. Moreover, pid_t is always at least as wide as
7226 int (else compilation of this module fails), which is safe. */
7227 if (killpg(pgid, signal) == -1)
7228 return posix_error();
7229 Py_RETURN_NONE;
7230}
7231#endif /* HAVE_KILLPG */
7232
Brian Curtineb24d742010-04-12 17:16:38 +00007233
Guido van Rossumc0125471996-06-28 18:55:32 +00007234#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007235#ifdef HAVE_SYS_LOCK_H
7236#include <sys/lock.h>
7237#endif
7238
Larry Hastings2f936352014-08-05 14:04:04 +10007239/*[clinic input]
7240os.plock
7241 op: int
7242 /
7243
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007244Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007245[clinic start generated code]*/
7246
Larry Hastings2f936352014-08-05 14:04:04 +10007247static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007248os_plock_impl(PyObject *module, int op)
7249/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007250{
Victor Stinner8c62be82010-05-06 00:08:46 +00007251 if (plock(op) == -1)
7252 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007253 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007254}
Larry Hastings2f936352014-08-05 14:04:04 +10007255#endif /* HAVE_PLOCK */
7256
Guido van Rossumc0125471996-06-28 18:55:32 +00007257
Guido van Rossumb6775db1994-08-01 11:34:53 +00007258#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007259/*[clinic input]
7260os.setuid
7261
7262 uid: uid_t
7263 /
7264
7265Set the current process's user id.
7266[clinic start generated code]*/
7267
Larry Hastings2f936352014-08-05 14:04:04 +10007268static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007269os_setuid_impl(PyObject *module, uid_t uid)
7270/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007271{
Victor Stinner8c62be82010-05-06 00:08:46 +00007272 if (setuid(uid) < 0)
7273 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007274 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007275}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007276#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007277
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007278
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007279#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007280/*[clinic input]
7281os.seteuid
7282
7283 euid: uid_t
7284 /
7285
7286Set the current process's effective user id.
7287[clinic start generated code]*/
7288
Larry Hastings2f936352014-08-05 14:04:04 +10007289static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007290os_seteuid_impl(PyObject *module, uid_t euid)
7291/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007292{
7293 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007294 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007295 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007296}
7297#endif /* HAVE_SETEUID */
7298
Larry Hastings2f936352014-08-05 14:04:04 +10007299
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007300#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007301/*[clinic input]
7302os.setegid
7303
7304 egid: gid_t
7305 /
7306
7307Set the current process's effective group id.
7308[clinic start generated code]*/
7309
Larry Hastings2f936352014-08-05 14:04:04 +10007310static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007311os_setegid_impl(PyObject *module, gid_t egid)
7312/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007313{
7314 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007315 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007316 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007317}
7318#endif /* HAVE_SETEGID */
7319
Larry Hastings2f936352014-08-05 14:04:04 +10007320
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007321#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007322/*[clinic input]
7323os.setreuid
7324
7325 ruid: uid_t
7326 euid: uid_t
7327 /
7328
7329Set the current process's real and effective user ids.
7330[clinic start generated code]*/
7331
Larry Hastings2f936352014-08-05 14:04:04 +10007332static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007333os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7334/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007335{
Victor Stinner8c62be82010-05-06 00:08:46 +00007336 if (setreuid(ruid, euid) < 0) {
7337 return posix_error();
7338 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007339 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007340 }
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007341}
7342#endif /* HAVE_SETREUID */
7343
Larry Hastings2f936352014-08-05 14:04:04 +10007344
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007345#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007346/*[clinic input]
7347os.setregid
7348
7349 rgid: gid_t
7350 egid: gid_t
7351 /
7352
7353Set the current process's real and effective group ids.
7354[clinic start generated code]*/
7355
Larry Hastings2f936352014-08-05 14:04:04 +10007356static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007357os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7358/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007359{
7360 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007361 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007362 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007363}
7364#endif /* HAVE_SETREGID */
7365
Larry Hastings2f936352014-08-05 14:04:04 +10007366
Guido van Rossumb6775db1994-08-01 11:34:53 +00007367#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007368/*[clinic input]
7369os.setgid
7370 gid: gid_t
7371 /
7372
7373Set the current process's group id.
7374[clinic start generated code]*/
7375
Larry Hastings2f936352014-08-05 14:04:04 +10007376static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007377os_setgid_impl(PyObject *module, gid_t gid)
7378/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007379{
Victor Stinner8c62be82010-05-06 00:08:46 +00007380 if (setgid(gid) < 0)
7381 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007382 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007383}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007384#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007385
Larry Hastings2f936352014-08-05 14:04:04 +10007386
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007387#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007388/*[clinic input]
7389os.setgroups
7390
7391 groups: object
7392 /
7393
7394Set the groups of the current process to list.
7395[clinic start generated code]*/
7396
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007397static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007398os_setgroups(PyObject *module, PyObject *groups)
7399/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007400{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007401 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007402 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007403
Victor Stinner8c62be82010-05-06 00:08:46 +00007404 if (!PySequence_Check(groups)) {
7405 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7406 return NULL;
7407 }
7408 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007409 if (len < 0) {
7410 return NULL;
7411 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007412 if (len > MAX_GROUPS) {
7413 PyErr_SetString(PyExc_ValueError, "too many groups");
7414 return NULL;
7415 }
7416 for(i = 0; i < len; i++) {
7417 PyObject *elem;
7418 elem = PySequence_GetItem(groups, i);
7419 if (!elem)
7420 return NULL;
7421 if (!PyLong_Check(elem)) {
7422 PyErr_SetString(PyExc_TypeError,
7423 "groups must be integers");
7424 Py_DECREF(elem);
7425 return NULL;
7426 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007427 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007428 Py_DECREF(elem);
7429 return NULL;
7430 }
7431 }
7432 Py_DECREF(elem);
7433 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007434
Victor Stinner8c62be82010-05-06 00:08:46 +00007435 if (setgroups(len, grouplist) < 0)
7436 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007437 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007438}
7439#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007440
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007441#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7442static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007443wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007444{
Victor Stinner8c62be82010-05-06 00:08:46 +00007445 PyObject *result;
7446 static PyObject *struct_rusage;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02007447 _Py_IDENTIFIER(struct_rusage);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007448
Victor Stinner8c62be82010-05-06 00:08:46 +00007449 if (pid == -1)
7450 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007451
Victor Stinner8c62be82010-05-06 00:08:46 +00007452 if (struct_rusage == NULL) {
7453 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7454 if (m == NULL)
7455 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02007456 struct_rusage = _PyObject_GetAttrId(m, &PyId_struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007457 Py_DECREF(m);
7458 if (struct_rusage == NULL)
7459 return NULL;
7460 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007461
Victor Stinner8c62be82010-05-06 00:08:46 +00007462 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7463 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
7464 if (!result)
7465 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007466
7467#ifndef doubletime
7468#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7469#endif
7470
Victor Stinner8c62be82010-05-06 00:08:46 +00007471 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007472 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007473 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007474 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007475#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007476 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7477 SET_INT(result, 2, ru->ru_maxrss);
7478 SET_INT(result, 3, ru->ru_ixrss);
7479 SET_INT(result, 4, ru->ru_idrss);
7480 SET_INT(result, 5, ru->ru_isrss);
7481 SET_INT(result, 6, ru->ru_minflt);
7482 SET_INT(result, 7, ru->ru_majflt);
7483 SET_INT(result, 8, ru->ru_nswap);
7484 SET_INT(result, 9, ru->ru_inblock);
7485 SET_INT(result, 10, ru->ru_oublock);
7486 SET_INT(result, 11, ru->ru_msgsnd);
7487 SET_INT(result, 12, ru->ru_msgrcv);
7488 SET_INT(result, 13, ru->ru_nsignals);
7489 SET_INT(result, 14, ru->ru_nvcsw);
7490 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007491#undef SET_INT
7492
Victor Stinner8c62be82010-05-06 00:08:46 +00007493 if (PyErr_Occurred()) {
7494 Py_DECREF(result);
7495 return NULL;
7496 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007497
Victor Stinner8c62be82010-05-06 00:08:46 +00007498 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007499}
7500#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7501
Larry Hastings2f936352014-08-05 14:04:04 +10007502
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007503#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007504/*[clinic input]
7505os.wait3
7506
7507 options: int
7508Wait for completion of a child process.
7509
7510Returns a tuple of information about the child process:
7511 (pid, status, rusage)
7512[clinic start generated code]*/
7513
Larry Hastings2f936352014-08-05 14:04:04 +10007514static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007515os_wait3_impl(PyObject *module, int options)
7516/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007517{
Victor Stinner8c62be82010-05-06 00:08:46 +00007518 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007519 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007520 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007521 WAIT_TYPE status;
7522 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007523
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007524 do {
7525 Py_BEGIN_ALLOW_THREADS
7526 pid = wait3(&status, options, &ru);
7527 Py_END_ALLOW_THREADS
7528 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7529 if (pid < 0)
7530 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007531
Victor Stinner4195b5c2012-02-08 23:03:19 +01007532 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007533}
7534#endif /* HAVE_WAIT3 */
7535
Larry Hastings2f936352014-08-05 14:04:04 +10007536
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007537#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007538/*[clinic input]
7539
7540os.wait4
7541
7542 pid: pid_t
7543 options: int
7544
7545Wait for completion of a specific child process.
7546
7547Returns a tuple of information about the child process:
7548 (pid, status, rusage)
7549[clinic start generated code]*/
7550
Larry Hastings2f936352014-08-05 14:04:04 +10007551static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007552os_wait4_impl(PyObject *module, pid_t pid, int options)
7553/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007554{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007555 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007556 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007557 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007558 WAIT_TYPE status;
7559 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007560
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007561 do {
7562 Py_BEGIN_ALLOW_THREADS
7563 res = wait4(pid, &status, options, &ru);
7564 Py_END_ALLOW_THREADS
7565 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7566 if (res < 0)
7567 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007568
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007569 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007570}
7571#endif /* HAVE_WAIT4 */
7572
Larry Hastings2f936352014-08-05 14:04:04 +10007573
Ross Lagerwall7807c352011-03-17 20:20:30 +02007574#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007575/*[clinic input]
7576os.waitid
7577
7578 idtype: idtype_t
7579 Must be one of be P_PID, P_PGID or P_ALL.
7580 id: id_t
7581 The id to wait on.
7582 options: int
7583 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7584 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7585 /
7586
7587Returns the result of waiting for a process or processes.
7588
7589Returns either waitid_result or None if WNOHANG is specified and there are
7590no children in a waitable state.
7591[clinic start generated code]*/
7592
Larry Hastings2f936352014-08-05 14:04:04 +10007593static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007594os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7595/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007596{
7597 PyObject *result;
7598 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007599 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007600 siginfo_t si;
7601 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007602
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007603 do {
7604 Py_BEGIN_ALLOW_THREADS
7605 res = waitid(idtype, id, &si, options);
7606 Py_END_ALLOW_THREADS
7607 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7608 if (res < 0)
7609 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007610
7611 if (si.si_pid == 0)
7612 Py_RETURN_NONE;
7613
Eddie Elizondo474eedf2018-11-13 04:09:31 -08007614 result = PyStructSequence_New(WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007615 if (!result)
7616 return NULL;
7617
7618 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007619 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007620 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7621 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7622 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7623 if (PyErr_Occurred()) {
7624 Py_DECREF(result);
7625 return NULL;
7626 }
7627
7628 return result;
7629}
Larry Hastings2f936352014-08-05 14:04:04 +10007630#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007631
Larry Hastings2f936352014-08-05 14:04:04 +10007632
7633#if defined(HAVE_WAITPID)
7634/*[clinic input]
7635os.waitpid
7636 pid: pid_t
7637 options: int
7638 /
7639
7640Wait for completion of a given child process.
7641
7642Returns a tuple of information regarding the child process:
7643 (pid, status)
7644
7645The options argument is ignored on Windows.
7646[clinic start generated code]*/
7647
Larry Hastings2f936352014-08-05 14:04:04 +10007648static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007649os_waitpid_impl(PyObject *module, pid_t pid, int options)
7650/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007651{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007652 pid_t res;
7653 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007654 WAIT_TYPE status;
7655 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007656
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007657 do {
7658 Py_BEGIN_ALLOW_THREADS
7659 res = waitpid(pid, &status, options);
7660 Py_END_ALLOW_THREADS
7661 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7662 if (res < 0)
7663 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007664
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007665 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007666}
Tim Petersab034fa2002-02-01 11:27:43 +00007667#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007668/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007669/*[clinic input]
7670os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007671 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007672 options: int
7673 /
7674
7675Wait for completion of a given process.
7676
7677Returns a tuple of information regarding the process:
7678 (pid, status << 8)
7679
7680The options argument is ignored on Windows.
7681[clinic start generated code]*/
7682
Larry Hastings2f936352014-08-05 14:04:04 +10007683static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007684os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007685/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007686{
7687 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007688 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007689 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007690
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007691 do {
7692 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007693 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007694 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007695 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007696 Py_END_ALLOW_THREADS
7697 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007698 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007699 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007700
Victor Stinner8c62be82010-05-06 00:08:46 +00007701 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007702 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007703}
Larry Hastings2f936352014-08-05 14:04:04 +10007704#endif
7705
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007706
Guido van Rossumad0ee831995-03-01 10:34:45 +00007707#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007708/*[clinic input]
7709os.wait
7710
7711Wait for completion of a child process.
7712
7713Returns a tuple of information about the child process:
7714 (pid, status)
7715[clinic start generated code]*/
7716
Larry Hastings2f936352014-08-05 14:04:04 +10007717static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007718os_wait_impl(PyObject *module)
7719/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007720{
Victor Stinner8c62be82010-05-06 00:08:46 +00007721 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007722 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007723 WAIT_TYPE status;
7724 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007725
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007726 do {
7727 Py_BEGIN_ALLOW_THREADS
7728 pid = wait(&status);
7729 Py_END_ALLOW_THREADS
7730 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7731 if (pid < 0)
7732 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007733
Victor Stinner8c62be82010-05-06 00:08:46 +00007734 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007735}
Larry Hastings2f936352014-08-05 14:04:04 +10007736#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007737
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007738
Larry Hastings9cf065c2012-06-22 16:30:09 -07007739#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007740/*[clinic input]
7741os.readlink
7742
7743 path: path_t
7744 *
7745 dir_fd: dir_fd(requires='readlinkat') = None
7746
7747Return a string representing the path to which the symbolic link points.
7748
7749If dir_fd is not None, it should be a file descriptor open to a directory,
7750and path should be relative; path will then be relative to that directory.
7751
7752dir_fd may not be implemented on your platform. If it is unavailable,
7753using it will raise a NotImplementedError.
7754[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007755
Barry Warsaw53699e91996-12-10 23:23:01 +00007756static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007757os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7758/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007759{
Berker Peksage0b5b202018-08-15 13:03:41 +03007760#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007761 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007762 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007763
7764 Py_BEGIN_ALLOW_THREADS
7765#ifdef HAVE_READLINKAT
7766 if (dir_fd != DEFAULT_DIR_FD)
7767 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7768 else
7769#endif
7770 length = readlink(path->narrow, buffer, MAXPATHLEN);
7771 Py_END_ALLOW_THREADS
7772
7773 if (length < 0) {
7774 return path_error(path);
7775 }
7776 buffer[length] = '\0';
7777
7778 if (PyUnicode_Check(path->object))
7779 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7780 else
7781 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007782#elif defined(MS_WINDOWS)
7783 DWORD n_bytes_returned;
7784 DWORD io_result;
7785 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007786 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7787 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
7788 const wchar_t *print_name;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007789 PyObject *result;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007790
Larry Hastings2f936352014-08-05 14:04:04 +10007791 /* First get a handle to the reparse point */
7792 Py_BEGIN_ALLOW_THREADS
7793 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007794 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007795 0,
7796 0,
7797 0,
7798 OPEN_EXISTING,
7799 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7800 0);
7801 Py_END_ALLOW_THREADS
7802
Berker Peksage0b5b202018-08-15 13:03:41 +03007803 if (reparse_point_handle == INVALID_HANDLE_VALUE) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007804 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007805 }
Larry Hastings2f936352014-08-05 14:04:04 +10007806
7807 Py_BEGIN_ALLOW_THREADS
7808 /* New call DeviceIoControl to read the reparse point */
7809 io_result = DeviceIoControl(
7810 reparse_point_handle,
7811 FSCTL_GET_REPARSE_POINT,
7812 0, 0, /* in buffer */
7813 target_buffer, sizeof(target_buffer),
7814 &n_bytes_returned,
7815 0 /* we're not using OVERLAPPED_IO */
7816 );
7817 CloseHandle(reparse_point_handle);
7818 Py_END_ALLOW_THREADS
7819
Berker Peksage0b5b202018-08-15 13:03:41 +03007820 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007821 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007822 }
Larry Hastings2f936352014-08-05 14:04:04 +10007823
7824 if (rdb->ReparseTag != IO_REPARSE_TAG_SYMLINK)
7825 {
7826 PyErr_SetString(PyExc_ValueError,
7827 "not a symbolic link");
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007828 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10007829 }
SSE43c34aad2018-02-13 00:10:35 +07007830 print_name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7831 rdb->SymbolicLinkReparseBuffer.PrintNameOffset);
Larry Hastings2f936352014-08-05 14:04:04 +10007832
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007833 result = PyUnicode_FromWideChar(print_name,
7834 rdb->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(wchar_t));
7835 if (path->narrow) {
7836 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Berker Peksage0b5b202018-08-15 13:03:41 +03007837 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007838 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03007839#endif
Larry Hastings2f936352014-08-05 14:04:04 +10007840}
Berker Peksage0b5b202018-08-15 13:03:41 +03007841#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007842
Larry Hastings9cf065c2012-06-22 16:30:09 -07007843#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07007844
7845#if defined(MS_WINDOWS)
7846
Steve Dower6921e732018-03-05 14:26:08 -08007847/* Remove the last portion of the path - return 0 on success */
7848static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007849_dirnameW(WCHAR *path)
7850{
Jason R. Coombs3a092862013-05-27 23:21:28 -04007851 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08007852 size_t length = wcsnlen_s(path, MAX_PATH);
7853 if (length == MAX_PATH) {
7854 return -1;
7855 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007856
7857 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08007858 for(ptr = path + length; ptr != path; ptr--) {
7859 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04007860 break;
Steve Dower6921e732018-03-05 14:26:08 -08007861 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007862 }
7863 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08007864 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04007865}
7866
Victor Stinner31b3b922013-06-05 01:49:17 +02007867/* Is this path absolute? */
7868static int
7869_is_absW(const WCHAR *path)
7870{
Steve Dower6921e732018-03-05 14:26:08 -08007871 return path[0] == L'\\' || path[0] == L'/' ||
7872 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04007873}
7874
Steve Dower6921e732018-03-05 14:26:08 -08007875/* join root and rest with a backslash - return 0 on success */
7876static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007877_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
7878{
Victor Stinner31b3b922013-06-05 01:49:17 +02007879 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08007880 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04007881 }
7882
Steve Dower6921e732018-03-05 14:26:08 -08007883 if (wcscpy_s(dest_path, MAX_PATH, root)) {
7884 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04007885 }
Steve Dower6921e732018-03-05 14:26:08 -08007886
7887 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
7888 return -1;
7889 }
7890
7891 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04007892}
7893
Victor Stinner31b3b922013-06-05 01:49:17 +02007894/* Return True if the path at src relative to dest is a directory */
7895static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007896_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04007897{
Jason R. Coombs3a092862013-05-27 23:21:28 -04007898 WIN32_FILE_ATTRIBUTE_DATA src_info;
7899 WCHAR dest_parent[MAX_PATH];
7900 WCHAR src_resolved[MAX_PATH] = L"";
7901
7902 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08007903 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
7904 _dirnameW(dest_parent)) {
7905 return 0;
7906 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007907 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08007908 if (_joinW(src_resolved, dest_parent, src)) {
7909 return 0;
7910 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007911 return (
7912 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
7913 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
7914 );
7915}
Larry Hastings9cf065c2012-06-22 16:30:09 -07007916#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007917
Larry Hastings2f936352014-08-05 14:04:04 +10007918
7919/*[clinic input]
7920os.symlink
7921 src: path_t
7922 dst: path_t
7923 target_is_directory: bool = False
7924 *
7925 dir_fd: dir_fd(requires='symlinkat')=None
7926
7927# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
7928
7929Create a symbolic link pointing to src named dst.
7930
7931target_is_directory is required on Windows if the target is to be
7932 interpreted as a directory. (On Windows, symlink requires
7933 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
7934 target_is_directory is ignored on non-Windows platforms.
7935
7936If dir_fd is not None, it should be a file descriptor open to a directory,
7937 and path should be relative; path will then be relative to that directory.
7938dir_fd may not be implemented on your platform.
7939 If it is unavailable, using it will raise a NotImplementedError.
7940
7941[clinic start generated code]*/
7942
Larry Hastings2f936352014-08-05 14:04:04 +10007943static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007944os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04007945 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007946/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007947{
Larry Hastings9cf065c2012-06-22 16:30:09 -07007948#ifdef MS_WINDOWS
7949 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007950 DWORD flags = 0;
7951
7952 /* Assumed true, set to false if detected to not be available. */
7953 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07007954#else
7955 int result;
7956#endif
7957
Larry Hastings9cf065c2012-06-22 16:30:09 -07007958#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07007959
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007960 if (windows_has_symlink_unprivileged_flag) {
7961 /* Allow non-admin symlinks if system allows it. */
7962 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
7963 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007964
Larry Hastings9cf065c2012-06-22 16:30:09 -07007965 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08007966 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007967 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
7968 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
7969 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
7970 }
7971
7972 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08007973 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07007974 Py_END_ALLOW_THREADS
7975
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007976 if (windows_has_symlink_unprivileged_flag && !result &&
7977 ERROR_INVALID_PARAMETER == GetLastError()) {
7978
7979 Py_BEGIN_ALLOW_THREADS
7980 _Py_BEGIN_SUPPRESS_IPH
7981 /* This error might be caused by
7982 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
7983 Try again, and update windows_has_symlink_unprivileged_flag if we
7984 are successful this time.
7985
7986 NOTE: There is a risk of a race condition here if there are other
7987 conditions than the flag causing ERROR_INVALID_PARAMETER, and
7988 another process (or thread) changes that condition in between our
7989 calls to CreateSymbolicLink.
7990 */
7991 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
7992 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
7993 _Py_END_SUPPRESS_IPH
7994 Py_END_ALLOW_THREADS
7995
7996 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
7997 windows_has_symlink_unprivileged_flag = FALSE;
7998 }
7999 }
8000
Larry Hastings2f936352014-08-05 14:04:04 +10008001 if (!result)
8002 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008003
8004#else
8005
Steve Dower6921e732018-03-05 14:26:08 -08008006 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8007 PyErr_SetString(PyExc_ValueError,
8008 "symlink: src and dst must be the same type");
8009 return NULL;
8010 }
8011
Larry Hastings9cf065c2012-06-22 16:30:09 -07008012 Py_BEGIN_ALLOW_THREADS
8013#if HAVE_SYMLINKAT
8014 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008015 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008016 else
8017#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008018 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008019 Py_END_ALLOW_THREADS
8020
Larry Hastings2f936352014-08-05 14:04:04 +10008021 if (result)
8022 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008023#endif
8024
Larry Hastings2f936352014-08-05 14:04:04 +10008025 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008026}
8027#endif /* HAVE_SYMLINK */
8028
Larry Hastings9cf065c2012-06-22 16:30:09 -07008029
Brian Curtind40e6f72010-07-08 21:39:08 +00008030
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008031
Larry Hastings605a62d2012-06-24 04:33:36 -07008032static PyStructSequence_Field times_result_fields[] = {
8033 {"user", "user time"},
8034 {"system", "system time"},
8035 {"children_user", "user time of children"},
8036 {"children_system", "system time of children"},
8037 {"elapsed", "elapsed time since an arbitrary point in the past"},
8038 {NULL}
8039};
8040
8041PyDoc_STRVAR(times_result__doc__,
8042"times_result: Result from os.times().\n\n\
8043This object may be accessed either as a tuple of\n\
8044 (user, system, children_user, children_system, elapsed),\n\
8045or via the attributes user, system, children_user, children_system,\n\
8046and elapsed.\n\
8047\n\
8048See os.times for more information.");
8049
8050static PyStructSequence_Desc times_result_desc = {
8051 "times_result", /* name */
8052 times_result__doc__, /* doc */
8053 times_result_fields,
8054 5
8055};
8056
Eddie Elizondo474eedf2018-11-13 04:09:31 -08008057static PyTypeObject* TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07008058
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008059#ifdef MS_WINDOWS
8060#define HAVE_TIMES /* mandatory, for the method table */
8061#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008062
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008063#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008064
8065static PyObject *
8066build_times_result(double user, double system,
8067 double children_user, double children_system,
8068 double elapsed)
8069{
Eddie Elizondo474eedf2018-11-13 04:09:31 -08008070 PyObject *value = PyStructSequence_New(TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008071 if (value == NULL)
8072 return NULL;
8073
8074#define SET(i, field) \
8075 { \
8076 PyObject *o = PyFloat_FromDouble(field); \
8077 if (!o) { \
8078 Py_DECREF(value); \
8079 return NULL; \
8080 } \
8081 PyStructSequence_SET_ITEM(value, i, o); \
8082 } \
8083
8084 SET(0, user);
8085 SET(1, system);
8086 SET(2, children_user);
8087 SET(3, children_system);
8088 SET(4, elapsed);
8089
8090#undef SET
8091
8092 return value;
8093}
8094
Larry Hastings605a62d2012-06-24 04:33:36 -07008095
Larry Hastings2f936352014-08-05 14:04:04 +10008096#ifndef MS_WINDOWS
8097#define NEED_TICKS_PER_SECOND
8098static long ticks_per_second = -1;
8099#endif /* MS_WINDOWS */
8100
8101/*[clinic input]
8102os.times
8103
8104Return a collection containing process timing information.
8105
8106The object returned behaves like a named tuple with these fields:
8107 (utime, stime, cutime, cstime, elapsed_time)
8108All fields are floating point numbers.
8109[clinic start generated code]*/
8110
Larry Hastings2f936352014-08-05 14:04:04 +10008111static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008112os_times_impl(PyObject *module)
8113/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008114#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008115{
Victor Stinner8c62be82010-05-06 00:08:46 +00008116 FILETIME create, exit, kernel, user;
8117 HANDLE hProc;
8118 hProc = GetCurrentProcess();
8119 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8120 /* The fields of a FILETIME structure are the hi and lo part
8121 of a 64-bit value expressed in 100 nanosecond units.
8122 1e7 is one second in such units; 1e-7 the inverse.
8123 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8124 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008125 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008126 (double)(user.dwHighDateTime*429.4967296 +
8127 user.dwLowDateTime*1e-7),
8128 (double)(kernel.dwHighDateTime*429.4967296 +
8129 kernel.dwLowDateTime*1e-7),
8130 (double)0,
8131 (double)0,
8132 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008133}
Larry Hastings2f936352014-08-05 14:04:04 +10008134#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008135{
Larry Hastings2f936352014-08-05 14:04:04 +10008136
8137
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008138 struct tms t;
8139 clock_t c;
8140 errno = 0;
8141 c = times(&t);
8142 if (c == (clock_t) -1)
8143 return posix_error();
8144 return build_times_result(
8145 (double)t.tms_utime / ticks_per_second,
8146 (double)t.tms_stime / ticks_per_second,
8147 (double)t.tms_cutime / ticks_per_second,
8148 (double)t.tms_cstime / ticks_per_second,
8149 (double)c / ticks_per_second);
8150}
Larry Hastings2f936352014-08-05 14:04:04 +10008151#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008152#endif /* HAVE_TIMES */
8153
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008154
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008155#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008156/*[clinic input]
8157os.getsid
8158
8159 pid: pid_t
8160 /
8161
8162Call the system call getsid(pid) and return the result.
8163[clinic start generated code]*/
8164
Larry Hastings2f936352014-08-05 14:04:04 +10008165static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008166os_getsid_impl(PyObject *module, pid_t pid)
8167/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008168{
Victor Stinner8c62be82010-05-06 00:08:46 +00008169 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008170 sid = getsid(pid);
8171 if (sid < 0)
8172 return posix_error();
8173 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008174}
8175#endif /* HAVE_GETSID */
8176
8177
Guido van Rossumb6775db1994-08-01 11:34:53 +00008178#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008179/*[clinic input]
8180os.setsid
8181
8182Call the system call setsid().
8183[clinic start generated code]*/
8184
Larry Hastings2f936352014-08-05 14:04:04 +10008185static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008186os_setsid_impl(PyObject *module)
8187/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008188{
Victor Stinner8c62be82010-05-06 00:08:46 +00008189 if (setsid() < 0)
8190 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008191 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008192}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008193#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008194
Larry Hastings2f936352014-08-05 14:04:04 +10008195
Guido van Rossumb6775db1994-08-01 11:34:53 +00008196#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008197/*[clinic input]
8198os.setpgid
8199
8200 pid: pid_t
8201 pgrp: pid_t
8202 /
8203
8204Call the system call setpgid(pid, pgrp).
8205[clinic start generated code]*/
8206
Larry Hastings2f936352014-08-05 14:04:04 +10008207static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008208os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8209/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008210{
Victor Stinner8c62be82010-05-06 00:08:46 +00008211 if (setpgid(pid, pgrp) < 0)
8212 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008213 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008214}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008215#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008216
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008217
Guido van Rossumb6775db1994-08-01 11:34:53 +00008218#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008219/*[clinic input]
8220os.tcgetpgrp
8221
8222 fd: int
8223 /
8224
8225Return the process group associated with the terminal specified by fd.
8226[clinic start generated code]*/
8227
Larry Hastings2f936352014-08-05 14:04:04 +10008228static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008229os_tcgetpgrp_impl(PyObject *module, int fd)
8230/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008231{
8232 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008233 if (pgid < 0)
8234 return posix_error();
8235 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008236}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008237#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008238
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008239
Guido van Rossumb6775db1994-08-01 11:34:53 +00008240#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008241/*[clinic input]
8242os.tcsetpgrp
8243
8244 fd: int
8245 pgid: pid_t
8246 /
8247
8248Set the process group associated with the terminal specified by fd.
8249[clinic start generated code]*/
8250
Larry Hastings2f936352014-08-05 14:04:04 +10008251static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008252os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8253/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008254{
Victor Stinner8c62be82010-05-06 00:08:46 +00008255 if (tcsetpgrp(fd, pgid) < 0)
8256 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008257 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008258}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008259#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008260
Guido van Rossum687dd131993-05-17 08:34:16 +00008261/* Functions acting on file descriptors */
8262
Victor Stinnerdaf45552013-08-28 00:53:59 +02008263#ifdef O_CLOEXEC
8264extern int _Py_open_cloexec_works;
8265#endif
8266
Larry Hastings2f936352014-08-05 14:04:04 +10008267
8268/*[clinic input]
8269os.open -> int
8270 path: path_t
8271 flags: int
8272 mode: int = 0o777
8273 *
8274 dir_fd: dir_fd(requires='openat') = None
8275
8276# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8277
8278Open a file for low level IO. Returns a file descriptor (integer).
8279
8280If dir_fd is not None, it should be a file descriptor open to a directory,
8281 and path should be relative; path will then be relative to that directory.
8282dir_fd may not be implemented on your platform.
8283 If it is unavailable, using it will raise a NotImplementedError.
8284[clinic start generated code]*/
8285
Larry Hastings2f936352014-08-05 14:04:04 +10008286static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008287os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8288/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008289{
8290 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008291 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008292
Victor Stinnerdaf45552013-08-28 00:53:59 +02008293#ifdef O_CLOEXEC
8294 int *atomic_flag_works = &_Py_open_cloexec_works;
8295#elif !defined(MS_WINDOWS)
8296 int *atomic_flag_works = NULL;
8297#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008298
Victor Stinnerdaf45552013-08-28 00:53:59 +02008299#ifdef MS_WINDOWS
8300 flags |= O_NOINHERIT;
8301#elif defined(O_CLOEXEC)
8302 flags |= O_CLOEXEC;
8303#endif
8304
Steve Dowerb82e17e2019-05-23 08:45:22 -07008305 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8306 return -1;
8307 }
8308
Steve Dower8fc89802015-04-12 00:26:27 -04008309 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008310 do {
8311 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008312#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008313 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008314#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008315#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008316 if (dir_fd != DEFAULT_DIR_FD)
8317 fd = openat(dir_fd, path->narrow, flags, mode);
8318 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008319#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008320 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008321#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008322 Py_END_ALLOW_THREADS
8323 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008324 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008325
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008326 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008327 if (!async_err)
8328 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008329 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008330 }
8331
Victor Stinnerdaf45552013-08-28 00:53:59 +02008332#ifndef MS_WINDOWS
8333 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8334 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008335 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008336 }
8337#endif
8338
Larry Hastings2f936352014-08-05 14:04:04 +10008339 return fd;
8340}
8341
8342
8343/*[clinic input]
8344os.close
8345
8346 fd: int
8347
8348Close a file descriptor.
8349[clinic start generated code]*/
8350
Barry Warsaw53699e91996-12-10 23:23:01 +00008351static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008352os_close_impl(PyObject *module, int fd)
8353/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008354{
Larry Hastings2f936352014-08-05 14:04:04 +10008355 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008356 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8357 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8358 * for more details.
8359 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008360 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008361 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008362 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008363 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008364 Py_END_ALLOW_THREADS
8365 if (res < 0)
8366 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008367 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008368}
8369
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008370
Larry Hastings2f936352014-08-05 14:04:04 +10008371/*[clinic input]
8372os.closerange
8373
8374 fd_low: int
8375 fd_high: int
8376 /
8377
8378Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8379[clinic start generated code]*/
8380
Larry Hastings2f936352014-08-05 14:04:04 +10008381static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008382os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8383/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008384{
8385 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00008386 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008387 _Py_BEGIN_SUPPRESS_IPH
Benjamin Peterson207116b2016-09-08 11:28:06 -07008388 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008389 close(i);
Steve Dower8fc89802015-04-12 00:26:27 -04008390 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008391 Py_END_ALLOW_THREADS
8392 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008393}
8394
8395
Larry Hastings2f936352014-08-05 14:04:04 +10008396/*[clinic input]
8397os.dup -> int
8398
8399 fd: int
8400 /
8401
8402Return a duplicate of a file descriptor.
8403[clinic start generated code]*/
8404
Larry Hastings2f936352014-08-05 14:04:04 +10008405static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008406os_dup_impl(PyObject *module, int fd)
8407/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008408{
8409 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008410}
8411
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008412
Larry Hastings2f936352014-08-05 14:04:04 +10008413/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008414os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008415 fd: int
8416 fd2: int
8417 inheritable: bool=True
8418
8419Duplicate file descriptor.
8420[clinic start generated code]*/
8421
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008422static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008423os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008424/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008425{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008426 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008427#if defined(HAVE_DUP3) && \
8428 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8429 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008430 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008431#endif
8432
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008433 if (fd < 0 || fd2 < 0) {
8434 posix_error();
8435 return -1;
8436 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008437
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008438 /* dup2() can fail with EINTR if the target FD is already open, because it
8439 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8440 * upon close(), and therefore below.
8441 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008442#ifdef MS_WINDOWS
8443 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008444 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008445 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008446 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008447 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008448 if (res < 0) {
8449 posix_error();
8450 return -1;
8451 }
8452 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008453
8454 /* Character files like console cannot be make non-inheritable */
8455 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8456 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008457 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008458 }
8459
8460#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8461 Py_BEGIN_ALLOW_THREADS
8462 if (!inheritable)
8463 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8464 else
8465 res = dup2(fd, fd2);
8466 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008467 if (res < 0) {
8468 posix_error();
8469 return -1;
8470 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008471
8472#else
8473
8474#ifdef HAVE_DUP3
8475 if (!inheritable && dup3_works != 0) {
8476 Py_BEGIN_ALLOW_THREADS
8477 res = dup3(fd, fd2, O_CLOEXEC);
8478 Py_END_ALLOW_THREADS
8479 if (res < 0) {
8480 if (dup3_works == -1)
8481 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008482 if (dup3_works) {
8483 posix_error();
8484 return -1;
8485 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008486 }
8487 }
8488
8489 if (inheritable || dup3_works == 0)
8490 {
8491#endif
8492 Py_BEGIN_ALLOW_THREADS
8493 res = dup2(fd, fd2);
8494 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008495 if (res < 0) {
8496 posix_error();
8497 return -1;
8498 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008499
8500 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8501 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008502 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008503 }
8504#ifdef HAVE_DUP3
8505 }
8506#endif
8507
8508#endif
8509
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008510 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008511}
8512
Larry Hastings2f936352014-08-05 14:04:04 +10008513
Ross Lagerwall7807c352011-03-17 20:20:30 +02008514#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008515/*[clinic input]
8516os.lockf
8517
8518 fd: int
8519 An open file descriptor.
8520 command: int
8521 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8522 length: Py_off_t
8523 The number of bytes to lock, starting at the current position.
8524 /
8525
8526Apply, test or remove a POSIX lock on an open file descriptor.
8527
8528[clinic start generated code]*/
8529
Larry Hastings2f936352014-08-05 14:04:04 +10008530static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008531os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8532/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008533{
8534 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008535
8536 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008537 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008538 Py_END_ALLOW_THREADS
8539
8540 if (res < 0)
8541 return posix_error();
8542
8543 Py_RETURN_NONE;
8544}
Larry Hastings2f936352014-08-05 14:04:04 +10008545#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008546
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008547
Larry Hastings2f936352014-08-05 14:04:04 +10008548/*[clinic input]
8549os.lseek -> Py_off_t
8550
8551 fd: int
8552 position: Py_off_t
8553 how: int
8554 /
8555
8556Set the position of a file descriptor. Return the new position.
8557
8558Return the new cursor position in number of bytes
8559relative to the beginning of the file.
8560[clinic start generated code]*/
8561
Larry Hastings2f936352014-08-05 14:04:04 +10008562static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008563os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8564/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008565{
8566 Py_off_t result;
8567
Guido van Rossum687dd131993-05-17 08:34:16 +00008568#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008569 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8570 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008571 case 0: how = SEEK_SET; break;
8572 case 1: how = SEEK_CUR; break;
8573 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008574 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008575#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008576
Victor Stinner8c62be82010-05-06 00:08:46 +00008577 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008578 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008579#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008580 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008581#else
Larry Hastings2f936352014-08-05 14:04:04 +10008582 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008583#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008584 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008585 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008586 if (result < 0)
8587 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008588
Larry Hastings2f936352014-08-05 14:04:04 +10008589 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008590}
8591
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008592
Larry Hastings2f936352014-08-05 14:04:04 +10008593/*[clinic input]
8594os.read
8595 fd: int
8596 length: Py_ssize_t
8597 /
8598
8599Read from a file descriptor. Returns a bytes object.
8600[clinic start generated code]*/
8601
Larry Hastings2f936352014-08-05 14:04:04 +10008602static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008603os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8604/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008605{
Victor Stinner8c62be82010-05-06 00:08:46 +00008606 Py_ssize_t n;
8607 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008608
8609 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008610 errno = EINVAL;
8611 return posix_error();
8612 }
Larry Hastings2f936352014-08-05 14:04:04 +10008613
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008614 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008615
8616 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008617 if (buffer == NULL)
8618 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008619
Victor Stinner66aab0c2015-03-19 22:53:20 +01008620 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8621 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008622 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008623 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008624 }
Larry Hastings2f936352014-08-05 14:04:04 +10008625
8626 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008627 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008628
Victor Stinner8c62be82010-05-06 00:08:46 +00008629 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008630}
8631
Ross Lagerwall7807c352011-03-17 20:20:30 +02008632#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008633 || defined(__APPLE__))) \
8634 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8635 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8636static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008637iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008638{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008639 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008640
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008641 *iov = PyMem_New(struct iovec, cnt);
8642 if (*iov == NULL) {
8643 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008644 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008645 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008646
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008647 *buf = PyMem_New(Py_buffer, cnt);
8648 if (*buf == NULL) {
8649 PyMem_Del(*iov);
8650 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008651 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008652 }
8653
8654 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008655 PyObject *item = PySequence_GetItem(seq, i);
8656 if (item == NULL)
8657 goto fail;
8658 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8659 Py_DECREF(item);
8660 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008661 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008662 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008663 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008664 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008665 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008666 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008667
8668fail:
8669 PyMem_Del(*iov);
8670 for (j = 0; j < i; j++) {
8671 PyBuffer_Release(&(*buf)[j]);
8672 }
8673 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008674 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008675}
8676
8677static void
8678iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8679{
8680 int i;
8681 PyMem_Del(iov);
8682 for (i = 0; i < cnt; i++) {
8683 PyBuffer_Release(&buf[i]);
8684 }
8685 PyMem_Del(buf);
8686}
8687#endif
8688
Larry Hastings2f936352014-08-05 14:04:04 +10008689
Ross Lagerwall7807c352011-03-17 20:20:30 +02008690#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008691/*[clinic input]
8692os.readv -> Py_ssize_t
8693
8694 fd: int
8695 buffers: object
8696 /
8697
8698Read from a file descriptor fd into an iterable of buffers.
8699
8700The buffers should be mutable buffers accepting bytes.
8701readv will transfer data into each buffer until it is full
8702and then move on to the next buffer in the sequence to hold
8703the rest of the data.
8704
8705readv returns the total number of bytes read,
8706which may be less than the total capacity of all the buffers.
8707[clinic start generated code]*/
8708
Larry Hastings2f936352014-08-05 14:04:04 +10008709static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008710os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8711/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008712{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008713 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008714 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008715 struct iovec *iov;
8716 Py_buffer *buf;
8717
Larry Hastings2f936352014-08-05 14:04:04 +10008718 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008719 PyErr_SetString(PyExc_TypeError,
8720 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008721 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008722 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008723
Larry Hastings2f936352014-08-05 14:04:04 +10008724 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008725 if (cnt < 0)
8726 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008727
8728 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8729 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008730
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008731 do {
8732 Py_BEGIN_ALLOW_THREADS
8733 n = readv(fd, iov, cnt);
8734 Py_END_ALLOW_THREADS
8735 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008736
8737 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008738 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008739 if (!async_err)
8740 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008741 return -1;
8742 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008743
Larry Hastings2f936352014-08-05 14:04:04 +10008744 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008745}
Larry Hastings2f936352014-08-05 14:04:04 +10008746#endif /* HAVE_READV */
8747
Ross Lagerwall7807c352011-03-17 20:20:30 +02008748
8749#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008750/*[clinic input]
8751# TODO length should be size_t! but Python doesn't support parsing size_t yet.
8752os.pread
8753
8754 fd: int
8755 length: int
8756 offset: Py_off_t
8757 /
8758
8759Read a number of bytes from a file descriptor starting at a particular offset.
8760
8761Read length bytes from file descriptor fd, starting at offset bytes from
8762the beginning of the file. The file offset remains unchanged.
8763[clinic start generated code]*/
8764
Larry Hastings2f936352014-08-05 14:04:04 +10008765static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008766os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset)
8767/*[clinic end generated code: output=435b29ee32b54a78 input=084948dcbaa35d4c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008768{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008769 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008770 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008771 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008772
Larry Hastings2f936352014-08-05 14:04:04 +10008773 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008774 errno = EINVAL;
8775 return posix_error();
8776 }
Larry Hastings2f936352014-08-05 14:04:04 +10008777 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008778 if (buffer == NULL)
8779 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008780
8781 do {
8782 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008783 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008784 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008785 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008786 Py_END_ALLOW_THREADS
8787 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8788
Ross Lagerwall7807c352011-03-17 20:20:30 +02008789 if (n < 0) {
8790 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008791 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008792 }
Larry Hastings2f936352014-08-05 14:04:04 +10008793 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008794 _PyBytes_Resize(&buffer, n);
8795 return buffer;
8796}
Larry Hastings2f936352014-08-05 14:04:04 +10008797#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008798
Pablo Galindo4defba32018-01-27 16:16:37 +00008799#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8800/*[clinic input]
8801os.preadv -> Py_ssize_t
8802
8803 fd: int
8804 buffers: object
8805 offset: Py_off_t
8806 flags: int = 0
8807 /
8808
8809Reads from a file descriptor into a number of mutable bytes-like objects.
8810
8811Combines the functionality of readv() and pread(). As readv(), it will
8812transfer data into each buffer until it is full and then move on to the next
8813buffer in the sequence to hold the rest of the data. Its fourth argument,
8814specifies the file offset at which the input operation is to be performed. It
8815will return the total number of bytes read (which can be less than the total
8816capacity of all the objects).
8817
8818The flags argument contains a bitwise OR of zero or more of the following flags:
8819
8820- RWF_HIPRI
8821- RWF_NOWAIT
8822
8823Using non-zero flags requires Linux 4.6 or newer.
8824[clinic start generated code]*/
8825
8826static Py_ssize_t
8827os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
8828 int flags)
8829/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
8830{
8831 Py_ssize_t cnt, n;
8832 int async_err = 0;
8833 struct iovec *iov;
8834 Py_buffer *buf;
8835
8836 if (!PySequence_Check(buffers)) {
8837 PyErr_SetString(PyExc_TypeError,
8838 "preadv2() arg 2 must be a sequence");
8839 return -1;
8840 }
8841
8842 cnt = PySequence_Size(buffers);
8843 if (cnt < 0) {
8844 return -1;
8845 }
8846
8847#ifndef HAVE_PREADV2
8848 if(flags != 0) {
8849 argument_unavailable_error("preadv2", "flags");
8850 return -1;
8851 }
8852#endif
8853
8854 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
8855 return -1;
8856 }
8857#ifdef HAVE_PREADV2
8858 do {
8859 Py_BEGIN_ALLOW_THREADS
8860 _Py_BEGIN_SUPPRESS_IPH
8861 n = preadv2(fd, iov, cnt, offset, flags);
8862 _Py_END_SUPPRESS_IPH
8863 Py_END_ALLOW_THREADS
8864 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8865#else
8866 do {
8867 Py_BEGIN_ALLOW_THREADS
8868 _Py_BEGIN_SUPPRESS_IPH
8869 n = preadv(fd, iov, cnt, offset);
8870 _Py_END_SUPPRESS_IPH
8871 Py_END_ALLOW_THREADS
8872 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8873#endif
8874
8875 iov_cleanup(iov, buf, cnt);
8876 if (n < 0) {
8877 if (!async_err) {
8878 posix_error();
8879 }
8880 return -1;
8881 }
8882
8883 return n;
8884}
8885#endif /* HAVE_PREADV */
8886
Larry Hastings2f936352014-08-05 14:04:04 +10008887
8888/*[clinic input]
8889os.write -> Py_ssize_t
8890
8891 fd: int
8892 data: Py_buffer
8893 /
8894
8895Write a bytes object to a file descriptor.
8896[clinic start generated code]*/
8897
Larry Hastings2f936352014-08-05 14:04:04 +10008898static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008899os_write_impl(PyObject *module, int fd, Py_buffer *data)
8900/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008901{
Victor Stinner66aab0c2015-03-19 22:53:20 +01008902 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008903}
8904
8905#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008906PyDoc_STRVAR(posix_sendfile__doc__,
Martin Panterbf19d162015-09-09 01:01:13 +00008907"sendfile(out, in, offset, count) -> byteswritten\n\
Martin Panter94994132015-09-09 05:29:24 +00008908sendfile(out, in, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008909 -> byteswritten\n\
Martin Panterbf19d162015-09-09 01:01:13 +00008910Copy count bytes from file descriptor in to file descriptor out.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008911
Larry Hastings2f936352014-08-05 14:04:04 +10008912/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008913static PyObject *
8914posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
8915{
8916 int in, out;
8917 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008918 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008919 off_t offset;
8920
8921#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
8922#ifndef __APPLE__
8923 Py_ssize_t len;
8924#endif
8925 PyObject *headers = NULL, *trailers = NULL;
8926 Py_buffer *hbuf, *tbuf;
8927 off_t sbytes;
8928 struct sf_hdtr sf;
8929 int flags = 0;
Martin Panterbf19d162015-09-09 01:01:13 +00008930 /* Beware that "in" clashes with Python's own "in" operator keyword */
Benjamin Petersond8a43b42011-02-26 21:35:16 +00008931 static char *keywords[] = {"out", "in",
8932 "offset", "count",
8933 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008934
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02008935 sf.headers = NULL;
8936 sf.trailers = NULL;
8937
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008938#ifdef __APPLE__
8939 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10008940 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008941#else
8942 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10008943 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008944#endif
8945 &headers, &trailers, &flags))
8946 return NULL;
8947 if (headers != NULL) {
8948 if (!PySequence_Check(headers)) {
8949 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00008950 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008951 return NULL;
8952 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008953 Py_ssize_t i = PySequence_Size(headers);
8954 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008955 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008956 if (i > INT_MAX) {
8957 PyErr_SetString(PyExc_OverflowError,
8958 "sendfile() header is too large");
8959 return NULL;
8960 }
8961 if (i > 0) {
8962 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008963 if (iov_setup(&(sf.headers), &hbuf,
8964 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008965 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008966#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008967 for (i = 0; i < sf.hdr_cnt; i++) {
8968 Py_ssize_t blen = sf.headers[i].iov_len;
8969# define OFF_T_MAX 0x7fffffffffffffff
8970 if (sbytes >= OFF_T_MAX - blen) {
8971 PyErr_SetString(PyExc_OverflowError,
8972 "sendfile() header is too large");
8973 return NULL;
8974 }
8975 sbytes += blen;
8976 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008977#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008978 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008979 }
8980 }
8981 if (trailers != NULL) {
8982 if (!PySequence_Check(trailers)) {
8983 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00008984 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008985 return NULL;
8986 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008987 Py_ssize_t i = PySequence_Size(trailers);
8988 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008989 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008990 if (i > INT_MAX) {
8991 PyErr_SetString(PyExc_OverflowError,
8992 "sendfile() trailer is too large");
8993 return NULL;
8994 }
8995 if (i > 0) {
8996 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008997 if (iov_setup(&(sf.trailers), &tbuf,
8998 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008999 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009000 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009001 }
9002 }
9003
Steve Dower8fc89802015-04-12 00:26:27 -04009004 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009005 do {
9006 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009007#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009008 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009009#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009010 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009011#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009012 Py_END_ALLOW_THREADS
9013 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009014 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009015
9016 if (sf.headers != NULL)
9017 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9018 if (sf.trailers != NULL)
9019 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9020
9021 if (ret < 0) {
9022 if ((errno == EAGAIN) || (errno == EBUSY)) {
9023 if (sbytes != 0) {
9024 // some data has been sent
9025 goto done;
9026 }
9027 else {
9028 // no data has been sent; upper application is supposed
9029 // to retry on EAGAIN or EBUSY
9030 return posix_error();
9031 }
9032 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009033 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009034 }
9035 goto done;
9036
9037done:
9038 #if !defined(HAVE_LARGEFILE_SUPPORT)
9039 return Py_BuildValue("l", sbytes);
9040 #else
9041 return Py_BuildValue("L", sbytes);
9042 #endif
9043
9044#else
9045 Py_ssize_t count;
9046 PyObject *offobj;
9047 static char *keywords[] = {"out", "in",
9048 "offset", "count", NULL};
9049 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9050 keywords, &out, &in, &offobj, &count))
9051 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009052#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009053 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009054 do {
9055 Py_BEGIN_ALLOW_THREADS
9056 ret = sendfile(out, in, NULL, count);
9057 Py_END_ALLOW_THREADS
9058 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009059 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009060 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009061 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009062 }
9063#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009064 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009065 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009066
9067 do {
9068 Py_BEGIN_ALLOW_THREADS
9069 ret = sendfile(out, in, &offset, count);
9070 Py_END_ALLOW_THREADS
9071 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009072 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009073 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009074 return Py_BuildValue("n", ret);
9075#endif
9076}
Larry Hastings2f936352014-08-05 14:04:04 +10009077#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009078
Larry Hastings2f936352014-08-05 14:04:04 +10009079
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009080#if defined(__APPLE__)
9081/*[clinic input]
9082os._fcopyfile
9083
9084 infd: int
9085 outfd: int
9086 flags: int
9087 /
9088
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009089Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009090[clinic start generated code]*/
9091
9092static PyObject *
9093os__fcopyfile_impl(PyObject *module, int infd, int outfd, int flags)
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009094/*[clinic end generated code: output=8e8885c721ec38e3 input=69e0770e600cb44f]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009095{
9096 int ret;
9097
9098 Py_BEGIN_ALLOW_THREADS
9099 ret = fcopyfile(infd, outfd, NULL, flags);
9100 Py_END_ALLOW_THREADS
9101 if (ret < 0)
9102 return posix_error();
9103 Py_RETURN_NONE;
9104}
9105#endif
9106
9107
Larry Hastings2f936352014-08-05 14:04:04 +10009108/*[clinic input]
9109os.fstat
9110
9111 fd : int
9112
9113Perform a stat system call on the given file descriptor.
9114
9115Like stat(), but for an open file descriptor.
9116Equivalent to os.stat(fd).
9117[clinic start generated code]*/
9118
Larry Hastings2f936352014-08-05 14:04:04 +10009119static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009120os_fstat_impl(PyObject *module, int fd)
9121/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009122{
Victor Stinner8c62be82010-05-06 00:08:46 +00009123 STRUCT_STAT st;
9124 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009125 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009126
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009127 do {
9128 Py_BEGIN_ALLOW_THREADS
9129 res = FSTAT(fd, &st);
9130 Py_END_ALLOW_THREADS
9131 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009132 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009133#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009134 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009135#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009136 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009137#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009138 }
Tim Peters5aa91602002-01-30 05:46:57 +00009139
Victor Stinner4195b5c2012-02-08 23:03:19 +01009140 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009141}
9142
Larry Hastings2f936352014-08-05 14:04:04 +10009143
9144/*[clinic input]
9145os.isatty -> bool
9146 fd: int
9147 /
9148
9149Return True if the fd is connected to a terminal.
9150
9151Return True if the file descriptor is an open file descriptor
9152connected to the slave end of a terminal.
9153[clinic start generated code]*/
9154
Larry Hastings2f936352014-08-05 14:04:04 +10009155static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009156os_isatty_impl(PyObject *module, int fd)
9157/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009158{
Steve Dower8fc89802015-04-12 00:26:27 -04009159 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009160 _Py_BEGIN_SUPPRESS_IPH
9161 return_value = isatty(fd);
9162 _Py_END_SUPPRESS_IPH
9163 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009164}
9165
9166
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009167#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009168/*[clinic input]
9169os.pipe
9170
9171Create a pipe.
9172
9173Returns a tuple of two file descriptors:
9174 (read_fd, write_fd)
9175[clinic start generated code]*/
9176
Larry Hastings2f936352014-08-05 14:04:04 +10009177static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009178os_pipe_impl(PyObject *module)
9179/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009180{
Victor Stinner8c62be82010-05-06 00:08:46 +00009181 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009182#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009183 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009184 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009185 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009186#else
9187 int res;
9188#endif
9189
9190#ifdef MS_WINDOWS
9191 attr.nLength = sizeof(attr);
9192 attr.lpSecurityDescriptor = NULL;
9193 attr.bInheritHandle = FALSE;
9194
9195 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009196 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009197 ok = CreatePipe(&read, &write, &attr, 0);
9198 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009199 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9200 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009201 if (fds[0] == -1 || fds[1] == -1) {
9202 CloseHandle(read);
9203 CloseHandle(write);
9204 ok = 0;
9205 }
9206 }
Steve Dowerc3630612016-11-19 18:41:16 -08009207 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009208 Py_END_ALLOW_THREADS
9209
Victor Stinner8c62be82010-05-06 00:08:46 +00009210 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009211 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009212#else
9213
9214#ifdef HAVE_PIPE2
9215 Py_BEGIN_ALLOW_THREADS
9216 res = pipe2(fds, O_CLOEXEC);
9217 Py_END_ALLOW_THREADS
9218
9219 if (res != 0 && errno == ENOSYS)
9220 {
9221#endif
9222 Py_BEGIN_ALLOW_THREADS
9223 res = pipe(fds);
9224 Py_END_ALLOW_THREADS
9225
9226 if (res == 0) {
9227 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9228 close(fds[0]);
9229 close(fds[1]);
9230 return NULL;
9231 }
9232 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9233 close(fds[0]);
9234 close(fds[1]);
9235 return NULL;
9236 }
9237 }
9238#ifdef HAVE_PIPE2
9239 }
9240#endif
9241
9242 if (res != 0)
9243 return PyErr_SetFromErrno(PyExc_OSError);
9244#endif /* !MS_WINDOWS */
9245 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009246}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009247#endif /* HAVE_PIPE */
9248
Larry Hastings2f936352014-08-05 14:04:04 +10009249
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009250#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009251/*[clinic input]
9252os.pipe2
9253
9254 flags: int
9255 /
9256
9257Create a pipe with flags set atomically.
9258
9259Returns a tuple of two file descriptors:
9260 (read_fd, write_fd)
9261
9262flags can be constructed by ORing together one or more of these values:
9263O_NONBLOCK, O_CLOEXEC.
9264[clinic start generated code]*/
9265
Larry Hastings2f936352014-08-05 14:04:04 +10009266static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009267os_pipe2_impl(PyObject *module, int flags)
9268/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009269{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009270 int fds[2];
9271 int res;
9272
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009273 res = pipe2(fds, flags);
9274 if (res != 0)
9275 return posix_error();
9276 return Py_BuildValue("(ii)", fds[0], fds[1]);
9277}
9278#endif /* HAVE_PIPE2 */
9279
Larry Hastings2f936352014-08-05 14:04:04 +10009280
Ross Lagerwall7807c352011-03-17 20:20:30 +02009281#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009282/*[clinic input]
9283os.writev -> Py_ssize_t
9284 fd: int
9285 buffers: object
9286 /
9287
9288Iterate over buffers, and write the contents of each to a file descriptor.
9289
9290Returns the total number of bytes written.
9291buffers must be a sequence of bytes-like objects.
9292[clinic start generated code]*/
9293
Larry Hastings2f936352014-08-05 14:04:04 +10009294static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009295os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9296/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009297{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009298 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009299 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009300 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009301 struct iovec *iov;
9302 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009303
9304 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009305 PyErr_SetString(PyExc_TypeError,
9306 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009307 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009308 }
Larry Hastings2f936352014-08-05 14:04:04 +10009309 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009310 if (cnt < 0)
9311 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009312
Larry Hastings2f936352014-08-05 14:04:04 +10009313 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9314 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009315 }
9316
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009317 do {
9318 Py_BEGIN_ALLOW_THREADS
9319 result = writev(fd, iov, cnt);
9320 Py_END_ALLOW_THREADS
9321 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009322
9323 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009324 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009325 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009326
Georg Brandl306336b2012-06-24 12:55:33 +02009327 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009328}
Larry Hastings2f936352014-08-05 14:04:04 +10009329#endif /* HAVE_WRITEV */
9330
9331
9332#ifdef HAVE_PWRITE
9333/*[clinic input]
9334os.pwrite -> Py_ssize_t
9335
9336 fd: int
9337 buffer: Py_buffer
9338 offset: Py_off_t
9339 /
9340
9341Write bytes to a file descriptor starting at a particular offset.
9342
9343Write buffer to fd, starting at offset bytes from the beginning of
9344the file. Returns the number of bytes writte. Does not change the
9345current file offset.
9346[clinic start generated code]*/
9347
Larry Hastings2f936352014-08-05 14:04:04 +10009348static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009349os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9350/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009351{
9352 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009353 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009354
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009355 do {
9356 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009357 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009358 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009359 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009360 Py_END_ALLOW_THREADS
9361 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009362
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009363 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009364 posix_error();
9365 return size;
9366}
9367#endif /* HAVE_PWRITE */
9368
Pablo Galindo4defba32018-01-27 16:16:37 +00009369#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9370/*[clinic input]
9371os.pwritev -> Py_ssize_t
9372
9373 fd: int
9374 buffers: object
9375 offset: Py_off_t
9376 flags: int = 0
9377 /
9378
9379Writes the contents of bytes-like objects to a file descriptor at a given offset.
9380
9381Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9382of bytes-like objects. Buffers are processed in array order. Entire contents of first
9383buffer is written before proceeding to second, and so on. The operating system may
9384set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9385This function writes the contents of each object to the file descriptor and returns
9386the total number of bytes written.
9387
9388The flags argument contains a bitwise OR of zero or more of the following flags:
9389
9390- RWF_DSYNC
9391- RWF_SYNC
9392
9393Using non-zero flags requires Linux 4.7 or newer.
9394[clinic start generated code]*/
9395
9396static Py_ssize_t
9397os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9398 int flags)
9399/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9400{
9401 Py_ssize_t cnt;
9402 Py_ssize_t result;
9403 int async_err = 0;
9404 struct iovec *iov;
9405 Py_buffer *buf;
9406
9407 if (!PySequence_Check(buffers)) {
9408 PyErr_SetString(PyExc_TypeError,
9409 "pwritev() arg 2 must be a sequence");
9410 return -1;
9411 }
9412
9413 cnt = PySequence_Size(buffers);
9414 if (cnt < 0) {
9415 return -1;
9416 }
9417
9418#ifndef HAVE_PWRITEV2
9419 if(flags != 0) {
9420 argument_unavailable_error("pwritev2", "flags");
9421 return -1;
9422 }
9423#endif
9424
9425 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9426 return -1;
9427 }
9428#ifdef HAVE_PWRITEV2
9429 do {
9430 Py_BEGIN_ALLOW_THREADS
9431 _Py_BEGIN_SUPPRESS_IPH
9432 result = pwritev2(fd, iov, cnt, offset, flags);
9433 _Py_END_SUPPRESS_IPH
9434 Py_END_ALLOW_THREADS
9435 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9436#else
9437 do {
9438 Py_BEGIN_ALLOW_THREADS
9439 _Py_BEGIN_SUPPRESS_IPH
9440 result = pwritev(fd, iov, cnt, offset);
9441 _Py_END_SUPPRESS_IPH
9442 Py_END_ALLOW_THREADS
9443 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9444#endif
9445
9446 iov_cleanup(iov, buf, cnt);
9447 if (result < 0) {
9448 if (!async_err) {
9449 posix_error();
9450 }
9451 return -1;
9452 }
9453
9454 return result;
9455}
9456#endif /* HAVE_PWRITEV */
9457
9458
9459
Larry Hastings2f936352014-08-05 14:04:04 +10009460
9461#ifdef HAVE_MKFIFO
9462/*[clinic input]
9463os.mkfifo
9464
9465 path: path_t
9466 mode: int=0o666
9467 *
9468 dir_fd: dir_fd(requires='mkfifoat')=None
9469
9470Create a "fifo" (a POSIX named pipe).
9471
9472If dir_fd is not None, it should be a file descriptor open to a directory,
9473 and path should be relative; path will then be relative to that directory.
9474dir_fd may not be implemented on your platform.
9475 If it is unavailable, using it will raise a NotImplementedError.
9476[clinic start generated code]*/
9477
Larry Hastings2f936352014-08-05 14:04:04 +10009478static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009479os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9480/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009481{
9482 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009483 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009484
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009485 do {
9486 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009487#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009488 if (dir_fd != DEFAULT_DIR_FD)
9489 result = mkfifoat(dir_fd, path->narrow, mode);
9490 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009491#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009492 result = mkfifo(path->narrow, mode);
9493 Py_END_ALLOW_THREADS
9494 } while (result != 0 && errno == EINTR &&
9495 !(async_err = PyErr_CheckSignals()));
9496 if (result != 0)
9497 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009498
9499 Py_RETURN_NONE;
9500}
9501#endif /* HAVE_MKFIFO */
9502
9503
9504#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9505/*[clinic input]
9506os.mknod
9507
9508 path: path_t
9509 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009510 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009511 *
9512 dir_fd: dir_fd(requires='mknodat')=None
9513
9514Create a node in the file system.
9515
9516Create a node in the file system (file, device special file or named pipe)
9517at path. mode specifies both the permissions to use and the
9518type of node to be created, being combined (bitwise OR) with one of
9519S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9520device defines the newly created device special file (probably using
9521os.makedev()). Otherwise device is ignored.
9522
9523If dir_fd is not None, it should be a file descriptor open to a directory,
9524 and path should be relative; path will then be relative to that directory.
9525dir_fd may not be implemented on your platform.
9526 If it is unavailable, using it will raise a NotImplementedError.
9527[clinic start generated code]*/
9528
Larry Hastings2f936352014-08-05 14:04:04 +10009529static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009530os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009531 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009532/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009533{
9534 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009535 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009536
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009537 do {
9538 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009539#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009540 if (dir_fd != DEFAULT_DIR_FD)
9541 result = mknodat(dir_fd, path->narrow, mode, device);
9542 else
Larry Hastings2f936352014-08-05 14:04:04 +10009543#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009544 result = mknod(path->narrow, mode, device);
9545 Py_END_ALLOW_THREADS
9546 } while (result != 0 && errno == EINTR &&
9547 !(async_err = PyErr_CheckSignals()));
9548 if (result != 0)
9549 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009550
9551 Py_RETURN_NONE;
9552}
9553#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9554
9555
9556#ifdef HAVE_DEVICE_MACROS
9557/*[clinic input]
9558os.major -> unsigned_int
9559
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009560 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009561 /
9562
9563Extracts a device major number from a raw device number.
9564[clinic start generated code]*/
9565
Larry Hastings2f936352014-08-05 14:04:04 +10009566static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009567os_major_impl(PyObject *module, dev_t device)
9568/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009569{
9570 return major(device);
9571}
9572
9573
9574/*[clinic input]
9575os.minor -> unsigned_int
9576
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009577 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009578 /
9579
9580Extracts a device minor number from a raw device number.
9581[clinic start generated code]*/
9582
Larry Hastings2f936352014-08-05 14:04:04 +10009583static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009584os_minor_impl(PyObject *module, dev_t device)
9585/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009586{
9587 return minor(device);
9588}
9589
9590
9591/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009592os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009593
9594 major: int
9595 minor: int
9596 /
9597
9598Composes a raw device number from the major and minor device numbers.
9599[clinic start generated code]*/
9600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009601static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009602os_makedev_impl(PyObject *module, int major, int minor)
9603/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009604{
9605 return makedev(major, minor);
9606}
9607#endif /* HAVE_DEVICE_MACROS */
9608
9609
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009610#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009611/*[clinic input]
9612os.ftruncate
9613
9614 fd: int
9615 length: Py_off_t
9616 /
9617
9618Truncate a file, specified by file descriptor, to a specific length.
9619[clinic start generated code]*/
9620
Larry Hastings2f936352014-08-05 14:04:04 +10009621static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009622os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9623/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009624{
9625 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009626 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009627
Steve Dowerb82e17e2019-05-23 08:45:22 -07009628 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9629 return NULL;
9630 }
9631
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009632 do {
9633 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009634 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009635#ifdef MS_WINDOWS
9636 result = _chsize_s(fd, length);
9637#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009638 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009639#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009640 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009641 Py_END_ALLOW_THREADS
9642 } while (result != 0 && errno == EINTR &&
9643 !(async_err = PyErr_CheckSignals()));
9644 if (result != 0)
9645 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009646 Py_RETURN_NONE;
9647}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009648#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009649
9650
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009651#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009652/*[clinic input]
9653os.truncate
9654 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9655 length: Py_off_t
9656
9657Truncate a file, specified by path, to a specific length.
9658
9659On some platforms, path may also be specified as an open file descriptor.
9660 If this functionality is unavailable, using it raises an exception.
9661[clinic start generated code]*/
9662
Larry Hastings2f936352014-08-05 14:04:04 +10009663static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009664os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9665/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009666{
9667 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009668#ifdef MS_WINDOWS
9669 int fd;
9670#endif
9671
9672 if (path->fd != -1)
9673 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009674
Steve Dowerb82e17e2019-05-23 08:45:22 -07009675 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9676 return NULL;
9677 }
9678
Larry Hastings2f936352014-08-05 14:04:04 +10009679 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009680 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009681#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009682 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009683 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009684 result = -1;
9685 else {
9686 result = _chsize_s(fd, length);
9687 close(fd);
9688 if (result < 0)
9689 errno = result;
9690 }
9691#else
9692 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009693#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009694 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009695 Py_END_ALLOW_THREADS
9696 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009697 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009698
9699 Py_RETURN_NONE;
9700}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009701#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009702
Ross Lagerwall7807c352011-03-17 20:20:30 +02009703
Victor Stinnerd6b17692014-09-30 12:20:05 +02009704/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9705 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9706 defined, which is the case in Python on AIX. AIX bug report:
9707 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9708#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9709# define POSIX_FADVISE_AIX_BUG
9710#endif
9711
Victor Stinnerec39e262014-09-30 12:35:58 +02009712
Victor Stinnerd6b17692014-09-30 12:20:05 +02009713#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009714/*[clinic input]
9715os.posix_fallocate
9716
9717 fd: int
9718 offset: Py_off_t
9719 length: Py_off_t
9720 /
9721
9722Ensure a file has allocated at least a particular number of bytes on disk.
9723
9724Ensure that the file specified by fd encompasses a range of bytes
9725starting at offset bytes from the beginning and continuing for length bytes.
9726[clinic start generated code]*/
9727
Larry Hastings2f936352014-08-05 14:04:04 +10009728static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009729os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009730 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009731/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009732{
9733 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009734 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009735
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009736 do {
9737 Py_BEGIN_ALLOW_THREADS
9738 result = posix_fallocate(fd, offset, length);
9739 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009740 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9741
9742 if (result == 0)
9743 Py_RETURN_NONE;
9744
9745 if (async_err)
9746 return NULL;
9747
9748 errno = result;
9749 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009750}
Victor Stinnerec39e262014-09-30 12:35:58 +02009751#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +10009752
Ross Lagerwall7807c352011-03-17 20:20:30 +02009753
Victor Stinnerd6b17692014-09-30 12:20:05 +02009754#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009755/*[clinic input]
9756os.posix_fadvise
9757
9758 fd: int
9759 offset: Py_off_t
9760 length: Py_off_t
9761 advice: int
9762 /
9763
9764Announce an intention to access data in a specific pattern.
9765
9766Announce an intention to access data in a specific pattern, thus allowing
9767the kernel to make optimizations.
9768The advice applies to the region of the file specified by fd starting at
9769offset and continuing for length bytes.
9770advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
9771POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
9772POSIX_FADV_DONTNEED.
9773[clinic start generated code]*/
9774
Larry Hastings2f936352014-08-05 14:04:04 +10009775static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009776os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009777 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009778/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009779{
9780 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009781 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009782
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009783 do {
9784 Py_BEGIN_ALLOW_THREADS
9785 result = posix_fadvise(fd, offset, length, advice);
9786 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009787 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9788
9789 if (result == 0)
9790 Py_RETURN_NONE;
9791
9792 if (async_err)
9793 return NULL;
9794
9795 errno = result;
9796 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009797}
Victor Stinnerec39e262014-09-30 12:35:58 +02009798#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009799
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009800#ifdef HAVE_PUTENV
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009801
Fred Drake762e2061999-08-26 17:23:54 +00009802/* Save putenv() parameters as values here, so we can collect them when they
9803 * get re-set with another call for the same key. */
9804static PyObject *posix_putenv_garbage;
9805
Larry Hastings2f936352014-08-05 14:04:04 +10009806static void
9807posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009808{
Larry Hastings2f936352014-08-05 14:04:04 +10009809 /* Install the first arg and newstr in posix_putenv_garbage;
9810 * this will cause previous value to be collected. This has to
9811 * happen after the real putenv() call because the old value
9812 * was still accessible until then. */
9813 if (PyDict_SetItem(posix_putenv_garbage, name, value))
9814 /* really not much we can do; just leak */
9815 PyErr_Clear();
9816 else
9817 Py_DECREF(value);
9818}
9819
9820
Thomas Hellerf78f12a2007-11-08 19:33:05 +00009821#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009822/*[clinic input]
9823os.putenv
9824
9825 name: unicode
9826 value: unicode
9827 /
9828
9829Change or add an environment variable.
9830[clinic start generated code]*/
9831
Larry Hastings2f936352014-08-05 14:04:04 +10009832static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009833os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9834/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009835{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03009836 const wchar_t *env;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009837 Py_ssize_t size;
Larry Hastings2f936352014-08-05 14:04:04 +10009838
Serhiy Storchaka77703942017-06-25 07:33:01 +03009839 /* Search from index 1 because on Windows starting '=' is allowed for
9840 defining hidden environment variables. */
9841 if (PyUnicode_GET_LENGTH(name) == 0 ||
9842 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
9843 {
9844 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9845 return NULL;
9846 }
Larry Hastings2f936352014-08-05 14:04:04 +10009847 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
9848 if (unicode == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +10009849 return NULL;
Victor Stinner84ae1182010-05-06 22:05:07 +00009850 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009851
9852 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
9853 if (env == NULL)
9854 goto error;
9855 if (size > _MAX_ENV) {
Victor Stinner65170952011-11-22 22:16:17 +01009856 PyErr_Format(PyExc_ValueError,
9857 "the environment variable is longer than %u characters",
9858 _MAX_ENV);
9859 goto error;
9860 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009861 if (wcslen(env) != (size_t)size) {
9862 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnereb5657a2011-09-30 01:44:27 +02009863 goto error;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009864 }
9865
Larry Hastings2f936352014-08-05 14:04:04 +10009866 if (_wputenv(env)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009867 posix_error();
Victor Stinner84ae1182010-05-06 22:05:07 +00009868 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00009869 }
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009870
Larry Hastings2f936352014-08-05 14:04:04 +10009871 posix_putenv_garbage_setitem(name, unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +00009872 Py_RETURN_NONE;
9873
9874error:
Larry Hastings2f936352014-08-05 14:04:04 +10009875 Py_DECREF(unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +00009876 return NULL;
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009877}
Larry Hastings2f936352014-08-05 14:04:04 +10009878#else /* MS_WINDOWS */
9879/*[clinic input]
9880os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +00009881
Larry Hastings2f936352014-08-05 14:04:04 +10009882 name: FSConverter
9883 value: FSConverter
9884 /
9885
9886Change or add an environment variable.
9887[clinic start generated code]*/
9888
Larry Hastings2f936352014-08-05 14:04:04 +10009889static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009890os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9891/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009892{
9893 PyObject *bytes = NULL;
9894 char *env;
Serhiy Storchaka77703942017-06-25 07:33:01 +03009895 const char *name_string = PyBytes_AS_STRING(name);
9896 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +10009897
Serhiy Storchaka77703942017-06-25 07:33:01 +03009898 if (strchr(name_string, '=') != NULL) {
9899 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9900 return NULL;
9901 }
Larry Hastings2f936352014-08-05 14:04:04 +10009902 bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
9903 if (bytes == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +10009904 return NULL;
9905 }
9906
9907 env = PyBytes_AS_STRING(bytes);
9908 if (putenv(env)) {
9909 Py_DECREF(bytes);
9910 return posix_error();
9911 }
9912
9913 posix_putenv_garbage_setitem(name, bytes);
9914 Py_RETURN_NONE;
9915}
9916#endif /* MS_WINDOWS */
9917#endif /* HAVE_PUTENV */
9918
9919
9920#ifdef HAVE_UNSETENV
9921/*[clinic input]
9922os.unsetenv
9923 name: FSConverter
9924 /
9925
9926Delete an environment variable.
9927[clinic start generated code]*/
9928
Larry Hastings2f936352014-08-05 14:04:04 +10009929static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009930os_unsetenv_impl(PyObject *module, PyObject *name)
9931/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009932{
Victor Stinner984890f2011-11-24 13:53:38 +01009933#ifndef HAVE_BROKEN_UNSETENV
Victor Stinner60b385e2011-11-22 22:01:28 +01009934 int err;
Victor Stinner984890f2011-11-24 13:53:38 +01009935#endif
Victor Stinner84ae1182010-05-06 22:05:07 +00009936
Victor Stinner984890f2011-11-24 13:53:38 +01009937#ifdef HAVE_BROKEN_UNSETENV
9938 unsetenv(PyBytes_AS_STRING(name));
9939#else
Victor Stinner65170952011-11-22 22:16:17 +01009940 err = unsetenv(PyBytes_AS_STRING(name));
Larry Hastings2f936352014-08-05 14:04:04 +10009941 if (err)
Victor Stinner60b385e2011-11-22 22:01:28 +01009942 return posix_error();
Victor Stinner984890f2011-11-24 13:53:38 +01009943#endif
Guido van Rossumc524d952001-10-19 01:31:59 +00009944
Victor Stinner8c62be82010-05-06 00:08:46 +00009945 /* Remove the key from posix_putenv_garbage;
9946 * this will cause it to be collected. This has to
9947 * happen after the real unsetenv() call because the
9948 * old value was still accessible until then.
9949 */
Victor Stinner65170952011-11-22 22:16:17 +01009950 if (PyDict_DelItem(posix_putenv_garbage, name)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009951 /* really not much we can do; just leak */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02009952 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
9953 return NULL;
9954 }
Victor Stinner8c62be82010-05-06 00:08:46 +00009955 PyErr_Clear();
9956 }
Victor Stinner84ae1182010-05-06 22:05:07 +00009957 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +00009958}
Larry Hastings2f936352014-08-05 14:04:04 +10009959#endif /* HAVE_UNSETENV */
Guido van Rossumc524d952001-10-19 01:31:59 +00009960
Larry Hastings2f936352014-08-05 14:04:04 +10009961
9962/*[clinic input]
9963os.strerror
9964
9965 code: int
9966 /
9967
9968Translate an error code to a message string.
9969[clinic start generated code]*/
9970
Larry Hastings2f936352014-08-05 14:04:04 +10009971static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009972os_strerror_impl(PyObject *module, int code)
9973/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009974{
9975 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +00009976 if (message == NULL) {
9977 PyErr_SetString(PyExc_ValueError,
9978 "strerror() argument out of range");
9979 return NULL;
9980 }
Victor Stinner1b579672011-12-17 05:47:23 +01009981 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +00009982}
Guido van Rossumb6a47161997-09-15 22:54:34 +00009983
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009984
Guido van Rossumc9641791998-08-04 15:26:23 +00009985#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +00009986#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +10009987/*[clinic input]
9988os.WCOREDUMP -> bool
9989
9990 status: int
9991 /
9992
9993Return True if the process returning status was dumped to a core file.
9994[clinic start generated code]*/
9995
Larry Hastings2f936352014-08-05 14:04:04 +10009996static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009997os_WCOREDUMP_impl(PyObject *module, int status)
9998/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009999{
10000 WAIT_TYPE wait_status;
10001 WAIT_STATUS_INT(wait_status) = status;
10002 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010003}
10004#endif /* WCOREDUMP */
10005
Larry Hastings2f936352014-08-05 14:04:04 +100010006
Fred Drake106c1a02002-04-23 15:58:02 +000010007#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010008/*[clinic input]
10009os.WIFCONTINUED -> bool
10010
10011 status: int
10012
10013Return True if a particular process was continued from a job control stop.
10014
10015Return True if the process returning status was continued from a
10016job control stop.
10017[clinic start generated code]*/
10018
Larry Hastings2f936352014-08-05 14:04:04 +100010019static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010020os_WIFCONTINUED_impl(PyObject *module, int status)
10021/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010022{
10023 WAIT_TYPE wait_status;
10024 WAIT_STATUS_INT(wait_status) = status;
10025 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010026}
10027#endif /* WIFCONTINUED */
10028
Larry Hastings2f936352014-08-05 14:04:04 +100010029
Guido van Rossumc9641791998-08-04 15:26:23 +000010030#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010031/*[clinic input]
10032os.WIFSTOPPED -> bool
10033
10034 status: int
10035
10036Return True if the process returning status was stopped.
10037[clinic start generated code]*/
10038
Larry Hastings2f936352014-08-05 14:04:04 +100010039static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010040os_WIFSTOPPED_impl(PyObject *module, int status)
10041/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010042{
10043 WAIT_TYPE wait_status;
10044 WAIT_STATUS_INT(wait_status) = status;
10045 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010046}
10047#endif /* WIFSTOPPED */
10048
Larry Hastings2f936352014-08-05 14:04:04 +100010049
Guido van Rossumc9641791998-08-04 15:26:23 +000010050#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010051/*[clinic input]
10052os.WIFSIGNALED -> bool
10053
10054 status: int
10055
10056Return True if the process returning status was terminated by a signal.
10057[clinic start generated code]*/
10058
Larry Hastings2f936352014-08-05 14:04:04 +100010059static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010060os_WIFSIGNALED_impl(PyObject *module, int status)
10061/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010062{
10063 WAIT_TYPE wait_status;
10064 WAIT_STATUS_INT(wait_status) = status;
10065 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010066}
10067#endif /* WIFSIGNALED */
10068
Larry Hastings2f936352014-08-05 14:04:04 +100010069
Guido van Rossumc9641791998-08-04 15:26:23 +000010070#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010071/*[clinic input]
10072os.WIFEXITED -> bool
10073
10074 status: int
10075
10076Return True if the process returning status exited via the exit() system call.
10077[clinic start generated code]*/
10078
Larry Hastings2f936352014-08-05 14:04:04 +100010079static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010080os_WIFEXITED_impl(PyObject *module, int status)
10081/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010082{
10083 WAIT_TYPE wait_status;
10084 WAIT_STATUS_INT(wait_status) = status;
10085 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010086}
10087#endif /* WIFEXITED */
10088
Larry Hastings2f936352014-08-05 14:04:04 +100010089
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010090#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010091/*[clinic input]
10092os.WEXITSTATUS -> int
10093
10094 status: int
10095
10096Return the process return code from status.
10097[clinic start generated code]*/
10098
Larry Hastings2f936352014-08-05 14:04:04 +100010099static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010100os_WEXITSTATUS_impl(PyObject *module, int status)
10101/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010102{
10103 WAIT_TYPE wait_status;
10104 WAIT_STATUS_INT(wait_status) = status;
10105 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010106}
10107#endif /* WEXITSTATUS */
10108
Larry Hastings2f936352014-08-05 14:04:04 +100010109
Guido van Rossumc9641791998-08-04 15:26:23 +000010110#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010111/*[clinic input]
10112os.WTERMSIG -> int
10113
10114 status: int
10115
10116Return the signal that terminated the process that provided the status value.
10117[clinic start generated code]*/
10118
Larry Hastings2f936352014-08-05 14:04:04 +100010119static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010120os_WTERMSIG_impl(PyObject *module, int status)
10121/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010122{
10123 WAIT_TYPE wait_status;
10124 WAIT_STATUS_INT(wait_status) = status;
10125 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010126}
10127#endif /* WTERMSIG */
10128
Larry Hastings2f936352014-08-05 14:04:04 +100010129
Guido van Rossumc9641791998-08-04 15:26:23 +000010130#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010131/*[clinic input]
10132os.WSTOPSIG -> int
10133
10134 status: int
10135
10136Return the signal that stopped the process that provided the status value.
10137[clinic start generated code]*/
10138
Larry Hastings2f936352014-08-05 14:04:04 +100010139static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010140os_WSTOPSIG_impl(PyObject *module, int status)
10141/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010142{
10143 WAIT_TYPE wait_status;
10144 WAIT_STATUS_INT(wait_status) = status;
10145 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010146}
10147#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010148#endif /* HAVE_SYS_WAIT_H */
10149
10150
Thomas Wouters477c8d52006-05-27 19:21:47 +000010151#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010152#ifdef _SCO_DS
10153/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10154 needed definitions in sys/statvfs.h */
10155#define _SVID3
10156#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010157#include <sys/statvfs.h>
10158
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010159static PyObject*
10160_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondo474eedf2018-11-13 04:09:31 -080010161 PyObject *v = PyStructSequence_New(StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010162 if (v == NULL)
10163 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010164
10165#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010166 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10167 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10168 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10169 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10170 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10171 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10172 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10173 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10174 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10175 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010176#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010177 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10178 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10179 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010180 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010181 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010182 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010183 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010184 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010185 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010186 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010187 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010188 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010189 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010190 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010191 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10192 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010193#endif
Michael Felt502d5512018-01-05 13:01:58 +010010194/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10195 * (issue #32390). */
10196#if defined(_AIX) && defined(_ALL_SOURCE)
10197 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10198#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010199 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010200#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010201 if (PyErr_Occurred()) {
10202 Py_DECREF(v);
10203 return NULL;
10204 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010205
Victor Stinner8c62be82010-05-06 00:08:46 +000010206 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010207}
10208
Larry Hastings2f936352014-08-05 14:04:04 +100010209
10210/*[clinic input]
10211os.fstatvfs
10212 fd: int
10213 /
10214
10215Perform an fstatvfs system call on the given fd.
10216
10217Equivalent to statvfs(fd).
10218[clinic start generated code]*/
10219
Larry Hastings2f936352014-08-05 14:04:04 +100010220static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010221os_fstatvfs_impl(PyObject *module, int fd)
10222/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010223{
10224 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010225 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010226 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010227
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010228 do {
10229 Py_BEGIN_ALLOW_THREADS
10230 result = fstatvfs(fd, &st);
10231 Py_END_ALLOW_THREADS
10232 } while (result != 0 && errno == EINTR &&
10233 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010234 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010235 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010236
Victor Stinner8c62be82010-05-06 00:08:46 +000010237 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010238}
Larry Hastings2f936352014-08-05 14:04:04 +100010239#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010240
10241
Thomas Wouters477c8d52006-05-27 19:21:47 +000010242#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010243#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010244/*[clinic input]
10245os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010246
Larry Hastings2f936352014-08-05 14:04:04 +100010247 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10248
10249Perform a statvfs system call on the given path.
10250
10251path may always be specified as a string.
10252On some platforms, path may also be specified as an open file descriptor.
10253 If this functionality is unavailable, using it raises an exception.
10254[clinic start generated code]*/
10255
Larry Hastings2f936352014-08-05 14:04:04 +100010256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010257os_statvfs_impl(PyObject *module, path_t *path)
10258/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010259{
10260 int result;
10261 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010262
10263 Py_BEGIN_ALLOW_THREADS
10264#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010265 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010266#ifdef __APPLE__
10267 /* handle weak-linking on Mac OS X 10.3 */
10268 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010269 fd_specified("statvfs", path->fd);
10270 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010271 }
10272#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010273 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010274 }
10275 else
10276#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010277 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010278 Py_END_ALLOW_THREADS
10279
10280 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010281 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010282 }
10283
Larry Hastings2f936352014-08-05 14:04:04 +100010284 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010285}
Larry Hastings2f936352014-08-05 14:04:04 +100010286#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10287
Guido van Rossum94f6f721999-01-06 18:42:14 +000010288
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010289#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010290/*[clinic input]
10291os._getdiskusage
10292
Steve Dower23ad6d02018-02-22 10:39:10 -080010293 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010294
10295Return disk usage statistics about the given path as a (total, free) tuple.
10296[clinic start generated code]*/
10297
Larry Hastings2f936352014-08-05 14:04:04 +100010298static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010299os__getdiskusage_impl(PyObject *module, path_t *path)
10300/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010301{
10302 BOOL retval;
10303 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010304 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010305
10306 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010307 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010308 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010309 if (retval == 0) {
10310 if (GetLastError() == ERROR_DIRECTORY) {
10311 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010312
Joe Pamerc8c02492018-09-25 10:57:36 -040010313 dir_path = PyMem_New(wchar_t, path->length + 1);
10314 if (dir_path == NULL) {
10315 return PyErr_NoMemory();
10316 }
10317
10318 wcscpy_s(dir_path, path->length + 1, path->wide);
10319
10320 if (_dirnameW(dir_path) != -1) {
10321 Py_BEGIN_ALLOW_THREADS
10322 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10323 Py_END_ALLOW_THREADS
10324 }
10325 /* Record the last error in case it's modified by PyMem_Free. */
10326 err = GetLastError();
10327 PyMem_Free(dir_path);
10328 if (retval) {
10329 goto success;
10330 }
10331 }
10332 return PyErr_SetFromWindowsErr(err);
10333 }
10334
10335success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010336 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10337}
Larry Hastings2f936352014-08-05 14:04:04 +100010338#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010339
10340
Fred Drakec9680921999-12-13 16:37:25 +000010341/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10342 * It maps strings representing configuration variable names to
10343 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010344 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010345 * rarely-used constants. There are three separate tables that use
10346 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010347 *
10348 * This code is always included, even if none of the interfaces that
10349 * need it are included. The #if hackery needed to avoid it would be
10350 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010351 */
10352struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010353 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010354 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010355};
10356
Fred Drake12c6e2d1999-12-14 21:25:03 +000010357static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010358conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010359 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010360{
Christian Heimes217cfd12007-12-02 14:31:20 +000010361 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010362 int value = _PyLong_AsInt(arg);
10363 if (value == -1 && PyErr_Occurred())
10364 return 0;
10365 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010366 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010367 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010368 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010369 /* look up the value in the table using a binary search */
10370 size_t lo = 0;
10371 size_t mid;
10372 size_t hi = tablesize;
10373 int cmp;
10374 const char *confname;
10375 if (!PyUnicode_Check(arg)) {
10376 PyErr_SetString(PyExc_TypeError,
10377 "configuration names must be strings or integers");
10378 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010379 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010380 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010381 if (confname == NULL)
10382 return 0;
10383 while (lo < hi) {
10384 mid = (lo + hi) / 2;
10385 cmp = strcmp(confname, table[mid].name);
10386 if (cmp < 0)
10387 hi = mid;
10388 else if (cmp > 0)
10389 lo = mid + 1;
10390 else {
10391 *valuep = table[mid].value;
10392 return 1;
10393 }
10394 }
10395 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10396 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010397 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010398}
10399
10400
10401#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10402static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010403#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010404 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010405#endif
10406#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010407 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010408#endif
Fred Drakec9680921999-12-13 16:37:25 +000010409#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010410 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010411#endif
10412#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010413 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010414#endif
10415#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010416 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010417#endif
10418#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010419 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010420#endif
10421#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010422 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010423#endif
10424#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010425 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010426#endif
10427#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010428 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010429#endif
10430#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010431 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010432#endif
10433#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010434 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010435#endif
10436#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010437 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010438#endif
10439#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010440 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010441#endif
10442#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010443 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010444#endif
10445#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010446 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010447#endif
10448#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010449 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010450#endif
10451#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010452 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010453#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010454#ifdef _PC_ACL_ENABLED
10455 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10456#endif
10457#ifdef _PC_MIN_HOLE_SIZE
10458 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10459#endif
10460#ifdef _PC_ALLOC_SIZE_MIN
10461 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10462#endif
10463#ifdef _PC_REC_INCR_XFER_SIZE
10464 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10465#endif
10466#ifdef _PC_REC_MAX_XFER_SIZE
10467 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10468#endif
10469#ifdef _PC_REC_MIN_XFER_SIZE
10470 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10471#endif
10472#ifdef _PC_REC_XFER_ALIGN
10473 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10474#endif
10475#ifdef _PC_SYMLINK_MAX
10476 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10477#endif
10478#ifdef _PC_XATTR_ENABLED
10479 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10480#endif
10481#ifdef _PC_XATTR_EXISTS
10482 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10483#endif
10484#ifdef _PC_TIMESTAMP_RESOLUTION
10485 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10486#endif
Fred Drakec9680921999-12-13 16:37:25 +000010487};
10488
Fred Drakec9680921999-12-13 16:37:25 +000010489static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010490conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010491{
10492 return conv_confname(arg, valuep, posix_constants_pathconf,
10493 sizeof(posix_constants_pathconf)
10494 / sizeof(struct constdef));
10495}
10496#endif
10497
Larry Hastings2f936352014-08-05 14:04:04 +100010498
Fred Drakec9680921999-12-13 16:37:25 +000010499#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010500/*[clinic input]
10501os.fpathconf -> long
10502
10503 fd: int
10504 name: path_confname
10505 /
10506
10507Return the configuration limit name for the file descriptor fd.
10508
10509If there is no limit, return -1.
10510[clinic start generated code]*/
10511
Larry Hastings2f936352014-08-05 14:04:04 +100010512static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010513os_fpathconf_impl(PyObject *module, int fd, int name)
10514/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010515{
10516 long limit;
10517
10518 errno = 0;
10519 limit = fpathconf(fd, name);
10520 if (limit == -1 && errno != 0)
10521 posix_error();
10522
10523 return limit;
10524}
10525#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010526
10527
10528#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010529/*[clinic input]
10530os.pathconf -> long
10531 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10532 name: path_confname
10533
10534Return the configuration limit name for the file or directory path.
10535
10536If there is no limit, return -1.
10537On some platforms, path may also be specified as an open file descriptor.
10538 If this functionality is unavailable, using it raises an exception.
10539[clinic start generated code]*/
10540
Larry Hastings2f936352014-08-05 14:04:04 +100010541static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010542os_pathconf_impl(PyObject *module, path_t *path, int name)
10543/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010544{
Victor Stinner8c62be82010-05-06 00:08:46 +000010545 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010546
Victor Stinner8c62be82010-05-06 00:08:46 +000010547 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010548#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010549 if (path->fd != -1)
10550 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010551 else
10552#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010553 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010554 if (limit == -1 && errno != 0) {
10555 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010556 /* could be a path or name problem */
10557 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010558 else
Larry Hastings2f936352014-08-05 14:04:04 +100010559 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010560 }
Larry Hastings2f936352014-08-05 14:04:04 +100010561
10562 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010563}
Larry Hastings2f936352014-08-05 14:04:04 +100010564#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010565
10566#ifdef HAVE_CONFSTR
10567static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010568#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010569 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010570#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010571#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010572 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010573#endif
10574#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010575 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010576#endif
Fred Draked86ed291999-12-15 15:34:33 +000010577#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010578 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010579#endif
10580#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010581 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010582#endif
10583#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010584 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010585#endif
10586#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010587 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010588#endif
Fred Drakec9680921999-12-13 16:37:25 +000010589#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010590 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010591#endif
10592#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010593 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010594#endif
10595#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010596 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010597#endif
10598#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010599 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010600#endif
10601#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010602 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010603#endif
10604#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010605 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010606#endif
10607#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010608 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010609#endif
10610#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010611 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010612#endif
Fred Draked86ed291999-12-15 15:34:33 +000010613#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010614 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010615#endif
Fred Drakec9680921999-12-13 16:37:25 +000010616#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010617 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010618#endif
Fred Draked86ed291999-12-15 15:34:33 +000010619#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010620 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010621#endif
10622#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010623 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010624#endif
10625#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010626 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010627#endif
10628#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010629 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010630#endif
Fred Drakec9680921999-12-13 16:37:25 +000010631#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010632 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010633#endif
10634#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010635 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010636#endif
10637#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010638 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010639#endif
10640#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010641 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010642#endif
10643#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010644 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010645#endif
10646#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010647 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010648#endif
10649#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010650 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010651#endif
10652#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010653 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010654#endif
10655#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010656 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010657#endif
10658#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010659 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010660#endif
10661#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010662 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010663#endif
10664#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010665 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010666#endif
10667#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010668 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010669#endif
10670#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010671 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010672#endif
10673#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010674 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010675#endif
10676#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010677 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010678#endif
Fred Draked86ed291999-12-15 15:34:33 +000010679#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010680 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010681#endif
10682#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010683 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010684#endif
10685#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010686 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010687#endif
10688#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010689 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010690#endif
10691#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010692 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010693#endif
10694#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010695 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010696#endif
10697#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010698 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010699#endif
10700#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010701 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010702#endif
10703#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010704 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010705#endif
10706#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010707 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010708#endif
10709#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010710 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010711#endif
10712#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010713 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010714#endif
10715#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010716 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010717#endif
Fred Drakec9680921999-12-13 16:37:25 +000010718};
10719
10720static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010721conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010722{
10723 return conv_confname(arg, valuep, posix_constants_confstr,
10724 sizeof(posix_constants_confstr)
10725 / sizeof(struct constdef));
10726}
10727
Larry Hastings2f936352014-08-05 14:04:04 +100010728
10729/*[clinic input]
10730os.confstr
10731
10732 name: confstr_confname
10733 /
10734
10735Return a string-valued system configuration variable.
10736[clinic start generated code]*/
10737
Larry Hastings2f936352014-08-05 14:04:04 +100010738static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010739os_confstr_impl(PyObject *module, int name)
10740/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000010741{
10742 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000010743 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010744 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000010745
Victor Stinnercb043522010-09-10 23:49:04 +000010746 errno = 0;
10747 len = confstr(name, buffer, sizeof(buffer));
10748 if (len == 0) {
10749 if (errno) {
10750 posix_error();
10751 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000010752 }
10753 else {
Victor Stinnercb043522010-09-10 23:49:04 +000010754 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000010755 }
10756 }
Victor Stinnercb043522010-09-10 23:49:04 +000010757
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010758 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010010759 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000010760 char *buf = PyMem_Malloc(len);
10761 if (buf == NULL)
10762 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010010763 len2 = confstr(name, buf, len);
10764 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020010765 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000010766 PyMem_Free(buf);
10767 }
10768 else
10769 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000010770 return result;
10771}
Larry Hastings2f936352014-08-05 14:04:04 +100010772#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000010773
10774
10775#ifdef HAVE_SYSCONF
10776static struct constdef posix_constants_sysconf[] = {
10777#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000010778 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000010779#endif
10780#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000010781 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000010782#endif
10783#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010784 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010785#endif
10786#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010787 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000010788#endif
10789#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010790 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010791#endif
10792#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000010793 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000010794#endif
10795#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000010796 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000010797#endif
10798#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010799 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010800#endif
10801#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000010802 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000010803#endif
10804#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010805 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000010806#endif
Fred Draked86ed291999-12-15 15:34:33 +000010807#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010808 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010809#endif
10810#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000010811 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000010812#endif
Fred Drakec9680921999-12-13 16:37:25 +000010813#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010814 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010815#endif
Fred Drakec9680921999-12-13 16:37:25 +000010816#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010817 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010818#endif
10819#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010820 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010821#endif
10822#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010823 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010824#endif
10825#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010826 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010827#endif
10828#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010829 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010830#endif
Fred Draked86ed291999-12-15 15:34:33 +000010831#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010832 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000010833#endif
Fred Drakec9680921999-12-13 16:37:25 +000010834#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000010835 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000010836#endif
10837#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010838 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010839#endif
10840#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010841 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010842#endif
10843#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010844 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010845#endif
10846#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010847 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010848#endif
Fred Draked86ed291999-12-15 15:34:33 +000010849#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000010850 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000010851#endif
Fred Drakec9680921999-12-13 16:37:25 +000010852#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010853 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010854#endif
10855#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010856 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000010857#endif
10858#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010859 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010860#endif
10861#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010862 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010863#endif
10864#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010865 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010866#endif
10867#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000010868 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000010869#endif
10870#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010871 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010872#endif
10873#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010874 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010875#endif
10876#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000010877 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000010878#endif
10879#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010880 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010881#endif
10882#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010883 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000010884#endif
10885#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010886 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000010887#endif
10888#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010889 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010890#endif
10891#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010892 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010893#endif
10894#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010895 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010896#endif
10897#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010898 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010899#endif
10900#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010901 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000010902#endif
10903#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010904 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010905#endif
10906#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010907 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010908#endif
10909#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000010910 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000010911#endif
10912#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010913 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010914#endif
10915#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010916 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000010917#endif
10918#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010919 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000010920#endif
Fred Draked86ed291999-12-15 15:34:33 +000010921#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000010922 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000010923#endif
Fred Drakec9680921999-12-13 16:37:25 +000010924#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010925 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010926#endif
10927#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010928 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010929#endif
10930#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010931 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010932#endif
Fred Draked86ed291999-12-15 15:34:33 +000010933#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000010934 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000010935#endif
Fred Drakec9680921999-12-13 16:37:25 +000010936#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000010937 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000010938#endif
Fred Draked86ed291999-12-15 15:34:33 +000010939#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000010940 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000010941#endif
10942#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000010943 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000010944#endif
Fred Drakec9680921999-12-13 16:37:25 +000010945#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010946 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010947#endif
10948#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010949 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010950#endif
10951#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010952 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010953#endif
10954#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010955 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000010956#endif
Fred Draked86ed291999-12-15 15:34:33 +000010957#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000010958 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000010959#endif
Fred Drakec9680921999-12-13 16:37:25 +000010960#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000010961 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000010962#endif
10963#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000010964 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000010965#endif
10966#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010967 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010968#endif
10969#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000010970 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000010971#endif
10972#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000010973 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000010974#endif
10975#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000010976 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000010977#endif
10978#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000010979 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000010980#endif
Fred Draked86ed291999-12-15 15:34:33 +000010981#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000010982 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000010983#endif
Fred Drakec9680921999-12-13 16:37:25 +000010984#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010985 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010986#endif
10987#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010988 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010989#endif
Fred Draked86ed291999-12-15 15:34:33 +000010990#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010991 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010992#endif
Fred Drakec9680921999-12-13 16:37:25 +000010993#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010994 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010995#endif
10996#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010997 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000010998#endif
10999#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011000 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011001#endif
11002#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011003 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011004#endif
11005#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011006 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011007#endif
11008#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011009 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011010#endif
11011#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011012 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011013#endif
11014#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011015 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011016#endif
11017#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011018 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011019#endif
Fred Draked86ed291999-12-15 15:34:33 +000011020#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011021 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011022#endif
11023#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011024 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011025#endif
Fred Drakec9680921999-12-13 16:37:25 +000011026#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011027 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011028#endif
11029#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011030 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011031#endif
11032#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011033 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011034#endif
11035#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011036 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011037#endif
11038#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011039 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011040#endif
11041#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011042 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011043#endif
11044#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011045 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011046#endif
11047#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011048 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011049#endif
11050#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011051 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011052#endif
11053#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011054 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011055#endif
11056#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011057 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011058#endif
11059#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011060 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011061#endif
11062#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011063 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011064#endif
11065#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011066 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011067#endif
11068#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011069 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011070#endif
11071#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011072 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011073#endif
11074#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011075 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011076#endif
11077#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011078 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011079#endif
11080#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011081 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011082#endif
11083#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011084 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011085#endif
11086#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011087 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011088#endif
11089#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011090 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011091#endif
11092#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011093 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011094#endif
11095#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011096 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011097#endif
11098#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011099 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011100#endif
11101#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011102 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011103#endif
11104#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011105 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011106#endif
11107#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011108 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011109#endif
11110#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011111 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011112#endif
11113#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011114 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011115#endif
11116#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011117 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011118#endif
11119#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011120 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011121#endif
11122#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011123 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011124#endif
11125#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011126 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011127#endif
11128#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011129 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011130#endif
Fred Draked86ed291999-12-15 15:34:33 +000011131#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011132 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011133#endif
Fred Drakec9680921999-12-13 16:37:25 +000011134#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011135 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011136#endif
11137#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011138 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011139#endif
11140#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011141 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011142#endif
11143#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011144 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011145#endif
11146#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011147 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011148#endif
11149#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011150 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011151#endif
11152#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011153 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011154#endif
11155#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011156 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011157#endif
11158#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011159 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011160#endif
11161#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011162 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011163#endif
11164#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011165 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011166#endif
11167#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011168 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011169#endif
11170#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011171 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011172#endif
11173#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011174 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011175#endif
11176#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011177 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011178#endif
11179#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011180 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011181#endif
11182#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011183 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011184#endif
11185#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011186 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011187#endif
11188#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011189 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011190#endif
11191#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011192 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011193#endif
11194#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011195 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011196#endif
11197#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011198 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011199#endif
11200#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011201 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011202#endif
11203#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011204 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011205#endif
11206#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011207 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011208#endif
11209#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011210 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011211#endif
11212#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011213 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011214#endif
11215#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011216 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011217#endif
11218#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011219 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011220#endif
11221#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011222 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011223#endif
11224#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011225 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011226#endif
11227#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011228 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011229#endif
11230#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011231 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011232#endif
11233#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011234 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011235#endif
11236#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011237 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011238#endif
11239#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011240 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011241#endif
11242#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011243 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011244#endif
11245#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011246 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011247#endif
11248#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011249 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011250#endif
11251#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011252 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011253#endif
11254#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011255 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011256#endif
11257#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011258 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011259#endif
11260#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011261 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011262#endif
11263#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011264 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011265#endif
11266#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011267 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011268#endif
11269};
11270
11271static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011272conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011273{
11274 return conv_confname(arg, valuep, posix_constants_sysconf,
11275 sizeof(posix_constants_sysconf)
11276 / sizeof(struct constdef));
11277}
11278
Larry Hastings2f936352014-08-05 14:04:04 +100011279
11280/*[clinic input]
11281os.sysconf -> long
11282 name: sysconf_confname
11283 /
11284
11285Return an integer-valued system configuration variable.
11286[clinic start generated code]*/
11287
Larry Hastings2f936352014-08-05 14:04:04 +100011288static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011289os_sysconf_impl(PyObject *module, int name)
11290/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011291{
11292 long value;
11293
11294 errno = 0;
11295 value = sysconf(name);
11296 if (value == -1 && errno != 0)
11297 posix_error();
11298 return value;
11299}
11300#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011301
11302
Fred Drakebec628d1999-12-15 18:31:10 +000011303/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011304 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011305 * the exported dictionaries that are used to publish information about the
11306 * names available on the host platform.
11307 *
11308 * Sorting the table at runtime ensures that the table is properly ordered
11309 * when used, even for platforms we're not able to test on. It also makes
11310 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011311 */
Fred Drakebec628d1999-12-15 18:31:10 +000011312
11313static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011314cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011315{
11316 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011317 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011318 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011319 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011320
11321 return strcmp(c1->name, c2->name);
11322}
11323
11324static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011325setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011326 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011327{
Fred Drakebec628d1999-12-15 18:31:10 +000011328 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011329 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011330
11331 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11332 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011333 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011334 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011335
Barry Warsaw3155db32000-04-13 15:20:40 +000011336 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011337 PyObject *o = PyLong_FromLong(table[i].value);
11338 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11339 Py_XDECREF(o);
11340 Py_DECREF(d);
11341 return -1;
11342 }
11343 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011344 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011345 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011346}
11347
Fred Drakebec628d1999-12-15 18:31:10 +000011348/* Return -1 on failure, 0 on success. */
11349static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011350setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011351{
11352#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011353 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011354 sizeof(posix_constants_pathconf)
11355 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011356 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011357 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011358#endif
11359#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011360 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011361 sizeof(posix_constants_confstr)
11362 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011363 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011364 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011365#endif
11366#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011367 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011368 sizeof(posix_constants_sysconf)
11369 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011370 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011371 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011372#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011373 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011374}
Fred Draked86ed291999-12-15 15:34:33 +000011375
11376
Larry Hastings2f936352014-08-05 14:04:04 +100011377/*[clinic input]
11378os.abort
11379
11380Abort the interpreter immediately.
11381
11382This function 'dumps core' or otherwise fails in the hardest way possible
11383on the hosting operating system. This function never returns.
11384[clinic start generated code]*/
11385
Larry Hastings2f936352014-08-05 14:04:04 +100011386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011387os_abort_impl(PyObject *module)
11388/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011389{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011390 abort();
11391 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011392#ifndef __clang__
11393 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11394 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11395 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011396 Py_FatalError("abort() called from Python code didn't abort!");
11397 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011398#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011399}
Fred Drakebec628d1999-12-15 18:31:10 +000011400
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011401#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011402/* Grab ShellExecute dynamically from shell32 */
11403static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011404static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11405 LPCWSTR, INT);
11406static int
11407check_ShellExecute()
11408{
11409 HINSTANCE hShell32;
11410
11411 /* only recheck */
11412 if (-1 == has_ShellExecute) {
11413 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011414 /* Security note: this call is not vulnerable to "DLL hijacking".
11415 SHELL32 is part of "KnownDLLs" and so Windows always load
11416 the system SHELL32.DLL, even if there is another SHELL32.DLL
11417 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011418 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011419 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011420 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11421 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011422 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011423 } else {
11424 has_ShellExecute = 0;
11425 }
Tony Roberts4860f012019-02-02 18:16:42 +010011426 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011427 }
11428 return has_ShellExecute;
11429}
11430
11431
Steve Dowercc16be82016-09-08 10:35:16 -070011432/*[clinic input]
11433os.startfile
11434 filepath: path_t
11435 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011436
Steve Dowercc16be82016-09-08 10:35:16 -070011437startfile(filepath [, operation])
11438
11439Start a file with its associated application.
11440
11441When "operation" is not specified or "open", this acts like
11442double-clicking the file in Explorer, or giving the file name as an
11443argument to the DOS "start" command: the file is opened with whatever
11444application (if any) its extension is associated.
11445When another "operation" is given, it specifies what should be done with
11446the file. A typical operation is "print".
11447
11448startfile returns as soon as the associated application is launched.
11449There is no option to wait for the application to close, and no way
11450to retrieve the application's exit status.
11451
11452The filepath is relative to the current directory. If you want to use
11453an absolute path, make sure the first character is not a slash ("/");
11454the underlying Win32 ShellExecute function doesn't work if it is.
11455[clinic start generated code]*/
11456
11457static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011458os_startfile_impl(PyObject *module, path_t *filepath,
11459 const Py_UNICODE *operation)
11460/*[clinic end generated code: output=66dc311c94d50797 input=63950bf2986380d0]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011461{
11462 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011463
11464 if(!check_ShellExecute()) {
11465 /* If the OS doesn't have ShellExecute, return a
11466 NotImplementedError. */
11467 return PyErr_Format(PyExc_NotImplementedError,
11468 "startfile not available on this platform");
11469 }
11470
Victor Stinner8c62be82010-05-06 00:08:46 +000011471 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011472 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011473 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011474 Py_END_ALLOW_THREADS
11475
Victor Stinner8c62be82010-05-06 00:08:46 +000011476 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011477 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011478 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011479 }
Steve Dowercc16be82016-09-08 10:35:16 -070011480 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011481}
Larry Hastings2f936352014-08-05 14:04:04 +100011482#endif /* MS_WINDOWS */
11483
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011484
Martin v. Löwis438b5342002-12-27 10:16:42 +000011485#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011486/*[clinic input]
11487os.getloadavg
11488
11489Return average recent system load information.
11490
11491Return the number of processes in the system run queue averaged over
11492the last 1, 5, and 15 minutes as a tuple of three floats.
11493Raises OSError if the load average was unobtainable.
11494[clinic start generated code]*/
11495
Larry Hastings2f936352014-08-05 14:04:04 +100011496static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011497os_getloadavg_impl(PyObject *module)
11498/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011499{
11500 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011501 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011502 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11503 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011504 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011505 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011506}
Larry Hastings2f936352014-08-05 14:04:04 +100011507#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011508
Larry Hastings2f936352014-08-05 14:04:04 +100011509
11510/*[clinic input]
11511os.device_encoding
11512 fd: int
11513
11514Return a string describing the encoding of a terminal's file descriptor.
11515
11516The file descriptor must be attached to a terminal.
11517If the device is not a terminal, return None.
11518[clinic start generated code]*/
11519
Larry Hastings2f936352014-08-05 14:04:04 +100011520static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011521os_device_encoding_impl(PyObject *module, int fd)
11522/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011523{
Brett Cannonefb00c02012-02-29 18:31:31 -050011524 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011525}
11526
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011527
Larry Hastings2f936352014-08-05 14:04:04 +100011528#ifdef HAVE_SETRESUID
11529/*[clinic input]
11530os.setresuid
11531
11532 ruid: uid_t
11533 euid: uid_t
11534 suid: uid_t
11535 /
11536
11537Set the current process's real, effective, and saved user ids.
11538[clinic start generated code]*/
11539
Larry Hastings2f936352014-08-05 14:04:04 +100011540static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011541os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11542/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011543{
Victor Stinner8c62be82010-05-06 00:08:46 +000011544 if (setresuid(ruid, euid, suid) < 0)
11545 return posix_error();
11546 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011547}
Larry Hastings2f936352014-08-05 14:04:04 +100011548#endif /* HAVE_SETRESUID */
11549
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011550
11551#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011552/*[clinic input]
11553os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011554
Larry Hastings2f936352014-08-05 14:04:04 +100011555 rgid: gid_t
11556 egid: gid_t
11557 sgid: gid_t
11558 /
11559
11560Set the current process's real, effective, and saved group ids.
11561[clinic start generated code]*/
11562
Larry Hastings2f936352014-08-05 14:04:04 +100011563static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011564os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11565/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011566{
Victor Stinner8c62be82010-05-06 00:08:46 +000011567 if (setresgid(rgid, egid, sgid) < 0)
11568 return posix_error();
11569 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011570}
Larry Hastings2f936352014-08-05 14:04:04 +100011571#endif /* HAVE_SETRESGID */
11572
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011573
11574#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011575/*[clinic input]
11576os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011577
Larry Hastings2f936352014-08-05 14:04:04 +100011578Return a tuple of the current process's real, effective, and saved user ids.
11579[clinic start generated code]*/
11580
Larry Hastings2f936352014-08-05 14:04:04 +100011581static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011582os_getresuid_impl(PyObject *module)
11583/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011584{
Victor Stinner8c62be82010-05-06 00:08:46 +000011585 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011586 if (getresuid(&ruid, &euid, &suid) < 0)
11587 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011588 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11589 _PyLong_FromUid(euid),
11590 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011591}
Larry Hastings2f936352014-08-05 14:04:04 +100011592#endif /* HAVE_GETRESUID */
11593
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011594
11595#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011596/*[clinic input]
11597os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011598
Larry Hastings2f936352014-08-05 14:04:04 +100011599Return a tuple of the current process's real, effective, and saved group ids.
11600[clinic start generated code]*/
11601
Larry Hastings2f936352014-08-05 14:04:04 +100011602static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011603os_getresgid_impl(PyObject *module)
11604/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011605{
11606 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011607 if (getresgid(&rgid, &egid, &sgid) < 0)
11608 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011609 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11610 _PyLong_FromGid(egid),
11611 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011612}
Larry Hastings2f936352014-08-05 14:04:04 +100011613#endif /* HAVE_GETRESGID */
11614
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011615
Benjamin Peterson9428d532011-09-14 11:45:52 -040011616#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011617/*[clinic input]
11618os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011619
Larry Hastings2f936352014-08-05 14:04:04 +100011620 path: path_t(allow_fd=True)
11621 attribute: path_t
11622 *
11623 follow_symlinks: bool = True
11624
11625Return the value of extended attribute attribute on path.
11626
BNMetricsb9427072018-11-02 15:20:19 +000011627path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011628If follow_symlinks is False, and the last element of the path is a symbolic
11629 link, getxattr will examine the symbolic link itself instead of the file
11630 the link points to.
11631
11632[clinic start generated code]*/
11633
Larry Hastings2f936352014-08-05 14:04:04 +100011634static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011635os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011636 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011637/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011638{
11639 Py_ssize_t i;
11640 PyObject *buffer = NULL;
11641
11642 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11643 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011644
Larry Hastings9cf065c2012-06-22 16:30:09 -070011645 for (i = 0; ; i++) {
11646 void *ptr;
11647 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011648 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011649 Py_ssize_t buffer_size = buffer_sizes[i];
11650 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011651 path_error(path);
11652 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011653 }
11654 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11655 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011656 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011657 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011658
Larry Hastings9cf065c2012-06-22 16:30:09 -070011659 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011660 if (path->fd >= 0)
11661 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011662 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011663 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011664 else
Larry Hastings2f936352014-08-05 14:04:04 +100011665 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011666 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011667
Larry Hastings9cf065c2012-06-22 16:30:09 -070011668 if (result < 0) {
11669 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011670 if (errno == ERANGE)
11671 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011672 path_error(path);
11673 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011674 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011675
Larry Hastings9cf065c2012-06-22 16:30:09 -070011676 if (result != buffer_size) {
11677 /* Can only shrink. */
11678 _PyBytes_Resize(&buffer, result);
11679 }
11680 break;
11681 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011682
Larry Hastings9cf065c2012-06-22 16:30:09 -070011683 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011684}
11685
Larry Hastings2f936352014-08-05 14:04:04 +100011686
11687/*[clinic input]
11688os.setxattr
11689
11690 path: path_t(allow_fd=True)
11691 attribute: path_t
11692 value: Py_buffer
11693 flags: int = 0
11694 *
11695 follow_symlinks: bool = True
11696
11697Set extended attribute attribute on path to value.
11698
BNMetricsb9427072018-11-02 15:20:19 +000011699path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011700If follow_symlinks is False, and the last element of the path is a symbolic
11701 link, setxattr will modify the symbolic link itself instead of the file
11702 the link points to.
11703
11704[clinic start generated code]*/
11705
Benjamin Peterson799bd802011-08-31 22:15:17 -040011706static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011707os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011708 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011709/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011710{
Larry Hastings2f936352014-08-05 14:04:04 +100011711 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011712
Larry Hastings2f936352014-08-05 14:04:04 +100011713 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011714 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011715
Benjamin Peterson799bd802011-08-31 22:15:17 -040011716 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011717 if (path->fd > -1)
11718 result = fsetxattr(path->fd, attribute->narrow,
11719 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011720 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011721 result = setxattr(path->narrow, attribute->narrow,
11722 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011723 else
Larry Hastings2f936352014-08-05 14:04:04 +100011724 result = lsetxattr(path->narrow, attribute->narrow,
11725 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011726 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011727
Larry Hastings9cf065c2012-06-22 16:30:09 -070011728 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100011729 path_error(path);
11730 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011731 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011732
Larry Hastings2f936352014-08-05 14:04:04 +100011733 Py_RETURN_NONE;
11734}
11735
11736
11737/*[clinic input]
11738os.removexattr
11739
11740 path: path_t(allow_fd=True)
11741 attribute: path_t
11742 *
11743 follow_symlinks: bool = True
11744
11745Remove extended attribute attribute on path.
11746
BNMetricsb9427072018-11-02 15:20:19 +000011747path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011748If follow_symlinks is False, and the last element of the path is a symbolic
11749 link, removexattr will modify the symbolic link itself instead of the file
11750 the link points to.
11751
11752[clinic start generated code]*/
11753
Larry Hastings2f936352014-08-05 14:04:04 +100011754static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011755os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011756 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011757/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011758{
11759 ssize_t result;
11760
11761 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
11762 return NULL;
11763
11764 Py_BEGIN_ALLOW_THREADS;
11765 if (path->fd > -1)
11766 result = fremovexattr(path->fd, attribute->narrow);
11767 else if (follow_symlinks)
11768 result = removexattr(path->narrow, attribute->narrow);
11769 else
11770 result = lremovexattr(path->narrow, attribute->narrow);
11771 Py_END_ALLOW_THREADS;
11772
11773 if (result) {
11774 return path_error(path);
11775 }
11776
11777 Py_RETURN_NONE;
11778}
11779
11780
11781/*[clinic input]
11782os.listxattr
11783
11784 path: path_t(allow_fd=True, nullable=True) = None
11785 *
11786 follow_symlinks: bool = True
11787
11788Return a list of extended attributes on path.
11789
BNMetricsb9427072018-11-02 15:20:19 +000011790path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011791if path is None, listxattr will examine the current directory.
11792If follow_symlinks is False, and the last element of the path is a symbolic
11793 link, listxattr will examine the symbolic link itself instead of the file
11794 the link points to.
11795[clinic start generated code]*/
11796
Larry Hastings2f936352014-08-05 14:04:04 +100011797static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011798os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011799/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011800{
Larry Hastings9cf065c2012-06-22 16:30:09 -070011801 Py_ssize_t i;
11802 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100011803 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011804 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011805
Larry Hastings2f936352014-08-05 14:04:04 +100011806 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070011807 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011808
Larry Hastings2f936352014-08-05 14:04:04 +100011809 name = path->narrow ? path->narrow : ".";
11810
Larry Hastings9cf065c2012-06-22 16:30:09 -070011811 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011812 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011813 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011814 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070011815 Py_ssize_t buffer_size = buffer_sizes[i];
11816 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020011817 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100011818 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011819 break;
11820 }
11821 buffer = PyMem_MALLOC(buffer_size);
11822 if (!buffer) {
11823 PyErr_NoMemory();
11824 break;
11825 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011826
Larry Hastings9cf065c2012-06-22 16:30:09 -070011827 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011828 if (path->fd > -1)
11829 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011830 else if (follow_symlinks)
11831 length = listxattr(name, buffer, buffer_size);
11832 else
11833 length = llistxattr(name, buffer, buffer_size);
11834 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011835
Larry Hastings9cf065c2012-06-22 16:30:09 -070011836 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020011837 if (errno == ERANGE) {
11838 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050011839 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011840 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020011841 }
Larry Hastings2f936352014-08-05 14:04:04 +100011842 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011843 break;
11844 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011845
Larry Hastings9cf065c2012-06-22 16:30:09 -070011846 result = PyList_New(0);
11847 if (!result) {
11848 goto exit;
11849 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011850
Larry Hastings9cf065c2012-06-22 16:30:09 -070011851 end = buffer + length;
11852 for (trace = start = buffer; trace != end; trace++) {
11853 if (!*trace) {
11854 int error;
11855 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
11856 trace - start);
11857 if (!attribute) {
11858 Py_DECREF(result);
11859 result = NULL;
11860 goto exit;
11861 }
11862 error = PyList_Append(result, attribute);
11863 Py_DECREF(attribute);
11864 if (error) {
11865 Py_DECREF(result);
11866 result = NULL;
11867 goto exit;
11868 }
11869 start = trace + 1;
11870 }
11871 }
11872 break;
11873 }
11874exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070011875 if (buffer)
11876 PyMem_FREE(buffer);
11877 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011878}
Benjamin Peterson9428d532011-09-14 11:45:52 -040011879#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040011880
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011881
Larry Hastings2f936352014-08-05 14:04:04 +100011882/*[clinic input]
11883os.urandom
11884
11885 size: Py_ssize_t
11886 /
11887
11888Return a bytes object containing random bytes suitable for cryptographic use.
11889[clinic start generated code]*/
11890
Larry Hastings2f936352014-08-05 14:04:04 +100011891static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011892os_urandom_impl(PyObject *module, Py_ssize_t size)
11893/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011894{
11895 PyObject *bytes;
11896 int result;
11897
Georg Brandl2fb477c2012-02-21 00:33:36 +010011898 if (size < 0)
11899 return PyErr_Format(PyExc_ValueError,
11900 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100011901 bytes = PyBytes_FromStringAndSize(NULL, size);
11902 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010011903 return NULL;
11904
Victor Stinnere66987e2016-09-06 16:33:52 -070011905 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100011906 if (result == -1) {
11907 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010011908 return NULL;
11909 }
Larry Hastings2f936352014-08-05 14:04:04 +100011910 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010011911}
11912
Zackery Spytz43fdbd22019-05-29 13:57:07 -060011913#ifdef HAVE_MEMFD_CREATE
11914/*[clinic input]
11915os.memfd_create
11916
11917 name: FSConverter
11918 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
11919
11920[clinic start generated code]*/
11921
11922static PyObject *
11923os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
11924/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
11925{
11926 int fd;
11927 const char *bytes = PyBytes_AS_STRING(name);
11928 Py_BEGIN_ALLOW_THREADS
11929 fd = memfd_create(bytes, flags);
11930 Py_END_ALLOW_THREADS
11931 if (fd == -1) {
11932 return PyErr_SetFromErrno(PyExc_OSError);
11933 }
11934 return PyLong_FromLong(fd);
11935}
11936#endif
11937
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011938/* Terminal size querying */
11939
Eddie Elizondo474eedf2018-11-13 04:09:31 -080011940static PyTypeObject* TerminalSizeType;
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011941
11942PyDoc_STRVAR(TerminalSize_docstring,
11943 "A tuple of (columns, lines) for holding terminal window size");
11944
11945static PyStructSequence_Field TerminalSize_fields[] = {
11946 {"columns", "width of the terminal window in characters"},
11947 {"lines", "height of the terminal window in characters"},
11948 {NULL, NULL}
11949};
11950
11951static PyStructSequence_Desc TerminalSize_desc = {
11952 "os.terminal_size",
11953 TerminalSize_docstring,
11954 TerminalSize_fields,
11955 2,
11956};
11957
11958#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100011959/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011960PyDoc_STRVAR(termsize__doc__,
11961 "Return the size of the terminal window as (columns, lines).\n" \
11962 "\n" \
11963 "The optional argument fd (default standard output) specifies\n" \
11964 "which file descriptor should be queried.\n" \
11965 "\n" \
11966 "If the file descriptor is not connected to a terminal, an OSError\n" \
11967 "is thrown.\n" \
11968 "\n" \
11969 "This function will only be defined if an implementation is\n" \
11970 "available for this system.\n" \
11971 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080011972 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011973 "normally be used, os.get_terminal_size is the low-level implementation.");
11974
11975static PyObject*
11976get_terminal_size(PyObject *self, PyObject *args)
11977{
11978 int columns, lines;
11979 PyObject *termsize;
11980
11981 int fd = fileno(stdout);
11982 /* Under some conditions stdout may not be connected and
11983 * fileno(stdout) may point to an invalid file descriptor. For example
11984 * GUI apps don't have valid standard streams by default.
11985 *
11986 * If this happens, and the optional fd argument is not present,
11987 * the ioctl below will fail returning EBADF. This is what we want.
11988 */
11989
11990 if (!PyArg_ParseTuple(args, "|i", &fd))
11991 return NULL;
11992
11993#ifdef TERMSIZE_USE_IOCTL
11994 {
11995 struct winsize w;
11996 if (ioctl(fd, TIOCGWINSZ, &w))
11997 return PyErr_SetFromErrno(PyExc_OSError);
11998 columns = w.ws_col;
11999 lines = w.ws_row;
12000 }
12001#endif /* TERMSIZE_USE_IOCTL */
12002
12003#ifdef TERMSIZE_USE_CONIO
12004 {
12005 DWORD nhandle;
12006 HANDLE handle;
12007 CONSOLE_SCREEN_BUFFER_INFO csbi;
12008 switch (fd) {
12009 case 0: nhandle = STD_INPUT_HANDLE;
12010 break;
12011 case 1: nhandle = STD_OUTPUT_HANDLE;
12012 break;
12013 case 2: nhandle = STD_ERROR_HANDLE;
12014 break;
12015 default:
12016 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12017 }
12018 handle = GetStdHandle(nhandle);
12019 if (handle == NULL)
12020 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12021 if (handle == INVALID_HANDLE_VALUE)
12022 return PyErr_SetFromWindowsErr(0);
12023
12024 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12025 return PyErr_SetFromWindowsErr(0);
12026
12027 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12028 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12029 }
12030#endif /* TERMSIZE_USE_CONIO */
12031
Eddie Elizondo474eedf2018-11-13 04:09:31 -080012032 termsize = PyStructSequence_New(TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012033 if (termsize == NULL)
12034 return NULL;
12035 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12036 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12037 if (PyErr_Occurred()) {
12038 Py_DECREF(termsize);
12039 return NULL;
12040 }
12041 return termsize;
12042}
12043#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12044
Larry Hastings2f936352014-08-05 14:04:04 +100012045
12046/*[clinic input]
12047os.cpu_count
12048
Charles-François Natali80d62e62015-08-13 20:37:08 +010012049Return the number of CPUs in the system; return None if indeterminable.
12050
12051This number is not equivalent to the number of CPUs the current process can
12052use. The number of usable CPUs can be obtained with
12053``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012054[clinic start generated code]*/
12055
Larry Hastings2f936352014-08-05 14:04:04 +100012056static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012057os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012058/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012059{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012060 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012061#ifdef MS_WINDOWS
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012062 /* Vista is supported and the GetMaximumProcessorCount API is Win7+
12063 Need to fallback to Vista behavior if this call isn't present */
12064 HINSTANCE hKernel32;
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012065 static DWORD(CALLBACK *_GetMaximumProcessorCount)(WORD) = NULL;
Tony Roberts4860f012019-02-02 18:16:42 +010012066 Py_BEGIN_ALLOW_THREADS
12067 hKernel32 = GetModuleHandleW(L"KERNEL32");
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012068 *(FARPROC*)&_GetMaximumProcessorCount = GetProcAddress(hKernel32,
12069 "GetMaximumProcessorCount");
Tony Roberts4860f012019-02-02 18:16:42 +010012070 Py_END_ALLOW_THREADS
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012071 if (_GetMaximumProcessorCount != NULL) {
12072 ncpu = _GetMaximumProcessorCount(ALL_PROCESSOR_GROUPS);
12073 }
12074 else {
12075 SYSTEM_INFO sysinfo;
12076 GetSystemInfo(&sysinfo);
12077 ncpu = sysinfo.dwNumberOfProcessors;
12078 }
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012079#elif defined(__hpux)
12080 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12081#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12082 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012083#elif defined(__DragonFly__) || \
12084 defined(__OpenBSD__) || \
12085 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012086 defined(__NetBSD__) || \
12087 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012088 int mib[2];
12089 size_t len = sizeof(ncpu);
12090 mib[0] = CTL_HW;
12091 mib[1] = HW_NCPU;
12092 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12093 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012094#endif
12095 if (ncpu >= 1)
12096 return PyLong_FromLong(ncpu);
12097 else
12098 Py_RETURN_NONE;
12099}
12100
Victor Stinnerdaf45552013-08-28 00:53:59 +020012101
Larry Hastings2f936352014-08-05 14:04:04 +100012102/*[clinic input]
12103os.get_inheritable -> bool
12104
12105 fd: int
12106 /
12107
12108Get the close-on-exe flag of the specified file descriptor.
12109[clinic start generated code]*/
12110
Larry Hastings2f936352014-08-05 14:04:04 +100012111static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012112os_get_inheritable_impl(PyObject *module, int fd)
12113/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012114{
Steve Dower8fc89802015-04-12 00:26:27 -040012115 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012116 _Py_BEGIN_SUPPRESS_IPH
12117 return_value = _Py_get_inheritable(fd);
12118 _Py_END_SUPPRESS_IPH
12119 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012120}
12121
12122
12123/*[clinic input]
12124os.set_inheritable
12125 fd: int
12126 inheritable: int
12127 /
12128
12129Set the inheritable flag of the specified file descriptor.
12130[clinic start generated code]*/
12131
Larry Hastings2f936352014-08-05 14:04:04 +100012132static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012133os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12134/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012135{
Steve Dower8fc89802015-04-12 00:26:27 -040012136 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012137
Steve Dower8fc89802015-04-12 00:26:27 -040012138 _Py_BEGIN_SUPPRESS_IPH
12139 result = _Py_set_inheritable(fd, inheritable, NULL);
12140 _Py_END_SUPPRESS_IPH
12141 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012142 return NULL;
12143 Py_RETURN_NONE;
12144}
12145
12146
12147#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012148/*[clinic input]
12149os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012150 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012151 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012152
Larry Hastings2f936352014-08-05 14:04:04 +100012153Get the close-on-exe flag of the specified file descriptor.
12154[clinic start generated code]*/
12155
Larry Hastings2f936352014-08-05 14:04:04 +100012156static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012157os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012158/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012159{
12160 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012161
12162 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12163 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012164 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012165 }
12166
Larry Hastings2f936352014-08-05 14:04:04 +100012167 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012168}
12169
Victor Stinnerdaf45552013-08-28 00:53:59 +020012170
Larry Hastings2f936352014-08-05 14:04:04 +100012171/*[clinic input]
12172os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012173 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012174 inheritable: bool
12175 /
12176
12177Set the inheritable flag of the specified handle.
12178[clinic start generated code]*/
12179
Larry Hastings2f936352014-08-05 14:04:04 +100012180static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012181os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012182 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012183/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012184{
12185 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012186 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12187 PyErr_SetFromWindowsErr(0);
12188 return NULL;
12189 }
12190 Py_RETURN_NONE;
12191}
Larry Hastings2f936352014-08-05 14:04:04 +100012192#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012193
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012194#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012195/*[clinic input]
12196os.get_blocking -> bool
12197 fd: int
12198 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012199
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012200Get the blocking mode of the file descriptor.
12201
12202Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12203[clinic start generated code]*/
12204
12205static int
12206os_get_blocking_impl(PyObject *module, int fd)
12207/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012208{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012209 int blocking;
12210
Steve Dower8fc89802015-04-12 00:26:27 -040012211 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012212 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012213 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012214 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012215}
12216
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012217/*[clinic input]
12218os.set_blocking
12219 fd: int
12220 blocking: bool(accept={int})
12221 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012222
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012223Set the blocking mode of the specified file descriptor.
12224
12225Set the O_NONBLOCK flag if blocking is False,
12226clear the O_NONBLOCK flag otherwise.
12227[clinic start generated code]*/
12228
12229static PyObject *
12230os_set_blocking_impl(PyObject *module, int fd, int blocking)
12231/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012232{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012233 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012234
Steve Dower8fc89802015-04-12 00:26:27 -040012235 _Py_BEGIN_SUPPRESS_IPH
12236 result = _Py_set_blocking(fd, blocking);
12237 _Py_END_SUPPRESS_IPH
12238 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012239 return NULL;
12240 Py_RETURN_NONE;
12241}
12242#endif /* !MS_WINDOWS */
12243
12244
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012245/*[clinic input]
12246class os.DirEntry "DirEntry *" "&DirEntryType"
12247[clinic start generated code]*/
12248/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3138f09f7c683f1d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012249
12250typedef struct {
12251 PyObject_HEAD
12252 PyObject *name;
12253 PyObject *path;
12254 PyObject *stat;
12255 PyObject *lstat;
12256#ifdef MS_WINDOWS
12257 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012258 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012259 int got_file_index;
12260#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012261#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012262 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012263#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012264 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012265 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012266#endif
12267} DirEntry;
12268
12269static void
12270DirEntry_dealloc(DirEntry *entry)
12271{
12272 Py_XDECREF(entry->name);
12273 Py_XDECREF(entry->path);
12274 Py_XDECREF(entry->stat);
12275 Py_XDECREF(entry->lstat);
12276 Py_TYPE(entry)->tp_free((PyObject *)entry);
12277}
12278
12279/* Forward reference */
12280static int
12281DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12282
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012283/*[clinic input]
12284os.DirEntry.is_symlink -> bool
12285
12286Return True if the entry is a symbolic link; cached per entry.
12287[clinic start generated code]*/
12288
Victor Stinner6036e442015-03-08 01:58:04 +010012289static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012290os_DirEntry_is_symlink_impl(DirEntry *self)
12291/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012292{
12293#ifdef MS_WINDOWS
12294 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012295#elif defined(HAVE_DIRENT_D_TYPE)
12296 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012297 if (self->d_type != DT_UNKNOWN)
12298 return self->d_type == DT_LNK;
12299 else
12300 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012301#else
12302 /* POSIX without d_type */
12303 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012304#endif
12305}
12306
12307static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012308DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12309{
12310 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012311 STRUCT_STAT st;
12312 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012313
12314#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012315 if (!PyUnicode_FSDecoder(self->path, &ub))
12316 return NULL;
12317 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012318#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012319 if (!PyUnicode_FSConverter(self->path, &ub))
12320 return NULL;
12321 const char *path = PyBytes_AS_STRING(ub);
12322 if (self->dir_fd != DEFAULT_DIR_FD) {
12323#ifdef HAVE_FSTATAT
12324 result = fstatat(self->dir_fd, path, &st,
12325 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12326#else
12327 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12328 return NULL;
12329#endif /* HAVE_FSTATAT */
12330 }
12331 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012332#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012333 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012334 if (follow_symlinks)
12335 result = STAT(path, &st);
12336 else
12337 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012338 }
12339 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012340
12341 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012342 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012343
12344 return _pystat_fromstructstat(&st);
12345}
12346
12347static PyObject *
12348DirEntry_get_lstat(DirEntry *self)
12349{
12350 if (!self->lstat) {
12351#ifdef MS_WINDOWS
12352 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12353#else /* POSIX */
12354 self->lstat = DirEntry_fetch_stat(self, 0);
12355#endif
12356 }
12357 Py_XINCREF(self->lstat);
12358 return self->lstat;
12359}
12360
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012361/*[clinic input]
12362os.DirEntry.stat
12363 *
12364 follow_symlinks: bool = True
12365
12366Return stat_result object for the entry; cached per entry.
12367[clinic start generated code]*/
12368
Victor Stinner6036e442015-03-08 01:58:04 +010012369static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012370os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12371/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012372{
12373 if (!follow_symlinks)
12374 return DirEntry_get_lstat(self);
12375
12376 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012377 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012378 if (result == -1)
12379 return NULL;
12380 else if (result)
12381 self->stat = DirEntry_fetch_stat(self, 1);
12382 else
12383 self->stat = DirEntry_get_lstat(self);
12384 }
12385
12386 Py_XINCREF(self->stat);
12387 return self->stat;
12388}
12389
Victor Stinner6036e442015-03-08 01:58:04 +010012390/* Set exception and return -1 on error, 0 for False, 1 for True */
12391static int
12392DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12393{
12394 PyObject *stat = NULL;
12395 PyObject *st_mode = NULL;
12396 long mode;
12397 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012398#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012399 int is_symlink;
12400 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012401#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012402#ifdef MS_WINDOWS
12403 unsigned long dir_bits;
12404#endif
Victor Stinner35a97c02015-03-08 02:59:09 +010012405 _Py_IDENTIFIER(st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012406
12407#ifdef MS_WINDOWS
12408 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12409 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012410#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012411 is_symlink = self->d_type == DT_LNK;
12412 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12413#endif
12414
Victor Stinner35a97c02015-03-08 02:59:09 +010012415#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012416 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012417#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012418 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012419 if (!stat) {
12420 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12421 /* If file doesn't exist (anymore), then return False
12422 (i.e., say it's not a file/directory) */
12423 PyErr_Clear();
12424 return 0;
12425 }
12426 goto error;
12427 }
12428 st_mode = _PyObject_GetAttrId(stat, &PyId_st_mode);
12429 if (!st_mode)
12430 goto error;
12431
12432 mode = PyLong_AsLong(st_mode);
12433 if (mode == -1 && PyErr_Occurred())
12434 goto error;
12435 Py_CLEAR(st_mode);
12436 Py_CLEAR(stat);
12437 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012438#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012439 }
12440 else if (is_symlink) {
12441 assert(mode_bits != S_IFLNK);
12442 result = 0;
12443 }
12444 else {
12445 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12446#ifdef MS_WINDOWS
12447 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12448 if (mode_bits == S_IFDIR)
12449 result = dir_bits != 0;
12450 else
12451 result = dir_bits == 0;
12452#else /* POSIX */
12453 if (mode_bits == S_IFDIR)
12454 result = self->d_type == DT_DIR;
12455 else
12456 result = self->d_type == DT_REG;
12457#endif
12458 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012459#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012460
12461 return result;
12462
12463error:
12464 Py_XDECREF(st_mode);
12465 Py_XDECREF(stat);
12466 return -1;
12467}
12468
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012469/*[clinic input]
12470os.DirEntry.is_dir -> bool
12471 *
12472 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012473
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012474Return True if the entry is a directory; cached per entry.
12475[clinic start generated code]*/
12476
12477static int
12478os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12479/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12480{
12481 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012482}
12483
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012484/*[clinic input]
12485os.DirEntry.is_file -> bool
12486 *
12487 follow_symlinks: bool = True
12488
12489Return True if the entry is a file; cached per entry.
12490[clinic start generated code]*/
12491
12492static int
12493os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12494/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012495{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012496 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012497}
12498
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012499/*[clinic input]
12500os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012501
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012502Return inode of the entry; cached per entry.
12503[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012504
12505static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012506os_DirEntry_inode_impl(DirEntry *self)
12507/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012508{
12509#ifdef MS_WINDOWS
12510 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012511 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012512 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012513 STRUCT_STAT stat;
12514 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012515
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012516 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012517 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012518 path = PyUnicode_AsUnicode(unicode);
12519 result = LSTAT(path, &stat);
12520 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012521
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012522 if (result != 0)
12523 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012524
12525 self->win32_file_index = stat.st_ino;
12526 self->got_file_index = 1;
12527 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012528 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12529 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012530#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012531 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12532 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012533#endif
12534}
12535
12536static PyObject *
12537DirEntry_repr(DirEntry *self)
12538{
12539 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12540}
12541
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012542/*[clinic input]
12543os.DirEntry.__fspath__
12544
12545Returns the path for the entry.
12546[clinic start generated code]*/
12547
Brett Cannon96881cd2016-06-10 14:37:21 -070012548static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012549os_DirEntry___fspath___impl(DirEntry *self)
12550/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012551{
12552 Py_INCREF(self->path);
12553 return self->path;
12554}
12555
Victor Stinner6036e442015-03-08 01:58:04 +010012556static PyMemberDef DirEntry_members[] = {
12557 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12558 "the entry's base filename, relative to scandir() \"path\" argument"},
12559 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12560 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12561 {NULL}
12562};
12563
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012564#include "clinic/posixmodule.c.h"
12565
Victor Stinner6036e442015-03-08 01:58:04 +010012566static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012567 OS_DIRENTRY_IS_DIR_METHODDEF
12568 OS_DIRENTRY_IS_FILE_METHODDEF
12569 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12570 OS_DIRENTRY_STAT_METHODDEF
12571 OS_DIRENTRY_INODE_METHODDEF
12572 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012573 {NULL}
12574};
12575
Benjamin Peterson5646de42015-04-12 17:56:34 -040012576static PyTypeObject DirEntryType = {
Victor Stinner6036e442015-03-08 01:58:04 +010012577 PyVarObject_HEAD_INIT(NULL, 0)
12578 MODNAME ".DirEntry", /* tp_name */
12579 sizeof(DirEntry), /* tp_basicsize */
12580 0, /* tp_itemsize */
12581 /* methods */
12582 (destructor)DirEntry_dealloc, /* tp_dealloc */
12583 0, /* tp_print */
12584 0, /* tp_getattr */
12585 0, /* tp_setattr */
12586 0, /* tp_compare */
12587 (reprfunc)DirEntry_repr, /* tp_repr */
12588 0, /* tp_as_number */
12589 0, /* tp_as_sequence */
12590 0, /* tp_as_mapping */
12591 0, /* tp_hash */
12592 0, /* tp_call */
12593 0, /* tp_str */
12594 0, /* tp_getattro */
12595 0, /* tp_setattro */
12596 0, /* tp_as_buffer */
12597 Py_TPFLAGS_DEFAULT, /* tp_flags */
12598 0, /* tp_doc */
12599 0, /* tp_traverse */
12600 0, /* tp_clear */
12601 0, /* tp_richcompare */
12602 0, /* tp_weaklistoffset */
12603 0, /* tp_iter */
12604 0, /* tp_iternext */
12605 DirEntry_methods, /* tp_methods */
12606 DirEntry_members, /* tp_members */
12607};
12608
12609#ifdef MS_WINDOWS
12610
12611static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012612join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012613{
12614 Py_ssize_t path_len;
12615 Py_ssize_t size;
12616 wchar_t *result;
12617 wchar_t ch;
12618
12619 if (!path_wide) { /* Default arg: "." */
12620 path_wide = L".";
12621 path_len = 1;
12622 }
12623 else {
12624 path_len = wcslen(path_wide);
12625 }
12626
12627 /* The +1's are for the path separator and the NUL */
12628 size = path_len + 1 + wcslen(filename) + 1;
12629 result = PyMem_New(wchar_t, size);
12630 if (!result) {
12631 PyErr_NoMemory();
12632 return NULL;
12633 }
12634 wcscpy(result, path_wide);
12635 if (path_len > 0) {
12636 ch = result[path_len - 1];
12637 if (ch != SEP && ch != ALTSEP && ch != L':')
12638 result[path_len++] = SEP;
12639 wcscpy(result + path_len, filename);
12640 }
12641 return result;
12642}
12643
12644static PyObject *
12645DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12646{
12647 DirEntry *entry;
12648 BY_HANDLE_FILE_INFORMATION file_info;
12649 ULONG reparse_tag;
12650 wchar_t *joined_path;
12651
12652 entry = PyObject_New(DirEntry, &DirEntryType);
12653 if (!entry)
12654 return NULL;
12655 entry->name = NULL;
12656 entry->path = NULL;
12657 entry->stat = NULL;
12658 entry->lstat = NULL;
12659 entry->got_file_index = 0;
12660
12661 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12662 if (!entry->name)
12663 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012664 if (path->narrow) {
12665 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12666 if (!entry->name)
12667 goto error;
12668 }
Victor Stinner6036e442015-03-08 01:58:04 +010012669
12670 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12671 if (!joined_path)
12672 goto error;
12673
12674 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12675 PyMem_Free(joined_path);
12676 if (!entry->path)
12677 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012678 if (path->narrow) {
12679 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12680 if (!entry->path)
12681 goto error;
12682 }
Victor Stinner6036e442015-03-08 01:58:04 +010012683
Steve Dowercc16be82016-09-08 10:35:16 -070012684 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012685 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12686
12687 return (PyObject *)entry;
12688
12689error:
12690 Py_DECREF(entry);
12691 return NULL;
12692}
12693
12694#else /* POSIX */
12695
12696static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012697join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012698{
12699 Py_ssize_t path_len;
12700 Py_ssize_t size;
12701 char *result;
12702
12703 if (!path_narrow) { /* Default arg: "." */
12704 path_narrow = ".";
12705 path_len = 1;
12706 }
12707 else {
12708 path_len = strlen(path_narrow);
12709 }
12710
12711 if (filename_len == -1)
12712 filename_len = strlen(filename);
12713
12714 /* The +1's are for the path separator and the NUL */
12715 size = path_len + 1 + filename_len + 1;
12716 result = PyMem_New(char, size);
12717 if (!result) {
12718 PyErr_NoMemory();
12719 return NULL;
12720 }
12721 strcpy(result, path_narrow);
12722 if (path_len > 0 && result[path_len - 1] != '/')
12723 result[path_len++] = '/';
12724 strcpy(result + path_len, filename);
12725 return result;
12726}
12727
12728static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012729DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012730 ino_t d_ino
12731#ifdef HAVE_DIRENT_D_TYPE
12732 , unsigned char d_type
12733#endif
12734 )
Victor Stinner6036e442015-03-08 01:58:04 +010012735{
12736 DirEntry *entry;
12737 char *joined_path;
12738
12739 entry = PyObject_New(DirEntry, &DirEntryType);
12740 if (!entry)
12741 return NULL;
12742 entry->name = NULL;
12743 entry->path = NULL;
12744 entry->stat = NULL;
12745 entry->lstat = NULL;
12746
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012747 if (path->fd != -1) {
12748 entry->dir_fd = path->fd;
12749 joined_path = NULL;
12750 }
12751 else {
12752 entry->dir_fd = DEFAULT_DIR_FD;
12753 joined_path = join_path_filename(path->narrow, name, name_len);
12754 if (!joined_path)
12755 goto error;
12756 }
Victor Stinner6036e442015-03-08 01:58:04 +010012757
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030012758 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010012759 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012760 if (joined_path)
12761 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012762 }
12763 else {
12764 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012765 if (joined_path)
12766 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012767 }
12768 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012769 if (!entry->name)
12770 goto error;
12771
12772 if (path->fd != -1) {
12773 entry->path = entry->name;
12774 Py_INCREF(entry->path);
12775 }
12776 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010012777 goto error;
12778
Victor Stinner35a97c02015-03-08 02:59:09 +010012779#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012780 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012781#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012782 entry->d_ino = d_ino;
12783
12784 return (PyObject *)entry;
12785
12786error:
12787 Py_XDECREF(entry);
12788 return NULL;
12789}
12790
12791#endif
12792
12793
12794typedef struct {
12795 PyObject_HEAD
12796 path_t path;
12797#ifdef MS_WINDOWS
12798 HANDLE handle;
12799 WIN32_FIND_DATAW file_data;
12800 int first_time;
12801#else /* POSIX */
12802 DIR *dirp;
12803#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012804#ifdef HAVE_FDOPENDIR
12805 int fd;
12806#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012807} ScandirIterator;
12808
12809#ifdef MS_WINDOWS
12810
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012811static int
12812ScandirIterator_is_closed(ScandirIterator *iterator)
12813{
12814 return iterator->handle == INVALID_HANDLE_VALUE;
12815}
12816
Victor Stinner6036e442015-03-08 01:58:04 +010012817static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012818ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010012819{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012820 HANDLE handle = iterator->handle;
12821
12822 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010012823 return;
12824
Victor Stinner6036e442015-03-08 01:58:04 +010012825 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012826 Py_BEGIN_ALLOW_THREADS
12827 FindClose(handle);
12828 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010012829}
12830
12831static PyObject *
12832ScandirIterator_iternext(ScandirIterator *iterator)
12833{
12834 WIN32_FIND_DATAW *file_data = &iterator->file_data;
12835 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012836 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012837
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012838 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012839 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010012840 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012841
12842 while (1) {
12843 if (!iterator->first_time) {
12844 Py_BEGIN_ALLOW_THREADS
12845 success = FindNextFileW(iterator->handle, file_data);
12846 Py_END_ALLOW_THREADS
12847 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012848 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010012849 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012850 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012851 break;
12852 }
12853 }
12854 iterator->first_time = 0;
12855
12856 /* Skip over . and .. */
12857 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012858 wcscmp(file_data->cFileName, L"..") != 0) {
12859 entry = DirEntry_from_find_data(&iterator->path, file_data);
12860 if (!entry)
12861 break;
12862 return entry;
12863 }
Victor Stinner6036e442015-03-08 01:58:04 +010012864
12865 /* Loop till we get a non-dot directory or finish iterating */
12866 }
12867
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012868 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012869 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010012870 return NULL;
12871}
12872
12873#else /* POSIX */
12874
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012875static int
12876ScandirIterator_is_closed(ScandirIterator *iterator)
12877{
12878 return !iterator->dirp;
12879}
12880
Victor Stinner6036e442015-03-08 01:58:04 +010012881static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012882ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010012883{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012884 DIR *dirp = iterator->dirp;
12885
12886 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010012887 return;
12888
Victor Stinner6036e442015-03-08 01:58:04 +010012889 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012890 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012891#ifdef HAVE_FDOPENDIR
12892 if (iterator->path.fd != -1)
12893 rewinddir(dirp);
12894#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012895 closedir(dirp);
12896 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010012897 return;
12898}
12899
12900static PyObject *
12901ScandirIterator_iternext(ScandirIterator *iterator)
12902{
12903 struct dirent *direntp;
12904 Py_ssize_t name_len;
12905 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012906 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012907
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012908 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012909 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010012910 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012911
12912 while (1) {
12913 errno = 0;
12914 Py_BEGIN_ALLOW_THREADS
12915 direntp = readdir(iterator->dirp);
12916 Py_END_ALLOW_THREADS
12917
12918 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012919 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010012920 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012921 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012922 break;
12923 }
12924
12925 /* Skip over . and .. */
12926 name_len = NAMLEN(direntp);
12927 is_dot = direntp->d_name[0] == '.' &&
12928 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
12929 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012930 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010012931 name_len, direntp->d_ino
12932#ifdef HAVE_DIRENT_D_TYPE
12933 , direntp->d_type
12934#endif
12935 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012936 if (!entry)
12937 break;
12938 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012939 }
12940
12941 /* Loop till we get a non-dot directory or finish iterating */
12942 }
12943
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012944 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012945 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010012946 return NULL;
12947}
12948
12949#endif
12950
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012951static PyObject *
12952ScandirIterator_close(ScandirIterator *self, PyObject *args)
12953{
12954 ScandirIterator_closedir(self);
12955 Py_RETURN_NONE;
12956}
12957
12958static PyObject *
12959ScandirIterator_enter(PyObject *self, PyObject *args)
12960{
12961 Py_INCREF(self);
12962 return self;
12963}
12964
12965static PyObject *
12966ScandirIterator_exit(ScandirIterator *self, PyObject *args)
12967{
12968 ScandirIterator_closedir(self);
12969 Py_RETURN_NONE;
12970}
12971
Victor Stinner6036e442015-03-08 01:58:04 +010012972static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010012973ScandirIterator_finalize(ScandirIterator *iterator)
12974{
12975 PyObject *error_type, *error_value, *error_traceback;
12976
12977 /* Save the current exception, if any. */
12978 PyErr_Fetch(&error_type, &error_value, &error_traceback);
12979
12980 if (!ScandirIterator_is_closed(iterator)) {
12981 ScandirIterator_closedir(iterator);
12982
12983 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
12984 "unclosed scandir iterator %R", iterator)) {
12985 /* Spurious errors can appear at shutdown */
12986 if (PyErr_ExceptionMatches(PyExc_Warning)) {
12987 PyErr_WriteUnraisable((PyObject *) iterator);
12988 }
12989 }
12990 }
12991
Victor Stinner7bfa4092016-03-23 00:43:54 +010012992 path_cleanup(&iterator->path);
12993
12994 /* Restore the saved exception. */
12995 PyErr_Restore(error_type, error_value, error_traceback);
12996}
12997
12998static void
Victor Stinner6036e442015-03-08 01:58:04 +010012999ScandirIterator_dealloc(ScandirIterator *iterator)
13000{
Victor Stinner7bfa4092016-03-23 00:43:54 +010013001 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13002 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013003
Victor Stinner6036e442015-03-08 01:58:04 +010013004 Py_TYPE(iterator)->tp_free((PyObject *)iterator);
13005}
13006
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013007static PyMethodDef ScandirIterator_methods[] = {
13008 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13009 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13010 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13011 {NULL}
13012};
13013
Benjamin Peterson5646de42015-04-12 17:56:34 -040013014static PyTypeObject ScandirIteratorType = {
Victor Stinner6036e442015-03-08 01:58:04 +010013015 PyVarObject_HEAD_INIT(NULL, 0)
13016 MODNAME ".ScandirIterator", /* tp_name */
13017 sizeof(ScandirIterator), /* tp_basicsize */
13018 0, /* tp_itemsize */
13019 /* methods */
13020 (destructor)ScandirIterator_dealloc, /* tp_dealloc */
13021 0, /* tp_print */
13022 0, /* tp_getattr */
13023 0, /* tp_setattr */
13024 0, /* tp_compare */
13025 0, /* tp_repr */
13026 0, /* tp_as_number */
13027 0, /* tp_as_sequence */
13028 0, /* tp_as_mapping */
13029 0, /* tp_hash */
13030 0, /* tp_call */
13031 0, /* tp_str */
13032 0, /* tp_getattro */
13033 0, /* tp_setattro */
13034 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +020013035 Py_TPFLAGS_DEFAULT, /* tp_flags */
Victor Stinner6036e442015-03-08 01:58:04 +010013036 0, /* tp_doc */
13037 0, /* tp_traverse */
13038 0, /* tp_clear */
13039 0, /* tp_richcompare */
13040 0, /* tp_weaklistoffset */
13041 PyObject_SelfIter, /* tp_iter */
13042 (iternextfunc)ScandirIterator_iternext, /* tp_iternext */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013043 ScandirIterator_methods, /* tp_methods */
Victor Stinner7bfa4092016-03-23 00:43:54 +010013044 0, /* tp_members */
13045 0, /* tp_getset */
13046 0, /* tp_base */
13047 0, /* tp_dict */
13048 0, /* tp_descr_get */
13049 0, /* tp_descr_set */
13050 0, /* tp_dictoffset */
13051 0, /* tp_init */
13052 0, /* tp_alloc */
13053 0, /* tp_new */
13054 0, /* tp_free */
13055 0, /* tp_is_gc */
13056 0, /* tp_bases */
13057 0, /* tp_mro */
13058 0, /* tp_cache */
13059 0, /* tp_subclasses */
13060 0, /* tp_weaklist */
13061 0, /* tp_del */
13062 0, /* tp_version_tag */
13063 (destructor)ScandirIterator_finalize, /* tp_finalize */
Victor Stinner6036e442015-03-08 01:58:04 +010013064};
13065
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013066/*[clinic input]
13067os.scandir
13068
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013069 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013070
13071Return an iterator of DirEntry objects for given path.
13072
BNMetricsb9427072018-11-02 15:20:19 +000013073path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013074is bytes, the names of yielded DirEntry objects will also be bytes; in
13075all other circumstances they will be str.
13076
13077If path is None, uses the path='.'.
13078[clinic start generated code]*/
13079
Victor Stinner6036e442015-03-08 01:58:04 +010013080static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013081os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013082/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013083{
13084 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013085#ifdef MS_WINDOWS
13086 wchar_t *path_strW;
13087#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013088 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013089#ifdef HAVE_FDOPENDIR
13090 int fd = -1;
13091#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013092#endif
13093
13094 iterator = PyObject_New(ScandirIterator, &ScandirIteratorType);
13095 if (!iterator)
13096 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013097
13098#ifdef MS_WINDOWS
13099 iterator->handle = INVALID_HANDLE_VALUE;
13100#else
13101 iterator->dirp = NULL;
13102#endif
13103
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013104 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013105 /* Move the ownership to iterator->path */
13106 path->object = NULL;
13107 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013108
13109#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013110 iterator->first_time = 1;
13111
13112 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13113 if (!path_strW)
13114 goto error;
13115
13116 Py_BEGIN_ALLOW_THREADS
13117 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13118 Py_END_ALLOW_THREADS
13119
13120 PyMem_Free(path_strW);
13121
13122 if (iterator->handle == INVALID_HANDLE_VALUE) {
13123 path_error(&iterator->path);
13124 goto error;
13125 }
13126#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013127 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013128#ifdef HAVE_FDOPENDIR
13129 if (path->fd != -1) {
13130 /* closedir() closes the FD, so we duplicate it */
13131 fd = _Py_dup(path->fd);
13132 if (fd == -1)
13133 goto error;
13134
13135 Py_BEGIN_ALLOW_THREADS
13136 iterator->dirp = fdopendir(fd);
13137 Py_END_ALLOW_THREADS
13138 }
13139 else
13140#endif
13141 {
13142 if (iterator->path.narrow)
13143 path_str = iterator->path.narrow;
13144 else
13145 path_str = ".";
13146
13147 Py_BEGIN_ALLOW_THREADS
13148 iterator->dirp = opendir(path_str);
13149 Py_END_ALLOW_THREADS
13150 }
Victor Stinner6036e442015-03-08 01:58:04 +010013151
13152 if (!iterator->dirp) {
13153 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013154#ifdef HAVE_FDOPENDIR
13155 if (fd != -1) {
13156 Py_BEGIN_ALLOW_THREADS
13157 close(fd);
13158 Py_END_ALLOW_THREADS
13159 }
13160#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013161 goto error;
13162 }
13163#endif
13164
13165 return (PyObject *)iterator;
13166
13167error:
13168 Py_DECREF(iterator);
13169 return NULL;
13170}
13171
Ethan Furman410ef8e2016-06-04 12:06:26 -070013172/*
13173 Return the file system path representation of the object.
13174
13175 If the object is str or bytes, then allow it to pass through with
13176 an incremented refcount. If the object defines __fspath__(), then
13177 return the result of that method. All other types raise a TypeError.
13178*/
13179PyObject *
13180PyOS_FSPath(PyObject *path)
13181{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013182 /* For error message reasons, this function is manually inlined in
13183 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013184 _Py_IDENTIFIER(__fspath__);
13185 PyObject *func = NULL;
13186 PyObject *path_repr = NULL;
13187
13188 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13189 Py_INCREF(path);
13190 return path;
13191 }
13192
13193 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13194 if (NULL == func) {
13195 return PyErr_Format(PyExc_TypeError,
13196 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013197 "not %.200s",
13198 Py_TYPE(path)->tp_name);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013199 }
13200
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013201 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013202 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013203 if (NULL == path_repr) {
13204 return NULL;
13205 }
13206
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013207 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13208 PyErr_Format(PyExc_TypeError,
13209 "expected %.200s.__fspath__() to return str or bytes, "
13210 "not %.200s", Py_TYPE(path)->tp_name,
13211 Py_TYPE(path_repr)->tp_name);
13212 Py_DECREF(path_repr);
13213 return NULL;
13214 }
13215
Ethan Furman410ef8e2016-06-04 12:06:26 -070013216 return path_repr;
13217}
13218
13219/*[clinic input]
13220os.fspath
13221
13222 path: object
13223
13224Return the file system path representation of the object.
13225
Brett Cannonb4f43e92016-06-09 14:32:08 -070013226If the object is str or bytes, then allow it to pass through as-is. If the
13227object defines __fspath__(), then return the result of that method. All other
13228types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013229[clinic start generated code]*/
13230
13231static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013232os_fspath_impl(PyObject *module, PyObject *path)
13233/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013234{
13235 return PyOS_FSPath(path);
13236}
Victor Stinner6036e442015-03-08 01:58:04 +010013237
Victor Stinner9b1f4742016-09-06 16:18:52 -070013238#ifdef HAVE_GETRANDOM_SYSCALL
13239/*[clinic input]
13240os.getrandom
13241
13242 size: Py_ssize_t
13243 flags: int=0
13244
13245Obtain a series of random bytes.
13246[clinic start generated code]*/
13247
13248static PyObject *
13249os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13250/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13251{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013252 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013253 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013254
13255 if (size < 0) {
13256 errno = EINVAL;
13257 return posix_error();
13258 }
13259
Victor Stinnerec2319c2016-09-20 23:00:59 +020013260 bytes = PyBytes_FromStringAndSize(NULL, size);
13261 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013262 PyErr_NoMemory();
13263 return NULL;
13264 }
13265
13266 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013267 n = syscall(SYS_getrandom,
13268 PyBytes_AS_STRING(bytes),
13269 PyBytes_GET_SIZE(bytes),
13270 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013271 if (n < 0 && errno == EINTR) {
13272 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013273 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013274 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013275
13276 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013277 continue;
13278 }
13279 break;
13280 }
13281
13282 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013283 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013284 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013285 }
13286
Victor Stinnerec2319c2016-09-20 23:00:59 +020013287 if (n != size) {
13288 _PyBytes_Resize(&bytes, n);
13289 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013290
13291 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013292
13293error:
13294 Py_DECREF(bytes);
13295 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013296}
13297#endif /* HAVE_GETRANDOM_SYSCALL */
13298
Steve Dower2438cdf2019-03-29 16:37:16 -070013299#ifdef MS_WINDOWS
13300/* bpo-36085: Helper functions for managing DLL search directories
13301 * on win32
13302 */
13303
13304typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13305typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13306
13307/*[clinic input]
13308os._add_dll_directory
13309
13310 path: path_t
13311
13312Add a path to the DLL search path.
13313
13314This search path is used when resolving dependencies for imported
13315extension modules (the module itself is resolved through sys.path),
13316and also by ctypes.
13317
13318Returns an opaque value that may be passed to os.remove_dll_directory
13319to remove this directory from the search path.
13320[clinic start generated code]*/
13321
13322static PyObject *
13323os__add_dll_directory_impl(PyObject *module, path_t *path)
13324/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13325{
13326 HMODULE hKernel32;
13327 PAddDllDirectory AddDllDirectory;
13328 DLL_DIRECTORY_COOKIE cookie = 0;
13329 DWORD err = 0;
13330
13331 /* For Windows 7, we have to load this. As this will be a fairly
13332 infrequent operation, just do it each time. Kernel32 is always
13333 loaded. */
13334 Py_BEGIN_ALLOW_THREADS
13335 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13336 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13337 hKernel32, "AddDllDirectory")) ||
13338 !(cookie = (*AddDllDirectory)(path->wide))) {
13339 err = GetLastError();
13340 }
13341 Py_END_ALLOW_THREADS
13342
13343 if (err) {
13344 return win32_error_object_err("add_dll_directory",
13345 path->object, err);
13346 }
13347
13348 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13349}
13350
13351/*[clinic input]
13352os._remove_dll_directory
13353
13354 cookie: object
13355
13356Removes a path from the DLL search path.
13357
13358The parameter is an opaque value that was returned from
13359os.add_dll_directory. You can only remove directories that you added
13360yourself.
13361[clinic start generated code]*/
13362
13363static PyObject *
13364os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13365/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13366{
13367 HMODULE hKernel32;
13368 PRemoveDllDirectory RemoveDllDirectory;
13369 DLL_DIRECTORY_COOKIE cookieValue;
13370 DWORD err = 0;
13371
13372 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13373 PyErr_SetString(PyExc_TypeError,
13374 "Provided cookie was not returned from os.add_dll_directory");
13375 return NULL;
13376 }
13377
13378 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13379 cookie, "DLL directory cookie");
13380
13381 /* For Windows 7, we have to load this. As this will be a fairly
13382 infrequent operation, just do it each time. Kernel32 is always
13383 loaded. */
13384 Py_BEGIN_ALLOW_THREADS
13385 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13386 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13387 hKernel32, "RemoveDllDirectory")) ||
13388 !(*RemoveDllDirectory)(cookieValue)) {
13389 err = GetLastError();
13390 }
13391 Py_END_ALLOW_THREADS
13392
13393 if (err) {
13394 return win32_error_object_err("remove_dll_directory",
13395 NULL, err);
13396 }
13397
13398 if (PyCapsule_SetName(cookie, NULL)) {
13399 return NULL;
13400 }
13401
13402 Py_RETURN_NONE;
13403}
13404
13405#endif
Larry Hastings31826802013-10-19 00:09:25 -070013406
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013407static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013408
13409 OS_STAT_METHODDEF
13410 OS_ACCESS_METHODDEF
13411 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013412 OS_CHDIR_METHODDEF
13413 OS_CHFLAGS_METHODDEF
13414 OS_CHMOD_METHODDEF
13415 OS_FCHMOD_METHODDEF
13416 OS_LCHMOD_METHODDEF
13417 OS_CHOWN_METHODDEF
13418 OS_FCHOWN_METHODDEF
13419 OS_LCHOWN_METHODDEF
13420 OS_LCHFLAGS_METHODDEF
13421 OS_CHROOT_METHODDEF
13422 OS_CTERMID_METHODDEF
13423 OS_GETCWD_METHODDEF
13424 OS_GETCWDB_METHODDEF
13425 OS_LINK_METHODDEF
13426 OS_LISTDIR_METHODDEF
13427 OS_LSTAT_METHODDEF
13428 OS_MKDIR_METHODDEF
13429 OS_NICE_METHODDEF
13430 OS_GETPRIORITY_METHODDEF
13431 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013432 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013433 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013434 OS_READLINK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013435 OS_RENAME_METHODDEF
13436 OS_REPLACE_METHODDEF
13437 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013438 OS_SYMLINK_METHODDEF
13439 OS_SYSTEM_METHODDEF
13440 OS_UMASK_METHODDEF
13441 OS_UNAME_METHODDEF
13442 OS_UNLINK_METHODDEF
13443 OS_REMOVE_METHODDEF
13444 OS_UTIME_METHODDEF
13445 OS_TIMES_METHODDEF
13446 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013447 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013448 OS_EXECV_METHODDEF
13449 OS_EXECVE_METHODDEF
13450 OS_SPAWNV_METHODDEF
13451 OS_SPAWNVE_METHODDEF
13452 OS_FORK1_METHODDEF
13453 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013454 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013455 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13456 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13457 OS_SCHED_GETPARAM_METHODDEF
13458 OS_SCHED_GETSCHEDULER_METHODDEF
13459 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13460 OS_SCHED_SETPARAM_METHODDEF
13461 OS_SCHED_SETSCHEDULER_METHODDEF
13462 OS_SCHED_YIELD_METHODDEF
13463 OS_SCHED_SETAFFINITY_METHODDEF
13464 OS_SCHED_GETAFFINITY_METHODDEF
13465 OS_OPENPTY_METHODDEF
13466 OS_FORKPTY_METHODDEF
13467 OS_GETEGID_METHODDEF
13468 OS_GETEUID_METHODDEF
13469 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013470#ifdef HAVE_GETGROUPLIST
13471 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13472#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013473 OS_GETGROUPS_METHODDEF
13474 OS_GETPID_METHODDEF
13475 OS_GETPGRP_METHODDEF
13476 OS_GETPPID_METHODDEF
13477 OS_GETUID_METHODDEF
13478 OS_GETLOGIN_METHODDEF
13479 OS_KILL_METHODDEF
13480 OS_KILLPG_METHODDEF
13481 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013482#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013483 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013484#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013485 OS_SETUID_METHODDEF
13486 OS_SETEUID_METHODDEF
13487 OS_SETREUID_METHODDEF
13488 OS_SETGID_METHODDEF
13489 OS_SETEGID_METHODDEF
13490 OS_SETREGID_METHODDEF
13491 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013492#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013493 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013494#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013495 OS_GETPGID_METHODDEF
13496 OS_SETPGRP_METHODDEF
13497 OS_WAIT_METHODDEF
13498 OS_WAIT3_METHODDEF
13499 OS_WAIT4_METHODDEF
13500 OS_WAITID_METHODDEF
13501 OS_WAITPID_METHODDEF
13502 OS_GETSID_METHODDEF
13503 OS_SETSID_METHODDEF
13504 OS_SETPGID_METHODDEF
13505 OS_TCGETPGRP_METHODDEF
13506 OS_TCSETPGRP_METHODDEF
13507 OS_OPEN_METHODDEF
13508 OS_CLOSE_METHODDEF
13509 OS_CLOSERANGE_METHODDEF
13510 OS_DEVICE_ENCODING_METHODDEF
13511 OS_DUP_METHODDEF
13512 OS_DUP2_METHODDEF
13513 OS_LOCKF_METHODDEF
13514 OS_LSEEK_METHODDEF
13515 OS_READ_METHODDEF
13516 OS_READV_METHODDEF
13517 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013518 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013519 OS_WRITE_METHODDEF
13520 OS_WRITEV_METHODDEF
13521 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013522 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013523#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013524 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013525 posix_sendfile__doc__},
13526#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013527 OS_FSTAT_METHODDEF
13528 OS_ISATTY_METHODDEF
13529 OS_PIPE_METHODDEF
13530 OS_PIPE2_METHODDEF
13531 OS_MKFIFO_METHODDEF
13532 OS_MKNOD_METHODDEF
13533 OS_MAJOR_METHODDEF
13534 OS_MINOR_METHODDEF
13535 OS_MAKEDEV_METHODDEF
13536 OS_FTRUNCATE_METHODDEF
13537 OS_TRUNCATE_METHODDEF
13538 OS_POSIX_FALLOCATE_METHODDEF
13539 OS_POSIX_FADVISE_METHODDEF
13540 OS_PUTENV_METHODDEF
13541 OS_UNSETENV_METHODDEF
13542 OS_STRERROR_METHODDEF
13543 OS_FCHDIR_METHODDEF
13544 OS_FSYNC_METHODDEF
13545 OS_SYNC_METHODDEF
13546 OS_FDATASYNC_METHODDEF
13547 OS_WCOREDUMP_METHODDEF
13548 OS_WIFCONTINUED_METHODDEF
13549 OS_WIFSTOPPED_METHODDEF
13550 OS_WIFSIGNALED_METHODDEF
13551 OS_WIFEXITED_METHODDEF
13552 OS_WEXITSTATUS_METHODDEF
13553 OS_WTERMSIG_METHODDEF
13554 OS_WSTOPSIG_METHODDEF
13555 OS_FSTATVFS_METHODDEF
13556 OS_STATVFS_METHODDEF
13557 OS_CONFSTR_METHODDEF
13558 OS_SYSCONF_METHODDEF
13559 OS_FPATHCONF_METHODDEF
13560 OS_PATHCONF_METHODDEF
13561 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013562 OS__GETFULLPATHNAME_METHODDEF
13563 OS__ISDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013564 OS__GETDISKUSAGE_METHODDEF
13565 OS__GETFINALPATHNAME_METHODDEF
13566 OS__GETVOLUMEPATHNAME_METHODDEF
13567 OS_GETLOADAVG_METHODDEF
13568 OS_URANDOM_METHODDEF
13569 OS_SETRESUID_METHODDEF
13570 OS_SETRESGID_METHODDEF
13571 OS_GETRESUID_METHODDEF
13572 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013573
Larry Hastings2f936352014-08-05 14:04:04 +100013574 OS_GETXATTR_METHODDEF
13575 OS_SETXATTR_METHODDEF
13576 OS_REMOVEXATTR_METHODDEF
13577 OS_LISTXATTR_METHODDEF
13578
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013579#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13580 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13581#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013582 OS_CPU_COUNT_METHODDEF
13583 OS_GET_INHERITABLE_METHODDEF
13584 OS_SET_INHERITABLE_METHODDEF
13585 OS_GET_HANDLE_INHERITABLE_METHODDEF
13586 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013587#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013588 OS_GET_BLOCKING_METHODDEF
13589 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013590#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013591 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013592 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013593 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013594 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013595#ifdef MS_WINDOWS
13596 OS__ADD_DLL_DIRECTORY_METHODDEF
13597 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13598#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013599 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013600};
13601
Barry Warsaw4a342091996-12-19 23:50:02 +000013602static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013603all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013604{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013605#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013606 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013607#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013608#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013609 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013610#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013611#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013612 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013613#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013614#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013615 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013616#endif
Fred Drakec9680921999-12-13 16:37:25 +000013617#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013618 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013619#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013620#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013621 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013622#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013623#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013624 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013625#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013626#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013627 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013628#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013629#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013630 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013631#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013632#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013633 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013634#endif
13635#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013636 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013637#endif
13638#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013639 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013640#endif
13641#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013642 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013643#endif
13644#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013645 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013646#endif
13647#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013648 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013649#endif
13650#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013651 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013652#endif
13653#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013654 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013655#endif
13656#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013657 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013658#endif
13659#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013660 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013661#endif
13662#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013663 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013664#endif
13665#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013666 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013667#endif
13668#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013669 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013670#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013671#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013672 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013673#endif
13674#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013675 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013676#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013677#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013678 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013679#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013680#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013681 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013682#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013683#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013684#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013685 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013686#endif
13687#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013688 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013689#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013690#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013691#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013692 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013693#endif
13694#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013695 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013696#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013697#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013698 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013699#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013700#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013701 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013702#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013703#ifdef O_TMPFILE
13704 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13705#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013706#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013707 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013708#endif
13709#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013710 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013711#endif
13712#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013713 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013714#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013715#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013716 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013717#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013718#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013719 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013720#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013721
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013722
Jesus Cea94363612012-06-22 18:32:07 +020013723#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013724 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013725#endif
13726#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013727 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013728#endif
13729
Tim Peters5aa91602002-01-30 05:46:57 +000013730/* MS Windows */
13731#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013732 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013733 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013734#endif
13735#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013736 /* Optimize for short life (keep in memory). */
13737 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013738 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013739#endif
13740#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013741 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013742 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013743#endif
13744#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013745 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013746 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013747#endif
13748#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013749 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013750 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013751#endif
13752
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013753/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013754#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013755 /* Send a SIGIO signal whenever input or output
13756 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013757 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013758#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013759#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013760 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013761 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013762#endif
13763#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013764 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013765 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013766#endif
13767#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013768 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013769 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013770#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013771#ifdef O_NOLINKS
13772 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013773 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013774#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013775#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000013776 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013777 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013778#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000013779
Victor Stinner8c62be82010-05-06 00:08:46 +000013780 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013781#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013782 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013783#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013784#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013785 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013786#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013787#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013788 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013789#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013790#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013791 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013792#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013793#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013794 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013795#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013796#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013797 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013798#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013799#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013800 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013801#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013802#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013803 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013804#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013805#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013806 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013807#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013808#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013809 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013810#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013811#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013812 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013813#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013814#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013815 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013816#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013817#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013818 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013819#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013820#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013821 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013822#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013823#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013824 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013825#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013826#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013827 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013828#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013829#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013830 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013831#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013832
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000013833 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013834#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013835 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013836#endif /* ST_RDONLY */
13837#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013838 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013839#endif /* ST_NOSUID */
13840
doko@ubuntu.comca616a22013-12-08 15:23:07 +010013841 /* GNU extensions */
13842#ifdef ST_NODEV
13843 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
13844#endif /* ST_NODEV */
13845#ifdef ST_NOEXEC
13846 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
13847#endif /* ST_NOEXEC */
13848#ifdef ST_SYNCHRONOUS
13849 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
13850#endif /* ST_SYNCHRONOUS */
13851#ifdef ST_MANDLOCK
13852 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
13853#endif /* ST_MANDLOCK */
13854#ifdef ST_WRITE
13855 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
13856#endif /* ST_WRITE */
13857#ifdef ST_APPEND
13858 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
13859#endif /* ST_APPEND */
13860#ifdef ST_NOATIME
13861 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
13862#endif /* ST_NOATIME */
13863#ifdef ST_NODIRATIME
13864 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
13865#endif /* ST_NODIRATIME */
13866#ifdef ST_RELATIME
13867 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
13868#endif /* ST_RELATIME */
13869
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013870 /* FreeBSD sendfile() constants */
13871#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013872 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013873#endif
13874#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013875 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013876#endif
13877#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013878 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013879#endif
13880
Ross Lagerwall7807c352011-03-17 20:20:30 +020013881 /* constants for posix_fadvise */
13882#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013883 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013884#endif
13885#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013886 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013887#endif
13888#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013889 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013890#endif
13891#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013892 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013893#endif
13894#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013895 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013896#endif
13897#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013898 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013899#endif
13900
13901 /* constants for waitid */
13902#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013903 if (PyModule_AddIntMacro(m, P_PID)) return -1;
13904 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
13905 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013906#endif
13907#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013908 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013909#endif
13910#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013911 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013912#endif
13913#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013914 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013915#endif
13916#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013917 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013918#endif
13919#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013920 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013921#endif
13922#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013923 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013924#endif
13925#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013926 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013927#endif
13928
13929 /* constants for lockf */
13930#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013931 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013932#endif
13933#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013934 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013935#endif
13936#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013937 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013938#endif
13939#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013940 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013941#endif
13942
Pablo Galindo4defba32018-01-27 16:16:37 +000013943#ifdef RWF_DSYNC
13944 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
13945#endif
13946#ifdef RWF_HIPRI
13947 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
13948#endif
13949#ifdef RWF_SYNC
13950 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
13951#endif
13952#ifdef RWF_NOWAIT
13953 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
13954#endif
13955
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013956/* constants for posix_spawn */
13957#ifdef HAVE_POSIX_SPAWN
13958 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
13959 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
13960 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
13961#endif
13962
pxinwrf2d7ac72019-05-21 18:46:37 +080013963#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013964 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
13965 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013966 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080013967#endif
13968#ifdef HAVE_SPAWNV
13969 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013970 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000013971#endif
13972
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013973#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070013974#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013975 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070013976#endif
13977#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013978 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070013979#endif
13980#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013981 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070013982#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013983#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080013984 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013985#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013986#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013987 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013988#endif
13989#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013990 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013991#endif
13992#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013993 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050013994#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020013995#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013996 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020013997#endif
13998#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013999 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014000#endif
14001#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014002 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014003#endif
14004#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014005 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014006#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014007#endif
14008
Benjamin Peterson9428d532011-09-14 11:45:52 -040014009#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014010 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14011 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14012 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014013#endif
14014
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014015#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014016 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014017#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014018#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014019 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014020#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014021#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014022 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014023#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014024#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014025 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014026#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014027#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014028 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014029#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014030#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014031 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014032#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014033#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014034 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014035#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014036#if HAVE_DECL_RTLD_MEMBER
14037 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14038#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014039
Victor Stinner9b1f4742016-09-06 16:18:52 -070014040#ifdef HAVE_GETRANDOM_SYSCALL
14041 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14042 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14043#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014044#ifdef HAVE_MEMFD_CREATE
14045 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14046 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14047#ifdef MFD_HUGETLB
14048 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014049#endif
14050#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014051 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014052#endif
14053#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014054 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014055#endif
14056#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014057 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014058#endif
14059#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014060 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014061#endif
14062#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014063 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014064#endif
14065#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014066 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014067#endif
14068#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014069 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014070#endif
14071#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014072 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014073#endif
14074#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014075 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014076#endif
14077#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014078 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014079#endif
14080#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014081 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014082#endif
14083#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014084 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014085#endif
14086#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014087 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014088#endif
14089#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014090 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14091#endif
14092#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014093
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014094#if defined(__APPLE__)
14095 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14096#endif
14097
Steve Dower2438cdf2019-03-29 16:37:16 -070014098#ifdef MS_WINDOWS
14099 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14100 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14101 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14102 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14103 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14104#endif
14105
Victor Stinner8c62be82010-05-06 00:08:46 +000014106 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014107}
14108
14109
Martin v. Löwis1a214512008-06-11 05:26:20 +000014110static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014111 PyModuleDef_HEAD_INIT,
14112 MODNAME,
14113 posix__doc__,
14114 -1,
14115 posix_methods,
14116 NULL,
14117 NULL,
14118 NULL,
14119 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +000014120};
14121
14122
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014123static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014124
14125#ifdef HAVE_FACCESSAT
14126 "HAVE_FACCESSAT",
14127#endif
14128
14129#ifdef HAVE_FCHDIR
14130 "HAVE_FCHDIR",
14131#endif
14132
14133#ifdef HAVE_FCHMOD
14134 "HAVE_FCHMOD",
14135#endif
14136
14137#ifdef HAVE_FCHMODAT
14138 "HAVE_FCHMODAT",
14139#endif
14140
14141#ifdef HAVE_FCHOWN
14142 "HAVE_FCHOWN",
14143#endif
14144
Larry Hastings00964ed2013-08-12 13:49:30 -040014145#ifdef HAVE_FCHOWNAT
14146 "HAVE_FCHOWNAT",
14147#endif
14148
Larry Hastings9cf065c2012-06-22 16:30:09 -070014149#ifdef HAVE_FEXECVE
14150 "HAVE_FEXECVE",
14151#endif
14152
14153#ifdef HAVE_FDOPENDIR
14154 "HAVE_FDOPENDIR",
14155#endif
14156
Georg Brandl306336b2012-06-24 12:55:33 +020014157#ifdef HAVE_FPATHCONF
14158 "HAVE_FPATHCONF",
14159#endif
14160
Larry Hastings9cf065c2012-06-22 16:30:09 -070014161#ifdef HAVE_FSTATAT
14162 "HAVE_FSTATAT",
14163#endif
14164
14165#ifdef HAVE_FSTATVFS
14166 "HAVE_FSTATVFS",
14167#endif
14168
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014169#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014170 "HAVE_FTRUNCATE",
14171#endif
14172
Larry Hastings9cf065c2012-06-22 16:30:09 -070014173#ifdef HAVE_FUTIMENS
14174 "HAVE_FUTIMENS",
14175#endif
14176
14177#ifdef HAVE_FUTIMES
14178 "HAVE_FUTIMES",
14179#endif
14180
14181#ifdef HAVE_FUTIMESAT
14182 "HAVE_FUTIMESAT",
14183#endif
14184
14185#ifdef HAVE_LINKAT
14186 "HAVE_LINKAT",
14187#endif
14188
14189#ifdef HAVE_LCHFLAGS
14190 "HAVE_LCHFLAGS",
14191#endif
14192
14193#ifdef HAVE_LCHMOD
14194 "HAVE_LCHMOD",
14195#endif
14196
14197#ifdef HAVE_LCHOWN
14198 "HAVE_LCHOWN",
14199#endif
14200
14201#ifdef HAVE_LSTAT
14202 "HAVE_LSTAT",
14203#endif
14204
14205#ifdef HAVE_LUTIMES
14206 "HAVE_LUTIMES",
14207#endif
14208
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014209#ifdef HAVE_MEMFD_CREATE
14210 "HAVE_MEMFD_CREATE",
14211#endif
14212
Larry Hastings9cf065c2012-06-22 16:30:09 -070014213#ifdef HAVE_MKDIRAT
14214 "HAVE_MKDIRAT",
14215#endif
14216
14217#ifdef HAVE_MKFIFOAT
14218 "HAVE_MKFIFOAT",
14219#endif
14220
14221#ifdef HAVE_MKNODAT
14222 "HAVE_MKNODAT",
14223#endif
14224
14225#ifdef HAVE_OPENAT
14226 "HAVE_OPENAT",
14227#endif
14228
14229#ifdef HAVE_READLINKAT
14230 "HAVE_READLINKAT",
14231#endif
14232
14233#ifdef HAVE_RENAMEAT
14234 "HAVE_RENAMEAT",
14235#endif
14236
14237#ifdef HAVE_SYMLINKAT
14238 "HAVE_SYMLINKAT",
14239#endif
14240
14241#ifdef HAVE_UNLINKAT
14242 "HAVE_UNLINKAT",
14243#endif
14244
14245#ifdef HAVE_UTIMENSAT
14246 "HAVE_UTIMENSAT",
14247#endif
14248
14249#ifdef MS_WINDOWS
14250 "MS_WINDOWS",
14251#endif
14252
14253 NULL
14254};
14255
14256
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014257PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014258INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014259{
Victor Stinner8c62be82010-05-06 00:08:46 +000014260 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014261 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014262 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014263
Victor Stinner8c62be82010-05-06 00:08:46 +000014264 m = PyModule_Create(&posixmodule);
14265 if (m == NULL)
14266 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014267
Victor Stinner8c62be82010-05-06 00:08:46 +000014268 /* Initialize environ dictionary */
14269 v = convertenviron();
14270 Py_XINCREF(v);
14271 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14272 return NULL;
14273 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014274
Victor Stinner8c62be82010-05-06 00:08:46 +000014275 if (all_ins(m))
14276 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014277
Victor Stinner8c62be82010-05-06 00:08:46 +000014278 if (setup_confname_tables(m))
14279 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014280
Victor Stinner8c62be82010-05-06 00:08:46 +000014281 Py_INCREF(PyExc_OSError);
14282 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014283
Guido van Rossumb3d39562000-01-31 18:41:26 +000014284#ifdef HAVE_PUTENV
Victor Stinner8c62be82010-05-06 00:08:46 +000014285 if (posix_putenv_garbage == NULL)
14286 posix_putenv_garbage = PyDict_New();
Guido van Rossumb3d39562000-01-31 18:41:26 +000014287#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +000014288
Victor Stinner8c62be82010-05-06 00:08:46 +000014289 if (!initialized) {
Ross Lagerwall7807c352011-03-17 20:20:30 +020014290#if defined(HAVE_WAITID) && !defined(__APPLE__)
14291 waitid_result_desc.name = MODNAME ".waitid_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014292 WaitidResultType = PyStructSequence_NewType(&waitid_result_desc);
14293 if (WaitidResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014294 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014295 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020014296#endif
14297
Christian Heimes25827622013-10-12 01:27:08 +020014298 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
Victor Stinner8c62be82010-05-06 00:08:46 +000014299 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14300 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14301 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014302 StatResultType = PyStructSequence_NewType(&stat_result_desc);
14303 if (StatResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014304 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014305 }
14306 structseq_new = StatResultType->tp_new;
14307 StatResultType->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014308
Christian Heimes25827622013-10-12 01:27:08 +020014309 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014310 StatVFSResultType = PyStructSequence_NewType(&statvfs_result_desc);
14311 if (StatVFSResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014312 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014313 }
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014314#ifdef NEED_TICKS_PER_SECOND
14315# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinner8c62be82010-05-06 00:08:46 +000014316 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014317# elif defined(HZ)
Victor Stinner8c62be82010-05-06 00:08:46 +000014318 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014319# else
Victor Stinner8c62be82010-05-06 00:08:46 +000014320 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014321# endif
14322#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014323
William Orr81574b82018-10-01 22:19:56 -070014324#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014325 sched_param_desc.name = MODNAME ".sched_param";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014326 SchedParamType = PyStructSequence_NewType(&sched_param_desc);
14327 if (SchedParamType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014328 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014329 }
14330 SchedParamType->tp_new = os_sched_param;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014331#endif
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014332
14333 /* initialize TerminalSize_info */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014334 TerminalSizeType = PyStructSequence_NewType(&TerminalSize_desc);
14335 if (TerminalSizeType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014336 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014337 }
Victor Stinner6036e442015-03-08 01:58:04 +010014338
14339 /* initialize scandir types */
14340 if (PyType_Ready(&ScandirIteratorType) < 0)
14341 return NULL;
14342 if (PyType_Ready(&DirEntryType) < 0)
14343 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014344 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020014345#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014346 Py_INCREF((PyObject*) WaitidResultType);
14347 PyModule_AddObject(m, "waitid_result", (PyObject*) WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +020014348#endif
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014349 Py_INCREF((PyObject*) StatResultType);
14350 PyModule_AddObject(m, "stat_result", (PyObject*) StatResultType);
14351 Py_INCREF((PyObject*) StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000014352 PyModule_AddObject(m, "statvfs_result",
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014353 (PyObject*) StatVFSResultType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014354
14355#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014356 Py_INCREF(SchedParamType);
14357 PyModule_AddObject(m, "sched_param", (PyObject *)SchedParamType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014358#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014359
Larry Hastings605a62d2012-06-24 04:33:36 -070014360 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014361 TimesResultType = PyStructSequence_NewType(&times_result_desc);
14362 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014363 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014364 }
14365 PyModule_AddObject(m, "times_result", (PyObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070014366
14367 uname_result_desc.name = MODNAME ".uname_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014368 UnameResultType = PyStructSequence_NewType(&uname_result_desc);
14369 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014370 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014371 }
14372 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070014373
Thomas Wouters477c8d52006-05-27 19:21:47 +000014374#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014375 /*
14376 * Step 2 of weak-linking support on Mac OS X.
14377 *
14378 * The code below removes functions that are not available on the
14379 * currently active platform.
14380 *
14381 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014382 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014383 * OSX 10.4.
14384 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014385#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014386 if (fstatvfs == NULL) {
14387 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14388 return NULL;
14389 }
14390 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014391#endif /* HAVE_FSTATVFS */
14392
14393#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014394 if (statvfs == NULL) {
14395 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14396 return NULL;
14397 }
14398 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014399#endif /* HAVE_STATVFS */
14400
14401# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014402 if (lchown == NULL) {
14403 if (PyObject_DelAttrString(m, "lchown") == -1) {
14404 return NULL;
14405 }
14406 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014407#endif /* HAVE_LCHOWN */
14408
14409
14410#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014411
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014412 Py_INCREF(TerminalSizeType);
14413 PyModule_AddObject(m, "terminal_size", (PyObject*)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014414
Larry Hastings6fe20b32012-04-19 15:07:49 -070014415 billion = PyLong_FromLong(1000000000);
14416 if (!billion)
14417 return NULL;
14418
Larry Hastings9cf065c2012-06-22 16:30:09 -070014419 /* suppress "function not used" warnings */
14420 {
14421 int ignored;
14422 fd_specified("", -1);
14423 follow_symlinks_specified("", 1);
14424 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14425 dir_fd_converter(Py_None, &ignored);
14426 dir_fd_unavailable(Py_None, &ignored);
14427 }
14428
14429 /*
14430 * provide list of locally available functions
14431 * so os.py can populate support_* lists
14432 */
14433 list = PyList_New(0);
14434 if (!list)
14435 return NULL;
14436 for (trace = have_functions; *trace; trace++) {
14437 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14438 if (!unicode)
14439 return NULL;
14440 if (PyList_Append(list, unicode))
14441 return NULL;
14442 Py_DECREF(unicode);
14443 }
14444 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014445
14446 Py_INCREF((PyObject *) &DirEntryType);
Brett Cannona32c4d02016-06-24 14:14:44 -070014447 PyModule_AddObject(m, "DirEntry", (PyObject *)&DirEntryType);
Larry Hastings9cf065c2012-06-22 16:30:09 -070014448
14449 initialized = 1;
14450
Victor Stinner8c62be82010-05-06 00:08:46 +000014451 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014452}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014453
14454#ifdef __cplusplus
14455}
14456#endif