blob: 2f791d1df953a06f95ea868c8809c43b63d4781d [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
Pablo Galindoaac4d032019-05-31 19:39:47 +0100120#ifdef HAVE_COPY_FILE_RANGE
121#include <unistd.h>
122#endif
123
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500124#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500125#undef HAVE_SCHED_SETAFFINITY
126#endif
127
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200128#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Benjamin Peterson9428d532011-09-14 11:45:52 -0400129#define USE_XATTRS
130#endif
131
132#ifdef USE_XATTRS
Benjamin Petersonb77fe172011-09-13 17:20:47 -0400133#include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400134#endif
135
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000136#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
137#ifdef HAVE_SYS_SOCKET_H
138#include <sys/socket.h>
139#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000140#endif
141
Victor Stinner8b905bd2011-10-25 13:34:04 +0200142#ifdef HAVE_DLFCN_H
143#include <dlfcn.h>
144#endif
145
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200146#ifdef __hpux
147#include <sys/mpctl.h>
148#endif
149
150#if defined(__DragonFly__) || \
151 defined(__OpenBSD__) || \
152 defined(__FreeBSD__) || \
153 defined(__NetBSD__) || \
154 defined(__APPLE__)
155#include <sys/sysctl.h>
156#endif
157
Victor Stinner9b1f4742016-09-06 16:18:52 -0700158#ifdef HAVE_LINUX_RANDOM_H
159# include <linux/random.h>
160#endif
161#ifdef HAVE_GETRANDOM_SYSCALL
162# include <sys/syscall.h>
163#endif
164
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100165#if defined(MS_WINDOWS)
166# define TERMSIZE_USE_CONIO
167#elif defined(HAVE_SYS_IOCTL_H)
168# include <sys/ioctl.h>
169# if defined(HAVE_TERMIOS_H)
170# include <termios.h>
171# endif
172# if defined(TIOCGWINSZ)
173# define TERMSIZE_USE_IOCTL
174# endif
175#endif /* MS_WINDOWS */
176
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000177/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000178/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000179#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000180#define HAVE_OPENDIR 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000181#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000182#include <process.h>
183#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000184#ifdef _MSC_VER /* Microsoft compiler */
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000185#define HAVE_GETPPID 1
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000186#define HAVE_GETLOGIN 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000187#define HAVE_SPAWNV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000188#define HAVE_EXECV 1
Steve Dowercc16be82016-09-08 10:35:16 -0700189#define HAVE_WSPAWNV 1
190#define HAVE_WEXECV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000191#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000192#define HAVE_SYSTEM 1
193#define HAVE_CWAIT 1
194#define HAVE_FSYNC 1
Tim Peters11b23062003-04-23 02:39:17 +0000195#define fsync _commit
Andrew MacIntyre6c73af22002-03-03 03:07:07 +0000196#else
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000197/* Unix functions that the configure script doesn't check for */
pxinwrf2d7ac72019-05-21 18:46:37 +0800198#ifndef __VXWORKS__
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000199#define HAVE_EXECV 1
200#define HAVE_FORK 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000201#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
Guido van Rossum2242f2f2001-04-11 20:58:20 +0000202#define HAVE_FORK1 1
203#endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800204#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000205#define HAVE_GETEGID 1
206#define HAVE_GETEUID 1
207#define HAVE_GETGID 1
208#define HAVE_GETPPID 1
209#define HAVE_GETUID 1
210#define HAVE_KILL 1
211#define HAVE_OPENDIR 1
212#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000213#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000214#define HAVE_WAIT 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000215#define HAVE_TTYNAME 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000216#endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000217#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000218
Victor Stinnera2f7c002012-02-08 03:36:25 +0100219
Larry Hastings61272b72014-01-07 12:41:53 -0800220/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000221# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800222module os
Larry Hastings61272b72014-01-07 12:41:53 -0800223[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000224/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100225
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000226#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000227
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000228#if defined(__sgi)&&_COMPILER_VERSION>=700
229/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
230 (default) */
231extern char *ctermid_r(char *);
232#endif
233
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000234#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235
pxinwrf2d7ac72019-05-21 18:46:37 +0800236#if defined(__VXWORKS__)
237#include <vxCpuLib.h>
238#include <rtpLib.h>
239#include <wait.h>
240#include <taskLib.h>
241#ifndef _P_WAIT
242#define _P_WAIT 0
243#define _P_NOWAIT 1
244#define _P_NOWAITO 1
245#endif
246#endif /* __VXWORKS__ */
247
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000248#ifdef HAVE_POSIX_SPAWN
249#include <spawn.h>
250#endif
251
Guido van Rossumb6775db1994-08-01 11:34:53 +0000252#ifdef HAVE_UTIME_H
253#include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000254#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000255
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000256#ifdef HAVE_SYS_UTIME_H
257#include <sys/utime.h>
258#define HAVE_UTIME_H /* pretend we do for the rest of this file */
259#endif /* HAVE_SYS_UTIME_H */
260
Guido van Rossumb6775db1994-08-01 11:34:53 +0000261#ifdef HAVE_SYS_TIMES_H
262#include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000263#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000264
265#ifdef HAVE_SYS_PARAM_H
266#include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000267#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000268
269#ifdef HAVE_SYS_UTSNAME_H
270#include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000271#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000272
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000273#ifdef HAVE_DIRENT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000274#include <dirent.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000275#define NAMLEN(dirent) strlen((dirent)->d_name)
276#else
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000277#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000278#include <direct.h>
279#define NAMLEN(dirent) strlen((dirent)->d_name)
280#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000281#define dirent direct
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000282#define NAMLEN(dirent) (dirent)->d_namlen
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000283#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000284#ifdef HAVE_SYS_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000285#include <sys/ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000286#endif
287#ifdef HAVE_SYS_DIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000288#include <sys/dir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000289#endif
290#ifdef HAVE_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000291#include <ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000292#endif
293#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000294
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000295#ifdef _MSC_VER
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000296#ifdef HAVE_DIRECT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000297#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000298#endif
299#ifdef HAVE_IO_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300#include <io.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000301#endif
302#ifdef HAVE_PROCESS_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303#include <process.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000304#endif
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000305#ifndef IO_REPARSE_TAG_SYMLINK
Amaury Forgeot d'Arc844807e2010-08-16 22:16:51 +0000306#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000307#endif
Tim Golden0321cf22014-05-05 19:46:17 +0100308#ifndef IO_REPARSE_TAG_MOUNT_POINT
309#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
310#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000311#include "osdefs.h"
Kristján Valur Jónssonf64e6512009-04-13 10:16:14 +0000312#include <malloc.h>
Guido van Rossumb6775db1994-08-01 11:34:53 +0000313#include <windows.h>
Victor Stinner8c62be82010-05-06 00:08:46 +0000314#include <shellapi.h> /* for ShellExecute() */
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000315#include <lmcons.h> /* for UNLEN */
Brian Curtin52173d42010-12-02 18:29:18 +0000316#define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000317#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000318
Tim Petersbc2e10e2002-03-03 23:17:02 +0000319#ifndef MAXPATHLEN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000320#if defined(PATH_MAX) && PATH_MAX > 1024
321#define MAXPATHLEN PATH_MAX
322#else
Tim Petersbc2e10e2002-03-03 23:17:02 +0000323#define MAXPATHLEN 1024
Thomas Wouters477c8d52006-05-27 19:21:47 +0000324#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000325#endif /* MAXPATHLEN */
326
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000327#ifdef UNION_WAIT
328/* Emulate some macros on systems that have a union instead of macros */
329
330#ifndef WIFEXITED
331#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
332#endif
333
334#ifndef WEXITSTATUS
335#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
336#endif
337
338#ifndef WTERMSIG
339#define WTERMSIG(u_wait) ((u_wait).w_termsig)
340#endif
341
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000342#define WAIT_TYPE union wait
343#define WAIT_STATUS_INT(s) (s.w_status)
344
345#else /* !UNION_WAIT */
346#define WAIT_TYPE int
347#define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000348#endif /* UNION_WAIT */
349
Greg Wardb48bc172000-03-01 21:51:56 +0000350/* Don't use the "_r" form if we don't need it (also, won't have a
351 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200352#if defined(HAVE_CTERMID_R)
Greg Wardb48bc172000-03-01 21:51:56 +0000353#define USE_CTERMID_R
354#endif
355
Fred Drake699f3522000-06-29 21:12:41 +0000356/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000357#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000358#undef FSTAT
359#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200360#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +0000361# define STAT win32_stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700362# define LSTAT win32_lstat
Victor Stinnere134a7f2015-03-30 10:09:31 +0200363# define FSTAT _Py_fstat_noraise
Steve Dowerf2f373f2015-02-21 08:44:05 -0800364# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000365#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000366# define STAT stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700367# define LSTAT lstat
Victor Stinner8c62be82010-05-06 00:08:46 +0000368# define FSTAT fstat
369# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000370#endif
371
Tim Peters11b23062003-04-23 02:39:17 +0000372#if defined(MAJOR_IN_MKDEV)
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000373#include <sys/mkdev.h>
374#else
375#if defined(MAJOR_IN_SYSMACROS)
376#include <sys/sysmacros.h>
377#endif
Neal Norwitz3d949422002-04-20 13:46:43 +0000378#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
379#include <sys/mkdev.h>
380#endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000381#endif
Fred Drake699f3522000-06-29 21:12:41 +0000382
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200383#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +0100384#define INITFUNC PyInit_nt
385#define MODNAME "nt"
386#else
387#define INITFUNC PyInit_posix
388#define MODNAME "posix"
389#endif
390
jcea6c51d512018-01-28 14:00:08 +0100391#if defined(__sun)
392/* Something to implement in autoconf, not present in autoconf 2.69 */
393#define HAVE_STRUCT_STAT_ST_FSTYPE 1
394#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200395
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600396/* memfd_create is either defined in sys/mman.h or sys/memfd.h
397 * linux/memfd.h defines additional flags
398 */
399#ifdef HAVE_SYS_MMAN_H
400#include <sys/mman.h>
401#endif
402#ifdef HAVE_SYS_MEMFD_H
403#include <sys/memfd.h>
404#endif
405#ifdef HAVE_LINUX_MEMFD_H
406#include <linux/memfd.h>
407#endif
408
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800409#ifdef _Py_MEMORY_SANITIZER
410# include <sanitizer/msan_interface.h>
411#endif
412
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200413#ifdef HAVE_FORK
414static void
415run_at_forkers(PyObject *lst, int reverse)
416{
417 Py_ssize_t i;
418 PyObject *cpy;
419
420 if (lst != NULL) {
421 assert(PyList_CheckExact(lst));
422
423 /* Use a list copy in case register_at_fork() is called from
424 * one of the callbacks.
425 */
426 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
427 if (cpy == NULL)
428 PyErr_WriteUnraisable(lst);
429 else {
430 if (reverse)
431 PyList_Reverse(cpy);
432 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
433 PyObject *func, *res;
434 func = PyList_GET_ITEM(cpy, i);
435 res = PyObject_CallObject(func, NULL);
436 if (res == NULL)
437 PyErr_WriteUnraisable(func);
438 else
439 Py_DECREF(res);
440 }
441 Py_DECREF(cpy);
442 }
443 }
444}
445
446void
447PyOS_BeforeFork(void)
448{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200449 run_at_forkers(_PyInterpreterState_Get()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200450
451 _PyImport_AcquireLock();
452}
453
454void
455PyOS_AfterFork_Parent(void)
456{
457 if (_PyImport_ReleaseLock() <= 0)
458 Py_FatalError("failed releasing import lock after fork");
459
Victor Stinnercaba55b2018-08-03 15:33:52 +0200460 run_at_forkers(_PyInterpreterState_Get()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200461}
462
463void
464PyOS_AfterFork_Child(void)
465{
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200466 _PyRuntimeState *runtime = &_PyRuntime;
467 _PyGILState_Reinit(runtime);
Victor Stinnerd5d9e812019-05-13 12:35:37 +0200468 _PyEval_ReInitThreads(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200469 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200470 _PySignal_AfterFork();
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200471 _PyRuntimeState_ReInitThreads(runtime);
Victor Stinnerb49858b2019-05-24 15:20:23 +0200472 _PyInterpreterState_DeleteExceptMain(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200473
Victor Stinnercaba55b2018-08-03 15:33:52 +0200474 run_at_forkers(_PyInterpreterState_Get()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200475}
476
477static int
478register_at_forker(PyObject **lst, PyObject *func)
479{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700480 if (func == NULL) /* nothing to register? do nothing. */
481 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200482 if (*lst == NULL) {
483 *lst = PyList_New(0);
484 if (*lst == NULL)
485 return -1;
486 }
487 return PyList_Append(*lst, func);
488}
489#endif
490
491/* Legacy wrapper */
492void
493PyOS_AfterFork(void)
494{
495#ifdef HAVE_FORK
496 PyOS_AfterFork_Child();
497#endif
498}
499
500
Victor Stinner6036e442015-03-08 01:58:04 +0100501#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200502/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700503void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
504void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200505 ULONG, struct _Py_stat_struct *);
506#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700507
Larry Hastings9cf065c2012-06-22 16:30:09 -0700508
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200509#ifndef MS_WINDOWS
510PyObject *
511_PyLong_FromUid(uid_t uid)
512{
513 if (uid == (uid_t)-1)
514 return PyLong_FromLong(-1);
515 return PyLong_FromUnsignedLong(uid);
516}
517
518PyObject *
519_PyLong_FromGid(gid_t gid)
520{
521 if (gid == (gid_t)-1)
522 return PyLong_FromLong(-1);
523 return PyLong_FromUnsignedLong(gid);
524}
525
526int
527_Py_Uid_Converter(PyObject *obj, void *p)
528{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700529 uid_t uid;
530 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200531 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200532 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700533 unsigned long uresult;
534
535 index = PyNumber_Index(obj);
536 if (index == NULL) {
537 PyErr_Format(PyExc_TypeError,
538 "uid should be integer, not %.200s",
539 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200540 return 0;
541 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700542
543 /*
544 * Handling uid_t is complicated for two reasons:
545 * * Although uid_t is (always?) unsigned, it still
546 * accepts -1.
547 * * We don't know its size in advance--it may be
548 * bigger than an int, or it may be smaller than
549 * a long.
550 *
551 * So a bit of defensive programming is in order.
552 * Start with interpreting the value passed
553 * in as a signed long and see if it works.
554 */
555
556 result = PyLong_AsLongAndOverflow(index, &overflow);
557
558 if (!overflow) {
559 uid = (uid_t)result;
560
561 if (result == -1) {
562 if (PyErr_Occurred())
563 goto fail;
564 /* It's a legitimate -1, we're done. */
565 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200566 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700567
568 /* Any other negative number is disallowed. */
569 if (result < 0)
570 goto underflow;
571
572 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200573 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700574 (long)uid != result)
575 goto underflow;
576 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200577 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700578
579 if (overflow < 0)
580 goto underflow;
581
582 /*
583 * Okay, the value overflowed a signed long. If it
584 * fits in an *unsigned* long, it may still be okay,
585 * as uid_t may be unsigned long on this platform.
586 */
587 uresult = PyLong_AsUnsignedLong(index);
588 if (PyErr_Occurred()) {
589 if (PyErr_ExceptionMatches(PyExc_OverflowError))
590 goto overflow;
591 goto fail;
592 }
593
594 uid = (uid_t)uresult;
595
596 /*
597 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
598 * but this value would get interpreted as (uid_t)-1 by chown
599 * and its siblings. That's not what the user meant! So we
600 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100601 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700602 */
603 if (uid == (uid_t)-1)
604 goto overflow;
605
606 /* Ensure the value wasn't truncated. */
607 if (sizeof(uid_t) < sizeof(long) &&
608 (unsigned long)uid != uresult)
609 goto overflow;
610 /* fallthrough */
611
612success:
613 Py_DECREF(index);
614 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200615 return 1;
616
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700617underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200618 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700619 "uid is less than minimum");
620 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200621
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700622overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200623 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700624 "uid is greater than maximum");
625 /* fallthrough */
626
627fail:
628 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200629 return 0;
630}
631
632int
633_Py_Gid_Converter(PyObject *obj, void *p)
634{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700635 gid_t gid;
636 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200637 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200638 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700639 unsigned long uresult;
640
641 index = PyNumber_Index(obj);
642 if (index == NULL) {
643 PyErr_Format(PyExc_TypeError,
644 "gid should be integer, not %.200s",
645 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200646 return 0;
647 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700648
649 /*
650 * Handling gid_t is complicated for two reasons:
651 * * Although gid_t is (always?) unsigned, it still
652 * accepts -1.
653 * * We don't know its size in advance--it may be
654 * bigger than an int, or it may be smaller than
655 * a long.
656 *
657 * So a bit of defensive programming is in order.
658 * Start with interpreting the value passed
659 * in as a signed long and see if it works.
660 */
661
662 result = PyLong_AsLongAndOverflow(index, &overflow);
663
664 if (!overflow) {
665 gid = (gid_t)result;
666
667 if (result == -1) {
668 if (PyErr_Occurred())
669 goto fail;
670 /* It's a legitimate -1, we're done. */
671 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200672 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700673
674 /* Any other negative number is disallowed. */
675 if (result < 0) {
676 goto underflow;
677 }
678
679 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200680 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700681 (long)gid != result)
682 goto underflow;
683 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200684 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700685
686 if (overflow < 0)
687 goto underflow;
688
689 /*
690 * Okay, the value overflowed a signed long. If it
691 * fits in an *unsigned* long, it may still be okay,
692 * as gid_t may be unsigned long on this platform.
693 */
694 uresult = PyLong_AsUnsignedLong(index);
695 if (PyErr_Occurred()) {
696 if (PyErr_ExceptionMatches(PyExc_OverflowError))
697 goto overflow;
698 goto fail;
699 }
700
701 gid = (gid_t)uresult;
702
703 /*
704 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
705 * but this value would get interpreted as (gid_t)-1 by chown
706 * and its siblings. That's not what the user meant! So we
707 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100708 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700709 */
710 if (gid == (gid_t)-1)
711 goto overflow;
712
713 /* Ensure the value wasn't truncated. */
714 if (sizeof(gid_t) < sizeof(long) &&
715 (unsigned long)gid != uresult)
716 goto overflow;
717 /* fallthrough */
718
719success:
720 Py_DECREF(index);
721 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200722 return 1;
723
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700724underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200725 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700726 "gid is less than minimum");
727 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200728
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700729overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200730 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700731 "gid is greater than maximum");
732 /* fallthrough */
733
734fail:
735 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200736 return 0;
737}
738#endif /* MS_WINDOWS */
739
740
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700741#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800742
743
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200744#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
745static int
746_Py_Dev_Converter(PyObject *obj, void *p)
747{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200748 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200749 if (PyErr_Occurred())
750 return 0;
751 return 1;
752}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800753#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200754
755
Larry Hastings9cf065c2012-06-22 16:30:09 -0700756#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400757/*
758 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
759 * without the int cast, the value gets interpreted as uint (4291925331),
760 * which doesn't play nicely with all the initializer lines in this file that
761 * look like this:
762 * int dir_fd = DEFAULT_DIR_FD;
763 */
764#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700765#else
766#define DEFAULT_DIR_FD (-100)
767#endif
768
769static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300770_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200771{
772 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700773 long long_value;
774
775 PyObject *index = PyNumber_Index(o);
776 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700777 return 0;
778 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700779
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300780 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700781 long_value = PyLong_AsLongAndOverflow(index, &overflow);
782 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300783 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200784 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700785 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700786 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700787 return 0;
788 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200789 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700790 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700791 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700792 return 0;
793 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700794
Larry Hastings9cf065c2012-06-22 16:30:09 -0700795 *p = (int)long_value;
796 return 1;
797}
798
799static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200800dir_fd_converter(PyObject *o, void *p)
801{
802 if (o == Py_None) {
803 *(int *)p = DEFAULT_DIR_FD;
804 return 1;
805 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300806 else if (PyIndex_Check(o)) {
807 return _fd_converter(o, (int *)p);
808 }
809 else {
810 PyErr_Format(PyExc_TypeError,
811 "argument should be integer or None, not %.200s",
812 Py_TYPE(o)->tp_name);
813 return 0;
814 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700815}
816
817
Larry Hastings9cf065c2012-06-22 16:30:09 -0700818/*
819 * A PyArg_ParseTuple "converter" function
820 * that handles filesystem paths in the manner
821 * preferred by the os module.
822 *
823 * path_converter accepts (Unicode) strings and their
824 * subclasses, and bytes and their subclasses. What
825 * it does with the argument depends on the platform:
826 *
827 * * On Windows, if we get a (Unicode) string we
828 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700829 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700830 *
831 * * On all other platforms, strings are encoded
832 * to bytes using PyUnicode_FSConverter, then we
833 * extract the char * from the bytes object and
834 * return that.
835 *
836 * path_converter also optionally accepts signed
837 * integers (representing open file descriptors) instead
838 * of path strings.
839 *
840 * Input fields:
841 * path.nullable
842 * If nonzero, the path is permitted to be None.
843 * path.allow_fd
844 * If nonzero, the path is permitted to be a file handle
845 * (a signed int) instead of a string.
846 * path.function_name
847 * If non-NULL, path_converter will use that as the name
848 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700849 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700850 * path.argument_name
851 * If non-NULL, path_converter will use that as the name
852 * of the parameter in error messages.
853 * (If path.argument_name is NULL it uses "path".)
854 *
855 * Output fields:
856 * path.wide
857 * Points to the path if it was expressed as Unicode
858 * and was not encoded. (Only used on Windows.)
859 * path.narrow
860 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700861 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000862 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700863 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700864 * path.fd
865 * Contains a file descriptor if path.accept_fd was true
866 * and the caller provided a signed integer instead of any
867 * sort of string.
868 *
869 * WARNING: if your "path" parameter is optional, and is
870 * unspecified, path_converter will never get called.
871 * So if you set allow_fd, you *MUST* initialize path.fd = -1
872 * yourself!
873 * path.length
874 * The length of the path in characters, if specified as
875 * a string.
876 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800877 * The original object passed in (if get a PathLike object,
878 * the result of PyOS_FSPath() is treated as the original object).
879 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700880 * path.cleanup
881 * For internal use only. May point to a temporary object.
882 * (Pay no attention to the man behind the curtain.)
883 *
884 * At most one of path.wide or path.narrow will be non-NULL.
885 * If path was None and path.nullable was set,
886 * or if path was an integer and path.allow_fd was set,
887 * both path.wide and path.narrow will be NULL
888 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200889 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700890 * path_converter takes care to not write to the path_t
891 * unless it's successful. However it must reset the
892 * "cleanup" field each time it's called.
893 *
894 * Use as follows:
895 * path_t path;
896 * memset(&path, 0, sizeof(path));
897 * PyArg_ParseTuple(args, "O&", path_converter, &path);
898 * // ... use values from path ...
899 * path_cleanup(&path);
900 *
901 * (Note that if PyArg_Parse fails you don't need to call
902 * path_cleanup(). However it is safe to do so.)
903 */
904typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100905 const char *function_name;
906 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700907 int nullable;
908 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300909 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700910#ifdef MS_WINDOWS
911 BOOL narrow;
912#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300913 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700914#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700915 int fd;
916 Py_ssize_t length;
917 PyObject *object;
918 PyObject *cleanup;
919} path_t;
920
Steve Dowercc16be82016-09-08 10:35:16 -0700921#ifdef MS_WINDOWS
922#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
923 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
924#else
Larry Hastings2f936352014-08-05 14:04:04 +1000925#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
926 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700927#endif
Larry Hastings31826802013-10-19 00:09:25 -0700928
Larry Hastings9cf065c2012-06-22 16:30:09 -0700929static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800930path_cleanup(path_t *path)
931{
932 Py_CLEAR(path->object);
933 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700934}
935
936static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300937path_converter(PyObject *o, void *p)
938{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700939 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800940 PyObject *bytes = NULL;
941 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700942 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300943 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700944#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800945 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700946 const wchar_t *wide;
947#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700948
949#define FORMAT_EXCEPTION(exc, fmt) \
950 PyErr_Format(exc, "%s%s" fmt, \
951 path->function_name ? path->function_name : "", \
952 path->function_name ? ": " : "", \
953 path->argument_name ? path->argument_name : "path")
954
955 /* Py_CLEANUP_SUPPORTED support */
956 if (o == NULL) {
957 path_cleanup(path);
958 return 1;
959 }
960
Brett Cannon3f9183b2016-08-26 14:44:48 -0700961 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800962 path->object = path->cleanup = NULL;
963 /* path->object owns a reference to the original object */
964 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700965
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300966 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700967 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700968#ifdef MS_WINDOWS
969 path->narrow = FALSE;
970#else
Larry Hastings9cf065c2012-06-22 16:30:09 -0700971 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700972#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700973 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +0800974 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700975 }
976
Brett Cannon3f9183b2016-08-26 14:44:48 -0700977 /* Only call this here so that we don't treat the return value of
978 os.fspath() as an fd or buffer. */
979 is_index = path->allow_fd && PyIndex_Check(o);
980 is_buffer = PyObject_CheckBuffer(o);
981 is_bytes = PyBytes_Check(o);
982 is_unicode = PyUnicode_Check(o);
983
984 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
985 /* Inline PyOS_FSPath() for better error messages. */
986 _Py_IDENTIFIER(__fspath__);
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000987 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700988
989 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
990 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +0800991 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700992 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000993 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -0700994 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000995 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -0700996 goto error_exit;
997 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000998 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -0700999 is_unicode = 1;
1000 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001001 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001002 is_bytes = 1;
1003 }
1004 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001005 PyErr_Format(PyExc_TypeError,
1006 "expected %.200s.__fspath__() to return str or bytes, "
1007 "not %.200s", Py_TYPE(o)->tp_name,
1008 Py_TYPE(res)->tp_name);
1009 Py_DECREF(res);
1010 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001011 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001012
1013 /* still owns a reference to the original object */
1014 Py_DECREF(o);
1015 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001016 }
1017
1018 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001019#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001020 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001021 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001022 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001023 }
Victor Stinner59799a82013-11-13 14:17:30 +01001024 if (length > 32767) {
1025 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001026 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001027 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001028 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001029 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001030 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001031 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001032
1033 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001034 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001035 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001036 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001037#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001038 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001039 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001040 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001041#endif
1042 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001043 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001044 bytes = o;
1045 Py_INCREF(bytes);
1046 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001047 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001048 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001049 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001050 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1051 "%s%s%s should be %s, not %.200s",
1052 path->function_name ? path->function_name : "",
1053 path->function_name ? ": " : "",
1054 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001055 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1056 "integer or None" :
1057 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1058 path->nullable ? "string, bytes, os.PathLike or None" :
1059 "string, bytes or os.PathLike",
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001060 Py_TYPE(o)->tp_name)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001061 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001062 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001063 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001064 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001065 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001066 }
1067 }
Steve Dowercc16be82016-09-08 10:35:16 -07001068 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001069 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001070 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001071 }
1072 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001073#ifdef MS_WINDOWS
1074 path->narrow = FALSE;
1075#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001076 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001077#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001078 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001079 }
1080 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001081 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001082 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1083 path->function_name ? path->function_name : "",
1084 path->function_name ? ": " : "",
1085 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001086 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1087 "integer or None" :
1088 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1089 path->nullable ? "string, bytes, os.PathLike or None" :
1090 "string, bytes or os.PathLike",
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001091 Py_TYPE(o)->tp_name);
Xiang Zhang04316c42017-01-08 23:26:57 +08001092 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001093 }
1094
Larry Hastings9cf065c2012-06-22 16:30:09 -07001095 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001096 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001097 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001098 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001099 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001100 }
1101
Steve Dowercc16be82016-09-08 10:35:16 -07001102#ifdef MS_WINDOWS
1103 wo = PyUnicode_DecodeFSDefaultAndSize(
1104 narrow,
1105 length
1106 );
1107 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001108 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001109 }
1110
Xiang Zhang04316c42017-01-08 23:26:57 +08001111 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001112 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001113 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001114 }
1115 if (length > 32767) {
1116 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001117 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001118 }
1119 if (wcslen(wide) != length) {
1120 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001121 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001122 }
1123 path->wide = wide;
1124 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001125 path->cleanup = wo;
1126 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001127#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001128 path->wide = NULL;
1129 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001130 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001131 /* Still a reference owned by path->object, don't have to
1132 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001133 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001134 }
1135 else {
1136 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001137 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001138#endif
1139 path->fd = -1;
1140
1141 success_exit:
1142 path->length = length;
1143 path->object = o;
1144 return Py_CLEANUP_SUPPORTED;
1145
1146 error_exit:
1147 Py_XDECREF(o);
1148 Py_XDECREF(bytes);
1149#ifdef MS_WINDOWS
1150 Py_XDECREF(wo);
1151#endif
1152 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001153}
1154
1155static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001156argument_unavailable_error(const char *function_name, const char *argument_name)
1157{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001158 PyErr_Format(PyExc_NotImplementedError,
1159 "%s%s%s unavailable on this platform",
1160 (function_name != NULL) ? function_name : "",
1161 (function_name != NULL) ? ": ": "",
1162 argument_name);
1163}
1164
1165static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001166dir_fd_unavailable(PyObject *o, void *p)
1167{
1168 int dir_fd;
1169 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001170 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001171 if (dir_fd != DEFAULT_DIR_FD) {
1172 argument_unavailable_error(NULL, "dir_fd");
1173 return 0;
1174 }
1175 *(int *)p = dir_fd;
1176 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001177}
1178
1179static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001180fd_specified(const char *function_name, int fd)
1181{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001182 if (fd == -1)
1183 return 0;
1184
1185 argument_unavailable_error(function_name, "fd");
1186 return 1;
1187}
1188
1189static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001190follow_symlinks_specified(const char *function_name, int follow_symlinks)
1191{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001192 if (follow_symlinks)
1193 return 0;
1194
1195 argument_unavailable_error(function_name, "follow_symlinks");
1196 return 1;
1197}
1198
1199static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001200path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1201{
Steve Dowercc16be82016-09-08 10:35:16 -07001202 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1203#ifndef MS_WINDOWS
1204 && !path->narrow
1205#endif
1206 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001207 PyErr_Format(PyExc_ValueError,
1208 "%s: can't specify dir_fd without matching path",
1209 function_name);
1210 return 1;
1211 }
1212 return 0;
1213}
1214
1215static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001216dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1217{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001218 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1219 PyErr_Format(PyExc_ValueError,
1220 "%s: can't specify both dir_fd and fd",
1221 function_name);
1222 return 1;
1223 }
1224 return 0;
1225}
1226
1227static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001228fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1229 int follow_symlinks)
1230{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001231 if ((fd > 0) && (!follow_symlinks)) {
1232 PyErr_Format(PyExc_ValueError,
1233 "%s: cannot use fd and follow_symlinks together",
1234 function_name);
1235 return 1;
1236 }
1237 return 0;
1238}
1239
1240static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001241dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1242 int follow_symlinks)
1243{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001244 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1245 PyErr_Format(PyExc_ValueError,
1246 "%s: cannot use dir_fd and follow_symlinks together",
1247 function_name);
1248 return 1;
1249 }
1250 return 0;
1251}
1252
Larry Hastings2f936352014-08-05 14:04:04 +10001253#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001254 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001255#else
Larry Hastings2f936352014-08-05 14:04:04 +10001256 typedef off_t Py_off_t;
1257#endif
1258
1259static int
1260Py_off_t_converter(PyObject *arg, void *addr)
1261{
1262#ifdef HAVE_LARGEFILE_SUPPORT
1263 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1264#else
1265 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001266#endif
1267 if (PyErr_Occurred())
1268 return 0;
1269 return 1;
1270}
Larry Hastings2f936352014-08-05 14:04:04 +10001271
1272static PyObject *
1273PyLong_FromPy_off_t(Py_off_t offset)
1274{
1275#ifdef HAVE_LARGEFILE_SUPPORT
1276 return PyLong_FromLongLong(offset);
1277#else
1278 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001279#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001280}
1281
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001282#ifdef HAVE_SIGSET_T
1283/* Convert an iterable of integers to a sigset.
1284 Return 1 on success, return 0 and raise an exception on error. */
1285int
1286_Py_Sigset_Converter(PyObject *obj, void *addr)
1287{
1288 sigset_t *mask = (sigset_t *)addr;
1289 PyObject *iterator, *item;
1290 long signum;
1291 int overflow;
1292
Rémi Lapeyref0900192019-05-04 01:30:53 +02001293 // The extra parens suppress the unreachable-code warning with clang on MacOS
1294 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001295 /* Probably only if mask == NULL. */
1296 PyErr_SetFromErrno(PyExc_OSError);
1297 return 0;
1298 }
1299
1300 iterator = PyObject_GetIter(obj);
1301 if (iterator == NULL) {
1302 return 0;
1303 }
1304
1305 while ((item = PyIter_Next(iterator)) != NULL) {
1306 signum = PyLong_AsLongAndOverflow(item, &overflow);
1307 Py_DECREF(item);
1308 if (signum <= 0 || signum >= NSIG) {
1309 if (overflow || signum != -1 || !PyErr_Occurred()) {
1310 PyErr_Format(PyExc_ValueError,
1311 "signal number %ld out of range", signum);
1312 }
1313 goto error;
1314 }
1315 if (sigaddset(mask, (int)signum)) {
1316 if (errno != EINVAL) {
1317 /* Probably impossible */
1318 PyErr_SetFromErrno(PyExc_OSError);
1319 goto error;
1320 }
1321 /* For backwards compatibility, allow idioms such as
1322 * `range(1, NSIG)` but warn about invalid signal numbers
1323 */
1324 const char msg[] =
1325 "invalid signal number %ld, please use valid_signals()";
1326 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1327 goto error;
1328 }
1329 }
1330 }
1331 if (!PyErr_Occurred()) {
1332 Py_DECREF(iterator);
1333 return 1;
1334 }
1335
1336error:
1337 Py_DECREF(iterator);
1338 return 0;
1339}
1340#endif /* HAVE_SIGSET_T */
1341
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001342#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001343
1344static int
Brian Curtind25aef52011-06-13 15:16:04 -05001345win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001346{
Martin Panter70214ad2016-08-04 02:38:59 +00001347 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1348 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001349 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001350
1351 if (0 == DeviceIoControl(
1352 reparse_point_handle,
1353 FSCTL_GET_REPARSE_POINT,
1354 NULL, 0, /* in buffer */
1355 target_buffer, sizeof(target_buffer),
1356 &n_bytes_returned,
1357 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001358 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001359
1360 if (reparse_tag)
1361 *reparse_tag = rdb->ReparseTag;
1362
Brian Curtind25aef52011-06-13 15:16:04 -05001363 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001364}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001365
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001366#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001367
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001368/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001369#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001370/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001371** environ directly, we must obtain it with _NSGetEnviron(). See also
1372** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001373*/
1374#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001375#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001376extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001377#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001378
Barry Warsaw53699e91996-12-10 23:23:01 +00001379static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001380convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001381{
Victor Stinner8c62be82010-05-06 00:08:46 +00001382 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001383#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001384 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001385#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001386 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001387#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001388
Victor Stinner8c62be82010-05-06 00:08:46 +00001389 d = PyDict_New();
1390 if (d == NULL)
1391 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001392#ifdef MS_WINDOWS
1393 /* _wenviron must be initialized in this way if the program is started
1394 through main() instead of wmain(). */
1395 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001396 e = _wenviron;
Miss Islington (bot)836cf312019-12-06 11:32:33 -08001397#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1398 /* environ is not accessible as an extern in a shared object on OSX; use
1399 _NSGetEnviron to resolve it. The value changes if you add environment
1400 variables between calls to Py_Initialize, so don't cache the value. */
1401 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001402#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001403 e = environ;
1404#endif
1405 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001406 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001407 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001408 PyObject *k;
1409 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001410#ifdef MS_WINDOWS
1411 const wchar_t *p = wcschr(*e, L'=');
1412#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001413 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001414#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001415 if (p == NULL)
1416 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001417#ifdef MS_WINDOWS
1418 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1419#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001420 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001421#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001422 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001423 Py_DECREF(d);
1424 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001425 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001426#ifdef MS_WINDOWS
1427 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1428#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001429 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001430#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001431 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001432 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001433 Py_DECREF(d);
1434 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001435 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001436 if (PyDict_GetItemWithError(d, k) == NULL) {
1437 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1438 Py_DECREF(v);
1439 Py_DECREF(k);
1440 Py_DECREF(d);
1441 return NULL;
1442 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001443 }
1444 Py_DECREF(k);
1445 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001446 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001447 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001448}
1449
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001450/* Set a POSIX-specific error from errno, and return NULL */
1451
Barry Warsawd58d7641998-07-23 16:14:40 +00001452static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001453posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001454{
Victor Stinner8c62be82010-05-06 00:08:46 +00001455 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001456}
Mark Hammondef8b6542001-05-13 08:04:26 +00001457
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001458#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001459static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001460win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001461{
Victor Stinner8c62be82010-05-06 00:08:46 +00001462 /* XXX We should pass the function name along in the future.
1463 (winreg.c also wants to pass the function name.)
1464 This would however require an additional param to the
1465 Windows error object, which is non-trivial.
1466 */
1467 errno = GetLastError();
1468 if (filename)
1469 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1470 else
1471 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001472}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001473
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001474static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001475win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001476{
1477 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001478 if (filename)
1479 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001480 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001481 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001482 filename);
1483 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001484 return PyErr_SetFromWindowsErr(err);
1485}
1486
1487static PyObject *
1488win32_error_object(const char* function, PyObject* filename)
1489{
1490 errno = GetLastError();
1491 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001492}
1493
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001494#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001495
Larry Hastings9cf065c2012-06-22 16:30:09 -07001496static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001497posix_path_object_error(PyObject *path)
1498{
1499 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1500}
1501
1502static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001503path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001504{
1505#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001506 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1507 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001508#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001509 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001510#endif
1511}
1512
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001513static PyObject *
1514path_object_error2(PyObject *path, PyObject *path2)
1515{
1516#ifdef MS_WINDOWS
1517 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1518 PyExc_OSError, 0, path, path2);
1519#else
1520 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1521#endif
1522}
1523
1524static PyObject *
1525path_error(path_t *path)
1526{
1527 return path_object_error(path->object);
1528}
Larry Hastings31826802013-10-19 00:09:25 -07001529
Larry Hastingsb0827312014-02-09 22:05:19 -08001530static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001531posix_path_error(path_t *path)
1532{
1533 return posix_path_object_error(path->object);
1534}
1535
1536static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001537path_error2(path_t *path, path_t *path2)
1538{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001539 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001540}
1541
1542
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001543/* POSIX generic methods */
1544
Larry Hastings2f936352014-08-05 14:04:04 +10001545static int
1546fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001547{
Victor Stinner8c62be82010-05-06 00:08:46 +00001548 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001549 int *pointer = (int *)p;
1550 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001551 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001552 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001553 *pointer = fd;
1554 return 1;
1555}
1556
1557static PyObject *
1558posix_fildes_fd(int fd, int (*func)(int))
1559{
1560 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001561 int async_err = 0;
1562
1563 do {
1564 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001565 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001566 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001567 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001568 Py_END_ALLOW_THREADS
1569 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1570 if (res != 0)
1571 return (!async_err) ? posix_error() : NULL;
1572 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001573}
Guido van Rossum21142a01999-01-08 21:05:37 +00001574
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001575
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001576#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001577/* This is a reimplementation of the C library's chdir function,
1578 but one that produces Win32 errors instead of DOS error codes.
1579 chdir is essentially a wrapper around SetCurrentDirectory; however,
1580 it also needs to set "magic" environment variables indicating
1581 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001582static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001583win32_wchdir(LPCWSTR path)
1584{
Victor Stinnered537822015-12-13 21:40:26 +01001585 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001586 int result;
1587 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001588
Victor Stinner8c62be82010-05-06 00:08:46 +00001589 if(!SetCurrentDirectoryW(path))
1590 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001591 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001592 if (!result)
1593 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001594 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001595 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001596 if (!new_path) {
1597 SetLastError(ERROR_OUTOFMEMORY);
1598 return FALSE;
1599 }
1600 result = GetCurrentDirectoryW(result, new_path);
1601 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001602 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001603 return FALSE;
1604 }
1605 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001606 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1607 wcsncmp(new_path, L"//", 2) == 0);
1608 if (!is_unc_like_path) {
1609 env[1] = new_path[0];
1610 result = SetEnvironmentVariableW(env, new_path);
1611 }
Victor Stinnered537822015-12-13 21:40:26 +01001612 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001613 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001614 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001615}
1616#endif
1617
Martin v. Löwis14694662006-02-03 12:54:16 +00001618#ifdef MS_WINDOWS
1619/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1620 - time stamps are restricted to second resolution
1621 - file modification times suffer from forth-and-back conversions between
1622 UTC and local time
1623 Therefore, we implement our own stat, based on the Win32 API directly.
1624*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001625#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001626#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dower9eb3d542019-08-21 15:52:42 -07001627#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001628
Victor Stinner6036e442015-03-08 01:58:04 +01001629static void
Steve Dowercc16be82016-09-08 10:35:16 -07001630find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1631 BY_HANDLE_FILE_INFORMATION *info,
1632 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001633{
1634 memset(info, 0, sizeof(*info));
1635 info->dwFileAttributes = pFileData->dwFileAttributes;
1636 info->ftCreationTime = pFileData->ftCreationTime;
1637 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1638 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1639 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1640 info->nFileSizeLow = pFileData->nFileSizeLow;
1641/* info->nNumberOfLinks = 1; */
1642 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1643 *reparse_tag = pFileData->dwReserved0;
1644 else
1645 *reparse_tag = 0;
1646}
1647
Guido van Rossumd8faa362007-04-27 19:54:29 +00001648static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001649attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001650{
Victor Stinner8c62be82010-05-06 00:08:46 +00001651 HANDLE hFindFile;
1652 WIN32_FIND_DATAW FileData;
1653 hFindFile = FindFirstFileW(pszFile, &FileData);
1654 if (hFindFile == INVALID_HANDLE_VALUE)
1655 return FALSE;
1656 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001657 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001658 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001659}
1660
Brian Curtind25aef52011-06-13 15:16:04 -05001661static int
Steve Dowercc16be82016-09-08 10:35:16 -07001662win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001663 BOOL traverse)
1664{
Steve Dower9eb3d542019-08-21 15:52:42 -07001665 HANDLE hFile;
1666 BY_HANDLE_FILE_INFORMATION fileInfo;
1667 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1668 DWORD fileType, error;
1669 BOOL isUnhandledTag = FALSE;
1670 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001671
Steve Dower9eb3d542019-08-21 15:52:42 -07001672 DWORD access = FILE_READ_ATTRIBUTES;
1673 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1674 if (!traverse) {
1675 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1676 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001677
Steve Dower9eb3d542019-08-21 15:52:42 -07001678 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001679 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dower9eb3d542019-08-21 15:52:42 -07001680 /* Either the path doesn't exist, or the caller lacks access. */
1681 error = GetLastError();
1682 switch (error) {
1683 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1684 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1685 /* Try reading the parent directory. */
1686 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1687 /* Cannot read the parent directory. */
1688 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001689 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001690 }
Steve Dower9eb3d542019-08-21 15:52:42 -07001691 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1692 if (traverse ||
1693 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1694 /* The stat call has to traverse but cannot, so fail. */
1695 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001696 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001697 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001698 }
Steve Dower9eb3d542019-08-21 15:52:42 -07001699 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001700
Steve Dower9eb3d542019-08-21 15:52:42 -07001701 case ERROR_INVALID_PARAMETER:
1702 /* \\.\con requires read or write access. */
1703 hFile = CreateFileW(path, access | GENERIC_READ,
1704 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1705 OPEN_EXISTING, flags, NULL);
1706 if (hFile == INVALID_HANDLE_VALUE) {
1707 SetLastError(error);
1708 return -1;
1709 }
1710 break;
1711
1712 case ERROR_CANT_ACCESS_FILE:
1713 /* bpo37834: open unhandled reparse points if traverse fails. */
1714 if (traverse) {
1715 traverse = FALSE;
1716 isUnhandledTag = TRUE;
1717 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1718 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1719 }
1720 if (hFile == INVALID_HANDLE_VALUE) {
1721 SetLastError(error);
1722 return -1;
1723 }
1724 break;
1725
1726 default:
1727 return -1;
1728 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001729 }
Steve Dower9eb3d542019-08-21 15:52:42 -07001730
1731 if (hFile != INVALID_HANDLE_VALUE) {
1732 /* Handle types other than files on disk. */
1733 fileType = GetFileType(hFile);
1734 if (fileType != FILE_TYPE_DISK) {
1735 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1736 retval = -1;
1737 goto cleanup;
1738 }
1739 DWORD fileAttributes = GetFileAttributesW(path);
1740 memset(result, 0, sizeof(*result));
1741 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1742 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1743 /* \\.\pipe\ or \\.\mailslot\ */
1744 result->st_mode = _S_IFDIR;
1745 } else if (fileType == FILE_TYPE_CHAR) {
1746 /* \\.\nul */
1747 result->st_mode = _S_IFCHR;
1748 } else if (fileType == FILE_TYPE_PIPE) {
1749 /* \\.\pipe\spam */
1750 result->st_mode = _S_IFIFO;
1751 }
1752 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1753 goto cleanup;
1754 }
1755
1756 /* Query the reparse tag, and traverse a non-link. */
1757 if (!traverse) {
1758 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1759 &tagInfo, sizeof(tagInfo))) {
1760 /* Allow devices that do not support FileAttributeTagInfo. */
1761 switch (GetLastError()) {
1762 case ERROR_INVALID_PARAMETER:
1763 case ERROR_INVALID_FUNCTION:
1764 case ERROR_NOT_SUPPORTED:
1765 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1766 tagInfo.ReparseTag = 0;
1767 break;
1768 default:
1769 retval = -1;
1770 goto cleanup;
1771 }
1772 } else if (tagInfo.FileAttributes &
1773 FILE_ATTRIBUTE_REPARSE_POINT) {
1774 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1775 if (isUnhandledTag) {
1776 /* Traversing previously failed for either this link
1777 or its target. */
1778 SetLastError(ERROR_CANT_ACCESS_FILE);
1779 retval = -1;
1780 goto cleanup;
1781 }
1782 /* Traverse a non-link, but not if traversing already failed
1783 for an unhandled tag. */
1784 } else if (!isUnhandledTag) {
1785 CloseHandle(hFile);
1786 return win32_xstat_impl(path, result, TRUE);
1787 }
1788 }
1789 }
1790
1791 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1792 switch (GetLastError()) {
1793 case ERROR_INVALID_PARAMETER:
1794 case ERROR_INVALID_FUNCTION:
1795 case ERROR_NOT_SUPPORTED:
Miss Islington (bot)cad7abf2019-09-04 15:18:05 -07001796 /* Volumes and physical disks are block devices, e.g.
1797 \\.\C: and \\.\PhysicalDrive0. */
1798 memset(result, 0, sizeof(*result));
1799 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dower9eb3d542019-08-21 15:52:42 -07001800 goto cleanup;
1801 }
Miss Islington (bot)cad7abf2019-09-04 15:18:05 -07001802 retval = -1;
Steve Dower9eb3d542019-08-21 15:52:42 -07001803 goto cleanup;
1804 }
1805 }
1806
1807 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1808
1809 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1810 /* Fix the file execute permissions. This hack sets S_IEXEC if
1811 the filename has an extension that is commonly used by files
1812 that CreateProcessW can execute. A real implementation calls
1813 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1814 AccessCheck to check for generic read, write, and execute
1815 access. */
1816 const wchar_t *fileExtension = wcsrchr(path, '.');
1817 if (fileExtension) {
1818 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1819 _wcsicmp(fileExtension, L".bat") == 0 ||
1820 _wcsicmp(fileExtension, L".cmd") == 0 ||
1821 _wcsicmp(fileExtension, L".com") == 0) {
1822 result->st_mode |= 0111;
1823 }
1824 }
1825 }
1826
1827cleanup:
1828 if (hFile != INVALID_HANDLE_VALUE) {
Miss Islington (bot)cad7abf2019-09-04 15:18:05 -07001829 /* Preserve last error if we are failing */
1830 error = retval ? GetLastError() : 0;
1831 if (!CloseHandle(hFile)) {
1832 retval = -1;
1833 } else if (retval) {
1834 /* Restore last error */
1835 SetLastError(error);
1836 }
Steve Dower9eb3d542019-08-21 15:52:42 -07001837 }
1838
1839 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001840}
1841
1842static int
Steve Dowercc16be82016-09-08 10:35:16 -07001843win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001844{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001845 /* Protocol violation: we explicitly clear errno, instead of
1846 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001847 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001848 errno = 0;
1849 return code;
1850}
Brian Curtind25aef52011-06-13 15:16:04 -05001851/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001852
1853 In Posix, stat automatically traverses symlinks and returns the stat
1854 structure for the target. In Windows, the equivalent GetFileAttributes by
1855 default does not traverse symlinks and instead returns attributes for
1856 the symlink.
1857
Steve Dower9eb3d542019-08-21 15:52:42 -07001858 Instead, we will open the file (which *does* traverse symlinks by default)
1859 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001860
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001861static int
Steve Dowercc16be82016-09-08 10:35:16 -07001862win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001863{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001864 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001865}
1866
Victor Stinner8c62be82010-05-06 00:08:46 +00001867static int
Steve Dowercc16be82016-09-08 10:35:16 -07001868win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001869{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001870 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001871}
1872
Martin v. Löwis14694662006-02-03 12:54:16 +00001873#endif /* MS_WINDOWS */
1874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001875PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001876"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001877This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001878 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001879or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1880\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001881Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1882or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001883\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001884See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001885
1886static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001887 {"st_mode", "protection bits"},
1888 {"st_ino", "inode"},
1889 {"st_dev", "device"},
1890 {"st_nlink", "number of hard links"},
1891 {"st_uid", "user ID of owner"},
1892 {"st_gid", "group ID of owner"},
1893 {"st_size", "total size, in bytes"},
1894 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1895 {NULL, "integer time of last access"},
1896 {NULL, "integer time of last modification"},
1897 {NULL, "integer time of last change"},
1898 {"st_atime", "time of last access"},
1899 {"st_mtime", "time of last modification"},
1900 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001901 {"st_atime_ns", "time of last access in nanoseconds"},
1902 {"st_mtime_ns", "time of last modification in nanoseconds"},
1903 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001904#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001905 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001906#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001907#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001908 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001909#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001910#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001911 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001912#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001913#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001914 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001915#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001916#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001917 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001918#endif
1919#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001920 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001921#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001922#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1923 {"st_file_attributes", "Windows file attribute bits"},
1924#endif
jcea6c51d512018-01-28 14:00:08 +01001925#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1926 {"st_fstype", "Type of filesystem"},
1927#endif
Steve Dower9eb3d542019-08-21 15:52:42 -07001928#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1929 {"st_reparse_tag", "Windows reparse tag"},
1930#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001931 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001932};
1933
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001934#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001935#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001936#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001937#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001938#endif
1939
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001940#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001941#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1942#else
1943#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1944#endif
1945
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001946#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001947#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1948#else
1949#define ST_RDEV_IDX ST_BLOCKS_IDX
1950#endif
1951
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001952#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1953#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1954#else
1955#define ST_FLAGS_IDX ST_RDEV_IDX
1956#endif
1957
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001958#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001959#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001960#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001961#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001962#endif
1963
1964#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1965#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1966#else
1967#define ST_BIRTHTIME_IDX ST_GEN_IDX
1968#endif
1969
Zachary Ware63f277b2014-06-19 09:46:37 -05001970#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1971#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
1972#else
1973#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
1974#endif
1975
jcea6c51d512018-01-28 14:00:08 +01001976#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1977#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
1978#else
1979#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
1980#endif
1981
Steve Dower9eb3d542019-08-21 15:52:42 -07001982#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1983#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
1984#else
1985#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
1986#endif
1987
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001988static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001989 "stat_result", /* name */
1990 stat_result__doc__, /* doc */
1991 stat_result_fields,
1992 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001993};
1994
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001995PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001996"statvfs_result: Result from statvfs or fstatvfs.\n\n\
1997This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001998 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00001999or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002000\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002001See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002002
2003static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002004 {"f_bsize", },
2005 {"f_frsize", },
2006 {"f_blocks", },
2007 {"f_bfree", },
2008 {"f_bavail", },
2009 {"f_files", },
2010 {"f_ffree", },
2011 {"f_favail", },
2012 {"f_flag", },
2013 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002014 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002015 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002016};
2017
2018static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002019 "statvfs_result", /* name */
2020 statvfs_result__doc__, /* doc */
2021 statvfs_result_fields,
2022 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002023};
2024
Ross Lagerwall7807c352011-03-17 20:20:30 +02002025#if defined(HAVE_WAITID) && !defined(__APPLE__)
2026PyDoc_STRVAR(waitid_result__doc__,
2027"waitid_result: Result from waitid.\n\n\
2028This object may be accessed either as a tuple of\n\
2029 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2030or via the attributes si_pid, si_uid, and so on.\n\
2031\n\
2032See os.waitid for more information.");
2033
2034static PyStructSequence_Field waitid_result_fields[] = {
2035 {"si_pid", },
2036 {"si_uid", },
2037 {"si_signo", },
2038 {"si_status", },
2039 {"si_code", },
2040 {0}
2041};
2042
2043static PyStructSequence_Desc waitid_result_desc = {
2044 "waitid_result", /* name */
2045 waitid_result__doc__, /* doc */
2046 waitid_result_fields,
2047 5
2048};
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002049static PyTypeObject* WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +02002050#endif
2051
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002052static int initialized;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002053static PyTypeObject* StatResultType;
2054static PyTypeObject* StatVFSResultType;
William Orr81574b82018-10-01 22:19:56 -07002055#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002056static PyTypeObject* SchedParamType;
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002057#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002058static newfunc structseq_new;
2059
2060static PyObject *
2061statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2062{
Victor Stinner8c62be82010-05-06 00:08:46 +00002063 PyStructSequence *result;
2064 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002065
Victor Stinner8c62be82010-05-06 00:08:46 +00002066 result = (PyStructSequence*)structseq_new(type, args, kwds);
2067 if (!result)
2068 return NULL;
2069 /* If we have been initialized from a tuple,
2070 st_?time might be set to None. Initialize it
2071 from the int slots. */
2072 for (i = 7; i <= 9; i++) {
2073 if (result->ob_item[i+3] == Py_None) {
2074 Py_DECREF(Py_None);
2075 Py_INCREF(result->ob_item[i]);
2076 result->ob_item[i+3] = result->ob_item[i];
2077 }
2078 }
2079 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002080}
2081
2082
Larry Hastings6fe20b32012-04-19 15:07:49 -07002083static PyObject *billion = NULL;
2084
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002085static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002086fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002087{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002088 PyObject *s = _PyLong_FromTime_t(sec);
2089 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2090 PyObject *s_in_ns = NULL;
2091 PyObject *ns_total = NULL;
2092 PyObject *float_s = NULL;
2093
2094 if (!(s && ns_fractional))
2095 goto exit;
2096
2097 s_in_ns = PyNumber_Multiply(s, billion);
2098 if (!s_in_ns)
2099 goto exit;
2100
2101 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2102 if (!ns_total)
2103 goto exit;
2104
Victor Stinner01b5aab2017-10-24 02:02:00 -07002105 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2106 if (!float_s) {
2107 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002108 }
2109
2110 PyStructSequence_SET_ITEM(v, index, s);
2111 PyStructSequence_SET_ITEM(v, index+3, float_s);
2112 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2113 s = NULL;
2114 float_s = NULL;
2115 ns_total = NULL;
2116exit:
2117 Py_XDECREF(s);
2118 Py_XDECREF(ns_fractional);
2119 Py_XDECREF(s_in_ns);
2120 Py_XDECREF(ns_total);
2121 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002122}
2123
Tim Peters5aa91602002-01-30 05:46:57 +00002124/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002125 (used by posix_stat() and posix_fstat()) */
2126static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002127_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002128{
Victor Stinner8c62be82010-05-06 00:08:46 +00002129 unsigned long ansec, mnsec, cnsec;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002130 PyObject *v = PyStructSequence_New(StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002131 if (v == NULL)
2132 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002133
Victor Stinner8c62be82010-05-06 00:08:46 +00002134 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002135 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002136 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002137#ifdef MS_WINDOWS
2138 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002139#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002140 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002141#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002142 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002143#if defined(MS_WINDOWS)
2144 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2145 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2146#else
2147 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2148 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2149#endif
xdegaye50e86032017-05-22 11:15:08 +02002150 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2151 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002152
Martin v. Löwis14694662006-02-03 12:54:16 +00002153#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002154 ansec = st->st_atim.tv_nsec;
2155 mnsec = st->st_mtim.tv_nsec;
2156 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002157#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002158 ansec = st->st_atimespec.tv_nsec;
2159 mnsec = st->st_mtimespec.tv_nsec;
2160 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002161#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002162 ansec = st->st_atime_nsec;
2163 mnsec = st->st_mtime_nsec;
2164 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002165#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002166 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002167#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002168 fill_time(v, 7, st->st_atime, ansec);
2169 fill_time(v, 8, st->st_mtime, mnsec);
2170 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002171
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002172#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002173 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2174 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002175#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002176#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002177 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2178 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002179#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002180#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002181 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2182 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002183#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002184#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002185 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2186 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002187#endif
2188#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002189 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002190 PyObject *val;
2191 unsigned long bsec,bnsec;
2192 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002193#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002194 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002195#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002196 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002197#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002198 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002199 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2200 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002201 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002202#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002203#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002204 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2205 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002206#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002207#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2208 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2209 PyLong_FromUnsignedLong(st->st_file_attributes));
2210#endif
jcea6c51d512018-01-28 14:00:08 +01002211#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2212 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2213 PyUnicode_FromString(st->st_fstype));
2214#endif
Steve Dower9eb3d542019-08-21 15:52:42 -07002215#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2216 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2217 PyLong_FromUnsignedLong(st->st_reparse_tag));
2218#endif
Fred Drake699f3522000-06-29 21:12:41 +00002219
Victor Stinner8c62be82010-05-06 00:08:46 +00002220 if (PyErr_Occurred()) {
2221 Py_DECREF(v);
2222 return NULL;
2223 }
Fred Drake699f3522000-06-29 21:12:41 +00002224
Victor Stinner8c62be82010-05-06 00:08:46 +00002225 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002226}
2227
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002228/* POSIX methods */
2229
Guido van Rossum94f6f721999-01-06 18:42:14 +00002230
2231static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002232posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002233 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002234{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002235 STRUCT_STAT st;
2236 int result;
2237
2238#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2239 if (follow_symlinks_specified(function_name, follow_symlinks))
2240 return NULL;
2241#endif
2242
2243 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2244 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2245 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2246 return NULL;
2247
2248 Py_BEGIN_ALLOW_THREADS
2249 if (path->fd != -1)
2250 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002251#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002252 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002253 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002254 else
Steve Dowercc16be82016-09-08 10:35:16 -07002255 result = win32_lstat(path->wide, &st);
2256#else
2257 else
2258#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002259 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2260 result = LSTAT(path->narrow, &st);
2261 else
Steve Dowercc16be82016-09-08 10:35:16 -07002262#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002263#ifdef HAVE_FSTATAT
2264 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2265 result = fstatat(dir_fd, path->narrow, &st,
2266 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2267 else
Steve Dowercc16be82016-09-08 10:35:16 -07002268#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002269 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002270#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002271 Py_END_ALLOW_THREADS
2272
Victor Stinner292c8352012-10-30 02:17:38 +01002273 if (result != 0) {
2274 return path_error(path);
2275 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002276
2277 return _pystat_fromstructstat(&st);
2278}
2279
Larry Hastings2f936352014-08-05 14:04:04 +10002280/*[python input]
2281
2282for s in """
2283
2284FACCESSAT
2285FCHMODAT
2286FCHOWNAT
2287FSTATAT
2288LINKAT
2289MKDIRAT
2290MKFIFOAT
2291MKNODAT
2292OPENAT
2293READLINKAT
2294SYMLINKAT
2295UNLINKAT
2296
2297""".strip().split():
2298 s = s.strip()
2299 print("""
2300#ifdef HAVE_{s}
2301 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002302#else
Larry Hastings2f936352014-08-05 14:04:04 +10002303 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002304#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002305""".rstrip().format(s=s))
2306
2307for s in """
2308
2309FCHDIR
2310FCHMOD
2311FCHOWN
2312FDOPENDIR
2313FEXECVE
2314FPATHCONF
2315FSTATVFS
2316FTRUNCATE
2317
2318""".strip().split():
2319 s = s.strip()
2320 print("""
2321#ifdef HAVE_{s}
2322 #define PATH_HAVE_{s} 1
2323#else
2324 #define PATH_HAVE_{s} 0
2325#endif
2326
2327""".rstrip().format(s=s))
2328[python start generated code]*/
2329
2330#ifdef HAVE_FACCESSAT
2331 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2332#else
2333 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2334#endif
2335
2336#ifdef HAVE_FCHMODAT
2337 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2338#else
2339 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2340#endif
2341
2342#ifdef HAVE_FCHOWNAT
2343 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2344#else
2345 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2346#endif
2347
2348#ifdef HAVE_FSTATAT
2349 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2350#else
2351 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2352#endif
2353
2354#ifdef HAVE_LINKAT
2355 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2356#else
2357 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2358#endif
2359
2360#ifdef HAVE_MKDIRAT
2361 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2362#else
2363 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2364#endif
2365
2366#ifdef HAVE_MKFIFOAT
2367 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2368#else
2369 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2370#endif
2371
2372#ifdef HAVE_MKNODAT
2373 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2374#else
2375 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2376#endif
2377
2378#ifdef HAVE_OPENAT
2379 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2380#else
2381 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2382#endif
2383
2384#ifdef HAVE_READLINKAT
2385 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2386#else
2387 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2388#endif
2389
2390#ifdef HAVE_SYMLINKAT
2391 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2392#else
2393 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2394#endif
2395
2396#ifdef HAVE_UNLINKAT
2397 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2398#else
2399 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2400#endif
2401
2402#ifdef HAVE_FCHDIR
2403 #define PATH_HAVE_FCHDIR 1
2404#else
2405 #define PATH_HAVE_FCHDIR 0
2406#endif
2407
2408#ifdef HAVE_FCHMOD
2409 #define PATH_HAVE_FCHMOD 1
2410#else
2411 #define PATH_HAVE_FCHMOD 0
2412#endif
2413
2414#ifdef HAVE_FCHOWN
2415 #define PATH_HAVE_FCHOWN 1
2416#else
2417 #define PATH_HAVE_FCHOWN 0
2418#endif
2419
2420#ifdef HAVE_FDOPENDIR
2421 #define PATH_HAVE_FDOPENDIR 1
2422#else
2423 #define PATH_HAVE_FDOPENDIR 0
2424#endif
2425
2426#ifdef HAVE_FEXECVE
2427 #define PATH_HAVE_FEXECVE 1
2428#else
2429 #define PATH_HAVE_FEXECVE 0
2430#endif
2431
2432#ifdef HAVE_FPATHCONF
2433 #define PATH_HAVE_FPATHCONF 1
2434#else
2435 #define PATH_HAVE_FPATHCONF 0
2436#endif
2437
2438#ifdef HAVE_FSTATVFS
2439 #define PATH_HAVE_FSTATVFS 1
2440#else
2441 #define PATH_HAVE_FSTATVFS 0
2442#endif
2443
2444#ifdef HAVE_FTRUNCATE
2445 #define PATH_HAVE_FTRUNCATE 1
2446#else
2447 #define PATH_HAVE_FTRUNCATE 0
2448#endif
2449/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002450
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002451#ifdef MS_WINDOWS
2452 #undef PATH_HAVE_FTRUNCATE
2453 #define PATH_HAVE_FTRUNCATE 1
2454#endif
Larry Hastings31826802013-10-19 00:09:25 -07002455
Larry Hastings61272b72014-01-07 12:41:53 -08002456/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002457
2458class path_t_converter(CConverter):
2459
2460 type = "path_t"
2461 impl_by_reference = True
2462 parse_by_reference = True
2463
2464 converter = 'path_converter'
2465
2466 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002467 # right now path_t doesn't support default values.
2468 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002469 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002470 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002471
Larry Hastings2f936352014-08-05 14:04:04 +10002472 if self.c_default not in (None, 'Py_None'):
2473 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002474
2475 self.nullable = nullable
2476 self.allow_fd = allow_fd
2477
Larry Hastings7726ac92014-01-31 22:03:12 -08002478 def pre_render(self):
2479 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002480 if isinstance(value, str):
2481 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002482 return str(int(bool(value)))
2483
2484 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002485 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002486 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002487 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002488 strify(self.nullable),
2489 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002490 )
2491
2492 def cleanup(self):
2493 return "path_cleanup(&" + self.name + ");\n"
2494
2495
2496class dir_fd_converter(CConverter):
2497 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002498
Larry Hastings2f936352014-08-05 14:04:04 +10002499 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002500 if self.default in (unspecified, None):
2501 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002502 if isinstance(requires, str):
2503 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2504 else:
2505 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002506
Larry Hastings2f936352014-08-05 14:04:04 +10002507class fildes_converter(CConverter):
2508 type = 'int'
2509 converter = 'fildes_converter'
2510
2511class uid_t_converter(CConverter):
2512 type = "uid_t"
2513 converter = '_Py_Uid_Converter'
2514
2515class gid_t_converter(CConverter):
2516 type = "gid_t"
2517 converter = '_Py_Gid_Converter'
2518
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002519class dev_t_converter(CConverter):
2520 type = 'dev_t'
2521 converter = '_Py_Dev_Converter'
2522
2523class dev_t_return_converter(unsigned_long_return_converter):
2524 type = 'dev_t'
2525 conversion_fn = '_PyLong_FromDev'
2526 unsigned_cast = '(dev_t)'
2527
Larry Hastings2f936352014-08-05 14:04:04 +10002528class FSConverter_converter(CConverter):
2529 type = 'PyObject *'
2530 converter = 'PyUnicode_FSConverter'
2531 def converter_init(self):
2532 if self.default is not unspecified:
2533 fail("FSConverter_converter does not support default values")
2534 self.c_default = 'NULL'
2535
2536 def cleanup(self):
2537 return "Py_XDECREF(" + self.name + ");\n"
2538
2539class pid_t_converter(CConverter):
2540 type = 'pid_t'
2541 format_unit = '" _Py_PARSE_PID "'
2542
2543class idtype_t_converter(int_converter):
2544 type = 'idtype_t'
2545
2546class id_t_converter(CConverter):
2547 type = 'id_t'
2548 format_unit = '" _Py_PARSE_PID "'
2549
Benjamin Petersonca470632016-09-06 13:47:26 -07002550class intptr_t_converter(CConverter):
2551 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002552 format_unit = '" _Py_PARSE_INTPTR "'
2553
2554class Py_off_t_converter(CConverter):
2555 type = 'Py_off_t'
2556 converter = 'Py_off_t_converter'
2557
2558class Py_off_t_return_converter(long_return_converter):
2559 type = 'Py_off_t'
2560 conversion_fn = 'PyLong_FromPy_off_t'
2561
2562class path_confname_converter(CConverter):
2563 type="int"
2564 converter="conv_path_confname"
2565
2566class confstr_confname_converter(path_confname_converter):
2567 converter='conv_confstr_confname'
2568
2569class sysconf_confname_converter(path_confname_converter):
2570 converter="conv_sysconf_confname"
2571
2572class sched_param_converter(CConverter):
2573 type = 'struct sched_param'
2574 converter = 'convert_sched_param'
2575 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002576
Larry Hastings61272b72014-01-07 12:41:53 -08002577[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002578/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002579
Larry Hastings61272b72014-01-07 12:41:53 -08002580/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002581
Larry Hastings2a727912014-01-16 11:32:01 -08002582os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002583
2584 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002585 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002586 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002587
2588 *
2589
Larry Hastings2f936352014-08-05 14:04:04 +10002590 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002591 If not None, it should be a file descriptor open to a directory,
2592 and path should be a relative string; path will then be relative to
2593 that directory.
2594
2595 follow_symlinks: bool = True
2596 If False, and the last element of the path is a symbolic link,
2597 stat will examine the symbolic link itself instead of the file
2598 the link points to.
2599
2600Perform a stat system call on the given path.
2601
2602dir_fd and follow_symlinks may not be implemented
2603 on your platform. If they are unavailable, using them will raise a
2604 NotImplementedError.
2605
2606It's an error to use dir_fd or follow_symlinks when specifying path as
2607 an open file descriptor.
2608
Larry Hastings61272b72014-01-07 12:41:53 -08002609[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002610
Larry Hastings31826802013-10-19 00:09:25 -07002611static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002612os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002613/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002614{
2615 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2616}
2617
Larry Hastings2f936352014-08-05 14:04:04 +10002618
2619/*[clinic input]
2620os.lstat
2621
2622 path : path_t
2623
2624 *
2625
2626 dir_fd : dir_fd(requires='fstatat') = None
2627
2628Perform a stat system call on the given path, without following symbolic links.
2629
2630Like stat(), but do not follow symbolic links.
2631Equivalent to stat(path, follow_symlinks=False).
2632[clinic start generated code]*/
2633
Larry Hastings2f936352014-08-05 14:04:04 +10002634static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002635os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2636/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002637{
2638 int follow_symlinks = 0;
2639 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2640}
Larry Hastings31826802013-10-19 00:09:25 -07002641
Larry Hastings2f936352014-08-05 14:04:04 +10002642
Larry Hastings61272b72014-01-07 12:41:53 -08002643/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002644os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002645
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002646 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002647 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002648
2649 mode: int
2650 Operating-system mode bitfield. Can be F_OK to test existence,
2651 or the inclusive-OR of R_OK, W_OK, and X_OK.
2652
2653 *
2654
Larry Hastings2f936352014-08-05 14:04:04 +10002655 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002656 If not None, it should be a file descriptor open to a directory,
2657 and path should be relative; path will then be relative to that
2658 directory.
2659
2660 effective_ids: bool = False
2661 If True, access will use the effective uid/gid instead of
2662 the real uid/gid.
2663
2664 follow_symlinks: bool = True
2665 If False, and the last element of the path is a symbolic link,
2666 access will examine the symbolic link itself instead of the file
2667 the link points to.
2668
2669Use the real uid/gid to test for access to a path.
2670
2671{parameters}
2672dir_fd, effective_ids, and follow_symlinks may not be implemented
2673 on your platform. If they are unavailable, using them will raise a
2674 NotImplementedError.
2675
2676Note that most operations will use the effective uid/gid, therefore this
2677 routine can be used in a suid/sgid environment to test if the invoking user
2678 has the specified access to the path.
2679
Larry Hastings61272b72014-01-07 12:41:53 -08002680[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002681
Larry Hastings2f936352014-08-05 14:04:04 +10002682static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002683os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002684 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002685/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002686{
Larry Hastings2f936352014-08-05 14:04:04 +10002687 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002688
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002689#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002690 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002691#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002692 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002693#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002694
Larry Hastings9cf065c2012-06-22 16:30:09 -07002695#ifndef HAVE_FACCESSAT
2696 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002697 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002698
2699 if (effective_ids) {
2700 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002701 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002702 }
2703#endif
2704
2705#ifdef MS_WINDOWS
2706 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002707 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002708 Py_END_ALLOW_THREADS
2709
2710 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002711 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002712 * * we didn't get a -1, and
2713 * * write access wasn't requested,
2714 * * or the file isn't read-only,
2715 * * or it's a directory.
2716 * (Directories cannot be read-only on Windows.)
2717 */
Larry Hastings2f936352014-08-05 14:04:04 +10002718 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002719 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002720 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002721 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002722#else
2723
2724 Py_BEGIN_ALLOW_THREADS
2725#ifdef HAVE_FACCESSAT
2726 if ((dir_fd != DEFAULT_DIR_FD) ||
2727 effective_ids ||
2728 !follow_symlinks) {
2729 int flags = 0;
2730 if (!follow_symlinks)
2731 flags |= AT_SYMLINK_NOFOLLOW;
2732 if (effective_ids)
2733 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002734 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002735 }
2736 else
2737#endif
Larry Hastings31826802013-10-19 00:09:25 -07002738 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002739 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002740 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002741#endif
2742
Larry Hastings9cf065c2012-06-22 16:30:09 -07002743 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002744}
2745
Guido van Rossumd371ff11999-01-25 16:12:23 +00002746#ifndef F_OK
2747#define F_OK 0
2748#endif
2749#ifndef R_OK
2750#define R_OK 4
2751#endif
2752#ifndef W_OK
2753#define W_OK 2
2754#endif
2755#ifndef X_OK
2756#define X_OK 1
2757#endif
2758
Larry Hastings31826802013-10-19 00:09:25 -07002759
Guido van Rossumd371ff11999-01-25 16:12:23 +00002760#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002761/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002762os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002763
2764 fd: int
2765 Integer file descriptor handle.
2766
2767 /
2768
2769Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002770[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002771
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002772static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002773os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002774/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002775{
2776 char *ret;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002777
Larry Hastings31826802013-10-19 00:09:25 -07002778 ret = ttyname(fd);
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002779 if (ret == NULL) {
2780 return posix_error();
2781 }
2782 return PyUnicode_DecodeFSDefault(ret);
Guido van Rossum94f6f721999-01-06 18:42:14 +00002783}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002784#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002785
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002786#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002787/*[clinic input]
2788os.ctermid
2789
2790Return the name of the controlling terminal for this process.
2791[clinic start generated code]*/
2792
Larry Hastings2f936352014-08-05 14:04:04 +10002793static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002794os_ctermid_impl(PyObject *module)
2795/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002796{
Victor Stinner8c62be82010-05-06 00:08:46 +00002797 char *ret;
2798 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002799
Greg Wardb48bc172000-03-01 21:51:56 +00002800#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002801 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002802#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002803 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002804#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002805 if (ret == NULL)
2806 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002807 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002808}
Larry Hastings2f936352014-08-05 14:04:04 +10002809#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002810
Larry Hastings2f936352014-08-05 14:04:04 +10002811
2812/*[clinic input]
2813os.chdir
2814
2815 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2816
2817Change the current working directory to the specified path.
2818
2819path may always be specified as a string.
2820On some platforms, path may also be specified as an open file descriptor.
2821 If this functionality is unavailable, using it raises an exception.
2822[clinic start generated code]*/
2823
Larry Hastings2f936352014-08-05 14:04:04 +10002824static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002825os_chdir_impl(PyObject *module, path_t *path)
2826/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002827{
2828 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002829
Steve Dowera00b5be2020-02-13 08:30:27 +00002830 if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
2831 return NULL;
2832 }
2833
Larry Hastings9cf065c2012-06-22 16:30:09 -07002834 Py_BEGIN_ALLOW_THREADS
2835#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002836 /* on unix, success = 0, on windows, success = !0 */
2837 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002838#else
2839#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002840 if (path->fd != -1)
2841 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002842 else
2843#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002844 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002845#endif
2846 Py_END_ALLOW_THREADS
2847
2848 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002849 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002850 }
2851
Larry Hastings2f936352014-08-05 14:04:04 +10002852 Py_RETURN_NONE;
2853}
2854
2855
2856#ifdef HAVE_FCHDIR
2857/*[clinic input]
2858os.fchdir
2859
2860 fd: fildes
2861
2862Change to the directory of the given file descriptor.
2863
2864fd must be opened on a directory, not a file.
2865Equivalent to os.chdir(fd).
2866
2867[clinic start generated code]*/
2868
Fred Drake4d1e64b2002-04-15 19:40:07 +00002869static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002870os_fchdir_impl(PyObject *module, int fd)
2871/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002872{
Steve Dowera00b5be2020-02-13 08:30:27 +00002873 if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
2874 return NULL;
2875 }
Larry Hastings2f936352014-08-05 14:04:04 +10002876 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002877}
2878#endif /* HAVE_FCHDIR */
2879
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002880
Larry Hastings2f936352014-08-05 14:04:04 +10002881/*[clinic input]
2882os.chmod
2883
2884 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002885 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002886 On some platforms, path may also be specified as an open file descriptor.
2887 If this functionality is unavailable, using it raises an exception.
2888
2889 mode: int
2890 Operating-system mode bitfield.
2891
2892 *
2893
2894 dir_fd : dir_fd(requires='fchmodat') = None
2895 If not None, it should be a file descriptor open to a directory,
2896 and path should be relative; path will then be relative to that
2897 directory.
2898
2899 follow_symlinks: bool = True
2900 If False, and the last element of the path is a symbolic link,
2901 chmod will modify the symbolic link itself instead of the file
2902 the link points to.
2903
2904Change the access permissions of a file.
2905
2906It is an error to use dir_fd or follow_symlinks when specifying path as
2907 an open file descriptor.
2908dir_fd and follow_symlinks may not be implemented on your platform.
2909 If they are unavailable, using them will raise a NotImplementedError.
2910
2911[clinic start generated code]*/
2912
Larry Hastings2f936352014-08-05 14:04:04 +10002913static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002914os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002915 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002916/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002917{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002918 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002919
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002920#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002921 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002922#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00002923
Larry Hastings9cf065c2012-06-22 16:30:09 -07002924#ifdef HAVE_FCHMODAT
2925 int fchmodat_nofollow_unsupported = 0;
2926#endif
2927
Larry Hastings9cf065c2012-06-22 16:30:09 -07002928#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
2929 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002930 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002931#endif
2932
Steve Dowera00b5be2020-02-13 08:30:27 +00002933 if (PySys_Audit("os.chmod", "Oii", path->object, mode,
2934 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
2935 return NULL;
2936 }
2937
Larry Hastings9cf065c2012-06-22 16:30:09 -07002938#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002939 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002940 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01002941 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002942 result = 0;
2943 else {
2944 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00002945 attr &= ~FILE_ATTRIBUTE_READONLY;
2946 else
2947 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07002948 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002949 }
2950 Py_END_ALLOW_THREADS
2951
2952 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002953 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002954 }
2955#else /* MS_WINDOWS */
2956 Py_BEGIN_ALLOW_THREADS
2957#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002958 if (path->fd != -1)
2959 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002960 else
2961#endif
2962#ifdef HAVE_LCHMOD
2963 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10002964 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002965 else
2966#endif
2967#ifdef HAVE_FCHMODAT
2968 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
2969 /*
2970 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
2971 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002972 * and then says it isn't implemented yet.
2973 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002974 *
2975 * Once it is supported, os.chmod will automatically
2976 * support dir_fd and follow_symlinks=False. (Hopefully.)
2977 * Until then, we need to be careful what exception we raise.
2978 */
Larry Hastings2f936352014-08-05 14:04:04 +10002979 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002980 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2981 /*
2982 * But wait! We can't throw the exception without allowing threads,
2983 * and we can't do that in this nested scope. (Macro trickery, sigh.)
2984 */
2985 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002986 result &&
2987 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
2988 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00002989 }
2990 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00002991#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002992 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002993 Py_END_ALLOW_THREADS
2994
2995 if (result) {
2996#ifdef HAVE_FCHMODAT
2997 if (fchmodat_nofollow_unsupported) {
2998 if (dir_fd != DEFAULT_DIR_FD)
2999 dir_fd_and_follow_symlinks_invalid("chmod",
3000 dir_fd, follow_symlinks);
3001 else
3002 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003003 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003004 }
3005 else
3006#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003007 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003008 }
3009#endif
3010
Larry Hastings2f936352014-08-05 14:04:04 +10003011 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003012}
3013
Larry Hastings9cf065c2012-06-22 16:30:09 -07003014
Christian Heimes4e30a842007-11-30 22:12:06 +00003015#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003016/*[clinic input]
3017os.fchmod
3018
3019 fd: int
3020 mode: int
3021
3022Change the access permissions of the file given by file descriptor fd.
3023
3024Equivalent to os.chmod(fd, mode).
3025[clinic start generated code]*/
3026
Larry Hastings2f936352014-08-05 14:04:04 +10003027static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003028os_fchmod_impl(PyObject *module, int fd, int mode)
3029/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003030{
3031 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003032 int async_err = 0;
3033
Steve Dowera00b5be2020-02-13 08:30:27 +00003034 if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
3035 return NULL;
3036 }
3037
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003038 do {
3039 Py_BEGIN_ALLOW_THREADS
3040 res = fchmod(fd, mode);
3041 Py_END_ALLOW_THREADS
3042 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3043 if (res != 0)
3044 return (!async_err) ? posix_error() : NULL;
3045
Victor Stinner8c62be82010-05-06 00:08:46 +00003046 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003047}
3048#endif /* HAVE_FCHMOD */
3049
Larry Hastings2f936352014-08-05 14:04:04 +10003050
Christian Heimes4e30a842007-11-30 22:12:06 +00003051#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003052/*[clinic input]
3053os.lchmod
3054
3055 path: path_t
3056 mode: int
3057
3058Change the access permissions of a file, without following symbolic links.
3059
3060If path is a symlink, this affects the link itself rather than the target.
3061Equivalent to chmod(path, mode, follow_symlinks=False)."
3062[clinic start generated code]*/
3063
Larry Hastings2f936352014-08-05 14:04:04 +10003064static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003065os_lchmod_impl(PyObject *module, path_t *path, int mode)
3066/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003067{
Victor Stinner8c62be82010-05-06 00:08:46 +00003068 int res;
Steve Dowera00b5be2020-02-13 08:30:27 +00003069 if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
3070 return NULL;
3071 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003072 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003073 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003074 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003075 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003076 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003077 return NULL;
3078 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003079 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003080}
3081#endif /* HAVE_LCHMOD */
3082
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003083
Thomas Wouterscf297e42007-02-23 15:07:44 +00003084#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003085/*[clinic input]
3086os.chflags
3087
3088 path: path_t
3089 flags: unsigned_long(bitwise=True)
3090 follow_symlinks: bool=True
3091
3092Set file flags.
3093
3094If follow_symlinks is False, and the last element of the path is a symbolic
3095 link, chflags will change flags on the symbolic link itself instead of the
3096 file the link points to.
3097follow_symlinks may not be implemented on your platform. If it is
3098unavailable, using it will raise a NotImplementedError.
3099
3100[clinic start generated code]*/
3101
Larry Hastings2f936352014-08-05 14:04:04 +10003102static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003103os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003104 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003105/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003106{
3107 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003108
3109#ifndef HAVE_LCHFLAGS
3110 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003111 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003112#endif
3113
Steve Dowera00b5be2020-02-13 08:30:27 +00003114 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3115 return NULL;
3116 }
3117
Victor Stinner8c62be82010-05-06 00:08:46 +00003118 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003119#ifdef HAVE_LCHFLAGS
3120 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003121 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003122 else
3123#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003124 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003125 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003126
Larry Hastings2f936352014-08-05 14:04:04 +10003127 if (result)
3128 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003129
Larry Hastings2f936352014-08-05 14:04:04 +10003130 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003131}
3132#endif /* HAVE_CHFLAGS */
3133
Larry Hastings2f936352014-08-05 14:04:04 +10003134
Thomas Wouterscf297e42007-02-23 15:07:44 +00003135#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003136/*[clinic input]
3137os.lchflags
3138
3139 path: path_t
3140 flags: unsigned_long(bitwise=True)
3141
3142Set file flags.
3143
3144This function will not follow symbolic links.
3145Equivalent to chflags(path, flags, follow_symlinks=False).
3146[clinic start generated code]*/
3147
Larry Hastings2f936352014-08-05 14:04:04 +10003148static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003149os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3150/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003151{
Victor Stinner8c62be82010-05-06 00:08:46 +00003152 int res;
Steve Dowera00b5be2020-02-13 08:30:27 +00003153 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3154 return NULL;
3155 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003156 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003157 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003158 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003159 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003160 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003161 }
Victor Stinner292c8352012-10-30 02:17:38 +01003162 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003163}
3164#endif /* HAVE_LCHFLAGS */
3165
Larry Hastings2f936352014-08-05 14:04:04 +10003166
Martin v. Löwis244edc82001-10-04 22:44:26 +00003167#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003168/*[clinic input]
3169os.chroot
3170 path: path_t
3171
3172Change root directory to path.
3173
3174[clinic start generated code]*/
3175
Larry Hastings2f936352014-08-05 14:04:04 +10003176static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003177os_chroot_impl(PyObject *module, path_t *path)
3178/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003179{
3180 int res;
3181 Py_BEGIN_ALLOW_THREADS
3182 res = chroot(path->narrow);
3183 Py_END_ALLOW_THREADS
3184 if (res < 0)
3185 return path_error(path);
3186 Py_RETURN_NONE;
3187}
3188#endif /* HAVE_CHROOT */
3189
Martin v. Löwis244edc82001-10-04 22:44:26 +00003190
Guido van Rossum21142a01999-01-08 21:05:37 +00003191#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003192/*[clinic input]
3193os.fsync
3194
3195 fd: fildes
3196
3197Force write of fd to disk.
3198[clinic start generated code]*/
3199
Larry Hastings2f936352014-08-05 14:04:04 +10003200static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003201os_fsync_impl(PyObject *module, int fd)
3202/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003203{
3204 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003205}
3206#endif /* HAVE_FSYNC */
3207
Larry Hastings2f936352014-08-05 14:04:04 +10003208
Ross Lagerwall7807c352011-03-17 20:20:30 +02003209#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003210/*[clinic input]
3211os.sync
3212
3213Force write of everything to disk.
3214[clinic start generated code]*/
3215
Larry Hastings2f936352014-08-05 14:04:04 +10003216static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003217os_sync_impl(PyObject *module)
3218/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003219{
3220 Py_BEGIN_ALLOW_THREADS
3221 sync();
3222 Py_END_ALLOW_THREADS
3223 Py_RETURN_NONE;
3224}
Larry Hastings2f936352014-08-05 14:04:04 +10003225#endif /* HAVE_SYNC */
3226
Ross Lagerwall7807c352011-03-17 20:20:30 +02003227
Guido van Rossum21142a01999-01-08 21:05:37 +00003228#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003229#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003230extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3231#endif
3232
Larry Hastings2f936352014-08-05 14:04:04 +10003233/*[clinic input]
3234os.fdatasync
3235
3236 fd: fildes
3237
3238Force write of fd to disk without forcing update of metadata.
3239[clinic start generated code]*/
3240
Larry Hastings2f936352014-08-05 14:04:04 +10003241static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003242os_fdatasync_impl(PyObject *module, int fd)
3243/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003244{
3245 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003246}
3247#endif /* HAVE_FDATASYNC */
3248
3249
Fredrik Lundh10723342000-07-10 16:38:09 +00003250#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003251/*[clinic input]
3252os.chown
3253
3254 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003255 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003256
3257 uid: uid_t
3258
3259 gid: gid_t
3260
3261 *
3262
3263 dir_fd : dir_fd(requires='fchownat') = None
3264 If not None, it should be a file descriptor open to a directory,
3265 and path should be relative; path will then be relative to that
3266 directory.
3267
3268 follow_symlinks: bool = True
3269 If False, and the last element of the path is a symbolic link,
3270 stat will examine the symbolic link itself instead of the file
3271 the link points to.
3272
3273Change the owner and group id of path to the numeric uid and gid.\
3274
3275path may always be specified as a string.
3276On some platforms, path may also be specified as an open file descriptor.
3277 If this functionality is unavailable, using it raises an exception.
3278If dir_fd is not None, it should be a file descriptor open to a directory,
3279 and path should be relative; path will then be relative to that directory.
3280If follow_symlinks is False, and the last element of the path is a symbolic
3281 link, chown will modify the symbolic link itself instead of the file the
3282 link points to.
3283It is an error to use dir_fd or follow_symlinks when specifying path as
3284 an open file descriptor.
3285dir_fd and follow_symlinks may not be implemented on your platform.
3286 If they are unavailable, using them will raise a NotImplementedError.
3287
3288[clinic start generated code]*/
3289
Larry Hastings2f936352014-08-05 14:04:04 +10003290static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003291os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003292 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003293/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003294{
3295 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003296
3297#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3298 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003299 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003300#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003301 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3302 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3303 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003304
3305#ifdef __APPLE__
3306 /*
3307 * This is for Mac OS X 10.3, which doesn't have lchown.
3308 * (But we still have an lchown symbol because of weak-linking.)
3309 * It doesn't have fchownat either. So there's no possibility
3310 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003311 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003312 if ((!follow_symlinks) && (lchown == NULL)) {
3313 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003314 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003315 }
3316#endif
3317
Steve Dowera00b5be2020-02-13 08:30:27 +00003318 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
3319 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3320 return NULL;
3321 }
3322
Victor Stinner8c62be82010-05-06 00:08:46 +00003323 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003324#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003325 if (path->fd != -1)
3326 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003327 else
3328#endif
3329#ifdef HAVE_LCHOWN
3330 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003331 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003332 else
3333#endif
3334#ifdef HAVE_FCHOWNAT
3335 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003336 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003337 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3338 else
3339#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003340 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003341 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003342
Larry Hastings2f936352014-08-05 14:04:04 +10003343 if (result)
3344 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003345
Larry Hastings2f936352014-08-05 14:04:04 +10003346 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003347}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003348#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003349
Larry Hastings2f936352014-08-05 14:04:04 +10003350
Christian Heimes4e30a842007-11-30 22:12:06 +00003351#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003352/*[clinic input]
3353os.fchown
3354
3355 fd: int
3356 uid: uid_t
3357 gid: gid_t
3358
3359Change the owner and group id of the file specified by file descriptor.
3360
3361Equivalent to os.chown(fd, uid, gid).
3362
3363[clinic start generated code]*/
3364
Larry Hastings2f936352014-08-05 14:04:04 +10003365static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003366os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3367/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003368{
Victor Stinner8c62be82010-05-06 00:08:46 +00003369 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003370 int async_err = 0;
3371
Steve Dowera00b5be2020-02-13 08:30:27 +00003372 if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
3373 return NULL;
3374 }
3375
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003376 do {
3377 Py_BEGIN_ALLOW_THREADS
3378 res = fchown(fd, uid, gid);
3379 Py_END_ALLOW_THREADS
3380 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3381 if (res != 0)
3382 return (!async_err) ? posix_error() : NULL;
3383
Victor Stinner8c62be82010-05-06 00:08:46 +00003384 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003385}
3386#endif /* HAVE_FCHOWN */
3387
Larry Hastings2f936352014-08-05 14:04:04 +10003388
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003389#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003390/*[clinic input]
3391os.lchown
3392
3393 path : path_t
3394 uid: uid_t
3395 gid: gid_t
3396
3397Change the owner and group id of path to the numeric uid and gid.
3398
3399This function will not follow symbolic links.
3400Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3401[clinic start generated code]*/
3402
Larry Hastings2f936352014-08-05 14:04:04 +10003403static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003404os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3405/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003406{
Victor Stinner8c62be82010-05-06 00:08:46 +00003407 int res;
Steve Dowera00b5be2020-02-13 08:30:27 +00003408 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
3409 return NULL;
3410 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003411 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003412 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003413 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003414 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003415 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003416 }
Larry Hastings2f936352014-08-05 14:04:04 +10003417 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003418}
3419#endif /* HAVE_LCHOWN */
3420
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003421
Barry Warsaw53699e91996-12-10 23:23:01 +00003422static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003423posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003424{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003425#ifdef MS_WINDOWS
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003426 wchar_t wbuf[MAXPATHLEN];
3427 wchar_t *wbuf2 = wbuf;
3428 DWORD len;
3429
3430 Py_BEGIN_ALLOW_THREADS
3431 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3432 /* If the buffer is large enough, len does not include the
3433 terminating \0. If the buffer is too small, len includes
3434 the space needed for the terminator. */
3435 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Miss Islington (bot)68c1c392019-06-28 09:23:06 -07003436 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003437 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003438 }
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003439 else {
3440 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003441 }
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003442 if (wbuf2) {
3443 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003444 }
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003445 }
3446 Py_END_ALLOW_THREADS
3447
3448 if (!wbuf2) {
3449 PyErr_NoMemory();
3450 return NULL;
3451 }
3452 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003453 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003454 PyMem_RawFree(wbuf2);
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003455 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003456 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003457
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003458 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3459 if (wbuf2 != wbuf) {
3460 PyMem_RawFree(wbuf2);
3461 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003462
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003463 if (use_bytes) {
3464 if (resobj == NULL) {
3465 return NULL;
3466 }
3467 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3468 }
3469
3470 return resobj;
3471#else
3472 const size_t chunk = 1024;
3473
3474 char *buf = NULL;
3475 char *cwd = NULL;
3476 size_t buflen = 0;
3477
Victor Stinner8c62be82010-05-06 00:08:46 +00003478 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003479 do {
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003480 char *newbuf;
3481 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3482 buflen += chunk;
3483 newbuf = PyMem_RawRealloc(buf, buflen);
3484 }
3485 else {
3486 newbuf = NULL;
3487 }
3488 if (newbuf == NULL) {
3489 PyMem_RawFree(buf);
3490 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003491 break;
3492 }
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003493 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003494
Victor Stinner4403d7d2015-04-25 00:16:10 +02003495 cwd = getcwd(buf, buflen);
3496 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003497 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003498
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003499 if (buf == NULL) {
3500 return PyErr_NoMemory();
3501 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003502 if (cwd == NULL) {
3503 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003504 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003505 }
3506
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003507 PyObject *obj;
3508 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003509 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003510 }
3511 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003512 obj = PyUnicode_DecodeFSDefault(buf);
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003513 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003514 PyMem_RawFree(buf);
3515
3516 return obj;
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003517#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003518}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003519
Larry Hastings2f936352014-08-05 14:04:04 +10003520
3521/*[clinic input]
3522os.getcwd
3523
3524Return a unicode string representing the current working directory.
3525[clinic start generated code]*/
3526
Larry Hastings2f936352014-08-05 14:04:04 +10003527static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003528os_getcwd_impl(PyObject *module)
3529/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003530{
3531 return posix_getcwd(0);
3532}
3533
Larry Hastings2f936352014-08-05 14:04:04 +10003534
3535/*[clinic input]
3536os.getcwdb
3537
3538Return a bytes string representing the current working directory.
3539[clinic start generated code]*/
3540
Larry Hastings2f936352014-08-05 14:04:04 +10003541static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003542os_getcwdb_impl(PyObject *module)
3543/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003544{
3545 return posix_getcwd(1);
3546}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003547
Larry Hastings2f936352014-08-05 14:04:04 +10003548
Larry Hastings9cf065c2012-06-22 16:30:09 -07003549#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3550#define HAVE_LINK 1
3551#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003552
Guido van Rossumb6775db1994-08-01 11:34:53 +00003553#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003554/*[clinic input]
3555
3556os.link
3557
3558 src : path_t
3559 dst : path_t
3560 *
3561 src_dir_fd : dir_fd = None
3562 dst_dir_fd : dir_fd = None
3563 follow_symlinks: bool = True
3564
3565Create a hard link to a file.
3566
3567If either src_dir_fd or dst_dir_fd is not None, it should be a file
3568 descriptor open to a directory, and the respective path string (src or dst)
3569 should be relative; the path will then be relative to that directory.
3570If follow_symlinks is False, and the last element of src is a symbolic
3571 link, link will create a link to the symbolic link itself instead of the
3572 file the link points to.
3573src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3574 platform. If they are unavailable, using them will raise a
3575 NotImplementedError.
3576[clinic start generated code]*/
3577
Larry Hastings2f936352014-08-05 14:04:04 +10003578static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003579os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003580 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003581/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003582{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003583#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003584 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003585#else
3586 int result;
3587#endif
3588
Larry Hastings9cf065c2012-06-22 16:30:09 -07003589#ifndef HAVE_LINKAT
3590 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3591 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003592 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003593 }
3594#endif
3595
Steve Dowercc16be82016-09-08 10:35:16 -07003596#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003597 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003598 PyErr_SetString(PyExc_NotImplementedError,
3599 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003600 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003601 }
Steve Dowercc16be82016-09-08 10:35:16 -07003602#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003603
Steve Dowera00b5be2020-02-13 08:30:27 +00003604 if (PySys_Audit("os.link", "OOii", src->object, dst->object,
3605 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
3606 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
3607 return NULL;
3608 }
3609
Brian Curtin1b9df392010-11-24 20:24:31 +00003610#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003611 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003612 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003613 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003614
Larry Hastings2f936352014-08-05 14:04:04 +10003615 if (!result)
3616 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003617#else
3618 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003619#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003620 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3621 (dst_dir_fd != DEFAULT_DIR_FD) ||
3622 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003623 result = linkat(src_dir_fd, src->narrow,
3624 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003625 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3626 else
Steve Dowercc16be82016-09-08 10:35:16 -07003627#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003628 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003629 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003630
Larry Hastings2f936352014-08-05 14:04:04 +10003631 if (result)
3632 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003633#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003634
Larry Hastings2f936352014-08-05 14:04:04 +10003635 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003636}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003637#endif
3638
Brian Curtin1b9df392010-11-24 20:24:31 +00003639
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003640#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003641static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003642_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003643{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003644 PyObject *v;
3645 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3646 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003647 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003648 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003649 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003650 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003651
Steve Dowercc16be82016-09-08 10:35:16 -07003652 WIN32_FIND_DATAW wFileData;
3653 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003654
Steve Dowercc16be82016-09-08 10:35:16 -07003655 if (!path->wide) { /* Default arg: "." */
3656 po_wchars = L".";
3657 len = 1;
3658 } else {
3659 po_wchars = path->wide;
3660 len = wcslen(path->wide);
3661 }
3662 /* The +5 is so we can append "\\*.*\0" */
3663 wnamebuf = PyMem_New(wchar_t, len + 5);
3664 if (!wnamebuf) {
3665 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003666 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003667 }
Steve Dowercc16be82016-09-08 10:35:16 -07003668 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003669 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003670 wchar_t wch = wnamebuf[len-1];
3671 if (wch != SEP && wch != ALTSEP && wch != L':')
3672 wnamebuf[len++] = SEP;
3673 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003674 }
Steve Dowercc16be82016-09-08 10:35:16 -07003675 if ((list = PyList_New(0)) == NULL) {
3676 goto exit;
3677 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003678 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003679 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003680 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003681 if (hFindFile == INVALID_HANDLE_VALUE) {
3682 int error = GetLastError();
3683 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003684 goto exit;
3685 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003686 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003687 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003688 }
3689 do {
3690 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003691 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3692 wcscmp(wFileData.cFileName, L"..") != 0) {
3693 v = PyUnicode_FromWideChar(wFileData.cFileName,
3694 wcslen(wFileData.cFileName));
3695 if (path->narrow && v) {
3696 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3697 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003698 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003699 Py_DECREF(list);
3700 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003701 break;
3702 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003703 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003704 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003705 Py_DECREF(list);
3706 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003707 break;
3708 }
3709 Py_DECREF(v);
3710 }
3711 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003712 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003713 Py_END_ALLOW_THREADS
3714 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3715 it got to the end of the directory. */
3716 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003717 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003718 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003719 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003720 }
3721 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003722
Larry Hastings9cf065c2012-06-22 16:30:09 -07003723exit:
3724 if (hFindFile != INVALID_HANDLE_VALUE) {
3725 if (FindClose(hFindFile) == FALSE) {
3726 if (list != NULL) {
3727 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003728 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003729 }
3730 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003731 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003732 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003733
Larry Hastings9cf065c2012-06-22 16:30:09 -07003734 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003735} /* end of _listdir_windows_no_opendir */
3736
3737#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3738
3739static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003740_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003741{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003742 PyObject *v;
3743 DIR *dirp = NULL;
3744 struct dirent *ep;
3745 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003746#ifdef HAVE_FDOPENDIR
3747 int fd = -1;
3748#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003749
Victor Stinner8c62be82010-05-06 00:08:46 +00003750 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003751#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003752 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003753 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003754 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003755 if (fd == -1)
3756 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003757
Larry Hastingsfdaea062012-06-25 04:42:23 -07003758 return_str = 1;
3759
Larry Hastings9cf065c2012-06-22 16:30:09 -07003760 Py_BEGIN_ALLOW_THREADS
3761 dirp = fdopendir(fd);
3762 Py_END_ALLOW_THREADS
3763 }
3764 else
3765#endif
3766 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003767 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003768 if (path->narrow) {
3769 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003770 /* only return bytes if they specified a bytes-like object */
3771 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003772 }
3773 else {
3774 name = ".";
3775 return_str = 1;
3776 }
3777
Larry Hastings9cf065c2012-06-22 16:30:09 -07003778 Py_BEGIN_ALLOW_THREADS
3779 dirp = opendir(name);
3780 Py_END_ALLOW_THREADS
3781 }
3782
3783 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003784 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003785#ifdef HAVE_FDOPENDIR
3786 if (fd != -1) {
3787 Py_BEGIN_ALLOW_THREADS
3788 close(fd);
3789 Py_END_ALLOW_THREADS
3790 }
3791#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003792 goto exit;
3793 }
3794 if ((list = PyList_New(0)) == NULL) {
3795 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003796 }
3797 for (;;) {
3798 errno = 0;
3799 Py_BEGIN_ALLOW_THREADS
3800 ep = readdir(dirp);
3801 Py_END_ALLOW_THREADS
3802 if (ep == NULL) {
3803 if (errno == 0) {
3804 break;
3805 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003806 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003807 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003808 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003809 }
3810 }
3811 if (ep->d_name[0] == '.' &&
3812 (NAMLEN(ep) == 1 ||
3813 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3814 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003815 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003816 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3817 else
3818 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003819 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003820 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003821 break;
3822 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003823 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003824 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003825 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003826 break;
3827 }
3828 Py_DECREF(v);
3829 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003830
Larry Hastings9cf065c2012-06-22 16:30:09 -07003831exit:
3832 if (dirp != NULL) {
3833 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003834#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003835 if (fd > -1)
3836 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003837#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003838 closedir(dirp);
3839 Py_END_ALLOW_THREADS
3840 }
3841
Larry Hastings9cf065c2012-06-22 16:30:09 -07003842 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003843} /* end of _posix_listdir */
3844#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003845
Larry Hastings2f936352014-08-05 14:04:04 +10003846
3847/*[clinic input]
3848os.listdir
3849
3850 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3851
3852Return a list containing the names of the files in the directory.
3853
BNMetricsb9427072018-11-02 15:20:19 +00003854path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003855 the filenames returned will also be bytes; in all other circumstances
3856 the filenames returned will be str.
3857If path is None, uses the path='.'.
3858On some platforms, path may also be specified as an open file descriptor;\
3859 the file descriptor must refer to a directory.
3860 If this functionality is unavailable, using it raises NotImplementedError.
3861
3862The list is in arbitrary order. It does not include the special
3863entries '.' and '..' even if they are present in the directory.
3864
3865
3866[clinic start generated code]*/
3867
Larry Hastings2f936352014-08-05 14:04:04 +10003868static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003869os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003870/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003871{
Miss Islington (bot)8763d432019-06-24 09:09:47 -07003872 if (PySys_Audit("os.listdir", "O",
3873 path->object ? path->object : Py_None) < 0) {
3874 return NULL;
3875 }
Larry Hastings2f936352014-08-05 14:04:04 +10003876#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3877 return _listdir_windows_no_opendir(path, NULL);
3878#else
3879 return _posix_listdir(path, NULL);
3880#endif
3881}
3882
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003883#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003884/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003885/*[clinic input]
3886os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003887
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003888 path: path_t
3889 /
3890
3891[clinic start generated code]*/
3892
3893static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003894os__getfullpathname_impl(PyObject *module, path_t *path)
3895/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003896{
Steve Dowercc16be82016-09-08 10:35:16 -07003897 wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
3898 wchar_t *wtemp;
3899 DWORD result;
3900 PyObject *v;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003901
Steve Dowercc16be82016-09-08 10:35:16 -07003902 result = GetFullPathNameW(path->wide,
3903 Py_ARRAY_LENGTH(woutbuf),
3904 woutbuf, &wtemp);
3905 if (result > Py_ARRAY_LENGTH(woutbuf)) {
3906 woutbufp = PyMem_New(wchar_t, result);
3907 if (!woutbufp)
3908 return PyErr_NoMemory();
3909 result = GetFullPathNameW(path->wide, result, woutbufp, &wtemp);
Victor Stinner8c62be82010-05-06 00:08:46 +00003910 }
Steve Dowercc16be82016-09-08 10:35:16 -07003911 if (result) {
3912 v = PyUnicode_FromWideChar(woutbufp, wcslen(woutbufp));
3913 if (path->narrow)
3914 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3915 } else
3916 v = win32_error_object("GetFullPathNameW", path->object);
3917 if (woutbufp != woutbuf)
3918 PyMem_Free(woutbufp);
3919 return v;
Larry Hastings2f936352014-08-05 14:04:04 +10003920}
Brian Curtind40e6f72010-07-08 21:39:08 +00003921
Brian Curtind25aef52011-06-13 15:16:04 -05003922
Larry Hastings2f936352014-08-05 14:04:04 +10003923/*[clinic input]
3924os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003925
Steve Dower23ad6d02018-02-22 10:39:10 -08003926 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003927 /
3928
3929A helper function for samepath on windows.
3930[clinic start generated code]*/
3931
Larry Hastings2f936352014-08-05 14:04:04 +10003932static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003933os__getfinalpathname_impl(PyObject *module, path_t *path)
3934/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003935{
3936 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003937 wchar_t buf[MAXPATHLEN], *target_path = buf;
3938 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003939 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003940 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003941
Steve Dower23ad6d02018-02-22 10:39:10 -08003942 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003943 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003944 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003945 0, /* desired access */
3946 0, /* share mode */
3947 NULL, /* security attributes */
3948 OPEN_EXISTING,
3949 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3950 FILE_FLAG_BACKUP_SEMANTICS,
3951 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003952 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003953
Steve Dower23ad6d02018-02-22 10:39:10 -08003954 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003955 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08003956 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003957
3958 /* We have a good handle to the target, use it to determine the
3959 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003960 while (1) {
3961 Py_BEGIN_ALLOW_THREADS
3962 result_length = GetFinalPathNameByHandleW(hFile, target_path,
3963 buf_size, VOLUME_NAME_DOS);
3964 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003965
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003966 if (!result_length) {
3967 result = win32_error_object("GetFinalPathNameByHandleW",
3968 path->object);
3969 goto cleanup;
3970 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003971
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003972 if (result_length < buf_size) {
3973 break;
3974 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003975
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003976 wchar_t *tmp;
3977 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
3978 result_length * sizeof(*tmp));
3979 if (!tmp) {
3980 result = PyErr_NoMemory();
3981 goto cleanup;
3982 }
3983
3984 buf_size = result_length;
3985 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08003986 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003987
Victor Stinner9d3b93b2011-11-22 02:27:30 +01003988 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dower9eb3d542019-08-21 15:52:42 -07003989 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08003990 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dower9eb3d542019-08-21 15:52:42 -07003991 }
Steve Dower23ad6d02018-02-22 10:39:10 -08003992
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003993cleanup:
3994 if (target_path != buf) {
3995 PyMem_Free(target_path);
3996 }
3997 CloseHandle(hFile);
3998 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10003999}
Brian Curtin62857742010-09-06 17:07:27 +00004000
Tim Golden6b528062013-08-01 12:44:00 +01004001
Larry Hastings2f936352014-08-05 14:04:04 +10004002/*[clinic input]
4003os._getvolumepathname
4004
Steve Dower23ad6d02018-02-22 10:39:10 -08004005 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004006
4007A helper function for ismount on Win32.
4008[clinic start generated code]*/
4009
Larry Hastings2f936352014-08-05 14:04:04 +10004010static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004011os__getvolumepathname_impl(PyObject *module, path_t *path)
4012/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004013{
4014 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004015 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004016 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004017 BOOL ret;
4018
Tim Golden6b528062013-08-01 12:44:00 +01004019 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004020 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004021
Victor Stinner850a18e2017-10-24 16:53:32 -07004022 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004023 PyErr_SetString(PyExc_OverflowError, "path too long");
4024 return NULL;
4025 }
4026
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004027 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004028 if (mountpath == NULL)
4029 return PyErr_NoMemory();
4030
4031 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004032 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004033 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004034 Py_END_ALLOW_THREADS
4035
4036 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004037 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004038 goto exit;
4039 }
4040 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004041 if (path->narrow)
4042 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004043
4044exit:
4045 PyMem_Free(mountpath);
4046 return result;
4047}
Tim Golden6b528062013-08-01 12:44:00 +01004048
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004049#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004050
Larry Hastings2f936352014-08-05 14:04:04 +10004051
4052/*[clinic input]
4053os.mkdir
4054
4055 path : path_t
4056
4057 mode: int = 0o777
4058
4059 *
4060
4061 dir_fd : dir_fd(requires='mkdirat') = None
4062
4063# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4064
4065Create a directory.
4066
4067If dir_fd is not None, it should be a file descriptor open to a directory,
4068 and path should be relative; path will then be relative to that directory.
4069dir_fd may not be implemented on your platform.
4070 If it is unavailable, using it will raise a NotImplementedError.
4071
4072The mode argument is ignored on Windows.
4073[clinic start generated code]*/
4074
Larry Hastings2f936352014-08-05 14:04:04 +10004075static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004076os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4077/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004078{
4079 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004080
Steve Dowera00b5be2020-02-13 08:30:27 +00004081 if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
4082 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4083 return NULL;
4084 }
4085
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004086#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004087 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004088 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004089 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004090
Larry Hastings2f936352014-08-05 14:04:04 +10004091 if (!result)
4092 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004093#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004094 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004095#if HAVE_MKDIRAT
4096 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004097 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004098 else
4099#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004100#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004101 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004102#else
Larry Hastings2f936352014-08-05 14:04:04 +10004103 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004104#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004105 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004106 if (result < 0)
4107 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004108#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004109 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004110}
4111
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004112
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004113/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4114#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004115#include <sys/resource.h>
4116#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004117
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004118
4119#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004120/*[clinic input]
4121os.nice
4122
4123 increment: int
4124 /
4125
4126Add increment to the priority of process and return the new priority.
4127[clinic start generated code]*/
4128
Larry Hastings2f936352014-08-05 14:04:04 +10004129static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004130os_nice_impl(PyObject *module, int increment)
4131/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004132{
4133 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004134
Victor Stinner8c62be82010-05-06 00:08:46 +00004135 /* There are two flavours of 'nice': one that returns the new
4136 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004137 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004138 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004139
Victor Stinner8c62be82010-05-06 00:08:46 +00004140 If we are of the nice family that returns the new priority, we
4141 need to clear errno before the call, and check if errno is filled
4142 before calling posix_error() on a returnvalue of -1, because the
4143 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004144
Victor Stinner8c62be82010-05-06 00:08:46 +00004145 errno = 0;
4146 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004147#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004148 if (value == 0)
4149 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004150#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004151 if (value == -1 && errno != 0)
4152 /* either nice() or getpriority() returned an error */
4153 return posix_error();
4154 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004155}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004156#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004157
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004158
4159#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004160/*[clinic input]
4161os.getpriority
4162
4163 which: int
4164 who: int
4165
4166Return program scheduling priority.
4167[clinic start generated code]*/
4168
Larry Hastings2f936352014-08-05 14:04:04 +10004169static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004170os_getpriority_impl(PyObject *module, int which, int who)
4171/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004172{
4173 int retval;
4174
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004175 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004176 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004177 if (errno != 0)
4178 return posix_error();
4179 return PyLong_FromLong((long)retval);
4180}
4181#endif /* HAVE_GETPRIORITY */
4182
4183
4184#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004185/*[clinic input]
4186os.setpriority
4187
4188 which: int
4189 who: int
4190 priority: int
4191
4192Set program scheduling priority.
4193[clinic start generated code]*/
4194
Larry Hastings2f936352014-08-05 14:04:04 +10004195static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004196os_setpriority_impl(PyObject *module, int which, int who, int priority)
4197/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004198{
4199 int retval;
4200
4201 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004202 if (retval == -1)
4203 return posix_error();
4204 Py_RETURN_NONE;
4205}
4206#endif /* HAVE_SETPRIORITY */
4207
4208
Barry Warsaw53699e91996-12-10 23:23:01 +00004209static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004210internal_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 +00004211{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004212 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004213 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004214
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004215#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004216 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004217 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004218#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004219 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004220#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004221
Larry Hastings9cf065c2012-06-22 16:30:09 -07004222 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4223 (dst_dir_fd != DEFAULT_DIR_FD);
4224#ifndef HAVE_RENAMEAT
4225 if (dir_fd_specified) {
4226 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004227 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004228 }
4229#endif
4230
Steve Dowera00b5be2020-02-13 08:30:27 +00004231 if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
4232 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
4233 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
4234 return NULL;
4235 }
4236
Larry Hastings9cf065c2012-06-22 16:30:09 -07004237#ifdef MS_WINDOWS
4238 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004239 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004240 Py_END_ALLOW_THREADS
4241
Larry Hastings2f936352014-08-05 14:04:04 +10004242 if (!result)
4243 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004244
4245#else
Steve Dowercc16be82016-09-08 10:35:16 -07004246 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4247 PyErr_Format(PyExc_ValueError,
4248 "%s: src and dst must be the same type", function_name);
4249 return NULL;
4250 }
4251
Larry Hastings9cf065c2012-06-22 16:30:09 -07004252 Py_BEGIN_ALLOW_THREADS
4253#ifdef HAVE_RENAMEAT
4254 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004255 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004256 else
4257#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004258 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004259 Py_END_ALLOW_THREADS
4260
Larry Hastings2f936352014-08-05 14:04:04 +10004261 if (result)
4262 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004263#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004264 Py_RETURN_NONE;
4265}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004266
Larry Hastings2f936352014-08-05 14:04:04 +10004267
4268/*[clinic input]
4269os.rename
4270
4271 src : path_t
4272 dst : path_t
4273 *
4274 src_dir_fd : dir_fd = None
4275 dst_dir_fd : dir_fd = None
4276
4277Rename a file or directory.
4278
4279If either src_dir_fd or dst_dir_fd is not None, it should be a file
4280 descriptor open to a directory, and the respective path string (src or dst)
4281 should be relative; the path will then be relative to that directory.
4282src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4283 If they are unavailable, using them will raise a NotImplementedError.
4284[clinic start generated code]*/
4285
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004286static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004287os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004288 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004289/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004290{
Larry Hastings2f936352014-08-05 14:04:04 +10004291 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004292}
4293
Larry Hastings2f936352014-08-05 14:04:04 +10004294
4295/*[clinic input]
4296os.replace = os.rename
4297
4298Rename a file or directory, overwriting the destination.
4299
4300If either src_dir_fd or dst_dir_fd is not None, it should be a file
4301 descriptor open to a directory, and the respective path string (src or dst)
4302 should be relative; the path will then be relative to that directory.
4303src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004304 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004305[clinic start generated code]*/
4306
Larry Hastings2f936352014-08-05 14:04:04 +10004307static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004308os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4309 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004310/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004311{
4312 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4313}
4314
4315
4316/*[clinic input]
4317os.rmdir
4318
4319 path: path_t
4320 *
4321 dir_fd: dir_fd(requires='unlinkat') = None
4322
4323Remove a directory.
4324
4325If dir_fd is not None, it should be a file descriptor open to a directory,
4326 and path should be relative; path will then be relative to that directory.
4327dir_fd may not be implemented on your platform.
4328 If it is unavailable, using it will raise a NotImplementedError.
4329[clinic start generated code]*/
4330
Larry Hastings2f936352014-08-05 14:04:04 +10004331static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004332os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4333/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004334{
4335 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004336
Steve Dowera00b5be2020-02-13 08:30:27 +00004337 if (PySys_Audit("os.rmdir", "Oi", path->object,
4338 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4339 return NULL;
4340 }
4341
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004342 Py_BEGIN_ALLOW_THREADS
4343#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004344 /* Windows, success=1, UNIX, success=0 */
4345 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004346#else
4347#ifdef HAVE_UNLINKAT
4348 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004349 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004350 else
4351#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004352 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004353#endif
4354 Py_END_ALLOW_THREADS
4355
Larry Hastings2f936352014-08-05 14:04:04 +10004356 if (result)
4357 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004358
Larry Hastings2f936352014-08-05 14:04:04 +10004359 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004360}
4361
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004362
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004363#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004364#ifdef MS_WINDOWS
4365/*[clinic input]
4366os.system -> long
4367
4368 command: Py_UNICODE
4369
4370Execute the command in a subshell.
4371[clinic start generated code]*/
4372
Larry Hastings2f936352014-08-05 14:04:04 +10004373static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004374os_system_impl(PyObject *module, const Py_UNICODE *command)
4375/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004376{
4377 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004378
Miss Islington (bot)5fb81422019-10-18 09:32:14 -07004379 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004380 return -1;
4381 }
4382
Victor Stinner8c62be82010-05-06 00:08:46 +00004383 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004384 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004385 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004386 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004387 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004388 return result;
4389}
4390#else /* MS_WINDOWS */
4391/*[clinic input]
4392os.system -> long
4393
4394 command: FSConverter
4395
4396Execute the command in a subshell.
4397[clinic start generated code]*/
4398
Larry Hastings2f936352014-08-05 14:04:04 +10004399static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004400os_system_impl(PyObject *module, PyObject *command)
4401/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004402{
4403 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004404 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004405
Miss Islington (bot)5fb81422019-10-18 09:32:14 -07004406 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004407 return -1;
4408 }
4409
Larry Hastings2f936352014-08-05 14:04:04 +10004410 Py_BEGIN_ALLOW_THREADS
4411 result = system(bytes);
4412 Py_END_ALLOW_THREADS
4413 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004414}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004415#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004416#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004417
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004418
Larry Hastings2f936352014-08-05 14:04:04 +10004419/*[clinic input]
4420os.umask
4421
4422 mask: int
4423 /
4424
4425Set the current numeric umask and return the previous umask.
4426[clinic start generated code]*/
4427
Larry Hastings2f936352014-08-05 14:04:04 +10004428static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004429os_umask_impl(PyObject *module, int mask)
4430/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004431{
4432 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004433 if (i < 0)
4434 return posix_error();
4435 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004436}
4437
Brian Curtind40e6f72010-07-08 21:39:08 +00004438#ifdef MS_WINDOWS
4439
4440/* override the default DeleteFileW behavior so that directory
4441symlinks can be removed with this function, the same as with
4442Unix symlinks */
4443BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4444{
4445 WIN32_FILE_ATTRIBUTE_DATA info;
4446 WIN32_FIND_DATAW find_data;
4447 HANDLE find_data_handle;
4448 int is_directory = 0;
4449 int is_link = 0;
4450
4451 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4452 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004453
Brian Curtind40e6f72010-07-08 21:39:08 +00004454 /* Get WIN32_FIND_DATA structure for the path to determine if
4455 it is a symlink */
4456 if(is_directory &&
4457 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4458 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4459
4460 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004461 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4462 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4463 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4464 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004465 FindClose(find_data_handle);
4466 }
4467 }
4468 }
4469
4470 if (is_directory && is_link)
4471 return RemoveDirectoryW(lpFileName);
4472
4473 return DeleteFileW(lpFileName);
4474}
4475#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004476
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004477
Larry Hastings2f936352014-08-05 14:04:04 +10004478/*[clinic input]
4479os.unlink
4480
4481 path: path_t
4482 *
4483 dir_fd: dir_fd(requires='unlinkat')=None
4484
4485Remove a file (same as remove()).
4486
4487If dir_fd is not None, it should be a file descriptor open to a directory,
4488 and path should be relative; path will then be relative to that directory.
4489dir_fd may not be implemented on your platform.
4490 If it is unavailable, using it will raise a NotImplementedError.
4491
4492[clinic start generated code]*/
4493
Larry Hastings2f936352014-08-05 14:04:04 +10004494static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004495os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4496/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004497{
4498 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004499
Steve Dowera00b5be2020-02-13 08:30:27 +00004500 if (PySys_Audit("os.remove", "Oi", path->object,
4501 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4502 return NULL;
4503 }
4504
Larry Hastings9cf065c2012-06-22 16:30:09 -07004505 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004506 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004507#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004508 /* Windows, success=1, UNIX, success=0 */
4509 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004510#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004511#ifdef HAVE_UNLINKAT
4512 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004513 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004514 else
4515#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004516 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004517#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004518 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004519 Py_END_ALLOW_THREADS
4520
Larry Hastings2f936352014-08-05 14:04:04 +10004521 if (result)
4522 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004523
Larry Hastings2f936352014-08-05 14:04:04 +10004524 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004525}
4526
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004527
Larry Hastings2f936352014-08-05 14:04:04 +10004528/*[clinic input]
4529os.remove = os.unlink
4530
4531Remove a file (same as unlink()).
4532
4533If dir_fd is not None, it should be a file descriptor open to a directory,
4534 and path should be relative; path will then be relative to that directory.
4535dir_fd may not be implemented on your platform.
4536 If it is unavailable, using it will raise a NotImplementedError.
4537[clinic start generated code]*/
4538
Larry Hastings2f936352014-08-05 14:04:04 +10004539static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004540os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4541/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004542{
4543 return os_unlink_impl(module, path, dir_fd);
4544}
4545
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004546
Larry Hastings605a62d2012-06-24 04:33:36 -07004547static PyStructSequence_Field uname_result_fields[] = {
4548 {"sysname", "operating system name"},
4549 {"nodename", "name of machine on network (implementation-defined)"},
4550 {"release", "operating system release"},
4551 {"version", "operating system version"},
4552 {"machine", "hardware identifier"},
4553 {NULL}
4554};
4555
4556PyDoc_STRVAR(uname_result__doc__,
4557"uname_result: Result from os.uname().\n\n\
4558This object may be accessed either as a tuple of\n\
4559 (sysname, nodename, release, version, machine),\n\
4560or via the attributes sysname, nodename, release, version, and machine.\n\
4561\n\
4562See os.uname for more information.");
4563
4564static PyStructSequence_Desc uname_result_desc = {
4565 "uname_result", /* name */
4566 uname_result__doc__, /* doc */
4567 uname_result_fields,
4568 5
4569};
4570
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004571static PyTypeObject* UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07004572
4573
4574#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004575/*[clinic input]
4576os.uname
4577
4578Return an object identifying the current operating system.
4579
4580The object behaves like a named tuple with the following fields:
4581 (sysname, nodename, release, version, machine)
4582
4583[clinic start generated code]*/
4584
Larry Hastings2f936352014-08-05 14:04:04 +10004585static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004586os_uname_impl(PyObject *module)
4587/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004588{
Victor Stinner8c62be82010-05-06 00:08:46 +00004589 struct utsname u;
4590 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004591 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004592
Victor Stinner8c62be82010-05-06 00:08:46 +00004593 Py_BEGIN_ALLOW_THREADS
4594 res = uname(&u);
4595 Py_END_ALLOW_THREADS
4596 if (res < 0)
4597 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004598
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004599 value = PyStructSequence_New(UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004600 if (value == NULL)
4601 return NULL;
4602
4603#define SET(i, field) \
4604 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004605 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004606 if (!o) { \
4607 Py_DECREF(value); \
4608 return NULL; \
4609 } \
4610 PyStructSequence_SET_ITEM(value, i, o); \
4611 } \
4612
4613 SET(0, u.sysname);
4614 SET(1, u.nodename);
4615 SET(2, u.release);
4616 SET(3, u.version);
4617 SET(4, u.machine);
4618
4619#undef SET
4620
4621 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004622}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004623#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004624
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004625
Larry Hastings9cf065c2012-06-22 16:30:09 -07004626
4627typedef struct {
4628 int now;
4629 time_t atime_s;
4630 long atime_ns;
4631 time_t mtime_s;
4632 long mtime_ns;
4633} utime_t;
4634
4635/*
Victor Stinner484df002014-10-09 13:52:31 +02004636 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004637 * they also intentionally leak the declaration of a pointer named "time"
4638 */
4639#define UTIME_TO_TIMESPEC \
4640 struct timespec ts[2]; \
4641 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004642 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004643 time = NULL; \
4644 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004645 ts[0].tv_sec = ut->atime_s; \
4646 ts[0].tv_nsec = ut->atime_ns; \
4647 ts[1].tv_sec = ut->mtime_s; \
4648 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004649 time = ts; \
4650 } \
4651
4652#define UTIME_TO_TIMEVAL \
4653 struct timeval tv[2]; \
4654 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004655 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004656 time = NULL; \
4657 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004658 tv[0].tv_sec = ut->atime_s; \
4659 tv[0].tv_usec = ut->atime_ns / 1000; \
4660 tv[1].tv_sec = ut->mtime_s; \
4661 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004662 time = tv; \
4663 } \
4664
4665#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004666 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004667 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004668 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004669 time = NULL; \
4670 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004671 u.actime = ut->atime_s; \
4672 u.modtime = ut->mtime_s; \
4673 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004674 }
4675
4676#define UTIME_TO_TIME_T \
4677 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004678 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004679 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004680 time = NULL; \
4681 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004682 timet[0] = ut->atime_s; \
4683 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004684 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004685 } \
4686
4687
Victor Stinner528a9ab2015-09-03 21:30:26 +02004688#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004689
4690static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004691utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004692{
4693#ifdef HAVE_UTIMENSAT
4694 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4695 UTIME_TO_TIMESPEC;
4696 return utimensat(dir_fd, path, time, flags);
4697#elif defined(HAVE_FUTIMESAT)
4698 UTIME_TO_TIMEVAL;
4699 /*
4700 * follow_symlinks will never be false here;
4701 * we only allow !follow_symlinks and dir_fd together
4702 * if we have utimensat()
4703 */
4704 assert(follow_symlinks);
4705 return futimesat(dir_fd, path, time);
4706#endif
4707}
4708
Larry Hastings2f936352014-08-05 14:04:04 +10004709 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4710#else
4711 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004712#endif
4713
Victor Stinner528a9ab2015-09-03 21:30:26 +02004714#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004715
4716static int
Victor Stinner484df002014-10-09 13:52:31 +02004717utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004718{
4719#ifdef HAVE_FUTIMENS
4720 UTIME_TO_TIMESPEC;
4721 return futimens(fd, time);
4722#else
4723 UTIME_TO_TIMEVAL;
4724 return futimes(fd, time);
4725#endif
4726}
4727
Larry Hastings2f936352014-08-05 14:04:04 +10004728 #define PATH_UTIME_HAVE_FD 1
4729#else
4730 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004731#endif
4732
Victor Stinner5ebae872015-09-22 01:29:33 +02004733#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4734# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4735#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004736
Victor Stinner4552ced2015-09-21 22:37:15 +02004737#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004738
4739static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004740utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004741{
4742#ifdef HAVE_UTIMENSAT
4743 UTIME_TO_TIMESPEC;
4744 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4745#else
4746 UTIME_TO_TIMEVAL;
4747 return lutimes(path, time);
4748#endif
4749}
4750
4751#endif
4752
4753#ifndef MS_WINDOWS
4754
4755static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004756utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004757{
4758#ifdef HAVE_UTIMENSAT
4759 UTIME_TO_TIMESPEC;
4760 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4761#elif defined(HAVE_UTIMES)
4762 UTIME_TO_TIMEVAL;
4763 return utimes(path, time);
4764#elif defined(HAVE_UTIME_H)
4765 UTIME_TO_UTIMBUF;
4766 return utime(path, time);
4767#else
4768 UTIME_TO_TIME_T;
4769 return utime(path, time);
4770#endif
4771}
4772
4773#endif
4774
Larry Hastings76ad59b2012-05-03 00:30:07 -07004775static int
4776split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4777{
4778 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004779 PyObject *divmod;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004780 divmod = PyNumber_Divmod(py_long, billion);
4781 if (!divmod)
4782 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004783 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4784 PyErr_Format(PyExc_TypeError,
4785 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
4786 Py_TYPE(py_long)->tp_name, Py_TYPE(divmod)->tp_name);
4787 goto exit;
4788 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004789 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4790 if ((*s == -1) && PyErr_Occurred())
4791 goto exit;
4792 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004793 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004794 goto exit;
4795
4796 result = 1;
4797exit:
4798 Py_XDECREF(divmod);
4799 return result;
4800}
4801
Larry Hastings2f936352014-08-05 14:04:04 +10004802
4803/*[clinic input]
4804os.utime
4805
4806 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004807 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004808 *
4809 ns: object = NULL
4810 dir_fd: dir_fd(requires='futimensat') = None
4811 follow_symlinks: bool=True
4812
Martin Panter0ff89092015-09-09 01:56:53 +00004813# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004814
4815Set the access and modified time of path.
4816
4817path may always be specified as a string.
4818On some platforms, path may also be specified as an open file descriptor.
4819 If this functionality is unavailable, using it raises an exception.
4820
4821If times is not None, it must be a tuple (atime, mtime);
4822 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004823If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004824 atime_ns and mtime_ns should be expressed as integer nanoseconds
4825 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004826If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004827Specifying tuples for both times and ns is an error.
4828
4829If dir_fd is not None, it should be a file descriptor open to a directory,
4830 and path should be relative; path will then be relative to that directory.
4831If follow_symlinks is False, and the last element of the path is a symbolic
4832 link, utime will modify the symbolic link itself instead of the file the
4833 link points to.
4834It is an error to use dir_fd or follow_symlinks when specifying path
4835 as an open file descriptor.
4836dir_fd and follow_symlinks may not be available on your platform.
4837 If they are unavailable, using them will raise a NotImplementedError.
4838
4839[clinic start generated code]*/
4840
Larry Hastings2f936352014-08-05 14:04:04 +10004841static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004842os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4843 int dir_fd, int follow_symlinks)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004844/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004845{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004846#ifdef MS_WINDOWS
4847 HANDLE hFile;
4848 FILETIME atime, mtime;
4849#else
4850 int result;
4851#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004852
Larry Hastings2f936352014-08-05 14:04:04 +10004853 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004854
Christian Heimesb3c87242013-08-01 00:08:16 +02004855 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004856
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004857 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004858 PyErr_SetString(PyExc_ValueError,
4859 "utime: you may specify either 'times'"
4860 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004861 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004862 }
4863
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004864 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004865 time_t a_sec, m_sec;
4866 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004867 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004868 PyErr_SetString(PyExc_TypeError,
4869 "utime: 'times' must be either"
4870 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004871 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004872 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004873 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004874 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004875 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004876 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004877 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004878 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004879 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004880 utime.atime_s = a_sec;
4881 utime.atime_ns = a_nsec;
4882 utime.mtime_s = m_sec;
4883 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004884 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004885 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004886 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004887 PyErr_SetString(PyExc_TypeError,
4888 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004889 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004890 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004891 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004892 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004893 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004894 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004895 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004896 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004897 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004898 }
4899 else {
4900 /* times and ns are both None/unspecified. use "now". */
4901 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004902 }
4903
Victor Stinner4552ced2015-09-21 22:37:15 +02004904#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004905 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004906 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004907#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004908
Larry Hastings2f936352014-08-05 14:04:04 +10004909 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4910 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4911 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004912 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004913
Larry Hastings9cf065c2012-06-22 16:30:09 -07004914#if !defined(HAVE_UTIMENSAT)
4915 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004916 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004917 "utime: cannot use dir_fd and follow_symlinks "
4918 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004919 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004920 }
4921#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004922
Steve Dowera00b5be2020-02-13 08:30:27 +00004923 if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
4924 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4925 return NULL;
4926 }
4927
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004928#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004929 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004930 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4931 NULL, OPEN_EXISTING,
4932 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004933 Py_END_ALLOW_THREADS
4934 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004935 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004936 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004937 }
4938
Larry Hastings9cf065c2012-06-22 16:30:09 -07004939 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004940 GetSystemTimeAsFileTime(&mtime);
4941 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004942 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004943 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004944 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4945 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004946 }
4947 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4948 /* Avoid putting the file name into the error here,
4949 as that may confuse the user into believing that
4950 something is wrong with the file, when it also
4951 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004952 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004953 CloseHandle(hFile);
4954 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004955 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004956 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004957#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004958 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004959
Victor Stinner4552ced2015-09-21 22:37:15 +02004960#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004961 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004962 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004963 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004964#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004965
Victor Stinner528a9ab2015-09-03 21:30:26 +02004966#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004967 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004968 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004969 else
4970#endif
4971
Victor Stinner528a9ab2015-09-03 21:30:26 +02004972#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004973 if (path->fd != -1)
4974 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004975 else
4976#endif
4977
Larry Hastings2f936352014-08-05 14:04:04 +10004978 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004979
4980 Py_END_ALLOW_THREADS
4981
4982 if (result < 0) {
4983 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004984 posix_error();
4985 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004986 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004987
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004988#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004989
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004990 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004991}
4992
Guido van Rossum3b066191991-06-04 19:40:25 +00004993/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004994
Larry Hastings2f936352014-08-05 14:04:04 +10004995
4996/*[clinic input]
4997os._exit
4998
4999 status: int
5000
5001Exit to the system with specified status, without normal exit processing.
5002[clinic start generated code]*/
5003
Larry Hastings2f936352014-08-05 14:04:04 +10005004static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005005os__exit_impl(PyObject *module, int status)
5006/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005007{
5008 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005009 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005010}
5011
Steve Dowercc16be82016-09-08 10:35:16 -07005012#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5013#define EXECV_CHAR wchar_t
5014#else
5015#define EXECV_CHAR char
5016#endif
5017
pxinwrf2d7ac72019-05-21 18:46:37 +08005018#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005019static void
Steve Dowercc16be82016-09-08 10:35:16 -07005020free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005021{
Victor Stinner8c62be82010-05-06 00:08:46 +00005022 Py_ssize_t i;
5023 for (i = 0; i < count; i++)
5024 PyMem_Free(array[i]);
5025 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005026}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005027
Berker Peksag81816462016-09-15 20:19:47 +03005028static int
5029fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005030{
Victor Stinner8c62be82010-05-06 00:08:46 +00005031 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005032 PyObject *ub;
5033 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005034#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005035 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005036 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005037 *out = PyUnicode_AsWideCharString(ub, &size);
5038 if (*out)
5039 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005040#else
Berker Peksag81816462016-09-15 20:19:47 +03005041 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005042 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005043 size = PyBytes_GET_SIZE(ub);
5044 *out = PyMem_Malloc(size + 1);
5045 if (*out) {
5046 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5047 result = 1;
5048 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005049 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005050#endif
Berker Peksag81816462016-09-15 20:19:47 +03005051 Py_DECREF(ub);
5052 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005053}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005054#endif
5055
pxinwrf2d7ac72019-05-21 18:46:37 +08005056#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005057static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005058parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5059{
Victor Stinner8c62be82010-05-06 00:08:46 +00005060 Py_ssize_t i, pos, envc;
5061 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005062 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005063 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005064
Victor Stinner8c62be82010-05-06 00:08:46 +00005065 i = PyMapping_Size(env);
5066 if (i < 0)
5067 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005068 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005069 if (envlist == NULL) {
5070 PyErr_NoMemory();
5071 return NULL;
5072 }
5073 envc = 0;
5074 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005075 if (!keys)
5076 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005077 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005078 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005079 goto error;
5080 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5081 PyErr_Format(PyExc_TypeError,
5082 "env.keys() or env.values() is not a list");
5083 goto error;
5084 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005085
Victor Stinner8c62be82010-05-06 00:08:46 +00005086 for (pos = 0; pos < i; pos++) {
5087 key = PyList_GetItem(keys, pos);
5088 val = PyList_GetItem(vals, pos);
5089 if (!key || !val)
5090 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005091
Berker Peksag81816462016-09-15 20:19:47 +03005092#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5093 if (!PyUnicode_FSDecoder(key, &key2))
5094 goto error;
5095 if (!PyUnicode_FSDecoder(val, &val2)) {
5096 Py_DECREF(key2);
5097 goto error;
5098 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005099 /* Search from index 1 because on Windows starting '=' is allowed for
5100 defining hidden environment variables. */
5101 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5102 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5103 {
5104 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005105 Py_DECREF(key2);
5106 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005107 goto error;
5108 }
Berker Peksag81816462016-09-15 20:19:47 +03005109 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5110#else
5111 if (!PyUnicode_FSConverter(key, &key2))
5112 goto error;
5113 if (!PyUnicode_FSConverter(val, &val2)) {
5114 Py_DECREF(key2);
5115 goto error;
5116 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005117 if (PyBytes_GET_SIZE(key2) == 0 ||
5118 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5119 {
5120 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005121 Py_DECREF(key2);
5122 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005123 goto error;
5124 }
Berker Peksag81816462016-09-15 20:19:47 +03005125 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5126 PyBytes_AS_STRING(val2));
5127#endif
5128 Py_DECREF(key2);
5129 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005130 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005131 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005132
5133 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5134 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005135 goto error;
5136 }
Berker Peksag81816462016-09-15 20:19:47 +03005137
Steve Dowercc16be82016-09-08 10:35:16 -07005138 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005139 }
5140 Py_DECREF(vals);
5141 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005142
Victor Stinner8c62be82010-05-06 00:08:46 +00005143 envlist[envc] = 0;
5144 *envc_ptr = envc;
5145 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005146
5147error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005148 Py_XDECREF(keys);
5149 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005150 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005151 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005152}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005153
Steve Dowercc16be82016-09-08 10:35:16 -07005154static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005155parse_arglist(PyObject* argv, Py_ssize_t *argc)
5156{
5157 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005158 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005159 if (argvlist == NULL) {
5160 PyErr_NoMemory();
5161 return NULL;
5162 }
5163 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005164 PyObject* item = PySequence_ITEM(argv, i);
5165 if (item == NULL)
5166 goto fail;
5167 if (!fsconvert_strdup(item, &argvlist[i])) {
5168 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005169 goto fail;
5170 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005171 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005172 }
5173 argvlist[*argc] = NULL;
5174 return argvlist;
5175fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005176 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005177 free_string_array(argvlist, *argc);
5178 return NULL;
5179}
Steve Dowercc16be82016-09-08 10:35:16 -07005180
Ross Lagerwall7807c352011-03-17 20:20:30 +02005181#endif
5182
Larry Hastings2f936352014-08-05 14:04:04 +10005183
Ross Lagerwall7807c352011-03-17 20:20:30 +02005184#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005185/*[clinic input]
5186os.execv
5187
Steve Dowercc16be82016-09-08 10:35:16 -07005188 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005189 Path of executable file.
5190 argv: object
5191 Tuple or list of strings.
5192 /
5193
5194Execute an executable path with arguments, replacing current process.
5195[clinic start generated code]*/
5196
Larry Hastings2f936352014-08-05 14:04:04 +10005197static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005198os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5199/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005200{
Steve Dowercc16be82016-09-08 10:35:16 -07005201 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005202 Py_ssize_t argc;
5203
5204 /* execv has two arguments: (path, argv), where
5205 argv is a list or tuple of strings. */
5206
Ross Lagerwall7807c352011-03-17 20:20:30 +02005207 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5208 PyErr_SetString(PyExc_TypeError,
5209 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005210 return NULL;
5211 }
5212 argc = PySequence_Size(argv);
5213 if (argc < 1) {
5214 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005215 return NULL;
5216 }
5217
5218 argvlist = parse_arglist(argv, &argc);
5219 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005220 return NULL;
5221 }
Steve Dowerbce26262016-11-19 19:17:26 -08005222 if (!argvlist[0][0]) {
5223 PyErr_SetString(PyExc_ValueError,
5224 "execv() arg 2 first element cannot be empty");
5225 free_string_array(argvlist, argc);
5226 return NULL;
5227 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005228
Steve Dowera00b5be2020-02-13 08:30:27 +00005229 if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005230 free_string_array(argvlist, argc);
5231 return NULL;
5232 }
5233
Steve Dowerbce26262016-11-19 19:17:26 -08005234 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005235#ifdef HAVE_WEXECV
5236 _wexecv(path->wide, argvlist);
5237#else
5238 execv(path->narrow, argvlist);
5239#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005240 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005241
5242 /* If we get here it's definitely an error */
5243
5244 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005245 return posix_error();
5246}
5247
Larry Hastings2f936352014-08-05 14:04:04 +10005248
5249/*[clinic input]
5250os.execve
5251
5252 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5253 Path of executable file.
5254 argv: object
5255 Tuple or list of strings.
5256 env: object
5257 Dictionary of strings mapping to strings.
5258
5259Execute an executable path with arguments, replacing current process.
5260[clinic start generated code]*/
5261
Larry Hastings2f936352014-08-05 14:04:04 +10005262static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005263os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5264/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005265{
Steve Dowercc16be82016-09-08 10:35:16 -07005266 EXECV_CHAR **argvlist = NULL;
5267 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005268 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005269
Victor Stinner8c62be82010-05-06 00:08:46 +00005270 /* execve has three arguments: (path, argv, env), where
5271 argv is a list or tuple of strings and env is a dictionary
5272 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005273
Ross Lagerwall7807c352011-03-17 20:20:30 +02005274 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005275 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005276 "execve: argv must be a tuple or list");
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005277 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005278 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005279 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005280 if (argc < 1) {
5281 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5282 return NULL;
5283 }
5284
Victor Stinner8c62be82010-05-06 00:08:46 +00005285 if (!PyMapping_Check(env)) {
5286 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005287 "execve: environment must be a mapping object");
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005288 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005289 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005290
Ross Lagerwall7807c352011-03-17 20:20:30 +02005291 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005292 if (argvlist == NULL) {
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005293 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005294 }
Steve Dowerbce26262016-11-19 19:17:26 -08005295 if (!argvlist[0][0]) {
5296 PyErr_SetString(PyExc_ValueError,
5297 "execve: argv first element cannot be empty");
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005298 goto fail_0;
Steve Dowerbce26262016-11-19 19:17:26 -08005299 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005300
Victor Stinner8c62be82010-05-06 00:08:46 +00005301 envlist = parse_envlist(env, &envc);
5302 if (envlist == NULL)
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005303 goto fail_0;
5304
Steve Dowera00b5be2020-02-13 08:30:27 +00005305 if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005306 goto fail_1;
5307 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005308
Steve Dowerbce26262016-11-19 19:17:26 -08005309 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005310#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005311 if (path->fd > -1)
5312 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005313 else
5314#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005315#ifdef HAVE_WEXECV
5316 _wexecve(path->wide, argvlist, envlist);
5317#else
Larry Hastings2f936352014-08-05 14:04:04 +10005318 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005319#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005320 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005321
5322 /* If we get here it's definitely an error */
5323
Alexey Izbyshev83460312018-10-20 03:28:22 +03005324 posix_path_error(path);
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005325 fail_1:
Steve Dowercc16be82016-09-08 10:35:16 -07005326 free_string_array(envlist, envc);
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005327 fail_0:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005328 if (argvlist)
5329 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005330 return NULL;
5331}
Steve Dowercc16be82016-09-08 10:35:16 -07005332
Larry Hastings9cf065c2012-06-22 16:30:09 -07005333#endif /* HAVE_EXECV */
5334
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005335#ifdef HAVE_POSIX_SPAWN
5336
5337enum posix_spawn_file_actions_identifier {
5338 POSIX_SPAWN_OPEN,
5339 POSIX_SPAWN_CLOSE,
5340 POSIX_SPAWN_DUP2
5341};
5342
William Orr81574b82018-10-01 22:19:56 -07005343#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005344static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005345convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005346#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005347
5348static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005349parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5350 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005351 PyObject *setsigdef, PyObject *scheduler,
5352 posix_spawnattr_t *attrp)
5353{
5354 long all_flags = 0;
5355
5356 errno = posix_spawnattr_init(attrp);
5357 if (errno) {
5358 posix_error();
5359 return -1;
5360 }
5361
5362 if (setpgroup) {
5363 pid_t pgid = PyLong_AsPid(setpgroup);
5364 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5365 goto fail;
5366 }
5367 errno = posix_spawnattr_setpgroup(attrp, pgid);
5368 if (errno) {
5369 posix_error();
5370 goto fail;
5371 }
5372 all_flags |= POSIX_SPAWN_SETPGROUP;
5373 }
5374
5375 if (resetids) {
5376 all_flags |= POSIX_SPAWN_RESETIDS;
5377 }
5378
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005379 if (setsid) {
5380#ifdef POSIX_SPAWN_SETSID
5381 all_flags |= POSIX_SPAWN_SETSID;
5382#elif defined(POSIX_SPAWN_SETSID_NP)
5383 all_flags |= POSIX_SPAWN_SETSID_NP;
5384#else
5385 argument_unavailable_error(func_name, "setsid");
5386 return -1;
5387#endif
5388 }
5389
Pablo Galindo254a4662018-09-07 16:44:24 +01005390 if (setsigmask) {
5391 sigset_t set;
5392 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5393 goto fail;
5394 }
5395 errno = posix_spawnattr_setsigmask(attrp, &set);
5396 if (errno) {
5397 posix_error();
5398 goto fail;
5399 }
5400 all_flags |= POSIX_SPAWN_SETSIGMASK;
5401 }
5402
5403 if (setsigdef) {
5404 sigset_t set;
5405 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5406 goto fail;
5407 }
5408 errno = posix_spawnattr_setsigdefault(attrp, &set);
5409 if (errno) {
5410 posix_error();
5411 goto fail;
5412 }
5413 all_flags |= POSIX_SPAWN_SETSIGDEF;
5414 }
5415
5416 if (scheduler) {
5417#ifdef POSIX_SPAWN_SETSCHEDULER
5418 PyObject *py_schedpolicy;
5419 struct sched_param schedparam;
5420
5421 if (!PyArg_ParseTuple(scheduler, "OO&"
5422 ";A scheduler tuple must have two elements",
5423 &py_schedpolicy, convert_sched_param, &schedparam)) {
5424 goto fail;
5425 }
5426 if (py_schedpolicy != Py_None) {
5427 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5428
5429 if (schedpolicy == -1 && PyErr_Occurred()) {
5430 goto fail;
5431 }
5432 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5433 if (errno) {
5434 posix_error();
5435 goto fail;
5436 }
5437 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5438 }
5439 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5440 if (errno) {
5441 posix_error();
5442 goto fail;
5443 }
5444 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5445#else
5446 PyErr_SetString(PyExc_NotImplementedError,
5447 "The scheduler option is not supported in this system.");
5448 goto fail;
5449#endif
5450 }
5451
5452 errno = posix_spawnattr_setflags(attrp, all_flags);
5453 if (errno) {
5454 posix_error();
5455 goto fail;
5456 }
5457
5458 return 0;
5459
5460fail:
5461 (void)posix_spawnattr_destroy(attrp);
5462 return -1;
5463}
5464
5465static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005466parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005467 posix_spawn_file_actions_t *file_actionsp,
5468 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005469{
5470 PyObject *seq;
5471 PyObject *file_action = NULL;
5472 PyObject *tag_obj;
5473
5474 seq = PySequence_Fast(file_actions,
5475 "file_actions must be a sequence or None");
5476 if (seq == NULL) {
5477 return -1;
5478 }
5479
5480 errno = posix_spawn_file_actions_init(file_actionsp);
5481 if (errno) {
5482 posix_error();
5483 Py_DECREF(seq);
5484 return -1;
5485 }
5486
Miss Islington (bot)04d46922019-06-26 14:20:09 -07005487 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005488 file_action = PySequence_Fast_GET_ITEM(seq, i);
5489 Py_INCREF(file_action);
5490 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5491 PyErr_SetString(PyExc_TypeError,
5492 "Each file_actions element must be a non-empty tuple");
5493 goto fail;
5494 }
5495 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5496 if (tag == -1 && PyErr_Occurred()) {
5497 goto fail;
5498 }
5499
5500 /* Populate the file_actions object */
5501 switch (tag) {
5502 case POSIX_SPAWN_OPEN: {
5503 int fd, oflag;
5504 PyObject *path;
5505 unsigned long mode;
5506 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5507 ";A open file_action tuple must have 5 elements",
5508 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5509 &oflag, &mode))
5510 {
5511 goto fail;
5512 }
Pablo Galindocb970732018-06-19 09:19:50 +01005513 if (PyList_Append(temp_buffer, path)) {
5514 Py_DECREF(path);
5515 goto fail;
5516 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005517 errno = posix_spawn_file_actions_addopen(file_actionsp,
5518 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005519 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005520 if (errno) {
5521 posix_error();
5522 goto fail;
5523 }
5524 break;
5525 }
5526 case POSIX_SPAWN_CLOSE: {
5527 int fd;
5528 if (!PyArg_ParseTuple(file_action, "Oi"
5529 ";A close file_action tuple must have 2 elements",
5530 &tag_obj, &fd))
5531 {
5532 goto fail;
5533 }
5534 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5535 if (errno) {
5536 posix_error();
5537 goto fail;
5538 }
5539 break;
5540 }
5541 case POSIX_SPAWN_DUP2: {
5542 int fd1, fd2;
5543 if (!PyArg_ParseTuple(file_action, "Oii"
5544 ";A dup2 file_action tuple must have 3 elements",
5545 &tag_obj, &fd1, &fd2))
5546 {
5547 goto fail;
5548 }
5549 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5550 fd1, fd2);
5551 if (errno) {
5552 posix_error();
5553 goto fail;
5554 }
5555 break;
5556 }
5557 default: {
5558 PyErr_SetString(PyExc_TypeError,
5559 "Unknown file_actions identifier");
5560 goto fail;
5561 }
5562 }
5563 Py_DECREF(file_action);
5564 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005565
Serhiy Storchakaef347532018-05-01 16:45:04 +03005566 Py_DECREF(seq);
5567 return 0;
5568
5569fail:
5570 Py_DECREF(seq);
5571 Py_DECREF(file_action);
5572 (void)posix_spawn_file_actions_destroy(file_actionsp);
5573 return -1;
5574}
5575
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005576
5577static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005578py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5579 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005580 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005581 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005582{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005583 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005584 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005585 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005586 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005587 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005588 posix_spawnattr_t attr;
5589 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005590 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005591 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005592 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005593 pid_t pid;
5594 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005595
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005596 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005597 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005598 like posix.environ. */
5599
Serhiy Storchakaef347532018-05-01 16:45:04 +03005600 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005601 PyErr_Format(PyExc_TypeError,
5602 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005603 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005604 }
5605 argc = PySequence_Size(argv);
5606 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005607 PyErr_Format(PyExc_ValueError,
5608 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005609 return NULL;
5610 }
5611
5612 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005613 PyErr_Format(PyExc_TypeError,
5614 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005615 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005616 }
5617
5618 argvlist = parse_arglist(argv, &argc);
5619 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005620 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005621 }
5622 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005623 PyErr_Format(PyExc_ValueError,
5624 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005625 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005626 }
5627
5628 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005629 if (envlist == NULL) {
5630 goto exit;
5631 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005632
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005633 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005634 /* There is a bug in old versions of glibc that makes some of the
5635 * helper functions for manipulating file actions not copy the provided
5636 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5637 * copy the value of path for some old versions of glibc (<2.20).
5638 * The use of temp_buffer here is a workaround that keeps the
5639 * python objects that own the buffers alive until posix_spawn gets called.
5640 * Check https://bugs.python.org/issue33630 and
5641 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5642 temp_buffer = PyList_New(0);
5643 if (!temp_buffer) {
5644 goto exit;
5645 }
5646 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005647 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005648 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005649 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005650 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005651
Victor Stinner325e4ba2019-02-01 15:47:24 +01005652 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5653 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005654 goto exit;
5655 }
5656 attrp = &attr;
5657
Steve Dowera00b5be2020-02-13 08:30:27 +00005658 if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005659 goto exit;
5660 }
5661
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005662 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005663#ifdef HAVE_POSIX_SPAWNP
5664 if (use_posix_spawnp) {
5665 err_code = posix_spawnp(&pid, path->narrow,
5666 file_actionsp, attrp, argvlist, envlist);
5667 }
5668 else
5669#endif /* HAVE_POSIX_SPAWNP */
5670 {
5671 err_code = posix_spawn(&pid, path->narrow,
5672 file_actionsp, attrp, argvlist, envlist);
5673 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005674 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005675
Serhiy Storchakaef347532018-05-01 16:45:04 +03005676 if (err_code) {
5677 errno = err_code;
5678 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005679 goto exit;
5680 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005681#ifdef _Py_MEMORY_SANITIZER
5682 __msan_unpoison(&pid, sizeof(pid));
5683#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005684 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005685
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005686exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005687 if (file_actionsp) {
5688 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005689 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005690 if (attrp) {
5691 (void)posix_spawnattr_destroy(attrp);
5692 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005693 if (envlist) {
5694 free_string_array(envlist, envc);
5695 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005696 if (argvlist) {
5697 free_string_array(argvlist, argc);
5698 }
Pablo Galindocb970732018-06-19 09:19:50 +01005699 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005700 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005701}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005702
5703
5704/*[clinic input]
5705
5706os.posix_spawn
5707 path: path_t
5708 Path of executable file.
5709 argv: object
5710 Tuple or list of strings.
5711 env: object
5712 Dictionary of strings mapping to strings.
5713 /
5714 *
5715 file_actions: object(c_default='NULL') = ()
5716 A sequence of file action tuples.
5717 setpgroup: object = NULL
5718 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5719 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005720 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5721 setsid: bool(accept={int}) = False
5722 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005723 setsigmask: object(c_default='NULL') = ()
5724 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5725 setsigdef: object(c_default='NULL') = ()
5726 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5727 scheduler: object = NULL
5728 A tuple with the scheduler policy (optional) and parameters.
5729
5730Execute the program specified by path in a new process.
5731[clinic start generated code]*/
5732
5733static PyObject *
5734os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5735 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005736 PyObject *setpgroup, int resetids, int setsid,
5737 PyObject *setsigmask, PyObject *setsigdef,
5738 PyObject *scheduler)
5739/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005740{
5741 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005742 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005743 scheduler);
5744}
5745 #endif /* HAVE_POSIX_SPAWN */
5746
5747
5748
5749#ifdef HAVE_POSIX_SPAWNP
5750/*[clinic input]
5751
5752os.posix_spawnp
5753 path: path_t
5754 Path of executable file.
5755 argv: object
5756 Tuple or list of strings.
5757 env: object
5758 Dictionary of strings mapping to strings.
5759 /
5760 *
5761 file_actions: object(c_default='NULL') = ()
5762 A sequence of file action tuples.
5763 setpgroup: object = NULL
5764 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5765 resetids: bool(accept={int}) = False
5766 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005767 setsid: bool(accept={int}) = False
5768 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005769 setsigmask: object(c_default='NULL') = ()
5770 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5771 setsigdef: object(c_default='NULL') = ()
5772 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5773 scheduler: object = NULL
5774 A tuple with the scheduler policy (optional) and parameters.
5775
5776Execute the program specified by path in a new process.
5777[clinic start generated code]*/
5778
5779static PyObject *
5780os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5781 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005782 PyObject *setpgroup, int resetids, int setsid,
5783 PyObject *setsigmask, PyObject *setsigdef,
5784 PyObject *scheduler)
5785/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005786{
5787 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005788 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005789 scheduler);
5790}
5791#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005792
pxinwrf2d7ac72019-05-21 18:46:37 +08005793#ifdef HAVE_RTPSPAWN
5794static intptr_t
5795_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5796 const char *envp[])
5797{
5798 RTP_ID rtpid;
5799 int status;
5800 pid_t res;
5801 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005802
pxinwrf2d7ac72019-05-21 18:46:37 +08005803 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5804 uStackSize=0 cannot be used, the default stack size is too small for
5805 Python. */
5806 if (envp) {
5807 rtpid = rtpSpawn(rtpFileName, argv, envp,
5808 100, 0x1000000, 0, VX_FP_TASK);
5809 }
5810 else {
5811 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5812 100, 0x1000000, 0, VX_FP_TASK);
5813 }
5814 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5815 do {
5816 res = waitpid((pid_t)rtpid, &status, 0);
5817 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5818
5819 if (res < 0)
5820 return RTP_ID_ERROR;
5821 return ((intptr_t)status);
5822 }
5823 return ((intptr_t)rtpid);
5824}
5825#endif
5826
5827#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005828/*[clinic input]
5829os.spawnv
5830
5831 mode: int
5832 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005833 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005834 Path of executable file.
5835 argv: object
5836 Tuple or list of strings.
5837 /
5838
5839Execute the program specified by path in a new process.
5840[clinic start generated code]*/
5841
Larry Hastings2f936352014-08-05 14:04:04 +10005842static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005843os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5844/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005845{
Steve Dowercc16be82016-09-08 10:35:16 -07005846 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005847 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005848 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005849 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005850 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005851
Victor Stinner8c62be82010-05-06 00:08:46 +00005852 /* spawnv has three arguments: (mode, path, argv), where
5853 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005854
Victor Stinner8c62be82010-05-06 00:08:46 +00005855 if (PyList_Check(argv)) {
5856 argc = PyList_Size(argv);
5857 getitem = PyList_GetItem;
5858 }
5859 else if (PyTuple_Check(argv)) {
5860 argc = PyTuple_Size(argv);
5861 getitem = PyTuple_GetItem;
5862 }
5863 else {
5864 PyErr_SetString(PyExc_TypeError,
5865 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005866 return NULL;
5867 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005868 if (argc == 0) {
5869 PyErr_SetString(PyExc_ValueError,
5870 "spawnv() arg 2 cannot be empty");
5871 return NULL;
5872 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005873
Steve Dowercc16be82016-09-08 10:35:16 -07005874 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005875 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005876 return PyErr_NoMemory();
5877 }
5878 for (i = 0; i < argc; i++) {
5879 if (!fsconvert_strdup((*getitem)(argv, i),
5880 &argvlist[i])) {
5881 free_string_array(argvlist, i);
5882 PyErr_SetString(
5883 PyExc_TypeError,
5884 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005885 return NULL;
5886 }
Steve Dower93ff8722016-11-19 19:03:54 -08005887 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005888 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005889 PyErr_SetString(
5890 PyExc_ValueError,
5891 "spawnv() arg 2 first element cannot be empty");
5892 return NULL;
5893 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005894 }
5895 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005896
pxinwrf2d7ac72019-05-21 18:46:37 +08005897#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005898 if (mode == _OLD_P_OVERLAY)
5899 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005900#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005901
Steve Dowera00b5be2020-02-13 08:30:27 +00005902 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08005903 Py_None) < 0) {
5904 free_string_array(argvlist, argc);
5905 return NULL;
5906 }
5907
Victor Stinner8c62be82010-05-06 00:08:46 +00005908 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005909 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005910#ifdef HAVE_WSPAWNV
5911 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005912#elif defined(HAVE_RTPSPAWN)
5913 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005914#else
5915 spawnval = _spawnv(mode, path->narrow, argvlist);
5916#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005917 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005918 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005919
Victor Stinner8c62be82010-05-06 00:08:46 +00005920 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005921
Victor Stinner8c62be82010-05-06 00:08:46 +00005922 if (spawnval == -1)
5923 return posix_error();
5924 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005925 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005926}
5927
Larry Hastings2f936352014-08-05 14:04:04 +10005928/*[clinic input]
5929os.spawnve
5930
5931 mode: int
5932 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005933 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005934 Path of executable file.
5935 argv: object
5936 Tuple or list of strings.
5937 env: object
5938 Dictionary of strings mapping to strings.
5939 /
5940
5941Execute the program specified by path in a new process.
5942[clinic start generated code]*/
5943
Larry Hastings2f936352014-08-05 14:04:04 +10005944static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005945os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005946 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005947/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005948{
Steve Dowercc16be82016-09-08 10:35:16 -07005949 EXECV_CHAR **argvlist;
5950 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005951 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005952 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005953 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005954 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005955 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005956
Victor Stinner8c62be82010-05-06 00:08:46 +00005957 /* spawnve has four arguments: (mode, path, argv, env), where
5958 argv is a list or tuple of strings and env is a dictionary
5959 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005960
Victor Stinner8c62be82010-05-06 00:08:46 +00005961 if (PyList_Check(argv)) {
5962 argc = PyList_Size(argv);
5963 getitem = PyList_GetItem;
5964 }
5965 else if (PyTuple_Check(argv)) {
5966 argc = PyTuple_Size(argv);
5967 getitem = PyTuple_GetItem;
5968 }
5969 else {
5970 PyErr_SetString(PyExc_TypeError,
5971 "spawnve() arg 2 must be a tuple or list");
5972 goto fail_0;
5973 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005974 if (argc == 0) {
5975 PyErr_SetString(PyExc_ValueError,
5976 "spawnve() arg 2 cannot be empty");
5977 goto fail_0;
5978 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005979 if (!PyMapping_Check(env)) {
5980 PyErr_SetString(PyExc_TypeError,
5981 "spawnve() arg 3 must be a mapping object");
5982 goto fail_0;
5983 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005984
Steve Dowercc16be82016-09-08 10:35:16 -07005985 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005986 if (argvlist == NULL) {
5987 PyErr_NoMemory();
5988 goto fail_0;
5989 }
5990 for (i = 0; i < argc; i++) {
5991 if (!fsconvert_strdup((*getitem)(argv, i),
5992 &argvlist[i]))
5993 {
5994 lastarg = i;
5995 goto fail_1;
5996 }
Steve Dowerbce26262016-11-19 19:17:26 -08005997 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005998 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08005999 PyErr_SetString(
6000 PyExc_ValueError,
6001 "spawnv() arg 2 first element cannot be empty");
6002 goto fail_1;
6003 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006004 }
6005 lastarg = argc;
6006 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006007
Victor Stinner8c62be82010-05-06 00:08:46 +00006008 envlist = parse_envlist(env, &envc);
6009 if (envlist == NULL)
6010 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006011
pxinwrf2d7ac72019-05-21 18:46:37 +08006012#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006013 if (mode == _OLD_P_OVERLAY)
6014 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006015#endif
Tim Peters25059d32001-12-07 20:35:43 +00006016
Steve Dowera00b5be2020-02-13 08:30:27 +00006017 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08006018 goto fail_2;
6019 }
6020
Victor Stinner8c62be82010-05-06 00:08:46 +00006021 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006022 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006023#ifdef HAVE_WSPAWNV
6024 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006025#elif defined(HAVE_RTPSPAWN)
6026 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6027 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006028#else
6029 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6030#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006031 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006032 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006033
Victor Stinner8c62be82010-05-06 00:08:46 +00006034 if (spawnval == -1)
6035 (void) posix_error();
6036 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006037 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006038
Miss Islington (bot)3498ac52020-02-04 16:32:32 -08006039 fail_2:
Victor Stinner8c62be82010-05-06 00:08:46 +00006040 while (--envc >= 0)
6041 PyMem_DEL(envlist[envc]);
6042 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006043 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006044 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006045 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006046 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006047}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006048
Guido van Rossuma1065681999-01-25 23:20:23 +00006049#endif /* HAVE_SPAWNV */
6050
6051
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006052#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006053
6054/* Helper function to validate arguments.
6055 Returns 0 on success. non-zero on failure with a TypeError raised.
6056 If obj is non-NULL it must be callable. */
6057static int
6058check_null_or_callable(PyObject *obj, const char* obj_name)
6059{
6060 if (obj && !PyCallable_Check(obj)) {
6061 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
6062 obj_name, Py_TYPE(obj)->tp_name);
6063 return -1;
6064 }
6065 return 0;
6066}
6067
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006068/*[clinic input]
6069os.register_at_fork
6070
Gregory P. Smith163468a2017-05-29 10:03:41 -07006071 *
6072 before: object=NULL
6073 A callable to be called in the parent before the fork() syscall.
6074 after_in_child: object=NULL
6075 A callable to be called in the child after fork().
6076 after_in_parent: object=NULL
6077 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006078
Gregory P. Smith163468a2017-05-29 10:03:41 -07006079Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006080
Gregory P. Smith163468a2017-05-29 10:03:41 -07006081'before' callbacks are called in reverse order.
6082'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006083
6084[clinic start generated code]*/
6085
6086static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006087os_register_at_fork_impl(PyObject *module, PyObject *before,
6088 PyObject *after_in_child, PyObject *after_in_parent)
6089/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006090{
6091 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006092
Gregory P. Smith163468a2017-05-29 10:03:41 -07006093 if (!before && !after_in_child && !after_in_parent) {
6094 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6095 return NULL;
6096 }
6097 if (check_null_or_callable(before, "before") ||
6098 check_null_or_callable(after_in_child, "after_in_child") ||
6099 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006100 return NULL;
6101 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02006102 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006103
Gregory P. Smith163468a2017-05-29 10:03:41 -07006104 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006105 return NULL;
6106 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006107 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006108 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006109 }
6110 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6111 return NULL;
6112 }
6113 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006114}
6115#endif /* HAVE_FORK */
6116
6117
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006118#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006119/*[clinic input]
6120os.fork1
6121
6122Fork a child process with a single multiplexed (i.e., not bound) thread.
6123
6124Return 0 to child process and PID of child to parent process.
6125[clinic start generated code]*/
6126
Larry Hastings2f936352014-08-05 14:04:04 +10006127static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006128os_fork1_impl(PyObject *module)
6129/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006130{
Victor Stinner8c62be82010-05-06 00:08:46 +00006131 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006132
Eric Snow59032962018-09-14 14:17:20 -07006133 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6134 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6135 return NULL;
6136 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006137 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006138 pid = fork1();
6139 if (pid == 0) {
6140 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006141 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006142 } else {
6143 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006144 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006145 }
6146 if (pid == -1)
6147 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006148 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006149}
Larry Hastings2f936352014-08-05 14:04:04 +10006150#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006151
6152
Guido van Rossumad0ee831995-03-01 10:34:45 +00006153#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006154/*[clinic input]
6155os.fork
6156
6157Fork a child process.
6158
6159Return 0 to child process and PID of child to parent process.
6160[clinic start generated code]*/
6161
Larry Hastings2f936352014-08-05 14:04:04 +10006162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006163os_fork_impl(PyObject *module)
6164/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006165{
Victor Stinner8c62be82010-05-06 00:08:46 +00006166 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006167
Eric Snow59032962018-09-14 14:17:20 -07006168 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6169 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6170 return NULL;
6171 }
Steve Dowera00b5be2020-02-13 08:30:27 +00006172 if (PySys_Audit("os.fork", NULL) < 0) {
6173 return NULL;
6174 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006175 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006176 pid = fork();
6177 if (pid == 0) {
6178 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006179 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006180 } else {
6181 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006182 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006183 }
6184 if (pid == -1)
6185 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006186 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006187}
Larry Hastings2f936352014-08-05 14:04:04 +10006188#endif /* HAVE_FORK */
6189
Guido van Rossum85e3b011991-06-03 12:42:10 +00006190
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006191#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006192#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006193/*[clinic input]
6194os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006195
Larry Hastings2f936352014-08-05 14:04:04 +10006196 policy: int
6197
6198Get the maximum scheduling priority for policy.
6199[clinic start generated code]*/
6200
Larry Hastings2f936352014-08-05 14:04:04 +10006201static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006202os_sched_get_priority_max_impl(PyObject *module, int policy)
6203/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006204{
6205 int max;
6206
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006207 max = sched_get_priority_max(policy);
6208 if (max < 0)
6209 return posix_error();
6210 return PyLong_FromLong(max);
6211}
6212
Larry Hastings2f936352014-08-05 14:04:04 +10006213
6214/*[clinic input]
6215os.sched_get_priority_min
6216
6217 policy: int
6218
6219Get the minimum scheduling priority for policy.
6220[clinic start generated code]*/
6221
Larry Hastings2f936352014-08-05 14:04:04 +10006222static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006223os_sched_get_priority_min_impl(PyObject *module, int policy)
6224/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006225{
6226 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006227 if (min < 0)
6228 return posix_error();
6229 return PyLong_FromLong(min);
6230}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006231#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6232
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006233
Larry Hastings2f936352014-08-05 14:04:04 +10006234#ifdef HAVE_SCHED_SETSCHEDULER
6235/*[clinic input]
6236os.sched_getscheduler
6237 pid: pid_t
6238 /
6239
6240Get the scheduling policy for the process identifiedy by pid.
6241
6242Passing 0 for pid returns the scheduling policy for the calling process.
6243[clinic start generated code]*/
6244
Larry Hastings2f936352014-08-05 14:04:04 +10006245static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006246os_sched_getscheduler_impl(PyObject *module, pid_t pid)
6247/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=5f14cfd1f189e1a0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006248{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006249 int policy;
6250
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006251 policy = sched_getscheduler(pid);
6252 if (policy < 0)
6253 return posix_error();
6254 return PyLong_FromLong(policy);
6255}
Larry Hastings2f936352014-08-05 14:04:04 +10006256#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006257
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006258
William Orr81574b82018-10-01 22:19:56 -07006259#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006260/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006261class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006262
6263@classmethod
6264os.sched_param.__new__
6265
6266 sched_priority: object
6267 A scheduling parameter.
6268
6269Current has only one field: sched_priority");
6270[clinic start generated code]*/
6271
Larry Hastings2f936352014-08-05 14:04:04 +10006272static PyObject *
6273os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006274/*[clinic end generated code: output=48f4067d60f48c13 input=ab4de35a9a7811f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006275{
6276 PyObject *res;
6277
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006278 res = PyStructSequence_New(type);
6279 if (!res)
6280 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006281 Py_INCREF(sched_priority);
6282 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006283 return res;
6284}
6285
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006286
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006287PyDoc_VAR(os_sched_param__doc__);
6288
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006289static PyStructSequence_Field sched_param_fields[] = {
6290 {"sched_priority", "the scheduling priority"},
6291 {0}
6292};
6293
6294static PyStructSequence_Desc sched_param_desc = {
6295 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006296 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006297 sched_param_fields,
6298 1
6299};
6300
6301static int
6302convert_sched_param(PyObject *param, struct sched_param *res)
6303{
6304 long priority;
6305
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006306 if (Py_TYPE(param) != SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006307 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6308 return 0;
6309 }
6310 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6311 if (priority == -1 && PyErr_Occurred())
6312 return 0;
6313 if (priority > INT_MAX || priority < INT_MIN) {
6314 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6315 return 0;
6316 }
6317 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6318 return 1;
6319}
William Orr81574b82018-10-01 22:19:56 -07006320#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006321
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006322
6323#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006324/*[clinic input]
6325os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006326
Larry Hastings2f936352014-08-05 14:04:04 +10006327 pid: pid_t
6328 policy: int
6329 param: sched_param
6330 /
6331
6332Set the scheduling policy for the process identified by pid.
6333
6334If pid is 0, the calling process is changed.
6335param is an instance of sched_param.
6336[clinic start generated code]*/
6337
Larry Hastings2f936352014-08-05 14:04:04 +10006338static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006339os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006340 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006341/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006342{
Jesus Cea9c822272011-09-10 01:40:52 +02006343 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006344 ** sched_setscheduler() returns 0 in Linux, but the previous
6345 ** scheduling policy under Solaris/Illumos, and others.
6346 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006347 */
Larry Hastings2f936352014-08-05 14:04:04 +10006348 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006349 return posix_error();
6350 Py_RETURN_NONE;
6351}
Larry Hastings2f936352014-08-05 14:04:04 +10006352#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006353
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006354
6355#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006356/*[clinic input]
6357os.sched_getparam
6358 pid: pid_t
6359 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006360
Larry Hastings2f936352014-08-05 14:04:04 +10006361Returns scheduling parameters for the process identified by pid.
6362
6363If pid is 0, returns parameters for the calling process.
6364Return value is an instance of sched_param.
6365[clinic start generated code]*/
6366
Larry Hastings2f936352014-08-05 14:04:04 +10006367static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006368os_sched_getparam_impl(PyObject *module, pid_t pid)
6369/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006370{
6371 struct sched_param param;
6372 PyObject *result;
6373 PyObject *priority;
6374
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006375 if (sched_getparam(pid, &param))
6376 return posix_error();
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006377 result = PyStructSequence_New(SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006378 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006379 return NULL;
6380 priority = PyLong_FromLong(param.sched_priority);
6381 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006382 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006383 return NULL;
6384 }
Larry Hastings2f936352014-08-05 14:04:04 +10006385 PyStructSequence_SET_ITEM(result, 0, priority);
6386 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006387}
6388
Larry Hastings2f936352014-08-05 14:04:04 +10006389
6390/*[clinic input]
6391os.sched_setparam
6392 pid: pid_t
6393 param: sched_param
6394 /
6395
6396Set scheduling parameters for the process identified by pid.
6397
6398If pid is 0, sets parameters for the calling process.
6399param should be an instance of sched_param.
6400[clinic start generated code]*/
6401
Larry Hastings2f936352014-08-05 14:04:04 +10006402static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006403os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006404 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006405/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006406{
6407 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006408 return posix_error();
6409 Py_RETURN_NONE;
6410}
Larry Hastings2f936352014-08-05 14:04:04 +10006411#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006412
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006413
6414#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006415/*[clinic input]
6416os.sched_rr_get_interval -> double
6417 pid: pid_t
6418 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006419
Larry Hastings2f936352014-08-05 14:04:04 +10006420Return the round-robin quantum for the process identified by pid, in seconds.
6421
6422Value returned is a float.
6423[clinic start generated code]*/
6424
Larry Hastings2f936352014-08-05 14:04:04 +10006425static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006426os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6427/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006428{
6429 struct timespec interval;
6430 if (sched_rr_get_interval(pid, &interval)) {
6431 posix_error();
6432 return -1.0;
6433 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006434#ifdef _Py_MEMORY_SANITIZER
6435 __msan_unpoison(&interval, sizeof(interval));
6436#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006437 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6438}
6439#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006440
Larry Hastings2f936352014-08-05 14:04:04 +10006441
6442/*[clinic input]
6443os.sched_yield
6444
6445Voluntarily relinquish the CPU.
6446[clinic start generated code]*/
6447
Larry Hastings2f936352014-08-05 14:04:04 +10006448static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006449os_sched_yield_impl(PyObject *module)
6450/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006451{
6452 if (sched_yield())
6453 return posix_error();
6454 Py_RETURN_NONE;
6455}
6456
Benjamin Peterson2740af82011-08-02 17:41:34 -05006457#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006458/* The minimum number of CPUs allocated in a cpu_set_t */
6459static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006460
Larry Hastings2f936352014-08-05 14:04:04 +10006461/*[clinic input]
6462os.sched_setaffinity
6463 pid: pid_t
6464 mask : object
6465 /
6466
6467Set the CPU affinity of the process identified by pid to mask.
6468
6469mask should be an iterable of integers identifying CPUs.
6470[clinic start generated code]*/
6471
Larry Hastings2f936352014-08-05 14:04:04 +10006472static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006473os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6474/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006475{
Antoine Pitrou84869872012-08-04 16:16:35 +02006476 int ncpus;
6477 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006478 cpu_set_t *cpu_set = NULL;
6479 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006480
Larry Hastings2f936352014-08-05 14:04:04 +10006481 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006482 if (iterator == NULL)
6483 return NULL;
6484
6485 ncpus = NCPUS_START;
6486 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006487 cpu_set = CPU_ALLOC(ncpus);
6488 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006489 PyErr_NoMemory();
6490 goto error;
6491 }
Larry Hastings2f936352014-08-05 14:04:04 +10006492 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006493
6494 while ((item = PyIter_Next(iterator))) {
6495 long cpu;
6496 if (!PyLong_Check(item)) {
6497 PyErr_Format(PyExc_TypeError,
6498 "expected an iterator of ints, "
6499 "but iterator yielded %R",
6500 Py_TYPE(item));
6501 Py_DECREF(item);
6502 goto error;
6503 }
6504 cpu = PyLong_AsLong(item);
6505 Py_DECREF(item);
6506 if (cpu < 0) {
6507 if (!PyErr_Occurred())
6508 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6509 goto error;
6510 }
6511 if (cpu > INT_MAX - 1) {
6512 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6513 goto error;
6514 }
6515 if (cpu >= ncpus) {
6516 /* Grow CPU mask to fit the CPU number */
6517 int newncpus = ncpus;
6518 cpu_set_t *newmask;
6519 size_t newsetsize;
6520 while (newncpus <= cpu) {
6521 if (newncpus > INT_MAX / 2)
6522 newncpus = cpu + 1;
6523 else
6524 newncpus = newncpus * 2;
6525 }
6526 newmask = CPU_ALLOC(newncpus);
6527 if (newmask == NULL) {
6528 PyErr_NoMemory();
6529 goto error;
6530 }
6531 newsetsize = CPU_ALLOC_SIZE(newncpus);
6532 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006533 memcpy(newmask, cpu_set, setsize);
6534 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006535 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006536 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006537 ncpus = newncpus;
6538 }
Larry Hastings2f936352014-08-05 14:04:04 +10006539 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006540 }
Miss Islington (bot)6fbed532019-06-27 09:45:30 -07006541 if (PyErr_Occurred()) {
6542 goto error;
6543 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006544 Py_CLEAR(iterator);
6545
Larry Hastings2f936352014-08-05 14:04:04 +10006546 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006547 posix_error();
6548 goto error;
6549 }
Larry Hastings2f936352014-08-05 14:04:04 +10006550 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006551 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006552
6553error:
Larry Hastings2f936352014-08-05 14:04:04 +10006554 if (cpu_set)
6555 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006556 Py_XDECREF(iterator);
6557 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006558}
6559
Larry Hastings2f936352014-08-05 14:04:04 +10006560
6561/*[clinic input]
6562os.sched_getaffinity
6563 pid: pid_t
6564 /
6565
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006566Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006567
6568The affinity is returned as a set of CPU identifiers.
6569[clinic start generated code]*/
6570
Larry Hastings2f936352014-08-05 14:04:04 +10006571static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006572os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006573/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006574{
Antoine Pitrou84869872012-08-04 16:16:35 +02006575 int cpu, ncpus, count;
6576 size_t setsize;
6577 cpu_set_t *mask = NULL;
6578 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006579
Antoine Pitrou84869872012-08-04 16:16:35 +02006580 ncpus = NCPUS_START;
6581 while (1) {
6582 setsize = CPU_ALLOC_SIZE(ncpus);
6583 mask = CPU_ALLOC(ncpus);
6584 if (mask == NULL)
6585 return PyErr_NoMemory();
6586 if (sched_getaffinity(pid, setsize, mask) == 0)
6587 break;
6588 CPU_FREE(mask);
6589 if (errno != EINVAL)
6590 return posix_error();
6591 if (ncpus > INT_MAX / 2) {
6592 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6593 "a large enough CPU set");
6594 return NULL;
6595 }
6596 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006597 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006598
6599 res = PySet_New(NULL);
6600 if (res == NULL)
6601 goto error;
6602 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6603 if (CPU_ISSET_S(cpu, setsize, mask)) {
6604 PyObject *cpu_num = PyLong_FromLong(cpu);
6605 --count;
6606 if (cpu_num == NULL)
6607 goto error;
6608 if (PySet_Add(res, cpu_num)) {
6609 Py_DECREF(cpu_num);
6610 goto error;
6611 }
6612 Py_DECREF(cpu_num);
6613 }
6614 }
6615 CPU_FREE(mask);
6616 return res;
6617
6618error:
6619 if (mask)
6620 CPU_FREE(mask);
6621 Py_XDECREF(res);
6622 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006623}
6624
Benjamin Peterson2740af82011-08-02 17:41:34 -05006625#endif /* HAVE_SCHED_SETAFFINITY */
6626
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006627#endif /* HAVE_SCHED_H */
6628
Larry Hastings2f936352014-08-05 14:04:04 +10006629
Neal Norwitzb59798b2003-03-21 01:43:31 +00006630/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006631/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6632#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006633#define DEV_PTY_FILE "/dev/ptc"
6634#define HAVE_DEV_PTMX
6635#else
6636#define DEV_PTY_FILE "/dev/ptmx"
6637#endif
6638
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006639#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006640#ifdef HAVE_PTY_H
6641#include <pty.h>
6642#else
6643#ifdef HAVE_LIBUTIL_H
6644#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006645#else
6646#ifdef HAVE_UTIL_H
6647#include <util.h>
6648#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006649#endif /* HAVE_LIBUTIL_H */
6650#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006651#ifdef HAVE_STROPTS_H
6652#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006653#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006654#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006655
Larry Hastings2f936352014-08-05 14:04:04 +10006656
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006657#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006658/*[clinic input]
6659os.openpty
6660
6661Open a pseudo-terminal.
6662
6663Return a tuple of (master_fd, slave_fd) containing open file descriptors
6664for both the master and slave ends.
6665[clinic start generated code]*/
6666
Larry Hastings2f936352014-08-05 14:04:04 +10006667static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006668os_openpty_impl(PyObject *module)
6669/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006670{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006671 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006672#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006673 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006674#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006675#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006676 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006677#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006678 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006679#endif
6680#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006681
Thomas Wouters70c21a12000-07-14 14:28:33 +00006682#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006683 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006684 goto posix_error;
6685
6686 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6687 goto error;
6688 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6689 goto error;
6690
Neal Norwitzb59798b2003-03-21 01:43:31 +00006691#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006692 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6693 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006694 goto posix_error;
6695 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6696 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006697
Victor Stinnerdaf45552013-08-28 00:53:59 +02006698 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006699 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006700 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006701
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006702#else
Victor Stinner000de532013-11-25 23:19:58 +01006703 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006704 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006705 goto posix_error;
6706
Victor Stinner8c62be82010-05-06 00:08:46 +00006707 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006708
Victor Stinner8c62be82010-05-06 00:08:46 +00006709 /* change permission of slave */
6710 if (grantpt(master_fd) < 0) {
6711 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006712 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006713 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006714
Victor Stinner8c62be82010-05-06 00:08:46 +00006715 /* unlock slave */
6716 if (unlockpt(master_fd) < 0) {
6717 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006718 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006719 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006720
Victor Stinner8c62be82010-05-06 00:08:46 +00006721 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006722
Victor Stinner8c62be82010-05-06 00:08:46 +00006723 slave_name = ptsname(master_fd); /* get name of slave */
6724 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006725 goto posix_error;
6726
6727 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006728 if (slave_fd == -1)
6729 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006730
6731 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6732 goto posix_error;
6733
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006734#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006735 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6736 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006737#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006738 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006739#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006740#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006741#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006742
Victor Stinner8c62be82010-05-06 00:08:46 +00006743 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006744
Victor Stinnerdaf45552013-08-28 00:53:59 +02006745posix_error:
6746 posix_error();
6747error:
6748 if (master_fd != -1)
6749 close(master_fd);
6750 if (slave_fd != -1)
6751 close(slave_fd);
6752 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006753}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006754#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006755
Larry Hastings2f936352014-08-05 14:04:04 +10006756
Fred Drake8cef4cf2000-06-28 16:40:38 +00006757#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006758/*[clinic input]
6759os.forkpty
6760
6761Fork a new process with a new pseudo-terminal as controlling tty.
6762
6763Returns a tuple of (pid, master_fd).
6764Like fork(), return pid of 0 to the child process,
6765and pid of child to the parent process.
6766To both, return fd of newly opened pseudo-terminal.
6767[clinic start generated code]*/
6768
Larry Hastings2f936352014-08-05 14:04:04 +10006769static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006770os_forkpty_impl(PyObject *module)
6771/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006772{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006773 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006774 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006775
Eric Snow59032962018-09-14 14:17:20 -07006776 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6777 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6778 return NULL;
6779 }
Steve Dowera00b5be2020-02-13 08:30:27 +00006780 if (PySys_Audit("os.forkpty", NULL) < 0) {
6781 return NULL;
6782 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006783 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006784 pid = forkpty(&master_fd, NULL, NULL, NULL);
6785 if (pid == 0) {
6786 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006787 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006788 } else {
6789 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006790 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006791 }
6792 if (pid == -1)
6793 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006794 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006795}
Larry Hastings2f936352014-08-05 14:04:04 +10006796#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006797
Ross Lagerwall7807c352011-03-17 20:20:30 +02006798
Guido van Rossumad0ee831995-03-01 10:34:45 +00006799#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006800/*[clinic input]
6801os.getegid
6802
6803Return the current process's effective group id.
6804[clinic start generated code]*/
6805
Larry Hastings2f936352014-08-05 14:04:04 +10006806static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006807os_getegid_impl(PyObject *module)
6808/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006809{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006810 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006811}
Larry Hastings2f936352014-08-05 14:04:04 +10006812#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006813
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006814
Guido van Rossumad0ee831995-03-01 10:34:45 +00006815#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006816/*[clinic input]
6817os.geteuid
6818
6819Return the current process's effective user id.
6820[clinic start generated code]*/
6821
Larry Hastings2f936352014-08-05 14:04:04 +10006822static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006823os_geteuid_impl(PyObject *module)
6824/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006825{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006826 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006827}
Larry Hastings2f936352014-08-05 14:04:04 +10006828#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006829
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006830
Guido van Rossumad0ee831995-03-01 10:34:45 +00006831#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006832/*[clinic input]
6833os.getgid
6834
6835Return the current process's group id.
6836[clinic start generated code]*/
6837
Larry Hastings2f936352014-08-05 14:04:04 +10006838static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006839os_getgid_impl(PyObject *module)
6840/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006841{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006842 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006843}
Larry Hastings2f936352014-08-05 14:04:04 +10006844#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006845
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006846
Berker Peksag39404992016-09-15 20:45:16 +03006847#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006848/*[clinic input]
6849os.getpid
6850
6851Return the current process id.
6852[clinic start generated code]*/
6853
Larry Hastings2f936352014-08-05 14:04:04 +10006854static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006855os_getpid_impl(PyObject *module)
6856/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006857{
Victor Stinner8c62be82010-05-06 00:08:46 +00006858 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006859}
Berker Peksag39404992016-09-15 20:45:16 +03006860#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006861
Miss Islington (bot)c80183e2019-06-13 00:27:23 -07006862#ifdef NGROUPS_MAX
6863#define MAX_GROUPS NGROUPS_MAX
6864#else
6865 /* defined to be 16 on Solaris7, so this should be a small number */
6866#define MAX_GROUPS 64
6867#endif
6868
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006869#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006870
6871/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006872PyDoc_STRVAR(posix_getgrouplist__doc__,
6873"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6874Returns a list of groups to which a user belongs.\n\n\
6875 user: username to lookup\n\
6876 group: base group id of the user");
6877
6878static PyObject *
6879posix_getgrouplist(PyObject *self, PyObject *args)
6880{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006881 const char *user;
6882 int i, ngroups;
6883 PyObject *list;
6884#ifdef __APPLE__
6885 int *groups, basegid;
6886#else
6887 gid_t *groups, basegid;
6888#endif
Miss Islington (bot)c80183e2019-06-13 00:27:23 -07006889
6890 /*
6891 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6892 * number of supplimental groups a users can belong to.
6893 * We have to increment it by one because
6894 * getgrouplist() returns both the supplemental groups
6895 * and the primary group, i.e. all of the groups the
6896 * user belongs to.
6897 */
6898 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006899
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006900#ifdef __APPLE__
6901 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006902 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006903#else
6904 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6905 _Py_Gid_Converter, &basegid))
6906 return NULL;
6907#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006908
6909#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006910 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006911#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006912 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006913#endif
6914 if (groups == NULL)
6915 return PyErr_NoMemory();
6916
6917 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6918 PyMem_Del(groups);
6919 return posix_error();
6920 }
6921
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006922#ifdef _Py_MEMORY_SANITIZER
6923 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6924 __msan_unpoison(&ngroups, sizeof(ngroups));
6925 __msan_unpoison(groups, ngroups*sizeof(*groups));
6926#endif
6927
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006928 list = PyList_New(ngroups);
6929 if (list == NULL) {
6930 PyMem_Del(groups);
6931 return NULL;
6932 }
6933
6934 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006935#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006936 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006937#else
6938 PyObject *o = _PyLong_FromGid(groups[i]);
6939#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006940 if (o == NULL) {
6941 Py_DECREF(list);
6942 PyMem_Del(groups);
6943 return NULL;
6944 }
6945 PyList_SET_ITEM(list, i, o);
6946 }
6947
6948 PyMem_Del(groups);
6949
6950 return list;
6951}
Larry Hastings2f936352014-08-05 14:04:04 +10006952#endif /* HAVE_GETGROUPLIST */
6953
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006954
Fred Drakec9680921999-12-13 16:37:25 +00006955#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006956/*[clinic input]
6957os.getgroups
6958
6959Return list of supplemental group IDs for the process.
6960[clinic start generated code]*/
6961
Larry Hastings2f936352014-08-05 14:04:04 +10006962static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006963os_getgroups_impl(PyObject *module)
6964/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006965{
6966 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00006967 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006968
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006969 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006970 * This is a helper variable to store the intermediate result when
6971 * that happens.
6972 *
6973 * To keep the code readable the OSX behaviour is unconditional,
6974 * according to the POSIX spec this should be safe on all unix-y
6975 * systems.
6976 */
6977 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006978 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006979
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006980#ifdef __APPLE__
6981 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6982 * there are more groups than can fit in grouplist. Therefore, on OS X
6983 * always first call getgroups with length 0 to get the actual number
6984 * of groups.
6985 */
6986 n = getgroups(0, NULL);
6987 if (n < 0) {
6988 return posix_error();
6989 } else if (n <= MAX_GROUPS) {
6990 /* groups will fit in existing array */
6991 alt_grouplist = grouplist;
6992 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006993 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006994 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006995 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006996 }
6997 }
6998
6999 n = getgroups(n, alt_grouplist);
7000 if (n == -1) {
7001 if (alt_grouplist != grouplist) {
7002 PyMem_Free(alt_grouplist);
7003 }
7004 return posix_error();
7005 }
7006#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007007 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007008 if (n < 0) {
7009 if (errno == EINVAL) {
7010 n = getgroups(0, NULL);
7011 if (n == -1) {
7012 return posix_error();
7013 }
7014 if (n == 0) {
7015 /* Avoid malloc(0) */
7016 alt_grouplist = grouplist;
7017 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007018 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007019 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007020 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007021 }
7022 n = getgroups(n, alt_grouplist);
7023 if (n == -1) {
7024 PyMem_Free(alt_grouplist);
7025 return posix_error();
7026 }
7027 }
7028 } else {
7029 return posix_error();
7030 }
7031 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007032#endif
7033
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007034 result = PyList_New(n);
7035 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007036 int i;
7037 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007038 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007039 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007040 Py_DECREF(result);
7041 result = NULL;
7042 break;
Fred Drakec9680921999-12-13 16:37:25 +00007043 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007044 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007045 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007046 }
7047
7048 if (alt_grouplist != grouplist) {
7049 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007050 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007051
Fred Drakec9680921999-12-13 16:37:25 +00007052 return result;
7053}
Larry Hastings2f936352014-08-05 14:04:04 +10007054#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007055
Antoine Pitroub7572f02009-12-02 20:46:48 +00007056#ifdef HAVE_INITGROUPS
7057PyDoc_STRVAR(posix_initgroups__doc__,
7058"initgroups(username, gid) -> None\n\n\
7059Call the system initgroups() to initialize the group access list with all of\n\
7060the groups of which the specified username is a member, plus the specified\n\
7061group id.");
7062
Larry Hastings2f936352014-08-05 14:04:04 +10007063/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00007064static PyObject *
7065posix_initgroups(PyObject *self, PyObject *args)
7066{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007067 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007068 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007069 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007070#ifdef __APPLE__
7071 int gid;
7072#else
7073 gid_t gid;
7074#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007075
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007076#ifdef __APPLE__
7077 if (!PyArg_ParseTuple(args, "O&i:initgroups",
7078 PyUnicode_FSConverter, &oname,
7079 &gid))
7080#else
7081 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
7082 PyUnicode_FSConverter, &oname,
7083 _Py_Gid_Converter, &gid))
7084#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00007085 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007086 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007087
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007088 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007089 Py_DECREF(oname);
7090 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007091 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007092
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007093 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007094}
Larry Hastings2f936352014-08-05 14:04:04 +10007095#endif /* HAVE_INITGROUPS */
7096
Antoine Pitroub7572f02009-12-02 20:46:48 +00007097
Martin v. Löwis606edc12002-06-13 21:09:11 +00007098#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007099/*[clinic input]
7100os.getpgid
7101
7102 pid: pid_t
7103
7104Call the system call getpgid(), and return the result.
7105[clinic start generated code]*/
7106
Larry Hastings2f936352014-08-05 14:04:04 +10007107static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007108os_getpgid_impl(PyObject *module, pid_t pid)
7109/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007110{
7111 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007112 if (pgid < 0)
7113 return posix_error();
7114 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007115}
7116#endif /* HAVE_GETPGID */
7117
7118
Guido van Rossumb6775db1994-08-01 11:34:53 +00007119#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007120/*[clinic input]
7121os.getpgrp
7122
7123Return the current process group id.
7124[clinic start generated code]*/
7125
Larry Hastings2f936352014-08-05 14:04:04 +10007126static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007127os_getpgrp_impl(PyObject *module)
7128/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007129{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007130#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007131 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007132#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007133 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007134#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007135}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007136#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007137
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007138
Guido van Rossumb6775db1994-08-01 11:34:53 +00007139#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007140/*[clinic input]
7141os.setpgrp
7142
7143Make the current process the leader of its process group.
7144[clinic start generated code]*/
7145
Larry Hastings2f936352014-08-05 14:04:04 +10007146static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007147os_setpgrp_impl(PyObject *module)
7148/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007149{
Guido van Rossum64933891994-10-20 21:56:42 +00007150#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007151 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007152#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007153 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007154#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007155 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007156 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007157}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007158#endif /* HAVE_SETPGRP */
7159
Guido van Rossumad0ee831995-03-01 10:34:45 +00007160#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007161
7162#ifdef MS_WINDOWS
7163#include <tlhelp32.h>
7164
7165static PyObject*
7166win32_getppid()
7167{
7168 HANDLE snapshot;
7169 pid_t mypid;
7170 PyObject* result = NULL;
7171 BOOL have_record;
7172 PROCESSENTRY32 pe;
7173
7174 mypid = getpid(); /* This function never fails */
7175
7176 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7177 if (snapshot == INVALID_HANDLE_VALUE)
7178 return PyErr_SetFromWindowsErr(GetLastError());
7179
7180 pe.dwSize = sizeof(pe);
7181 have_record = Process32First(snapshot, &pe);
7182 while (have_record) {
7183 if (mypid == (pid_t)pe.th32ProcessID) {
7184 /* We could cache the ulong value in a static variable. */
7185 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7186 break;
7187 }
7188
7189 have_record = Process32Next(snapshot, &pe);
7190 }
7191
7192 /* If our loop exits and our pid was not found (result will be NULL)
7193 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7194 * error anyway, so let's raise it. */
7195 if (!result)
7196 result = PyErr_SetFromWindowsErr(GetLastError());
7197
7198 CloseHandle(snapshot);
7199
7200 return result;
7201}
7202#endif /*MS_WINDOWS*/
7203
Larry Hastings2f936352014-08-05 14:04:04 +10007204
7205/*[clinic input]
7206os.getppid
7207
7208Return the parent's process id.
7209
7210If the parent process has already exited, Windows machines will still
7211return its id; others systems will return the id of the 'init' process (1).
7212[clinic start generated code]*/
7213
Larry Hastings2f936352014-08-05 14:04:04 +10007214static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007215os_getppid_impl(PyObject *module)
7216/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007217{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007218#ifdef MS_WINDOWS
7219 return win32_getppid();
7220#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007221 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007222#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007223}
7224#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007225
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007226
Fred Drake12c6e2d1999-12-14 21:25:03 +00007227#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007228/*[clinic input]
7229os.getlogin
7230
7231Return the actual login name.
7232[clinic start generated code]*/
7233
Larry Hastings2f936352014-08-05 14:04:04 +10007234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007235os_getlogin_impl(PyObject *module)
7236/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007237{
Victor Stinner8c62be82010-05-06 00:08:46 +00007238 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007239#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007240 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007241 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007242
7243 if (GetUserNameW(user_name, &num_chars)) {
7244 /* num_chars is the number of unicode chars plus null terminator */
7245 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007246 }
7247 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007248 result = PyErr_SetFromWindowsErr(GetLastError());
7249#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007250 char *name;
7251 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007252
Victor Stinner8c62be82010-05-06 00:08:46 +00007253 errno = 0;
7254 name = getlogin();
7255 if (name == NULL) {
7256 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007257 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007258 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007259 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007260 }
7261 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007262 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007263 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007264#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007265 return result;
7266}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007267#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007268
Larry Hastings2f936352014-08-05 14:04:04 +10007269
Guido van Rossumad0ee831995-03-01 10:34:45 +00007270#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007271/*[clinic input]
7272os.getuid
7273
7274Return the current process's user id.
7275[clinic start generated code]*/
7276
Larry Hastings2f936352014-08-05 14:04:04 +10007277static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007278os_getuid_impl(PyObject *module)
7279/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007280{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007281 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007282}
Larry Hastings2f936352014-08-05 14:04:04 +10007283#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007284
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007285
Brian Curtineb24d742010-04-12 17:16:38 +00007286#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007287#define HAVE_KILL
7288#endif /* MS_WINDOWS */
7289
7290#ifdef HAVE_KILL
7291/*[clinic input]
7292os.kill
7293
7294 pid: pid_t
7295 signal: Py_ssize_t
7296 /
7297
7298Kill a process with a signal.
7299[clinic start generated code]*/
7300
Larry Hastings2f936352014-08-05 14:04:04 +10007301static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007302os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7303/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007304{
Steve Dowera00b5be2020-02-13 08:30:27 +00007305 if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
7306 return NULL;
7307 }
7308#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007309 if (kill(pid, (int)signal) == -1)
7310 return posix_error();
7311 Py_RETURN_NONE;
Larry Hastings2f936352014-08-05 14:04:04 +10007312#else /* !MS_WINDOWS */
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007313 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007314 DWORD sig = (DWORD)signal;
7315 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007316 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007317
Victor Stinner8c62be82010-05-06 00:08:46 +00007318 /* Console processes which share a common console can be sent CTRL+C or
7319 CTRL+BREAK events, provided they handle said events. */
7320 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007321 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007322 err = GetLastError();
7323 PyErr_SetFromWindowsErr(err);
7324 }
7325 else
7326 Py_RETURN_NONE;
7327 }
Brian Curtineb24d742010-04-12 17:16:38 +00007328
Victor Stinner8c62be82010-05-06 00:08:46 +00007329 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7330 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007331 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007332 if (handle == NULL) {
7333 err = GetLastError();
7334 return PyErr_SetFromWindowsErr(err);
7335 }
Brian Curtineb24d742010-04-12 17:16:38 +00007336
Victor Stinner8c62be82010-05-06 00:08:46 +00007337 if (TerminateProcess(handle, sig) == 0) {
7338 err = GetLastError();
7339 result = PyErr_SetFromWindowsErr(err);
7340 } else {
7341 Py_INCREF(Py_None);
7342 result = Py_None;
7343 }
Brian Curtineb24d742010-04-12 17:16:38 +00007344
Victor Stinner8c62be82010-05-06 00:08:46 +00007345 CloseHandle(handle);
7346 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10007347#endif /* !MS_WINDOWS */
Steve Dowera00b5be2020-02-13 08:30:27 +00007348}
Larry Hastings2f936352014-08-05 14:04:04 +10007349#endif /* HAVE_KILL */
7350
7351
7352#ifdef HAVE_KILLPG
7353/*[clinic input]
7354os.killpg
7355
7356 pgid: pid_t
7357 signal: int
7358 /
7359
7360Kill a process group with a signal.
7361[clinic start generated code]*/
7362
Larry Hastings2f936352014-08-05 14:04:04 +10007363static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007364os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7365/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007366{
Steve Dowera00b5be2020-02-13 08:30:27 +00007367 if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
7368 return NULL;
7369 }
Larry Hastings2f936352014-08-05 14:04:04 +10007370 /* XXX some man pages make the `pgid` parameter an int, others
7371 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7372 take the same type. Moreover, pid_t is always at least as wide as
7373 int (else compilation of this module fails), which is safe. */
7374 if (killpg(pgid, signal) == -1)
7375 return posix_error();
7376 Py_RETURN_NONE;
7377}
7378#endif /* HAVE_KILLPG */
7379
Brian Curtineb24d742010-04-12 17:16:38 +00007380
Guido van Rossumc0125471996-06-28 18:55:32 +00007381#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007382#ifdef HAVE_SYS_LOCK_H
7383#include <sys/lock.h>
7384#endif
7385
Larry Hastings2f936352014-08-05 14:04:04 +10007386/*[clinic input]
7387os.plock
7388 op: int
7389 /
7390
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007391Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007392[clinic start generated code]*/
7393
Larry Hastings2f936352014-08-05 14:04:04 +10007394static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007395os_plock_impl(PyObject *module, int op)
7396/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007397{
Victor Stinner8c62be82010-05-06 00:08:46 +00007398 if (plock(op) == -1)
7399 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007400 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007401}
Larry Hastings2f936352014-08-05 14:04:04 +10007402#endif /* HAVE_PLOCK */
7403
Guido van Rossumc0125471996-06-28 18:55:32 +00007404
Guido van Rossumb6775db1994-08-01 11:34:53 +00007405#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007406/*[clinic input]
7407os.setuid
7408
7409 uid: uid_t
7410 /
7411
7412Set the current process's user id.
7413[clinic start generated code]*/
7414
Larry Hastings2f936352014-08-05 14:04:04 +10007415static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007416os_setuid_impl(PyObject *module, uid_t uid)
7417/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007418{
Victor Stinner8c62be82010-05-06 00:08:46 +00007419 if (setuid(uid) < 0)
7420 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007421 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007422}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007423#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007424
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007425
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007426#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007427/*[clinic input]
7428os.seteuid
7429
7430 euid: uid_t
7431 /
7432
7433Set the current process's effective user id.
7434[clinic start generated code]*/
7435
Larry Hastings2f936352014-08-05 14:04:04 +10007436static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007437os_seteuid_impl(PyObject *module, uid_t euid)
7438/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007439{
7440 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007441 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007442 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007443}
7444#endif /* HAVE_SETEUID */
7445
Larry Hastings2f936352014-08-05 14:04:04 +10007446
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007447#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007448/*[clinic input]
7449os.setegid
7450
7451 egid: gid_t
7452 /
7453
7454Set the current process's effective group id.
7455[clinic start generated code]*/
7456
Larry Hastings2f936352014-08-05 14:04:04 +10007457static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007458os_setegid_impl(PyObject *module, gid_t egid)
7459/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007460{
7461 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007462 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007463 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007464}
7465#endif /* HAVE_SETEGID */
7466
Larry Hastings2f936352014-08-05 14:04:04 +10007467
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007468#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007469/*[clinic input]
7470os.setreuid
7471
7472 ruid: uid_t
7473 euid: uid_t
7474 /
7475
7476Set the current process's real and effective user ids.
7477[clinic start generated code]*/
7478
Larry Hastings2f936352014-08-05 14:04:04 +10007479static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007480os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7481/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007482{
Victor Stinner8c62be82010-05-06 00:08:46 +00007483 if (setreuid(ruid, euid) < 0) {
7484 return posix_error();
7485 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007486 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007487 }
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007488}
7489#endif /* HAVE_SETREUID */
7490
Larry Hastings2f936352014-08-05 14:04:04 +10007491
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007492#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007493/*[clinic input]
7494os.setregid
7495
7496 rgid: gid_t
7497 egid: gid_t
7498 /
7499
7500Set the current process's real and effective group ids.
7501[clinic start generated code]*/
7502
Larry Hastings2f936352014-08-05 14:04:04 +10007503static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007504os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7505/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007506{
7507 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007508 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007509 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007510}
7511#endif /* HAVE_SETREGID */
7512
Larry Hastings2f936352014-08-05 14:04:04 +10007513
Guido van Rossumb6775db1994-08-01 11:34:53 +00007514#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007515/*[clinic input]
7516os.setgid
7517 gid: gid_t
7518 /
7519
7520Set the current process's group id.
7521[clinic start generated code]*/
7522
Larry Hastings2f936352014-08-05 14:04:04 +10007523static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007524os_setgid_impl(PyObject *module, gid_t gid)
7525/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007526{
Victor Stinner8c62be82010-05-06 00:08:46 +00007527 if (setgid(gid) < 0)
7528 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007529 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007530}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007531#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007532
Larry Hastings2f936352014-08-05 14:04:04 +10007533
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007534#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007535/*[clinic input]
7536os.setgroups
7537
7538 groups: object
7539 /
7540
7541Set the groups of the current process to list.
7542[clinic start generated code]*/
7543
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007544static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007545os_setgroups(PyObject *module, PyObject *groups)
7546/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007547{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007548 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007549 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007550
Victor Stinner8c62be82010-05-06 00:08:46 +00007551 if (!PySequence_Check(groups)) {
7552 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7553 return NULL;
7554 }
7555 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007556 if (len < 0) {
7557 return NULL;
7558 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007559 if (len > MAX_GROUPS) {
7560 PyErr_SetString(PyExc_ValueError, "too many groups");
7561 return NULL;
7562 }
7563 for(i = 0; i < len; i++) {
7564 PyObject *elem;
7565 elem = PySequence_GetItem(groups, i);
7566 if (!elem)
7567 return NULL;
7568 if (!PyLong_Check(elem)) {
7569 PyErr_SetString(PyExc_TypeError,
7570 "groups must be integers");
7571 Py_DECREF(elem);
7572 return NULL;
7573 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007574 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007575 Py_DECREF(elem);
7576 return NULL;
7577 }
7578 }
7579 Py_DECREF(elem);
7580 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007581
Victor Stinner8c62be82010-05-06 00:08:46 +00007582 if (setgroups(len, grouplist) < 0)
7583 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007584 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007585}
7586#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007587
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007588#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7589static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007590wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007591{
Victor Stinner8c62be82010-05-06 00:08:46 +00007592 PyObject *result;
7593 static PyObject *struct_rusage;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02007594 _Py_IDENTIFIER(struct_rusage);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007595
Victor Stinner8c62be82010-05-06 00:08:46 +00007596 if (pid == -1)
7597 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007598
Victor Stinner8c62be82010-05-06 00:08:46 +00007599 if (struct_rusage == NULL) {
7600 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7601 if (m == NULL)
7602 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02007603 struct_rusage = _PyObject_GetAttrId(m, &PyId_struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007604 Py_DECREF(m);
7605 if (struct_rusage == NULL)
7606 return NULL;
7607 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007608
Victor Stinner8c62be82010-05-06 00:08:46 +00007609 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7610 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
7611 if (!result)
7612 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007613
7614#ifndef doubletime
7615#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7616#endif
7617
Victor Stinner8c62be82010-05-06 00:08:46 +00007618 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007619 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007620 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007621 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007622#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007623 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7624 SET_INT(result, 2, ru->ru_maxrss);
7625 SET_INT(result, 3, ru->ru_ixrss);
7626 SET_INT(result, 4, ru->ru_idrss);
7627 SET_INT(result, 5, ru->ru_isrss);
7628 SET_INT(result, 6, ru->ru_minflt);
7629 SET_INT(result, 7, ru->ru_majflt);
7630 SET_INT(result, 8, ru->ru_nswap);
7631 SET_INT(result, 9, ru->ru_inblock);
7632 SET_INT(result, 10, ru->ru_oublock);
7633 SET_INT(result, 11, ru->ru_msgsnd);
7634 SET_INT(result, 12, ru->ru_msgrcv);
7635 SET_INT(result, 13, ru->ru_nsignals);
7636 SET_INT(result, 14, ru->ru_nvcsw);
7637 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007638#undef SET_INT
7639
Victor Stinner8c62be82010-05-06 00:08:46 +00007640 if (PyErr_Occurred()) {
7641 Py_DECREF(result);
7642 return NULL;
7643 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007644
Victor Stinner8c62be82010-05-06 00:08:46 +00007645 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007646}
7647#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7648
Larry Hastings2f936352014-08-05 14:04:04 +10007649
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007650#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007651/*[clinic input]
7652os.wait3
7653
7654 options: int
7655Wait for completion of a child process.
7656
7657Returns a tuple of information about the child process:
7658 (pid, status, rusage)
7659[clinic start generated code]*/
7660
Larry Hastings2f936352014-08-05 14:04:04 +10007661static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007662os_wait3_impl(PyObject *module, int options)
7663/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007664{
Victor Stinner8c62be82010-05-06 00:08:46 +00007665 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007666 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007667 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007668 WAIT_TYPE status;
7669 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007670
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007671 do {
7672 Py_BEGIN_ALLOW_THREADS
7673 pid = wait3(&status, options, &ru);
7674 Py_END_ALLOW_THREADS
7675 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7676 if (pid < 0)
7677 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007678
Victor Stinner4195b5c2012-02-08 23:03:19 +01007679 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007680}
7681#endif /* HAVE_WAIT3 */
7682
Larry Hastings2f936352014-08-05 14:04:04 +10007683
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007684#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007685/*[clinic input]
7686
7687os.wait4
7688
7689 pid: pid_t
7690 options: int
7691
7692Wait for completion of a specific child process.
7693
7694Returns a tuple of information about the child process:
7695 (pid, status, rusage)
7696[clinic start generated code]*/
7697
Larry Hastings2f936352014-08-05 14:04:04 +10007698static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007699os_wait4_impl(PyObject *module, pid_t pid, int options)
7700/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007701{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007702 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007703 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007704 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007705 WAIT_TYPE status;
7706 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007707
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007708 do {
7709 Py_BEGIN_ALLOW_THREADS
7710 res = wait4(pid, &status, options, &ru);
7711 Py_END_ALLOW_THREADS
7712 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7713 if (res < 0)
7714 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007715
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007716 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007717}
7718#endif /* HAVE_WAIT4 */
7719
Larry Hastings2f936352014-08-05 14:04:04 +10007720
Ross Lagerwall7807c352011-03-17 20:20:30 +02007721#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007722/*[clinic input]
7723os.waitid
7724
7725 idtype: idtype_t
7726 Must be one of be P_PID, P_PGID or P_ALL.
7727 id: id_t
7728 The id to wait on.
7729 options: int
7730 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7731 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7732 /
7733
7734Returns the result of waiting for a process or processes.
7735
7736Returns either waitid_result or None if WNOHANG is specified and there are
7737no children in a waitable state.
7738[clinic start generated code]*/
7739
Larry Hastings2f936352014-08-05 14:04:04 +10007740static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007741os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7742/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007743{
7744 PyObject *result;
7745 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007746 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007747 siginfo_t si;
7748 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007749
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007750 do {
7751 Py_BEGIN_ALLOW_THREADS
7752 res = waitid(idtype, id, &si, options);
7753 Py_END_ALLOW_THREADS
7754 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7755 if (res < 0)
7756 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007757
7758 if (si.si_pid == 0)
7759 Py_RETURN_NONE;
7760
Eddie Elizondo474eedf2018-11-13 04:09:31 -08007761 result = PyStructSequence_New(WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007762 if (!result)
7763 return NULL;
7764
7765 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007766 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007767 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7768 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7769 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7770 if (PyErr_Occurred()) {
7771 Py_DECREF(result);
7772 return NULL;
7773 }
7774
7775 return result;
7776}
Larry Hastings2f936352014-08-05 14:04:04 +10007777#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007778
Larry Hastings2f936352014-08-05 14:04:04 +10007779
7780#if defined(HAVE_WAITPID)
7781/*[clinic input]
7782os.waitpid
7783 pid: pid_t
7784 options: int
7785 /
7786
7787Wait for completion of a given child process.
7788
7789Returns a tuple of information regarding the child process:
7790 (pid, status)
7791
7792The options argument is ignored on Windows.
7793[clinic start generated code]*/
7794
Larry Hastings2f936352014-08-05 14:04:04 +10007795static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007796os_waitpid_impl(PyObject *module, pid_t pid, int options)
7797/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007798{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007799 pid_t res;
7800 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007801 WAIT_TYPE status;
7802 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007803
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007804 do {
7805 Py_BEGIN_ALLOW_THREADS
7806 res = waitpid(pid, &status, options);
7807 Py_END_ALLOW_THREADS
7808 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7809 if (res < 0)
7810 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007811
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007812 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007813}
Tim Petersab034fa2002-02-01 11:27:43 +00007814#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007815/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007816/*[clinic input]
7817os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007818 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007819 options: int
7820 /
7821
7822Wait for completion of a given process.
7823
7824Returns a tuple of information regarding the process:
7825 (pid, status << 8)
7826
7827The options argument is ignored on Windows.
7828[clinic start generated code]*/
7829
Larry Hastings2f936352014-08-05 14:04:04 +10007830static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007831os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007832/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007833{
7834 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007835 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007836 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007837
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007838 do {
7839 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007840 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007841 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007842 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007843 Py_END_ALLOW_THREADS
7844 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007845 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007846 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007847
Victor Stinner8c62be82010-05-06 00:08:46 +00007848 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007849 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007850}
Larry Hastings2f936352014-08-05 14:04:04 +10007851#endif
7852
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007853
Guido van Rossumad0ee831995-03-01 10:34:45 +00007854#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007855/*[clinic input]
7856os.wait
7857
7858Wait for completion of a child process.
7859
7860Returns a tuple of information about the child process:
7861 (pid, status)
7862[clinic start generated code]*/
7863
Larry Hastings2f936352014-08-05 14:04:04 +10007864static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007865os_wait_impl(PyObject *module)
7866/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007867{
Victor Stinner8c62be82010-05-06 00:08:46 +00007868 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007869 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007870 WAIT_TYPE status;
7871 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007872
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007873 do {
7874 Py_BEGIN_ALLOW_THREADS
7875 pid = wait(&status);
7876 Py_END_ALLOW_THREADS
7877 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7878 if (pid < 0)
7879 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007880
Victor Stinner8c62be82010-05-06 00:08:46 +00007881 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007882}
Larry Hastings2f936352014-08-05 14:04:04 +10007883#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007884
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007885
Larry Hastings9cf065c2012-06-22 16:30:09 -07007886#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007887/*[clinic input]
7888os.readlink
7889
7890 path: path_t
7891 *
7892 dir_fd: dir_fd(requires='readlinkat') = None
7893
7894Return a string representing the path to which the symbolic link points.
7895
7896If dir_fd is not None, it should be a file descriptor open to a directory,
7897and path should be relative; path will then be relative to that directory.
7898
7899dir_fd may not be implemented on your platform. If it is unavailable,
7900using it will raise a NotImplementedError.
7901[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007902
Barry Warsaw53699e91996-12-10 23:23:01 +00007903static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007904os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7905/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007906{
Berker Peksage0b5b202018-08-15 13:03:41 +03007907#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007908 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007909 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007910
7911 Py_BEGIN_ALLOW_THREADS
7912#ifdef HAVE_READLINKAT
7913 if (dir_fd != DEFAULT_DIR_FD)
7914 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7915 else
7916#endif
7917 length = readlink(path->narrow, buffer, MAXPATHLEN);
7918 Py_END_ALLOW_THREADS
7919
7920 if (length < 0) {
7921 return path_error(path);
7922 }
7923 buffer[length] = '\0';
7924
7925 if (PyUnicode_Check(path->object))
7926 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7927 else
7928 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007929#elif defined(MS_WINDOWS)
7930 DWORD n_bytes_returned;
Steve Dower9eb3d542019-08-21 15:52:42 -07007931 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03007932 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007933 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7934 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Miss Islington (bot)54dac6c2019-09-03 13:13:41 -07007935 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007936
Larry Hastings2f936352014-08-05 14:04:04 +10007937 /* First get a handle to the reparse point */
7938 Py_BEGIN_ALLOW_THREADS
7939 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007940 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007941 0,
7942 0,
7943 0,
7944 OPEN_EXISTING,
7945 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7946 0);
Steve Dower9eb3d542019-08-21 15:52:42 -07007947 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
7948 /* New call DeviceIoControl to read the reparse point */
7949 io_result = DeviceIoControl(
7950 reparse_point_handle,
7951 FSCTL_GET_REPARSE_POINT,
7952 0, 0, /* in buffer */
7953 target_buffer, sizeof(target_buffer),
7954 &n_bytes_returned,
7955 0 /* we're not using OVERLAPPED_IO */
7956 );
7957 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03007958 }
Larry Hastings2f936352014-08-05 14:04:04 +10007959 Py_END_ALLOW_THREADS
7960
Berker Peksage0b5b202018-08-15 13:03:41 +03007961 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007962 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007963 }
Larry Hastings2f936352014-08-05 14:04:04 +10007964
Steve Dower9eb3d542019-08-21 15:52:42 -07007965 wchar_t *name = NULL;
7966 Py_ssize_t nameLen = 0;
7967 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10007968 {
Steve Dower9eb3d542019-08-21 15:52:42 -07007969 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7970 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
7971 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10007972 }
Steve Dower9eb3d542019-08-21 15:52:42 -07007973 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
7974 {
7975 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
7976 rdb->MountPointReparseBuffer.SubstituteNameOffset);
7977 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
7978 }
7979 else
7980 {
7981 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
7982 }
7983 if (name) {
7984 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
7985 /* Our buffer is mutable, so this is okay */
7986 name[1] = L'\\';
7987 }
7988 result = PyUnicode_FromWideChar(name, nameLen);
Miss Islington (bot)54dac6c2019-09-03 13:13:41 -07007989 if (result && path->narrow) {
Steve Dower9eb3d542019-08-21 15:52:42 -07007990 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
7991 }
Berker Peksage0b5b202018-08-15 13:03:41 +03007992 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007993 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03007994#endif
Larry Hastings2f936352014-08-05 14:04:04 +10007995}
Berker Peksage0b5b202018-08-15 13:03:41 +03007996#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007997
Larry Hastings9cf065c2012-06-22 16:30:09 -07007998#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07007999
8000#if defined(MS_WINDOWS)
8001
Steve Dower6921e732018-03-05 14:26:08 -08008002/* Remove the last portion of the path - return 0 on success */
8003static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008004_dirnameW(WCHAR *path)
8005{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008006 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008007 size_t length = wcsnlen_s(path, MAX_PATH);
8008 if (length == MAX_PATH) {
8009 return -1;
8010 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008011
8012 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008013 for(ptr = path + length; ptr != path; ptr--) {
8014 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008015 break;
Steve Dower6921e732018-03-05 14:26:08 -08008016 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008017 }
8018 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008019 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008020}
8021
Victor Stinner31b3b922013-06-05 01:49:17 +02008022/* Is this path absolute? */
8023static int
8024_is_absW(const WCHAR *path)
8025{
Steve Dower6921e732018-03-05 14:26:08 -08008026 return path[0] == L'\\' || path[0] == L'/' ||
8027 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008028}
8029
Steve Dower6921e732018-03-05 14:26:08 -08008030/* join root and rest with a backslash - return 0 on success */
8031static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008032_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8033{
Victor Stinner31b3b922013-06-05 01:49:17 +02008034 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008035 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008036 }
8037
Steve Dower6921e732018-03-05 14:26:08 -08008038 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8039 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008040 }
Steve Dower6921e732018-03-05 14:26:08 -08008041
8042 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8043 return -1;
8044 }
8045
8046 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008047}
8048
Victor Stinner31b3b922013-06-05 01:49:17 +02008049/* Return True if the path at src relative to dest is a directory */
8050static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008051_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008052{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008053 WIN32_FILE_ATTRIBUTE_DATA src_info;
8054 WCHAR dest_parent[MAX_PATH];
8055 WCHAR src_resolved[MAX_PATH] = L"";
8056
8057 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008058 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8059 _dirnameW(dest_parent)) {
8060 return 0;
8061 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008062 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008063 if (_joinW(src_resolved, dest_parent, src)) {
8064 return 0;
8065 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008066 return (
8067 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8068 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8069 );
8070}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008071#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008072
Larry Hastings2f936352014-08-05 14:04:04 +10008073
8074/*[clinic input]
8075os.symlink
8076 src: path_t
8077 dst: path_t
8078 target_is_directory: bool = False
8079 *
8080 dir_fd: dir_fd(requires='symlinkat')=None
8081
8082# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8083
8084Create a symbolic link pointing to src named dst.
8085
8086target_is_directory is required on Windows if the target is to be
8087 interpreted as a directory. (On Windows, symlink requires
8088 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8089 target_is_directory is ignored on non-Windows platforms.
8090
8091If dir_fd is not None, it should be a file descriptor open to a directory,
8092 and path should be relative; path will then be relative to that directory.
8093dir_fd may not be implemented on your platform.
8094 If it is unavailable, using it will raise a NotImplementedError.
8095
8096[clinic start generated code]*/
8097
Larry Hastings2f936352014-08-05 14:04:04 +10008098static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008099os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008100 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008101/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008102{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008103#ifdef MS_WINDOWS
8104 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008105 DWORD flags = 0;
8106
8107 /* Assumed true, set to false if detected to not be available. */
8108 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008109#else
8110 int result;
8111#endif
8112
Steve Dowera00b5be2020-02-13 08:30:27 +00008113 if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
8114 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
8115 return NULL;
8116 }
8117
Larry Hastings9cf065c2012-06-22 16:30:09 -07008118#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008119
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008120 if (windows_has_symlink_unprivileged_flag) {
8121 /* Allow non-admin symlinks if system allows it. */
8122 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8123 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008124
Larry Hastings9cf065c2012-06-22 16:30:09 -07008125 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008126 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008127 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8128 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8129 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8130 }
8131
8132 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008133 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008134 Py_END_ALLOW_THREADS
8135
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008136 if (windows_has_symlink_unprivileged_flag && !result &&
8137 ERROR_INVALID_PARAMETER == GetLastError()) {
8138
8139 Py_BEGIN_ALLOW_THREADS
8140 _Py_BEGIN_SUPPRESS_IPH
8141 /* This error might be caused by
8142 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8143 Try again, and update windows_has_symlink_unprivileged_flag if we
8144 are successful this time.
8145
8146 NOTE: There is a risk of a race condition here if there are other
8147 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8148 another process (or thread) changes that condition in between our
8149 calls to CreateSymbolicLink.
8150 */
8151 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8152 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8153 _Py_END_SUPPRESS_IPH
8154 Py_END_ALLOW_THREADS
8155
8156 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8157 windows_has_symlink_unprivileged_flag = FALSE;
8158 }
8159 }
8160
Larry Hastings2f936352014-08-05 14:04:04 +10008161 if (!result)
8162 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008163
8164#else
8165
Steve Dower6921e732018-03-05 14:26:08 -08008166 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8167 PyErr_SetString(PyExc_ValueError,
8168 "symlink: src and dst must be the same type");
8169 return NULL;
8170 }
8171
Larry Hastings9cf065c2012-06-22 16:30:09 -07008172 Py_BEGIN_ALLOW_THREADS
8173#if HAVE_SYMLINKAT
8174 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008175 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008176 else
8177#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008178 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008179 Py_END_ALLOW_THREADS
8180
Larry Hastings2f936352014-08-05 14:04:04 +10008181 if (result)
8182 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008183#endif
8184
Larry Hastings2f936352014-08-05 14:04:04 +10008185 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008186}
8187#endif /* HAVE_SYMLINK */
8188
Larry Hastings9cf065c2012-06-22 16:30:09 -07008189
Brian Curtind40e6f72010-07-08 21:39:08 +00008190
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008191
Larry Hastings605a62d2012-06-24 04:33:36 -07008192static PyStructSequence_Field times_result_fields[] = {
8193 {"user", "user time"},
8194 {"system", "system time"},
8195 {"children_user", "user time of children"},
8196 {"children_system", "system time of children"},
8197 {"elapsed", "elapsed time since an arbitrary point in the past"},
8198 {NULL}
8199};
8200
8201PyDoc_STRVAR(times_result__doc__,
8202"times_result: Result from os.times().\n\n\
8203This object may be accessed either as a tuple of\n\
8204 (user, system, children_user, children_system, elapsed),\n\
8205or via the attributes user, system, children_user, children_system,\n\
8206and elapsed.\n\
8207\n\
8208See os.times for more information.");
8209
8210static PyStructSequence_Desc times_result_desc = {
8211 "times_result", /* name */
8212 times_result__doc__, /* doc */
8213 times_result_fields,
8214 5
8215};
8216
Eddie Elizondo474eedf2018-11-13 04:09:31 -08008217static PyTypeObject* TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07008218
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008219#ifdef MS_WINDOWS
8220#define HAVE_TIMES /* mandatory, for the method table */
8221#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008222
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008223#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008224
8225static PyObject *
8226build_times_result(double user, double system,
8227 double children_user, double children_system,
8228 double elapsed)
8229{
Eddie Elizondo474eedf2018-11-13 04:09:31 -08008230 PyObject *value = PyStructSequence_New(TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008231 if (value == NULL)
8232 return NULL;
8233
8234#define SET(i, field) \
8235 { \
8236 PyObject *o = PyFloat_FromDouble(field); \
8237 if (!o) { \
8238 Py_DECREF(value); \
8239 return NULL; \
8240 } \
8241 PyStructSequence_SET_ITEM(value, i, o); \
8242 } \
8243
8244 SET(0, user);
8245 SET(1, system);
8246 SET(2, children_user);
8247 SET(3, children_system);
8248 SET(4, elapsed);
8249
8250#undef SET
8251
8252 return value;
8253}
8254
Larry Hastings605a62d2012-06-24 04:33:36 -07008255
Larry Hastings2f936352014-08-05 14:04:04 +10008256#ifndef MS_WINDOWS
8257#define NEED_TICKS_PER_SECOND
8258static long ticks_per_second = -1;
8259#endif /* MS_WINDOWS */
8260
8261/*[clinic input]
8262os.times
8263
8264Return a collection containing process timing information.
8265
8266The object returned behaves like a named tuple with these fields:
8267 (utime, stime, cutime, cstime, elapsed_time)
8268All fields are floating point numbers.
8269[clinic start generated code]*/
8270
Larry Hastings2f936352014-08-05 14:04:04 +10008271static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008272os_times_impl(PyObject *module)
8273/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008274#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008275{
Victor Stinner8c62be82010-05-06 00:08:46 +00008276 FILETIME create, exit, kernel, user;
8277 HANDLE hProc;
8278 hProc = GetCurrentProcess();
8279 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8280 /* The fields of a FILETIME structure are the hi and lo part
8281 of a 64-bit value expressed in 100 nanosecond units.
8282 1e7 is one second in such units; 1e-7 the inverse.
8283 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8284 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008285 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008286 (double)(user.dwHighDateTime*429.4967296 +
8287 user.dwLowDateTime*1e-7),
8288 (double)(kernel.dwHighDateTime*429.4967296 +
8289 kernel.dwLowDateTime*1e-7),
8290 (double)0,
8291 (double)0,
8292 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008293}
Larry Hastings2f936352014-08-05 14:04:04 +10008294#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008295{
Larry Hastings2f936352014-08-05 14:04:04 +10008296
8297
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008298 struct tms t;
8299 clock_t c;
8300 errno = 0;
8301 c = times(&t);
8302 if (c == (clock_t) -1)
8303 return posix_error();
8304 return build_times_result(
8305 (double)t.tms_utime / ticks_per_second,
8306 (double)t.tms_stime / ticks_per_second,
8307 (double)t.tms_cutime / ticks_per_second,
8308 (double)t.tms_cstime / ticks_per_second,
8309 (double)c / ticks_per_second);
8310}
Larry Hastings2f936352014-08-05 14:04:04 +10008311#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008312#endif /* HAVE_TIMES */
8313
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008314
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008315#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008316/*[clinic input]
8317os.getsid
8318
8319 pid: pid_t
8320 /
8321
8322Call the system call getsid(pid) and return the result.
8323[clinic start generated code]*/
8324
Larry Hastings2f936352014-08-05 14:04:04 +10008325static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008326os_getsid_impl(PyObject *module, pid_t pid)
8327/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008328{
Victor Stinner8c62be82010-05-06 00:08:46 +00008329 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008330 sid = getsid(pid);
8331 if (sid < 0)
8332 return posix_error();
8333 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008334}
8335#endif /* HAVE_GETSID */
8336
8337
Guido van Rossumb6775db1994-08-01 11:34:53 +00008338#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008339/*[clinic input]
8340os.setsid
8341
8342Call the system call setsid().
8343[clinic start generated code]*/
8344
Larry Hastings2f936352014-08-05 14:04:04 +10008345static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008346os_setsid_impl(PyObject *module)
8347/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008348{
Victor Stinner8c62be82010-05-06 00:08:46 +00008349 if (setsid() < 0)
8350 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008351 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008352}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008353#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008354
Larry Hastings2f936352014-08-05 14:04:04 +10008355
Guido van Rossumb6775db1994-08-01 11:34:53 +00008356#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008357/*[clinic input]
8358os.setpgid
8359
8360 pid: pid_t
8361 pgrp: pid_t
8362 /
8363
8364Call the system call setpgid(pid, pgrp).
8365[clinic start generated code]*/
8366
Larry Hastings2f936352014-08-05 14:04:04 +10008367static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008368os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8369/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008370{
Victor Stinner8c62be82010-05-06 00:08:46 +00008371 if (setpgid(pid, pgrp) < 0)
8372 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008373 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008374}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008375#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008376
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008377
Guido van Rossumb6775db1994-08-01 11:34:53 +00008378#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008379/*[clinic input]
8380os.tcgetpgrp
8381
8382 fd: int
8383 /
8384
8385Return the process group associated with the terminal specified by fd.
8386[clinic start generated code]*/
8387
Larry Hastings2f936352014-08-05 14:04:04 +10008388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008389os_tcgetpgrp_impl(PyObject *module, int fd)
8390/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008391{
8392 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008393 if (pgid < 0)
8394 return posix_error();
8395 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008396}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008397#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008398
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008399
Guido van Rossumb6775db1994-08-01 11:34:53 +00008400#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008401/*[clinic input]
8402os.tcsetpgrp
8403
8404 fd: int
8405 pgid: pid_t
8406 /
8407
8408Set the process group associated with the terminal specified by fd.
8409[clinic start generated code]*/
8410
Larry Hastings2f936352014-08-05 14:04:04 +10008411static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008412os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8413/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008414{
Victor Stinner8c62be82010-05-06 00:08:46 +00008415 if (tcsetpgrp(fd, pgid) < 0)
8416 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008417 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008418}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008419#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008420
Guido van Rossum687dd131993-05-17 08:34:16 +00008421/* Functions acting on file descriptors */
8422
Victor Stinnerdaf45552013-08-28 00:53:59 +02008423#ifdef O_CLOEXEC
8424extern int _Py_open_cloexec_works;
8425#endif
8426
Larry Hastings2f936352014-08-05 14:04:04 +10008427
8428/*[clinic input]
8429os.open -> int
8430 path: path_t
8431 flags: int
8432 mode: int = 0o777
8433 *
8434 dir_fd: dir_fd(requires='openat') = None
8435
8436# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8437
8438Open a file for low level IO. Returns a file descriptor (integer).
8439
8440If dir_fd is not None, it should be a file descriptor open to a directory,
8441 and path should be relative; path will then be relative to that directory.
8442dir_fd may not be implemented on your platform.
8443 If it is unavailable, using it will raise a NotImplementedError.
8444[clinic start generated code]*/
8445
Larry Hastings2f936352014-08-05 14:04:04 +10008446static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008447os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8448/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008449{
8450 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008451 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008452
Victor Stinnerdaf45552013-08-28 00:53:59 +02008453#ifdef O_CLOEXEC
8454 int *atomic_flag_works = &_Py_open_cloexec_works;
8455#elif !defined(MS_WINDOWS)
8456 int *atomic_flag_works = NULL;
8457#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008458
Victor Stinnerdaf45552013-08-28 00:53:59 +02008459#ifdef MS_WINDOWS
8460 flags |= O_NOINHERIT;
8461#elif defined(O_CLOEXEC)
8462 flags |= O_CLOEXEC;
8463#endif
8464
Steve Dowerb82e17e2019-05-23 08:45:22 -07008465 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8466 return -1;
8467 }
8468
Steve Dower8fc89802015-04-12 00:26:27 -04008469 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008470 do {
8471 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008472#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008473 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008474#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008475#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008476 if (dir_fd != DEFAULT_DIR_FD)
8477 fd = openat(dir_fd, path->narrow, flags, mode);
8478 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008479#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008480 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008481#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008482 Py_END_ALLOW_THREADS
8483 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008484 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008485
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008486 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008487 if (!async_err)
8488 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008489 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008490 }
8491
Victor Stinnerdaf45552013-08-28 00:53:59 +02008492#ifndef MS_WINDOWS
8493 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8494 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008495 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008496 }
8497#endif
8498
Larry Hastings2f936352014-08-05 14:04:04 +10008499 return fd;
8500}
8501
8502
8503/*[clinic input]
8504os.close
8505
8506 fd: int
8507
8508Close a file descriptor.
8509[clinic start generated code]*/
8510
Barry Warsaw53699e91996-12-10 23:23:01 +00008511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008512os_close_impl(PyObject *module, int fd)
8513/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008514{
Larry Hastings2f936352014-08-05 14:04:04 +10008515 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008516 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8517 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8518 * for more details.
8519 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008520 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008521 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008522 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008523 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008524 Py_END_ALLOW_THREADS
8525 if (res < 0)
8526 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008527 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008528}
8529
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008530
Miss Islington (bot)84eb42e2019-09-12 04:19:21 -07008531#ifdef HAVE_FDWALK
8532static int
8533_fdwalk_close_func(void *lohi, int fd)
8534{
8535 int lo = ((int *)lohi)[0];
8536 int hi = ((int *)lohi)[1];
8537
8538 if (fd >= hi)
8539 return 1;
8540 else if (fd >= lo)
8541 close(fd);
8542 return 0;
8543}
8544#endif /* HAVE_FDWALK */
8545
Larry Hastings2f936352014-08-05 14:04:04 +10008546/*[clinic input]
8547os.closerange
8548
8549 fd_low: int
8550 fd_high: int
8551 /
8552
8553Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8554[clinic start generated code]*/
8555
Larry Hastings2f936352014-08-05 14:04:04 +10008556static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008557os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8558/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008559{
Miss Islington (bot)84eb42e2019-09-12 04:19:21 -07008560#ifdef HAVE_FDWALK
8561 int lohi[2];
8562#else
Larry Hastings2f936352014-08-05 14:04:04 +10008563 int i;
Miss Islington (bot)84eb42e2019-09-12 04:19:21 -07008564#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008565 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008566 _Py_BEGIN_SUPPRESS_IPH
Miss Islington (bot)84eb42e2019-09-12 04:19:21 -07008567#ifdef HAVE_FDWALK
8568 lohi[0] = Py_MAX(fd_low, 0);
8569 lohi[1] = fd_high;
8570 fdwalk(_fdwalk_close_func, lohi);
8571#else
Benjamin Peterson207116b2016-09-08 11:28:06 -07008572 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008573 close(i);
Miss Islington (bot)84eb42e2019-09-12 04:19:21 -07008574#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008575 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008576 Py_END_ALLOW_THREADS
8577 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008578}
8579
8580
Larry Hastings2f936352014-08-05 14:04:04 +10008581/*[clinic input]
8582os.dup -> int
8583
8584 fd: int
8585 /
8586
8587Return a duplicate of a file descriptor.
8588[clinic start generated code]*/
8589
Larry Hastings2f936352014-08-05 14:04:04 +10008590static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008591os_dup_impl(PyObject *module, int fd)
8592/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008593{
8594 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008595}
8596
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008597
Larry Hastings2f936352014-08-05 14:04:04 +10008598/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008599os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008600 fd: int
8601 fd2: int
8602 inheritable: bool=True
8603
8604Duplicate file descriptor.
8605[clinic start generated code]*/
8606
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008607static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008608os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008609/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008610{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008611 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008612#if defined(HAVE_DUP3) && \
8613 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8614 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008615 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008616#endif
8617
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008618 if (fd < 0 || fd2 < 0) {
8619 posix_error();
8620 return -1;
8621 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008622
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008623 /* dup2() can fail with EINTR if the target FD is already open, because it
8624 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8625 * upon close(), and therefore below.
8626 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008627#ifdef MS_WINDOWS
8628 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008629 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008630 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008631 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008632 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008633 if (res < 0) {
8634 posix_error();
8635 return -1;
8636 }
8637 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008638
8639 /* Character files like console cannot be make non-inheritable */
8640 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8641 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008642 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008643 }
8644
8645#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8646 Py_BEGIN_ALLOW_THREADS
8647 if (!inheritable)
8648 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8649 else
8650 res = dup2(fd, fd2);
8651 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008652 if (res < 0) {
8653 posix_error();
8654 return -1;
8655 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008656
8657#else
8658
8659#ifdef HAVE_DUP3
8660 if (!inheritable && dup3_works != 0) {
8661 Py_BEGIN_ALLOW_THREADS
8662 res = dup3(fd, fd2, O_CLOEXEC);
8663 Py_END_ALLOW_THREADS
8664 if (res < 0) {
8665 if (dup3_works == -1)
8666 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008667 if (dup3_works) {
8668 posix_error();
8669 return -1;
8670 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008671 }
8672 }
8673
8674 if (inheritable || dup3_works == 0)
8675 {
8676#endif
8677 Py_BEGIN_ALLOW_THREADS
8678 res = dup2(fd, fd2);
8679 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008680 if (res < 0) {
8681 posix_error();
8682 return -1;
8683 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008684
8685 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8686 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008687 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008688 }
8689#ifdef HAVE_DUP3
8690 }
8691#endif
8692
8693#endif
8694
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008695 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008696}
8697
Larry Hastings2f936352014-08-05 14:04:04 +10008698
Ross Lagerwall7807c352011-03-17 20:20:30 +02008699#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008700/*[clinic input]
8701os.lockf
8702
8703 fd: int
8704 An open file descriptor.
8705 command: int
8706 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8707 length: Py_off_t
8708 The number of bytes to lock, starting at the current position.
8709 /
8710
8711Apply, test or remove a POSIX lock on an open file descriptor.
8712
8713[clinic start generated code]*/
8714
Larry Hastings2f936352014-08-05 14:04:04 +10008715static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008716os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8717/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008718{
8719 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008720
Steve Dowera00b5be2020-02-13 08:30:27 +00008721 if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
8722 return NULL;
8723 }
8724
Ross Lagerwall7807c352011-03-17 20:20:30 +02008725 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008726 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008727 Py_END_ALLOW_THREADS
8728
8729 if (res < 0)
8730 return posix_error();
8731
8732 Py_RETURN_NONE;
8733}
Larry Hastings2f936352014-08-05 14:04:04 +10008734#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008735
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008736
Larry Hastings2f936352014-08-05 14:04:04 +10008737/*[clinic input]
8738os.lseek -> Py_off_t
8739
8740 fd: int
8741 position: Py_off_t
8742 how: int
8743 /
8744
8745Set the position of a file descriptor. Return the new position.
8746
8747Return the new cursor position in number of bytes
8748relative to the beginning of the file.
8749[clinic start generated code]*/
8750
Larry Hastings2f936352014-08-05 14:04:04 +10008751static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008752os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8753/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008754{
8755 Py_off_t result;
8756
Guido van Rossum687dd131993-05-17 08:34:16 +00008757#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008758 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8759 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008760 case 0: how = SEEK_SET; break;
8761 case 1: how = SEEK_CUR; break;
8762 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008763 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008764#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008765
Victor Stinner8c62be82010-05-06 00:08:46 +00008766 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008767 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008768#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008769 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008770#else
Larry Hastings2f936352014-08-05 14:04:04 +10008771 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008772#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008773 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008774 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008775 if (result < 0)
8776 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008777
Larry Hastings2f936352014-08-05 14:04:04 +10008778 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008779}
8780
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008781
Larry Hastings2f936352014-08-05 14:04:04 +10008782/*[clinic input]
8783os.read
8784 fd: int
8785 length: Py_ssize_t
8786 /
8787
8788Read from a file descriptor. Returns a bytes object.
8789[clinic start generated code]*/
8790
Larry Hastings2f936352014-08-05 14:04:04 +10008791static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008792os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8793/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008794{
Victor Stinner8c62be82010-05-06 00:08:46 +00008795 Py_ssize_t n;
8796 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008797
8798 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008799 errno = EINVAL;
8800 return posix_error();
8801 }
Larry Hastings2f936352014-08-05 14:04:04 +10008802
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008803 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008804
8805 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008806 if (buffer == NULL)
8807 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008808
Victor Stinner66aab0c2015-03-19 22:53:20 +01008809 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8810 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008811 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008812 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008813 }
Larry Hastings2f936352014-08-05 14:04:04 +10008814
8815 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008816 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008817
Victor Stinner8c62be82010-05-06 00:08:46 +00008818 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008819}
8820
Ross Lagerwall7807c352011-03-17 20:20:30 +02008821#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008822 || defined(__APPLE__))) \
8823 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8824 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8825static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008826iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008827{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008828 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008829
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008830 *iov = PyMem_New(struct iovec, cnt);
8831 if (*iov == NULL) {
8832 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008833 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008834 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008835
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008836 *buf = PyMem_New(Py_buffer, cnt);
8837 if (*buf == NULL) {
8838 PyMem_Del(*iov);
8839 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008840 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008841 }
8842
8843 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008844 PyObject *item = PySequence_GetItem(seq, i);
8845 if (item == NULL)
8846 goto fail;
8847 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8848 Py_DECREF(item);
8849 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008850 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008851 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008852 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008853 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008854 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008855 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008856
8857fail:
8858 PyMem_Del(*iov);
8859 for (j = 0; j < i; j++) {
8860 PyBuffer_Release(&(*buf)[j]);
8861 }
8862 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008863 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008864}
8865
8866static void
8867iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8868{
8869 int i;
8870 PyMem_Del(iov);
8871 for (i = 0; i < cnt; i++) {
8872 PyBuffer_Release(&buf[i]);
8873 }
8874 PyMem_Del(buf);
8875}
8876#endif
8877
Larry Hastings2f936352014-08-05 14:04:04 +10008878
Ross Lagerwall7807c352011-03-17 20:20:30 +02008879#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008880/*[clinic input]
8881os.readv -> Py_ssize_t
8882
8883 fd: int
8884 buffers: object
8885 /
8886
8887Read from a file descriptor fd into an iterable of buffers.
8888
8889The buffers should be mutable buffers accepting bytes.
8890readv will transfer data into each buffer until it is full
8891and then move on to the next buffer in the sequence to hold
8892the rest of the data.
8893
8894readv returns the total number of bytes read,
8895which may be less than the total capacity of all the buffers.
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_readv_impl(PyObject *module, int fd, PyObject *buffers)
8900/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008901{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008902 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008903 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008904 struct iovec *iov;
8905 Py_buffer *buf;
8906
Larry Hastings2f936352014-08-05 14:04:04 +10008907 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008908 PyErr_SetString(PyExc_TypeError,
8909 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008910 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008911 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008912
Larry Hastings2f936352014-08-05 14:04:04 +10008913 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008914 if (cnt < 0)
8915 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008916
8917 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8918 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008919
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008920 do {
8921 Py_BEGIN_ALLOW_THREADS
8922 n = readv(fd, iov, cnt);
8923 Py_END_ALLOW_THREADS
8924 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008925
8926 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008927 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008928 if (!async_err)
8929 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008930 return -1;
8931 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008932
Larry Hastings2f936352014-08-05 14:04:04 +10008933 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008934}
Larry Hastings2f936352014-08-05 14:04:04 +10008935#endif /* HAVE_READV */
8936
Ross Lagerwall7807c352011-03-17 20:20:30 +02008937
8938#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008939/*[clinic input]
8940# TODO length should be size_t! but Python doesn't support parsing size_t yet.
8941os.pread
8942
8943 fd: int
8944 length: int
8945 offset: Py_off_t
8946 /
8947
8948Read a number of bytes from a file descriptor starting at a particular offset.
8949
8950Read length bytes from file descriptor fd, starting at offset bytes from
8951the beginning of the file. The file offset remains unchanged.
8952[clinic start generated code]*/
8953
Larry Hastings2f936352014-08-05 14:04:04 +10008954static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008955os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset)
8956/*[clinic end generated code: output=435b29ee32b54a78 input=084948dcbaa35d4c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008957{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008958 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008959 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008960 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008961
Larry Hastings2f936352014-08-05 14:04:04 +10008962 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008963 errno = EINVAL;
8964 return posix_error();
8965 }
Larry Hastings2f936352014-08-05 14:04:04 +10008966 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008967 if (buffer == NULL)
8968 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008969
8970 do {
8971 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008972 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008973 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008974 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008975 Py_END_ALLOW_THREADS
8976 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8977
Ross Lagerwall7807c352011-03-17 20:20:30 +02008978 if (n < 0) {
8979 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008980 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008981 }
Larry Hastings2f936352014-08-05 14:04:04 +10008982 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008983 _PyBytes_Resize(&buffer, n);
8984 return buffer;
8985}
Larry Hastings2f936352014-08-05 14:04:04 +10008986#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008987
Pablo Galindo4defba32018-01-27 16:16:37 +00008988#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8989/*[clinic input]
8990os.preadv -> Py_ssize_t
8991
8992 fd: int
8993 buffers: object
8994 offset: Py_off_t
8995 flags: int = 0
8996 /
8997
8998Reads from a file descriptor into a number of mutable bytes-like objects.
8999
9000Combines the functionality of readv() and pread(). As readv(), it will
9001transfer data into each buffer until it is full and then move on to the next
9002buffer in the sequence to hold the rest of the data. Its fourth argument,
9003specifies the file offset at which the input operation is to be performed. It
9004will return the total number of bytes read (which can be less than the total
9005capacity of all the objects).
9006
9007The flags argument contains a bitwise OR of zero or more of the following flags:
9008
9009- RWF_HIPRI
9010- RWF_NOWAIT
9011
9012Using non-zero flags requires Linux 4.6 or newer.
9013[clinic start generated code]*/
9014
9015static Py_ssize_t
9016os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9017 int flags)
9018/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9019{
9020 Py_ssize_t cnt, n;
9021 int async_err = 0;
9022 struct iovec *iov;
9023 Py_buffer *buf;
9024
9025 if (!PySequence_Check(buffers)) {
9026 PyErr_SetString(PyExc_TypeError,
9027 "preadv2() arg 2 must be a sequence");
9028 return -1;
9029 }
9030
9031 cnt = PySequence_Size(buffers);
9032 if (cnt < 0) {
9033 return -1;
9034 }
9035
9036#ifndef HAVE_PREADV2
9037 if(flags != 0) {
9038 argument_unavailable_error("preadv2", "flags");
9039 return -1;
9040 }
9041#endif
9042
9043 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9044 return -1;
9045 }
9046#ifdef HAVE_PREADV2
9047 do {
9048 Py_BEGIN_ALLOW_THREADS
9049 _Py_BEGIN_SUPPRESS_IPH
9050 n = preadv2(fd, iov, cnt, offset, flags);
9051 _Py_END_SUPPRESS_IPH
9052 Py_END_ALLOW_THREADS
9053 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9054#else
9055 do {
9056 Py_BEGIN_ALLOW_THREADS
9057 _Py_BEGIN_SUPPRESS_IPH
9058 n = preadv(fd, iov, cnt, offset);
9059 _Py_END_SUPPRESS_IPH
9060 Py_END_ALLOW_THREADS
9061 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9062#endif
9063
9064 iov_cleanup(iov, buf, cnt);
9065 if (n < 0) {
9066 if (!async_err) {
9067 posix_error();
9068 }
9069 return -1;
9070 }
9071
9072 return n;
9073}
9074#endif /* HAVE_PREADV */
9075
Larry Hastings2f936352014-08-05 14:04:04 +10009076
9077/*[clinic input]
9078os.write -> Py_ssize_t
9079
9080 fd: int
9081 data: Py_buffer
9082 /
9083
9084Write a bytes object to a file descriptor.
9085[clinic start generated code]*/
9086
Larry Hastings2f936352014-08-05 14:04:04 +10009087static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009088os_write_impl(PyObject *module, int fd, Py_buffer *data)
9089/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009090{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009091 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009092}
9093
9094#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009095PyDoc_STRVAR(posix_sendfile__doc__,
Martin Panterbf19d162015-09-09 01:01:13 +00009096"sendfile(out, in, offset, count) -> byteswritten\n\
Martin Panter94994132015-09-09 05:29:24 +00009097sendfile(out, in, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009098 -> byteswritten\n\
Martin Panterbf19d162015-09-09 01:01:13 +00009099Copy count bytes from file descriptor in to file descriptor out.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009100
Larry Hastings2f936352014-08-05 14:04:04 +10009101/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009102static PyObject *
9103posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
9104{
9105 int in, out;
9106 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009107 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009108 off_t offset;
9109
9110#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9111#ifndef __APPLE__
9112 Py_ssize_t len;
9113#endif
9114 PyObject *headers = NULL, *trailers = NULL;
9115 Py_buffer *hbuf, *tbuf;
9116 off_t sbytes;
9117 struct sf_hdtr sf;
9118 int flags = 0;
Martin Panterbf19d162015-09-09 01:01:13 +00009119 /* Beware that "in" clashes with Python's own "in" operator keyword */
Benjamin Petersond8a43b42011-02-26 21:35:16 +00009120 static char *keywords[] = {"out", "in",
9121 "offset", "count",
9122 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009123
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009124 sf.headers = NULL;
9125 sf.trailers = NULL;
9126
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009127#ifdef __APPLE__
9128 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009129 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009130#else
9131 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009132 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009133#endif
9134 &headers, &trailers, &flags))
9135 return NULL;
9136 if (headers != NULL) {
9137 if (!PySequence_Check(headers)) {
9138 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009139 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009140 return NULL;
9141 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009142 Py_ssize_t i = PySequence_Size(headers);
9143 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009144 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009145 if (i > INT_MAX) {
9146 PyErr_SetString(PyExc_OverflowError,
9147 "sendfile() header is too large");
9148 return NULL;
9149 }
9150 if (i > 0) {
9151 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009152 if (iov_setup(&(sf.headers), &hbuf,
9153 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009154 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009155#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009156 for (i = 0; i < sf.hdr_cnt; i++) {
9157 Py_ssize_t blen = sf.headers[i].iov_len;
9158# define OFF_T_MAX 0x7fffffffffffffff
9159 if (sbytes >= OFF_T_MAX - blen) {
9160 PyErr_SetString(PyExc_OverflowError,
9161 "sendfile() header is too large");
9162 return NULL;
9163 }
9164 sbytes += blen;
9165 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009166#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009167 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009168 }
9169 }
9170 if (trailers != NULL) {
9171 if (!PySequence_Check(trailers)) {
9172 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009173 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009174 return NULL;
9175 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009176 Py_ssize_t i = PySequence_Size(trailers);
9177 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009178 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009179 if (i > INT_MAX) {
9180 PyErr_SetString(PyExc_OverflowError,
9181 "sendfile() trailer is too large");
9182 return NULL;
9183 }
9184 if (i > 0) {
9185 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009186 if (iov_setup(&(sf.trailers), &tbuf,
9187 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009188 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009189 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009190 }
9191 }
9192
Steve Dower8fc89802015-04-12 00:26:27 -04009193 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009194 do {
9195 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009196#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009197 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009198#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009199 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009200#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009201 Py_END_ALLOW_THREADS
9202 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009203 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009204
9205 if (sf.headers != NULL)
9206 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9207 if (sf.trailers != NULL)
9208 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9209
9210 if (ret < 0) {
9211 if ((errno == EAGAIN) || (errno == EBUSY)) {
9212 if (sbytes != 0) {
9213 // some data has been sent
9214 goto done;
9215 }
9216 else {
9217 // no data has been sent; upper application is supposed
9218 // to retry on EAGAIN or EBUSY
9219 return posix_error();
9220 }
9221 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009222 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009223 }
9224 goto done;
9225
9226done:
9227 #if !defined(HAVE_LARGEFILE_SUPPORT)
9228 return Py_BuildValue("l", sbytes);
9229 #else
9230 return Py_BuildValue("L", sbytes);
9231 #endif
9232
9233#else
9234 Py_ssize_t count;
9235 PyObject *offobj;
9236 static char *keywords[] = {"out", "in",
9237 "offset", "count", NULL};
9238 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9239 keywords, &out, &in, &offobj, &count))
9240 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009241#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009242 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009243 do {
9244 Py_BEGIN_ALLOW_THREADS
9245 ret = sendfile(out, in, NULL, count);
9246 Py_END_ALLOW_THREADS
9247 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009248 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009249 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009250 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009251 }
9252#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009253 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009254 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009255
9256 do {
9257 Py_BEGIN_ALLOW_THREADS
9258 ret = sendfile(out, in, &offset, count);
9259 Py_END_ALLOW_THREADS
9260 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009261 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009262 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009263 return Py_BuildValue("n", ret);
9264#endif
9265}
Larry Hastings2f936352014-08-05 14:04:04 +10009266#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009267
Larry Hastings2f936352014-08-05 14:04:04 +10009268
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009269#if defined(__APPLE__)
9270/*[clinic input]
9271os._fcopyfile
9272
9273 infd: int
9274 outfd: int
9275 flags: int
9276 /
9277
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009278Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009279[clinic start generated code]*/
9280
9281static PyObject *
9282os__fcopyfile_impl(PyObject *module, int infd, int outfd, int flags)
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009283/*[clinic end generated code: output=8e8885c721ec38e3 input=69e0770e600cb44f]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009284{
9285 int ret;
9286
9287 Py_BEGIN_ALLOW_THREADS
9288 ret = fcopyfile(infd, outfd, NULL, flags);
9289 Py_END_ALLOW_THREADS
9290 if (ret < 0)
9291 return posix_error();
9292 Py_RETURN_NONE;
9293}
9294#endif
9295
9296
Larry Hastings2f936352014-08-05 14:04:04 +10009297/*[clinic input]
9298os.fstat
9299
9300 fd : int
9301
9302Perform a stat system call on the given file descriptor.
9303
9304Like stat(), but for an open file descriptor.
9305Equivalent to os.stat(fd).
9306[clinic start generated code]*/
9307
Larry Hastings2f936352014-08-05 14:04:04 +10009308static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009309os_fstat_impl(PyObject *module, int fd)
9310/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009311{
Victor Stinner8c62be82010-05-06 00:08:46 +00009312 STRUCT_STAT st;
9313 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009314 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009315
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009316 do {
9317 Py_BEGIN_ALLOW_THREADS
9318 res = FSTAT(fd, &st);
9319 Py_END_ALLOW_THREADS
9320 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009321 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009322#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009323 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009324#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009325 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009326#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009327 }
Tim Peters5aa91602002-01-30 05:46:57 +00009328
Victor Stinner4195b5c2012-02-08 23:03:19 +01009329 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009330}
9331
Larry Hastings2f936352014-08-05 14:04:04 +10009332
9333/*[clinic input]
9334os.isatty -> bool
9335 fd: int
9336 /
9337
9338Return True if the fd is connected to a terminal.
9339
9340Return True if the file descriptor is an open file descriptor
9341connected to the slave end of a terminal.
9342[clinic start generated code]*/
9343
Larry Hastings2f936352014-08-05 14:04:04 +10009344static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009345os_isatty_impl(PyObject *module, int fd)
9346/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009347{
Steve Dower8fc89802015-04-12 00:26:27 -04009348 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009349 _Py_BEGIN_SUPPRESS_IPH
9350 return_value = isatty(fd);
9351 _Py_END_SUPPRESS_IPH
9352 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009353}
9354
9355
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009356#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009357/*[clinic input]
9358os.pipe
9359
9360Create a pipe.
9361
9362Returns a tuple of two file descriptors:
9363 (read_fd, write_fd)
9364[clinic start generated code]*/
9365
Larry Hastings2f936352014-08-05 14:04:04 +10009366static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009367os_pipe_impl(PyObject *module)
9368/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009369{
Victor Stinner8c62be82010-05-06 00:08:46 +00009370 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009371#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009372 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009373 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009374 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009375#else
9376 int res;
9377#endif
9378
9379#ifdef MS_WINDOWS
9380 attr.nLength = sizeof(attr);
9381 attr.lpSecurityDescriptor = NULL;
9382 attr.bInheritHandle = FALSE;
9383
9384 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009385 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009386 ok = CreatePipe(&read, &write, &attr, 0);
9387 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009388 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9389 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009390 if (fds[0] == -1 || fds[1] == -1) {
9391 CloseHandle(read);
9392 CloseHandle(write);
9393 ok = 0;
9394 }
9395 }
Steve Dowerc3630612016-11-19 18:41:16 -08009396 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009397 Py_END_ALLOW_THREADS
9398
Victor Stinner8c62be82010-05-06 00:08:46 +00009399 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009400 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009401#else
9402
9403#ifdef HAVE_PIPE2
9404 Py_BEGIN_ALLOW_THREADS
9405 res = pipe2(fds, O_CLOEXEC);
9406 Py_END_ALLOW_THREADS
9407
9408 if (res != 0 && errno == ENOSYS)
9409 {
9410#endif
9411 Py_BEGIN_ALLOW_THREADS
9412 res = pipe(fds);
9413 Py_END_ALLOW_THREADS
9414
9415 if (res == 0) {
9416 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9417 close(fds[0]);
9418 close(fds[1]);
9419 return NULL;
9420 }
9421 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9422 close(fds[0]);
9423 close(fds[1]);
9424 return NULL;
9425 }
9426 }
9427#ifdef HAVE_PIPE2
9428 }
9429#endif
9430
9431 if (res != 0)
9432 return PyErr_SetFromErrno(PyExc_OSError);
9433#endif /* !MS_WINDOWS */
9434 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009435}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009436#endif /* HAVE_PIPE */
9437
Larry Hastings2f936352014-08-05 14:04:04 +10009438
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009439#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009440/*[clinic input]
9441os.pipe2
9442
9443 flags: int
9444 /
9445
9446Create a pipe with flags set atomically.
9447
9448Returns a tuple of two file descriptors:
9449 (read_fd, write_fd)
9450
9451flags can be constructed by ORing together one or more of these values:
9452O_NONBLOCK, O_CLOEXEC.
9453[clinic start generated code]*/
9454
Larry Hastings2f936352014-08-05 14:04:04 +10009455static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009456os_pipe2_impl(PyObject *module, int flags)
9457/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009458{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009459 int fds[2];
9460 int res;
9461
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009462 res = pipe2(fds, flags);
9463 if (res != 0)
9464 return posix_error();
9465 return Py_BuildValue("(ii)", fds[0], fds[1]);
9466}
9467#endif /* HAVE_PIPE2 */
9468
Larry Hastings2f936352014-08-05 14:04:04 +10009469
Ross Lagerwall7807c352011-03-17 20:20:30 +02009470#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009471/*[clinic input]
9472os.writev -> Py_ssize_t
9473 fd: int
9474 buffers: object
9475 /
9476
9477Iterate over buffers, and write the contents of each to a file descriptor.
9478
9479Returns the total number of bytes written.
9480buffers must be a sequence of bytes-like objects.
9481[clinic start generated code]*/
9482
Larry Hastings2f936352014-08-05 14:04:04 +10009483static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009484os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9485/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009486{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009487 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009488 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009489 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009490 struct iovec *iov;
9491 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009492
9493 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009494 PyErr_SetString(PyExc_TypeError,
9495 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009496 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009497 }
Larry Hastings2f936352014-08-05 14:04:04 +10009498 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009499 if (cnt < 0)
9500 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009501
Larry Hastings2f936352014-08-05 14:04:04 +10009502 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9503 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009504 }
9505
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009506 do {
9507 Py_BEGIN_ALLOW_THREADS
9508 result = writev(fd, iov, cnt);
9509 Py_END_ALLOW_THREADS
9510 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009511
9512 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009513 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009514 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009515
Georg Brandl306336b2012-06-24 12:55:33 +02009516 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009517}
Larry Hastings2f936352014-08-05 14:04:04 +10009518#endif /* HAVE_WRITEV */
9519
9520
9521#ifdef HAVE_PWRITE
9522/*[clinic input]
9523os.pwrite -> Py_ssize_t
9524
9525 fd: int
9526 buffer: Py_buffer
9527 offset: Py_off_t
9528 /
9529
9530Write bytes to a file descriptor starting at a particular offset.
9531
9532Write buffer to fd, starting at offset bytes from the beginning of
9533the file. Returns the number of bytes writte. Does not change the
9534current file offset.
9535[clinic start generated code]*/
9536
Larry Hastings2f936352014-08-05 14:04:04 +10009537static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009538os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9539/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009540{
9541 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009542 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009543
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009544 do {
9545 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009546 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009547 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009548 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009549 Py_END_ALLOW_THREADS
9550 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009551
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009552 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009553 posix_error();
9554 return size;
9555}
9556#endif /* HAVE_PWRITE */
9557
Pablo Galindo4defba32018-01-27 16:16:37 +00009558#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9559/*[clinic input]
9560os.pwritev -> Py_ssize_t
9561
9562 fd: int
9563 buffers: object
9564 offset: Py_off_t
9565 flags: int = 0
9566 /
9567
9568Writes the contents of bytes-like objects to a file descriptor at a given offset.
9569
9570Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9571of bytes-like objects. Buffers are processed in array order. Entire contents of first
9572buffer is written before proceeding to second, and so on. The operating system may
9573set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9574This function writes the contents of each object to the file descriptor and returns
9575the total number of bytes written.
9576
9577The flags argument contains a bitwise OR of zero or more of the following flags:
9578
9579- RWF_DSYNC
9580- RWF_SYNC
9581
9582Using non-zero flags requires Linux 4.7 or newer.
9583[clinic start generated code]*/
9584
9585static Py_ssize_t
9586os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9587 int flags)
9588/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9589{
9590 Py_ssize_t cnt;
9591 Py_ssize_t result;
9592 int async_err = 0;
9593 struct iovec *iov;
9594 Py_buffer *buf;
9595
9596 if (!PySequence_Check(buffers)) {
9597 PyErr_SetString(PyExc_TypeError,
9598 "pwritev() arg 2 must be a sequence");
9599 return -1;
9600 }
9601
9602 cnt = PySequence_Size(buffers);
9603 if (cnt < 0) {
9604 return -1;
9605 }
9606
9607#ifndef HAVE_PWRITEV2
9608 if(flags != 0) {
9609 argument_unavailable_error("pwritev2", "flags");
9610 return -1;
9611 }
9612#endif
9613
9614 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9615 return -1;
9616 }
9617#ifdef HAVE_PWRITEV2
9618 do {
9619 Py_BEGIN_ALLOW_THREADS
9620 _Py_BEGIN_SUPPRESS_IPH
9621 result = pwritev2(fd, iov, cnt, offset, flags);
9622 _Py_END_SUPPRESS_IPH
9623 Py_END_ALLOW_THREADS
9624 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9625#else
9626 do {
9627 Py_BEGIN_ALLOW_THREADS
9628 _Py_BEGIN_SUPPRESS_IPH
9629 result = pwritev(fd, iov, cnt, offset);
9630 _Py_END_SUPPRESS_IPH
9631 Py_END_ALLOW_THREADS
9632 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9633#endif
9634
9635 iov_cleanup(iov, buf, cnt);
9636 if (result < 0) {
9637 if (!async_err) {
9638 posix_error();
9639 }
9640 return -1;
9641 }
9642
9643 return result;
9644}
9645#endif /* HAVE_PWRITEV */
9646
Pablo Galindoaac4d032019-05-31 19:39:47 +01009647#ifdef HAVE_COPY_FILE_RANGE
9648/*[clinic input]
9649
9650os.copy_file_range
9651 src: int
9652 Source file descriptor.
9653 dst: int
9654 Destination file descriptor.
9655 count: Py_ssize_t
9656 Number of bytes to copy.
9657 offset_src: object = None
9658 Starting offset in src.
9659 offset_dst: object = None
9660 Starting offset in dst.
9661
9662Copy count bytes from one file descriptor to another.
9663
9664If offset_src is None, then src is read from the current position;
9665respectively for offset_dst.
9666[clinic start generated code]*/
9667
9668static PyObject *
9669os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9670 PyObject *offset_src, PyObject *offset_dst)
9671/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9672{
9673 off_t offset_src_val, offset_dst_val;
9674 off_t *p_offset_src = NULL;
9675 off_t *p_offset_dst = NULL;
9676 Py_ssize_t ret;
9677 int async_err = 0;
9678 /* The flags argument is provided to allow
9679 * for future extensions and currently must be to 0. */
9680 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009681
9682
Pablo Galindoaac4d032019-05-31 19:39:47 +01009683 if (count < 0) {
9684 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9685 return NULL;
9686 }
9687
9688 if (offset_src != Py_None) {
9689 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9690 return NULL;
9691 }
9692 p_offset_src = &offset_src_val;
9693 }
9694
9695 if (offset_dst != Py_None) {
9696 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9697 return NULL;
9698 }
9699 p_offset_dst = &offset_dst_val;
9700 }
9701
9702 do {
9703 Py_BEGIN_ALLOW_THREADS
9704 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9705 Py_END_ALLOW_THREADS
9706 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9707
9708 if (ret < 0) {
9709 return (!async_err) ? posix_error() : NULL;
9710 }
9711
9712 return PyLong_FromSsize_t(ret);
9713}
9714#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009715
9716#ifdef HAVE_MKFIFO
9717/*[clinic input]
9718os.mkfifo
9719
9720 path: path_t
9721 mode: int=0o666
9722 *
9723 dir_fd: dir_fd(requires='mkfifoat')=None
9724
9725Create a "fifo" (a POSIX named pipe).
9726
9727If dir_fd is not None, it should be a file descriptor open to a directory,
9728 and path should be relative; path will then be relative to that directory.
9729dir_fd may not be implemented on your platform.
9730 If it is unavailable, using it will raise a NotImplementedError.
9731[clinic start generated code]*/
9732
Larry Hastings2f936352014-08-05 14:04:04 +10009733static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009734os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9735/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009736{
9737 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009738 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009739
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009740 do {
9741 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009742#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009743 if (dir_fd != DEFAULT_DIR_FD)
9744 result = mkfifoat(dir_fd, path->narrow, mode);
9745 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009746#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009747 result = mkfifo(path->narrow, mode);
9748 Py_END_ALLOW_THREADS
9749 } while (result != 0 && errno == EINTR &&
9750 !(async_err = PyErr_CheckSignals()));
9751 if (result != 0)
9752 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009753
9754 Py_RETURN_NONE;
9755}
9756#endif /* HAVE_MKFIFO */
9757
9758
9759#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9760/*[clinic input]
9761os.mknod
9762
9763 path: path_t
9764 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009765 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009766 *
9767 dir_fd: dir_fd(requires='mknodat')=None
9768
9769Create a node in the file system.
9770
9771Create a node in the file system (file, device special file or named pipe)
9772at path. mode specifies both the permissions to use and the
9773type of node to be created, being combined (bitwise OR) with one of
9774S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9775device defines the newly created device special file (probably using
9776os.makedev()). Otherwise device is ignored.
9777
9778If dir_fd is not None, it should be a file descriptor open to a directory,
9779 and path should be relative; path will then be relative to that directory.
9780dir_fd may not be implemented on your platform.
9781 If it is unavailable, using it will raise a NotImplementedError.
9782[clinic start generated code]*/
9783
Larry Hastings2f936352014-08-05 14:04:04 +10009784static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009785os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009786 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009787/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009788{
9789 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009790 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009791
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009792 do {
9793 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009794#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009795 if (dir_fd != DEFAULT_DIR_FD)
9796 result = mknodat(dir_fd, path->narrow, mode, device);
9797 else
Larry Hastings2f936352014-08-05 14:04:04 +10009798#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009799 result = mknod(path->narrow, mode, device);
9800 Py_END_ALLOW_THREADS
9801 } while (result != 0 && errno == EINTR &&
9802 !(async_err = PyErr_CheckSignals()));
9803 if (result != 0)
9804 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009805
9806 Py_RETURN_NONE;
9807}
9808#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9809
9810
9811#ifdef HAVE_DEVICE_MACROS
9812/*[clinic input]
9813os.major -> unsigned_int
9814
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009815 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009816 /
9817
9818Extracts a device major number from a raw device number.
9819[clinic start generated code]*/
9820
Larry Hastings2f936352014-08-05 14:04:04 +10009821static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009822os_major_impl(PyObject *module, dev_t device)
9823/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009824{
9825 return major(device);
9826}
9827
9828
9829/*[clinic input]
9830os.minor -> unsigned_int
9831
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009832 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009833 /
9834
9835Extracts a device minor number from a raw device number.
9836[clinic start generated code]*/
9837
Larry Hastings2f936352014-08-05 14:04:04 +10009838static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009839os_minor_impl(PyObject *module, dev_t device)
9840/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009841{
9842 return minor(device);
9843}
9844
9845
9846/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009847os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009848
9849 major: int
9850 minor: int
9851 /
9852
9853Composes a raw device number from the major and minor device numbers.
9854[clinic start generated code]*/
9855
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009856static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009857os_makedev_impl(PyObject *module, int major, int minor)
9858/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009859{
9860 return makedev(major, minor);
9861}
9862#endif /* HAVE_DEVICE_MACROS */
9863
9864
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009865#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009866/*[clinic input]
9867os.ftruncate
9868
9869 fd: int
9870 length: Py_off_t
9871 /
9872
9873Truncate a file, specified by file descriptor, to a specific length.
9874[clinic start generated code]*/
9875
Larry Hastings2f936352014-08-05 14:04:04 +10009876static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009877os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9878/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009879{
9880 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009881 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009882
Steve Dowerb82e17e2019-05-23 08:45:22 -07009883 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9884 return NULL;
9885 }
9886
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009887 do {
9888 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009889 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009890#ifdef MS_WINDOWS
9891 result = _chsize_s(fd, length);
9892#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009893 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009894#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009895 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009896 Py_END_ALLOW_THREADS
9897 } while (result != 0 && errno == EINTR &&
9898 !(async_err = PyErr_CheckSignals()));
9899 if (result != 0)
9900 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009901 Py_RETURN_NONE;
9902}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009903#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009904
9905
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009906#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009907/*[clinic input]
9908os.truncate
9909 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9910 length: Py_off_t
9911
9912Truncate a file, specified by path, to a specific length.
9913
9914On some platforms, path may also be specified as an open file descriptor.
9915 If this functionality is unavailable, using it raises an exception.
9916[clinic start generated code]*/
9917
Larry Hastings2f936352014-08-05 14:04:04 +10009918static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009919os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9920/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009921{
9922 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009923#ifdef MS_WINDOWS
9924 int fd;
9925#endif
9926
9927 if (path->fd != -1)
9928 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009929
Steve Dowerb82e17e2019-05-23 08:45:22 -07009930 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9931 return NULL;
9932 }
9933
Larry Hastings2f936352014-08-05 14:04:04 +10009934 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009935 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009936#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009937 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009938 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009939 result = -1;
9940 else {
9941 result = _chsize_s(fd, length);
9942 close(fd);
9943 if (result < 0)
9944 errno = result;
9945 }
9946#else
9947 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009948#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009949 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009950 Py_END_ALLOW_THREADS
9951 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009952 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009953
9954 Py_RETURN_NONE;
9955}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009956#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009957
Ross Lagerwall7807c352011-03-17 20:20:30 +02009958
Victor Stinnerd6b17692014-09-30 12:20:05 +02009959/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9960 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9961 defined, which is the case in Python on AIX. AIX bug report:
9962 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9963#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9964# define POSIX_FADVISE_AIX_BUG
9965#endif
9966
Victor Stinnerec39e262014-09-30 12:35:58 +02009967
Victor Stinnerd6b17692014-09-30 12:20:05 +02009968#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009969/*[clinic input]
9970os.posix_fallocate
9971
9972 fd: int
9973 offset: Py_off_t
9974 length: Py_off_t
9975 /
9976
9977Ensure a file has allocated at least a particular number of bytes on disk.
9978
9979Ensure that the file specified by fd encompasses a range of bytes
9980starting at offset bytes from the beginning and continuing for length bytes.
9981[clinic start generated code]*/
9982
Larry Hastings2f936352014-08-05 14:04:04 +10009983static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009984os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009985 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009986/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009987{
9988 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009989 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009990
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009991 do {
9992 Py_BEGIN_ALLOW_THREADS
9993 result = posix_fallocate(fd, offset, length);
9994 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009995 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9996
9997 if (result == 0)
9998 Py_RETURN_NONE;
9999
10000 if (async_err)
10001 return NULL;
10002
10003 errno = result;
10004 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010005}
Victor Stinnerec39e262014-09-30 12:35:58 +020010006#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010007
Ross Lagerwall7807c352011-03-17 20:20:30 +020010008
Victor Stinnerd6b17692014-09-30 12:20:05 +020010009#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010010/*[clinic input]
10011os.posix_fadvise
10012
10013 fd: int
10014 offset: Py_off_t
10015 length: Py_off_t
10016 advice: int
10017 /
10018
10019Announce an intention to access data in a specific pattern.
10020
10021Announce an intention to access data in a specific pattern, thus allowing
10022the kernel to make optimizations.
10023The advice applies to the region of the file specified by fd starting at
10024offset and continuing for length bytes.
10025advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10026POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10027POSIX_FADV_DONTNEED.
10028[clinic start generated code]*/
10029
Larry Hastings2f936352014-08-05 14:04:04 +100010030static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010031os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010032 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010033/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010034{
10035 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010036 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010037
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010038 do {
10039 Py_BEGIN_ALLOW_THREADS
10040 result = posix_fadvise(fd, offset, length, advice);
10041 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010042 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10043
10044 if (result == 0)
10045 Py_RETURN_NONE;
10046
10047 if (async_err)
10048 return NULL;
10049
10050 errno = result;
10051 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010052}
Victor Stinnerec39e262014-09-30 12:35:58 +020010053#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010054
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010055#ifdef HAVE_PUTENV
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010056
Fred Drake762e2061999-08-26 17:23:54 +000010057/* Save putenv() parameters as values here, so we can collect them when they
10058 * get re-set with another call for the same key. */
10059static PyObject *posix_putenv_garbage;
10060
Larry Hastings2f936352014-08-05 14:04:04 +100010061static void
10062posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010063{
Larry Hastings2f936352014-08-05 14:04:04 +100010064 /* Install the first arg and newstr in posix_putenv_garbage;
10065 * this will cause previous value to be collected. This has to
10066 * happen after the real putenv() call because the old value
10067 * was still accessible until then. */
10068 if (PyDict_SetItem(posix_putenv_garbage, name, value))
10069 /* really not much we can do; just leak */
10070 PyErr_Clear();
10071 else
10072 Py_DECREF(value);
10073}
10074
10075
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010076#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010077/*[clinic input]
10078os.putenv
10079
10080 name: unicode
10081 value: unicode
10082 /
10083
10084Change or add an environment variable.
10085[clinic start generated code]*/
10086
Larry Hastings2f936352014-08-05 14:04:04 +100010087static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010088os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10089/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010090{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030010091 const wchar_t *env;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010092 Py_ssize_t size;
Larry Hastings2f936352014-08-05 14:04:04 +100010093
Serhiy Storchaka77703942017-06-25 07:33:01 +030010094 /* Search from index 1 because on Windows starting '=' is allowed for
10095 defining hidden environment variables. */
10096 if (PyUnicode_GET_LENGTH(name) == 0 ||
10097 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10098 {
10099 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10100 return NULL;
10101 }
Larry Hastings2f936352014-08-05 14:04:04 +100010102 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
10103 if (unicode == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010104 return NULL;
Victor Stinner84ae1182010-05-06 22:05:07 +000010105 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010106
10107 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
10108 if (env == NULL)
10109 goto error;
10110 if (size > _MAX_ENV) {
Victor Stinner65170952011-11-22 22:16:17 +010010111 PyErr_Format(PyExc_ValueError,
10112 "the environment variable is longer than %u characters",
10113 _MAX_ENV);
10114 goto error;
10115 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010116 if (wcslen(env) != (size_t)size) {
10117 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnereb5657a2011-09-30 01:44:27 +020010118 goto error;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010119 }
10120
Larry Hastings2f936352014-08-05 14:04:04 +100010121 if (_wputenv(env)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010122 posix_error();
Victor Stinner84ae1182010-05-06 22:05:07 +000010123 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +000010124 }
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010125
Larry Hastings2f936352014-08-05 14:04:04 +100010126 posix_putenv_garbage_setitem(name, unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +000010127 Py_RETURN_NONE;
10128
10129error:
Larry Hastings2f936352014-08-05 14:04:04 +100010130 Py_DECREF(unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +000010131 return NULL;
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010132}
Larry Hastings2f936352014-08-05 14:04:04 +100010133#else /* MS_WINDOWS */
10134/*[clinic input]
10135os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010136
Larry Hastings2f936352014-08-05 14:04:04 +100010137 name: FSConverter
10138 value: FSConverter
10139 /
10140
10141Change or add an environment variable.
10142[clinic start generated code]*/
10143
Larry Hastings2f936352014-08-05 14:04:04 +100010144static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010145os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10146/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010147{
10148 PyObject *bytes = NULL;
10149 char *env;
Serhiy Storchaka77703942017-06-25 07:33:01 +030010150 const char *name_string = PyBytes_AS_STRING(name);
10151 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010152
Serhiy Storchaka77703942017-06-25 07:33:01 +030010153 if (strchr(name_string, '=') != NULL) {
10154 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10155 return NULL;
10156 }
Steve Dowera00b5be2020-02-13 08:30:27 +000010157 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10158 return NULL;
10159 }
Larry Hastings2f936352014-08-05 14:04:04 +100010160 bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
10161 if (bytes == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010162 return NULL;
10163 }
10164
10165 env = PyBytes_AS_STRING(bytes);
10166 if (putenv(env)) {
10167 Py_DECREF(bytes);
10168 return posix_error();
10169 }
10170
10171 posix_putenv_garbage_setitem(name, bytes);
10172 Py_RETURN_NONE;
10173}
10174#endif /* MS_WINDOWS */
10175#endif /* HAVE_PUTENV */
10176
10177
10178#ifdef HAVE_UNSETENV
10179/*[clinic input]
10180os.unsetenv
10181 name: FSConverter
10182 /
10183
10184Delete an environment variable.
10185[clinic start generated code]*/
10186
Larry Hastings2f936352014-08-05 14:04:04 +100010187static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010188os_unsetenv_impl(PyObject *module, PyObject *name)
10189/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010190{
Victor Stinner984890f2011-11-24 13:53:38 +010010191#ifndef HAVE_BROKEN_UNSETENV
Victor Stinner60b385e2011-11-22 22:01:28 +010010192 int err;
Victor Stinner984890f2011-11-24 13:53:38 +010010193#endif
Victor Stinner84ae1182010-05-06 22:05:07 +000010194
Steve Dowera00b5be2020-02-13 08:30:27 +000010195 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10196 return NULL;
10197 }
10198
Victor Stinner984890f2011-11-24 13:53:38 +010010199#ifdef HAVE_BROKEN_UNSETENV
10200 unsetenv(PyBytes_AS_STRING(name));
10201#else
Victor Stinner65170952011-11-22 22:16:17 +010010202 err = unsetenv(PyBytes_AS_STRING(name));
Larry Hastings2f936352014-08-05 14:04:04 +100010203 if (err)
Victor Stinner60b385e2011-11-22 22:01:28 +010010204 return posix_error();
Victor Stinner984890f2011-11-24 13:53:38 +010010205#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010206
Victor Stinner8c62be82010-05-06 00:08:46 +000010207 /* Remove the key from posix_putenv_garbage;
10208 * this will cause it to be collected. This has to
10209 * happen after the real unsetenv() call because the
10210 * old value was still accessible until then.
10211 */
Victor Stinner65170952011-11-22 22:16:17 +010010212 if (PyDict_DelItem(posix_putenv_garbage, name)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010213 /* really not much we can do; just leak */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +020010214 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
10215 return NULL;
10216 }
Victor Stinner8c62be82010-05-06 00:08:46 +000010217 PyErr_Clear();
10218 }
Victor Stinner84ae1182010-05-06 22:05:07 +000010219 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010220}
Larry Hastings2f936352014-08-05 14:04:04 +100010221#endif /* HAVE_UNSETENV */
Guido van Rossumc524d952001-10-19 01:31:59 +000010222
Larry Hastings2f936352014-08-05 14:04:04 +100010223
10224/*[clinic input]
10225os.strerror
10226
10227 code: int
10228 /
10229
10230Translate an error code to a message string.
10231[clinic start generated code]*/
10232
Larry Hastings2f936352014-08-05 14:04:04 +100010233static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010234os_strerror_impl(PyObject *module, int code)
10235/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010236{
10237 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010238 if (message == NULL) {
10239 PyErr_SetString(PyExc_ValueError,
10240 "strerror() argument out of range");
10241 return NULL;
10242 }
Victor Stinner1b579672011-12-17 05:47:23 +010010243 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010244}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010245
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010246
Guido van Rossumc9641791998-08-04 15:26:23 +000010247#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010248#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010249/*[clinic input]
10250os.WCOREDUMP -> bool
10251
10252 status: int
10253 /
10254
10255Return True if the process returning status was dumped to a core file.
10256[clinic start generated code]*/
10257
Larry Hastings2f936352014-08-05 14:04:04 +100010258static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010259os_WCOREDUMP_impl(PyObject *module, int status)
10260/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010261{
10262 WAIT_TYPE wait_status;
10263 WAIT_STATUS_INT(wait_status) = status;
10264 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010265}
10266#endif /* WCOREDUMP */
10267
Larry Hastings2f936352014-08-05 14:04:04 +100010268
Fred Drake106c1a02002-04-23 15:58:02 +000010269#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010270/*[clinic input]
10271os.WIFCONTINUED -> bool
10272
10273 status: int
10274
10275Return True if a particular process was continued from a job control stop.
10276
10277Return True if the process returning status was continued from a
10278job control stop.
10279[clinic start generated code]*/
10280
Larry Hastings2f936352014-08-05 14:04:04 +100010281static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010282os_WIFCONTINUED_impl(PyObject *module, int status)
10283/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010284{
10285 WAIT_TYPE wait_status;
10286 WAIT_STATUS_INT(wait_status) = status;
10287 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010288}
10289#endif /* WIFCONTINUED */
10290
Larry Hastings2f936352014-08-05 14:04:04 +100010291
Guido van Rossumc9641791998-08-04 15:26:23 +000010292#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010293/*[clinic input]
10294os.WIFSTOPPED -> bool
10295
10296 status: int
10297
10298Return True if the process returning status was stopped.
10299[clinic start generated code]*/
10300
Larry Hastings2f936352014-08-05 14:04:04 +100010301static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010302os_WIFSTOPPED_impl(PyObject *module, int status)
10303/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010304{
10305 WAIT_TYPE wait_status;
10306 WAIT_STATUS_INT(wait_status) = status;
10307 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010308}
10309#endif /* WIFSTOPPED */
10310
Larry Hastings2f936352014-08-05 14:04:04 +100010311
Guido van Rossumc9641791998-08-04 15:26:23 +000010312#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010313/*[clinic input]
10314os.WIFSIGNALED -> bool
10315
10316 status: int
10317
10318Return True if the process returning status was terminated by a signal.
10319[clinic start generated code]*/
10320
Larry Hastings2f936352014-08-05 14:04:04 +100010321static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010322os_WIFSIGNALED_impl(PyObject *module, int status)
10323/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010324{
10325 WAIT_TYPE wait_status;
10326 WAIT_STATUS_INT(wait_status) = status;
10327 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010328}
10329#endif /* WIFSIGNALED */
10330
Larry Hastings2f936352014-08-05 14:04:04 +100010331
Guido van Rossumc9641791998-08-04 15:26:23 +000010332#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010333/*[clinic input]
10334os.WIFEXITED -> bool
10335
10336 status: int
10337
10338Return True if the process returning status exited via the exit() system call.
10339[clinic start generated code]*/
10340
Larry Hastings2f936352014-08-05 14:04:04 +100010341static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010342os_WIFEXITED_impl(PyObject *module, int status)
10343/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010344{
10345 WAIT_TYPE wait_status;
10346 WAIT_STATUS_INT(wait_status) = status;
10347 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010348}
10349#endif /* WIFEXITED */
10350
Larry Hastings2f936352014-08-05 14:04:04 +100010351
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010352#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010353/*[clinic input]
10354os.WEXITSTATUS -> int
10355
10356 status: int
10357
10358Return the process return code from status.
10359[clinic start generated code]*/
10360
Larry Hastings2f936352014-08-05 14:04:04 +100010361static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010362os_WEXITSTATUS_impl(PyObject *module, int status)
10363/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010364{
10365 WAIT_TYPE wait_status;
10366 WAIT_STATUS_INT(wait_status) = status;
10367 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010368}
10369#endif /* WEXITSTATUS */
10370
Larry Hastings2f936352014-08-05 14:04:04 +100010371
Guido van Rossumc9641791998-08-04 15:26:23 +000010372#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010373/*[clinic input]
10374os.WTERMSIG -> int
10375
10376 status: int
10377
10378Return the signal that terminated the process that provided the status value.
10379[clinic start generated code]*/
10380
Larry Hastings2f936352014-08-05 14:04:04 +100010381static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010382os_WTERMSIG_impl(PyObject *module, int status)
10383/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010384{
10385 WAIT_TYPE wait_status;
10386 WAIT_STATUS_INT(wait_status) = status;
10387 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010388}
10389#endif /* WTERMSIG */
10390
Larry Hastings2f936352014-08-05 14:04:04 +100010391
Guido van Rossumc9641791998-08-04 15:26:23 +000010392#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010393/*[clinic input]
10394os.WSTOPSIG -> int
10395
10396 status: int
10397
10398Return the signal that stopped the process that provided the status value.
10399[clinic start generated code]*/
10400
Larry Hastings2f936352014-08-05 14:04:04 +100010401static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010402os_WSTOPSIG_impl(PyObject *module, int status)
10403/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010404{
10405 WAIT_TYPE wait_status;
10406 WAIT_STATUS_INT(wait_status) = status;
10407 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010408}
10409#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010410#endif /* HAVE_SYS_WAIT_H */
10411
10412
Thomas Wouters477c8d52006-05-27 19:21:47 +000010413#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010414#ifdef _SCO_DS
10415/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10416 needed definitions in sys/statvfs.h */
10417#define _SVID3
10418#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010419#include <sys/statvfs.h>
10420
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010421static PyObject*
10422_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondo474eedf2018-11-13 04:09:31 -080010423 PyObject *v = PyStructSequence_New(StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010424 if (v == NULL)
10425 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010426
10427#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010428 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10429 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10430 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10431 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10432 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10433 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10434 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10435 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10436 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10437 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010438#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010439 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10440 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10441 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010442 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010443 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010444 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010445 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010446 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010447 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010448 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010449 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010450 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010451 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010452 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010453 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10454 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010455#endif
Michael Felt502d5512018-01-05 13:01:58 +010010456/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10457 * (issue #32390). */
10458#if defined(_AIX) && defined(_ALL_SOURCE)
10459 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10460#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010461 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010462#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010463 if (PyErr_Occurred()) {
10464 Py_DECREF(v);
10465 return NULL;
10466 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010467
Victor Stinner8c62be82010-05-06 00:08:46 +000010468 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010469}
10470
Larry Hastings2f936352014-08-05 14:04:04 +100010471
10472/*[clinic input]
10473os.fstatvfs
10474 fd: int
10475 /
10476
10477Perform an fstatvfs system call on the given fd.
10478
10479Equivalent to statvfs(fd).
10480[clinic start generated code]*/
10481
Larry Hastings2f936352014-08-05 14:04:04 +100010482static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010483os_fstatvfs_impl(PyObject *module, int fd)
10484/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010485{
10486 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010487 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010488 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010489
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010490 do {
10491 Py_BEGIN_ALLOW_THREADS
10492 result = fstatvfs(fd, &st);
10493 Py_END_ALLOW_THREADS
10494 } while (result != 0 && errno == EINTR &&
10495 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010496 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010497 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010498
Victor Stinner8c62be82010-05-06 00:08:46 +000010499 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010500}
Larry Hastings2f936352014-08-05 14:04:04 +100010501#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010502
10503
Thomas Wouters477c8d52006-05-27 19:21:47 +000010504#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010505#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010506/*[clinic input]
10507os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010508
Larry Hastings2f936352014-08-05 14:04:04 +100010509 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10510
10511Perform a statvfs system call on the given path.
10512
10513path may always be specified as a string.
10514On some platforms, path may also be specified as an open file descriptor.
10515 If this functionality is unavailable, using it raises an exception.
10516[clinic start generated code]*/
10517
Larry Hastings2f936352014-08-05 14:04:04 +100010518static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010519os_statvfs_impl(PyObject *module, path_t *path)
10520/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010521{
10522 int result;
10523 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010524
10525 Py_BEGIN_ALLOW_THREADS
10526#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010527 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010528#ifdef __APPLE__
10529 /* handle weak-linking on Mac OS X 10.3 */
10530 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010531 fd_specified("statvfs", path->fd);
10532 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010533 }
10534#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010535 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010536 }
10537 else
10538#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010539 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010540 Py_END_ALLOW_THREADS
10541
10542 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010543 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010544 }
10545
Larry Hastings2f936352014-08-05 14:04:04 +100010546 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010547}
Larry Hastings2f936352014-08-05 14:04:04 +100010548#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10549
Guido van Rossum94f6f721999-01-06 18:42:14 +000010550
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010551#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010552/*[clinic input]
10553os._getdiskusage
10554
Steve Dower23ad6d02018-02-22 10:39:10 -080010555 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010556
10557Return disk usage statistics about the given path as a (total, free) tuple.
10558[clinic start generated code]*/
10559
Larry Hastings2f936352014-08-05 14:04:04 +100010560static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010561os__getdiskusage_impl(PyObject *module, path_t *path)
10562/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010563{
10564 BOOL retval;
10565 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010566 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010567
10568 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010569 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010570 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010571 if (retval == 0) {
10572 if (GetLastError() == ERROR_DIRECTORY) {
10573 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010574
Joe Pamerc8c02492018-09-25 10:57:36 -040010575 dir_path = PyMem_New(wchar_t, path->length + 1);
10576 if (dir_path == NULL) {
10577 return PyErr_NoMemory();
10578 }
10579
10580 wcscpy_s(dir_path, path->length + 1, path->wide);
10581
10582 if (_dirnameW(dir_path) != -1) {
10583 Py_BEGIN_ALLOW_THREADS
10584 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10585 Py_END_ALLOW_THREADS
10586 }
10587 /* Record the last error in case it's modified by PyMem_Free. */
10588 err = GetLastError();
10589 PyMem_Free(dir_path);
10590 if (retval) {
10591 goto success;
10592 }
10593 }
10594 return PyErr_SetFromWindowsErr(err);
10595 }
10596
10597success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010598 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10599}
Larry Hastings2f936352014-08-05 14:04:04 +100010600#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010601
10602
Fred Drakec9680921999-12-13 16:37:25 +000010603/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10604 * It maps strings representing configuration variable names to
10605 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010606 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010607 * rarely-used constants. There are three separate tables that use
10608 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010609 *
10610 * This code is always included, even if none of the interfaces that
10611 * need it are included. The #if hackery needed to avoid it would be
10612 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010613 */
10614struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010615 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010616 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010617};
10618
Fred Drake12c6e2d1999-12-14 21:25:03 +000010619static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010620conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010621 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010622{
Christian Heimes217cfd12007-12-02 14:31:20 +000010623 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010624 int value = _PyLong_AsInt(arg);
10625 if (value == -1 && PyErr_Occurred())
10626 return 0;
10627 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010628 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010629 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010630 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010631 /* look up the value in the table using a binary search */
10632 size_t lo = 0;
10633 size_t mid;
10634 size_t hi = tablesize;
10635 int cmp;
10636 const char *confname;
10637 if (!PyUnicode_Check(arg)) {
10638 PyErr_SetString(PyExc_TypeError,
10639 "configuration names must be strings or integers");
10640 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010641 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010642 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010643 if (confname == NULL)
10644 return 0;
10645 while (lo < hi) {
10646 mid = (lo + hi) / 2;
10647 cmp = strcmp(confname, table[mid].name);
10648 if (cmp < 0)
10649 hi = mid;
10650 else if (cmp > 0)
10651 lo = mid + 1;
10652 else {
10653 *valuep = table[mid].value;
10654 return 1;
10655 }
10656 }
10657 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10658 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010659 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010660}
10661
10662
10663#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10664static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010665#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010666 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010667#endif
10668#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010669 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010670#endif
Fred Drakec9680921999-12-13 16:37:25 +000010671#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010672 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010673#endif
10674#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010675 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010676#endif
10677#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010678 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010679#endif
10680#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010681 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010682#endif
10683#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010684 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010685#endif
10686#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010687 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010688#endif
10689#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010690 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010691#endif
10692#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010693 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010694#endif
10695#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010696 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010697#endif
10698#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010699 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010700#endif
10701#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010702 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010703#endif
10704#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010705 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010706#endif
10707#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010708 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010709#endif
10710#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010711 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010712#endif
10713#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010714 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010715#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010716#ifdef _PC_ACL_ENABLED
10717 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10718#endif
10719#ifdef _PC_MIN_HOLE_SIZE
10720 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10721#endif
10722#ifdef _PC_ALLOC_SIZE_MIN
10723 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10724#endif
10725#ifdef _PC_REC_INCR_XFER_SIZE
10726 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10727#endif
10728#ifdef _PC_REC_MAX_XFER_SIZE
10729 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10730#endif
10731#ifdef _PC_REC_MIN_XFER_SIZE
10732 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10733#endif
10734#ifdef _PC_REC_XFER_ALIGN
10735 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10736#endif
10737#ifdef _PC_SYMLINK_MAX
10738 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10739#endif
10740#ifdef _PC_XATTR_ENABLED
10741 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10742#endif
10743#ifdef _PC_XATTR_EXISTS
10744 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10745#endif
10746#ifdef _PC_TIMESTAMP_RESOLUTION
10747 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10748#endif
Fred Drakec9680921999-12-13 16:37:25 +000010749};
10750
Fred Drakec9680921999-12-13 16:37:25 +000010751static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010752conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010753{
10754 return conv_confname(arg, valuep, posix_constants_pathconf,
10755 sizeof(posix_constants_pathconf)
10756 / sizeof(struct constdef));
10757}
10758#endif
10759
Larry Hastings2f936352014-08-05 14:04:04 +100010760
Fred Drakec9680921999-12-13 16:37:25 +000010761#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010762/*[clinic input]
10763os.fpathconf -> long
10764
10765 fd: int
10766 name: path_confname
10767 /
10768
10769Return the configuration limit name for the file descriptor fd.
10770
10771If there is no limit, return -1.
10772[clinic start generated code]*/
10773
Larry Hastings2f936352014-08-05 14:04:04 +100010774static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010775os_fpathconf_impl(PyObject *module, int fd, int name)
10776/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010777{
10778 long limit;
10779
10780 errno = 0;
10781 limit = fpathconf(fd, name);
10782 if (limit == -1 && errno != 0)
10783 posix_error();
10784
10785 return limit;
10786}
10787#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010788
10789
10790#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010791/*[clinic input]
10792os.pathconf -> long
10793 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10794 name: path_confname
10795
10796Return the configuration limit name for the file or directory path.
10797
10798If there is no limit, return -1.
10799On some platforms, path may also be specified as an open file descriptor.
10800 If this functionality is unavailable, using it raises an exception.
10801[clinic start generated code]*/
10802
Larry Hastings2f936352014-08-05 14:04:04 +100010803static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010804os_pathconf_impl(PyObject *module, path_t *path, int name)
10805/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010806{
Victor Stinner8c62be82010-05-06 00:08:46 +000010807 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010808
Victor Stinner8c62be82010-05-06 00:08:46 +000010809 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010810#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010811 if (path->fd != -1)
10812 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010813 else
10814#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010815 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010816 if (limit == -1 && errno != 0) {
10817 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010818 /* could be a path or name problem */
10819 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010820 else
Larry Hastings2f936352014-08-05 14:04:04 +100010821 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010822 }
Larry Hastings2f936352014-08-05 14:04:04 +100010823
10824 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010825}
Larry Hastings2f936352014-08-05 14:04:04 +100010826#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010827
10828#ifdef HAVE_CONFSTR
10829static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010830#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010831 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010832#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010833#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010834 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010835#endif
10836#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010837 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010838#endif
Fred Draked86ed291999-12-15 15:34:33 +000010839#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010840 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010841#endif
10842#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010843 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010844#endif
10845#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010846 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010847#endif
10848#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010849 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010850#endif
Fred Drakec9680921999-12-13 16:37:25 +000010851#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010852 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010853#endif
10854#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010855 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010856#endif
10857#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010858 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010859#endif
10860#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010861 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010862#endif
10863#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010864 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010865#endif
10866#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010867 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010868#endif
10869#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010870 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010871#endif
10872#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010873 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010874#endif
Fred Draked86ed291999-12-15 15:34:33 +000010875#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010876 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010877#endif
Fred Drakec9680921999-12-13 16:37:25 +000010878#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010879 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010880#endif
Fred Draked86ed291999-12-15 15:34:33 +000010881#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010882 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010883#endif
10884#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010885 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010886#endif
10887#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010888 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010889#endif
10890#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010891 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010892#endif
Fred Drakec9680921999-12-13 16:37:25 +000010893#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010894 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010895#endif
10896#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010897 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010898#endif
10899#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010900 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010901#endif
10902#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010903 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010904#endif
10905#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010906 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010907#endif
10908#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010909 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010910#endif
10911#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010912 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010913#endif
10914#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010915 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010916#endif
10917#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010918 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010919#endif
10920#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010921 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010922#endif
10923#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010924 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010925#endif
10926#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010927 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010928#endif
10929#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010930 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010931#endif
10932#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010933 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010934#endif
10935#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010936 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010937#endif
10938#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010939 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010940#endif
Fred Draked86ed291999-12-15 15:34:33 +000010941#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010942 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010943#endif
10944#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010945 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010946#endif
10947#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010948 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010949#endif
10950#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010951 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010952#endif
10953#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010954 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010955#endif
10956#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010957 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010958#endif
10959#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010960 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010961#endif
10962#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010963 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010964#endif
10965#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010966 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010967#endif
10968#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010969 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010970#endif
10971#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010972 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010973#endif
10974#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010975 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010976#endif
10977#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010978 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010979#endif
Fred Drakec9680921999-12-13 16:37:25 +000010980};
10981
10982static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010983conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010984{
10985 return conv_confname(arg, valuep, posix_constants_confstr,
10986 sizeof(posix_constants_confstr)
10987 / sizeof(struct constdef));
10988}
10989
Larry Hastings2f936352014-08-05 14:04:04 +100010990
10991/*[clinic input]
10992os.confstr
10993
10994 name: confstr_confname
10995 /
10996
10997Return a string-valued system configuration variable.
10998[clinic start generated code]*/
10999
Larry Hastings2f936352014-08-05 14:04:04 +100011000static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011001os_confstr_impl(PyObject *module, int name)
11002/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011003{
11004 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011005 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011006 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011007
Victor Stinnercb043522010-09-10 23:49:04 +000011008 errno = 0;
11009 len = confstr(name, buffer, sizeof(buffer));
11010 if (len == 0) {
11011 if (errno) {
11012 posix_error();
11013 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011014 }
11015 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011016 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011017 }
11018 }
Victor Stinnercb043522010-09-10 23:49:04 +000011019
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011020 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011021 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011022 char *buf = PyMem_Malloc(len);
11023 if (buf == NULL)
11024 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011025 len2 = confstr(name, buf, len);
11026 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011027 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011028 PyMem_Free(buf);
11029 }
11030 else
11031 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011032 return result;
11033}
Larry Hastings2f936352014-08-05 14:04:04 +100011034#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011035
11036
11037#ifdef HAVE_SYSCONF
11038static struct constdef posix_constants_sysconf[] = {
11039#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011040 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011041#endif
11042#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011043 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011044#endif
11045#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011046 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011047#endif
11048#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011049 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011050#endif
11051#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011052 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011053#endif
11054#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011055 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011056#endif
11057#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011058 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011059#endif
11060#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011061 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011062#endif
11063#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011064 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011065#endif
11066#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011067 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011068#endif
Fred Draked86ed291999-12-15 15:34:33 +000011069#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011070 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011071#endif
11072#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011073 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011074#endif
Fred Drakec9680921999-12-13 16:37:25 +000011075#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011076 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011077#endif
Fred Drakec9680921999-12-13 16:37:25 +000011078#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011079 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011080#endif
11081#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011082 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011083#endif
11084#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011085 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011086#endif
11087#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011088 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011089#endif
11090#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011091 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011092#endif
Fred Draked86ed291999-12-15 15:34:33 +000011093#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011094 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011095#endif
Fred Drakec9680921999-12-13 16:37:25 +000011096#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011097 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011098#endif
11099#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011100 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011101#endif
11102#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011103 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011104#endif
11105#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011106 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011107#endif
11108#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011109 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011110#endif
Fred Draked86ed291999-12-15 15:34:33 +000011111#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011112 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011113#endif
Fred Drakec9680921999-12-13 16:37:25 +000011114#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011115 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011116#endif
11117#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011118 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011119#endif
11120#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011121 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011122#endif
11123#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011124 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011125#endif
11126#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011127 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011128#endif
11129#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011130 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011131#endif
11132#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011133 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011134#endif
11135#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011136 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011137#endif
11138#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011139 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011140#endif
11141#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011142 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011143#endif
11144#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011145 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011146#endif
11147#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011148 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011149#endif
11150#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011151 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011152#endif
11153#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011154 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011155#endif
11156#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011157 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011158#endif
11159#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011160 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011161#endif
11162#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011163 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011164#endif
11165#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011166 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011167#endif
11168#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011169 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011170#endif
11171#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011172 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011173#endif
11174#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011175 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011176#endif
11177#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011178 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011179#endif
11180#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011181 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011182#endif
Fred Draked86ed291999-12-15 15:34:33 +000011183#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011184 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011185#endif
Fred Drakec9680921999-12-13 16:37:25 +000011186#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011187 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011188#endif
11189#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011190 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011191#endif
11192#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011193 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011194#endif
Fred Draked86ed291999-12-15 15:34:33 +000011195#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011196 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011197#endif
Fred Drakec9680921999-12-13 16:37:25 +000011198#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011199 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011200#endif
Fred Draked86ed291999-12-15 15:34:33 +000011201#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011202 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011203#endif
11204#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011205 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011206#endif
Fred Drakec9680921999-12-13 16:37:25 +000011207#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011208 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011209#endif
11210#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011211 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011212#endif
11213#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011214 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011215#endif
11216#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011217 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011218#endif
Fred Draked86ed291999-12-15 15:34:33 +000011219#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011220 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011221#endif
Fred Drakec9680921999-12-13 16:37:25 +000011222#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011223 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011224#endif
11225#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011226 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011227#endif
11228#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011229 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011230#endif
11231#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011232 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011233#endif
11234#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011235 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011236#endif
11237#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011238 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011239#endif
11240#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011241 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011242#endif
Fred Draked86ed291999-12-15 15:34:33 +000011243#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011244 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011245#endif
Fred Drakec9680921999-12-13 16:37:25 +000011246#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011247 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011248#endif
11249#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011250 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011251#endif
Fred Draked86ed291999-12-15 15:34:33 +000011252#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011253 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011254#endif
Fred Drakec9680921999-12-13 16:37:25 +000011255#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011256 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011257#endif
11258#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011259 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011260#endif
11261#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011262 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011263#endif
11264#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011265 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011266#endif
11267#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011268 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011269#endif
11270#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011271 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011272#endif
11273#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011274 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011275#endif
11276#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011277 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011278#endif
11279#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011280 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011281#endif
Fred Draked86ed291999-12-15 15:34:33 +000011282#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011283 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011284#endif
11285#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011286 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011287#endif
Fred Drakec9680921999-12-13 16:37:25 +000011288#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011289 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011290#endif
11291#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011292 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011293#endif
11294#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011295 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011296#endif
11297#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011298 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011299#endif
11300#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011301 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011302#endif
11303#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011304 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011305#endif
11306#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011307 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011308#endif
11309#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011310 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011311#endif
11312#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011313 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011314#endif
11315#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011316 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011317#endif
11318#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011319 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011320#endif
11321#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011322 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011323#endif
11324#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011325 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011326#endif
11327#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011328 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011329#endif
11330#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011331 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011332#endif
11333#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011334 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011335#endif
11336#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011337 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011338#endif
11339#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011340 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011341#endif
11342#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011343 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011344#endif
11345#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011346 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011347#endif
11348#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011349 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011350#endif
11351#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011352 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011353#endif
11354#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011355 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011356#endif
11357#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011358 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011359#endif
11360#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011361 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011362#endif
11363#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011364 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011365#endif
11366#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011367 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011368#endif
11369#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011370 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011371#endif
11372#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011373 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011374#endif
11375#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011376 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011377#endif
11378#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011379 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011380#endif
11381#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011382 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011383#endif
11384#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011385 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011386#endif
11387#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011388 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011389#endif
11390#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011391 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011392#endif
Fred Draked86ed291999-12-15 15:34:33 +000011393#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011394 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011395#endif
Fred Drakec9680921999-12-13 16:37:25 +000011396#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011397 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011398#endif
11399#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011400 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011401#endif
11402#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011403 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011404#endif
11405#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011406 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011407#endif
11408#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011409 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011410#endif
11411#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011412 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011413#endif
11414#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011415 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011416#endif
11417#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011418 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011419#endif
11420#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011421 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011422#endif
11423#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011424 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011425#endif
11426#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011427 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011428#endif
11429#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011430 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011431#endif
11432#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011433 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011434#endif
11435#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011436 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011437#endif
11438#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011439 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011440#endif
11441#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011442 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011443#endif
11444#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011445 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011446#endif
11447#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011448 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011449#endif
11450#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011451 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011452#endif
11453#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011454 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011455#endif
11456#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011457 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011458#endif
11459#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011460 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011461#endif
11462#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011463 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011464#endif
11465#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011466 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011467#endif
11468#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011469 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011470#endif
11471#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011472 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011473#endif
11474#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011475 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011476#endif
11477#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011478 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011479#endif
11480#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011481 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011482#endif
11483#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011484 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011485#endif
11486#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011487 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011488#endif
11489#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011490 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011491#endif
11492#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011493 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011494#endif
11495#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011496 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011497#endif
11498#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011499 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011500#endif
11501#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011502 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011503#endif
11504#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011505 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011506#endif
11507#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011508 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011509#endif
11510#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011511 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011512#endif
11513#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011514 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011515#endif
11516#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011517 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011518#endif
11519#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011520 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011521#endif
11522#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011523 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011524#endif
11525#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011526 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011527#endif
11528#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011529 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011530#endif
11531};
11532
11533static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011534conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011535{
11536 return conv_confname(arg, valuep, posix_constants_sysconf,
11537 sizeof(posix_constants_sysconf)
11538 / sizeof(struct constdef));
11539}
11540
Larry Hastings2f936352014-08-05 14:04:04 +100011541
11542/*[clinic input]
11543os.sysconf -> long
11544 name: sysconf_confname
11545 /
11546
11547Return an integer-valued system configuration variable.
11548[clinic start generated code]*/
11549
Larry Hastings2f936352014-08-05 14:04:04 +100011550static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011551os_sysconf_impl(PyObject *module, int name)
11552/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011553{
11554 long value;
11555
11556 errno = 0;
11557 value = sysconf(name);
11558 if (value == -1 && errno != 0)
11559 posix_error();
11560 return value;
11561}
11562#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011563
11564
Fred Drakebec628d1999-12-15 18:31:10 +000011565/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011566 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011567 * the exported dictionaries that are used to publish information about the
11568 * names available on the host platform.
11569 *
11570 * Sorting the table at runtime ensures that the table is properly ordered
11571 * when used, even for platforms we're not able to test on. It also makes
11572 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011573 */
Fred Drakebec628d1999-12-15 18:31:10 +000011574
11575static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011576cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011577{
11578 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011579 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011580 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011581 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011582
11583 return strcmp(c1->name, c2->name);
11584}
11585
11586static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011587setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011588 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011589{
Fred Drakebec628d1999-12-15 18:31:10 +000011590 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011591 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011592
11593 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11594 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011595 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011596 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011597
Barry Warsaw3155db32000-04-13 15:20:40 +000011598 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011599 PyObject *o = PyLong_FromLong(table[i].value);
11600 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11601 Py_XDECREF(o);
11602 Py_DECREF(d);
11603 return -1;
11604 }
11605 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011606 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011607 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011608}
11609
Fred Drakebec628d1999-12-15 18:31:10 +000011610/* Return -1 on failure, 0 on success. */
11611static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011612setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011613{
11614#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011615 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011616 sizeof(posix_constants_pathconf)
11617 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011618 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011619 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011620#endif
11621#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011622 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011623 sizeof(posix_constants_confstr)
11624 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011625 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011626 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011627#endif
11628#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011629 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011630 sizeof(posix_constants_sysconf)
11631 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011632 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011633 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011634#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011635 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011636}
Fred Draked86ed291999-12-15 15:34:33 +000011637
11638
Larry Hastings2f936352014-08-05 14:04:04 +100011639/*[clinic input]
11640os.abort
11641
11642Abort the interpreter immediately.
11643
11644This function 'dumps core' or otherwise fails in the hardest way possible
11645on the hosting operating system. This function never returns.
11646[clinic start generated code]*/
11647
Larry Hastings2f936352014-08-05 14:04:04 +100011648static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011649os_abort_impl(PyObject *module)
11650/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011651{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011652 abort();
11653 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011654#ifndef __clang__
11655 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11656 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11657 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011658 Py_FatalError("abort() called from Python code didn't abort!");
11659 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011660#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011661}
Fred Drakebec628d1999-12-15 18:31:10 +000011662
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011663#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011664/* Grab ShellExecute dynamically from shell32 */
11665static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011666static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11667 LPCWSTR, INT);
11668static int
11669check_ShellExecute()
11670{
11671 HINSTANCE hShell32;
11672
11673 /* only recheck */
11674 if (-1 == has_ShellExecute) {
11675 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011676 /* Security note: this call is not vulnerable to "DLL hijacking".
11677 SHELL32 is part of "KnownDLLs" and so Windows always load
11678 the system SHELL32.DLL, even if there is another SHELL32.DLL
11679 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011680 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011681 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011682 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11683 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011684 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011685 } else {
11686 has_ShellExecute = 0;
11687 }
Tony Roberts4860f012019-02-02 18:16:42 +010011688 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011689 }
11690 return has_ShellExecute;
11691}
11692
11693
Steve Dowercc16be82016-09-08 10:35:16 -070011694/*[clinic input]
11695os.startfile
11696 filepath: path_t
11697 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011698
Steve Dowercc16be82016-09-08 10:35:16 -070011699Start a file with its associated application.
11700
11701When "operation" is not specified or "open", this acts like
11702double-clicking the file in Explorer, or giving the file name as an
11703argument to the DOS "start" command: the file is opened with whatever
11704application (if any) its extension is associated.
11705When another "operation" is given, it specifies what should be done with
11706the file. A typical operation is "print".
11707
11708startfile returns as soon as the associated application is launched.
11709There is no option to wait for the application to close, and no way
11710to retrieve the application's exit status.
11711
11712The filepath is relative to the current directory. If you want to use
11713an absolute path, make sure the first character is not a slash ("/");
11714the underlying Win32 ShellExecute function doesn't work if it is.
11715[clinic start generated code]*/
11716
11717static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011718os_startfile_impl(PyObject *module, path_t *filepath,
11719 const Py_UNICODE *operation)
Serhiy Storchakad322abb2019-09-14 13:31:50 +030011720/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011721{
11722 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011723
11724 if(!check_ShellExecute()) {
11725 /* If the OS doesn't have ShellExecute, return a
11726 NotImplementedError. */
11727 return PyErr_Format(PyExc_NotImplementedError,
11728 "startfile not available on this platform");
11729 }
11730
Steve Dowera00b5be2020-02-13 08:30:27 +000011731 if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
Miss Islington (bot)3498ac52020-02-04 16:32:32 -080011732 return NULL;
11733 }
11734
Victor Stinner8c62be82010-05-06 00:08:46 +000011735 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011736 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011737 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011738 Py_END_ALLOW_THREADS
11739
Victor Stinner8c62be82010-05-06 00:08:46 +000011740 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011741 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011742 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011743 }
Steve Dowercc16be82016-09-08 10:35:16 -070011744 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011745}
Larry Hastings2f936352014-08-05 14:04:04 +100011746#endif /* MS_WINDOWS */
11747
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011748
Martin v. Löwis438b5342002-12-27 10:16:42 +000011749#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011750/*[clinic input]
11751os.getloadavg
11752
11753Return average recent system load information.
11754
11755Return the number of processes in the system run queue averaged over
11756the last 1, 5, and 15 minutes as a tuple of three floats.
11757Raises OSError if the load average was unobtainable.
11758[clinic start generated code]*/
11759
Larry Hastings2f936352014-08-05 14:04:04 +100011760static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011761os_getloadavg_impl(PyObject *module)
11762/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011763{
11764 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011765 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011766 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11767 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011768 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011769 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011770}
Larry Hastings2f936352014-08-05 14:04:04 +100011771#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011772
Larry Hastings2f936352014-08-05 14:04:04 +100011773
11774/*[clinic input]
11775os.device_encoding
11776 fd: int
11777
11778Return a string describing the encoding of a terminal's file descriptor.
11779
11780The file descriptor must be attached to a terminal.
11781If the device is not a terminal, return None.
11782[clinic start generated code]*/
11783
Larry Hastings2f936352014-08-05 14:04:04 +100011784static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011785os_device_encoding_impl(PyObject *module, int fd)
11786/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011787{
Brett Cannonefb00c02012-02-29 18:31:31 -050011788 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011789}
11790
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011791
Larry Hastings2f936352014-08-05 14:04:04 +100011792#ifdef HAVE_SETRESUID
11793/*[clinic input]
11794os.setresuid
11795
11796 ruid: uid_t
11797 euid: uid_t
11798 suid: uid_t
11799 /
11800
11801Set the current process's real, effective, and saved user ids.
11802[clinic start generated code]*/
11803
Larry Hastings2f936352014-08-05 14:04:04 +100011804static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011805os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11806/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011807{
Victor Stinner8c62be82010-05-06 00:08:46 +000011808 if (setresuid(ruid, euid, suid) < 0)
11809 return posix_error();
11810 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011811}
Larry Hastings2f936352014-08-05 14:04:04 +100011812#endif /* HAVE_SETRESUID */
11813
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011814
11815#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011816/*[clinic input]
11817os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011818
Larry Hastings2f936352014-08-05 14:04:04 +100011819 rgid: gid_t
11820 egid: gid_t
11821 sgid: gid_t
11822 /
11823
11824Set the current process's real, effective, and saved group ids.
11825[clinic start generated code]*/
11826
Larry Hastings2f936352014-08-05 14:04:04 +100011827static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011828os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11829/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011830{
Victor Stinner8c62be82010-05-06 00:08:46 +000011831 if (setresgid(rgid, egid, sgid) < 0)
11832 return posix_error();
11833 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011834}
Larry Hastings2f936352014-08-05 14:04:04 +100011835#endif /* HAVE_SETRESGID */
11836
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011837
11838#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011839/*[clinic input]
11840os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011841
Larry Hastings2f936352014-08-05 14:04:04 +100011842Return a tuple of the current process's real, effective, and saved user ids.
11843[clinic start generated code]*/
11844
Larry Hastings2f936352014-08-05 14:04:04 +100011845static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011846os_getresuid_impl(PyObject *module)
11847/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011848{
Victor Stinner8c62be82010-05-06 00:08:46 +000011849 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011850 if (getresuid(&ruid, &euid, &suid) < 0)
11851 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011852 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11853 _PyLong_FromUid(euid),
11854 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011855}
Larry Hastings2f936352014-08-05 14:04:04 +100011856#endif /* HAVE_GETRESUID */
11857
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011858
11859#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011860/*[clinic input]
11861os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011862
Larry Hastings2f936352014-08-05 14:04:04 +100011863Return a tuple of the current process's real, effective, and saved group ids.
11864[clinic start generated code]*/
11865
Larry Hastings2f936352014-08-05 14:04:04 +100011866static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011867os_getresgid_impl(PyObject *module)
11868/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011869{
11870 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011871 if (getresgid(&rgid, &egid, &sgid) < 0)
11872 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011873 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11874 _PyLong_FromGid(egid),
11875 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011876}
Larry Hastings2f936352014-08-05 14:04:04 +100011877#endif /* HAVE_GETRESGID */
11878
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011879
Benjamin Peterson9428d532011-09-14 11:45:52 -040011880#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011881/*[clinic input]
11882os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011883
Larry Hastings2f936352014-08-05 14:04:04 +100011884 path: path_t(allow_fd=True)
11885 attribute: path_t
11886 *
11887 follow_symlinks: bool = True
11888
11889Return the value of extended attribute attribute on path.
11890
BNMetricsb9427072018-11-02 15:20:19 +000011891path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011892If follow_symlinks is False, and the last element of the path is a symbolic
11893 link, getxattr will examine the symbolic link itself instead of the file
11894 the link points to.
11895
11896[clinic start generated code]*/
11897
Larry Hastings2f936352014-08-05 14:04:04 +100011898static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011899os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011900 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011901/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011902{
11903 Py_ssize_t i;
11904 PyObject *buffer = NULL;
11905
11906 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11907 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011908
Steve Dowera00b5be2020-02-13 08:30:27 +000011909 if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
11910 return NULL;
11911 }
11912
Larry Hastings9cf065c2012-06-22 16:30:09 -070011913 for (i = 0; ; i++) {
11914 void *ptr;
11915 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011916 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011917 Py_ssize_t buffer_size = buffer_sizes[i];
11918 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011919 path_error(path);
11920 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011921 }
11922 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11923 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011924 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011925 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011926
Larry Hastings9cf065c2012-06-22 16:30:09 -070011927 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011928 if (path->fd >= 0)
11929 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011930 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011931 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011932 else
Larry Hastings2f936352014-08-05 14:04:04 +100011933 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011934 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011935
Larry Hastings9cf065c2012-06-22 16:30:09 -070011936 if (result < 0) {
11937 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011938 if (errno == ERANGE)
11939 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011940 path_error(path);
11941 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011942 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011943
Larry Hastings9cf065c2012-06-22 16:30:09 -070011944 if (result != buffer_size) {
11945 /* Can only shrink. */
11946 _PyBytes_Resize(&buffer, result);
11947 }
11948 break;
11949 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011950
Larry Hastings9cf065c2012-06-22 16:30:09 -070011951 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011952}
11953
Larry Hastings2f936352014-08-05 14:04:04 +100011954
11955/*[clinic input]
11956os.setxattr
11957
11958 path: path_t(allow_fd=True)
11959 attribute: path_t
11960 value: Py_buffer
11961 flags: int = 0
11962 *
11963 follow_symlinks: bool = True
11964
11965Set extended attribute attribute on path to value.
11966
BNMetricsb9427072018-11-02 15:20:19 +000011967path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011968If follow_symlinks is False, and the last element of the path is a symbolic
11969 link, setxattr will modify the symbolic link itself instead of the file
11970 the link points to.
11971
11972[clinic start generated code]*/
11973
Benjamin Peterson799bd802011-08-31 22:15:17 -040011974static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011975os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011976 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011977/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011978{
Larry Hastings2f936352014-08-05 14:04:04 +100011979 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011980
Larry Hastings2f936352014-08-05 14:04:04 +100011981 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011982 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011983
Steve Dowera00b5be2020-02-13 08:30:27 +000011984 if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
11985 value->buf, value->len, flags) < 0) {
11986 return NULL;
11987 }
11988
Benjamin Peterson799bd802011-08-31 22:15:17 -040011989 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011990 if (path->fd > -1)
11991 result = fsetxattr(path->fd, attribute->narrow,
11992 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011993 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011994 result = setxattr(path->narrow, attribute->narrow,
11995 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011996 else
Larry Hastings2f936352014-08-05 14:04:04 +100011997 result = lsetxattr(path->narrow, attribute->narrow,
11998 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011999 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012000
Larry Hastings9cf065c2012-06-22 16:30:09 -070012001 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100012002 path_error(path);
12003 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012004 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012005
Larry Hastings2f936352014-08-05 14:04:04 +100012006 Py_RETURN_NONE;
12007}
12008
12009
12010/*[clinic input]
12011os.removexattr
12012
12013 path: path_t(allow_fd=True)
12014 attribute: path_t
12015 *
12016 follow_symlinks: bool = True
12017
12018Remove extended attribute attribute on path.
12019
BNMetricsb9427072018-11-02 15:20:19 +000012020path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012021If follow_symlinks is False, and the last element of the path is a symbolic
12022 link, removexattr will modify the symbolic link itself instead of the file
12023 the link points to.
12024
12025[clinic start generated code]*/
12026
Larry Hastings2f936352014-08-05 14:04:04 +100012027static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012028os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012029 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012030/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012031{
12032 ssize_t result;
12033
12034 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12035 return NULL;
12036
Steve Dowera00b5be2020-02-13 08:30:27 +000012037 if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
12038 return NULL;
12039 }
12040
Larry Hastings2f936352014-08-05 14:04:04 +100012041 Py_BEGIN_ALLOW_THREADS;
12042 if (path->fd > -1)
12043 result = fremovexattr(path->fd, attribute->narrow);
12044 else if (follow_symlinks)
12045 result = removexattr(path->narrow, attribute->narrow);
12046 else
12047 result = lremovexattr(path->narrow, attribute->narrow);
12048 Py_END_ALLOW_THREADS;
12049
12050 if (result) {
12051 return path_error(path);
12052 }
12053
12054 Py_RETURN_NONE;
12055}
12056
12057
12058/*[clinic input]
12059os.listxattr
12060
12061 path: path_t(allow_fd=True, nullable=True) = None
12062 *
12063 follow_symlinks: bool = True
12064
12065Return a list of extended attributes on path.
12066
BNMetricsb9427072018-11-02 15:20:19 +000012067path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012068if path is None, listxattr will examine the current directory.
12069If follow_symlinks is False, and the last element of the path is a symbolic
12070 link, listxattr will examine the symbolic link itself instead of the file
12071 the link points to.
12072[clinic start generated code]*/
12073
Larry Hastings2f936352014-08-05 14:04:04 +100012074static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012075os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012076/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012077{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012078 Py_ssize_t i;
12079 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012080 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012081 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012082
Larry Hastings2f936352014-08-05 14:04:04 +100012083 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012084 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012085
Steve Dowera00b5be2020-02-13 08:30:27 +000012086 if (PySys_Audit("os.listxattr", "(O)",
12087 path->object ? path->object : Py_None) < 0) {
12088 return NULL;
12089 }
12090
Larry Hastings2f936352014-08-05 14:04:04 +100012091 name = path->narrow ? path->narrow : ".";
12092
Larry Hastings9cf065c2012-06-22 16:30:09 -070012093 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012094 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012095 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012096 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012097 Py_ssize_t buffer_size = buffer_sizes[i];
12098 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012099 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012100 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012101 break;
12102 }
12103 buffer = PyMem_MALLOC(buffer_size);
12104 if (!buffer) {
12105 PyErr_NoMemory();
12106 break;
12107 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012108
Larry Hastings9cf065c2012-06-22 16:30:09 -070012109 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012110 if (path->fd > -1)
12111 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012112 else if (follow_symlinks)
12113 length = listxattr(name, buffer, buffer_size);
12114 else
12115 length = llistxattr(name, buffer, buffer_size);
12116 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012117
Larry Hastings9cf065c2012-06-22 16:30:09 -070012118 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012119 if (errno == ERANGE) {
12120 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012121 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012122 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012123 }
Larry Hastings2f936352014-08-05 14:04:04 +100012124 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012125 break;
12126 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012127
Larry Hastings9cf065c2012-06-22 16:30:09 -070012128 result = PyList_New(0);
12129 if (!result) {
12130 goto exit;
12131 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012132
Larry Hastings9cf065c2012-06-22 16:30:09 -070012133 end = buffer + length;
12134 for (trace = start = buffer; trace != end; trace++) {
12135 if (!*trace) {
12136 int error;
12137 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12138 trace - start);
12139 if (!attribute) {
12140 Py_DECREF(result);
12141 result = NULL;
12142 goto exit;
12143 }
12144 error = PyList_Append(result, attribute);
12145 Py_DECREF(attribute);
12146 if (error) {
12147 Py_DECREF(result);
12148 result = NULL;
12149 goto exit;
12150 }
12151 start = trace + 1;
12152 }
12153 }
12154 break;
12155 }
12156exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012157 if (buffer)
12158 PyMem_FREE(buffer);
12159 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012160}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012161#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012162
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012163
Larry Hastings2f936352014-08-05 14:04:04 +100012164/*[clinic input]
12165os.urandom
12166
12167 size: Py_ssize_t
12168 /
12169
12170Return a bytes object containing random bytes suitable for cryptographic use.
12171[clinic start generated code]*/
12172
Larry Hastings2f936352014-08-05 14:04:04 +100012173static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012174os_urandom_impl(PyObject *module, Py_ssize_t size)
12175/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012176{
12177 PyObject *bytes;
12178 int result;
12179
Georg Brandl2fb477c2012-02-21 00:33:36 +010012180 if (size < 0)
12181 return PyErr_Format(PyExc_ValueError,
12182 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012183 bytes = PyBytes_FromStringAndSize(NULL, size);
12184 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012185 return NULL;
12186
Victor Stinnere66987e2016-09-06 16:33:52 -070012187 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012188 if (result == -1) {
12189 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012190 return NULL;
12191 }
Larry Hastings2f936352014-08-05 14:04:04 +100012192 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012193}
12194
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012195#ifdef HAVE_MEMFD_CREATE
12196/*[clinic input]
12197os.memfd_create
12198
12199 name: FSConverter
12200 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12201
12202[clinic start generated code]*/
12203
12204static PyObject *
12205os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12206/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12207{
12208 int fd;
12209 const char *bytes = PyBytes_AS_STRING(name);
12210 Py_BEGIN_ALLOW_THREADS
12211 fd = memfd_create(bytes, flags);
12212 Py_END_ALLOW_THREADS
12213 if (fd == -1) {
12214 return PyErr_SetFromErrno(PyExc_OSError);
12215 }
12216 return PyLong_FromLong(fd);
12217}
12218#endif
12219
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012220/* Terminal size querying */
12221
Eddie Elizondo474eedf2018-11-13 04:09:31 -080012222static PyTypeObject* TerminalSizeType;
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012223
12224PyDoc_STRVAR(TerminalSize_docstring,
12225 "A tuple of (columns, lines) for holding terminal window size");
12226
12227static PyStructSequence_Field TerminalSize_fields[] = {
12228 {"columns", "width of the terminal window in characters"},
12229 {"lines", "height of the terminal window in characters"},
12230 {NULL, NULL}
12231};
12232
12233static PyStructSequence_Desc TerminalSize_desc = {
12234 "os.terminal_size",
12235 TerminalSize_docstring,
12236 TerminalSize_fields,
12237 2,
12238};
12239
12240#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012241/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012242PyDoc_STRVAR(termsize__doc__,
12243 "Return the size of the terminal window as (columns, lines).\n" \
12244 "\n" \
12245 "The optional argument fd (default standard output) specifies\n" \
12246 "which file descriptor should be queried.\n" \
12247 "\n" \
12248 "If the file descriptor is not connected to a terminal, an OSError\n" \
12249 "is thrown.\n" \
12250 "\n" \
12251 "This function will only be defined if an implementation is\n" \
12252 "available for this system.\n" \
12253 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012254 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012255 "normally be used, os.get_terminal_size is the low-level implementation.");
12256
12257static PyObject*
12258get_terminal_size(PyObject *self, PyObject *args)
12259{
12260 int columns, lines;
12261 PyObject *termsize;
12262
12263 int fd = fileno(stdout);
12264 /* Under some conditions stdout may not be connected and
12265 * fileno(stdout) may point to an invalid file descriptor. For example
12266 * GUI apps don't have valid standard streams by default.
12267 *
12268 * If this happens, and the optional fd argument is not present,
12269 * the ioctl below will fail returning EBADF. This is what we want.
12270 */
12271
12272 if (!PyArg_ParseTuple(args, "|i", &fd))
12273 return NULL;
12274
12275#ifdef TERMSIZE_USE_IOCTL
12276 {
12277 struct winsize w;
12278 if (ioctl(fd, TIOCGWINSZ, &w))
12279 return PyErr_SetFromErrno(PyExc_OSError);
12280 columns = w.ws_col;
12281 lines = w.ws_row;
12282 }
12283#endif /* TERMSIZE_USE_IOCTL */
12284
12285#ifdef TERMSIZE_USE_CONIO
12286 {
12287 DWORD nhandle;
12288 HANDLE handle;
12289 CONSOLE_SCREEN_BUFFER_INFO csbi;
12290 switch (fd) {
12291 case 0: nhandle = STD_INPUT_HANDLE;
12292 break;
12293 case 1: nhandle = STD_OUTPUT_HANDLE;
12294 break;
12295 case 2: nhandle = STD_ERROR_HANDLE;
12296 break;
12297 default:
12298 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12299 }
12300 handle = GetStdHandle(nhandle);
12301 if (handle == NULL)
12302 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12303 if (handle == INVALID_HANDLE_VALUE)
12304 return PyErr_SetFromWindowsErr(0);
12305
12306 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12307 return PyErr_SetFromWindowsErr(0);
12308
12309 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12310 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12311 }
12312#endif /* TERMSIZE_USE_CONIO */
12313
Eddie Elizondo474eedf2018-11-13 04:09:31 -080012314 termsize = PyStructSequence_New(TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012315 if (termsize == NULL)
12316 return NULL;
12317 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12318 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12319 if (PyErr_Occurred()) {
12320 Py_DECREF(termsize);
12321 return NULL;
12322 }
12323 return termsize;
12324}
12325#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12326
Larry Hastings2f936352014-08-05 14:04:04 +100012327
12328/*[clinic input]
12329os.cpu_count
12330
Charles-François Natali80d62e62015-08-13 20:37:08 +010012331Return the number of CPUs in the system; return None if indeterminable.
12332
12333This number is not equivalent to the number of CPUs the current process can
12334use. The number of usable CPUs can be obtained with
12335``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012336[clinic start generated code]*/
12337
Larry Hastings2f936352014-08-05 14:04:04 +100012338static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012339os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012340/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012341{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012342 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012343#ifdef MS_WINDOWS
Miss Islington (bot)43ee0e22019-09-11 08:56:13 -070012344 /* Declare prototype here to avoid pulling in all of the Win7 APIs in 3.8 */
12345 DWORD WINAPI GetActiveProcessorCount(WORD group);
12346 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012347#elif defined(__hpux)
12348 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12349#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12350 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012351#elif defined(__DragonFly__) || \
12352 defined(__OpenBSD__) || \
12353 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012354 defined(__NetBSD__) || \
12355 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012356 int mib[2];
12357 size_t len = sizeof(ncpu);
12358 mib[0] = CTL_HW;
12359 mib[1] = HW_NCPU;
12360 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12361 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012362#endif
12363 if (ncpu >= 1)
12364 return PyLong_FromLong(ncpu);
12365 else
12366 Py_RETURN_NONE;
12367}
12368
Victor Stinnerdaf45552013-08-28 00:53:59 +020012369
Larry Hastings2f936352014-08-05 14:04:04 +100012370/*[clinic input]
12371os.get_inheritable -> bool
12372
12373 fd: int
12374 /
12375
12376Get the close-on-exe flag of the specified file descriptor.
12377[clinic start generated code]*/
12378
Larry Hastings2f936352014-08-05 14:04:04 +100012379static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012380os_get_inheritable_impl(PyObject *module, int fd)
12381/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012382{
Steve Dower8fc89802015-04-12 00:26:27 -040012383 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012384 _Py_BEGIN_SUPPRESS_IPH
12385 return_value = _Py_get_inheritable(fd);
12386 _Py_END_SUPPRESS_IPH
12387 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012388}
12389
12390
12391/*[clinic input]
12392os.set_inheritable
12393 fd: int
12394 inheritable: int
12395 /
12396
12397Set the inheritable flag of the specified file descriptor.
12398[clinic start generated code]*/
12399
Larry Hastings2f936352014-08-05 14:04:04 +100012400static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012401os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12402/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012403{
Steve Dower8fc89802015-04-12 00:26:27 -040012404 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012405
Steve Dower8fc89802015-04-12 00:26:27 -040012406 _Py_BEGIN_SUPPRESS_IPH
12407 result = _Py_set_inheritable(fd, inheritable, NULL);
12408 _Py_END_SUPPRESS_IPH
12409 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012410 return NULL;
12411 Py_RETURN_NONE;
12412}
12413
12414
12415#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012416/*[clinic input]
12417os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012418 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012419 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012420
Larry Hastings2f936352014-08-05 14:04:04 +100012421Get the close-on-exe flag of the specified file descriptor.
12422[clinic start generated code]*/
12423
Larry Hastings2f936352014-08-05 14:04:04 +100012424static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012425os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012426/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012427{
12428 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012429
12430 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12431 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012432 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012433 }
12434
Larry Hastings2f936352014-08-05 14:04:04 +100012435 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012436}
12437
Victor Stinnerdaf45552013-08-28 00:53:59 +020012438
Larry Hastings2f936352014-08-05 14:04:04 +100012439/*[clinic input]
12440os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012441 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012442 inheritable: bool
12443 /
12444
12445Set the inheritable flag of the specified handle.
12446[clinic start generated code]*/
12447
Larry Hastings2f936352014-08-05 14:04:04 +100012448static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012449os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012450 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012451/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012452{
12453 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012454 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12455 PyErr_SetFromWindowsErr(0);
12456 return NULL;
12457 }
12458 Py_RETURN_NONE;
12459}
Larry Hastings2f936352014-08-05 14:04:04 +100012460#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012461
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012462#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012463/*[clinic input]
12464os.get_blocking -> bool
12465 fd: int
12466 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012467
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012468Get the blocking mode of the file descriptor.
12469
12470Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12471[clinic start generated code]*/
12472
12473static int
12474os_get_blocking_impl(PyObject *module, int fd)
12475/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012476{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012477 int blocking;
12478
Steve Dower8fc89802015-04-12 00:26:27 -040012479 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012480 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012481 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012482 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012483}
12484
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012485/*[clinic input]
12486os.set_blocking
12487 fd: int
12488 blocking: bool(accept={int})
12489 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012490
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012491Set the blocking mode of the specified file descriptor.
12492
12493Set the O_NONBLOCK flag if blocking is False,
12494clear the O_NONBLOCK flag otherwise.
12495[clinic start generated code]*/
12496
12497static PyObject *
12498os_set_blocking_impl(PyObject *module, int fd, int blocking)
12499/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012500{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012501 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012502
Steve Dower8fc89802015-04-12 00:26:27 -040012503 _Py_BEGIN_SUPPRESS_IPH
12504 result = _Py_set_blocking(fd, blocking);
12505 _Py_END_SUPPRESS_IPH
12506 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012507 return NULL;
12508 Py_RETURN_NONE;
12509}
12510#endif /* !MS_WINDOWS */
12511
12512
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012513/*[clinic input]
12514class os.DirEntry "DirEntry *" "&DirEntryType"
12515[clinic start generated code]*/
12516/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3138f09f7c683f1d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012517
12518typedef struct {
12519 PyObject_HEAD
12520 PyObject *name;
12521 PyObject *path;
12522 PyObject *stat;
12523 PyObject *lstat;
12524#ifdef MS_WINDOWS
12525 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012526 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012527 int got_file_index;
12528#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012529#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012530 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012531#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012532 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012533 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012534#endif
12535} DirEntry;
12536
12537static void
12538DirEntry_dealloc(DirEntry *entry)
12539{
12540 Py_XDECREF(entry->name);
12541 Py_XDECREF(entry->path);
12542 Py_XDECREF(entry->stat);
12543 Py_XDECREF(entry->lstat);
12544 Py_TYPE(entry)->tp_free((PyObject *)entry);
12545}
12546
12547/* Forward reference */
12548static int
12549DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12550
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012551/*[clinic input]
12552os.DirEntry.is_symlink -> bool
12553
12554Return True if the entry is a symbolic link; cached per entry.
12555[clinic start generated code]*/
12556
Victor Stinner6036e442015-03-08 01:58:04 +010012557static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012558os_DirEntry_is_symlink_impl(DirEntry *self)
12559/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012560{
12561#ifdef MS_WINDOWS
12562 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012563#elif defined(HAVE_DIRENT_D_TYPE)
12564 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012565 if (self->d_type != DT_UNKNOWN)
12566 return self->d_type == DT_LNK;
12567 else
12568 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012569#else
12570 /* POSIX without d_type */
12571 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012572#endif
12573}
12574
12575static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012576DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12577{
12578 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012579 STRUCT_STAT st;
12580 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012581
12582#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012583 if (!PyUnicode_FSDecoder(self->path, &ub))
12584 return NULL;
12585 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012586#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012587 if (!PyUnicode_FSConverter(self->path, &ub))
12588 return NULL;
12589 const char *path = PyBytes_AS_STRING(ub);
12590 if (self->dir_fd != DEFAULT_DIR_FD) {
12591#ifdef HAVE_FSTATAT
12592 result = fstatat(self->dir_fd, path, &st,
12593 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12594#else
12595 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12596 return NULL;
12597#endif /* HAVE_FSTATAT */
12598 }
12599 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012600#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012601 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012602 if (follow_symlinks)
12603 result = STAT(path, &st);
12604 else
12605 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012606 }
12607 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012608
12609 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012610 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012611
12612 return _pystat_fromstructstat(&st);
12613}
12614
12615static PyObject *
12616DirEntry_get_lstat(DirEntry *self)
12617{
12618 if (!self->lstat) {
12619#ifdef MS_WINDOWS
12620 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12621#else /* POSIX */
12622 self->lstat = DirEntry_fetch_stat(self, 0);
12623#endif
12624 }
12625 Py_XINCREF(self->lstat);
12626 return self->lstat;
12627}
12628
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012629/*[clinic input]
12630os.DirEntry.stat
12631 *
12632 follow_symlinks: bool = True
12633
12634Return stat_result object for the entry; cached per entry.
12635[clinic start generated code]*/
12636
Victor Stinner6036e442015-03-08 01:58:04 +010012637static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012638os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12639/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012640{
12641 if (!follow_symlinks)
12642 return DirEntry_get_lstat(self);
12643
12644 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012645 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012646 if (result == -1)
12647 return NULL;
12648 else if (result)
12649 self->stat = DirEntry_fetch_stat(self, 1);
12650 else
12651 self->stat = DirEntry_get_lstat(self);
12652 }
12653
12654 Py_XINCREF(self->stat);
12655 return self->stat;
12656}
12657
Victor Stinner6036e442015-03-08 01:58:04 +010012658/* Set exception and return -1 on error, 0 for False, 1 for True */
12659static int
12660DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12661{
12662 PyObject *stat = NULL;
12663 PyObject *st_mode = NULL;
12664 long mode;
12665 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012666#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012667 int is_symlink;
12668 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012669#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012670#ifdef MS_WINDOWS
12671 unsigned long dir_bits;
12672#endif
Victor Stinner35a97c02015-03-08 02:59:09 +010012673 _Py_IDENTIFIER(st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012674
12675#ifdef MS_WINDOWS
12676 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12677 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012678#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012679 is_symlink = self->d_type == DT_LNK;
12680 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12681#endif
12682
Victor Stinner35a97c02015-03-08 02:59:09 +010012683#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012684 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012685#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012686 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012687 if (!stat) {
12688 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12689 /* If file doesn't exist (anymore), then return False
12690 (i.e., say it's not a file/directory) */
12691 PyErr_Clear();
12692 return 0;
12693 }
12694 goto error;
12695 }
12696 st_mode = _PyObject_GetAttrId(stat, &PyId_st_mode);
12697 if (!st_mode)
12698 goto error;
12699
12700 mode = PyLong_AsLong(st_mode);
12701 if (mode == -1 && PyErr_Occurred())
12702 goto error;
12703 Py_CLEAR(st_mode);
12704 Py_CLEAR(stat);
12705 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012706#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012707 }
12708 else if (is_symlink) {
12709 assert(mode_bits != S_IFLNK);
12710 result = 0;
12711 }
12712 else {
12713 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12714#ifdef MS_WINDOWS
12715 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12716 if (mode_bits == S_IFDIR)
12717 result = dir_bits != 0;
12718 else
12719 result = dir_bits == 0;
12720#else /* POSIX */
12721 if (mode_bits == S_IFDIR)
12722 result = self->d_type == DT_DIR;
12723 else
12724 result = self->d_type == DT_REG;
12725#endif
12726 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012727#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012728
12729 return result;
12730
12731error:
12732 Py_XDECREF(st_mode);
12733 Py_XDECREF(stat);
12734 return -1;
12735}
12736
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012737/*[clinic input]
12738os.DirEntry.is_dir -> bool
12739 *
12740 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012741
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012742Return True if the entry is a directory; cached per entry.
12743[clinic start generated code]*/
12744
12745static int
12746os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12747/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12748{
12749 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012750}
12751
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012752/*[clinic input]
12753os.DirEntry.is_file -> bool
12754 *
12755 follow_symlinks: bool = True
12756
12757Return True if the entry is a file; cached per entry.
12758[clinic start generated code]*/
12759
12760static int
12761os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12762/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012763{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012764 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012765}
12766
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012767/*[clinic input]
12768os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012769
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012770Return inode of the entry; cached per entry.
12771[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012772
12773static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012774os_DirEntry_inode_impl(DirEntry *self)
12775/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012776{
12777#ifdef MS_WINDOWS
12778 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012779 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012780 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012781 STRUCT_STAT stat;
12782 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012783
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012784 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012785 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012786 path = PyUnicode_AsUnicode(unicode);
12787 result = LSTAT(path, &stat);
12788 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012789
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012790 if (result != 0)
12791 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012792
12793 self->win32_file_index = stat.st_ino;
12794 self->got_file_index = 1;
12795 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012796 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12797 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012798#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012799 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12800 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012801#endif
12802}
12803
12804static PyObject *
12805DirEntry_repr(DirEntry *self)
12806{
12807 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12808}
12809
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012810/*[clinic input]
12811os.DirEntry.__fspath__
12812
12813Returns the path for the entry.
12814[clinic start generated code]*/
12815
Brett Cannon96881cd2016-06-10 14:37:21 -070012816static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012817os_DirEntry___fspath___impl(DirEntry *self)
12818/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012819{
12820 Py_INCREF(self->path);
12821 return self->path;
12822}
12823
Victor Stinner6036e442015-03-08 01:58:04 +010012824static PyMemberDef DirEntry_members[] = {
12825 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12826 "the entry's base filename, relative to scandir() \"path\" argument"},
12827 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12828 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12829 {NULL}
12830};
12831
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012832#include "clinic/posixmodule.c.h"
12833
Victor Stinner6036e442015-03-08 01:58:04 +010012834static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012835 OS_DIRENTRY_IS_DIR_METHODDEF
12836 OS_DIRENTRY_IS_FILE_METHODDEF
12837 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12838 OS_DIRENTRY_STAT_METHODDEF
12839 OS_DIRENTRY_INODE_METHODDEF
12840 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012841 {NULL}
12842};
12843
Benjamin Peterson5646de42015-04-12 17:56:34 -040012844static PyTypeObject DirEntryType = {
Victor Stinner6036e442015-03-08 01:58:04 +010012845 PyVarObject_HEAD_INIT(NULL, 0)
12846 MODNAME ".DirEntry", /* tp_name */
12847 sizeof(DirEntry), /* tp_basicsize */
12848 0, /* tp_itemsize */
12849 /* methods */
12850 (destructor)DirEntry_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020012851 0, /* tp_vectorcall_offset */
Victor Stinner6036e442015-03-08 01:58:04 +010012852 0, /* tp_getattr */
12853 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020012854 0, /* tp_as_async */
Victor Stinner6036e442015-03-08 01:58:04 +010012855 (reprfunc)DirEntry_repr, /* tp_repr */
12856 0, /* tp_as_number */
12857 0, /* tp_as_sequence */
12858 0, /* tp_as_mapping */
12859 0, /* tp_hash */
12860 0, /* tp_call */
12861 0, /* tp_str */
12862 0, /* tp_getattro */
12863 0, /* tp_setattro */
12864 0, /* tp_as_buffer */
12865 Py_TPFLAGS_DEFAULT, /* tp_flags */
12866 0, /* tp_doc */
12867 0, /* tp_traverse */
12868 0, /* tp_clear */
12869 0, /* tp_richcompare */
12870 0, /* tp_weaklistoffset */
12871 0, /* tp_iter */
12872 0, /* tp_iternext */
12873 DirEntry_methods, /* tp_methods */
12874 DirEntry_members, /* tp_members */
12875};
12876
12877#ifdef MS_WINDOWS
12878
12879static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012880join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012881{
12882 Py_ssize_t path_len;
12883 Py_ssize_t size;
12884 wchar_t *result;
12885 wchar_t ch;
12886
12887 if (!path_wide) { /* Default arg: "." */
12888 path_wide = L".";
12889 path_len = 1;
12890 }
12891 else {
12892 path_len = wcslen(path_wide);
12893 }
12894
12895 /* The +1's are for the path separator and the NUL */
12896 size = path_len + 1 + wcslen(filename) + 1;
12897 result = PyMem_New(wchar_t, size);
12898 if (!result) {
12899 PyErr_NoMemory();
12900 return NULL;
12901 }
12902 wcscpy(result, path_wide);
12903 if (path_len > 0) {
12904 ch = result[path_len - 1];
12905 if (ch != SEP && ch != ALTSEP && ch != L':')
12906 result[path_len++] = SEP;
12907 wcscpy(result + path_len, filename);
12908 }
12909 return result;
12910}
12911
12912static PyObject *
12913DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12914{
12915 DirEntry *entry;
12916 BY_HANDLE_FILE_INFORMATION file_info;
12917 ULONG reparse_tag;
12918 wchar_t *joined_path;
12919
12920 entry = PyObject_New(DirEntry, &DirEntryType);
12921 if (!entry)
12922 return NULL;
12923 entry->name = NULL;
12924 entry->path = NULL;
12925 entry->stat = NULL;
12926 entry->lstat = NULL;
12927 entry->got_file_index = 0;
12928
12929 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12930 if (!entry->name)
12931 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012932 if (path->narrow) {
12933 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12934 if (!entry->name)
12935 goto error;
12936 }
Victor Stinner6036e442015-03-08 01:58:04 +010012937
12938 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12939 if (!joined_path)
12940 goto error;
12941
12942 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12943 PyMem_Free(joined_path);
12944 if (!entry->path)
12945 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012946 if (path->narrow) {
12947 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12948 if (!entry->path)
12949 goto error;
12950 }
Victor Stinner6036e442015-03-08 01:58:04 +010012951
Steve Dowercc16be82016-09-08 10:35:16 -070012952 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012953 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12954
12955 return (PyObject *)entry;
12956
12957error:
12958 Py_DECREF(entry);
12959 return NULL;
12960}
12961
12962#else /* POSIX */
12963
12964static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012965join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012966{
12967 Py_ssize_t path_len;
12968 Py_ssize_t size;
12969 char *result;
12970
12971 if (!path_narrow) { /* Default arg: "." */
12972 path_narrow = ".";
12973 path_len = 1;
12974 }
12975 else {
12976 path_len = strlen(path_narrow);
12977 }
12978
12979 if (filename_len == -1)
12980 filename_len = strlen(filename);
12981
12982 /* The +1's are for the path separator and the NUL */
12983 size = path_len + 1 + filename_len + 1;
12984 result = PyMem_New(char, size);
12985 if (!result) {
12986 PyErr_NoMemory();
12987 return NULL;
12988 }
12989 strcpy(result, path_narrow);
12990 if (path_len > 0 && result[path_len - 1] != '/')
12991 result[path_len++] = '/';
12992 strcpy(result + path_len, filename);
12993 return result;
12994}
12995
12996static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012997DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012998 ino_t d_ino
12999#ifdef HAVE_DIRENT_D_TYPE
13000 , unsigned char d_type
13001#endif
13002 )
Victor Stinner6036e442015-03-08 01:58:04 +010013003{
13004 DirEntry *entry;
13005 char *joined_path;
13006
13007 entry = PyObject_New(DirEntry, &DirEntryType);
13008 if (!entry)
13009 return NULL;
13010 entry->name = NULL;
13011 entry->path = NULL;
13012 entry->stat = NULL;
13013 entry->lstat = NULL;
13014
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013015 if (path->fd != -1) {
13016 entry->dir_fd = path->fd;
13017 joined_path = NULL;
13018 }
13019 else {
13020 entry->dir_fd = DEFAULT_DIR_FD;
13021 joined_path = join_path_filename(path->narrow, name, name_len);
13022 if (!joined_path)
13023 goto error;
13024 }
Victor Stinner6036e442015-03-08 01:58:04 +010013025
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013026 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013027 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013028 if (joined_path)
13029 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013030 }
13031 else {
13032 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013033 if (joined_path)
13034 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013035 }
13036 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013037 if (!entry->name)
13038 goto error;
13039
13040 if (path->fd != -1) {
13041 entry->path = entry->name;
13042 Py_INCREF(entry->path);
13043 }
13044 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013045 goto error;
13046
Victor Stinner35a97c02015-03-08 02:59:09 +010013047#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013048 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013049#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013050 entry->d_ino = d_ino;
13051
13052 return (PyObject *)entry;
13053
13054error:
13055 Py_XDECREF(entry);
13056 return NULL;
13057}
13058
13059#endif
13060
13061
13062typedef struct {
13063 PyObject_HEAD
13064 path_t path;
13065#ifdef MS_WINDOWS
13066 HANDLE handle;
13067 WIN32_FIND_DATAW file_data;
13068 int first_time;
13069#else /* POSIX */
13070 DIR *dirp;
13071#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013072#ifdef HAVE_FDOPENDIR
13073 int fd;
13074#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013075} ScandirIterator;
13076
13077#ifdef MS_WINDOWS
13078
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013079static int
13080ScandirIterator_is_closed(ScandirIterator *iterator)
13081{
13082 return iterator->handle == INVALID_HANDLE_VALUE;
13083}
13084
Victor Stinner6036e442015-03-08 01:58:04 +010013085static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013086ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013087{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013088 HANDLE handle = iterator->handle;
13089
13090 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013091 return;
13092
Victor Stinner6036e442015-03-08 01:58:04 +010013093 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013094 Py_BEGIN_ALLOW_THREADS
13095 FindClose(handle);
13096 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013097}
13098
13099static PyObject *
13100ScandirIterator_iternext(ScandirIterator *iterator)
13101{
13102 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13103 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013104 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013105
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013106 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013107 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013108 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013109
13110 while (1) {
13111 if (!iterator->first_time) {
13112 Py_BEGIN_ALLOW_THREADS
13113 success = FindNextFileW(iterator->handle, file_data);
13114 Py_END_ALLOW_THREADS
13115 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013116 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013117 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013118 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013119 break;
13120 }
13121 }
13122 iterator->first_time = 0;
13123
13124 /* Skip over . and .. */
13125 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013126 wcscmp(file_data->cFileName, L"..") != 0) {
13127 entry = DirEntry_from_find_data(&iterator->path, file_data);
13128 if (!entry)
13129 break;
13130 return entry;
13131 }
Victor Stinner6036e442015-03-08 01:58:04 +010013132
13133 /* Loop till we get a non-dot directory or finish iterating */
13134 }
13135
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013136 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013137 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013138 return NULL;
13139}
13140
13141#else /* POSIX */
13142
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013143static int
13144ScandirIterator_is_closed(ScandirIterator *iterator)
13145{
13146 return !iterator->dirp;
13147}
13148
Victor Stinner6036e442015-03-08 01:58:04 +010013149static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013150ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013151{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013152 DIR *dirp = iterator->dirp;
13153
13154 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013155 return;
13156
Victor Stinner6036e442015-03-08 01:58:04 +010013157 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013158 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013159#ifdef HAVE_FDOPENDIR
13160 if (iterator->path.fd != -1)
13161 rewinddir(dirp);
13162#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013163 closedir(dirp);
13164 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013165 return;
13166}
13167
13168static PyObject *
13169ScandirIterator_iternext(ScandirIterator *iterator)
13170{
13171 struct dirent *direntp;
13172 Py_ssize_t name_len;
13173 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013174 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013175
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013176 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013177 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013178 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013179
13180 while (1) {
13181 errno = 0;
13182 Py_BEGIN_ALLOW_THREADS
13183 direntp = readdir(iterator->dirp);
13184 Py_END_ALLOW_THREADS
13185
13186 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013187 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013188 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013189 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013190 break;
13191 }
13192
13193 /* Skip over . and .. */
13194 name_len = NAMLEN(direntp);
13195 is_dot = direntp->d_name[0] == '.' &&
13196 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13197 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013198 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013199 name_len, direntp->d_ino
13200#ifdef HAVE_DIRENT_D_TYPE
13201 , direntp->d_type
13202#endif
13203 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013204 if (!entry)
13205 break;
13206 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013207 }
13208
13209 /* Loop till we get a non-dot directory or finish iterating */
13210 }
13211
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013212 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013213 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013214 return NULL;
13215}
13216
13217#endif
13218
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013219static PyObject *
13220ScandirIterator_close(ScandirIterator *self, PyObject *args)
13221{
13222 ScandirIterator_closedir(self);
13223 Py_RETURN_NONE;
13224}
13225
13226static PyObject *
13227ScandirIterator_enter(PyObject *self, PyObject *args)
13228{
13229 Py_INCREF(self);
13230 return self;
13231}
13232
13233static PyObject *
13234ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13235{
13236 ScandirIterator_closedir(self);
13237 Py_RETURN_NONE;
13238}
13239
Victor Stinner6036e442015-03-08 01:58:04 +010013240static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013241ScandirIterator_finalize(ScandirIterator *iterator)
13242{
13243 PyObject *error_type, *error_value, *error_traceback;
13244
13245 /* Save the current exception, if any. */
13246 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13247
13248 if (!ScandirIterator_is_closed(iterator)) {
13249 ScandirIterator_closedir(iterator);
13250
13251 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13252 "unclosed scandir iterator %R", iterator)) {
13253 /* Spurious errors can appear at shutdown */
13254 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13255 PyErr_WriteUnraisable((PyObject *) iterator);
13256 }
13257 }
13258 }
13259
Victor Stinner7bfa4092016-03-23 00:43:54 +010013260 path_cleanup(&iterator->path);
13261
13262 /* Restore the saved exception. */
13263 PyErr_Restore(error_type, error_value, error_traceback);
13264}
13265
13266static void
Victor Stinner6036e442015-03-08 01:58:04 +010013267ScandirIterator_dealloc(ScandirIterator *iterator)
13268{
Victor Stinner7bfa4092016-03-23 00:43:54 +010013269 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13270 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013271
Victor Stinner6036e442015-03-08 01:58:04 +010013272 Py_TYPE(iterator)->tp_free((PyObject *)iterator);
13273}
13274
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013275static PyMethodDef ScandirIterator_methods[] = {
13276 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13277 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13278 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13279 {NULL}
13280};
13281
Benjamin Peterson5646de42015-04-12 17:56:34 -040013282static PyTypeObject ScandirIteratorType = {
Victor Stinner6036e442015-03-08 01:58:04 +010013283 PyVarObject_HEAD_INIT(NULL, 0)
13284 MODNAME ".ScandirIterator", /* tp_name */
13285 sizeof(ScandirIterator), /* tp_basicsize */
13286 0, /* tp_itemsize */
13287 /* methods */
13288 (destructor)ScandirIterator_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020013289 0, /* tp_vectorcall_offset */
Victor Stinner6036e442015-03-08 01:58:04 +010013290 0, /* tp_getattr */
13291 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020013292 0, /* tp_as_async */
Victor Stinner6036e442015-03-08 01:58:04 +010013293 0, /* tp_repr */
13294 0, /* tp_as_number */
13295 0, /* tp_as_sequence */
13296 0, /* tp_as_mapping */
13297 0, /* tp_hash */
13298 0, /* tp_call */
13299 0, /* tp_str */
13300 0, /* tp_getattro */
13301 0, /* tp_setattro */
13302 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +020013303 Py_TPFLAGS_DEFAULT, /* tp_flags */
Victor Stinner6036e442015-03-08 01:58:04 +010013304 0, /* tp_doc */
13305 0, /* tp_traverse */
13306 0, /* tp_clear */
13307 0, /* tp_richcompare */
13308 0, /* tp_weaklistoffset */
13309 PyObject_SelfIter, /* tp_iter */
13310 (iternextfunc)ScandirIterator_iternext, /* tp_iternext */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013311 ScandirIterator_methods, /* tp_methods */
Victor Stinner7bfa4092016-03-23 00:43:54 +010013312 0, /* tp_members */
13313 0, /* tp_getset */
13314 0, /* tp_base */
13315 0, /* tp_dict */
13316 0, /* tp_descr_get */
13317 0, /* tp_descr_set */
13318 0, /* tp_dictoffset */
13319 0, /* tp_init */
13320 0, /* tp_alloc */
13321 0, /* tp_new */
13322 0, /* tp_free */
13323 0, /* tp_is_gc */
13324 0, /* tp_bases */
13325 0, /* tp_mro */
13326 0, /* tp_cache */
13327 0, /* tp_subclasses */
13328 0, /* tp_weaklist */
13329 0, /* tp_del */
13330 0, /* tp_version_tag */
13331 (destructor)ScandirIterator_finalize, /* tp_finalize */
Victor Stinner6036e442015-03-08 01:58:04 +010013332};
13333
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013334/*[clinic input]
13335os.scandir
13336
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013337 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013338
13339Return an iterator of DirEntry objects for given path.
13340
BNMetricsb9427072018-11-02 15:20:19 +000013341path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013342is bytes, the names of yielded DirEntry objects will also be bytes; in
13343all other circumstances they will be str.
13344
13345If path is None, uses the path='.'.
13346[clinic start generated code]*/
13347
Victor Stinner6036e442015-03-08 01:58:04 +010013348static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013349os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013350/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013351{
13352 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013353#ifdef MS_WINDOWS
13354 wchar_t *path_strW;
13355#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013356 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013357#ifdef HAVE_FDOPENDIR
13358 int fd = -1;
13359#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013360#endif
13361
Miss Islington (bot)8763d432019-06-24 09:09:47 -070013362 if (PySys_Audit("os.scandir", "O",
13363 path->object ? path->object : Py_None) < 0) {
13364 return NULL;
13365 }
13366
Victor Stinner6036e442015-03-08 01:58:04 +010013367 iterator = PyObject_New(ScandirIterator, &ScandirIteratorType);
13368 if (!iterator)
13369 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013370
13371#ifdef MS_WINDOWS
13372 iterator->handle = INVALID_HANDLE_VALUE;
13373#else
13374 iterator->dirp = NULL;
13375#endif
13376
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013377 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013378 /* Move the ownership to iterator->path */
13379 path->object = NULL;
13380 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013381
13382#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013383 iterator->first_time = 1;
13384
13385 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13386 if (!path_strW)
13387 goto error;
13388
13389 Py_BEGIN_ALLOW_THREADS
13390 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13391 Py_END_ALLOW_THREADS
13392
13393 PyMem_Free(path_strW);
13394
13395 if (iterator->handle == INVALID_HANDLE_VALUE) {
13396 path_error(&iterator->path);
13397 goto error;
13398 }
13399#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013400 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013401#ifdef HAVE_FDOPENDIR
13402 if (path->fd != -1) {
13403 /* closedir() closes the FD, so we duplicate it */
13404 fd = _Py_dup(path->fd);
13405 if (fd == -1)
13406 goto error;
13407
13408 Py_BEGIN_ALLOW_THREADS
13409 iterator->dirp = fdopendir(fd);
13410 Py_END_ALLOW_THREADS
13411 }
13412 else
13413#endif
13414 {
13415 if (iterator->path.narrow)
13416 path_str = iterator->path.narrow;
13417 else
13418 path_str = ".";
13419
13420 Py_BEGIN_ALLOW_THREADS
13421 iterator->dirp = opendir(path_str);
13422 Py_END_ALLOW_THREADS
13423 }
Victor Stinner6036e442015-03-08 01:58:04 +010013424
13425 if (!iterator->dirp) {
13426 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013427#ifdef HAVE_FDOPENDIR
13428 if (fd != -1) {
13429 Py_BEGIN_ALLOW_THREADS
13430 close(fd);
13431 Py_END_ALLOW_THREADS
13432 }
13433#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013434 goto error;
13435 }
13436#endif
13437
13438 return (PyObject *)iterator;
13439
13440error:
13441 Py_DECREF(iterator);
13442 return NULL;
13443}
13444
Ethan Furman410ef8e2016-06-04 12:06:26 -070013445/*
13446 Return the file system path representation of the object.
13447
13448 If the object is str or bytes, then allow it to pass through with
13449 an incremented refcount. If the object defines __fspath__(), then
13450 return the result of that method. All other types raise a TypeError.
13451*/
13452PyObject *
13453PyOS_FSPath(PyObject *path)
13454{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013455 /* For error message reasons, this function is manually inlined in
13456 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013457 _Py_IDENTIFIER(__fspath__);
13458 PyObject *func = NULL;
13459 PyObject *path_repr = NULL;
13460
13461 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13462 Py_INCREF(path);
13463 return path;
13464 }
13465
13466 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13467 if (NULL == func) {
13468 return PyErr_Format(PyExc_TypeError,
13469 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013470 "not %.200s",
13471 Py_TYPE(path)->tp_name);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013472 }
13473
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013474 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013475 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013476 if (NULL == path_repr) {
13477 return NULL;
13478 }
13479
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013480 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13481 PyErr_Format(PyExc_TypeError,
13482 "expected %.200s.__fspath__() to return str or bytes, "
13483 "not %.200s", Py_TYPE(path)->tp_name,
13484 Py_TYPE(path_repr)->tp_name);
13485 Py_DECREF(path_repr);
13486 return NULL;
13487 }
13488
Ethan Furman410ef8e2016-06-04 12:06:26 -070013489 return path_repr;
13490}
13491
13492/*[clinic input]
13493os.fspath
13494
13495 path: object
13496
13497Return the file system path representation of the object.
13498
Brett Cannonb4f43e92016-06-09 14:32:08 -070013499If the object is str or bytes, then allow it to pass through as-is. If the
13500object defines __fspath__(), then return the result of that method. All other
13501types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013502[clinic start generated code]*/
13503
13504static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013505os_fspath_impl(PyObject *module, PyObject *path)
13506/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013507{
13508 return PyOS_FSPath(path);
13509}
Victor Stinner6036e442015-03-08 01:58:04 +010013510
Victor Stinner9b1f4742016-09-06 16:18:52 -070013511#ifdef HAVE_GETRANDOM_SYSCALL
13512/*[clinic input]
13513os.getrandom
13514
13515 size: Py_ssize_t
13516 flags: int=0
13517
13518Obtain a series of random bytes.
13519[clinic start generated code]*/
13520
13521static PyObject *
13522os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13523/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13524{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013525 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013526 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013527
13528 if (size < 0) {
13529 errno = EINVAL;
13530 return posix_error();
13531 }
13532
Victor Stinnerec2319c2016-09-20 23:00:59 +020013533 bytes = PyBytes_FromStringAndSize(NULL, size);
13534 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013535 PyErr_NoMemory();
13536 return NULL;
13537 }
13538
13539 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013540 n = syscall(SYS_getrandom,
13541 PyBytes_AS_STRING(bytes),
13542 PyBytes_GET_SIZE(bytes),
13543 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013544 if (n < 0 && errno == EINTR) {
13545 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013546 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013547 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013548
13549 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013550 continue;
13551 }
13552 break;
13553 }
13554
13555 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013556 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013557 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013558 }
13559
Victor Stinnerec2319c2016-09-20 23:00:59 +020013560 if (n != size) {
13561 _PyBytes_Resize(&bytes, n);
13562 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013563
13564 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013565
13566error:
13567 Py_DECREF(bytes);
13568 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013569}
13570#endif /* HAVE_GETRANDOM_SYSCALL */
13571
Steve Dower2438cdf2019-03-29 16:37:16 -070013572#ifdef MS_WINDOWS
13573/* bpo-36085: Helper functions for managing DLL search directories
13574 * on win32
13575 */
13576
13577typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13578typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13579
13580/*[clinic input]
13581os._add_dll_directory
13582
13583 path: path_t
13584
13585Add a path to the DLL search path.
13586
13587This search path is used when resolving dependencies for imported
13588extension modules (the module itself is resolved through sys.path),
13589and also by ctypes.
13590
13591Returns an opaque value that may be passed to os.remove_dll_directory
13592to remove this directory from the search path.
13593[clinic start generated code]*/
13594
13595static PyObject *
13596os__add_dll_directory_impl(PyObject *module, path_t *path)
13597/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13598{
13599 HMODULE hKernel32;
13600 PAddDllDirectory AddDllDirectory;
13601 DLL_DIRECTORY_COOKIE cookie = 0;
13602 DWORD err = 0;
13603
Steve Dowera00b5be2020-02-13 08:30:27 +000013604 if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
13605 return NULL;
13606 }
13607
Steve Dower2438cdf2019-03-29 16:37:16 -070013608 /* For Windows 7, we have to load this. As this will be a fairly
13609 infrequent operation, just do it each time. Kernel32 is always
13610 loaded. */
13611 Py_BEGIN_ALLOW_THREADS
13612 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13613 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13614 hKernel32, "AddDllDirectory")) ||
13615 !(cookie = (*AddDllDirectory)(path->wide))) {
13616 err = GetLastError();
13617 }
13618 Py_END_ALLOW_THREADS
13619
13620 if (err) {
13621 return win32_error_object_err("add_dll_directory",
13622 path->object, err);
13623 }
13624
13625 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13626}
13627
13628/*[clinic input]
13629os._remove_dll_directory
13630
13631 cookie: object
13632
13633Removes a path from the DLL search path.
13634
13635The parameter is an opaque value that was returned from
13636os.add_dll_directory. You can only remove directories that you added
13637yourself.
13638[clinic start generated code]*/
13639
13640static PyObject *
13641os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13642/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13643{
13644 HMODULE hKernel32;
13645 PRemoveDllDirectory RemoveDllDirectory;
13646 DLL_DIRECTORY_COOKIE cookieValue;
13647 DWORD err = 0;
13648
13649 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13650 PyErr_SetString(PyExc_TypeError,
13651 "Provided cookie was not returned from os.add_dll_directory");
13652 return NULL;
13653 }
13654
13655 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13656 cookie, "DLL directory cookie");
13657
13658 /* For Windows 7, we have to load this. As this will be a fairly
13659 infrequent operation, just do it each time. Kernel32 is always
13660 loaded. */
13661 Py_BEGIN_ALLOW_THREADS
13662 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13663 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13664 hKernel32, "RemoveDllDirectory")) ||
13665 !(*RemoveDllDirectory)(cookieValue)) {
13666 err = GetLastError();
13667 }
13668 Py_END_ALLOW_THREADS
13669
13670 if (err) {
13671 return win32_error_object_err("remove_dll_directory",
13672 NULL, err);
13673 }
13674
13675 if (PyCapsule_SetName(cookie, NULL)) {
13676 return NULL;
13677 }
13678
13679 Py_RETURN_NONE;
13680}
13681
13682#endif
Larry Hastings31826802013-10-19 00:09:25 -070013683
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013684static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013685
13686 OS_STAT_METHODDEF
13687 OS_ACCESS_METHODDEF
13688 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013689 OS_CHDIR_METHODDEF
13690 OS_CHFLAGS_METHODDEF
13691 OS_CHMOD_METHODDEF
13692 OS_FCHMOD_METHODDEF
13693 OS_LCHMOD_METHODDEF
13694 OS_CHOWN_METHODDEF
13695 OS_FCHOWN_METHODDEF
13696 OS_LCHOWN_METHODDEF
13697 OS_LCHFLAGS_METHODDEF
13698 OS_CHROOT_METHODDEF
13699 OS_CTERMID_METHODDEF
13700 OS_GETCWD_METHODDEF
13701 OS_GETCWDB_METHODDEF
13702 OS_LINK_METHODDEF
13703 OS_LISTDIR_METHODDEF
13704 OS_LSTAT_METHODDEF
13705 OS_MKDIR_METHODDEF
13706 OS_NICE_METHODDEF
13707 OS_GETPRIORITY_METHODDEF
13708 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013709 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013710 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013711 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013712 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013713 OS_RENAME_METHODDEF
13714 OS_REPLACE_METHODDEF
13715 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013716 OS_SYMLINK_METHODDEF
13717 OS_SYSTEM_METHODDEF
13718 OS_UMASK_METHODDEF
13719 OS_UNAME_METHODDEF
13720 OS_UNLINK_METHODDEF
13721 OS_REMOVE_METHODDEF
13722 OS_UTIME_METHODDEF
13723 OS_TIMES_METHODDEF
13724 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013725 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013726 OS_EXECV_METHODDEF
13727 OS_EXECVE_METHODDEF
13728 OS_SPAWNV_METHODDEF
13729 OS_SPAWNVE_METHODDEF
13730 OS_FORK1_METHODDEF
13731 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013732 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013733 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13734 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13735 OS_SCHED_GETPARAM_METHODDEF
13736 OS_SCHED_GETSCHEDULER_METHODDEF
13737 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13738 OS_SCHED_SETPARAM_METHODDEF
13739 OS_SCHED_SETSCHEDULER_METHODDEF
13740 OS_SCHED_YIELD_METHODDEF
13741 OS_SCHED_SETAFFINITY_METHODDEF
13742 OS_SCHED_GETAFFINITY_METHODDEF
13743 OS_OPENPTY_METHODDEF
13744 OS_FORKPTY_METHODDEF
13745 OS_GETEGID_METHODDEF
13746 OS_GETEUID_METHODDEF
13747 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013748#ifdef HAVE_GETGROUPLIST
13749 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13750#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013751 OS_GETGROUPS_METHODDEF
13752 OS_GETPID_METHODDEF
13753 OS_GETPGRP_METHODDEF
13754 OS_GETPPID_METHODDEF
13755 OS_GETUID_METHODDEF
13756 OS_GETLOGIN_METHODDEF
13757 OS_KILL_METHODDEF
13758 OS_KILLPG_METHODDEF
13759 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013760#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013761 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013762#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013763 OS_SETUID_METHODDEF
13764 OS_SETEUID_METHODDEF
13765 OS_SETREUID_METHODDEF
13766 OS_SETGID_METHODDEF
13767 OS_SETEGID_METHODDEF
13768 OS_SETREGID_METHODDEF
13769 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013770#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013771 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013772#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013773 OS_GETPGID_METHODDEF
13774 OS_SETPGRP_METHODDEF
13775 OS_WAIT_METHODDEF
13776 OS_WAIT3_METHODDEF
13777 OS_WAIT4_METHODDEF
13778 OS_WAITID_METHODDEF
13779 OS_WAITPID_METHODDEF
13780 OS_GETSID_METHODDEF
13781 OS_SETSID_METHODDEF
13782 OS_SETPGID_METHODDEF
13783 OS_TCGETPGRP_METHODDEF
13784 OS_TCSETPGRP_METHODDEF
13785 OS_OPEN_METHODDEF
13786 OS_CLOSE_METHODDEF
13787 OS_CLOSERANGE_METHODDEF
13788 OS_DEVICE_ENCODING_METHODDEF
13789 OS_DUP_METHODDEF
13790 OS_DUP2_METHODDEF
13791 OS_LOCKF_METHODDEF
13792 OS_LSEEK_METHODDEF
13793 OS_READ_METHODDEF
13794 OS_READV_METHODDEF
13795 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013796 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013797 OS_WRITE_METHODDEF
13798 OS_WRITEV_METHODDEF
13799 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013800 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013801#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013802 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013803 posix_sendfile__doc__},
13804#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013805 OS_FSTAT_METHODDEF
13806 OS_ISATTY_METHODDEF
13807 OS_PIPE_METHODDEF
13808 OS_PIPE2_METHODDEF
13809 OS_MKFIFO_METHODDEF
13810 OS_MKNOD_METHODDEF
13811 OS_MAJOR_METHODDEF
13812 OS_MINOR_METHODDEF
13813 OS_MAKEDEV_METHODDEF
13814 OS_FTRUNCATE_METHODDEF
13815 OS_TRUNCATE_METHODDEF
13816 OS_POSIX_FALLOCATE_METHODDEF
13817 OS_POSIX_FADVISE_METHODDEF
13818 OS_PUTENV_METHODDEF
13819 OS_UNSETENV_METHODDEF
13820 OS_STRERROR_METHODDEF
13821 OS_FCHDIR_METHODDEF
13822 OS_FSYNC_METHODDEF
13823 OS_SYNC_METHODDEF
13824 OS_FDATASYNC_METHODDEF
13825 OS_WCOREDUMP_METHODDEF
13826 OS_WIFCONTINUED_METHODDEF
13827 OS_WIFSTOPPED_METHODDEF
13828 OS_WIFSIGNALED_METHODDEF
13829 OS_WIFEXITED_METHODDEF
13830 OS_WEXITSTATUS_METHODDEF
13831 OS_WTERMSIG_METHODDEF
13832 OS_WSTOPSIG_METHODDEF
13833 OS_FSTATVFS_METHODDEF
13834 OS_STATVFS_METHODDEF
13835 OS_CONFSTR_METHODDEF
13836 OS_SYSCONF_METHODDEF
13837 OS_FPATHCONF_METHODDEF
13838 OS_PATHCONF_METHODDEF
13839 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013840 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013841 OS__GETDISKUSAGE_METHODDEF
13842 OS__GETFINALPATHNAME_METHODDEF
13843 OS__GETVOLUMEPATHNAME_METHODDEF
13844 OS_GETLOADAVG_METHODDEF
13845 OS_URANDOM_METHODDEF
13846 OS_SETRESUID_METHODDEF
13847 OS_SETRESGID_METHODDEF
13848 OS_GETRESUID_METHODDEF
13849 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013850
Larry Hastings2f936352014-08-05 14:04:04 +100013851 OS_GETXATTR_METHODDEF
13852 OS_SETXATTR_METHODDEF
13853 OS_REMOVEXATTR_METHODDEF
13854 OS_LISTXATTR_METHODDEF
13855
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013856#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13857 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13858#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013859 OS_CPU_COUNT_METHODDEF
13860 OS_GET_INHERITABLE_METHODDEF
13861 OS_SET_INHERITABLE_METHODDEF
13862 OS_GET_HANDLE_INHERITABLE_METHODDEF
13863 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013864#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013865 OS_GET_BLOCKING_METHODDEF
13866 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013867#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013868 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013869 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013870 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013871 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013872#ifdef MS_WINDOWS
13873 OS__ADD_DLL_DIRECTORY_METHODDEF
13874 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13875#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013876 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013877};
13878
Barry Warsaw4a342091996-12-19 23:50:02 +000013879static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013880all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013881{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013882#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013883 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013884#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013885#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013886 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013887#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013888#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013889 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013890#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013891#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013892 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013893#endif
Fred Drakec9680921999-12-13 16:37:25 +000013894#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013895 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013896#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013897#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013898 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013899#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013900#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013901 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013902#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013903#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013904 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013905#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013906#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013907 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013908#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013909#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013910 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013911#endif
13912#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013913 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013914#endif
13915#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013916 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013917#endif
13918#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013919 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013920#endif
13921#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013922 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013923#endif
13924#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013925 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013926#endif
13927#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013928 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013929#endif
13930#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013931 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013932#endif
13933#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013934 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013935#endif
13936#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013937 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013938#endif
13939#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013940 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013941#endif
13942#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013943 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013944#endif
13945#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013946 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013947#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013948#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013949 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013950#endif
13951#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013952 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013953#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013954#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013955 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013956#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013957#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013958 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013959#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013960#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013961#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013962 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013963#endif
13964#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013965 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013966#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013967#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013968#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013969 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013970#endif
13971#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013972 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013973#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013974#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013975 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013976#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013977#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013978 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013979#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013980#ifdef O_TMPFILE
13981 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13982#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013983#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013984 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013985#endif
13986#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013987 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013988#endif
13989#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013990 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013991#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013992#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013993 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013994#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013995#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013996 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013997#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013998
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013999
Jesus Cea94363612012-06-22 18:32:07 +020014000#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014001 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014002#endif
14003#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014004 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014005#endif
14006
Tim Peters5aa91602002-01-30 05:46:57 +000014007/* MS Windows */
14008#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000014009 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014010 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014011#endif
14012#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000014013 /* Optimize for short life (keep in memory). */
14014 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014015 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014016#endif
14017#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000014018 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014019 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014020#endif
14021#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000014022 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014023 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014024#endif
14025#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000014026 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014027 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014028#endif
14029
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014030/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014031#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000014032 /* Send a SIGIO signal whenever input or output
14033 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014034 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014035#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014036#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000014037 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014038 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014039#endif
14040#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000014041 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014042 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014043#endif
14044#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000014045 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014046 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014047#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014048#ifdef O_NOLINKS
14049 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014050 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014051#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014052#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000014053 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014054 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014055#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000014056
Victor Stinner8c62be82010-05-06 00:08:46 +000014057 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014058#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014059 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014060#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014061#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014062 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014063#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014064#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014065 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014066#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014067#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014068 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014069#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014070#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014071 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014072#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014073#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014074 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014075#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014076#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014077 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014078#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014079#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014080 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014081#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014082#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014083 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014084#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014085#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014086 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014087#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014088#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014089 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014090#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014091#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014092 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014093#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014094#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014095 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014096#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014097#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014098 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014099#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014100#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014101 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014102#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014103#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014104 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014105#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014106#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014107 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014108#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014109
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014110 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014111#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014112 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014113#endif /* ST_RDONLY */
14114#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014115 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014116#endif /* ST_NOSUID */
14117
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014118 /* GNU extensions */
14119#ifdef ST_NODEV
14120 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14121#endif /* ST_NODEV */
14122#ifdef ST_NOEXEC
14123 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14124#endif /* ST_NOEXEC */
14125#ifdef ST_SYNCHRONOUS
14126 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14127#endif /* ST_SYNCHRONOUS */
14128#ifdef ST_MANDLOCK
14129 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14130#endif /* ST_MANDLOCK */
14131#ifdef ST_WRITE
14132 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14133#endif /* ST_WRITE */
14134#ifdef ST_APPEND
14135 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14136#endif /* ST_APPEND */
14137#ifdef ST_NOATIME
14138 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14139#endif /* ST_NOATIME */
14140#ifdef ST_NODIRATIME
14141 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14142#endif /* ST_NODIRATIME */
14143#ifdef ST_RELATIME
14144 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14145#endif /* ST_RELATIME */
14146
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014147 /* FreeBSD sendfile() constants */
14148#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014149 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014150#endif
14151#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014152 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014153#endif
14154#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014155 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014156#endif
14157
Ross Lagerwall7807c352011-03-17 20:20:30 +020014158 /* constants for posix_fadvise */
14159#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014160 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014161#endif
14162#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014163 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014164#endif
14165#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014166 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014167#endif
14168#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014169 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014170#endif
14171#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014172 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014173#endif
14174#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014175 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014176#endif
14177
14178 /* constants for waitid */
14179#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014180 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14181 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14182 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014183#endif
14184#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014185 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014186#endif
14187#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014188 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014189#endif
14190#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014191 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014192#endif
14193#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014194 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014195#endif
14196#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014197 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014198#endif
14199#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014200 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014201#endif
14202#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014203 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014204#endif
14205
14206 /* constants for lockf */
14207#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014208 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014209#endif
14210#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014211 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014212#endif
14213#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014214 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014215#endif
14216#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014217 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014218#endif
14219
Pablo Galindo4defba32018-01-27 16:16:37 +000014220#ifdef RWF_DSYNC
14221 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14222#endif
14223#ifdef RWF_HIPRI
14224 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14225#endif
14226#ifdef RWF_SYNC
14227 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14228#endif
14229#ifdef RWF_NOWAIT
14230 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14231#endif
14232
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014233/* constants for posix_spawn */
14234#ifdef HAVE_POSIX_SPAWN
14235 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14236 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14237 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14238#endif
14239
pxinwrf2d7ac72019-05-21 18:46:37 +080014240#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014241 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14242 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014243 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014244#endif
14245#ifdef HAVE_SPAWNV
14246 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014247 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014248#endif
14249
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014250#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014251#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014252 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014253#endif
14254#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014255 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014256#endif
14257#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014258 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014259#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014260#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014261 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014262#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014263#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014264 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014265#endif
14266#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014267 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014268#endif
14269#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014270 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014271#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014272#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014273 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014274#endif
14275#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014276 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014277#endif
14278#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014279 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014280#endif
14281#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014282 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014283#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014284#endif
14285
Benjamin Peterson9428d532011-09-14 11:45:52 -040014286#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014287 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14288 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14289 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014290#endif
14291
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014292#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014293 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014294#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014295#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014296 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014297#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014298#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014299 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014300#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014301#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014302 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014303#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014304#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014305 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014306#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014307#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014308 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014309#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014310#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014311 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014312#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014313#if HAVE_DECL_RTLD_MEMBER
14314 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14315#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014316
Victor Stinner9b1f4742016-09-06 16:18:52 -070014317#ifdef HAVE_GETRANDOM_SYSCALL
14318 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14319 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14320#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014321#ifdef HAVE_MEMFD_CREATE
14322 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14323 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14324#ifdef MFD_HUGETLB
14325 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014326#endif
14327#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014328 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014329#endif
14330#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014331 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014332#endif
14333#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014334 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014335#endif
14336#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014337 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014338#endif
14339#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014340 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014341#endif
14342#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014343 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014344#endif
14345#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014346 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014347#endif
14348#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014349 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014350#endif
14351#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014352 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014353#endif
14354#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014355 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014356#endif
14357#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014358 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014359#endif
14360#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014361 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014362#endif
14363#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014364 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014365#endif
14366#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014367 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14368#endif
14369#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014370
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014371#if defined(__APPLE__)
14372 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14373#endif
14374
Steve Dower2438cdf2019-03-29 16:37:16 -070014375#ifdef MS_WINDOWS
14376 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14377 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14378 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14379 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14380 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14381#endif
14382
Victor Stinner8c62be82010-05-06 00:08:46 +000014383 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014384}
14385
14386
Martin v. Löwis1a214512008-06-11 05:26:20 +000014387static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014388 PyModuleDef_HEAD_INIT,
14389 MODNAME,
14390 posix__doc__,
14391 -1,
14392 posix_methods,
14393 NULL,
14394 NULL,
14395 NULL,
14396 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +000014397};
14398
14399
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014400static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014401
14402#ifdef HAVE_FACCESSAT
14403 "HAVE_FACCESSAT",
14404#endif
14405
14406#ifdef HAVE_FCHDIR
14407 "HAVE_FCHDIR",
14408#endif
14409
14410#ifdef HAVE_FCHMOD
14411 "HAVE_FCHMOD",
14412#endif
14413
14414#ifdef HAVE_FCHMODAT
14415 "HAVE_FCHMODAT",
14416#endif
14417
14418#ifdef HAVE_FCHOWN
14419 "HAVE_FCHOWN",
14420#endif
14421
Larry Hastings00964ed2013-08-12 13:49:30 -040014422#ifdef HAVE_FCHOWNAT
14423 "HAVE_FCHOWNAT",
14424#endif
14425
Larry Hastings9cf065c2012-06-22 16:30:09 -070014426#ifdef HAVE_FEXECVE
14427 "HAVE_FEXECVE",
14428#endif
14429
14430#ifdef HAVE_FDOPENDIR
14431 "HAVE_FDOPENDIR",
14432#endif
14433
Georg Brandl306336b2012-06-24 12:55:33 +020014434#ifdef HAVE_FPATHCONF
14435 "HAVE_FPATHCONF",
14436#endif
14437
Larry Hastings9cf065c2012-06-22 16:30:09 -070014438#ifdef HAVE_FSTATAT
14439 "HAVE_FSTATAT",
14440#endif
14441
14442#ifdef HAVE_FSTATVFS
14443 "HAVE_FSTATVFS",
14444#endif
14445
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014446#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014447 "HAVE_FTRUNCATE",
14448#endif
14449
Larry Hastings9cf065c2012-06-22 16:30:09 -070014450#ifdef HAVE_FUTIMENS
14451 "HAVE_FUTIMENS",
14452#endif
14453
14454#ifdef HAVE_FUTIMES
14455 "HAVE_FUTIMES",
14456#endif
14457
14458#ifdef HAVE_FUTIMESAT
14459 "HAVE_FUTIMESAT",
14460#endif
14461
14462#ifdef HAVE_LINKAT
14463 "HAVE_LINKAT",
14464#endif
14465
14466#ifdef HAVE_LCHFLAGS
14467 "HAVE_LCHFLAGS",
14468#endif
14469
14470#ifdef HAVE_LCHMOD
14471 "HAVE_LCHMOD",
14472#endif
14473
14474#ifdef HAVE_LCHOWN
14475 "HAVE_LCHOWN",
14476#endif
14477
14478#ifdef HAVE_LSTAT
14479 "HAVE_LSTAT",
14480#endif
14481
14482#ifdef HAVE_LUTIMES
14483 "HAVE_LUTIMES",
14484#endif
14485
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014486#ifdef HAVE_MEMFD_CREATE
14487 "HAVE_MEMFD_CREATE",
14488#endif
14489
Larry Hastings9cf065c2012-06-22 16:30:09 -070014490#ifdef HAVE_MKDIRAT
14491 "HAVE_MKDIRAT",
14492#endif
14493
14494#ifdef HAVE_MKFIFOAT
14495 "HAVE_MKFIFOAT",
14496#endif
14497
14498#ifdef HAVE_MKNODAT
14499 "HAVE_MKNODAT",
14500#endif
14501
14502#ifdef HAVE_OPENAT
14503 "HAVE_OPENAT",
14504#endif
14505
14506#ifdef HAVE_READLINKAT
14507 "HAVE_READLINKAT",
14508#endif
14509
14510#ifdef HAVE_RENAMEAT
14511 "HAVE_RENAMEAT",
14512#endif
14513
14514#ifdef HAVE_SYMLINKAT
14515 "HAVE_SYMLINKAT",
14516#endif
14517
14518#ifdef HAVE_UNLINKAT
14519 "HAVE_UNLINKAT",
14520#endif
14521
14522#ifdef HAVE_UTIMENSAT
14523 "HAVE_UTIMENSAT",
14524#endif
14525
14526#ifdef MS_WINDOWS
14527 "MS_WINDOWS",
14528#endif
14529
14530 NULL
14531};
14532
14533
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014534PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014535INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014536{
Victor Stinner8c62be82010-05-06 00:08:46 +000014537 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014538 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014539 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014540
Victor Stinner8c62be82010-05-06 00:08:46 +000014541 m = PyModule_Create(&posixmodule);
14542 if (m == NULL)
14543 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014544
Victor Stinner8c62be82010-05-06 00:08:46 +000014545 /* Initialize environ dictionary */
14546 v = convertenviron();
14547 Py_XINCREF(v);
14548 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14549 return NULL;
14550 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014551
Victor Stinner8c62be82010-05-06 00:08:46 +000014552 if (all_ins(m))
14553 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014554
Victor Stinner8c62be82010-05-06 00:08:46 +000014555 if (setup_confname_tables(m))
14556 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014557
Victor Stinner8c62be82010-05-06 00:08:46 +000014558 Py_INCREF(PyExc_OSError);
14559 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014560
Guido van Rossumb3d39562000-01-31 18:41:26 +000014561#ifdef HAVE_PUTENV
Victor Stinner8c62be82010-05-06 00:08:46 +000014562 if (posix_putenv_garbage == NULL)
14563 posix_putenv_garbage = PyDict_New();
Guido van Rossumb3d39562000-01-31 18:41:26 +000014564#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +000014565
Victor Stinner8c62be82010-05-06 00:08:46 +000014566 if (!initialized) {
Ross Lagerwall7807c352011-03-17 20:20:30 +020014567#if defined(HAVE_WAITID) && !defined(__APPLE__)
14568 waitid_result_desc.name = MODNAME ".waitid_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014569 WaitidResultType = PyStructSequence_NewType(&waitid_result_desc);
14570 if (WaitidResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014571 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014572 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020014573#endif
14574
Christian Heimes25827622013-10-12 01:27:08 +020014575 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
Victor Stinner8c62be82010-05-06 00:08:46 +000014576 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14577 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14578 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014579 StatResultType = PyStructSequence_NewType(&stat_result_desc);
14580 if (StatResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014581 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014582 }
14583 structseq_new = StatResultType->tp_new;
14584 StatResultType->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014585
Christian Heimes25827622013-10-12 01:27:08 +020014586 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014587 StatVFSResultType = PyStructSequence_NewType(&statvfs_result_desc);
14588 if (StatVFSResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014589 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014590 }
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014591#ifdef NEED_TICKS_PER_SECOND
14592# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinner8c62be82010-05-06 00:08:46 +000014593 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014594# elif defined(HZ)
Victor Stinner8c62be82010-05-06 00:08:46 +000014595 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014596# else
Victor Stinner8c62be82010-05-06 00:08:46 +000014597 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014598# endif
14599#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014600
William Orr81574b82018-10-01 22:19:56 -070014601#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014602 sched_param_desc.name = MODNAME ".sched_param";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014603 SchedParamType = PyStructSequence_NewType(&sched_param_desc);
14604 if (SchedParamType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014605 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014606 }
14607 SchedParamType->tp_new = os_sched_param;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014608#endif
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014609
14610 /* initialize TerminalSize_info */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014611 TerminalSizeType = PyStructSequence_NewType(&TerminalSize_desc);
14612 if (TerminalSizeType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014613 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014614 }
Victor Stinner6036e442015-03-08 01:58:04 +010014615
14616 /* initialize scandir types */
14617 if (PyType_Ready(&ScandirIteratorType) < 0)
14618 return NULL;
14619 if (PyType_Ready(&DirEntryType) < 0)
14620 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014621 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020014622#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014623 Py_INCREF((PyObject*) WaitidResultType);
14624 PyModule_AddObject(m, "waitid_result", (PyObject*) WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +020014625#endif
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014626 Py_INCREF((PyObject*) StatResultType);
14627 PyModule_AddObject(m, "stat_result", (PyObject*) StatResultType);
14628 Py_INCREF((PyObject*) StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000014629 PyModule_AddObject(m, "statvfs_result",
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014630 (PyObject*) StatVFSResultType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014631
14632#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014633 Py_INCREF(SchedParamType);
14634 PyModule_AddObject(m, "sched_param", (PyObject *)SchedParamType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014635#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014636
Larry Hastings605a62d2012-06-24 04:33:36 -070014637 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014638 TimesResultType = PyStructSequence_NewType(&times_result_desc);
14639 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014640 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014641 }
14642 PyModule_AddObject(m, "times_result", (PyObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070014643
14644 uname_result_desc.name = MODNAME ".uname_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014645 UnameResultType = PyStructSequence_NewType(&uname_result_desc);
14646 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014647 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014648 }
14649 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070014650
Thomas Wouters477c8d52006-05-27 19:21:47 +000014651#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014652 /*
14653 * Step 2 of weak-linking support on Mac OS X.
14654 *
14655 * The code below removes functions that are not available on the
14656 * currently active platform.
14657 *
14658 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014659 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014660 * OSX 10.4.
14661 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014662#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014663 if (fstatvfs == NULL) {
14664 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14665 return NULL;
14666 }
14667 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014668#endif /* HAVE_FSTATVFS */
14669
14670#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014671 if (statvfs == NULL) {
14672 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14673 return NULL;
14674 }
14675 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014676#endif /* HAVE_STATVFS */
14677
14678# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014679 if (lchown == NULL) {
14680 if (PyObject_DelAttrString(m, "lchown") == -1) {
14681 return NULL;
14682 }
14683 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014684#endif /* HAVE_LCHOWN */
14685
14686
14687#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014688
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014689 Py_INCREF(TerminalSizeType);
14690 PyModule_AddObject(m, "terminal_size", (PyObject*)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014691
Larry Hastings6fe20b32012-04-19 15:07:49 -070014692 billion = PyLong_FromLong(1000000000);
14693 if (!billion)
14694 return NULL;
14695
Larry Hastings9cf065c2012-06-22 16:30:09 -070014696 /* suppress "function not used" warnings */
14697 {
14698 int ignored;
14699 fd_specified("", -1);
14700 follow_symlinks_specified("", 1);
14701 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14702 dir_fd_converter(Py_None, &ignored);
14703 dir_fd_unavailable(Py_None, &ignored);
14704 }
14705
14706 /*
14707 * provide list of locally available functions
14708 * so os.py can populate support_* lists
14709 */
14710 list = PyList_New(0);
14711 if (!list)
14712 return NULL;
14713 for (trace = have_functions; *trace; trace++) {
14714 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14715 if (!unicode)
14716 return NULL;
14717 if (PyList_Append(list, unicode))
14718 return NULL;
14719 Py_DECREF(unicode);
14720 }
14721 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014722
14723 Py_INCREF((PyObject *) &DirEntryType);
Brett Cannona32c4d02016-06-24 14:14:44 -070014724 PyModule_AddObject(m, "DirEntry", (PyObject *)&DirEntryType);
Larry Hastings9cf065c2012-06-22 16:30:09 -070014725
14726 initialized = 1;
14727
Victor Stinner8c62be82010-05-06 00:08:46 +000014728 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014729}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014730
14731#ifdef __cplusplus
14732}
14733#endif